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:eu.sisob.uma.restserver.AuthorizationManager.java

/**
 * //from   w  w  w  .ja  v a 2  s  .  c  om
 * @param user
 * @param pass
 * @param message 
 * @return
 */
public static boolean validateAccess(String user, String pass, StringWriter message) {
    boolean valid = true;

    //getCrawkerTaskStatus(code)
    if (message != null)
        message.getBuffer().setLength(0);

    if (!SystemManager.getInstance().IsRunning()) {
        message.write("The back system is off. Please contact with the administrator."); //FIXME
        valid = false;
        return valid;
    }

    if (user != null && pass != null) {
        if (DBAuthorizeUserIn(user, pass)) {
            String code_task_folder = TASKS_USERS_PATH + File.separator + user;

            File f = new File(code_task_folder);
            if (!f.exists())
                f.mkdir();

            valid = true;
            if (message != null)
                message.write(TheResourceBundle.getString("Jsp Auth Msg")); //FIXME               
        } else {
            valid = false;
            if (message != null)
                message.write(TheResourceBundle.getString("Jsp Unauth Msg")); //FIXME                
        }
    } else {
        valid = false;
        if (message != null)
            message.write(TheResourceBundle.getString("Jsp Params Invalid Msg")); //FIXME
    }

    return valid;
}

From source file:eu.sisob.uma.restserver.AuthorizationManager.java

/**
 *
 * @param user//from   w  w w . ja  v  a2  s  .  c  o  m
 * @param pass
 * @param out_attributes
 * @param message
 * @return
 */
public static boolean validateAccess(String user, String pass, UserAttributes out_attributes,
        StringWriter message) {
    boolean valid = true;

    //getCrawkerTaskStatus(code)
    if (message != null)
        message.getBuffer().setLength(0);

    if (!SystemManager.getInstance().IsRunning()) {
        message.write("The back system is off. Please contact with the administrator."); //FIXME
        valid = false;
        return valid;
    }

    if (user != null && pass != null) {
        if (DBAuthorizeUserIn(user, pass, out_attributes)) {
            String code_task_folder = TASKS_USERS_PATH + File.separator + user;

            File f = new File(code_task_folder);
            if (!f.exists())
                f.mkdir();

            valid = true;
            if (message != null)
                message.write(TheResourceBundle.getString("Jsp Auth Msg")); //FIXME               
        } else {
            valid = false;
            if (message != null)
                message.write(TheResourceBundle.getString("Jsp Unauth Msg")); //FIXME                
        }
    } else {
        valid = false;
        if (message != null)
            message.write(TheResourceBundle.getString("Jsp Params Invalid Msg")); //FIXME
    }

    return valid;
}

From source file:com.smartnsoft.droid4me.ws.WebServiceCaller.java

/**
 * Turns the provided {@link InputStream} into a {@link String}, using the provided encoding.
 *
 * @param inputStream the input stream to convert ; not that it will have been {@link InputStream#close() closed}
 * @param encoding    the encoding to use
 * @return the string resulting from the provided input stream
 * @throws IOException if an error happened during the conversion
 * @see #getString(InputStream)/*  ww w  . ja  v  a 2s  .  co m*/
 * @see #getJson(InputStream, String)
 */
public static String getString(InputStream inputStream, String encoding) throws IOException {
    final StringWriter writer = new StringWriter();
    final InputStreamReader streamReader = new InputStreamReader(inputStream, encoding);
    // The 8192 parameter is there to please Android at runtime and discard the
    // "INFO/global(16464): INFO: Default buffer size used in BufferedReader constructor. It would be better to be explicit if a 8k-char buffer is required."
    // log
    final BufferedReader buffer = new BufferedReader(streamReader, 8192);
    String line = "";
    while (null != (line = buffer.readLine())) {
        writer.write(line);
    }
    return writer.toString();
}

From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java

/**
 * Get a JCE policy's details.//from  www  . j a va2 s  . co  m
 *
 * @param jcePolicy
 *            JCE policy
 * @return Policy details
 * @throws CryptoException
 *             If there was a problem getting the policy details
 */
public static String getPolicyDetails(JcePolicy jcePolicy) throws CryptoException {
    try {
        StringWriter sw = new StringWriter();

        File file = getJarFile(jcePolicy);

        // if there is no policy file at all, return empty string
        if (!file.exists()) {
            return "";
        }

        JarFile jar = new JarFile(file);

        Enumeration<JarEntry> jarEntries = jar.entries();

        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();

            String entryName = jarEntry.getName();

            if (!jarEntry.isDirectory() && entryName.endsWith(".policy")) {
                sw.write(entryName + ":\n\n");

                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(jar.getInputStream(jarEntry));
                    CopyUtil.copy(isr, sw);
                } finally {
                    IOUtils.closeQuietly(isr);
                }

                sw.write('\n');
            }
        }

        return sw.toString();
    } catch (IOException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoGetPolicyDetails.exception.message"), jcePolicy), ex);
    }
}

From source file:eu.sisob.uma.restserver.services.gate.GateTask.java

public static boolean launch(String user, String pass, String task_code, String code_task_folder, String email,
        StringWriter message, boolean verbose, boolean split_by_keyword) {
    if (message == null) {
        return false;
    }/*from   ww w .  ja v  a2s . c o  m*/
    boolean success = false;
    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) {
        success = false;
        message.write("You have not uploaded any file like this '" + input_data_source_filename_prefix_csv + "*"
                + input_data_source_filename_ext_csv + "' file");
    } else {
        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");
        }

        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");
        }

        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)) {
                success = false;
                message.write(input_data_documents_in_zip + " cannot bet unziped"); //FIXME
                return success;
            } else {

            }
        }

        RepositoryPreprocessDataMiddleData preprocessedRep = null;
        try {
            File verbose_dir = null;

            if (verbose) {
                verbose_dir = new File(code_task_folder_dir, AuthorizationManager.verbose_dirname);
                if (!verbose_dir.exists())
                    verbose_dir.mkdir();
            }

            HashMap<String, String[]> blocks_and_keywords = null;
            if (split_by_keyword) {
                blocks_and_keywords = GateDataExtractorService.getInstance().getBlocksAndKeywords();
            }

            preprocessedRep = GateDataExtractorSingle.createPreprocessRepositoryFromCSVFile(
                    csv_data_source_file, ';', documents_dir, verbose, verbose_dir, split_by_keyword,
                    blocks_and_keywords, middle_data_dir);

        } catch (Exception ex) {
            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\nAlso check that you have uploaded all the documents referenced in the csv file (if you have upload all the documents compressed in "
                    + input_data_documents_in_zip
                    + " file, please, check that it has all the files referenced in the csv).<br>Message: "
                    + ex.getMessage()); //FIXME
            ProjectLogger.LOGGER.error(message.toString(), ex);
        }

        if (preprocessedRep != null) {
            H2DBCredentials cred_resolver = GateDataExtractorService.getH2DBCredentials_Resolver();
            H2DBCredentials cred_trad = GateDataExtractorService.getH2DBCredentials_Trad_Tables_Academic();
            GateDataExtractorTaskInRest task = new GateDataExtractorTaskInRest(preprocessedRep, true, cred_trad,
                    true, cred_resolver, user, pass, task_code, code_task_folder, email);

            try {
                GateDataExtractorService.getInstance()
                        .addExecution((new CallbackableTaskExecutionWithResource(task)));
                success = true;
                message.write(TheResourceBundle.getString("Jsp Task Executed Msg"));
            } catch (Exception ex) {
                success = false;
                message.write(TheResourceBundle.getString("Jsp Task Executed Error Msg"));
                ProjectLogger.LOGGER.error(message.toString(), ex);
                validate = false;
            }
        }
    }

    return success;
}

From source file:org.newcashel.meta.model.NCClass.java

public static String getPrimaryKeyValue(String[] keys, Inst inst) throws Exception {
    try {/*from   w  w w.  jav a  2  s . c  o m*/
        StringWriter sw = new StringWriter();
        for (int i = 0; i < keys.length; i++) {
            Object value = PropertyUtils.getProperty(inst, keys[i]);
            if (value == null) {
                return null; // primary key part may not be available, ES will assign id
            }
            sw.write(value.toString());
            if ((i + 1) < keys.length) {
                sw.write("_");
            }
        }
        sw.flush();
        return sw.toString();

    } catch (Exception e) {
        String msg = "primary key build failed on this class: " + inst.getType();
        logger.error(msg);
        throw new Exception(msg);
    }
}

From source file:org.kse.crypto.jcepolicy.JcePolicyUtil.java

/**
 * Get a JCE policy's details.// w ww .j a v  a2  s.  c om
 *
 * @param jcePolicy
 *            JCE policy
 * @return Policy details
 * @throws CryptoException
 *             If there was a problem getting the policy details
 */
public static String getPolicyDetails(JcePolicy jcePolicy) throws CryptoException {
    JarFile jarFile = null;
    try {
        StringWriter sw = new StringWriter();

        File file = getJarFile(jcePolicy);

        // if there is no policy file at all, return empty string
        if (!file.exists()) {
            return "";
        }

        jarFile = new JarFile(file);

        Enumeration<JarEntry> jarEntries = jarFile.entries();

        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();

            String entryName = jarEntry.getName();

            if (!jarEntry.isDirectory() && entryName.endsWith(".policy")) {
                sw.write(entryName + ":\n\n");

                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(jarFile.getInputStream(jarEntry));
                    CopyUtil.copy(isr, sw);
                } finally {
                    IOUtils.closeQuietly(isr);
                }

                sw.write('\n');
            }
        }

        return sw.toString();
    } catch (IOException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoGetPolicyDetails.exception.message"), jcePolicy), ex);
    } finally {
        IOUtils.closeQuietly(jarFile);
    }
}

From source file:org.commonjava.indy.bind.jaxrs.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).append("\n");
    if (message != null) {
        sw.append("Message: ").append(message).append("\n");
    }// www  .  java2  s.  c  om

    if (error != null) {
        sw.append(error.getMessage());

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

        sw.write('\n');
    }

    return sw.toString();
}

From source file:com.thinkbiganalytics.discovery.util.ParserHelper.java

/**
 * Extracts the given number of rows from the file and returns a new reader for the sample.
 * This method protects memory in the case where a large file can be submitted with no delimiters.
 *//*from  www .j av  a 2 s .  co m*/
public static String extractSampleLines(InputStream is, Charset charset, int rows) throws IOException {

    StringWriter sw = new StringWriter();
    Validate.notNull(is, "empty input stream");
    Validate.notNull(charset, "charset cannot be null");
    Validate.exclusiveBetween(1, MAX_ROWS, rows, "invalid number of sample rows");

    // Sample the file in case there are no newlines
    StringWriter swBlock = new StringWriter();
    IOUtils.copyLarge(new InputStreamReader(is, charset), swBlock, -1, MAX_CHARS);
    try (BufferedReader br = new BufferedReader(new StringReader(swBlock.toString()))) {
        IOUtils.closeQuietly(swBlock);
        String line = br.readLine();
        int linesRead = 0;
        for (int i = 1; i <= rows && line != null; i++) {
            sw.write(line);
            sw.write("\n");
            linesRead++;
            line = br.readLine();
        }
        if (linesRead <= 1 && sw.toString().length() >= MAX_CHARS) {
            throw new IOException("Failed to detect newlines for sample file.");
        }
    }

    return sw.toString();
}

From source file:org.jahia.bin.errors.ErrorFileDumper.java

protected static String recursiveStackTraceToString(Throwable t, int curDepth) {
    if (t == null) {
        return "";
    }/*from   ww w  .j a  v a2 s  .  com*/
    StringWriter msgBodyWriter = new StringWriter();
    PrintWriter strOut = new PrintWriter(msgBodyWriter);
    Throwable innerThrowable = t.getCause();
    if (innerThrowable != null) {
        String innerExceptionTrace = recursiveStackTraceToString(innerThrowable, curDepth - 1);
        msgBodyWriter.write(innerExceptionTrace);
    }
    if (curDepth == 0) {
        strOut.println("Cause level : " + curDepth + " (level 0 is the most precise exception)");

    } else {
        strOut.println("Cause level : " + curDepth);
    }
    t.printStackTrace(strOut);
    return msgBodyWriter.toString();
}