Java Code Examples for org.apache.brooklyn.util.text.Strings

The following examples show how to use org.apache.brooklyn.util.text.Strings. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: brooklyn-server   Source File: Winrm4jTool.java    License: Apache License 2.0 6 votes vote down vote up
public Winrm4jTool(ConfigBag config) {
    this.bag = checkNotNull(config, "config bag");
    host = getRequiredConfig(config, PROP_HOST);
    port = config.get(PROP_PORT);
    useSecureWinrm = config.get(USE_HTTPS_WINRM);
    authenticationScheme = config.get(USE_NTLM) ? AuthSchemes.NTLM : null;
    computerName = Strings.isNonBlank(config.get(COMPUTER_NAME)) ? config.get(COMPUTER_NAME) : null;
    user = getRequiredConfig(config, PROP_USER);
    password = getRequiredConfig(config, PROP_PASSWORD);
    execTries = getRequiredConfig(config, PROP_EXEC_TRIES);
    execRetryDelay = getRequiredConfig(config, PROP_EXEC_RETRY_DELAY);
    logCredentials = getRequiredConfig(config, LOG_CREDENTIALS);
    operationTimeout = config.get(OPERATION_TIMEOUT);
    retriesOfNetworkFailures = config.get(RETRIES_OF_NETWORK_FAILURES);
    environment = config.get(ENVIRONMENT);
}
 
Example 2
Source Project: brooklyn-server   Source File: Yamls.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns the original YAML with the found item replaced by the given replacement YAML.
 * @param replacement YAML to put in for the found item;
 * this YAML typically should not have any special indentation -- if required when replacing it will be inserted.
 * <p>
 * if replacing an inline map entry, the supplied entry must follow the structure being replaced;
 * for example, if replacing the value in <code>key: value</code> with a map,
 * supplying a replacement <code>subkey: value</code> would result in invalid yaml;
 * the replacement must be supplied with a newline, either before the subkey or after.
 * (if unsure we believe it is always valid to include an initial newline or comment with newline.)
 */
public String getFullYamlTextWithExtractReplaced(String replacement) {
    if (!found()) throw new IllegalStateException("Cannot perform replacement when item was not matched.");
    String result = yaml.substring(0, getStartOfThis());
    
    String[] newLines = replacement.split("\n");
    for (int i=1; i<newLines.length; i++)
        newLines[i] = Strings.makePaddedString("", getStartColumnOfThis(), "", " ") + newLines[i];
    result += Strings.lines(newLines);
    if (replacement.endsWith("\n")) result += "\n";
    
    int end = getEndOfThis();
    result += yaml.substring(end);
    
    return result;
}
 
Example 3
@Test
public void testRestoresSimpleApp() throws Exception {
    messages.clear();
    messages.add("creating");
    origApp.createAndManageChild(EntitySpec.create(Entity.class, MyEntityForClassInitializationTesting.class));
    messages.add("created");
    messages.add("rebinding");
    newApp = rebind();
    messages.add("rebinded");
    
    log.debug("Create and rebind message sequence is:\n- "+Strings.join(messages, "\n- "));
    Assert.assertEquals(messages, MutableList.of(
        "creating", "ME.static_initializer", "ME.initializer", 
        "WIM.static_initializer", "WIM.initializer", "WIM.constructor", 
        "ME.constructor", "created", 
        "rebinding", "ME.initializer", "WIM.initializer", "WIM.constructor", 
        "ME.constructor", "rebinded"));
}
 
Example 4
Source Project: brooklyn-server   Source File: Main.java    License: Apache License 2.0 6 votes vote down vote up
protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) {
    Maybe<HighAvailabilityMode> highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability);
    if (!highAvailabilityMode.isPresent()) {
        if (Strings.isBlank(highAvailability)) {
            throw new FatalConfigurationRuntimeException("High availability mode must not be blank");
        } else {
            throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability);
        }
    }
   
    if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) {
        if (persistMode == PersistMode.DISABLED) {
            if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO)
                return HighAvailabilityMode.DISABLED;
            throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled");
        } else if (persistMode == PersistMode.CLEAN && 
                (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY 
                || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY
                || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) {
            throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN");
        }
    }
    return highAvailabilityMode.get();
}
 
Example 5
Source Project: brooklyn-server   Source File: LocationConfigUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<ConfigKey<String>,String> finalAndOriginalSpecs(String finalSpec, Object ...sourcesForOriginalSpec) {
    // yuck!: TODO should clean up how these things get passed around
    Map<ConfigKey<String>,String> result = MutableMap.of();
    if (finalSpec!=null) 
        result.put(LocationInternal.FINAL_SPEC, finalSpec);
    
    String originalSpec = null;
    for (Object source: sourcesForOriginalSpec) {
        if (source instanceof CharSequence) originalSpec = source.toString();
        else if (source instanceof Map) {
            if (originalSpec==null) originalSpec = Strings.toString( ((Map<?,?>)source).get(LocationInternal.ORIGINAL_SPEC) );
            if (originalSpec==null) originalSpec = Strings.toString( ((Map<?,?>)source).get(LocationInternal.ORIGINAL_SPEC.getName()) );
        }
        if (originalSpec!=null) break; 
    }
    if (originalSpec==null) originalSpec = finalSpec;
    if (originalSpec!=null)
        result.put(LocationInternal.ORIGINAL_SPEC, originalSpec);
    
    return result;
}
 
Example 6
Source Project: brooklyn-library   Source File: CouchDBNodeLiveTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(groups = "Live", dataProvider = "virtualMachineData")
protected void testOperatingSystemProvider(String imageId, String provider, String region, String description) throws Exception {
    log.info("Testing CouchDB on {}{} using {} ({})", new Object[] { provider, Strings.isNonEmpty(region) ? ":" + region : "", description, imageId });

    Map<String, String> properties = MutableMap.of("imageId", imageId);
    Location testLocation = app.getManagementContext().getLocationRegistry()
            .getLocationManaged(provider + (Strings.isNonEmpty(region) ? ":" + region : ""), properties);

    CouchDBNode couchdb = app.createAndManageChild(EntitySpec.create(CouchDBNode.class)
            .configure("httpPort", "12345+")
            .configure("clusterName", "TestCluster"));
    app.start(ImmutableList.of(testLocation));
    EntityAsserts.assertAttributeEqualsEventually(couchdb, Startable.SERVICE_UP, true);

    JcouchdbSupport jcouchdb = new JcouchdbSupport(couchdb);
    jcouchdb.jcouchdbTest();
}
 
Example 7
Source Project: brooklyn-server   Source File: BrooklynRestResourceUtils.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T extends Entity> org.apache.brooklyn.api.entity.EntitySpec<?> toCoreEntitySpec(Class<T> clazz, String name, Map<String,String> configO, String catalogItemId) {
    Map<String, String> config = (configO == null) ? Maps.<String,String>newLinkedHashMap() : Maps.newLinkedHashMap(configO);
    
    org.apache.brooklyn.api.entity.EntitySpec<? extends Entity> result;
    if (clazz.isInterface()) {
        result = org.apache.brooklyn.api.entity.EntitySpec.create(clazz);
    } else {
        // If this is a concrete class, particularly for an Application class, we want the proxy
        // to expose all interfaces it implements.
        Class interfaceclazz = (Application.class.isAssignableFrom(clazz)) ? Application.class : Entity.class;
        Set<Class<?>> additionalInterfaceClazzes = Reflections.getInterfacesIncludingClassAncestors(clazz);
        result = org.apache.brooklyn.api.entity.EntitySpec.create(interfaceclazz).impl(clazz).additionalInterfaces(additionalInterfaceClazzes);
    }
    
    result.catalogItemId(catalogItemId);
    if (!Strings.isEmpty(name)) result.displayName(name);
    result.configure( convertFlagsToKeys(result.getImplementation(), config) );
    return result;
}
 
Example 8
Source Project: brooklyn-server   Source File: VanillaSoftwareYamlTest.java    License: Apache License 2.0 6 votes vote down vote up
/** yaml variant of VanillaSoftwareProcessAndChildrenIntegrationTest */
@Test(groups="Integration")
public void testVanillaSoftwareYamlWithChildStartedAfter() {
    SimpleYamlLauncher l = new SimpleYamlLauncherForTests();
    try {
        Application app = l.launchAppYaml("vanilla-software-with-child-blueprint.yaml");
        log.info("started "+app);

        Entity p1 = Iterables.getOnlyElement( app.getChildren() );
        Long d1 = Long.parseLong( Strings.getFirstWordAfter(new ResourceUtils(this).getResourceAsString(Os.mergePaths(p1.getAttribute(SoftwareProcess.RUN_DIR), "DATE")), "utc") );
        
        Entity p2 = Iterables.getOnlyElement( p1.getChildren() );
        Long d2 = Long.parseLong( Strings.getFirstWordAfter(new ResourceUtils(this).getResourceAsString(Os.mergePaths(p2.getAttribute(SoftwareProcess.RUN_DIR), "DATE")), "utc") );
        Assert.assertTrue( d2-d1 > 2 && d2-d1 < 10, "p2 should have started 3s after parent, but it did not ("+(d2-d1)+"s difference" );
    } finally {
        l.destroyAll();
    }
    log.info("DONE");
}
 
Example 9
/**
 * Answers one of "OpenJDK", "Oracle", or other vendor info.
 */
protected Optional<String> getCurrentJavaVendor() {
    // TODO Also handle IBM jvm
    log.debug("Checking Java vendor at {}@{}", getEntity(), getLocation());
    ProcessTaskWrapper<Integer> versionCommand = Entities.submit(getEntity(), SshTasks.newSshExecTaskFactory(
            getLocation(), "java -version 2>&1 | awk 'NR==2 {print $1}'"));
    versionCommand.get();
    String stdOut = versionCommand.getStdout().trim();
    if (Strings.isBlank(stdOut)) {
        log.debug("Found no Java installed at {}@{}", getEntity(), getLocation());
        return Optional.absent();
    } else if ("Java(TM)".equals(stdOut)) {
        log.debug("Found Java version at {}@{}: {}", new Object[] {getEntity(), getLocation(), stdOut});
        return Optional.of("Oracle");
    } else {
        return Optional.of(stdOut);
    }
}
 
Example 10
Source Project: brooklyn-server   Source File: ShellAbstractTool.java    License: Apache License 2.0 6 votes vote down vote up
public ToolAbstractExecScript(Map<String,?> props) {
    this.props = props;
    this.separator = getOptionalVal(props, PROP_SEPARATOR);
    this.out = getOptionalVal(props, PROP_OUT_STREAM);
    this.err = getOptionalVal(props, PROP_ERR_STREAM);
    
    this.scriptDir = getOptionalVal(props, PROP_SCRIPT_DIR);
    this.runAsRoot = Boolean.TRUE.equals(getOptionalVal(props, PROP_RUN_AS_ROOT));
    this.authSudo = Boolean.TRUE.equals(getOptionalVal(props, PROP_AUTH_SUDO));
    this.noExtraOutput = Boolean.TRUE.equals(getOptionalVal(props, PROP_NO_EXTRA_OUTPUT));
    this.noDeleteAfterExec = Boolean.TRUE.equals(getOptionalVal(props, PROP_NO_DELETE_SCRIPT));
    this.password = getOptionalVal(props, PROP_PASSWORD);
    this.execTimeout = getOptionalVal(props, PROP_EXEC_TIMEOUT);
    
    String summary = getOptionalVal(props, PROP_SUMMARY);
    if (summary!=null) {
        summary = Strings.makeValidFilename(summary);
        if (summary.length()>30) 
            summary = summary.substring(0,30);
    }
    this.scriptNameWithoutExtension = "brooklyn-"+
            Time.makeDateStampString()+"-"+Identifiers.makeRandomId(4)+
            (Strings.isBlank(summary) ? "" : "-"+summary);
    this.scriptPath = Os.mergePathsUnix(scriptDir, scriptNameWithoutExtension+".sh");
}
 
Example 11
Source Project: brooklyn-server   Source File: WindowsTestFixture.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static MachineProvisioningLocation<WinRmMachineLocation> setUpWindowsLocation(ManagementContext mgmt, Map<String, ?> props) throws Exception {
    // Commented out / unused code included here to make it easy to supply a 
    // pre-existing Windows VM for use in a bunch of different tests.
    String userPassAtHost = System.getenv(EXISTING_WINDOWS_TEST_USER_PASS_HOST_ENV_VAR);
    if (Strings.isBlank(userPassAtHost)) {
        return (MachineProvisioningLocation<WinRmMachineLocation>) newJcloudsLocation((ManagementContextInternal) mgmt, props);
    } else {
        return (MachineProvisioningLocation<WinRmMachineLocation>) newByonLocation((ManagementContextInternal) mgmt,
            MutableMap.of(
                    "winrm", userPassAtHost.split("@")[1],
                    "password", userPassAtHost.split(":")[1].split("@")[0],
                    "user", userPassAtHost.split(":")[0]
                ));
    }
}
 
Example 12
Source Project: brooklyn-server   Source File: MachineInitTasks.java    License: Apache License 2.0 6 votes vote down vote up
protected String toTruncatedString(Iterable<?> vals, int maxShown) {
    StringBuilder result = new StringBuilder("[");
    int shown = 0;
    for (Object val : (vals == null ? ImmutableList.of() : vals)) {
        if (shown != 0) {
            result.append(", ");
        }
        if (shown < maxShown) {
            result.append(Strings.toString(val));
            shown++;
        } else {
            result.append("...");
            break;
        }
    }
    result.append("]");
    return result.toString();
}
 
Example 13
Source Project: brooklyn-server   Source File: CloudMachineNamerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateNewMachineName() {
    TestApplication app = mgmt.getEntityManager().createEntity(EntitySpec.create(TestApplication.class).displayName("TistApp"));
    TestEntity child = app.createAndManageChild(EntitySpec.create(TestEntity.class).displayName("TestEnt"));

    ConfigBag cfg = new ConfigBag()
        .configure(CloudLocationConfig.CALLER_CONTEXT, child);
    BasicCloudMachineNamer namer = new BasicCloudMachineNamer();
    
    String result = namer.generateNewMachineUniqueName(cfg);
    Assert.assertTrue(result.length() <= namer.getMaxNameLength(cfg));
    String user = Strings.maxlen(System.getProperty("user.name"), 4).toLowerCase();
    Assert.assertTrue(result.indexOf(user) >= 0);
    Assert.assertTrue(result.indexOf("-tistapp-") >= 0);
    Assert.assertTrue(result.indexOf("-testent-") >= 0);
    Assert.assertTrue(result.indexOf("-"+Strings.maxlen(app.getId(), 4).toLowerCase()) >= 0);
    Assert.assertTrue(result.indexOf("-"+Strings.maxlen(child.getId(), 4).toLowerCase()) >= 0);
}
 
Example 14
Source Project: brooklyn-server   Source File: SoftwareProcessEntityTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInstallDirAndRunDirUsingTilde() throws Exception {
    String dataDirName = ".brooklyn-foo"+Strings.makeRandomId(4);
    String dataDir = "~/"+dataDirName;
    String resolvedDataDir = Os.mergePaths(Os.home(), dataDirName);
    
    MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
        .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, dataDir));

    entity.start(ImmutableList.of(loc));

    Assert.assertEquals(Os.nativePath(entity.getAttribute(SoftwareProcess.INSTALL_DIR)),
                        Os.nativePath(Os.mergePaths(resolvedDataDir, "installs/MyService")));
    Assert.assertEquals(Os.nativePath(entity.getAttribute(SoftwareProcess.RUN_DIR)),
                        Os.nativePath(Os.mergePaths(resolvedDataDir, "apps/"+entity.getApplicationId()+"/entities/MyService_"+entity.getId())));
}
 
Example 15
Source Project: brooklyn-server   Source File: OsgiLauncherImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public OsgiLauncherImpl startPartOne() {
    // make sure brooklyn-core bundle is started
    brooklynVersion.getVersion();

    Configuration brooklynConfig = getConfiguration(configAdmin, BROOKLYN_CONFIG_PID);
    // Note that this doesn't check whether the files exist, just that there are potential alternative sources for configuration.
    if (brooklynConfig == null && Strings.isEmpty(globalBrooklynProperties) && Strings.isEmpty(localBrooklynProperties)) {
        LOG.warn("Config Admin PID '" + BROOKLYN_CONFIG_PID + "' not found, not using external configuration. Create a brooklyn.cfg file in etc folder.");
    }
    configSupplier = new ConfigSupplier(brooklynConfig);
    BrooklynPropertiesFactoryHelper helper = new BrooklynPropertiesFactoryHelper(
            globalBrooklynProperties, localBrooklynProperties, configSupplier);
    setBrooklynPropertiesBuilder(helper.createPropertiesBuilder());
    return super.startPartOne();
}
 
Example 16
Source Project: brooklyn-server   Source File: XmlMementoSerializer.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
protected String getContextDescription(Object contextHinter) {
    List<String> entries = MutableList.of();
    
    entries.add("in");
    entries.add(lookupContext.getContextDescription());
    
    if (contextHinter instanceof ReferencingMarshallingContext)
        entries.add("at "+((ReferencingMarshallingContext)contextHinter).currentPath());
    else if (contextHinter instanceof ReferenceByXPathUnmarshaller) {
        try {
            Method m = ReferenceByXPathUnmarshaller.class.getDeclaredMethod("getCurrentReferenceKey");
            m.setAccessible(true);
            entries.add("at "+m.invoke(contextHinter));
        } catch (Exception e) {
            Exceptions.propagateIfFatal(e);
            // ignore otherwise - we just won't have the position in the file
        }
    }
    
    return Strings.join(entries, " ");
}
 
Example 17
Source Project: brooklyn-server   Source File: SshCommandSensor.java    License: Apache License 2.0 6 votes vote down vote up
@Beta
public static String makeCommandExecutingInDirectory(String command, String executionDir, Entity entity) {
    String finalCommand = command;
    String execDir = executionDir;
    if (Strings.isBlank(execDir)) {
        // default to run dir
        execDir = (entity != null) ? entity.getAttribute(BrooklynConfigKeys.RUN_DIR) : null;
        // if no run dir, default to home
        if (Strings.isBlank(execDir)) {
            execDir = "~";
        }
    } else if (!Os.isAbsolutish(execDir)) {
        // relative paths taken wrt run dir
        String runDir = (entity != null) ? entity.getAttribute(BrooklynConfigKeys.RUN_DIR) : null;
        if (!Strings.isBlank(runDir)) {
            execDir = Os.mergePaths(runDir, execDir);
        }
    }
    if (!"~".equals(execDir)) {
        finalCommand = "mkdir -p '"+execDir+"' && cd '"+execDir+"' && "+finalCommand;
    }
    return finalCommand;
}
 
Example 18
Source Project: brooklyn-server   Source File: CatalogMakeOsgiBundleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCatalogBomLoadsFileInBundle() throws Exception {
    bm.setDefaultClassForLoading(getClass());
    File jf = bm.createJarFromClasspathDir("osgi/catalog-bundle-1");
    
    // add a file in the bundle
    String customText = "Sample data "+Identifiers.makeRandomId(4);
    jf = bm.copyAdding(jf, MutableMap.of(
            new ZipEntry("sample.txt"), (InputStream) new ByteArrayInputStream(customText.getBytes())));
    
    installBundle(jf);

    String yaml = Strings.lines("name: simple-app-yaml",
            "services:",
            "- type: " + "basic1",
            "  brooklyn.initializers:",
            "  - type: "+GetFileContentsEffector.class.getName());
    Entity app = createAndStartApplication(yaml);
    Entity basic1 = Iterables.getOnlyElement( app.getChildren() );
    
    // check the file put in the bundle gets loaded without needing to do anything special
    String contents = basic1.invoke(GetFileContentsEffector.GET_FILE_CONTENTS, MutableMap.of(GetFileContentsEffector.FILENAME.getName(), "classpath://sample.txt")).get();
    Asserts.assertEquals(contents, customText);
}
 
Example 19
Source Project: brooklyn-library   Source File: DatastoreMixins.java    License: Apache License 2.0 6 votes vote down vote up
/** returns the creation script contents, if it exists, or null if none is defined (error if it cannot be loaded) */
@Nullable public static InputStream getDatabaseCreationScript(Entity entity) {
    String url = entity.getConfig(DatastoreMixins.CREATION_SCRIPT_URL);
    if (!Strings.isBlank(url))
        return new ResourceUtils(entity).getResourceFromUrl(url);

    String templateUrl = entity.getConfig(DatastoreMixins.CREATION_SCRIPT_TEMPLATE);
    if (!Strings.isBlank(templateUrl)) {
        String template = TemplateProcessor.processTemplateContents(new ResourceUtils(entity).getResourceAsString(templateUrl), (EntityInternal) entity, ImmutableMap.<String, Object>of());
        try {
            return new ByteArrayInputStream(template.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw Exceptions.propagate(e);
        }
    }

    String contents = entity.getConfig(DatastoreMixins.CREATION_SCRIPT_CONTENTS);
    if (!Strings.isBlank(contents))
        return KnownSizeInputStream.of(contents);
    return null;
}
 
Example 20
Source Project: brooklyn-server   Source File: SshMachineLocation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String resolveOnBoxDirFor(Entity entity, String unresolvedPath) {
    ProcessTaskWrapper<Integer> baseTask = SshEffectorTasks.ssh(
        BashCommands.alternatives("mkdir -p \"${BASE_DIR}\"",
            BashCommands.chain(
                BashCommands.sudo("mkdir -p \"${BASE_DIR}\""),
                BashCommands.sudo("chown "+getUser()+" \"${BASE_DIR}\""))),
        "cd ~",
        "cd ${BASE_DIR}",
        "echo BASE_DIR_RESULT':'`pwd`:BASE_DIR_RESULT")
        .environmentVariable("BASE_DIR", unresolvedPath)
        .requiringExitCodeZero()
        .summary("initializing on-box base dir "+unresolvedPath).newTask();
    DynamicTasks.queueIfPossible(baseTask).orSubmitAsync(entity);
    return Strings.getFragmentBetween(baseTask.block().getStdout(), "BASE_DIR_RESULT:", ":BASE_DIR_RESULT");
}
 
Example 21
Source Project: brooklyn-library   Source File: MonitorUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
private Process createDumpingProcess(boolean writeToErr) throws IOException {
    String errSuffix = writeToErr ? " >&2" : "";
    //Windows limits the length of the arguments so echo multiple times instead
    String bigstr = Strings.repeat("a", 8000);
    String bigcmd = getExecPrefix() + Strings.repeat(getSilentPrefix() + "echo " + bigstr + errSuffix + Os.LINE_SEPARATOR, 15);
    File file = Os.newTempFile("test-consume", ".bat");
    file.setExecutable(true);
    Files.write(bigcmd, file, Charsets.UTF_8);
    Process process = MonitorUtils.exec(file.getAbsolutePath());
    return process;
}
 
Example 22
Source Project: brooklyn-server   Source File: ArchiveUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Deploys an archive file to a remote machine and extracts the contents.
 * <p>
 * Copies the archive file from the given URL to a file in a temporary directory and extracts
 * the contents in the destination directory. For Java archives of type {@code .jar},
 * {@code .war} or {@code .ear} the file is simply copied.
 * 
 * @return true if the archive is downloaded AND unpacked; false if it is downloaded but not unpacked; 
 * throws if there was an error downloading or, for known archive types, unpacking.
 *
 * @see #deploy(String, SshMachineLocation, String)
 * @see #deploy(Map, String, SshMachineLocation, String, String, String)
 * @see #install(SshMachineLocation, String, String, int)
 */
public static boolean deploy(ResourceUtils resolver, Map<String, ?> props, String archiveUrl, SshMachineLocation machine, String destDir, boolean keepArchiveAfterUnpacking, String optionalTmpDir, String optionalDestFile) {
    String destFile = optionalDestFile;
    if (destFile==null) destFile = Urls.getBasename(Preconditions.checkNotNull(archiveUrl, "archiveUrl"));
    if (Strings.isBlank(destFile)) 
        throw new IllegalStateException("Not given filename and cannot infer archive type from '"+archiveUrl+"'");
    
    String tmpDir = optionalTmpDir;
    if (tmpDir==null) tmpDir=Preconditions.checkNotNull(destDir, "destDir");
    if (props==null) props = MutableMap.of();
    String destPath = Os.mergePaths(tmpDir, destFile);

    // Use the location mutex to prevent package manager locking issues
    machine.acquireMutex("installing", "installing archive");
    try {
        int result = install(resolver, props, machine, archiveUrl, destPath, NUM_RETRIES_FOR_COPYING);
        if (result != 0) {
            throw new IllegalStateException(format("Unable to install archive %s to %s", archiveUrl, machine));
        }

        // extract, now using task if available
        MutableList<String> commands = MutableList.copyOf(installCommands(destFile))
                .appendAll(extractCommands(destFile, tmpDir, destDir, false, keepArchiveAfterUnpacking));
        if (DynamicTasks.getTaskQueuingContext()!=null) {
            result = DynamicTasks.queue(SshTasks.newSshExecTaskFactory(machine, commands.toArray(new String[0])).summary("extracting archive").requiringExitCodeZero()).get();
        } else {
            result = machine.execCommands(props, "extracting content", commands);
        }
        if (result != 0) {
            throw new IllegalStateException(format("Failed to expand archive %s on %s", archiveUrl, machine));
        }
        return ArchiveType.of(destFile)!=ArchiveType.UNKNOWN;
    } finally {
        machine.releaseMutex("installing");
    }
}
 
Example 23
Source Project: brooklyn-server   Source File: FeedConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    StringBuilder result = new StringBuilder();
    result.append(toStringBaseName());
    result.append("[");
    boolean contents = false;
    Object source = toStringPollSource();
    AttributeSensor<T> s = getSensor();
    if (Strings.isNonBlank(Strings.toString(source))) {
        result.append(Strings.toUniqueString(source, 40));
        if (s!=null) {
            result.append("->");
            result.append(s.getName());
        }
        contents = true;
    } else if (s!=null) {
        result.append(s.getName());
        contents = true;
    }
    MutableList<Object> fields = toStringOtherFields();
    if (fields!=null) {
        for (Object field: fields) {
            if (Strings.isNonBlank(Strings.toString(field))) {
                if (contents) result.append(";");
                contents = true;
                result.append(field);
            }
        }
    }
    result.append("]");
    return result.toString();
}
 
Example 24
Source Project: brooklyn-server   Source File: AbstractEntity.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Invoked by {@link EntityManagementSupport} when this entity is becoming managed (i.e. it has a working
 * management context, but before the entity is visible to other entities), including during a rebind.
 */
public void onManagementStarting() {
    if (isLegacyConstruction()) {
        entityType.setName(getEntityTypeName());
        if (displayNameAutoGenerated) displayName.set(getEntityType().getSimpleName()+":"+Strings.maxlen(getId(), 4));
    }
}
 
Example 25
Source Project: brooklyn-server   Source File: BasicBrooklynCatalog.java    License: Apache License 2.0 5 votes vote down vote up
private String makeAsIndentedList(String yaml) {
    String[] lines = yaml.split("\n");
    lines[0] = "- "+lines[0];
    for (int i=1; i<lines.length; i++)
        lines[i] = "  " + lines[i];
    return Strings.join(lines, "\n");
}
 
Example 26
@Override
public <D extends EntityDriver> String inferDriverClassName(DriverDependentEntity<D> entity, Class<D> driverInterface, Location location) {
    String driverInterfaceName = driverInterface.getName();
    if (!(location instanceof SshMachineLocation)) return null;
    if (!driverInterfaceName.endsWith("Driver")) {
        throw new IllegalArgumentException(String.format("Driver name [%s] doesn't end with 'Driver'; cannot auto-detect SshDriver class name", driverInterfaceName));
    }
    return Strings.removeFromEnd(driverInterfaceName, "Driver")+"SshDriver";
}
 
Example 27
@Test(groups="Integration")
@DisableOnWindows(reason = "Needs a bash shell available on localhost")
public void testPipeMultiline() throws Exception {
    String output = execRequiringZeroAndReturningStdout(loc,
            BashCommands.pipeTextTo("hello world\n"+"and goodbye\n", "wc")).get();

    assertEquals(Strings.replaceAllRegex(output, "\\s+", " ").trim(), "3 4 25");
}
 
Example 28
Source Project: brooklyn-server   Source File: TypeResource.java    License: Apache License 2.0 5 votes vote down vote up
static boolean isLatestOnly(String versions, boolean defaultValue) {
    if (ALL.equalsIgnoreCase(versions)) return false;
    if (LATEST.equalsIgnoreCase(versions)) return true;
    if (Strings.isNonBlank(versions)) {
        log.warn("Invalid 'versions' argument '"+versions+"' when listing types; should be 'all' or 'latest'");
    }
    return defaultValue;
}
 
Example 29
Source Project: brooklyn-library   Source File: MongoDBReplicaSetImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String apply(Collection<String> input) {
    String credentials = MongoDBAuthenticationUtils.usesAuthentication(entity) 
            ? String.format("%s:%[email protected]", 
                    entity.config().get(MongoDBAuthenticationMixins.ROOT_USERNAME), 
                    entity.config().get(MongoDBAuthenticationMixins.ROOT_PASSWORD)) 
            : "";
    return String.format("mongodb://%s%s", credentials, Strings.join(input, ","));
}
 
Example 30
Source Project: brooklyn-server   Source File: BrooklynWebServer.java    License: Apache License 2.0 5 votes vote down vote up
private void initSecurity(WebAppContext context) {
    if (skipSecurity) {
        // Could add <security-constraint> in an override web.xml here
        // instead of relying on the war having it (useful for downstream).
        // context.addOverrideDescriptor("override-web.xml");
        // But then should do the same in OSGi. For now require the web.xml
        // to have security pre-configured and ignore it if noConsoleSecurity used.
        //
        // Ignore security config in web.xml.
        context.setSecurityHandler(new NopSecurityHandler());
        
        // Above probably not used any more. Handled by the BrooklynSecurityProviderFilter* classes
        String provider = Strings.toString( ((ManagementContextInternal)managementContext).getBrooklynProperties().getConfigRaw(BrooklynWebConfig.SECURITY_PROVIDER_CLASSNAME).orNull() );
        if (provider==null) {
            ((ManagementContextInternal)managementContext).getBrooklynProperties().put(BrooklynWebConfig.SECURITY_PROVIDER_CLASSNAME, 
                AnyoneSecurityProvider.class.getName());
        } else if (AnyoneSecurityProvider.class.getName().equals(provider)) {
            // already set
        } else {
            // mismatch - warn, but continue
            log.warn("Server told to skip security with unexpected security provider: "+provider);
        }
    } else {
        // Cover for downstream projects which don't have the changes.
        context.addOverrideDescriptor(getClass().getResource("/web-security.xml").toExternalForm());
    }
}