List of usage examples for java.io ByteArrayOutputStream flush
public void flush() throws IOException
From source file:com.marklogic.xcc.ContentFactory.java
private static byte[] bytesFromStream(InputStream is) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[64 * 1024]; int rc;/*from w ww .ja v a2 s .co m*/ while ((rc = is.read(buffer)) != -1) { os.write(buffer, 0, rc); } is.close(); os.flush(); buffer = os.toByteArray(); os.close(); return (buffer); }
From source file:com.streamsets.pipeline.lib.util.ProtobufTypeUtil.java
/** * Converts a protobuf message to an SDC Record Field. * * @param record SDC Record to add field to * @param fieldPath location in record where to insert field. * @param descriptor protobuf descriptor instance * @param messageTypeToExtensionMap protobuf extensions map * @param message message to decode and insert into the specified field path * @return new Field instance representing the decoded message * @throws DataParserException//from w w w . j a va 2 s. com */ public static Field protobufToSdcField(Record record, String fieldPath, Descriptors.Descriptor descriptor, Map<String, Set<Descriptors.FieldDescriptor>> messageTypeToExtensionMap, Object message) throws DataParserException { Map<String, Field> sdcRecordMapFieldValue = new HashMap<>(); // get all the expected fields from the proto file Map<String, Descriptors.FieldDescriptor> protobufFields = new LinkedHashMap<>(); for (Descriptors.FieldDescriptor fieldDescriptor : descriptor.getFields()) { protobufFields.put(fieldDescriptor.getName(), fieldDescriptor); } // get all fields in the read message Map<Descriptors.FieldDescriptor, Object> values = ((DynamicMessage) message).getAllFields(); // for every field present in the proto definition create an sdc field. for (Descriptors.FieldDescriptor fieldDescriptor : protobufFields.values()) { Object value = values.get(fieldDescriptor); sdcRecordMapFieldValue.put(fieldDescriptor.getName(), createField(record, fieldPath, fieldDescriptor, messageTypeToExtensionMap, value)); } // handle applicable extensions for this message type if (messageTypeToExtensionMap.containsKey(descriptor.getFullName())) { for (Descriptors.FieldDescriptor fieldDescriptor : messageTypeToExtensionMap .get(descriptor.getFullName())) { if (values.containsKey(fieldDescriptor)) { Object value = values.get(fieldDescriptor); sdcRecordMapFieldValue.put(fieldDescriptor.getName(), createField(record, fieldPath, fieldDescriptor, messageTypeToExtensionMap, value)); } } } // handle unknown fields // unknown fields can go into the record header UnknownFieldSet unknownFields = ((DynamicMessage) message).getUnknownFields(); if (!unknownFields.asMap().isEmpty()) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { unknownFields.writeDelimitedTo(bOut); bOut.flush(); bOut.close(); } catch (IOException e) { throw new DataParserException(Errors.PROTOBUF_10, e.toString(), e); } String path = fieldPath.isEmpty() ? FORWARD_SLASH : fieldPath; byte[] bytes = org.apache.commons.codec.binary.Base64.encodeBase64(bOut.toByteArray()); record.getHeader().setAttribute(PROTOBUF_UNKNOWN_FIELDS_PREFIX + path, new String(bytes, StandardCharsets.UTF_8)); } return Field.create(sdcRecordMapFieldValue); }
From source file:com.schoentoon.connectbot.PubkeyListActivity.java
/** * Read given file into memory as <code>byte[]</code>. *///from w w w . j av a2 s. c om protected static byte[] readRaw(File file) throws Exception { InputStream is = new FileInputStream(file); ByteArrayOutputStream os = new ByteArrayOutputStream(); int bytesRead; byte[] buffer = new byte[1024]; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.flush(); os.close(); is.close(); return os.toByteArray(); }
From source file:main.java.vasolsim.common.file.ExamBuilder.java
/** * writes an editable, unlocked exam to a file * * @param exam the exam to be written * @param examFile the target file//from w ww. jav a2s .co m * @param overwrite if an existing file can be overwritten * * @return if the file write was successful * * @throws VaSolSimException */ public static boolean writeRaw(@Nonnull Exam exam, @Nonnull File examFile, boolean overwrite) throws VaSolSimException { /* * check the file creation status and handle it */ //if it exists if (examFile.isFile()) { //can't overwrite if (!overwrite) { throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS); } //can overwrite, clear the existing file else { PrintWriter printWriter; try { printWriter = new PrintWriter(examFile); } catch (FileNotFoundException e) { throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK); } printWriter.print(""); printWriter.close(); } } //no file, create one else { if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) { throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS); } try { if (!examFile.createNewFile()) { throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE); } } catch (IOException e) { throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION); } } /* * initialize the document */ Document examDoc; Transformer examTransformer; try { examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); examTransformer = TransformerFactory.newInstance().newTransformer(); examTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); examTransformer.setOutputProperty(OutputKeys.METHOD, "xml"); examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd"); examTransformer.setOutputProperty(INDENTATION_KEY, "4"); } catch (ParserConfigurationException e) { throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e); } catch (TransformerConfigurationException e) { throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e); } /* * build exam info */ Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME); examDoc.appendChild(root); Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME); root.appendChild(info); //exam info GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc); GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc); GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc); GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc); //start security xml section Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME); root.appendChild(security); GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME, Boolean.toString(exam.isReportingStats()), security, examDoc); GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME, Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME, exam.getStatsDestinationEmail(), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME, exam.getStatsSenderEmail(), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME, exam.getStatsSenderSMTPAddress(), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME, Integer.toString(exam.getStatsSenderSMTPPort()), security, examDoc); ArrayList<QuestionSet> questionSets = exam.getQuestionSets(); if (GenericUtils.verifyQuestionSetsIntegrity(questionSets)) { for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) { QuestionSet qSet = questionSets.get(setsIndex); Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME); root.appendChild(qSetElement); GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1), qSetElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME, (qSet.getName() == null || qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1) : qSet.getName(), qSetElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME, qSet.getResourceType().toString(), qSetElement, examDoc); if (qSet.getResources() != null) { for (BufferedImage img : qSet.getResources()) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(img, "png", out); out.flush(); GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME, convertBytesToHexString(out.toByteArray()), qSetElement, examDoc); } catch (IOException e) { throw new VaSolSimException("Error: cannot write images to byte array for transport"); } } } for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) { Question question = qSet.getQuestions().get(setIndex); Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME); qSetElement.appendChild(qElement); GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1), qElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME, (question.getName() == null || question.getName().equals("")) ? "Question " + (setIndex + 1) : question.getName(), qElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME, Boolean.toString(question.getScrambleAnswers()), qElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME, Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc); for (AnswerChoice answer : question.getCorrectAnswerChoices()) { GenericUtils.appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH, answer.getAnswerText(), qElement, examDoc); } for (int questionIndex = 0; questionIndex < question.getAnswerChoices() .size(); questionIndex++) { AnswerChoice ac = question.getAnswerChoices().get(questionIndex); Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME); qElement.appendChild(acElement); GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME, Integer.toString(questionIndex + 1), acElement, examDoc); GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME, ac.getVisibleChoiceID(), acElement, examDoc); GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement, examDoc); } } } } return true; }
From source file:com.jredrain.base.utils.CommandUtils.java
public static String executeShell(File shellFile, String... args) { String info = null;/*from ww w. ja va 2 s . c o m*/ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { String params = " "; if (CommonUtils.notEmpty(args)) { for (String p : args) { params += p + " "; } } CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath() + params); DefaultExecutor exec = new DefaultExecutor(); exec.setExitValues(null); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputStream); exec.setStreamHandler(streamHandler); exec.execute(commandLine); info = outputStream.toString().trim(); } catch (Exception e) { e.printStackTrace(); } finally { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } return info; } }
From source file:main.java.vasolsim.common.GenericUtils.java
/** * converts an awt image to a javafx image * * @param image// www . j av a 2s .com * * @return * * @throws VaSolSimException */ public static Image convertBufferedImageToFXImage(BufferedImage image) throws VaSolSimException { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, "png", out); out.flush(); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); return new Image(in); } catch (IOException e) { //TODO field message out throw new VaSolSimException("image error"); } }
From source file:de.unidue.inf.is.ezdl.dlcore.utils.StringUtils.java
/** * Compresses a string./*from www. ja v a 2 s. c om*/ * * @param s * The string to compress * @return The compressed string */ public static String compress(String s) { ByteArrayOutputStream baos = null; try { byte[] input = s.getBytes("UTF-8"); Deflater compresser = new Deflater(); compresser.setLevel(Deflater.BEST_COMPRESSION); compresser.setInput(input); compresser.finish(); baos = new ByteArrayOutputStream(); while (!compresser.finished()) { byte[] output = new byte[1024]; int compressedDataLength = compresser.deflate(output); baos.write(output, 0, compressedDataLength); } baos.flush(); return Base64.encodeBase64String(baos.toByteArray()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { ClosingUtils.close(baos); } return ""; }
From source file:de.codesourcery.jasm16.utils.Misc.java
public static byte[] readBytes(InputStream in) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); int len = 0;/*from w ww . j a v a2 s .c om*/ final byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.flush(); return out.toByteArray(); }
From source file:com.recomdata.datasetexplorer.proxy.XmlHttpProxy.java
public static JSONObject loadJSONObject(InputStream in) { ByteArrayOutputStream out = null; try {/* ww w . j a v a 2 s. c o m*/ byte[] buffer = new byte[1024]; int read = 0; out = new ByteArrayOutputStream(); while (true) { read = in.read(buffer); if (read <= 0) break; out.write(buffer, 0, read); } return new JSONObject(out.toString()); } catch (Exception e) { getLogger().severe("XmlHttpProxy error reading in json " + e); } finally { try { if (in != null) { in.close(); } if (out != null) { out.flush(); out.close(); } } catch (Exception e) { } } return null; }
From source file:com.mucommander.ui.viewer.image.ImageViewer.java
private static BufferedImage transcodeSVGDocument(AbstractFile file, float width, float height) throws IOException { // create a PNG transcoder. Transcoder t = new PNGTranscoder(); // Set the transcoding hints. if (width > 0) { t.addTranscodingHint(PNGTranscoder.KEY_WIDTH, width); }/* w w w . ja v a 2 s . c o m*/ if (height > 0) { t.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, height); } t.addTranscodingHint(PNGTranscoder.KEY_XML_PARSER_VALIDATING, false); // create the transcoder input. TranscoderInput input = new TranscoderInput(file.getInputStream()); ByteArrayOutputStream ostream = null; try { // create the transcoder output. ostream = new ByteArrayOutputStream(); TranscoderOutput output = new TranscoderOutput(ostream); // Save the image. t.transcode(input, output); // Flush and close the stream. ostream.flush(); ostream.close(); } catch (Exception ex) { ex.printStackTrace(); } // Convert the byte stream into an image. byte[] imgData = ostream.toByteArray(); // Return the newly rendered image. return ImageIO.read(new ByteArrayInputStream(imgData)); }