List of usage examples for java.io InputStream available
public int available() throws IOException
From source file:EditorDropTarget2.java
protected boolean dropContent(Transferable transferable, DropTargetDropEvent dtde) { if (!pane.isEditable()) { // Can't drop content on a read-only text control return false; }//from w w w . j ava 2 s. c o m try { // Check for a match with the current content type DataFlavor[] flavors = dtde.getCurrentDataFlavors(); DataFlavor selectedFlavor = null; // Look for either plain text or a String. for (int i = 0; i < flavors.length; i++) { DataFlavor flavor = flavors[i]; if (flavor.equals(DataFlavor.plainTextFlavor) || flavor.equals(DataFlavor.stringFlavor)) { selectedFlavor = flavor; break; } } if (selectedFlavor == null) { // No compatible flavor - should never happen return false; } DnDUtils.debugPrintln("Selected flavor is " + selectedFlavor.getHumanPresentableName()); // Get the transferable and then obtain the data Object data = transferable.getTransferData(selectedFlavor); DnDUtils.debugPrintln("Transfer data type is " + data.getClass().getName()); String insertData = null; if (data instanceof InputStream) { // Plain text flavor String charSet = selectedFlavor.getParameter("charset"); InputStream is = (InputStream) data; byte[] bytes = new byte[is.available()]; is.read(bytes); try { insertData = new String(bytes, charSet); } catch (UnsupportedEncodingException e) { // Use the platform default encoding insertData = new String(bytes); } } else if (data instanceof String) { // String flavor insertData = (String) data; } if (insertData != null) { int selectionStart = pane.getCaretPosition(); pane.replaceSelection(insertData); pane.select(selectionStart, selectionStart + insertData.length()); return true; } return false; } catch (Exception e) { return false; } }
From source file:com.mycollab.module.ecm.service.impl.ResourceServiceImpl.java
@Override public void saveContent(Content content, String createdUser, InputStream refStream, Integer sAccountId) { Integer fileSize = 0;/*from w w w .ja v a 2 s.com*/ if (sAccountId != null) { try { fileSize = refStream.available(); billingPlanCheckerService.validateAccountCanUploadMoreFiles(sAccountId, fileSize); } catch (IOException e) { LOG.error("Can not get available bytes", e); } } // detect mimeType and set to content String mimeType = MimeTypesUtil.detectMimeType(content.getPath()); content.setMimeType(mimeType); content.setSize(Long.valueOf(fileSize)); String contentPath = content.getPath(); rawContentService.saveContent(contentPath, refStream); if (MimeTypesUtil.isImage(mimeType)) { try (InputStream newInputStream = rawContentService.getContentStream(contentPath)) { BufferedImage image = ImageUtil.generateImageThumbnail(newInputStream); if (image != null) { String thumbnailPath = String.format(".thumbnail/%d/%s.%s", sAccountId, StringUtils.generateSoftUniqueId(), "png"); File tmpFile = File.createTempFile("tmp", "png"); ImageIO.write(image, "png", new FileOutputStream(tmpFile)); rawContentService.saveContent(thumbnailPath, new FileInputStream(tmpFile)); content.setThumbnail(thumbnailPath); } } catch (IOException e) { LOG.error("Error when generating thumbnail", e); } } contentJcrDao.saveContent(content, createdUser); SaveContentEvent event = new SaveContentEvent(content, createdUser, sAccountId); asyncEventBus.post(event); }
From source file:io.github.infolis.algorithm.RegexSearcher.java
private List<TextualReference> searchForPatterns(InfolisFile file) throws IOException { String inputClean = getFileAsString(file); List<TextualReference> res = new ArrayList<>(); for (String patternURI : this.getExecution().getPatterns()) { //debug(log, patternURI); log.trace(patternURI);// w ww . j av a2 s .c o m InfolisPattern pattern = getInputDataStoreClient().get(InfolisPattern.class, patternURI); //debug(log, "Searching for pattern '%s'", pattern.getPatternRegex()); log.trace("Searching for pattern '%s'", pattern.getPatternRegex()); Pattern p = Pattern.compile(pattern.getPatternRegex()); // set upper limit for processing time - prevents stack overflow // caused by monitoring process // (LimitedTimeMatcher) // 750000 suitable for -Xmx2g -Xms2g // processing time for documents depends on size of the document. // Allow 1024 milliseconds per KB InputStream openInputStream = getInputFileResolver().openInputStream(file); long maxTimeMillis = Math.min(75_000, openInputStream.available()); openInputStream.close(); // call m.find() as a thread: catastrophic backtracking may occur // which causes application to hang // thus monitor runtime of threat and terminate if processing takes // too long LimitedTimeMatcher ltm = new LimitedTimeMatcher(p, inputClean, maxTimeMillis, file.getFileName() + "\n" + pattern.getPatternRegex()); ltm.run(); // thread was aborted due to long processing time if (!ltm.finished()) { // TODO: what to do if search was aborted? log.error("Search was aborted. TODO"); // InfolisFileUtils.writeToFile(new // File("data/abortedMatches.txt"), "utf-8", filenameIn + ";" + // curPat + "\n", true); } while (ltm.matched()) { String context = ltm.group(); String studyName = ltm.group(1).trim(); log.debug("found pattern " + pattern.getPatternRegex() + " in " + file); log.debug("referenced study name: " + studyName); // if studyname contains no characters: ignore // TODO: not accurate - include accents etc in match... \p{M}? if (studyName.matches("\\P{L}+")) { log.debug("Invalid study name \"" + studyName + "\". Searching for next match of pattern " + pattern.getPatternRegex()); ltm.run(); continue; } // a study name is supposed to be a named entity and thus should // contain at least one upper-case character if (this.getExecution().isUpperCaseConstraint()) { if (studyName.toLowerCase().equals(studyName)) { ltm.run(); log.debug("Match does not satisfy uppercase-constraint \"" + studyName + "\". Processing new match..."); continue; } } List<TextualReference> references = SearchTermPosition.getContexts(getOutputDataStoreClient(), file.getUri(), studyName, context); for (TextualReference ref : references) { ref.setPattern(pattern.getUri()); log.debug("added reference: " + ref); } res.addAll(references); log.trace("Added references."); log.trace("Searching for next match of pattern " + pattern.getPatternRegex()); ltm.run(); } } log.trace("Done searching for patterns in " + file); return res; }
From source file:org.esupportail.papercut.services.PayBoxService.java
public void setDerPayboxPublicKeyFile(String derPayboxPublicKeyFile) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { org.springframework.core.io.Resource derPayboxPublicKeyRessource = new ClassPathResource( derPayboxPublicKeyFile);/* w ww . j av a 2 s .c o m*/ InputStream fis = derPayboxPublicKeyRessource.getInputStream(); DataInputStream dis = new DataInputStream(fis); byte[] pubKeyBytes = new byte[fis.available()]; dis.readFully(pubKeyBytes); fis.close(); dis.close(); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKeyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); this.payboxPublicKey = kf.generatePublic(x509EncodedKeySpec); }
From source file:algorithm.OpenStegoRandomLSBSteganography.java
@Override public List<RestoredFile> restore(File carrier) throws IOException { List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>(); File tmpDir = new File("tmpDir"); tmpDir.mkdir();/*from w ww . j a va2 s.c om*/ try { String[] args = new String[] { "java", "-jar", LIBRARY_DIRECTORY + "openstego.jar", "extract", "-a", "RandomLSB", "-sf", "" + carrier.toPath(), "-xd", "" + tmpDir.toPath() }; Process process = Runtime.getRuntime().exec(args); process.waitFor(); InputStream inputStream = process.getInputStream(); byte b[] = new byte[inputStream.available()]; inputStream.read(b, 0, b.length); } catch (InterruptedException e) { e.printStackTrace(); } String originalCarrierPath = ""; if (tmpDir.listFiles().length == 1) { File tmpMessage = tmpDir.listFiles()[0]; byte[] payloadSegmentBytes = FileUtils.readFileToByteArray(tmpMessage); PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(payloadSegmentBytes); RestoredFile message = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName()); message.originalFilePath = payloadSegment.getPayloadPath(); originalCarrierPath = payloadSegment.getCarrierPath(); FileUtils.writeByteArrayToFile(message, payloadSegment.getPayloadBytes()); message.validateChecksum(payloadSegment.getPayloadChecksum()); message.restorationNote = "Payload can be restored correctly."; message.wasPayload = true; restoredFiles.add(message); } FileUtils.forceDelete(tmpDir); RestoredFile copiedCarrier = new RestoredFile(RESTORED_DIRECTORY + carrier.getName()); FileUtils.copyFile(carrier, copiedCarrier); copiedCarrier.wasCarrier = true; copiedCarrier.checksumValid = false; copiedCarrier.restorationNote = "The carrier can't be restored with this steganography algorithm. It still contains the embedded payload file(s)."; copiedCarrier.originalFilePath = originalCarrierPath; restoredFiles.add(copiedCarrier); // The carrier can not be restored; for (RestoredFile file : restoredFiles) { file.algorithm = this; for (RestoredFile relatedFile : restoredFiles) { if (file != relatedFile) { file.relatedFiles.add(relatedFile); } } } return restoredFiles; }
From source file:com.clican.pluto.transaction.resources.memory.XAFileResourceMemoryImpl.java
public int prepare(Xid xid) throws XAException { InputStream is = null; try {// ww w .j av a2 s. c o m if (file.exists()) { is = new FileInputStream(file); byte[] data = new byte[is.available()]; is.read(data); oldDataMapping.put(xid, data); } else { oldDataMapping.put(xid, null); } } catch (Exception e) { log.error("", e); throw new XAException(XAException.XA_RBBASE); } finally { if (is != null) { try { is.close(); } catch (Exception e) { log.error("", e); } } } return XA_OK; }
From source file:com.google.blockly.android.codegen.CodeGeneratorService.java
private String loadAssetAsUtf8(String filename) throws IOException { InputStream input = null; try {//from ww w . ja v a2 s. c o m input = getAssets().open(filename); int size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); return new String(buffer, "UTF-8"); } catch (IOException e) { throw new IllegalArgumentException("Couldn't find asset file \"" + mDefinitions + "\""); } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.w(TAG, "Unable to close asset file \"" + filename + "\"", e); } } } }
From source file:com.easibeacon.examples.shop.MainActivity.java
public String loadJSONFromAsset() { String json = null;// w w w. j a v a 2 s. c o m try { InputStream is = getAssets().open("monuments.js"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; }
From source file:com.betfair.testing.utils.cougar.manager.CougarManagerTest.java
@Test public void sendPostRestRequest_Test() throws ParserConfigurationException, SAXException, IOException { String POSTQUERY = "<ComplexObject><name>sum</name><value1>7</value1><value2>75</value2></ComplexObject>"; //String expRestXMLRequestBody = "<ComplexObject xmlns=\"http://www.betfair.com/servicetypes/v2/Baseline/\"><name>sum</name><value1>7</value1><value2>75</value2></ComplexObject>"; String operationName = "someOperation"; String requestWrapper = "SomeOperationRequest"; String expRestXMLRequestBody = "<" + requestWrapper + " xmlns=\"http://www.betfair.com/servicetypes/v2/Baseline/\"><complexObject><name>sum</name><value1>7</value1><value2>75</value2></complexObject></" + requestWrapper + ">"; //String expRestJSONRequestBody = "{\"name\":\"sum\",\"value1\":7,\"value2\":75}" ; String expRestJSONRequestBody = "{\"complexObject\":{\"name\":\"sum\",\"value1\":7,\"value2\":75}}"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(POSTQUERY))); HttpCallBean httpCallBean = new HttpCallBean(); httpCallBean.setOperationName(operationName); httpCallBean.setServiceName("Baseline"); httpCallBean.setVersion("v2"); httpCallBean.setQueryParams(null);/*w w w . ja va2s .co m*/ httpCallBean.setHeaderParams(null); httpCallBean.setRestPostQueryObjects(document); cougarManager.makeRestCougarHTTPCalls(httpCallBean); List<HttpUriRequest> methodsSent = cougarTestDAO.methods; HttpPost methodSent; methodSent = (HttpPost) methodsSent.get(0); assertNull(methodSent.getURI().getQuery()); assertEquals("/Baseline/v2/" + operationName, methodSent.getURI().getPath()); Header[] headers = methodSent.getAllHeaders(); assertEquals(4, headers.length); assertEquals("Content-Type: application/json", String.valueOf(headers[0])); assertEquals("User-Agent: java/socket", String.valueOf(headers[1])); assertEquals("Accept: application/json", String.valueOf(headers[2])); //Changed this from 37... //assertEquals("Content-Length: 55", String.valueOf(headers[3])); assertEquals("X-Forwarded-For: 87.248.113.14", String.valueOf(headers[3])); StringEntity stringRequestEntity = (StringEntity) methodSent.getEntity(); InputStream inputStream = stringRequestEntity.getContent(); byte[] buffer = new byte[inputStream.available()]; int offset = 0; int read; while ((read = inputStream.read(buffer, offset, inputStream.available())) != -1) { offset += read; } assertEquals(expRestJSONRequestBody, new String(buffer, "UTF-8")); methodSent = (HttpPost) methodsSent.get(2); assertNull(methodSent.getURI().getQuery()); assertEquals("/Baseline/v2/" + operationName, methodSent.getURI().getPath()); headers = methodSent.getAllHeaders(); assertEquals(4, headers.length); stringRequestEntity = (StringEntity) methodSent.getEntity(); inputStream = stringRequestEntity.getContent(); buffer = new byte[inputStream.available()]; offset = 0; while ((read = inputStream.read(buffer, offset, inputStream.available())) != -1) { offset += read; } assertEquals(expRestXMLRequestBody, new String(buffer, "UTF-8")); assertEquals("Content-Type: application/xml", String.valueOf(headers[0])); assertEquals("User-Agent: java/socket", String.valueOf(headers[1])); assertEquals("Accept: application/xml", String.valueOf(headers[2])); //assertEquals("Content-Length: 141", String.valueOf(headers[3])); //assertEquals("Content-Length: 186", String.valueOf(headers[3])); assertEquals("X-Forwarded-For: 87.248.113.14", String.valueOf(headers[3])); }
From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException { try {//from w w w.ja v a 2s . c om SSLSession session = sslsock.getSession(); if (session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server' // chain. Hopefully this will unearth the real problem: final InputStream in = sslsock.getInputStream(); in.available(); // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = sslsock.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. sslsock.startHandshake(); session = sslsock.getSession(); } } if (session == null) { throw new SSLHandshakeException("SSL session not available"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Secure session established"); LOGGER.debug(" negotiated protocol: {}", session.getProtocol()); LOGGER.debug(" negotiated cipher suite: {}", session.getCipherSuite()); try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal peer = x509.getSubjectX500Principal(); LOGGER.debug(" peer principal: {}", peer); final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames(); if (altNames1 != null) { final List<String> altNames = new ArrayList<>(); for (final List<?> aC : altNames1) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } LOGGER.debug(" peer alternative names: {}", altNames); } final X500Principal issuer = x509.getIssuerX500Principal(); LOGGER.debug(" issuer principal: {}", issuer); final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames(); if (altNames2 != null) { final List<String> altNames = new ArrayList<>(); for (final List<?> aC : altNames2) { if (!aC.isEmpty()) { altNames.add((String) aC.get(1)); } } LOGGER.debug(" issuer alternative names: {}", altNames); } } catch (Exception ignore) { } } if (!this.hostnameVerifier.verify(hostname, session)) { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; final X500Principal x500Principal = x509.getSubjectX500Principal(); throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match " + "the certificate subject provided by the peer (" + x500Principal.toString() + ")"); } // verifyHostName() didn't blowup - good! } catch (RuntimeException | IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (final Exception x) { iox.addSuppressed(x); } throw iox; } }