Java Code Examples for org.apache.commons.io.IOUtils.copy()

The following are Jave code examples for showing how to use copy() of the org.apache.commons.io.IOUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: monarch   File: ExampleSecurityManagerTest.java   View Source Code Vote up 6 votes
@Before
public void setUp() throws Exception {
  // resource file
  this.jsonResource = "org/apache/geode/security/templates/security.json";
  InputStream inputStream = ClassLoader.getSystemResourceAsStream(this.jsonResource);

  assertThat(inputStream).isNotNull();

  // non-resource file
  this.jsonFile = new File(temporaryFolder.getRoot(), "security.json");
  IOUtils.copy(inputStream, new FileOutputStream(this.jsonFile));

  // string
  this.json = FileUtils.readFileToString(this.jsonFile, "UTF-8");
  this.exampleSecurityManager = new ExampleSecurityManager();
}
 
Example 2
Project: q-mail   File: MessageCryptoHelper.java   View Source Code Vote up 6 votes
private OpenPgpDataSink<MimeBodyPart> getDataSinkForOpenPgpDecryptedInlineData() {
    return new OpenPgpDataSink<MimeBodyPart>() {
        @Override
        public MimeBodyPart processData(InputStream is) throws IOException {
            try {
                ByteArrayOutputStream decryptedByteOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(is, decryptedByteOutputStream);
                TextBody body = new TextBody(new String(decryptedByteOutputStream.toByteArray()));
                return new MimeBodyPart(body, "text/plain");
            } catch (MessagingException e) {
                Timber.e(e, "MessagingException");
            }

            return null;
        }
    };
}
 
Example 3
Project: plugin-vm-vcloud   File: VCloudPluginResource.java   View Source Code Vote up 6 votes
/**
 * Return a snapshot of the console.
 * 
 * @param subscription
 *            the valid screenshot of the console.
 * @return the valid screenshot of the console.
 */
@GET
@Path("{subscription:\\d+}/console.png")
@Produces("image/png")
public StreamingOutput getConsole(@PathParam("subscription") final int subscription) {
	final Map<String, String> parameters = subscriptionResource.getParameters(subscription);
	final VCloudCurlProcessor processor = new VCloudCurlProcessor();
	authenticate(parameters, processor);

	// Get the screen thumbnail
	return output -> {
		final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_API), "/") + "vApp/vm-" + parameters.get(PARAMETER_VM)
				+ "/screen";
		final CurlRequest curlRequest = new CurlRequest("GET", url, null, (request, response) -> {
			if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
				// Copy the stream
				IOUtils.copy(response.getEntity().getContent(), output);
				output.flush();
			}
			return false;
		});
		processor.process(curlRequest);
	};
}
 
Example 4
Project: esup-sgc   File: WsRestPhotoController.java   View Source Code Vote up 6 votes
@RequestMapping(value="/{eppn}/restrictedPhoto")
public void getAuthorizedPhoto(@PathVariable String eppn, HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
	List<Card> validCards = Card.findCardsByEppnAndEtatNotEquals(eppn, Etat.REJECTED, "dateEtat", "desc").getResultList();
	if(!validCards.isEmpty()) {
		Card card = validCards.get(0);
		User user = User.findUser(eppn);
		if(user.getDifPhoto()) {
			PhotoFile photoFile = card.getPhotoFile();
			Long size = photoFile.getFileSize();
			String contentType = photoFile.getContentType();
			response.setContentType(contentType);
			response.setContentLength(size.intValue());
			IOUtils.copy(photoFile.getBigFile().getBinaryFile().getBinaryStream(), response.getOutputStream());
		}else{
			ClassPathResource noImg = new ClassPathResource(ManagerCardController.IMG_INTERDIT);
			IOUtils.copy(noImg.getInputStream(), response.getOutputStream());
		}
	}
}
 
Example 5
Project: cas-5.1.0   File: TemplatedMetadataAndCertificatesGenerationService.java   View Source Code Vote up 6 votes
/**
 * Build metadata generator parameters by passing the encryption,
 * signing and back-channel certs to the parameter generator.
 *
 * @throws Exception Thrown if cert files are missing, or metadata file inaccessible.
 */
protected void buildMetadataGeneratorParameters() throws Exception {
    final SamlIdPProperties idp = casProperties.getAuthn().getSamlIdp();
    final Resource template = this.resourceLoader.getResource("classpath:/template-idp-metadata.xml");

    String signingKey = FileUtils.readFileToString(idp.getMetadata().getSigningCertFile().getFile(), StandardCharsets.UTF_8);
    signingKey = StringUtils.remove(signingKey, BEGIN_CERTIFICATE);
    signingKey = StringUtils.remove(signingKey, END_CERTIFICATE).trim();

    String encryptionKey = FileUtils.readFileToString(idp.getMetadata().getEncryptionCertFile().getFile(), StandardCharsets.UTF_8);
    encryptionKey = StringUtils.remove(encryptionKey, BEGIN_CERTIFICATE);
    encryptionKey = StringUtils.remove(encryptionKey, END_CERTIFICATE).trim();

    try (StringWriter writer = new StringWriter()) {
        IOUtils.copy(template.getInputStream(), writer, StandardCharsets.UTF_8);
        final String metadata = writer.toString()
                .replace("${entityId}", idp.getEntityId())
                .replace("${scope}", idp.getScope())
                .replace("${idpEndpointUrl}", getIdPEndpointUrl())
                .replace("${encryptionKey}", encryptionKey)
                .replace("${signingKey}", signingKey);
        FileUtils.write(idp.getMetadata().getMetadataFile(), metadata, StandardCharsets.UTF_8);
    }
}
 
Example 6
Project: JAddOn   File: ZipUtils.java   View Source Code Vote up 5 votes
private static void processFolder(final File folder, final ZipOutputStream zipOutputStream, final int prefixLength)
        throws IOException {
    for (final File file : folder.listFiles()) {
        if (file.isFile()) {
            final ZipEntry zipEntry = new ZipEntry(file.getPath().substring(prefixLength));
            zipOutputStream.putNextEntry(zipEntry);
            try (FileInputStream inputStream = new FileInputStream(file)) {
                IOUtils.copy(inputStream, zipOutputStream);
            }
            zipOutputStream.closeEntry();
        } else if (file.isDirectory()) {
            processFolder(file, zipOutputStream, prefixLength);
        }
    }
}
 
Example 7
Project: document-management-store-app   File: DocumentContentVersionService.java   View Source Code Vote up 5 votes
public void streamDocumentContentVersion(@NotNull DocumentContentVersion documentContentVersion) {
    if (documentContentVersion.getDocumentContent() == null || documentContentVersion.getDocumentContent().getData() == null) {
        throw new CantReadDocumentContentVersionBinaryException("File content is null", documentContentVersion);
    }
    try {
        response.setHeader(HttpHeaders.CONTENT_TYPE, documentContentVersion.getMimeType());
        response.setHeader(HttpHeaders.CONTENT_LENGTH, documentContentVersion.getSize().toString());
        response.setHeader("OriginalFileName", documentContentVersion.getOriginalDocumentName());
        IOUtils.copy(documentContentVersion.getDocumentContent().getData().getBinaryStream(), response.getOutputStream(), streamBufferSize);
    } catch (Exception e) {
        throw new CantReadDocumentContentVersionBinaryException(e, documentContentVersion);
    }
}
 
Example 8
Project: ServiceComb-Company-WorkShop   File: CacheUpdateFilter.java   View Source Code Vote up 5 votes
private String responseBody(RequestContext context) throws IOException {
  try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(STREAM_BUFFER_SIZE.get())) {
    IOUtils.copy(context.getResponseDataStream(), outputStream);
    context.setResponseBody(outputStream.toString());
    return outputStream.toString();
  }
}
 
Example 9
Project: urule   File: ResourceLoaderServletHandler.java   View Source Code Vote up 5 votes
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String path=req.getContextPath()+URuleServlet.URL+URL;
	String uri=req.getRequestURI();
	String resPath=uri.substring(path.length()+1);
	String p="classpath:"+resPath;
	if(p.endsWith(".js")){
		resp.setContentType("text/javascript");	
	}else if(p.endsWith(".css")){
		resp.setContentType("text/css");
	}else if(p.endsWith(".png")){
		resp.setContentType("image/png");
	}else if(p.endsWith(".jpg")){
		resp.setContentType("image/jpeg");
	}else{
		resp.setContentType("application/octet-stream");
	}
	InputStream input=applicationContext.getResource(p).getInputStream();
	OutputStream output=resp.getOutputStream();
	try{
		IOUtils.copy(input, output);			
	}finally{
		if(input!=null){
			input.close();
		}
		if(output!=null){
			output.flush();
			output.close();
		}
	}
}
 
Example 10
Project: ObsidianSuite   File: FileHandler.java   View Source Code Vote up 5 votes
public static void copyFileToBin(String fileName, InputStream inputStream) {
	binFolder.mkdirs();
	File copy = new File(binFolder, fileName);
	try 
	{
		if(copy.exists())
			copy.delete();
		FileOutputStream outputStream = new FileOutputStream(copy);
		IOUtils.copy(inputStream, outputStream);
	} 
	catch (IOException e) {e.printStackTrace();}		
}
 
Example 11
Project: convertigo-engine   File: BigMimeMultipart.java   View Source Code Vote up 5 votes
public MimePart nextPart(OutputStream os) throws IOException, MessagingException {			
	MimeBodyPart bodyPart = readHeaders();
	
	if (bodyPart != null) {
		IOUtils.copy(pis, os);
		
		pis.nextPart();	
	}
	
	return bodyPart;
}
 
Example 12
Project: pdf-converter   File: EpubCreator.java   View Source Code Vote up 5 votes
private void copyImages() throws IOException {
    File imagesDir = new File(basedir, "images");
    imagesDir.mkdirs();
    for(File file : listFiles()){
        IOUtils.copy(new FileInputStream(file), new FileOutputStream(new File(imagesDir, file.getName())));
    }
}
 
Example 13
Project: jfrog-idea-plugin   File: XrayImpl.java   View Source Code Vote up 5 votes
private static String readStream(InputStream stream) throws IOException {
    if (stream == null) {
        return "";
    }
    try (StringWriter writer = new StringWriter()){
        IOUtils.copy(stream, writer, "UTF-8");
        return writer.toString();
    }
}
 
Example 14
Project: airsonic   File: CoverArtController.java   View Source Code Vote up 5 votes
private void sendImage(File file, HttpServletResponse response) throws IOException {
    response.setContentType(StringUtil.getMimeType(FilenameUtils.getExtension(file.getName())));
    InputStream in = new FileInputStream(file);
    try {
        IOUtils.copy(in, response.getOutputStream());
    } finally {
        IOUtils.closeQuietly(in);
    }
}
 
Example 15
Project: TOSCAna   File: MapperTestConfiguration.java   View Source Code Vote up 5 votes
@Bean
public TagStorage tagStorage(Preferences preferences) throws Exception {
    new File(preferences.getDataDir(), "misc").mkdirs();
    File file = new File(preferences.getDataDir(), TagStorage.DOCKER_IMAGE_TAGS);
    InputStream input = getClass().getResourceAsStream("/kubernetes/base-image-mapper/docker-tagbase.json");
    FileOutputStream out = new FileOutputStream(file);

    IOUtils.copy(input, out);
    input.close();
    out.close();

    return new TagStorage(preferences);
}
 
Example 16
Project: cakes   File: SimpleDemos.java   View Source Code Vote up 5 votes
/**
 * 使用流的方式来操作hdfs上的文件
 */
@Test
public void testUploadByStream() throws IOException {
    FileSystem fileSystem = FileSystem.get(conf);
    FSDataOutputStream fsDataOutputStream = fileSystem.create(new Path("/精通Python设计模式.pdf"));
    FileInputStream inputStream = new FileInputStream(new File("/haoc/books/精通Python设计模式.pdf"));
    IOUtils.copy(inputStream, fsDataOutputStream);
}
 
Example 17
Project: yadaframework   File: YadaWebUtil.java   View Source Code Vote up 5 votes
/**
 * Save an uploaded file to the given target file
 * @param attachment
 * @param targetFile
 * @throws IOException
 */
public void saveAttachment(MultipartFile attachment, File targetFile) throws IOException {
	try (InputStream inputStream = attachment.getInputStream(); OutputStream outputStream = new FileOutputStream(targetFile)) {
		IOUtils.copy(inputStream, outputStream);
	} catch (IOException e) {
		throw e;
	}
}
 
Example 18
Project: cyberduck   File: SFTPPublicKeyAuthenticationTest.java   View Source Code Vote up 4 votes
@Test
public void testAuthenticatePuTTYKeyWithWrongPassword() throws Exception {
    final Credentials credentials = new Credentials(
        System.getProperties().getProperty("sftp.user"), ""
    );
    final Local key = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    try {
        credentials.setIdentity(key);
        new DefaultLocalTouchFeature().touch(key);
        final String putty = "PuTTY-User-Key-File-2: ssh-rsa\n" +
            "Encryption: aes256-cbc\n" +
            "Comment: rsa-key-20121215\n" +
            "Public-Lines: 4\n" +
            "AAAAB3NzaC1yc2EAAAABJQAAAIB7KdUyuvGb2ne9G9YDAjaYvX/Mq6Q6ppGjbEQo\n" +
            "bac66VUazxVpZsnAWikcdYAU7odkyt3jg7Nn1NgQS1a5mpXk/j77Ss5C9W4rymrU\n" +
            "p32cmbgB/KIV80DnOyZyOtDWDPM0M0RRXqQvAO6TsnmsNSnBa8puMLHqCtrhvvJD\n" +
            "KU+XEw==\n" +
            "Private-Lines: 8\n" +
            "4YMkPgLQJ9hOI1L1HsdOUnYi57tDy5h9DoPTHD55fhEYsn53h4WaHpxuZH8dTpbC\n" +
            "5TcV3vYTfhh+aFBY0p/FI8L1hKfABLRxhkqkkc7xMmOGlA6HejAc8oTA3VArgSeG\n" +
            "tRBuQRmBAC1Edtek/U+s8HzI2whzTw8tZoUUnT6844oc4tyCpWJUy5T8l+O3/03s\n" +
            "SceJ98DN2k+L358VY8AXgPxP6NJvHvIlwmIo+PtcMWsyZegfSHEnoXN2GN4N0ul6\n" +
            "298RzA9R+I3GSKKxsxUvWfOVibLq0dDM3+CTwcbmo4qvyM2xrRRLhObB2rVW07gL\n" +
            "7+FZpHxf44QoQQ8mVkDJNaT1faF+h/8tCp2j1Cj5yEPHMOHGTVMyaz7gqhoMw5RX\n" +
            "sfSP4ZaCGinLbouPrZN9Ue3ytwdEpmqU2MelmcZdcH6kWbLCqpWBswsxPfuhFdNt\n" +
            "oYhmT2+0DKBuBVCAM4qRdA==\n" +
            "Private-MAC: 40ccc8b9a7291ec64e5be0c99badbc8a012bf220";
        IOUtils.copy(new StringReader(putty), key.getOutputStream(false), Charset.forName("UTF-8"));
        final Host host = new Host(new SFTPProtocol(), "test.cyberduck.ch", credentials);
        final SFTPSession session = new SFTPSession(host);
        session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
        final AtomicBoolean p = new AtomicBoolean();
        try {
            assertFalse(new SFTPPublicKeyAuthentication(session).authenticate(host, new DisabledPasswordStore(), new DisabledLoginCallback() {
                @Override
                public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) throws LoginCanceledException {
                    p.set(true);
                    throw new LoginCanceledException();
                }
            }, new DisabledCancelCallback()));
        }
        catch(LoginCanceledException e) {
            // Expected
        }
        assertTrue(p.get());
        session.close();
    }
    finally {
        key.delete();
    }
}
 
Example 19
Project: lams   File: LearningDesignSVGServlet.java   View Source Code Vote up 4 votes
@Override
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
    String serverId = request.getParameter(CentralConstants.PARAM_SERVER_ID);
    String datetime = request.getParameter(CentralConstants.PARAM_DATE_TIME);
    String hashValue = request.getParameter(CentralConstants.PARAM_HASH_VALUE);
    String username = request.getParameter(CentralConstants.PARAM_USERNAME);

    // in case lsId parameter is provided - get learningDesignId from the responsible lesson, otherwise try to get
    // it from a request as "ldId" parameter
    Long lessonId = WebUtil.readLongParam(request, CentralConstants.PARAM_LESSON_ID, true);
    Long learningDesignId = (lessonId == null) ? WebUtil.readLongParam(request, CentralConstants.PARAM_LEARNING_DESIGN_ID) : 
	lessonService.getLessonDetails(lessonId).getLearningDesignID();

    if (serverId == null || datetime == null || hashValue == null || username == null) {
	String msg = "Parameters missing";
	log.error(msg);
	response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameters missing");
    }

    // LDEV-2196 preserve character encoding if necessary
    if (request.getCharacterEncoding() == null) {
	log.debug(
		"request.getCharacterEncoding is empty, parsing username and courseName as 8859_1 to UTF-8...");
	username = new String(username.getBytes("8859_1"), "UTF-8");
    }

    // get Server map
    ExtServer extServer = integrationService.getExtServer(serverId);

    // authenticate
    Authenticator.authenticate(extServer, datetime, username, hashValue);

    String imagePath = LearningDesignService.getLearningDesignSVGPath(learningDesignId);
    File imageFile = new File(imagePath);
    if (!imageFile.canRead()) {
	response.sendError(HttpServletResponse.SC_NOT_FOUND);
	return;
    }

    boolean download = WebUtil.readBooleanParam(request, "download", false);
    // should the image be downloaded or a part of page?
    if (download) {
	String name = learningDesignService
		.getLearningDesignDTO(learningDesignId, Configuration.get(ConfigurationKeys.SERVER_LANGUAGE))
		.getTitle();
	name += "." + "svg";
	name = FileUtil.encodeFilenameForDownload(request, name);
	response.setContentType("application/x-download");
	response.setHeader("Content-Disposition", "attachment;filename=" + name);
    } else {
	response.setContentType("image/svg+xml");
    }

    FileInputStream input = new FileInputStream(imagePath);
    OutputStream output = response.getOutputStream();
    IOUtils.copy(input, output);
    IOUtils.closeQuietly(input);
    IOUtils.closeQuietly(output);
} catch (Exception e) {
    log.error("Problem with LearningDesignSVGServlet request", e);
    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Problem with LearningDesignSVGServlet request");
}
   }
 
Example 20
Project: cf-mta-deploy-service   File: StreamUtil.java   View Source Code Vote up 4 votes
private static void createFile(Path fileToCreate, InputStream inputStream) throws IOException {
    Files.createFile(fileToCreate);
    try (OutputStream outputStream = Files.newOutputStream(fileToCreate)) {
        IOUtils.copy(inputStream, outputStream);
    }
}