Example usage for java.io StringWriter write

List of usage examples for java.io StringWriter write

Introduction

In this page you can find the example usage for java.io StringWriter write.

Prototype

public void write(String str) 

Source Link

Document

Write a string.

Usage

From source file:de.mpg.escidoc.services.aa.crypto.RSAEncoder.java

public static String rsaEncrypt(String string) throws Exception {
    StringWriter resultWriter = new StringWriter();
    byte[] bytes = string.getBytes("UTF-8");
    PublicKey pubKey = (PublicKey) readKeyFromFile(Config.getProperty("escidoc.aa.public.key.file"), true);
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    int blockSize = 245;
    for (int i = 0; i < bytes.length; i += blockSize) {
        byte[] result = cipher.doFinal(bytes, i, (i + blockSize < bytes.length ? blockSize : bytes.length - i));
        if (i > 0) {
            resultWriter.write("&");
        }//from   www .j a v a2  s  .co m
        resultWriter.write("auth=");
        resultWriter.write(URLEncoder.encode(new String(Base64.encodeBase64(result)), "ISO-8859-1"));
    }
    return resultWriter.toString();

}

From source file:org.commonjava.cartographer.rest.util.ResponseUtils.java

public static CharSequence formatEntity(final String id, final Throwable error, final String message) {
    final StringWriter sw = new StringWriter();
    sw.append("Id: ").append(id);
    if (message != null) {
        sw.append("\nMessage: ").append(message);
    }//w w  w  .j a  v  a2 s. com

    sw.append(error.getMessage());

    final Throwable cause = error.getCause();
    if (cause != null) {
        sw.append("\nError:\n\n");
        cause.printStackTrace(new PrintWriter(sw));
    }

    sw.write('\n');

    return sw.toString();
}

From source file:org.openecomp.core.utilities.CommonMethods.java

/**
 * Print stack trace string./*from  w w w .  j  a  v  a2 s .  c  o m*/
 *
 * @return the string
 */
public static String printStackTrace() {

    StringWriter sw = new StringWriter();
    StackTraceElement[] trace = Thread.currentThread().getStackTrace();
    for (StackTraceElement traceElement : trace) {
        sw.write("\t  " + traceElement);
        sw.write(System.lineSeparator());
    }
    String str = sw.toString();
    try {
        sw.close();
    } catch (IOException e0) {
        System.err.println(e0);
    }
    return str;

}

From source file:eu.sisob.uma.restserver.services.internalcvfiles.InternalCVFilesTask.java

public static boolean launch(String user, String pass, String task_code, String code_task_folder, String email,
        StringWriter message) {
    if (message == null) {
        return false;
    }//from w w  w.ja  v  a  2  s  .c  om

    message.getBuffer().setLength(0);
    File code_task_folder_dir = new File(code_task_folder);

    File documents_dir = code_task_folder_dir;

    File input_file = FileSystemManager.getFileIfExists(code_task_folder_dir,
            input_data_source_filename_prefix_csv, input_data_source_filename_ext_csv);
    boolean validate = input_file != null;

    if (!validate) {
        message.write("You have not uploaded any file like this '" + input_data_source_filename_prefix_csv + "*"
                + input_data_source_filename_ext_csv + "' file");
        return false;
    }

    try {
        validate = FileFormatConversor.checkResearchersCSV(input_file, true);
    } catch (Exception ex) {
        eu.sisob.uma.extractors.adhoc.email.ProjectLogger.LOGGER.error(message.toString(), ex);
        validate = false;
    }

    if (!validate) {
        message.write("The format of '" + input_file.getName() + "' does not seems be correct"); //FIXME
        return false;
    }

    String middle_data_folder = code_task_folder + File.separator + AuthorizationManager.middle_data_dirname;
    File middle_data_dir = null;
    try {
        middle_data_dir = FileSystemManager.createFileAndIfExistsDelete(middle_data_folder);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.toString(), ex);
        message.append("The file couldn't be created " + middle_data_dir.getName() + "\r\n");
        return false;
    }

    String results_data_folder = code_task_folder + File.separator + AuthorizationManager.results_dirname;
    File results_data_dir = null;
    try {
        results_data_dir = FileSystemManager.createFileAndIfExistsDelete(results_data_folder);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.toString(), ex);
        message.append("The file couldn't be created " + results_data_dir.getName() + "\r\n");
        return false;
    }

    File zip_file = new File(code_task_folder_dir, input_data_documents_in_zip);

    if (zip_file.exists()) {
        documents_dir = new File(code_task_folder_dir, AuthorizationManager.middle_data_dirname);
        if (!ZipUtil.unZipItToSameFolder(zip_file, documents_dir)) {
            message.write(input_data_documents_in_zip + " cannot bet unziped"); //FIXME
            return false;
        }
    }

    String output_filename = input_file.getName().replace(input_data_source_filename_prefix_csv,
            output_data_source_filename_prefix_csv);
    File output_file = new File(results_data_dir, output_filename);

    String out_filename_2 = input_file.getName().replace(input_data_source_filename_prefix_csv,
            output_data_with_files_source_filename_prefix_csv);
    File output_file_2 = new File(results_data_dir, out_filename_2);

    InternalCVFilesExtractorTaskInRest task = new InternalCVFilesExtractorTaskInRest(user, task_code,
            code_task_folder, email, input_file, documents_dir, output_file,
            new File(results_data_dir, results_dirname), new File(results_data_dir, zip_output_filename),
            output_file_2);

    try {
        EmailExtractorService.getInstance().addExecution((new CallbackableTaskExecution(task)));

        message.write(TheResourceBundle.getString("Jsp Task Executed Msg"));
    } catch (Exception ex) {
        message.write(TheResourceBundle.getString("Jsp Task Executed Error Msg"));
        ProjectLogger.LOGGER.error(message.toString(), ex);
        return false;
    }

    return true;
}

From source file:eu.sisob.uma.restserver.services.email.EmailTask.java

public static boolean launch(String user, String pass, String task_code, String code_task_folder, String email,
        List<String> filters, StringWriter message) {
    if (message == null) {
        return false;
    }//from w w  w .  ja  v  a 2 s . c  o  m

    message.getBuffer().setLength(0);
    File code_task_folder_dir = new File(code_task_folder);

    File documents_dir = code_task_folder_dir;

    File csv_data_source_file = FileSystemManager.getFileIfExists(code_task_folder_dir,
            input_data_source_filename_prefix_csv, input_data_source_filename_ext_csv);
    boolean validate = csv_data_source_file != null;

    if (!validate) {
        message.write("You have not uploaded any file like this '" + input_data_source_filename_prefix_csv + "*"
                + input_data_source_filename_ext_csv + "' file");
        return false;
    }

    try {
        validate = FileFormatConversor.checkResearchersCSV(csv_data_source_file, true);
    } catch (Exception ex) {
        eu.sisob.uma.extractors.adhoc.email.ProjectLogger.LOGGER.error(message.toString(), ex);
        validate = false;
    }

    if (!validate) {
        message.write("The format of '" + csv_data_source_file.getName() + "' does not seems be correct"); //FIXME
        return false;
    }

    String middle_data_folder = code_task_folder + File.separator + AuthorizationManager.middle_data_dirname;
    File middle_data_dir = null;
    try {
        middle_data_dir = FileSystemManager.createFileAndIfExistsDelete(middle_data_folder);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.toString(), ex);
        message.append("The file couldn't be created " + middle_data_dir.getName() + "\r\n");
        return false;
    }

    String results_data_folder = code_task_folder + File.separator + AuthorizationManager.results_dirname;
    File results_data_dir = null;
    try {
        results_data_dir = FileSystemManager.createFileAndIfExistsDelete(results_data_folder);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.toString(), ex);
        message.append("The file couldn't be created " + results_data_dir.getName() + "\r\n");
        return false;
    }

    File zip_file = new File(code_task_folder_dir, input_data_documents_in_zip);

    if (zip_file.exists()) {
        documents_dir = new File(code_task_folder_dir, AuthorizationManager.middle_data_dirname);
        if (!ZipUtil.unZipItToSameFolder(zip_file, documents_dir)) {
            message.write(input_data_documents_in_zip + " cannot bet unziped"); //FIXME
            return false;
        }
    }

    String out_filename = csv_data_source_file.getName().replace(input_data_source_filename_prefix_csv,
            output_data_source_filename_prefix_csv);
    File csv_data_output_file = new File(results_data_dir, out_filename);

    String out_filename_unfounded = csv_data_source_file.getName()
            .replace(input_data_source_filename_prefix_csv, output_data_source_nofound_filename_prefix_csv);
    File csv_data_output_file_unfounded = new File(results_data_dir, out_filename_unfounded);

    String out_filename_wor = csv_data_source_file.getName().replace(input_data_source_filename_prefix_csv,
            output_data_source_norepeat_filename_prefix_csv);
    File csv_data_output_file_wor = new File(results_data_dir, out_filename_wor);

    String out_filename_wor_notfound = csv_data_source_file.getName().replace(
            input_data_source_filename_prefix_csv, output_data_source_nofound_norepeat_filename_prefix_csv);
    File csv_data_output_file_notfound_wor = new File(results_data_dir, out_filename_wor_notfound);

    EmailExtractorTaskInRest task = new EmailExtractorTaskInRest(user, task_code, code_task_folder, email,
            csv_data_source_file, documents_dir, csv_data_output_file, csv_data_output_file_wor,
            csv_data_output_file_unfounded, csv_data_output_file_notfound_wor, filters);

    try {
        EmailExtractorService.getInstance().addExecution((new CallbackableTaskExecution(task)));

        message.write(TheResourceBundle.getString("Jsp Task Executed Msg"));
    } catch (Exception ex) {
        message.write(TheResourceBundle.getString("Jsp Task Executed Error Msg"));
        ProjectLogger.LOGGER.error(message.toString(), ex);
        return false;
    }

    return true;
}

From source file:com.cloudbees.jenkins.support.impl.RootCAs.java

public static void getRootCAList(StringWriter writer) {
    KeyStore instance = null;/*from ww  w.j ava2 s .  com*/
    try {
        instance = KeyStore.getInstance(KeyStore.getDefaultType());
        Enumeration<String> aliases = instance.aliases();
        while (aliases.hasMoreElements()) {
            String s = aliases.nextElement();
            writer.append("========");
            writer.append("Alias: " + s);
            writer.append(instance.getCertificate(s).getPublicKey().toString());
            writer.append("Trusted certificate: " + instance.isCertificateEntry(s));
        }
    } catch (KeyStoreException e) {
        writer.write(Functions.printThrowable(e));
    }
}

From source file:eu.sisob.uma.restserver.services.crawler.CrawlerTask.java

public static boolean launch(String user, String pass, String task_code, String code_task_folder, String email,
        StringWriter message) {
    if (message == null) {
        return false;
    }/*from   w  ww.  j  av  a2  s  .c  o m*/
    boolean success = false;
    message.getBuffer().setLength(0);
    File code_task_folder_dir = new File(code_task_folder);

    File csv_data_source_file = FileSystemManager.getFileIfExists(code_task_folder_dir,
            input_data_source_filename_prefix_csv, input_data_source_filename_ext_csv);

    boolean validate = csv_data_source_file != null;

    if (!validate) {
        success = false;
        message.write("You have not uploaded 'data-researchers-urls.csv' file"); //FIXME
    }

    org.dom4j.Document document = null;

    String middle_data_folder = code_task_folder + File.separator + AuthorizationManager.middle_data_dirname;
    File middle_data_dir = null;
    try {
        middle_data_dir = FileSystemManager.createFileAndIfExistsDelete(middle_data_folder);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.toString(), ex);
        message.append("The file couldn't be created " + middle_data_dir.getName() + "\r\n");
        return false;
    }

    String results_data_folder = code_task_folder + File.separator + AuthorizationManager.results_dirname;
    File results_data_dir = null;
    try {
        results_data_dir = FileSystemManager.createFileAndIfExistsDelete(results_data_folder);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.toString(), ex);
        message.append("The file couldn't be created " + results_data_dir.getName() + "\r\n");
        return false;
    }

    try {
        File middle_data_source_file = new File(middle_data_dir, middle_data_source_filename_xml);
        validate = FileFormatConversor.createResearchersXMLFileFromCSV(csv_data_source_file,
                middle_data_source_file);
    } catch (Exception ex) {
        ProjectLogger.LOGGER.error(ex.getMessage(), ex);
        validate = false;
    }

    if (!validate) {
        message.append("The format of '" + csv_data_source_file.getName()
                + "' does not seems be correct. Please check the headers of the csv file (read in the instructions which are optionals) and be sure that the field separators are ';'. Please read the intructions of the task."
                + "\r\n");
        return false;
    }

    try {
        File xmlFile = new File(middle_data_folder, middle_data_source_filename_xml);
        org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
        document = reader.read(xmlFile);
    } catch (Exception ex) {
        message.write("The format of '" + csv_data_source_file.getName() + "' does not seems be correct"); //FIXME
        ProjectLogger.LOGGER.error(message.toString(), ex);
        return false;
    }

    String out_filename = csv_data_source_file.getName().replace(input_data_source_filename_prefix_csv,
            output_data_source_filename_csv);
    File csv_data_output_file = new File(results_data_dir, out_filename);
    ResearchersCrawlerTaskInRest task = new ResearchersCrawlerTaskInRest(document,
            new File(ResearchersCrawlerService.CRAWLER_DATA_PATH), middle_data_dir, results_data_dir,
            csv_data_output_file, user, pass, task_code, code_task_folder, email);
    try {

        ResearchersCrawlerService.getInstance().addExecution(new CallbackableTaskExecution(task));
        success = true;
        message.write(TheResourceBundle.getString("Jsp Task Executed Msg"));

    } catch (InterruptedException ex) {

        message.write(TheResourceBundle.getString("Jsp Task Executed Error Msg"));
        ProjectLogger.LOGGER.error(message.toString(), ex);
        return false;
    }

    return true;
}

From source file:org.apache.bval.jsr.util.PathNavigation.java

private static String parseQuotedString(CharSequence path, PathPosition pos) throws Exception {
    int len = path.length();
    int start = pos.getIndex();
    if (start < len) {
        char quote = path.charAt(start);
        pos.next();/*from w  w  w  .  j a  v a2 s .co  m*/
        StringWriter w = new StringWriter();
        while (pos.getIndex() < len) {
            int here = pos.getIndex();
            // look for matching quote
            if (path.charAt(here) == quote) {
                pos.next();
                return w.toString();
            }
            int codePoints = StringEscapeUtils.UNESCAPE_JAVA.translate(path, here, w);
            if (codePoints == 0) {
                w.write(Character.toChars(Character.codePointAt(path, here)));
                pos.next();
            } else {
                for (int i = 0; i < codePoints; i++) {
                    pos.plus(Character.charCount(Character.codePointAt(path, pos.getIndex())));
                }
            }
        }
        // if reached, reset due to no ending quote found
        pos.setIndex(start);
    }
    return null;
}

From source file:com.moviejukebox.themoviedb.tools.WebBrowser.java

public static String request(URL url) throws MovieDbException {
    StringWriter content = null;

    try {/*  w  w w . j a v  a2 s  .c  o  m*/
        content = new StringWriter();

        BufferedReader in = null;
        URLConnection cnx = null;
        try {
            cnx = openProxiedConnection(url);

            sendHeader(cnx);
            readHeader(cnx);

            in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx)));
            String line;
            while ((line = in.readLine()) != null) {
                content.write(line);
            }
        } finally {
            if (in != null) {
                in.close();
            }

            if (cnx instanceof HttpURLConnection) {
                ((HttpURLConnection) cnx).disconnect();
            }
        }
        return content.toString();
    } catch (IOException ex) {
        throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, null, ex);
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException ex) {
                LOGGER.debug("Failed to close connection: " + ex.getMessage());
            }
        }
    }
}

From source file:com.agc.tmdb.Util.URLFetcher.java

/**
 * Can be used to Fetch the URL, where URL is Java.net.URL.
 * @param url//from w  ww. j  av a 2 s.c  om
 * @return
 * @throws TMDbException
 */
public static String fetch(URL url) throws TMDbException {
    System.out.println("URL: " + url);
    StringWriter content = null;

    try {
        content = new StringWriter();

        BufferedReader in = null;
        URLConnection connectionObject = null;
        try {
            connectionObject = openConnection(url);
            setBrowserProperties(connectionObject);

            in = new BufferedReader(
                    new InputStreamReader(connectionObject.getInputStream(), getCharset(connectionObject)));
            String line;
            while ((line = in.readLine()) != null) {
                content.write(line);
            }
        } finally {
            if (in != null) {
                in.close();
            }

            if (connectionObject instanceof HttpURLConnection) {
                ((HttpURLConnection) connectionObject).disconnect();
            }
        }
        return content.toString();
    } catch (IOException ex) {
        throw new TMDbException(TMDbExceptionTypes.EXCEPTION_CONNECTION_ERROR, null, ex);
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException ex) {
                throw new TMDbException(TMDbExceptionTypes.EXCEPTION_CONNECTION_ERROR,
                        "Failed to Close the connection.", ex);
            }
        }
    }
}