Example usage for org.apache.commons.io IOUtils write

List of usage examples for org.apache.commons.io IOUtils write

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils write.

Prototype

public static void write(StringBuffer data, OutputStream output) throws IOException 

Source Link

Document

Writes chars from a StringBuffer to bytes on an OutputStream using the default character encoding of the platform.

Usage

From source file:net.dontdrinkandroot.lastfm.api.CheckImplementationStatus.java

public static void main(final String[] args) throws DocumentException, IOException {

    CheckImplementationStatus.xmlReader = new Parser();
    CheckImplementationStatus.saxReader = new SAXReader(CheckImplementationStatus.xmlReader);

    final String packagePrefix = "net.dontdrinkandroot.lastfm.api.model.";

    final Map<String, Map<String, URL>> packages = CheckImplementationStatus.parseOverview();

    final StringBuffer html = new StringBuffer();
    html.append("<html>\n");
    html.append("<head>\n");
    html.append("<title>Implementation Status</title>\n");
    html.append("</head>\n");
    html.append("<body>\n");
    html.append("<h1>Implementation Status</h1>\n");

    final StringBuffer wiki = new StringBuffer();

    int numImplemented = 0;
    int numTested = 0;
    int numMethods = 0;

    final List<String> packageList = new ArrayList<String>(packages.keySet());
    Collections.sort(packageList);

    for (final String pkg : packageList) {

        System.out.println("Parsing " + pkg);
        html.append("<h2>" + pkg + "</h2>\n");
        wiki.append("\n===== " + pkg + " =====\n\n");

        Class<?> modelClass = null;
        final String className = packagePrefix + pkg;
        try {//from w  w  w.  j  a  va2  s .  c o m
            modelClass = Class.forName(className);
            System.out.println("\tClass " + modelClass.getName() + " exists");
        } catch (final ClassNotFoundException e) {
            // e.printStackTrace();
            System.out.println("\t" + className + ": DOES NOT exist");
        }

        Class<?> testClass = null;
        final String testClassName = packagePrefix + pkg + "Test";
        try {
            testClass = Class.forName(testClassName);
            System.out.println("\tTestClass " + testClass.getName() + " exists");
        } catch (final ClassNotFoundException e) {
            // e.printStackTrace();
            System.out.println("\t" + testClassName + ": TestClass for DOES NOT exist");
        }

        final List<String> methods = new ArrayList<String>(packages.get(pkg).keySet());
        Collections.sort(methods);

        final Method[] classMethods = modelClass.getMethods();
        final Method[] testMethods = testClass.getMethods();

        html.append("<table>\n");
        html.append("<tr><th>Method</th><th>Implemented</th><th>Tested</th></tr>\n");
        wiki.append("^ Method  ^ Implemented  ^ Tested  ^\n");

        numMethods += methods.size();

        for (final String method : methods) {

            System.out.println("\t\t parsing " + method);

            html.append("<tr>\n");
            html.append("<td>" + method + "</td>\n");
            wiki.append("| " + method + "  ");

            boolean classMethodFound = false;
            for (final Method classMethod : classMethods) {
                if (classMethod.getName().equals(method)) {
                    classMethodFound = true;
                    break;
                }
            }

            if (classMethodFound) {
                System.out.println("\t\t\tMethod " + method + " found");
                html.append("<td style=\"background-color: green\">true</td>\n");
                wiki.append("| yes  ");
                numImplemented++;
            } else {
                System.out.println("\t\t\t" + method + " NOT found");
                html.append("<td style=\"background-color: red\">false</td>\n");
                wiki.append("| **no**  ");
            }

            boolean testMethodFound = false;
            final String testMethodName = "test" + StringUtils.capitalize(method);
            for (final Method testMethod : testMethods) {
                if (testMethod.getName().equals(testMethodName)) {
                    testMethodFound = true;
                    break;
                }
            }

            if (testMethodFound) {
                System.out.println("\t\t\tTestMethod " + method + " found");
                html.append("<td style=\"background-color: green\">true</td>\n");
                wiki.append("| yes  |\n");
                numTested++;
            } else {
                System.out.println("\t\t\t" + testMethodName + " NOT found");
                html.append("<td style=\"background-color: red\">false</td>\n");
                wiki.append("| **no**  |\n");
            }

            html.append("</tr>\n");

        }

        html.append("</table>\n");

        // for (String methodName : methods) {
        // URL url = pkg.getValue().get(methodName);
        // System.out.println("PARSING: " + pkg.getKey() + "." + methodName + ": " + url);
        // String html = loadIntoString(url);
        // String description = null;
        // Matcher descMatcher = descriptionPattern.matcher(html);
        // if (descMatcher.find()) {
        // description = descMatcher.group(1).trim();
        // }
        // boolean post = false;
        // Matcher postMatcher = postPattern.matcher(html);
        // if (postMatcher.find()) {
        // post = true;
        // }
        // Matcher paramsMatcher = paramsPattern.matcher(html);
        // List<String[]> params = new ArrayList<String[]>();
        // boolean authenticated = false;
        // if (paramsMatcher.find()) {
        // String paramsString = paramsMatcher.group(1);
        // Matcher paramMatcher = paramPattern.matcher(paramsString);
        // while (paramMatcher.find()) {
        // String[] param = new String[3];
        // param[0] = paramMatcher.group(1);
        // param[1] = paramMatcher.group(3);
        // param[2] = paramMatcher.group(5);
        // // System.out.println(paramMatcher.group(1) + "|" + paramMatcher.group(3) + "|" +
        // paramMatcher.group(5));
        // if (param[0].equals("")) {
        // /* DO NOTHING */
        // } else if (param[0].equals("api_key")) {
        // /* DO NOTHING */
        // } else if (param[0].equals("api_sig")) {
        // authenticated = true;
        // } else {
        // params.add(param);
        // }
        // }
        // }
        // }
        // count++;
        //
    }

    html.append("<hr />");
    html.append("<p>" + numImplemented + "/" + numMethods + " implemented (" + numImplemented * 100 / numMethods
            + "%)</p>");
    html.append("<p>" + numTested + "/" + numMethods + " tested (" + numTested * 100 / numMethods + "%)</p>");

    html.append("</body>\n");
    html.append("</html>\n");

    FileOutputStream out = new FileOutputStream(new File(FileUtils.getTempDirectory(), "apistatus.html"));
    IOUtils.write(html, out);
    IOUtils.closeQuietly(out);

    out = new FileOutputStream(new File(FileUtils.getTempDirectory(), "apistatus.wiki.txt"));
    IOUtils.write(wiki, out);
    IOUtils.closeQuietly(out);
}

From source file:gov.nih.nci.cabig.caaers.rules.business.service.CaaersRulesEngineServiceIntegrationTest.java

public void testImportRules() throws Exception {

    InputStream in = RuleUtil.getResouceAsStream("sae_reporting_rules_sponsor_org_ctep.xml");
    String xml = RuleUtil.getFileContext(in);
    System.out.println(xml);//from w w w . j  a v  a  2  s. c o  m
    File f = File.createTempFile("r_" + System.currentTimeMillis(), "sae.xml");
    System.out.println(f.getAbsolutePath());
    FileWriter fw = new FileWriter(f);
    IOUtils.write(xml, fw);
    IOUtils.closeQuietly(fw);
    assertTrue(f.exists());

    assertTrue(findRuleSets().isEmpty());

    service.importRules(f.getAbsolutePath());
    f.delete();
    List<RuleSet> ruleSets = findRuleSets();
    assertFalse(ruleSets.isEmpty());

    RuleSet rs = ruleSets.get(0);

    assertTrue(rs.isEnabled());

    String xml2 = service.exportRules(rs.getRuleBindURI());

    assertNotNull(xml2);

    f = File.createTempFile("r_" + System.currentTimeMillis(), "sae.xml");
    fw = new FileWriter(f);
    IOUtils.write(xml, fw);
    IOUtils.closeQuietly(fw);
    assertTrue(f.exists());

    List<String> outList = service.importRules(f.getAbsolutePath());
    f.delete();
    assertEquals(rs.getRuleBindURI(), outList.get(0));

    String xml3 = service.exportRules(rs.getRuleBindURI());
    assertNotNull(xml3);

}

From source file:com.formkiq.web.config.TestDataController.java

/**
 * Provider Sample generic XML data with text/xml content type.
 * @param request {@link HttpServletRequest}
 * @param response {@link HttpServletResponse}
 * @throws IOException IOException//from w  w  w.ja  va 2s.c  o  m
 */
@RequestMapping(value = "/testdata/sample-generic1.xml", method = RequestMethod.GET)
public void sampleGeneric1(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    byte[] data = Resources.getResourceAsBytes("/testdata/sample-generic.xml");

    response.setContentType("text/xml");
    response.setContentLengthLong(data.length);
    IOUtils.write(data, response.getOutputStream());
}

From source file:com.labimo.portlet.DownloadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String hardwareUuid = request.getParameter("hardwareUuid");
    String licenseUuid = request.getParameter("licenseUuid");
    String fileName = "license.txt";
    License license = null;/*from   w  w  w . j  ava2s .c  o  m*/
    try {
        license = LicenseLocalServiceUtil.getLicense(licenseUuid);
        if (license != null && license.getValid()) {
            response.setHeader("Content-Type", "application/octet-stream");
            ServletOutputStream servletOutputStream = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            IOUtils.write(LicenseUtils.getChargesLicenseContent(hardwareUuid, license.getIssueDate(),
                    license.getValidDate()), servletOutputStream);

            servletOutputStream.flush();
            servletOutputStream.close();

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
     * String activationId = "1a508567-61f9-3e5a-8923-b27ca6d00028"; String
     * fileName = "license.txt"; List<Activation> activationList =
     * LicenseUtils
     * .getActivationListByLicenseUuid("4091a61b-4b3d-46b9-890d-2a3e63f09d3c"
     * ); if (activationList != null && activationList.size() > 0) { //
     * License license = // LicenseLocalServiceUtil.getLicense(licenseUuid);
     * License license = null; try { license = LicenseLocalServiceUtil
     * .getLicense("4091a61b-4b3d-46b9-890d-2a3e63f09d3c"); } catch
     * (PortalException e) { // TODO Auto-generated catch block
     * e.printStackTrace(); } catch (SystemException e) { // TODO
     * Auto-generated catch block e.printStackTrace(); }
     * System.out.println("getIssueDate = " + license.getIssueDate());
     * System.out.println("getValidDate = " + license.getValidDate());
     * System.out.println("getValid = " + license.getValid()); if
     * (license.getValid()) { response.setHeader("Content-Type",
     * "application/octet-stream"); ServletOutputStream servletOutputStream
     * = response .getOutputStream();
     * response.setHeader("Content-Disposition", "attachment; filename=\"" +
     * fileName + "\"");
     * 
     * try { IOUtils.write(LicenseUtils.getChargesLicenseContent(
     * activationId, license.getIssueDate(), license.getValidDate()),
     * servletOutputStream); } catch (Exception e) { // TODO Auto-generated
     * catch block e.printStackTrace(); } servletOutputStream.flush();
     * servletOutputStream.close();
     * 
     * } }
     */

}

From source file:de.knurt.fam.template.controller.json.JSONController2.java

/**
 * print out json with the key and values got from
 * {@link JSONController2#getKeyAndValues(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}
 * /* w  w w  . j  a  va 2  s . c o  m*/
 * @param rq
 *            request
 * @param rs
 *            response
 * @return null
 */
public ModelAndView handleRequest(HttpServletRequest rq, HttpServletResponse rs) {
    PrintWriter pw = null;
    try {
        rs.setHeader("Content-type", "application/json");
        pw = rs.getWriter();
        IOUtils.write(this.getJSONObject().toString(), pw);
    } catch (IOException ex) {
        this.onIOException(ex);
    } finally {
        IOUtils.closeQuietly(pw);
    }
    return null;
}

From source file:com.develcom.cliente.Cliente.java

public void buscarArchivo() throws FileNotFoundException, IOException {

    CodDecodArchivos cda = new CodDecodArchivos();
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    //        Bufer bufer = new Bufer();
    byte[] buffer = null;
    ResponseEntity<byte[]> response;

    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    headers.setAccept(Arrays.asList(MediaType.ALL));
    HttpEntity<String> entity = new HttpEntity<>(headers);

    response = restTemplate.exchange(// ww  w  .ja  v a 2  s.c  om
            "http://localhost:8080/ServicioDW4J/expediente/buscarFisicoDocumento/21593", HttpMethod.GET, entity,
            byte[].class);

    if (response.getStatusCode().equals(HttpStatus.OK)) {
        buffer = response.getBody();
        FileOutputStream output = new FileOutputStream(new File("c:/documentos/archivo.cod"));
        IOUtils.write(response.getBody(), output);
        cda.decodificar("c:/documentos/archivo.cod", "c:/documentos/archivo.pdf");
    }

}

From source file:com.develcom.reafolder.ClienteBajaArchivo.java

public void buscarArchivo() throws FileNotFoundException, IOException {

    CodDecodArchivos cda = new CodDecodArchivos();
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    Bufer bufer = new Bufer();
    byte[] buffer = null;
    ResponseEntity<byte[]> response;

    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    headers.setAccept(Arrays.asList(MediaType.ALL));
    HttpEntity<String> entity = new HttpEntity<>(headers);

    response = restTemplate.exchange(/*  www . ja  v a  2 s  .c o  m*/
            "http://localhost:8080/ServicioDW4J/expediente/buscarFisicoDocumento/21593", HttpMethod.GET, entity,
            byte[].class);

    if (response.getStatusCode().equals(HttpStatus.OK)) {
        buffer = response.getBody();
        FileOutputStream output = new FileOutputStream(new File("c:/documentos/archivo.cod"));
        IOUtils.write(response.getBody(), output);
        cda.decodificar("c:/documentos/archivo.cod", "c:/documentos/archivo.pdf");
    }

}

From source file:ch.aonyx.broker.ib.api.ServerCurrentVersionSynchronousRequest.java

int getResponse() {
    try {//from w w w . j a  va2 s  .co  m
        IOUtils.write(builder.toBytes(), outputStream);
    } catch (final IOException e) {
        LOGGER.error("", e);
    }
    return InputStreamUtils.readInt(inputStream);
}

From source file:ezbake.deployer.utilities.Utilities.java

public static void appendFilesInTarArchive(OutputStream output, Iterable<ArtifactDataEntry> filesToAdd)
        throws DeploymentException {
    ArchiveStreamFactory asf = new ArchiveStreamFactory();
    try (GZIPOutputStream gzs = new GZIPOutputStream(output)) {
        try (ArchiveOutputStream aos = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, gzs)) {
            for (ArtifactDataEntry entry : filesToAdd) {
                aos.putArchiveEntry(entry.getEntry());
                IOUtils.write(entry.getData(), aos);
                aos.closeArchiveEntry();
            }/*from w ww. j  a  va2s.c  o  m*/
        }
    } catch (ArchiveException e) {
        log.error(e.getMessage(), e);
        throw new DeploymentException(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new DeploymentException(e.getMessage());
    }
}

From source file:de.knurt.fam.template.controller.json.JSONController.java

/**
 * print out json with the key and values got from
 * {@link JSONController#getKeyAndValues(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}
 * /*w  w  w. j  av  a2s  .c o  m*/
 * @param rq
 *            request
 * @param rs
 *            response
 * @return null
 */
@Override
public ModelAndView handleRequest(HttpServletRequest rq, HttpServletResponse rs) {
    PrintWriter pw = null;
    try {
        rs.setHeader("Content-type", "application/json");
        pw = rs.getWriter();
        IOUtils.write(this.getJSONObject(rq, rs).toString(), pw);
    } catch (IOException ex) {
        this.onException(ex);
    } finally {
        IOUtils.closeQuietly(pw);
    }
    return null;
}