Java Code Examples for org.apache.commons.io.IOUtils

The following are top voted examples for showing how to use org.apache.commons.io.IOUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: pay   File: XMLParser.java   Source Code and License 9 votes vote down vote up
public static Map<String,Object> getMapFromXML(String xmlString) throws ParserConfigurationException, IOException, SAXException {

        //这里用Dom的方式解析回包的最主要目的是防止API新增回包字段
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream is =  IOUtils.toInputStream(xmlString);
        Document document = builder.parse(is);
        //获取到document里面的全部结点
        NodeList allNodes = document.getFirstChild().getChildNodes();
        Node node;
        Map<String, Object> map = new HashMap<String, Object>();
        int i=0;
        while (i < allNodes.getLength()) {
            node = allNodes.item(i);
            if(node instanceof Element){
                map.put(node.getNodeName(),node.getTextContent());
            }
            i++;
        }
        return map;

    }
 
Example 2
Project: spring-react-example   File: ReactViewResolver.java   Source Code and License 9 votes vote down vote up
public ReactViewResolver()
{
    final ClassLoader classLoader = this.getClass().getClassLoader();

    try
    {
        template = new BaseTemplate(
            IOUtils.toString(
                classLoader.getResourceAsStream(TEMPLATE_RESOURCE),
                BaseTemplate.UTF_8
            )
        );
    }
    catch (IOException e)
    {
        throw new ExampleException(e);
    }
}
 
Example 3
Project: AwsCommons   File: AbstractLambdaRouter.java   Source Code and License 7 votes vote down vote up
public void doHandle(final InputStream inStream, final OutputStream outStream) throws Exception {

        try {
            final JsonObject inputJson = SerializationUtil.parseAsJsonElement(IOUtils.toString(inStream, Charset.defaultCharset())).getAsJsonObject();

            final AbstractApiAction apiAction = instantiateAction(inputJson.getAsJsonPrimitive("action").getAsString());

            final UserInfo userInfo = new UserInfo(inputJson.getAsJsonPrimitive("uid").getAsString(), inputJson.getAsJsonPrimitive("groups").getAsString());

            final AbstractApiResponse responseObject = apiAction.getType() != null ?
                    apiAction.handleGeneric((IntegrationRequestBody) SerializationUtil.fromJson(inputJson.getAsJsonObject("body"), apiAction.getType()), userInfo) :
                    apiAction.handleGeneric(null, userInfo);

            if (responseObject != null) {
                IOUtils.write(responseObject.toJson(), outStream, Charset.defaultCharset());
            }
        } catch (final Exception e) {
            ExceptionHandler.processException(e);
        }
    }
 
Example 4
Project: monarch   File: ExampleSecurityManagerTest.java   Source Code and License 7 votes vote down vote up
@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 5
Project: AnyMall   File: GoodsCtrl.java   Source Code and License 7 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("application/json");
	response.setCharacterEncoding("utf-8");

	PrintWriter out = response.getWriter();

	String rawContent = IOUtils.toString(request.getReader());
	log.debug(String.format("request content: %s", rawContent));

	out.print(goodsDAO.findById(1));
}
 
Example 6
Project: mmsns   File: HadoopUtil.java   Source Code and License 7 votes vote down vote up
/**
 * 从hadoop中下载文件
 *
 * @param taskName
 * @param filePath
 */
public static void download(String taskName, String filePath, boolean existDelete) {
    File file = new File(filePath);
    if (file.exists()) {
        if (existDelete) {
            file.deleteOnExit();
        } else {
            return;
        }
    }
    String hadoopAddress = propertyConfig.getProperty("sqoop.task." + taskName + ".tolink.linkConfig.uri");
    String itemmodels = propertyConfig.getProperty("sqoop.task." + taskName + ".recommend.itemmodels");
    try {
        DistributedFileSystem distributedFileSystem = distributedFileSystem(hadoopAddress);
        FSDataInputStream fsDataInputStream = distributedFileSystem.open(new Path(itemmodels));
        byte[] bs = new byte[fsDataInputStream.available()];
        fsDataInputStream.read(bs);
        log.info(new String(bs));

        FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
        IOUtils.write(bs, fileOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    } catch (IOException e) {
        log.error(e);
    }
}
 
Example 7
Project: nifi-registry   File: FileSystemFlowPersistenceProvider.java   Source Code and License 7 votes vote down vote up
@Override
public synchronized byte[] getFlowContent(final String bucketId, final String flowId, final int version) throws FlowPersistenceException {
    final File snapshotFile = getSnapshotFile(bucketId, flowId, version);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Retrieving snapshot with filename {}", new Object[] {snapshotFile.getAbsolutePath()});
    }

    if (!snapshotFile.exists()) {
        return null;
    }

    try (final InputStream in = new FileInputStream(snapshotFile)){
        return IOUtils.toByteArray(in);
    } catch (IOException e) {
        throw new FlowPersistenceException("Error reading snapshot file: " + snapshotFile.getAbsolutePath(), e);
    }
}
 
Example 8
Project: cyberduck   File: SFTPCryptomatorInteroperabilityTest.java   Source Code and License 6 votes vote down vote up
/**
 * Create long file/folder with Cryptomator, read with Cyberduck
 */
@Test
public void testCryptomatorInteroperability_longNames_Tests() throws Exception {
    // create folder
    final java.nio.file.Path targetFolder = cryptoFileSystem.getPath("/", new AlphanumericRandomStringService().random());
    Files.createDirectory(targetFolder);
    // create file and write some random content
    java.nio.file.Path targetFile = targetFolder.resolve(new AlphanumericRandomStringService().random());
    final byte[] content = RandomUtils.nextBytes(20);
    Files.write(targetFile, content);

    // read with Cyberduck and compare
    final Host host = new Host(new SFTPProtocol(), "localhost", PORT_NUMBER, new Credentials("empty", "empty"));
    final SFTPSession session = new SFTPSession(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new SFTPHomeDirectoryService(session).find();
    final Path vault = new Path(home, "vault", EnumSet.of(Path.Type.directory));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore()).load(session, new DisabledPasswordCallback() {
        @Override
        public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) throws LoginCanceledException {
            return new VaultCredentials(passphrase);
        }
    });
    session.withRegistry(new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator));
    Path p = new Path(new Path(vault, targetFolder.getFileName().toString(), EnumSet.of(Path.Type.directory)), targetFile.getFileName().toString(), EnumSet.of(Path.Type.file));
    final InputStream read = new CryptoReadFeature(session, new SFTPReadFeature(session), cryptomator).read(p, new TransferStatus(), new DisabledConnectionCallback());
    final byte[] readContent = new byte[content.length];
    IOUtils.readFully(read, readContent);
    assertArrayEquals(content, readContent);
    session.close();
}
 
Example 9
Project: soundwave   File: ZkJobInfoStore.java   Source Code and License 6 votes vote down vote up
@Override
public JobRunInfo getLatestRun(String jobType) throws Exception {
  String path = String.format("%s/job/%s/latestrun", zkPath,
      jobType);
  ensureZkPathExists(path);
  byte[] data = ZkClient.getClient().getData().forPath(path);
  if (data != null && data.length > 0) {
    try {
      return mapper.readValue(IOUtils.toString(data, "UTF-8"), JobRunInfo.class);
    } catch (Exception e) {
      logger.error("Fail to read last run. Error {}", ExceptionUtils.getRootCauseMessage(e));
      return null;
    }
  } else {
    return null;
  }
}
 
Example 10
Project: jwala   File: BalancerManagerXmlParser.java   Source Code and License 6 votes vote down vote up
Manager getWorkerXml(final String balancerManagerContent) {
    Manager manager;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Manager.class);
        Unmarshaller unmarshal = jaxbContext.createUnmarshaller();
        manager = (Manager) unmarshal.unmarshal(IOUtils.toInputStream(balancerManagerContent));
        List<Manager.Balancer> balancers = manager.getBalancers();
        for (Manager.Balancer balancer : balancers) {
            LOGGER.info(balancer.getName());
            List<Manager.Balancer.Worker> balancer_workers = balancer.getWorkers();
            for (Manager.Balancer.Worker worker : balancer_workers) {
                LOGGER.info(worker.getName() + " " + worker.getRoute());
            }
        }
    } catch (JAXBException e) {
        LOGGER.error(e.toString());
        throw new ApplicationException("Failed to Parsing the Balancer Manager XML ", e);
    }
    return manager;
}
 
Example 11
Project: Cognizant-Intelligent-Test-Scripter   File: MacCompiler.java   Source Code and License 6 votes vote down vote up
@Override
public String compile() {
    try {

        final ProcessBuilder pb = new ProcessBuilder("/bin/sh", getScriptFile());
        pb.directory(new File(System.getProperty("user.dir")));
        final Process p = pb.start();
        p.waitFor();
        String sb = IOUtils.toString(p.getErrorStream(), "UTF-8");
        if (!"".equals(sb)) {
            return sb;
        }
        return "Completed.";
    } catch (Exception ex) {
        Logger.getLogger(MacCompiler.class.getName()).log(Level.SEVERE, null, ex);
        return ex.getMessage();
    }

}
 
Example 12
Project: plumdo-work   File: ProcessDefinitionImageResource.java   Source Code and License 6 votes vote down vote up
@RequestMapping(value = "/process-definition/{processDefinitionId}/image", method = RequestMethod.GET, name="流程定义流程图")
public ResponseEntity<byte[]> getProcessDefinitionImage(@PathVariable String processDefinitionId) {
	ProcessDefinition processDefinition = getProcessDefinitionFromRequest(processDefinitionId);
	InputStream imageStream = repositoryService.getProcessDiagram(processDefinition.getId());

	if (imageStream != null) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.setContentType(MediaType.IMAGE_PNG);
		try {
			return new ResponseEntity<byte[]>(IOUtils.toByteArray(imageStream), responseHeaders,HttpStatus.OK);
		} catch (Exception e) {
			throw new FlowableException("Error reading image stream", e);
		}
	} else {
		throw new FlowableIllegalArgumentException("Process definition with id '" + processDefinition.getId()+ "' has no image.");
	}
}
 
Example 13
Project: cas-5.1.0   File: GroovyRegisteredServiceUsernameProvider.java   Source Code and License 6 votes vote down vote up
private String resolveUsernameFromExternalGroovyScript(final Principal principal, final Service service) {
    try {
        LOGGER.debug("Found inline groovy script to execute");
        final String script = IOUtils.toString(ResourceUtils.getResourceFrom(this.groovyScript).getInputStream(), StandardCharsets.UTF_8);

        final Object result = getGroovyAttributeValue(principal, script);
        if (result != null) {
            LOGGER.debug("Found username [{}] from script [{}]", result, this.groovyScript);
            return result.toString();
        }
    } catch (final IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    LOGGER.warn("Groovy script [{}] returned no value for username attribute. Fallback to default [{}]",
            this.groovyScript, principal.getId());
    return principal.getId();
}
 
Example 14
Project: cyberduck   File: OneDriveBufferWriteFeatureTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testWriteUnknownLength() throws Exception {
    final OneDriveBufferWriteFeature feature = new OneDriveBufferWriteFeature(session);
    final Path container = new OneDriveHomeFinderFeature(session).find();
    final byte[] content = RandomUtils.nextBytes(5 * 1024 * 1024);
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final HttpResponseOutputStream<Void> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    new StreamCopier(status, status).transfer(in, out);
    in.close();
    out.flush();
    out.close();
    assertNull(out.getStatus());
    assertTrue(new DefaultFindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new OneDriveReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new OneDriveDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 15
Project: libcwfincore   File: JdbiProductEntityDao.java   Source Code and License 6 votes vote down vote up
private String getAllQuery() {
    URL queryLoc = getClass().getResource(getClass().getSimpleName() + "_getAll.sql");
    try {
        return IOUtils.toString(queryLoc, "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
Project: jwala   File: JsonCreateJvmDeserializerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDeserializeJsonCreateJvm() throws Exception {
    final InputStream in = this.getClass().getResourceAsStream("/json-create-jvm-data.json");
    final String jsonData = IOUtils.toString(in, Charset.defaultCharset());

    final ObjectMapper mapper = new ObjectMapper();

    final JsonCreateJvm jsonCreateJvm = mapper.readValue(jsonData, JsonCreateJvm.class);
    assertEquals("my-jvm", jsonCreateJvm.getJvmName());
    assertEquals("some-host", jsonCreateJvm.getHostName());
    assertEquals("jwala", jsonCreateJvm.getUserName());
    assertEquals("/manager", jsonCreateJvm.getStatusPath());
    assertEquals("1", jsonCreateJvm.getJdkMediaId());
    assertTrue(StringUtils.isNotEmpty(jsonCreateJvm.getEncryptedPassword()));
    assertNotEquals("password", jsonCreateJvm.getEncryptedPassword());
    assertEquals("8893", jsonCreateJvm.getAjpPort());
    assertEquals("8889", jsonCreateJvm.getHttpPort());
    assertEquals("8890", jsonCreateJvm.getHttpsPort());
    assertEquals("8891", jsonCreateJvm.getRedirectPort());
    assertEquals("8892", jsonCreateJvm.getShutdownPort());
    assertEquals("1", jsonCreateJvm.getGroupIds().get(0).getGroupId());
}
 
Example 17
Project: smartqq-agreement-core   File: WqqEncryptor.java   Source Code and License 6 votes vote down vote up
/**
 * 计算一些接口的hash值</p>
 * Function: hash</p>
 * <p>Description:</p>
 *
 * @param uin
 * @param ptwebqq
 * @return
 * @author [email protected]
 * @date 2016年12月21日 下午6:25:04
 * @version 1.0
 */
public static String hash(String uin, String ptwebqq) {

    try {
        String jsSources = IOUtils.toString(SourceLoader.getResourceAsInputStream("hash.js"), "utf-8");
        ScriptEngineManager scriptEMgr = new ScriptEngineManager();
        ScriptEngine engine = scriptEMgr.getEngineByMimeType("application/javascript");
        engine.eval(jsSources);
        Invocable invocable = (Invocable) engine;
        // 调用js
        return (String) invocable.invokeFunction("hash", uin, ptwebqq);
    } catch (Exception e) {
        logger.error("计算hash值异常", e);
    }

    return null;
}
 
Example 18
Project: cyberduck   File: CRC32ChecksumCompute.java   Source Code and License 6 votes vote down vote up
@Override
public Checksum compute(final InputStream in, final TransferStatus status) throws ChecksumException {
    final CRC32 crc32 = new CRC32();
    try {
        byte[] buffer = new byte[16384];
        int bytesRead;
        while((bytesRead = in.read(buffer, 0, buffer.length)) != -1) {
            crc32.update(buffer, 0, bytesRead);
        }
    }
    catch(IOException e) {
        throw new ChecksumException(LocaleFactory.localizedString("Checksum failure", "Error"), e.getMessage(), e);
    }
    finally {
        IOUtils.closeQuietly(in);
    }
    return new Checksum(HashAlgorithm.crc32, Long.toHexString(crc32.getValue()));
}
 
Example 19
Project: Moenagade   File: DeferredFileOutputStream.java   Source Code and License 6 votes vote down vote up
/**
 * Writes the data from this output stream to the specified output stream,
 * after it has been closed.
 *
 * @param out output stream to write to.
 * @exception IOException if this stream is not yet closed or an error occurs.
 */
public void writeTo(OutputStream out) throws IOException 
{
    // we may only need to check if this is closed if we are working with a file
    // but we should force the habit of closing wether we are working with
    // a file or memory.
    if (!closed)
    {
        throw new IOException("Stream not closed");
    }
    
    if(isInMemory())
    {
        memoryOutputStream.writeTo(out);
    }
    else
    {
        FileInputStream fis = new FileInputStream(outputFile);
        try {
            IOUtils.copy(fis, out);
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }
}
 
Example 20
Project: syndesis   File: ExtensionsITCase.java   Source Code and License 6 votes vote down vote up
private byte[] extensionData(int prg) throws IOException {
    try (ByteArrayOutputStream data = new ByteArrayOutputStream();
         JarOutputStream jar = new JarOutputStream(data)) {

        JarEntry definition = new JarEntry("META-INF/syndesis/syndesis-extension-definition.json");
        jar.putNextEntry(definition);

        Extension extension = new Extension.Builder()
            .extensionId("com.company:extension" + prg)
            .name("Extension " + prg)
            .description("Extension Description " + prg)
            .version("1.0")
            .build();

        byte[] content = Json.mapper().writeValueAsBytes(extension);
        IOUtils.write(content, jar);
        jar.closeEntry();
        jar.flush();
        return data.toByteArray();
    }
}
 
Example 21
Project: Backmemed   File: SimpleShaderTexture.java   Source Code and License 6 votes vote down vote up
public void loadTexture(IResourceManager resourceManager) throws IOException
{
    this.deleteGlTexture();
    InputStream inputstream = Shaders.getShaderPackResourceStream(this.texturePath);

    if (inputstream == null)
    {
        throw new FileNotFoundException("Shader texture not found: " + this.texturePath);
    }
    else
    {
        try
        {
            BufferedImage bufferedimage = TextureUtil.readBufferedImage(inputstream);
            TextureMetadataSection texturemetadatasection = this.loadTextureMetadataSection();
            TextureUtil.uploadTextureImageAllocate(this.getGlTextureId(), bufferedimage, texturemetadatasection.getTextureBlur(), texturemetadatasection.getTextureClamp());
        }
        finally
        {
            IOUtils.closeQuietly(inputstream);
        }
    }
}
 
Example 22
Project: Geolosys   File: ItemFieldManual.java   Source Code and License 6 votes vote down vote up
@SideOnly(Side.CLIENT)
public int getNumEntries()
{
    String langFile = Minecraft.getMinecraft().gameSettings.language;
    langFile = langFile.substring(0, langFile.indexOf("_")) + langFile.substring(langFile.indexOf("_")).toUpperCase();
    InputStream in = Geolosys.class.getResourceAsStream("/assets/geolosys/book/" + langFile + ".lang");
    int numLines = 0;
    if (in == null)
    {
        langFile = "en_US";
        in = Geolosys.class.getResourceAsStream("/assets/geolosys/lang/" + langFile + ".lang");
    }
    try
    {
        for (String s : IOUtils.readLines(in, "utf-8"))
        {
            if (s.indexOf("=") == -1)
            {
                continue;
            }
            if (s.contains("_title"))
            {
                numLines++;
            }
        }
    }
    catch (IOException e)
    {
    }
    return numLines;
}
 
Example 23
Project: dcmrs-broker   File: MultipartRelatedOutputStream.java   Source Code and License 6 votes vote down vote up
public void addPart(Part part) throws IOException
{
	if (currentPart != null) {
		IOUtils.write("\r\n", out, "UTF-8");
	}

	IOUtils.write("--" + boundary, out, "UTF-8");
	IOUtils.write("\r\n", out, "UTF-8");
	for (String name : part.headers.keySet()) {
		String value = part.headers.get(name);

		IOUtils.write(name + ": " + value, out, "UTF-8");
		IOUtils.write("\r\n", out, "UTF-8");
	}

	IOUtils.write("\r\n", out, "UTF-8");

	currentPart = part;
}
 
Example 24
Project: lams   File: HomeAction.java   Source Code and License 6 votes vote down vote up
public ActionForward getLearningDesignThumbnail(ActionMapping mapping, ActionForm form, HttpServletRequest req,
    HttpServletResponse res) throws IOException {
Long learningDesignId = WebUtil.readLongParam(req, CentralConstants.PARAM_LEARNING_DESIGN_ID);
String imagePath = LearningDesignService.getLearningDesignSVGPath(learningDesignId);
File imageFile = new File(imagePath);
if (!imageFile.canRead()) {
    res.sendError(HttpServletResponse.SC_NOT_FOUND);
    return null;
}

boolean download = WebUtil.readBooleanParam(req, "download", false);
// should the image be downloaded or a part of page?
if (download) {
    String name = getLearningDesignService()
	    .getLearningDesignDTO(learningDesignId, getUser().getLocaleLanguage()).getTitle();
    name += "." + "svg";
    name = FileUtil.encodeFilenameForDownload(req, name);
    res.setContentType("application/x-download");
    res.setHeader("Content-Disposition", "attachment;filename=" + name);
} else {
    res.setContentType("image/svg+xml");
}

FileInputStream input = new FileInputStream(imagePath);
OutputStream output = res.getOutputStream();
IOUtils.copy(input, output);
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);

return null;
   }
 
Example 25
Project: rekit-game   File: ImageManagement.java   Source Code and License 6 votes vote down vote up
/**
 * Try to get image multiple times, as sometimes stream will closes (don't
 * know why).
 *
 * @param nTry
 *            the number of the try
 * @param path
 *            the path
 * @return hopefully the image
 */
private static BufferedImage get(final String path, final int nTry) {
	if (nTry > ImageManagement.MAX_TRIES) {
		return null;
	}
	try {
		Resource icon = ImageManagement.LOAD.getResource(path);
		if (!icon.exists()) {
			GameConf.GAME_LOGGER.error("Icon does not exist.");
			return null;
		}
		// Read data to local buffer.
		ByteArrayInputStream is = new ByteArrayInputStream(IOUtils.toByteArray(icon.getInputStream()));
		return ImageIO.read(is);
	} catch (IOException | NullPointerException | IllegalStateException e) {
		GameConf.GAME_LOGGER.debug(e + " (" + path + "), Image does not exist. Try " + nTry);
		return ImageManagement.get(path, nTry + 1);
	}
}
 
Example 26
Project: sjk   File: ControllerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testbrokenLink() throws IOException, URISyntaxException {

    JSONObject object = new JSONObject();
    object.put("key", "sprSCKKWf8xUeXxEo6Bv0lE1sSjWRDkO");
    object.put("marketName", "eoemarket");
    object.put("count", 1);
    JSONArray data = new JSONArray();
    JSONObject o = new JSONObject();
    o.put("id", -1);
    o.put("link", "http://testsssssss");
    o.put("statusCode", 404);
    data.add(o);
    object.put("data", data);

    Reader input = new StringReader(object.toJSONString());
    byte[] binaryData = IOUtils.toByteArray(input, "UTF-8");
    String encodeBase64 = Base64.encodeBase64String(binaryData);

    String url = "http://localhost:8080/sjk-market/market/brokenLink.d";
    url = "http://app-t.sjk.ijinshan.com/market/brokenLink.d";
    URIBuilder builder = new URIBuilder(url);
    builder.setParameter("c", encodeBase64);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(builder.build());
    HttpResponse response = httpclient.execute(httpPost);
    logger.debug("URI: {} , {}", url, response.getStatusLine());

    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    // be convinient to debug
    String rspJSON = IOUtils.toString(is, "UTF-8");
    System.out.println(rspJSON);
}
 
Example 27
Project: synthea_java   File: CCDAExporterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCCDAExport() throws Exception {
  Config.set("exporter.baseDirectory", tempFolder.newFolder().toString());
  CDAUtil.loadPackages();
  List<String> validationErrors = new ArrayList<String>();

  int numberOfPeople = 10;
  Generator generator = new Generator(numberOfPeople);
  for (int i = 0; i < numberOfPeople; i++) {
    int x = validationErrors.size();
    TestHelper.exportOff();
    Person person = generator.generatePerson(i);
    Config.set("exporter.ccda.export", "true");
    String ccdaXml = CCDAExporter.export(person, System.currentTimeMillis());
    InputStream inputStream = IOUtils.toInputStream(ccdaXml, "UTF-8");
    try {
      CDAUtil.load(inputStream, new BasicValidationHandler() {
        public void handleError(Diagnostic diagnostic) {
          System.out.println("ERROR: " + diagnostic.getMessage());
          validationErrors.add(diagnostic.getMessage());
        }
      });
    } catch (Exception e) {
      e.printStackTrace();
    }
    int y = validationErrors.size();
    if (x != y) {
      Exporter.export(person, System.currentTimeMillis());
    }
  }

  assertEquals(0, validationErrors.size());
}
 
Example 28
Project: Backmemed   File: ResourceIndex.java   Source Code and License 5 votes vote down vote up
public ResourceIndex(File assetsFolder, String indexName)
{
    File file1 = new File(assetsFolder, "objects");
    File file2 = new File(assetsFolder, "indexes/" + indexName + ".json");
    BufferedReader bufferedreader = null;

    try
    {
        bufferedreader = Files.newReader(file2, Charsets.UTF_8);
        JsonObject jsonobject = (new JsonParser()).parse((Reader)bufferedreader).getAsJsonObject();
        JsonObject jsonobject1 = JsonUtils.getJsonObject(jsonobject, "objects", (JsonObject)null);

        if (jsonobject1 != null)
        {
            for (Entry<String, JsonElement> entry : jsonobject1.entrySet())
            {
                JsonObject jsonobject2 = (JsonObject)entry.getValue();
                String s = (String)entry.getKey();
                String[] astring = s.split("/", 2);
                String s1 = astring.length == 1 ? astring[0] : astring[0] + ":" + astring[1];
                String s2 = JsonUtils.getString(jsonobject2, "hash");
                File file3 = new File(file1, s2.substring(0, 2) + "/" + s2);
                this.resourceMap.put(s1, file3);
            }
        }
    }
    catch (JsonParseException var20)
    {
        LOGGER.error("Unable to parse resource index file: {}", new Object[] {file2});
    }
    catch (FileNotFoundException var21)
    {
        LOGGER.error("Can\'t find the resource index file: {}", new Object[] {file2});
    }
    finally
    {
        IOUtils.closeQuietly((Reader)bufferedreader);
    }
}
 
Example 29
Project: BUbiNG   File: ResponseMatches.java   Source Code and License 5 votes vote down vote up
/** Checks whether the response associated with this page matches (in ISO-8859-1 encoding)
 * the regular expression provided at construction time.
 *
 * @return <code>true</code> if the response associated with this page matches (in ISO-8859-1 encoding)
 * the regular expression provided at construction time.
 * @throws NullPointerException if the page has no byte content.
 */
@Override
public boolean apply(final HttpResponse httpResponse) {
	try {
		final InputStream content = httpResponse.getEntity().getContent();
		return pattern.matcher(IOUtils.toString(content, StandardCharsets.ISO_8859_1)).matches();
	}
	catch(IOException shouldntReallyHappen) {
		throw new RuntimeException(shouldntReallyHappen);
	}
}
 
Example 30
Project: sc-generator   File: DocumentController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void upload(MultipartFile file, HttpServletResponse response) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copy(file.getInputStream(), out);
    Swagger swagger = new SwaggerParser()
            .parse(out.toString("utf-8"));
    out.close();
    String content = objectMapper.writeValueAsString(swagger);
    documentService.save(new Document()
            .setContent(content)
            .setTitle(file.getOriginalFilename()));
    applicationEventPublisher.publishEvent(new InstanceRegisteredEvent<>(SwaggerDocDiscovery.class, swagger));
    response.sendRedirect("/#/document.html");
}
 
Example 31
Project: incubator-servicecomb-java-chassis   File: TestInputStreamPart.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws IOException {
  try (InputStream is = part.getInputStream()) {
    byte[] content = IOUtils.toByteArray(is);
    Assert.assertArrayEquals(bytes, content);
  }
}
 
Example 32
Project: hello-spring   File: AwareService.java   Source Code and License 5 votes vote down vote up
public void outputResult() {
	System.out.println("Bean的名称为:" + beanName);
	Resource resource = loader
	                .getResource("classpath:com/zhazhapan/spring/springtest/three/aware/test.txt");
	try {
		System.out.println("ResourceLoader加载人文件内容为:" + IOUtils.toString(resource.getInputStream()));
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 33
Project: java-natives   File: NativeLibrary.java   Source Code and License 5 votes vote down vote up
private File extractNativeLibraries(final File nativesDirectory, final String libraryPath) {
  final URL libraryUrl = Thread.currentThread().getContextClassLoader().getResource(libraryPath);
  if (libraryUrl == null) {
    throw new IllegalArgumentException(
        String.format("Unable to find native binary %s for library %s", libraryPath, key));
  }
  final String libraryName;
  libraryName = FilenameUtils.getName(libraryPath);
  final File libraryFile = new File(nativesDirectory, libraryName);
  libraryFile.getParentFile().mkdirs();
  try {
    final URLConnection urlConnection = libraryUrl.openConnection();
    try (final InputStream inputStream = urlConnection.getInputStream()) {
      try (final OutputStream outputStream =
          new BufferedOutputStream(new FileOutputStream(libraryFile))) {
        IOUtils.copy(inputStream, outputStream);
      }
    }
  } catch (final Exception exception) {
    throw new RuntimeException(exception);
  }
  if (deleteOnExit) {
    libraryFile.deleteOnExit();
  }
  // TODO make accessible for linux and mac
  return libraryFile;
}
 
Example 34
Project: Reer   File: GZipTaskOutputPacker.java   Source Code and License 5 votes vote down vote up
@Override
public void pack(TaskOutputsInternal taskOutputs, OutputStream output, TaskOutputOriginWriter writeOrigin) {
    GZIPOutputStream gzipOutput = createGzipOutputStream(output);
    try {
        delegate.pack(taskOutputs, gzipOutput, writeOrigin);
    } finally {
        IOUtils.closeQuietly(gzipOutput);
    }
}
 
Example 35
Project: nfse   File: GerarLoteRpsRespostaTest.java   Source Code and License 5 votes vote down vote up
@Test
public void quandoSucessoPojoDeveSerGeradoCorretamente() throws IOException {
  String xmlTest = IOUtils
      .toString(getClass().getClassLoader().getResourceAsStream("consultarLoteRpsResposta.xml"));

  ConsultarLoteRpsResposta pojo = ConsultarLoteRpsResposta.toPojo(xmlTest);
  assertNotNull(pojo.getListaNfse());
  assertNotNull(pojo.getListaNfse().getCompNfse().get(0));
  assertNotNull(pojo.getListaNfse().getCompNfse().get(0).getNfse());
  assertNotNull(pojo.getListaNfse().getCompNfse().get(0).getNfse().getInfNfse());
}
 
Example 36
Project: galop   File: ServerImpl.java   Source Code and License 5 votes vote down vote up
private synchronized void handleNewConnection(final Socket source, final Socket target) {
    if (!serverSocket.isClosed()) {
        final ConnectionHandler handler = connectionHandlerFactory.create(source, target);
        connectionHandlers.add(handler);
        executorService.execute(handler);
    } else {
        IOUtils.closeQuietly(source);
        IOUtils.closeQuietly(target);
    }

}
 
Example 37
Project: coffee-gb   File: FileBattery.java   Source Code and License 5 votes vote down vote up
private void saveClock(long[] clockData, OutputStream os) throws IOException {
    byte[] byteBuff = new byte[4 * clockData.length];
    ByteBuffer buff = ByteBuffer.wrap(byteBuff);
    buff.order(ByteOrder.LITTLE_ENDIAN);
    for (long d : clockData) {
        buff.putInt((int) d);
    }
    IOUtils.write(byteBuff, os);
}
 
Example 38
Project: cyberduck   File: CopyWorkerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCopyFile() throws Exception {
    final Host host = new Host(new FTPTLSProtocol(), "test.cyberduck.ch", new Credentials(
            System.getProperties().getProperty("ftp.user"), System.getProperties().getProperty("ftp.password")
    ));
    final FTPSession session = new FTPSession(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new DefaultHomeFinderService(session).find();
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final Path source = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final Path target = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore());
    cryptomator.create(session, null, new VaultCredentials("test"));
    final DefaultVaultRegistry registry = new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator);
    session.withRegistry(registry);
    final byte[] content = RandomUtils.nextBytes(40500);
    final TransferStatus status = new TransferStatus();
    new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new FTPDeleteFeature(session), cryptomator).pre(Transfer.Type.upload, Collections.singletonMap(source, status), new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), new CryptoWriteFeature<>(session, new FTPWriteFeature(session), cryptomator).write(source, status.length(content.length), new DisabledConnectionCallback()));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    final FTPSession copySession = new FTPSession(host);
    copySession.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    copySession.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final CopyWorker worker = new CopyWorker(Collections.singletonMap(source, target), new TestSessionPool(copySession, registry), PathCache.empty(), new DisabledProgressListener(), new DisabledConnectionCallback());
    worker.run(session);
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(target));
    final ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
    final InputStream in = new CryptoReadFeature(session, new FTPReadFeature(session), cryptomator).read(target, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    assertEquals(content.length, IOUtils.copy(in, out));
    assertArrayEquals(content, out.toByteArray());
    in.close();
    new DeleteWorker(new DisabledLoginCallback(), Collections.singletonList(vault), PathCache.empty(), new DisabledProgressListener()).run(session);
    session.close();
}
 
Example 39
Project: gate-core   File: TestResourceReference.java   Source Code and License 5 votes vote down vote up
public void testReadFromURL() throws Exception {

    URL url = getClass().getClassLoader()
        .getResource("gate/resources/gate.ac.uk/creole/creole.xml");
    ResourceReference rr = new ResourceReference(url);

    try (InputStream in = rr.openStream()) {
      String contents = IOUtils.toString(in);

      assertEquals("Length of data read not as expected", 98,
          contents.length());
    }
  }
 
Example 40
Project: Autotip   File: Hosts.java   Source Code and License 5 votes vote down vote up
public static void updateHosts() {
    Gson gson = new GsonBuilder().setPrettyPrinting()
            .disableHtmlEscaping()
            .create();
    try {
        String json = IOUtils.toString(
                new URL("https://gist.githubusercontent.com/Semx11/35d6b58783ef8d0527f82782f6555834/raw/hosts.json"));
        instance = gson.fromJson(json, Hosts.class);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 41
Project: cyoastudio   File: ProjectSerializer.java   Source Code and License 5 votes vote down vote up
public static Version readFileVersion(Path target) throws IOException {
	final byte[] data = ZipUtil.unpackEntry(target.toFile(), PROJECT_VERSION_FILENAME);
	if (data == null) {
		// Best guess, since the actual version information is hidden inside the JSON
		return Version.forIntegers(0, 2, 2);
	} else {
		InputStream stream = new ByteArrayInputStream(data);
		return Version.valueOf(IOUtils.toString(stream, Charset.forName("UTF-8")));
	}
}
 
Example 42
Project: cyberduck   File: B2ReadFeatureTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testReadRange() 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(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());

    final Path bucket = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path test = new Path(bucket, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    new B2TouchFeature(session).touch(test, new TransferStatus());

    final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    final byte[] content = RandomUtils.nextBytes(1000);
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);
    IOUtils.write(content, out);
    out.close();
    new B2SingleUploadService(new B2WriteFeature(session)).upload(
            test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
            new TransferStatus().length(content.length),
            new DisabledConnectionCallback());
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    status.setAppend(true);
    status.setOffset(100L);
    final InputStream in = new B2ReadFeature(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 B2DeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 43
Project: sql-first-mapper   File: TemplateUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Get velocity template by query name and package name, reads file from resources and returns as string
 *
 * @param packageName name of package
 * @param queryName name of query
 * @return string with velocity template file contents
 */
public static String getTemplate(String packageName, String queryName) {
    String resourceName = packageName.replace(".", "/") + "/sql/" + queryName + ".sql";
    InputStream inputStream = TemplateUtils.class.getClassLoader().getResourceAsStream(resourceName);
    try {
        return IOUtils.toString(inputStream);
    } catch (Exception e) {
        throw new RuntimeException("Unable to find " + resourceName, e);
    }
}
 
Example 44
Project: cyberduck   File: CopyWorkerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCopyFile() throws Exception {
    final Host host = new Host(new DAVProtocol(), "test.cyberduck.ch", new Credentials(
            System.getProperties().getProperty("webdav.user"), System.getProperties().getProperty("webdav.password")
    ));
    host.setDefaultPath("/dav/basic");
    final DAVSession session = new DAVSession(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new DefaultHomeFinderService(session).find();
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final Path source = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final Path target = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore());
    cryptomator.create(session, null, new VaultCredentials("test"));
    final DefaultVaultRegistry registry = new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator);
    session.withRegistry(registry);
    final byte[] content = RandomUtils.nextBytes(40500);
    final TransferStatus status = new TransferStatus();
    new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new DAVDeleteFeature(session), cryptomator).pre(Transfer.Type.upload, Collections.singletonMap(source, status), new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), new CryptoWriteFeature<>(session, new DAVWriteFeature(session), cryptomator).write(source, status.length(content.length), new DisabledConnectionCallback()));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    final CopyWorker worker = new CopyWorker(Collections.singletonMap(source, target), new TestSessionPool(session, registry), PathCache.empty(), new DisabledProgressListener(), new DisabledConnectionCallback());
    worker.run(session);
    assertTrue(new CryptoFindFeature(session, new DAVFindFeature(session), cryptomator).find(source));
    assertTrue(new CryptoFindFeature(session, new DAVFindFeature(session), cryptomator).find(target));
    final ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
    assertEquals(content.length, IOUtils.copy(new CryptoReadFeature(session, new DAVReadFeature(session), cryptomator).read(target, new TransferStatus().length(content.length), new DisabledConnectionCallback()), out));
    assertArrayEquals(content, out.toByteArray());
    new DeleteWorker(new DisabledLoginCallback(), Collections.singletonList(vault), PathCache.empty(), new DisabledProgressListener()).run(session);
    session.close();
}
 
Example 45
Project: azeroth   File: QiniuProvider.java   Source Code and License 5 votes vote down vote up
@Override
public String upload(String catalog, String fileName, InputStream in, FileType fileType) {
    try {
        byte[] bs = IOUtils.toByteArray(in);
        return upload(catalog, fileName, bs, fileType);
    } catch (IOException e) {
        throw new FSOperErrorException(name(), e);
    }
}
 
Example 46
Project: q-mail   File: AttachmentController.java   Source Code and License 5 votes vote down vote up
private void writeAttachmentToStorage(File file) throws IOException {
    InputStream in = context.getContentResolver().openInputStream(attachment.internalUri);
    try {
        OutputStream out = new FileOutputStream(file);
        try {
            IOUtils.copy(in, out);
            out.flush();
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}
 
Example 47
Project: q-mail   File: MigrationTest.java   Source Code and License 5 votes vote down vote up
private void copyAttachmentFromFile(String resourceName, int attachmentId, int expectedFilesize) throws IOException {
    File resourceFile = new File(getClass().getResource("/attach/" + resourceName).getFile());
    File attachmentFile = new File(attachmentDir, Integer.toString(attachmentId));
    BufferedInputStream input = new BufferedInputStream(new FileInputStream(resourceFile));
    BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(attachmentFile));
    int copied = IOUtils.copy(input, output);
    input.close();
    output.close();
    Assert.assertEquals(expectedFilesize, copied);
}
 
Example 48
Project: java-pwa   File: MyUI.java   Source Code and License 5 votes vote down vote up
@Override
protected void servletInitialized() throws ServletException {
	super.servletInitialized();

          HeaderTagHandler.init(getService());
	
	getService().addSessionInitListener(new SessionInitListener() {

		@Override
		public void sessionInit(SessionInitEvent event) throws ServiceException {
			event.getSession().addRequestHandler(new RequestHandler() {

				@Override
				public boolean handleRequest(VaadinSession session, VaadinRequest request,
						VaadinResponse response) throws IOException {

					String pathInfo = request.getPathInfo();
					InputStream in = null;

					if (pathInfo.endsWith("sw.js")) {
						response.setContentType("application/javascript");
						in = getClass().getResourceAsStream("/sw.js");
					}

					if (in != null) {
						OutputStream out = response.getOutputStream();
						IOUtils.copy(in, out);
						in.close();
						out.close();

						return true;
					} else {

						return false;
					}
				}
			});
		}
	});
}
 
Example 49
Project: file-type-plugin   File: FileType.java   Source Code and License 5 votes vote down vote up
private String verifyPossibleUtf8(String charsetName, InputStream inputStream) throws IOException {
  if (!FileType.DEFAULT_ENCODING.equals(charsetName)
          && isValidUtf8(IOUtils.toByteArray(inputStream))) {
    FileType.logger.log(Level.INFO, "Vai mudar o encoding de {0} para o default", charsetName);
    return FileType.DEFAULT_ENCODING;
  }
  return charsetName;
}
 
Example 50
Project: cyberduck   File: B2LargeUploadWriteFeatureTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testWriteZeroLength() 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(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final B2LargeUploadWriteFeature feature = new B2LargeUploadWriteFeature(session);
    final Path container = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final byte[] content = RandomUtils.nextBytes(0);
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final StatusOutputStream<VersionId> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    assertEquals(content.length, IOUtils.copyLarge(in, out));
    in.close();
    out.close();
    assertNotNull(out.getStatus());
    assertTrue(new DefaultFindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new B2ReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new B2DeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 51
Project: bromium   File: JavascriptInjectionPreparator.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an object which can be used to inject javascript in HTML code.
 * @param reader the reader from which the generated javascript is read
 * @throws IOException if exception happens while reading from the {@link Reader} to {@link String}
 */
public JavascriptInjectionPreparator(Reader reader) throws IOException {
    this.injectionCode = "<script>" +
            "(function() {" + System.lineSeparator() +
            IOUtils.toString(reader) +
            System.lineSeparator() + "})();" +
            "</script>";
}
 
Example 52
Project: bootstrap   File: ClassPathResourceMultipleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetInputStream1Path() throws IOException {
	final ClassPathResourceMultiple resource = new ClassPathResourceMultiple("csv/demo", dummyminus.class);
	InputStream stream = resource.getInputStream();
	Assert.assertNotNull(stream);
	IOUtils.closeQuietly(stream);
}
 
Example 53
Project: phoenix.webui.suite.runner   File: SuiteRunnerLauncher.java   Source Code and License 5 votes vote down vote up
/**
 * @param urlList
 * @throws IOException 
 * @throws UnsupportedEncodingException 
 */
private static void runnerRead(List<URL> urlList) throws UnsupportedEncodingException, IOException
{
	InputStream inputA = SuiteRunnerLauncher.class.getResourceAsStream("/");
	if(inputA == null)
	{
		return;
	}
	
	BufferedReader reader = new BufferedReader(new InputStreamReader(inputA));
	String line = null;
	while((line = reader.readLine()) != null)
	{
		URL itemUrl = SuiteRunnerLauncher.class.getResource("/" + line);
		if(itemUrl == null)
		{
			continue;
		}
		String path = URLDecoder.decode(itemUrl.getFile(), "utf-8");
		if(!path.endsWith(".xml"))
		{
			continue;
		}
		
		try(InputStream input = itemUrl.openStream())
		{
			byte[] content = IOUtils.toByteArray(input);
			if(SuiteUtils.isSuiteXml(content))
			{
				urlList.add(itemUrl);
			}
		}
	}
}
 
Example 54
Project: plugin-id-ldap   File: CsvStreamingOutputTest.java   Source Code and License 5 votes vote down vote up
@Test
public void write() throws IOException {
	final ActivitiesComputations computations = new ActivitiesComputations();

	// Nodes
	final Collection<INamableBean<String>> nodes = new ArrayList<>();
	final NamedBean<String> node1 = new NamedBean<>();
	nodes.add(node1);
	node1.setId("J0");
	node1.setName("J0N");
	final NamedBean<String> node2 = new NamedBean<>();
	nodes.add(node2);
	node2.setId("J1");
	node2.setName("J1N");
	computations.setNodes(nodes);

	// Activities
	final Map<String, Map<String, Activity>> activities = new HashMap<>();
	final Map<String, Activity> userActivities = new HashMap<>();
	activities.put("U0", userActivities);
	final Activity activity1 = new Activity();
	activity1.setLastConnection(new Date(0));
	userActivities.put("J0", activity1);
	computations.setActivities(activities);

	// Users
	final Collection<UserOrg> users = new ArrayList<>();
	final UserOrg user = new UserOrg();
	user.setFirstName("F0");
	user.setLastName("L0");
	user.setId("U0");
	user.setMails(new ArrayList<>());
	users.add(user);
	final UserOrg user2 = new UserOrg();
	user2.setFirstName("F1");
	user2.setLastName("L1");
	user2.setId("U1");
	user2.setMails(Arrays.asList("M1", "M2"));
	users.add(user2);
	computations.setUsers(users);

	// Call
	final ByteArrayOutputStream out = new ByteArrayOutputStream();
	new CsvStreamingOutput(computations).write(out);
	final List<String> lines = IOUtils.readLines(new ByteArrayInputStream(out.toByteArray()), StandardCharsets.UTF_8);

	// Check
	Assert.assertEquals(3, lines.size());
	Assert.assertEquals("user;firstName;lastName;mail;J0N;J1N", lines.get(0));
	Assert.assertEquals("U0;F0;L0;;1970/01/01 01:00:00;", lines.get(1));
	Assert.assertEquals("U1;F1;L1;M1", lines.get(2));

}
 
Example 55
Project: ureport   File: ResourceLoaderServletAction.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String path=req.getContextPath()+UReportServlet.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 if(p.endsWith(".svg")){
		resp.setContentType("image/svg+xml");			
	}else{
		resp.setContentType("application/octet-stream");
	}
	InputStream input=applicationContext.getResource(p).getInputStream();
	OutputStream output=resp.getOutputStream();
	try{
		IOUtils.copy(input, output);			
	}finally{
		IOUtils.closeQuietly(input);
		IOUtils.closeQuietly(output);
	}
}
 
Example 56
Project: plugin-vm-vcloud   File: VCloudPluginResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getConsole() throws Exception {
	prepareMockHome();
	httpServer.stubFor(get(urlPathEqualTo("/api/vApp/vm-75aa69b4-8cff-40cd-9338-9abafc7d5935/screen"))
			.willReturn(aResponse().withStatus(HttpStatus.SC_OK).withBody(IOUtils.toString(
					new ClassPathResource("mock-server/vcloud/vcloud-console.png").getInputStream(), StandardCharsets.UTF_8))));
	httpServer.start();

	final StreamingOutput imageStream = resource.getConsole(subscription);
	final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	imageStream.write(outputStream);
	Assert.assertTrue(outputStream.toByteArray().length > 1024);
}
 
Example 57
Project: hadoop   File: TestQueuePlacementPolicy.java   Source Code and License 5 votes vote down vote up
private QueuePlacementPolicy parse(String str) throws Exception {
  // Read and parse the allocations file.
  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
      .newInstance();
  docBuilderFactory.setIgnoringComments(true);
  DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
  Document doc = builder.parse(IOUtils.toInputStream(str));
  Element root = doc.getDocumentElement();
  return QueuePlacementPolicy.fromXml(root, configuredQueues, conf);
}
 
Example 58
Project: fake-smtp-server   File: TestResourceUtil.java   Source Code and License 5 votes vote down vote up
public static byte[] getTestFileContentBytes(String testFilename) throws IOException {
    return IOUtils.toByteArray(getTestFile(testFilename));
}
 
Example 59
Project: matrix-appservice-email   File: GmailClientFormatterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPlain() throws IOException {
    File f = new File("src/test/resources/gmailContent.txt");
    assertTrue(f.getAbsolutePath(), f.canRead());

    String output = formatter.formatPlain(IOUtils.toString(new FileReader(f)));
    assertTrue(output, "a".contentEquals(output));
}
 
Example 60
Project: GitHub   File: TestExternal.java   Source Code and License 5 votes vote down vote up
public ExtClassLoader() throws IOException{
    super(Thread.currentThread().getContextClassLoader());
    
    byte[] bytes;
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("external/VO.clazz");
    bytes = IOUtils.toByteArray(is);
    is.close();
    
    super.defineClass("external.VO", bytes, 0, bytes.length);
}