Example usage for java.io OutputStream toString

List of usage examples for java.io OutputStream toString

Introduction

In this page you can find the example usage for java.io OutputStream toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.opencastproject.index.service.util.RestUtils.java

public static String getJsonString(JValue json) throws WebApplicationException, IOException {
    OutputStream output = new OutputStream() {
        private StringBuilder string = new StringBuilder();

        @Override/*from w  ww. ja v a  2 s.  co m*/
        public void write(int b) throws IOException {
            this.string.append((char) b);
        }

        @Override
        public String toString() {
            return this.string.toString();
        }
    };

    stream(serializer.toJsonFx(json)).write(output);

    return output.toString();
}

From source file:org.nuxeo.theme.html.JSUtils.java

public static String compressSource(final String source) throws ThemeException {
    String compressedSource = source;
    InputStream in = null;//from   www  . j av a 2s .  c  o  m
    OutputStream out = null;

    try {
        in = new ByteArrayInputStream(source.getBytes());
        out = new ByteArrayOutputStream();

        JSMin compressor = new JSMin(in, out);
        try {
            compressor.jsmin();
        } catch (UnterminatedRegExpLiteralException e) {
            throw new ThemeException("Could not compress javascript", e);
        } catch (UnterminatedCommentException e) {
            throw new ThemeException("Could not compress javascript", e);
        } catch (UnterminatedStringLiteralException e) {
            throw new ThemeException("Could not compress javascript", e);
        }
        compressedSource = out.toString();
    } catch (IOException e) {
        throw new ThemeException("Could not compress javascript", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                log.error(e, e);
            } finally {
                out = null;
            }
        }
    }
    if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            log.error(e, e);
        } finally {
            in = null;
        }
    }

    return compressedSource;
}

From source file:com.valco.utility.FacturasUtility.java

public static String getFacturaConSello(Facturas factura) throws Exception {

    Clientes cliente = factura.getNotasDeVenta().getClientes();
    String xml = null;/*from  w ww. j  a  v  a  2s .c  om*/
    try {
        xml = formaXmlFactura(factura.getSerie(), Integer.toString(factura.getFolio()), factura.getFecha(),
                factura.getFormaPago(), factura.getTotal().setScale(2, RoundingMode.HALF_EVEN).toString(),
                factura.getSubtotal().setScale(2, RoundingMode.HALF_EVEN).toString(), factura.getMoneda(),
                factura.getMetodoPago(), factura.getLugar(), cliente.getCuentaBancaria().toString(),
                factura.getNoSeieCertEmisor(), "ingreso", "AAA010101AAA",
                "DISTRIBUIDORA DE CARNES VALCO S.A. DE C.V.", "PARRAL", "246", "123", "REVOLUCION", "CHIHUAHUA",
                "referencia", "CHIHUAHUA", "CHIHUAHUA", "MXICO", "31110", "REGIMEN", cliente.getRfc(),
                cliente.getNombreCompleto(), cliente.getCalle(), Integer.toString(cliente.getNumeroExterior()),
                cliente.getNumeroInterior(), cliente.getColonia(), cliente.getCiudad(), cliente.getEstado(),
                cliente.getPais(), Integer.toString(cliente.getCodigoPostal()),
                factura.getConceptosFacturas().iterator(), factura.getImpuestoses());
    } catch (ParseException ex) {
        throw new Exception("Ocurri un error al formar el XML de la factura");
    }
    OutputStream cadenaOriginal = null;
    try {
        cadenaOriginal = getCadenaOriginal("C:/SAT/cadenaoriginal_3_2.xslt",
                new String(xml.getBytes("Windows-1252")));
    } catch (UnsupportedEncodingException ex) {
        throw new Exception("Ocurri un error al obtener la cadena original");
    }
    factura.setCadenaOriginal(cadenaOriginal.toString());
    byte[] bytesKey = null;
    java.security.PrivateKey pk = null;
    try {
        bytesKey = getBytesPrivateKey("C:/SAT/aaa010101aaa__csd_01.key");
        pk = getPrivateKey(bytesKey, "12345678a");
    } catch (GeneralSecurityException ex) {
        throw new Exception(ex);
    }
    byte[] bytesCadenaFirmada = null;
    try {
        bytesCadenaFirmada = getBytesCadenaFirmada(pk, cadenaOriginal);
    } catch (Exception ex) {
        throw new Exception("Ocurri un error al ofirmar la cadena original");
    }
    String selloBase64 = getSelloBase64(bytesCadenaFirmada);
    xml = xml.replace("AQUIVAELSELLO", selloBase64);
    return xml;

}

From source file:tagtime.beeminder.BeeminderAPI.java

private static List<JSONObject> parseResponse(HttpResponse response) {
    OutputStream data;
    try {//from w  ww  . j  a  va 2 s .c  o m
        data = new ByteArrayOutputStream(response.getEntity().getContent().available());
        response.getEntity().writeTo(data);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    Object parseResult;
    try {
        parseResult = JSON_PARSER.parse(data.toString());
    } catch (ParseException e) {
        System.err.println(data.toString());
        e.printStackTrace();
        parseResult = null;
    }

    //close the stream used to read the response
    try {
        data.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //This might be redundant, but leave it even so, in case the HTTP
    //library changes.
    try {
        EntityUtils.consume(response.getEntity());
    } catch (IOException e) {
        e.printStackTrace();
    }

    //JSONParser.parse() can return multiple object types, depending
    //on the JSON itself
    List<JSONObject> parsedArray = null;
    if (parseResult instanceof JSONArray) {
        parsedArray = new ArrayList<JSONObject>();
        for (Object element : (JSONArray) parseResult) {
            if (element instanceof JSONObject) {
                parsedArray.add((JSONObject) element);
            } else {
                //Currently, it's safe to ignore any sub-arrays.
                //(Sorry if this messes things up in the future.)
            }
        }
    } else if (parseResult instanceof JSONObject) {
        parsedArray = new ArrayList<JSONObject>(1);

        parsedArray.add((JSONObject) parseResult);
    } else {
        System.out.println("Unknown result from JSON parser: " + parseResult);
        parsedArray = new ArrayList<JSONObject>();
    }

    return parsedArray;
}

From source file:org.openhie.openempi.openpixpdq.v3.util.Utilities.java

public static String objectMessageToString(Object message) {
    if (message == null) {
        return "";
    }//  w ww  .  j  av a 2  s  . c o  m
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(message.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        OutputStream outputStream = new ByteArrayOutputStream();
        jaxbMarshaller.marshal(message, outputStream);
        return outputStream.toString();
    } catch (JAXBException e) {
        log.warn("Unable to serialize a message into a string: " + e, e);
        throw new RuntimeException(e);
    }

}

From source file:org.sakaiproject.portlet.util.PortletHelper.java

public static void setErrorMessage(PortletRequest request, String errorMsg, Throwable t) {
    if (errorMsg == null)
        errorMsg = "null";
    PortletSession pSession = request.getPortletSession(true);
    pSession.setAttribute("error.message", errorMsg);

    OutputStream oStream = new ByteArrayOutputStream();
    PrintStream pStream = new PrintStream(oStream);

    t.printStackTrace(pStream);//from  ww  w.ja v  a2  s .  c  o  m

    // System.out.println("+++++++++++++++++++++++++");
    // System.out.println(oStream.toString());
    // System.out.println("+++++++++++++++++++++++++");

    // errorMsg = errorMsg .replaceAll("<","&lt;").replaceAll(">","&gt;");

    StringBuffer errorOut = new StringBuffer();
    errorOut.append("<p class=\"portlet-msg-error\">\n");
    errorOut.append(FormattedText.escapeHtmlFormattedText(errorMsg));
    errorOut.append("\n</p>\n<!-- Traceback for this error\n");
    errorOut.append(oStream.toString());
    errorOut.append("\n-->\n");

    pSession.setAttribute("error.output", errorOut.toString());

    Map map = request.getParameterMap();
    pSession.setAttribute("error.map", map);
}

From source file:com.microsoft.azuretools.utils.WebAppUtils.java

public static void deployCustomJdk(WebApp webApp, String jdkDownloadUrl, WebContainer webContainer,
        IProgressIndicator indicator) throws IOException, InterruptedException, WebAppException {
    FTPClient ftp = null;//from   www  . j a v a2 s  . com
    String customJdkFolderName = null;
    try {

        PublishingProfile pp = webApp.getPublishingProfile();
        ftp = getFtpConnection(pp);

        // stop and restart web app
        //            if (indicator != null) indicator.setText("Stopping the service...");
        //            webApp.stop();

        if (indicator != null)
            indicator.setText("Deleting custom jdk artifacts, if any (takes a while)...");
        removeCustomJdkArtifacts(ftp, indicator);

        if (indicator != null)
            indicator.setText("Uploading scripts...");
        uploadJdkDownloadScript(ftp, jdkDownloadUrl);

        //            if (indicator != null) indicator.setText("Starting the service...");
        //            webApp.start();

        final String siteUrl = "https://" + webApp.defaultHostName();

        // send get to activate the script
        sendGet(siteUrl);

        // Polling report.txt...
        if (indicator != null)
            indicator.setText("Checking the JDK gets downloaded and unpacked...");
        //int step = 0;
        while (!doesRemoteFileExist(ftp, ftpRootPath, reportFilename)) {
            if (indicator != null && indicator.isCanceled())
                throw new CancellationException("Canceled by user.");
            //if (step++ > 3) checkFreeSpaceAvailability(ftp);
            Thread.sleep(5000);
            sendGet(siteUrl);
        }

        if (indicator != null)
            indicator.setText("Checking status...");
        OutputStream reportFileStream = new ByteArrayOutputStream();
        ftp.retrieveFile("report.txt", reportFileStream);
        String reportFileString = reportFileStream.toString();
        if (reportFileString.startsWith("FAIL")) {
            String err = reportFileString.substring(reportFileString.indexOf(":" + 1));
            throw new WebAppException(err);
        }

        // get top level jdk folder name (under jdk folder)
        FTPFile[] ftpDirs = ftp.listDirectories(ftpJdkPath);
        if (ftpDirs.length != 1) {
            String err = "Bad JDK archive. Please make sure the JDK archive contains a single JDK folder. For example, 'my-jdk1.7.0_79.zip' archive should contain 'jdk1.7.0_79' folder only";
            throw new WebAppException(err);
        }

        customJdkFolderName = ftpDirs[0].getName();

        uploadWebConfigForCustomJdk(ftp, webApp, customJdkFolderName, webContainer, indicator);
    } catch (IOException | WebAppException | InterruptedException ex) {
        if (doesRemoteFolderExist(ftp, ftpRootPath, jdkFolderName)) {
            indicator.setText("Error happened. Cleaning up...");
            removeFtpDirectory(ftp, ftpJdkPath, indicator);
        }
        throw ex;
    } finally {
        indicator.setText("Removing working data from server...");
        cleanupWorkerData(ftp);
        if (ftp != null && ftp.isConnected()) {
            ftp.disconnect();
        }
    }
}

From source file:org.ebayopensource.turmeric.eclipse.errorlibrary.properties.ui.utils.TurmericErrorLibraryUtils.java

/**
 * Removes the error from props file./*  w  w w.j  a v a 2 s .  co  m*/
 *
 * @param domainFolder the domain folder
 * @param error the error
 * @throws CoreException the core exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void removeErrorFromPropsFile(IFolder domainFolder, ISOAError error)
        throws CoreException, IOException {
    IFile propsFile = getErrorPropsFile(domainFolder);
    if (propsFile != null && propsFile.isAccessible()) {
        InputStream input = null;
        OutputStream output = new ByteArrayOutputStream();
        try {
            input = propsFile.getContents();
            String[] keysToBeDeleted = new String[2];
            keysToBeDeleted[0] = error.getName() + "." + PropertiesSOAConstants.PROPS_KEY_MESSAGE;
            keysToBeDeleted[1] = error.getName() + "." + PropertiesSOAConstants.PROPS_KEY_RESOLUTION;
            PropertiesFileUtil.removePropertyByKey(input, output, keysToBeDeleted);
            String contents = output.toString();
            WorkspaceUtil.writeToFile(contents, propsFile, new NullProgressMonitor());
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
        }
    }
}

From source file:com.aurel.track.exchange.msProject.exchange.MsProjectExchangeBL.java

/**
 * Saves the msProjectExchangeBean/*  www  . j a  v a 2s .c om*/
 *
 * @param msProjectExchangeDataStoreBean
 * @return
 */
public static void saveMSProjectImportFile(MsProjectExchangeDataStoreBean msProjectExchangeDataStoreBean) {
    File file = msProjectExchangeDataStoreBean.getFile();
    String importFileContent = "";
    try {
        ProjectWriter writer = new MSPDIWriter();
        OutputStream out = new ByteArrayOutputStream();
        writer.write(msProjectExchangeDataStoreBean.getProject(), out);
        importFileContent = out.toString();
    } catch (Exception ex) {
        LOGGER.error("Errors while reading XML: " + ex.getMessage(), ex);
    }
    if (importFileContent != null) {
        TMSProjectExchangeBean msProjectExchangeBean = new TMSProjectExchangeBean();
        msProjectExchangeBean.setExchangeDirection(EXCHANGE_DIRECTION.IMPORT);
        msProjectExchangeBean.setEntityID(msProjectExchangeDataStoreBean.getEntityID());
        msProjectExchangeBean.setEntityType(msProjectExchangeDataStoreBean.getEntityType());
        msProjectExchangeBean.setChangedBy(msProjectExchangeDataStoreBean.getPersonBean().getObjectID());
        msProjectExchangeBean.setFileContent(importFileContent);
        msProjectExchangeBean.setFileName(file.getName());
        msProjectExchangeBean.setLastEdit(new Date());
        msProjectExchangeDAO.save(msProjectExchangeBean);
    }
    if (file != null) {
        file.delete();
    }
}

From source file:org.ebayopensource.turmeric.eclipse.errorlibrary.properties.utils.TurmericErrorLibraryUtils.java

/**
 * Adds the domain list props.//from   www .j  av a 2  s.c  o  m
 *
 * @param project the project
 * @param domainName the domain name
 * @param monitor the monitor
 * @throws CoreException the core exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void addDomainListProps(IProject project, String domainName, IProgressMonitor monitor)
        throws CoreException, IOException {
    IFile file = TurmericErrorLibraryUtils.getDomainListPropsFile(project);
    OutputStream output = new ByteArrayOutputStream();
    InputStream input = null;
    if (file.isAccessible()) {
        try {
            input = file.getContents();
            String key = PropertiesSOAConstants.PROPS_LIST_OF_DOMAINS;
            Collection<String> domains = TurmericErrorLibraryUtils.getAllErrorDomains(project);
            if (!domains.contains(domainName)) {
                domains.add(domainName);
            }
            String domainListStr = StringUtils.join(domains, ",");
            input = file.getContents();
            PropertiesFileUtil.updatePropertyByKey(input, output, key, domainListStr);
            String contents = output.toString();
            WorkspaceUtil.writeToFile(contents, file, monitor);
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
        }
    }
}