Example usage for java.io PrintStream append

List of usage examples for java.io PrintStream append

Introduction

In this page you can find the example usage for java.io PrintStream append.

Prototype

public PrintStream append(char c) 

Source Link

Document

Appends the specified character to this output stream.

Usage

From source file:org.apache.pig.backend.local.executionengine.LocalPigLauncher.java

@Override
public void explain(PhysicalPlan pp, PigContext pc, PrintStream ps, String format, boolean isVerbose)
        throws PlanException, VisitorException, IOException {
    pp.explain(ps, format, isVerbose);// w  ww .  j  av a  2 s.c  o m
    ps.append('\n');
}

From source file:uk.ac.diamond.scisoft.analysis.rcp.views.AsciiTextView.java

/**
 * Save text to file/*from  w  w w. ja  v  a  2  s  .  c  o m*/
 */
public void saveText() {
    FileDialog dialog = new FileDialog(getSite().getShell(), SWT.SAVE);
    dialog.setOverwrite(true);
    dialog.setFileName("text.txt");
    dialog.setFilterExtensions(new String[] { ".txt" });
    dialog.setFilterNames(new String[] { "Ascii text" });

    String fileName = dialog.open();
    if (fileName == null) {
        return;
    }

    try {
        final PrintStream stream = new PrintStream(fileName);

        getSite().getShell().getDisplay().asyncExec(new Runnable() {

            @Override
            public void run() {
                stream.append(text.getText());
                stream.close();
            }
        });
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:gov.nasa.ensemble.dictionary.nddl.NumericResourceTranslator.java

@Override
public void writeObjects(PrintStream oStrm) {
    for (ENumericResourceDef res : resourceDefs_) {
        ST classDecl = new ST(classTemplate);
        classDecl.add("className", NDDLUtil.escape(res.getName()));
        oStrm.append(classDecl.render());
    }//from ww w. ja  v a2s.c o  m
}

From source file:org.forgerock.openidm.shell.impl.RemoteCommandScope.java

private void prettyPrint(PrintStream out, String cmd, String name, String reason) {
    out.append("[").append(cmd).append("] ").append(name).append(" ")
            .append(DOTTED_PLACEHOLDER.substring(Math.min(name.length(), DOTTED_PLACEHOLDER.length())));
    if (null == reason) {
        out.println(" SUCCESS");
    } else {/*from   w  ww  .  j av  a2  s  .  c o m*/
        out.println(" FAILED");
        out.append("\t[").append(reason).println("]");
    }
}

From source file:rapture.sheet.file.FileSheetStore.java

private void appendCells(PrintStream stream, Collection<RaptureSheetCell> cells) {
    for (RaptureSheetCell cell : cells) {
        char i = 32;
        String data = cell.getData();
        if (data == null)
            continue; // cell has been deleted
        // Find a delimeter that is available.
        // NOTE: if negative column numbers are allowed then we can't use minus sign
        while ((data.indexOf(i) >= 0) || Character.isDigit(i) || (i == '-'))
            i++;//from w ww.  j a  v a 2s  .c om
        stream.append(i);
        stream.append(("" + cell.getRow()));
        stream.append(i);
        stream.append(("" + cell.getColumn()));
        stream.append(i);
        stream.append(("" + cell.getEpoch()));
        stream.append(i);
        stream.append(data.replaceAll("\n", "")); // newline not allowed
        stream.append('\n');
    }
}

From source file:org.codehaus.mojo.dbupgrade.sqlexec.DefaultSQLExec.java

/**
 * Exec the sql statement./*from w w w.  j  a  v  a 2  s.co  m*/
 */
private void execSQL(String sql, PrintStream out) throws SQLException {
    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;
    }

    if (config.isVerbose()) {
        out.append(sql).append("\n");
    }

    ResultSet resultSet = null;
    try {
        totalStatements++;

        boolean ret;
        int updateCount, updateCountTotal = 0;

        ret = statement.execute(sql);
        updateCount = statement.getUpdateCount();
        resultSet = statement.getResultSet();
        do {
            if (!ret) {
                if (updateCount != -1) {
                    updateCountTotal += updateCount;
                }
            } else {
                if (config.isPrintResultSet()) {
                    printResultSet(resultSet, out);
                }
            }
            ret = statement.getMoreResults();
            if (ret) {
                updateCount = statement.getUpdateCount();
                resultSet = statement.getResultSet();
            }
        } while (ret);

        if (config.isPrintResultSet()) {
            StringBuffer line = new StringBuffer();
            line.append(updateCountTotal).append(" rows affected");
            out.println(line);
        }

        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
        successfulStatements++;
    } catch (SQLException e) {
        if (SQLExecConfig.ON_ERROR_ABORT.equalsIgnoreCase(config.getOnError())) {
            throw new SQLException("Unable to execute: " + sql, e);
        }
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
}

From source file:org.omnaest.utils.structure.map.MapUtils.java

/**
 * Prints out a given {@link Map} using {@link String#valueOf(Object)} and all submaps indented to a new column.<br>
 * <br>/*  www.j  a  v  a2 s .co  m*/
 * Example:<br>
 * 
 * <pre>
 * -+
 *  |-- valueDouble=1.234
 *  |-+ testClassCopy
 *  | |-- valueDouble=5.678
 *  | |-- testClassCopy=null
 *  | |-- privateField=privateValue0.16433438667207334
 *  | |-+ future
 *  | | |-- countDownLatch=java.util.concurrent.CountDownLatch@1f4384c2[Count = 1]
 *  | | |-- shouldCancel=false
 *  | | |-- isCancelled=false
 *  | | |-- value=null
 *  | | |-- clazz=org.omnaest.utils.structure.element.FutureSimple
 * </pre>
 * 
 * @param printStream
 * @param map
 */
public static void printMapHierarchical(final PrintStream printStream, @SuppressWarnings("rawtypes") Map map) {
    //
    class MapPrinter {
        @SuppressWarnings("rawtypes")
        public void printMap(Map map, int indentation) {
            if (map != null) {
                String indentationString = StringUtils.repeat(" |", indentation / 2);
                printStream.append(indentation == 0 ? indentationString + "-+\n" : "");
                for (Object key : map.keySet()) {
                    //
                    Object value = map.get(key);

                    //
                    if (value instanceof Map) {
                        //
                        printStream.append(indentationString + " |-+ " + String.valueOf(key) + "\n");
                        this.printMap((Map) value, indentation + 2);
                    } else {
                        //
                        printStream.append(indentationString + " |-- " + String.valueOf(key) + "="
                                + String.valueOf(map.get(key)) + "\n");
                    }
                }
                printStream.append(indentationString + "\n");
            }
        }
    }

    //
    new MapPrinter().printMap(map, 0);
}

From source file:gov.nasa.ensemble.dictionary.nddl.NumericResourceTranslator.java

@Override
public void writeInitialState(PrintStream oStrm) {
    for (ENumericResourceDef res : resourceDefs_) {
        ST objDecl = new ST(objInstanceTemplate);
        objDecl.add("className", NDDLUtil.escape(res.getName()));
        objDecl.add("initCap", "0.0"); // TODO: do we have initCap at this point?
        // Hack! what should we use as maxCap if absent?
        double maxCap = (res.getMaximum() != null ? res.getMaximum() : 1e6);
        objDecl.add("maxCap", maxCap);
        // TODO: what about getMinimum, should we pass it to the model?
        // objDecl.add("minCap", res.getMinimum());
        oStrm.append(objDecl.render());
    }//from   ww w  .j  a v a2  s.  c o m
}

From source file:org.forgerock.openidm.shell.impl.RemoteCommandScope.java

/**
 * Imports the configuration set from a local file or directory.
 *
 * @param session the command session// w w  w .j  a v a  2  s.  c  o  m
 * @param userPass the username/password
 * @param idmUrl the url of the OpenIDM instance
 * @param idmPort the OpenIDM instance's port
 * @param replaceall whether or not to replace the config
 * @param source the source directory
 */
@Descriptor("Imports the configuration set from local file/directory.")
public void configimport(final CommandSession session,

        @Descriptor(USER_PASS_DESC) @MetaVar(USER_PASS_METAVAR) @Parameter(names = { "-u",
                "--user" }, absentValue = USER_PASS_DEFAULT) final String userPass,

        @Descriptor(IDM_URL_DESC) @MetaVar(IDM_URL_METAVAR) @Parameter(names = {
                "--url" }, absentValue = IDM_URL_DEFAULT) final String idmUrl,

        @Descriptor(IDM_PORT_DESC) @MetaVar(IDM_PORT_METAVAR) @Parameter(names = { "-P",
                "--port" }, absentValue = IDM_PORT_DEFAULT) final String idmPort,

        @Descriptor(REPLACE_ALL_DESC) @Parameter(names = { "-r", "--replaceall",
                "--replaceAll" }, presentValue = "true", absentValue = "false") final boolean replaceall,

        @Descriptor("source directory") final String source) {
    processOptions(userPass, idmUrl, idmPort);

    PrintStream console = session.getConsole();
    File file = IdentityServer.getFileForPath(source);
    console.println("...................................................................");
    if (file.isDirectory()) {
        console.println("[ConfigImport] Load JSON configuration files from:");
        console.append("[ConfigImport] \t").println(file.getAbsolutePath());

        FileFilter filter = new FileFilter() {
            public boolean accept(File f) {
                return f.getName().endsWith(".json");
            }
        };

        // Read the files from the provided source directory.
        File[] files = file.listFiles(filter);
        Map<String, File> localConfigSet = new HashMap<String, File>(files.length);
        for (File subFile : files) {
            if (subFile.isDirectory()) {
                continue;
            }
            String configName = subFile.getName().replaceFirst("-", "/");
            configName = ConfigBootstrapHelper.unqualifyPid(configName.substring(0, configName.length() - 5));
            if (configName.indexOf("-") > -1) {
                console.append(
                        "[WARN] Invalid file name found with multiple '-' character. The normalized config id: ");
                console.println(configName);
            }
            localConfigSet.put(configName, subFile);
        }

        // Read the remote configs that are currently active.
        Map<String, JsonValue> remoteConfigSet = new HashMap<String, JsonValue>();
        try {
            ResourceResponse responseValue = resource.read(null, Requests.newReadRequest("config"));
            Iterator<JsonValue> iterator = responseValue.getContent().get("configurations").iterator();
            while (iterator.hasNext()) {
                JsonValue configValue = iterator.next();
                // TODO catch JsonValueExceptions
                String id = ConfigBootstrapHelper.unqualifyPid(configValue.get("_id").required().asString());
                // Remove apache configurations
                if (!id.startsWith("org.apache")) {
                    remoteConfigSet.put(id, configValue);
                }
            }
        } catch (ResourceException e) {
            console.append("Remote operation failed: ").println(e.getMessage());
            return;
        } catch (Exception e) {
            console.append("Operation failed: ").println(e.getMessage());
            return;
        }

        final ResourcePath configResource = ResourcePath.valueOf("config");
        for (Map.Entry<String, File> entry : localConfigSet.entrySet()) {
            String sourceConfigId = entry.getKey();
            try {
                if (remoteConfigSet.containsKey(sourceConfigId)) {
                    // Update
                    UpdateRequest updateRequest = Requests.newUpdateRequest(
                            configResource.concat(sourceConfigId),
                            new JsonValue(mapper.readValue(entry.getValue(), Map.class)));

                    resource.update(null, updateRequest);
                    // If the update succeeded, remove the entry from 'remoteConfigSet' - this prevents it
                    // from being deleted below.  If this update fails, the entry will remain in remoteConfigSet
                    // and will be deleted from the remote IDM instance.
                    remoteConfigSet.remove(sourceConfigId);
                } else {
                    // Create
                    CreateRequest createRequest = Requests.newCreateRequest(
                            configResource.concat(sourceConfigId),
                            new JsonValue(mapper.readValue(entry.getValue(), Map.class)));
                    resource.create(null, createRequest);
                }
                prettyPrint(console, "ConfigImport", sourceConfigId, null);
            } catch (Exception e) {
                prettyPrint(console, "ConfigImport", sourceConfigId, e.getMessage());
            }
        }

        // Delete all additional config objects
        if (replaceall) {
            for (String configId : remoteConfigSet.keySet()) {
                if (isProtectedConfigId(configId)) {
                    prettyPrint(console, "ConfigDelete", configId,
                            "Protected configuration can not be deleted");
                    continue;
                }

                try {
                    // configId is concatenated to avoid file paths from getting url encoded -> '/'-> '%2f'
                    resource.delete(null, Requests.newDeleteRequest(configResource.concat(configId)));
                    prettyPrint(console, "ConfigDelete", configId, null);
                } catch (Exception e) {
                    prettyPrint(console, "ConfigDelete", configId, e.getMessage());
                }
            }
        }

    } else if (file.exists()) {
        // TODO import archive file
        console.println("Input path must be a directory not a file.");
    } else {
        console.append("[ConfigImport] Configuration directory not found at: ");
        console.println(file.getAbsolutePath());
    }
}

From source file:org.wso2.carbon.appfactory.jenkins.AppfactoryPluginManager.java

/**
 * When the user configures the project and enables this Notifier, when a build is performed
 * this method will be invoked by jenkins
 * This method is mainly used to notify appfactory regarding the build status and
 * store the tagged artifacts by user/* w  w w.j ava2s  . com*/
 * @param build
 * @param launcher
 * @param listener
 * @return
 * @throws InterruptedException
 * @throws IOException
 */
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {
    if (log.isDebugEnabled()) {
        log.debug("Perform action triggered for " + this.userName + " for " + this.applicationId + " - "
                + this.applicationVersion + " in " + this.repositoryFrom + ". Build status is "
                + build.getResult());
    }
    // logger for the console output of the build job
    PrintStream logger = listener.getLogger();
    String msg = "The build started by " + this.userName + " for " + this.applicationId + " - "
            + this.applicationVersion + " in " + this.repositoryFrom + " is notified as " + build.getResult();
    logger.append(msg);
    final String APPFACTORY_SERVER_URL = getDescriptor().getAppfactoryServerURL();
    String serviceURL = APPFACTORY_SERVER_URL + BUILDSTATUS_RECEIVER_NAME;
    BuildStatusReceiverClient client = new BuildStatusReceiverClient(serviceURL,
            getDescriptor().getAdminUserName(), getDescriptor().getAdminPassword());

    //Getting the tenant user name from the build parameters because we are sending it from AF
    String tenantUserName = build.getBuildVariables().get("tenantUserName");

    BuildStatusBean buildStatus = createBuildStatusBean(build.getNumber(), tenantUserName);

    if (build.getResult() == Result.SUCCESS) {
        buildStatus.setBuildSuccessful(true);
        buildStatus.setLogMsg("Build Successful");
        client.onBuildCompletion(buildStatus, tenantUserName);

        boolean isAutomatic = Boolean.parseBoolean(build.getEnvironment(listener).get("isAutomatic"));
        if (isAutomatic) {
            try {
                String stage = getStage(applicationId, applicationVersion);
                // this block is executed when a commit goes to a branch where auto deployment is enabled
                // so this is to deploy the app to the relevant stage. so deployAction = deploy

                sendMessageToDeploy(applicationId, applicationVersion, "HEAD", stage,
                        AppFactoryConstants.DEPLOY_ACTION_AUTO_DEPLOY, tenantUserName, this.repositoryFrom);
            } catch (ApplicationDeployerAppFactoryExceptionException e) {
                msg = "Error while retrieving the deployment stage of application " + applicationId
                        + " in version " + applicationVersion
                        + "Failed to deploy the artifact of automatic build";
                logger.append(msg);
                log.info(msg);
            }
        }
        //String deployAction = build.getEnvironment(listener).get("doDeploy");
        boolean doDeploy = Boolean.parseBoolean(build.getEnvironment(listener).get("doDeploy"));

        if (doDeploy) {

            String tagName = build.getEnvironment(listener).get("tagName");
            String stage = build.getEnvironment(listener).get("deployStage");
            String deployAction = AppFactoryConstants.DEPLOY_ACTION_AUTO_DEPLOY;
            if (tagName != null && tagName != "") {
                logger.append("sending message to deploy to stage ").append(stage).append(" with tag ")
                        .append(tagName);
                sendMessageToDeploy(applicationId, applicationVersion, "HEAD", stage, deployAction,
                        tenantUserName, this.repositoryFrom);
            } else {
                msg = "sending message to deploy to stage " + stage;
                logger.append(msg);
                log.info(msg);
                sendMessageToDeploy(applicationId, applicationVersion, "HEAD", stage, deployAction,
                        tenantUserName, this.repositoryFrom);
            }

        } else {
            logger.append("DoDeploy is false");
        }
        msg = "Successfully finished " + build.getFullDisplayName();
        log.info(msg);
        logger.append(msg);

    } else {
        if (Boolean.parseBoolean(build.getEnvironment(listener).get("isAutomatic"))) {
            // todo send a notification to appfactory saying the deployment failed
            logger.append("This automatic build will not deploy any artifacts since the build"
                    + " failed for application ").append(applicationId)
                    .append(" in " + "version " + applicationVersion);
        }
        buildStatus.setBuildSuccessful(false);
        //TODO get the error message from jenkins and put
        buildStatus.setLogMsg("Build Failed");
        client.onBuildCompletion(buildStatus, tenantUserName);
        msg = "Build failed " + build.getFullDisplayName();
        logger.append(msg);
        log.info(msg);
    }

    boolean shouldPersist = Boolean.parseBoolean(build.getEnvironment(listener).get("persistArtifact"));
    if (shouldPersist) {
        String tagName = build.getEnvironment(listener).get("tagName");

        if (tagName != null && !tagName.equals("")) {
            logger.append("Storing artifact permanently with the tag name ").append(tagName);

            //                We look for all the files which match the given extension
            FilePath[] files = build.getWorkspace().list("**/*." + this.applicationArtifactExtension);

            if (files != null && files.length > 0) {
                //                    Using the old logic. There should only be 1 artifact.
                //                    Taking the first and ignoring the rest
                FilePath sourceFilePath = files[0];
                String tenantDomain = MultitenantUtils.getTenantDomain(tenantUserName);
                //                    We need to create the target folder the file should be copied
                String filePath = this.getDescriptor().getStoragePath(tenantDomain) + File.separator
                        + build.getEnvironment(listener).get("JOB_NAME") + File.separator + tagName;
                File persistArtifact = new File(filePath);

                if (!persistArtifact.mkdirs()) {
                    listener.getLogger().append("Unable to create the tag directory");
                }

                //                    Creating the target file path.
                String targetFilePath = persistArtifact.getAbsolutePath() + File.separator
                        + sourceFilePath.getName();

                //                    This works for both the mater and slave builds
                sourceFilePath.copyTo(new FilePath(new File(targetFilePath)));
            } else {
                listener.getLogger().append("No artifacts were found to persist");
            }

        } else {
            logger.append("Cannot persist the artifact. Tag name cannot be null or empty");
        }

    } else {
        logger.append("Artifact is not stored permanently. persistArtifact = ")
                .append(String.valueOf(shouldPersist));
    }
    return true;
}