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); } }
@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; } }
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; }
@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(); }
@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(); } }
@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."); } }
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(); }
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; }
@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()); }
@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)); }
@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()); }
@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())); }
/** * 从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); } }
/** * 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); } } }
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(); } }
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); } } }
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; }
@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); } }
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); } }
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; }
/** * 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); } }
@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); }
@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()); }
/** * 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(); }
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); } }
/** 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); } }
@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"); }
@Test public void test() throws IOException { try (InputStream is = part.getInputStream()) { byte[] content = IOUtils.toByteArray(is); Assert.assertArrayEquals(bytes, content); } }
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(); } }
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; }
@Override public void pack(TaskOutputsInternal taskOutputs, OutputStream output, TaskOutputOriginWriter writeOrigin) { GZIPOutputStream gzipOutput = createGzipOutputStream(output); try { delegate.pack(taskOutputs, gzipOutput, writeOrigin); } finally { IOUtils.closeQuietly(gzipOutput); } }
@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()); }
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); } }
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); }
@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(); }
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()); } }
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(); } }
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"))); } }
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); } }