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:de.micromata.genome.gapp.GoogleDataStoreFileSystem.java

@Override
public void readBinaryFile(String file, OutputStream os) {
    try {// ww  w  .  j a  v  a 2s  .  c  o  m
        Entity ent = datastore.get(key(file));
        Object o = ent.getProperty(BDATA);
        byte[] data = null;
        if (o instanceof ShortBlob) {
            data = ((ShortBlob) o).getBytes();
        } else if (o instanceof Blob) {
            data = ((Blob) o).getBytes();
        } else {
            throw new RuntimeIOException("Read binary data from googlfs. Unknown type: "
                    + o.getClass().toString() + "; file: " + file);
        }
        IOUtils.write(data, os);
    } catch (IOException ex) {
        throw new RuntimeIOException("Cannot read file: " + file + "; " + ex.getMessage(), ex);
    } catch (EntityNotFoundException ex) {
        throw new FsFileExistsException("File not exists: " + file + "; " + ex.getMessage(), ex);
    }
}

From source file:ch.cyberduck.core.b2.B2ObjectListServiceTest.java

@Test
public void testListRevisions() throws Exception {
    final B2Session session = new B2Session(new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("b2.user"),
                    System.getProperties().getProperty("b2.key"))));
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path bucket = new B2DirectoryFeature(session)
            .mkdir(new Path(String.format("test-%s", UUID.randomUUID().toString()),
                    EnumSet.of(Path.Type.directory, Path.Type.volume)), null, new TransferStatus());
    final String name = UUID.randomUUID().toString();
    final Path file1 = new Path(bucket, name, EnumSet.of(Path.Type.file));
    final Path file2 = new Path(bucket, name, EnumSet.of(Path.Type.file));
    {//w  w  w  .  j a v  a  2s. c  o m
        final byte[] content = RandomUtils.nextBytes(1);
        final TransferStatus status = new TransferStatus();
        status.setLength(content.length);
        status.setChecksum(new SHA1ChecksumCompute().compute(new ByteArrayInputStream(content), status));
        final HttpResponseOutputStream<BaseB2Response> out = new B2WriteFeature(session).write(file1, status,
                new DisabledConnectionCallback());
        IOUtils.write(content, out);
        out.close();
        final B2FileResponse resopnse = (B2FileResponse) out.getStatus();
        final AttributedList<Path> list = new B2ObjectListService(session).list(bucket,
                new DisabledListProgressListener());
        file1.attributes().setVersionId(resopnse.getFileId());
        assertTrue(list.contains(file1));
        assertEquals("1", list.find(new SimplePathPredicate(file1)).attributes().getRevision());
        assertEquals(content.length, list.find(new SimplePathPredicate(file1)).attributes().getSize());
        assertEquals(bucket, list.find(new SimplePathPredicate(file1)).getParent());
    }
    // Replace
    {
        final byte[] content = RandomUtils.nextBytes(1);
        final TransferStatus status = new TransferStatus();
        status.setLength(content.length);
        status.setChecksum(new SHA1ChecksumCompute().compute(new ByteArrayInputStream(content), status));
        final HttpResponseOutputStream<BaseB2Response> out = new B2WriteFeature(session).write(file2, status,
                new DisabledConnectionCallback());
        IOUtils.write(content, out);
        out.close();
        final B2FileResponse resopnse = (B2FileResponse) out.getStatus();
        final AttributedList<Path> list = new B2ObjectListService(session).list(bucket,
                new DisabledListProgressListener());
        file2.attributes().setVersionId(resopnse.getFileId());
        assertTrue(list.contains(file2));
        assertEquals("1", list.get(file2).attributes().getRevision());
        assertFalse(list.get(file2).attributes().isDuplicate());
        assertTrue(list.contains(file1));
        assertEquals("2", list.get(file1).attributes().getRevision());
        assertTrue(list.get(file1).attributes().isDuplicate());
        assertEquals(bucket, list.get(file1).getParent());
    }
    new B2DeleteFeature(session).delete(Arrays.asList(file1, file2), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    {
        final AttributedList<Path> list = new B2ObjectListService(session).list(bucket,
                new DisabledListProgressListener());
        assertNull(list.find(new SimplePathPredicate(file1)));
        assertNull(list.find(new SimplePathPredicate(file2)));
    }
    new B2DeleteFeature(session).delete(Collections.singletonList(bucket), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}

From source file:com.nubits.nubot.notifications.jhipchat.Room.java

public boolean sendMessage(String message, UserId from, boolean notify, Color color) {
    String query = String.format(HipChatConstants.ROOMS_MESSAGE_QUERY_FORMAT, HipChatConstants.JSON_FORMAT,
            getOrigin().getAuthToken());

    StringBuilder params = new StringBuilder();

    if (message == null || from == null) {
        throw new IllegalArgumentException("Cant send message with null message or null user");
    } else {/* w w w .  j  a va2s.  c o m*/
        params.append("room_id=");
        params.append(getId());
        params.append("&from=");
        try {
            params.append(URLEncoder.encode(from.getName(), "UTF-8"));
            params.append("&message=");
            params.append(URLEncoder.encode(message, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

    }

    if (notify) {
        params.append("&notify=1");
    }

    if (color != null) {
        params.append("&color=");
        params.append(color.name().toLowerCase());
    }

    final String paramsToSend = params.toString();

    OutputStream output = null;
    InputStream input = null;

    HttpURLConnection connection = null;
    boolean result = false;

    try {
        URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.ROOMS_MESSAGE + query);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoOutput(true);

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", Integer.toString(paramsToSend.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        output = new BufferedOutputStream(connection.getOutputStream());
        IOUtils.write(paramsToSend, output);
        IOUtils.closeQuietly(output);

        input = connection.getInputStream();
        result = UtilParser.parseMessageResult(input);

    } catch (MalformedURLException e) {
        LOG.severe(e.getMessage());
    } catch (IOException e) {
        LOG.severe(e.getMessage());
    } finally {
        IOUtils.closeQuietly(output);
        connection.disconnect();
    }

    return result;
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.VaultServerService.java

public String getToken(String deploymentName, Vault vault) {
    String result = "";
    InitStatus initStatus;/*w ww  .ja va 2 s. co  m*/

    try {
        initStatus = vault.initStatus();
    } catch (RetrofitError e) {
        throw handleVaultError(e, "check init status");
    }

    if (!initStatus.isInitialized()) {
        try {
            InitResponse init = vault.init(new InitRequest().setSecretShares(3).setSecretThreshold(3));
            result = init.getRootToken();

            for (String key : init.getKeys()) {
                vault.unseal(new UnsealRequest().setKey(key));
            }
        } catch (RetrofitError e) {
            throw handleVaultError(e, "init vault");
        }
    }

    SealStatus sealStatus;
    try {
        sealStatus = vault.sealStatus();
    } catch (RetrofitError e) {
        throw handleVaultError(e, "check seal status");
    }

    if (sealStatus.isSealed()) {
        throw new HalException(Problem.Severity.FATAL,
                "Your vault is in a sealed state, no config can be written.");
    }

    File vaultTokenFile = halconfigDirectoryStructure.getVaultTokenPath(deploymentName).toFile();
    if (result.isEmpty()) {
        try {
            result = IOUtils.toString(new FileInputStream(vaultTokenFile));
        } catch (IOException e) {
            throw new HalException(
                    new ProblemBuilder(Problem.Severity.FATAL, "Unable to read vault token: " + e.getMessage())
                            .setRemediation("This file is needed for storing credentials to your vault server. "
                                    + "If you have deployed vault by hand, make sure Halyard can authenticate using the token in that file.")
                            .build());
        }
    } else {
        try {
            IOUtils.write(result.getBytes(), new FileOutputStream(vaultTokenFile));
        } catch (IOException e) {
            throw new HalException(Problem.Severity.FATAL, "Unable to write vault token: " + e.getMessage());
        }
    }

    return result;
}

From source file:com.openkm.servlet.admin.OmrServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);//from w  w  w  . j a v  a 2s . c o  m

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            String fileName = null;
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Set<String> properties = new HashSet<String>();
            Omr om = new Omr();

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("om_id")) {
                        om.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("om_name")) {
                        om.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("om_properties")) {
                        properties.add(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("om_active")) {
                        om.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    fileName = item.getName();
                }
            }

            om.setProperties(properties);

            if (action.equals("create") || action.equals("edit")) {
                // Store locally template file to be used later
                if (is != null && is.available() > 0) { // Case update only name
                    byte[] data = IOUtils.toByteArray(is);
                    File tmp = FileUtils.createTempFile();
                    FileOutputStream fos = new FileOutputStream(tmp);
                    IOUtils.write(data, fos);
                    IOUtils.closeQuietly(fos);

                    // Store template file
                    om.setTemplateFileName(FilenameUtils.getName(fileName));
                    om.setTemplateFileMime(MimeTypeConfig.mimeTypes.getContentType(fileName));
                    om.setTemplateFilContent(data);
                    IOUtils.closeQuietly(is);

                    // Create training files
                    Map<String, File> trainingMap = OMRHelper.trainingTemplate(tmp);
                    File ascFile = trainingMap.get(OMRHelper.ASC_FILE);
                    File configFile = trainingMap.get(OMRHelper.CONFIG_FILE);

                    // Store asc file
                    om.setAscFileName(om.getTemplateFileName() + ".asc");
                    om.setAscFileMime(MimeTypeConfig.MIME_TEXT);
                    is = new FileInputStream(ascFile);
                    om.setAscFileContent(IOUtils.toByteArray(is));
                    IOUtils.closeQuietly(is);

                    // Store config file
                    om.setConfigFileName(om.getTemplateFileName() + ".config");
                    om.setConfigFileMime(MimeTypeConfig.MIME_TEXT);
                    is = new FileInputStream(configFile);
                    om.setConfigFileContent(IOUtils.toByteArray(is));
                    IOUtils.closeQuietly(is);

                    // Delete temporal files
                    FileUtils.deleteQuietly(tmp);
                    FileUtils.deleteQuietly(ascFile);
                    FileUtils.deleteQuietly(configFile);
                }

                if (action.equals("create")) {
                    long id = OmrDAO.getInstance().create(om);

                    // Activity log
                    UserActivity.log(userId, "ADMIN_OMR_CREATE", Long.toString(id), null, om.toString());
                } else if (action.equals("edit")) {
                    OmrDAO.getInstance().updateTemplate(om);
                    om = OmrDAO.getInstance().findByPk(om.getId());

                    // Activity log
                    UserActivity.log(userId, "ADMIN_OMR_EDIT", Long.toString(om.getId()), null, om.toString());
                }

                list(userId, request, response);
            } else if (action.equals("delete")) {
                OmrDAO.getInstance().delete(om.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_DELETE", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("editAsc")) {
                Omr omr = OmrDAO.getInstance().findByPk(om.getId());
                omr.setAscFileContent(IOUtils.toByteArray(is));
                omr.setAscFileMime(MimeTypeConfig.MIME_TEXT);
                omr.setAscFileName(omr.getTemplateFileName() + ".asc");
                OmrDAO.getInstance().update(omr);
                omr = OmrDAO.getInstance().findByPk(om.getId());
                IOUtils.closeQuietly(is);

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_EDIT_ASC", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("editFields")) {
                Omr omr = OmrDAO.getInstance().findByPk(om.getId());
                omr.setFieldsFileContent(IOUtils.toByteArray(is));
                omr.setFieldsFileMime(MimeTypeConfig.MIME_TEXT);
                omr.setFieldsFileName(omr.getTemplateFileName() + ".fields");
                OmrDAO.getInstance().update(omr);
                omr = OmrDAO.getInstance().findByPk(om.getId());
                IOUtils.closeQuietly(is);

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_EDIT_FIELDS", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("check")) {
                File form = FileUtils.createTempFile();
                OutputStream formFile = new FileOutputStream(form);
                formFile.write(IOUtils.toByteArray(is));
                IOUtils.closeQuietly(formFile);
                formFile.close();
                Map<String, String> results = OMRHelper.process(form, om.getId());
                FileUtils.deleteQuietly(form);
                IOUtils.closeQuietly(is);
                UserActivity.log(userId, "ADMIN_OMR_CHECK_TEMPLATE", Long.toString(om.getId()), null, null);
                results(userId, request, response, action, results, om.getId());
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:com.ikon.servlet.admin.OmrServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);/*from w w w .jav  a  2 s. co m*/

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            String fileName = null;
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            Set<String> properties = new HashSet<String>();
            Omr om = new Omr();

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("om_id")) {
                        om.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("om_name")) {
                        om.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("om_properties")) {
                        properties.add(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("om_active")) {
                        om.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    fileName = item.getName();
                }
            }

            om.setProperties(properties);

            if (action.equals("create") || action.equals("edit")) {
                // Store locally template file to be used later
                if (is != null && is.available() > 0) { // Case update only name
                    byte[] data = IOUtils.toByteArray(is);
                    File tmp = FileUtils.createTempFile();
                    FileOutputStream fos = new FileOutputStream(tmp);
                    IOUtils.write(data, fos);
                    IOUtils.closeQuietly(fos);

                    // Store template file
                    om.setTemplateFileName(FilenameUtils.getName(fileName));
                    om.setTemplateFileMime(MimeTypeConfig.mimeTypes.getContentType(fileName));
                    om.setTemplateFilContent(data);
                    IOUtils.closeQuietly(is);

                    // Create training files
                    Map<String, File> trainingMap = OMRHelper.trainingTemplate(tmp);
                    File ascFile = trainingMap.get(OMRHelper.ASC_FILE);
                    File configFile = trainingMap.get(OMRHelper.CONFIG_FILE);

                    // Store asc file
                    om.setAscFileName(om.getTemplateFileName() + ".asc");
                    om.setAscFileMime(MimeTypeConfig.MIME_TEXT);
                    is = new FileInputStream(ascFile);
                    om.setAscFileContent(IOUtils.toByteArray(is));
                    IOUtils.closeQuietly(is);

                    // Store config file
                    om.setConfigFileName(om.getTemplateFileName() + ".config");
                    om.setConfigFileMime(MimeTypeConfig.MIME_TEXT);
                    is = new FileInputStream(configFile);
                    om.setConfigFileContent(IOUtils.toByteArray(is));
                    IOUtils.closeQuietly(is);

                    // Delete temporal files
                    FileUtils.deleteQuietly(tmp);
                    FileUtils.deleteQuietly(ascFile);
                    FileUtils.deleteQuietly(configFile);
                }

                if (action.equals("create")) {
                    long id = OmrDAO.getInstance().create(om);

                    // Activity log
                    UserActivity.log(userId, "ADMIN_OMR_CREATE", Long.toString(id), null, om.toString());
                } else if (action.equals("edit")) {
                    OmrDAO.getInstance().updateTemplate(om);
                    om = OmrDAO.getInstance().findByPk(om.getId());

                    // Activity log
                    UserActivity.log(userId, "ADMIN_OMR_EDIT", Long.toString(om.getId()), null, om.toString());
                }

                list(userId, request, response);
            } else if (action.equals("delete")) {
                OmrDAO.getInstance().delete(om.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_DELETE", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("editAsc")) {
                Omr omr = OmrDAO.getInstance().findByPk(om.getId());
                omr.setAscFileContent(IOUtils.toByteArray(is));
                omr.setAscFileMime(MimeTypeConfig.MIME_TEXT);
                omr.setAscFileName(omr.getTemplateFileName() + ".asc");
                OmrDAO.getInstance().update(omr);
                omr = OmrDAO.getInstance().findByPk(om.getId());
                IOUtils.closeQuietly(is);

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_EDIT_ASC", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("editFields")) {
                Omr omr = OmrDAO.getInstance().findByPk(om.getId());
                omr.setFieldsFileContent(IOUtils.toByteArray(is));
                omr.setFieldsFileMime(MimeTypeConfig.MIME_TEXT);
                omr.setFieldsFileName(omr.getTemplateFileName() + ".fields");
                OmrDAO.getInstance().update(omr);
                omr = OmrDAO.getInstance().findByPk(om.getId());
                IOUtils.closeQuietly(is);

                // Activity log
                UserActivity.log(userId, "ADMIN_OMR_EDIT_FIELDS", Long.toString(om.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("check")) {
                File form = FileUtils.createTempFile();
                OutputStream formFile = new FileOutputStream(form);
                formFile.write(IOUtils.toByteArray(is));
                IOUtils.closeQuietly(formFile);
                formFile.close();
                Map<String, String> results = OMRHelper.process(form, om.getId());
                FileUtils.deleteQuietly(form);
                IOUtils.closeQuietly(is);
                UserActivity.log(userId, "ADMIN_OMR_CHECK_TEMPLATE", Long.toString(om.getId()), null, null);
                results(userId, request, response, action, results, om.getId());
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (OMRException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (InvalidFileStructureException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (InvalidImageIndexException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (UnsupportedTypeException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (MissingParameterException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (WrongParameterException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.spec.DuplicateGerritListenersPreloadedProjectHudsonTestCase.java

/**
 * Tests that configuring an existing project via jenkins cli doesn't produce duplicated triggers
 * and that the trigger is configured for the new project pattern.
 *
 * @throws Exception if so/*from  w  ww.  j a v a 2  s.  c  o  m*/
 */
@Test
@LocalData
public void testReconfigureUsingCli() throws Exception {
    assertNrOfEventListeners(0);
    TopLevelItem testProj = j.jenkins.getItem("testProj");
    String gerritProjectPattern = "someotherproject";
    Document document = loadConfigXmlViaCli(testProj);
    String xml = changeConfigXml(gerritProjectPattern, document);

    List<String> cmd = javaCliJarCmd("update-job", testProj.getFullName());
    Process process = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));
    OutputStream output = process.getOutputStream();
    IOUtils.write(xml, output);
    IOUtils.closeQuietly(output);
    String response = IOUtils.toString(process.getInputStream());
    System.out.println(response);
    assertEquals(0, process.waitFor());
    assertNrOfEventListeners(0);
    assertEventListenerWithSomeOtherProjectSet(gerritProjectPattern);
}

From source file:com.thoughtworks.go.server.domain.JobInstanceLogTest.java

@Test
public void shouldFindIndexPageFromTestOutputRecursively() throws Exception {

    final File testOutput = new File(rootFolder, "testoutput");
    final File junitReportFolder = new File(testOutput, "junitreport");
    junitReportFolder.mkdirs();//  ww  w  .  ja  v a 2 s.  c o m
    FileOutputStream fileOutputStream = new FileOutputStream(new File(junitReportFolder, "index.html"));
    IOUtils.write("Test", fileOutputStream);
    IOUtils.closeQuietly(fileOutputStream);
    HashMap map = new HashMap();
    map.put("artifactfolder", rootFolder);
    jobInstanceLog = new JobInstanceLog(null, map);
    assertThat(jobInstanceLog.getTestIndexPage().getName(), is("index.html"));

}

From source file:mitm.common.security.crl.GenerateTestCRLs.java

@Test
public void testGenerateCACRLThisUpdateInFarFuture() throws Exception {
    X509CRLBuilder crlGenerator = createX509CRLBuilder();

    Date thisDate = TestUtils.parseDate("30-Nov-2030 11:38:35 GMT");

    Date nextDate = TestUtils.parseDate("30-Nov-2040 11:38:35 GMT");

    crlGenerator.setThisUpdate(thisDate);
    crlGenerator.setNextUpdate(nextDate);
    crlGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption");

    X509Certificate certificate = TestUtils
            .loadCertificate("test/resources/testdata/certificates/" + "valid_certificate_mitm_test_ca.cer");
    assertNotNull(certificate);/* w ww  . j  a va  2s .  co m*/

    Date revocationDate = TestUtils.parseDate("30-Nov-2006 11:38:35 GMT");

    crlGenerator.addCRLEntry(certificate.getSerialNumber(), revocationDate, CRLReason.keyCompromise);

    X509CRL crl = crlGenerator.generateCRL(new KeyAndCertificateImpl(caPrivateKey, caCertificate));

    assertEquals("EMAILADDRESS=ca@example.com, CN=MITM Test CA, L=Amsterdam, ST=NH, C=NL",
            crl.getIssuerX500Principal().toString());
    assertEquals(thisDate, crl.getThisUpdate());
    assertEquals(nextDate, crl.getNextUpdate());
    assertEquals(1, crl.getRevokedCertificates().size());
    assertTrue(crl.isRevoked(certificate));

    File crlFile = new File("test/tmp/testgeneratecacrlthisupdateinfarfuture.crl");

    FileOutputStream fos = new FileOutputStream(crlFile);

    IOUtils.write(crl.getEncoded(), fos);

    fos.close();
}

From source file:ch.cyberduck.core.sds.SDSReadFeatureTest.java

@Test
public void testReadRange() throws Exception {
    final Host host = new Host(new SDSProtocol(), "duck.ssp-europe.eu", new Credentials(
            System.getProperties().getProperty("sds.user"), System.getProperties().getProperty("sds.key")));
    final SDSSession session = new SDSSession(host, new DisabledX509TrustManager(),
            new DefaultX509KeyManager());
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path room = new SDSDirectoryFeature(session)
            .mkdir(new Path(new AlphanumericRandomStringService().random(),
                    EnumSet.of(Path.Type.directory, Path.Type.volume)), null, new TransferStatus());
    final Path test = new Path(room, new AlphanumericRandomStringService().random(),
            EnumSet.of(Path.Type.file));
    new SDSTouchFeature(session).touch(test, new TransferStatus());
    final Local local = new Local(System.getProperty("java.io.tmpdir"),
            new AlphanumericRandomStringService().random());
    final byte[] content = new RandomStringGenerator.Builder().build().generate(1000).getBytes();
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);//from   w  w w.j a  va 2 s .c  om
    IOUtils.write(content, out);
    out.close();
    final TransferStatus upload = new TransferStatus().length(content.length);
    upload.setExists(true);
    new DefaultUploadFeature<VersionId>(new SDSWriteFeature(session)).upload(test, local,
            new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), upload,
            new DisabledConnectionCallback());
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    status.setAppend(true);
    status.setOffset(100L);
    final InputStream in = new SDSReadFeature(session).read(test, status.length(content.length - 100),
            new DisabledConnectionCallback());
    assertNotNull(in);
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length - 100);
    new StreamCopier(status, status).transfer(in, buffer);
    final byte[] reference = new byte[content.length - 100];
    System.arraycopy(content, 100, reference, 0, content.length - 100);
    assertArrayEquals(reference, buffer.toByteArray());
    in.close();
    new SDSDeleteFeature(session).delete(Collections.singletonList(room), new DisabledLoginCallback(),
            new Delete.DisabledCallback());
    session.close();
}