Example usage for java.io PrintStream println

List of usage examples for java.io PrintStream println

Introduction

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

Prototype

public void println(Object x) 

Source Link

Document

Prints an Object and then terminate the line.

Usage

From source file:com.yohanliyanage.jenkins.plugins.sparkdeploy.deployer.DeploymentManager.java

public DeploymentManager(String masterRestUrl, PrintStream logger, boolean verbose) {
    this.logger = logger;
    this.verbose = verbose;
    try {//from w ww .  j a v  a 2  s . com
        this.masterRestUrl = new URL(Utils.getActualSparkMasterUrl(masterRestUrl));
        logger.println("Spark REST Service endpoint resolved to " + this.masterRestUrl);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Invalid Master REST URL: " + masterRestUrl);
    }
}

From source file:com.michelin.cio.hudson.plugins.qc.client.QualityCenterClientInstaller.java

public void install(Launcher launcher, TaskListener log, String expectedLocation, FilePath qcBundle)
        throws IOException, InterruptedException {
    PrintStream out = log.getLogger();
    String qcBundleName = qcBundle.getName();
    String qcBundlePath = qcBundle.absolutize().getRemote();

    out.println(Messages.QualityCenterClientInstaller_Installing(qcBundleName));
    String logFile = qcBundlePath + ".install.log";

    StringBuilder cmd = new StringBuilder();
    cmd.append('"').append(qcBundlePath).append('"');
    cmd.append(" /qn /norestart TARGETDIR=");
    cmd.append('"').append(expectedLocation).append('"');
    cmd.append(" /l ");
    cmd.append('"').append(logFile).append('"');

    // Run the install on the node
    // The result must be 0
    ArgumentListBuilder args = new ArgumentListBuilder().add("cmd.exe", "/C").addQuoted(cmd.toString());
    if (launcher.launch().cmds(args).stdout(out).pwd(expectedLocation).join() != 0) {
        log.fatalError(Messages.QualityCenterClientInstaller_AbortedInstall());
        // log file is in UTF-16
        InputStream is = new FileInputStream(logFile);
        InputStreamReader in = new InputStreamReader(is, "UTF-16");
        try {//from   w w  w  . j av  a 2s  .  c o m
            IOUtils.copy(in, new OutputStreamWriter(out));
        } finally {
            in.close();
            is.close();
        }
        throw new AbortException();
    }

    out.println(Messages.QualityCenterClientInstaller_InstallationSuccessfull());
}

From source file:jp.ikedam.jenkins.plugins.jobcopy_builder.AdditionalFileset.java

/**
 * Process one file.//from  www .  j  a  v  a 2s . com
 * 
 * @param dstFile
 * @param srcFile
 * @param logger
 * @return
 */
protected boolean performToFile(File dstFile, File srcFile, EnvVars env, PrintStream logger) {
    if (dstFile.exists() && !isOverwrite()) {
        logger.println(String.format("%s is already exists...skip.", dstFile.getPath()));
        return true;
    }

    // Read file into string.
    String fileContents;
    String encoding = "UTF-8";
    try {
        fileContents = FileUtils.readFileToString(srcFile, encoding);
    } catch (IOException e) {
        logger.println(String.format("Failed to read from %s", srcFile.getPath()));
        e.printStackTrace(logger);
        return false;
    }

    logger.println("Original contents:");
    logger.println(fileContents);

    // Apply additional operations to the retrieved Contents.
    if (getJobcopyOperationList() != null) {
        for (JobcopyOperation operation : getJobcopyOperationList()) {
            fileContents = operation.perform(fileContents, encoding, env, logger);
            if (fileContents == null) {
                return false;
            }
        }
    }
    logger.println("Copied contents:");
    logger.println(fileContents);

    try {
        // The directories seem to be automatically created. 
        FileUtils.writeStringToFile(dstFile, fileContents, encoding);
    } catch (IOException e) {
        logger.println(String.format("Failed to write to %s", dstFile.getPath()));
        e.printStackTrace(logger);
        return false;
    }

    return true;
}

From source file:de.ailis.wlandsuite.WebExtract.java

/**
 * Extracts the animations./*from  www  .j  a va 2  s. co m*/
 *
 * @param sourceDirectory
 *            The input directory
 * @param targetDirectory
 *            The output directory
 * @throws IOException
 *             When file operation fails.
 */

private void extractAnimations(final File sourceDirectory, final File targetDirectory) throws IOException {
    // Extract tilesets
    final File animsDirectory = new File(new File(targetDirectory, "images"), "animations");
    animsDirectory.mkdirs();

    for (int gameId = 1; gameId <= 2; gameId++) {
        final String filename = "allpics" + gameId;

        log.info("Reading " + filename);
        final Pics pics;
        final InputStream stream = new FileInputStream(new File(sourceDirectory, filename));
        try {
            pics = Pics.read(stream);
        } finally {
            stream.close();
        }

        int i = 0;
        for (final PicsAnimation animation : pics.getAnimations()) {
            log.info("Writing pic " + i);
            final File animDirectory = new File(animsDirectory, String.format("%d%02d", gameId, i));
            animDirectory.mkdirs();

            final TransparentEgaImage baseFrame = new TransparentEgaImage(
                    this.scaleFilter.scale(animation.getBaseFrame()));

            int layerId = 1;
            for (final PicsAnimationFrameSet frameSet : animation.getFrameSets()) {
                final List<Pic> frames = frameSet.getFrames();
                final List<PicsAnimationInstruction> instructions = frameSet.getInstructions();
                final GifAnimWriter gif = new GifAnimWriter(new File(animDirectory, "layer" + layerId + ".gif"),
                        0);
                try {
                    gif.setTransparentIndex(0);
                    gif.setDelay(instructions.get(0).getDelay() * 50);
                    TransparentEgaImage current = baseFrame;
                    if (layerId == 1)
                        gif.addFrame(current);
                    else
                        gif.addFrame(new TransparentEgaImage(baseFrame.getWidth(), baseFrame.getHeight()));
                    for (int j = 0; j < instructions.size(); j++) {
                        final PicsAnimationInstruction instruction = instructions.get(j);
                        final int frameIndex = instruction.getFrame();
                        final int delay = instructions.get((j + 1) % instructions.size()).getDelay();
                        final TransparentEgaImage frame = frameIndex == 0 ? baseFrame
                                : new TransparentEgaImage(this.scaleFilter.scale(frames.get(frameIndex - 1)));
                        gif.setDelay(delay * 50);
                        gif.addFrame(current.getDiff(frame));
                        current = frame;
                    }
                } finally {
                    gif.close();
                }
                layerId++;
            }

            final File htmlFile = new File(animDirectory, "index.html");
            final PrintStream html = new PrintStream(htmlFile);
            html.println("<html>");
            html.println("<body>");
            html.println("<div style=\"position:relative\">");
            html.println("<img src=\"layer1.gif\" />");
            for (int j = 2; j < layerId; j++) {
                html.println("<img src=\"layer" + j + ".gif\" style=\"position:absolute;left:0;top:0\" />");
            }
            html.println("</div>");
            html.println("</body>");
            html.println("</html>");
            html.close();

            i++;
        }
    }
}

From source file:jenkins.plugins.logstash.persistence.ElasticSearchDao.java

private String getErrorMessage(CloseableHttpResponse response) {
    ByteArrayOutputStream byteStream = null;
    PrintStream stream = null;
    try {//from   w  w w .  j a v a2s .  c  om
        byteStream = new ByteArrayOutputStream();
        stream = new PrintStream(byteStream);

        try {
            stream.print("HTTP error code: ");
            stream.println(response.getStatusLine().getStatusCode());
            stream.print("URI: ");
            stream.println(uri.toString());
            stream.println("RESPONSE: " + response.toString());
            response.getEntity().writeTo(stream);
        } catch (IOException e) {
            stream.println(ExceptionUtils.getStackTrace(e));
        }
        stream.flush();
        return byteStream.toString();
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:com.mockey.model.ResponseFromService.java

public void writeToOutput(HttpServletResponse resp) throws IOException {
    // copy the headers out
    if (headers != null) {
        for (Header header : headers) {

            // copy the cookies
            if (ignoreHeader(header.getName())) {
                log.debug("Ignoring header: " + header.getName());
            } else if (header.getName().equalsIgnoreCase("Set-Cookie")) {
                // Ignore...
            } else if (header.getName().equals("Content-Type")) {
                // copy the content type
                resp.setContentType(header.getValue());
            } else
                resp.setHeader(header.getName(), header.getValue());
        }//  www  .j  a v a2  s  .c o m
    }

    // For cookie information we already extracted from initialization.
    for (Cookie cookie : this.cookieList) {
        resp.addCookie(cookie);
    }
    if (body != null) {
        byte[] myISO88591asBytes = body.getBytes(HTTP.ISO_8859_1);
        new PrintStream(resp.getOutputStream()).write(myISO88591asBytes);
        resp.getOutputStream().flush();
    } else {
        PrintStream out = new PrintStream(resp.getOutputStream());
        out.println(body);
    }

}

From source file:ca.nines.ise.cmd.Validate.java

/**
 * {@inheritDoc}//from w w w  .j a va2s. co m
 */
@ErrorCode(code = { "dom.errors" })
@Override
public void execute(CommandLine cmd) throws Exception {
    File[] files;

    Log log = Log.getInstance();
    Locale.setDefault(Locale.ENGLISH);
    Schema schema = Schema.defaultSchema();
    DOMValidator dv = new DOMValidator();
    NestingValidator nv = new NestingValidator(schema);
    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    if (cmd.hasOption("l")) {
        out = new PrintStream(new FileOutputStream(cmd.getOptionValue("l")), true, "UTF-8");
    }

    files = getFilePaths(cmd);
    if (files != null) {
        out.println("Found " + files.length + " files to check.");
        for (File in : files) {
            DOM dom = new DOMBuilder(in).build();
            if (dom.getStatus() != DOM.DOMStatus.ERROR) {
                dv.validate(dom, schema);
                nv.validate(dom);
            } else {
                Message m = Message.builder("dom.errors").setSource(dom.getSource()).build();
                log.add(m);
            }
            if (log.count() > 0) {
                out.println(log);
            }
            log.clear();
        }
    }
}

From source file:jenkins.plugins.ec2slave.EC2ImageLaunchWrapper.java

/**
 * Creates an EC2 instance given an AMI, readying it to serve as a Jenkins
 * slave once launch is called later// w  w  w.j  ava  2s. c o m
 *
 * @param logger where to write messages so the user will see them in the
 *               tailed log in Jenkins
 * @throws InterruptedException if the check status wait fails
 */
public void preLaunch(PrintStream logger) throws InterruptedException {

    logger.println("Creating new EC2 instance from AMI [" + ami + "]...");
    if (testMode)
        return;

    curInstanceId = launchInstanceFromImage();

    int retries = 0;
    InstanceStateName state = null;

    while (++retries <= maxRetries) {

        logger.println(MessageFormat.format("checking state of instance [{0}]...", curInstanceId));

        state = getInstanceState(curInstanceId);

        logger.println(
                MessageFormat.format("state of instance [{0}] is [{1}]", curInstanceId, state.toString()));
        if (state == Running) {
            logger.println(MessageFormat.format(
                    "instance [{0}] is running, proceeding to launching Jenkins on this instance",
                    curInstanceId));
            Thread.sleep(retryIntervalSeconds * 3000);
            return;
        } else if (state == Pending) {
            logger.println(
                    MessageFormat.format("instance [{0}] is pending, waiting for [{1}] seconds before retrying",
                            curInstanceId, retryIntervalSeconds));
            Thread.sleep(retryIntervalSeconds * 1000);
        } else {
            String msg = MessageFormat.format(
                    "instance [{0}] encountered unexpected state [{1}]. Aborting launch", curInstanceId,
                    state.toString());
            logger.println(msg);
            throw new IllegalStateException(msg);
        }
    }
    throw new IllegalStateException("Maximum Number of retries " + maxRetries + " exceeded. Aborting launch");
}

From source file:hu.ppke.itk.nlpg.purepos.POSTagger.java

@Override
public void tag(Scanner scanner, PrintStream ps, int maxResultsNumber) {
    String line;/*from  w  ww .j a  v a 2s .  com*/
    while (scanner.hasNext()) {
        line = scanner.nextLine();
        String sentString = tagAndFormat(line, maxResultsNumber);
        ps.println(sentString);

    }

}

From source file:jp.ikedam.jenkins.plugins.jobcopy_builder.ReplaceOperation.java

/**
 * Returns modified XML Document of the job configuration.
 * /*from   ww w  . ja  v a  2  s  . co  m*/
 * Replace the strings in the job configuration: 
 * only applied to strings in text nodes, so the XML structure is never destroyed. 
 * 
 * @param doc       XML Document of the job to be copied (job/NAME/config.xml)
 * @param env       Variables defined in the build.
 * @param logger    The output stream to log.
 * @return          modified XML Document. Return null if an error occurs.
 * @see jp.ikedam.jenkins.plugins.jobcopy_builder.AbstractXmlJobcopyOperation#perform(org.w3c.dom.Document, hudson.EnvVars, java.io.PrintStream)
 */
@Override
public Document perform(Document doc, EnvVars env, PrintStream logger) {
    String fromStr = getFromStr();
    String toStr = getToStr();

    if (StringUtils.isEmpty(fromStr)) {
        logger.println("From String is empty");
        return null;
    }
    if (toStr == null) {
        toStr = "";
    }
    String expandedFromStr = isExpandFromStr() ? env.expand(fromStr) : fromStr;
    String expandedToStr = isExpandToStr() ? env.expand(toStr) : toStr;
    if (StringUtils.isEmpty(expandedFromStr)) {
        logger.println("From String got to be empty");
        return null;
    }
    if (expandedToStr == null) {
        expandedToStr = "";
    }

    logger.print("Replacing: " + expandedFromStr + " -> " + expandedToStr);
    try {
        // Retrieve all text nodes.
        NodeList textNodeList = getNodeList(doc, "//text()");

        // Perform replacing to all text nodes.
        // NodeList does not implement Collection, and foreach is not usable.
        for (int i = 0; i < textNodeList.getLength(); ++i) {
            Node node = textNodeList.item(i);
            node.setNodeValue(StringUtils.replace(node.getNodeValue(), expandedFromStr, expandedToStr));
        }
        logger.println("");

        return doc;
    } catch (Exception e) {
        logger.print("Error occured in XML operation");
        e.printStackTrace(logger);
        return null;
    }
}