List of usage examples for org.apache.commons.io IOUtils toString
public static String toString(byte[] input) throws IOException
byte[]
as a String using the default character encoding of the platform. From source file:com.pixa.gcmsender.GcmSender.java
public static void main(String[] args) { if (args.length < 1 || args.length > 2 || args[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println(/*w w w . j av a2 s.c om*/ "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(1); } try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", args[0].trim()); // Where to send GCM message. if (args.length > 1 && args[1] != null) { jGcmData.put("to", args[1].trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); e.printStackTrace(); } }
From source file:com.pp.dcasajus.forkpoint.GcmSender.java
public static void main(String[] args) { if (args.length < 1 || args.length > 2 || args[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println(/* www. jav a 2 s .com*/ "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(1); } try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", args[0].trim()); // Where to send GCM message. if (args.length > 1 && args[1] != null) { jGcmData.put("to", args[1].trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.chimpler.example.FacetLuceneIndexer.java
public static void main(String args[]) throws Exception { // if (args.length != 3) { // System.err.println("Parameters: [index directory] [taxonomy directory] [json file]"); // System.exit(1); // }/* w w w . ja v a2 s . c o m*/ String indexDirectory = "index"; String taxonomyDirectory = "taxonomy"; String jsonFileName = "/home/qiuqiang/workspace/facet-lucene-example/books.json"; IndexWriterConfig writerConfig = new IndexWriterConfig(LUCENE_VERSION, new WhitespaceAnalyzer(LUCENE_VERSION)); writerConfig.setOpenMode(OpenMode.APPEND); IndexWriter indexWriter = new IndexWriter(FSDirectory.open(new File(indexDirectory)), writerConfig); TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(MMapDirectory.open(new File(taxonomyDirectory)), OpenMode.APPEND); TaxonomyReader taxonomyReader = new DirectoryTaxonomyReader(FSDirectory.open(new File(taxonomyDirectory))); String content = IOUtils.toString(new FileInputStream(jsonFileName)); JSONArray bookArray = new JSONArray(content); Field idField = new IntField("id", 0, Store.YES); Field titleField = new TextField("title", "", Store.YES); Field authorsField = new TextField("authors", "", Store.YES); Field bookCategoryField = new TextField("book_category", "", Store.YES); indexWriter.deleteAll(); FacetFields facetFields = new FacetFields(taxonomyWriter); for (int i = 0; i < bookArray.length(); i++) { Document document = new Document(); JSONObject book = bookArray.getJSONObject(i); int id = book.getInt("id"); String title = book.getString("title"); String bookCategory = book.getString("book_category"); List<CategoryPath> categoryPaths = new ArrayList<CategoryPath>(); String authorsString = ""; JSONArray authors = book.getJSONArray("authors"); for (int j = 0; j < authors.length(); j++) { String author = authors.getString(j); if (j > 0) { authorsString += ", "; } categoryPaths.add(new CategoryPath("author", author)); authorsString += author; } categoryPaths.add(new CategoryPath("book_category" + bookCategory, '/')); idField.setIntValue(id); titleField.setStringValue(title); authorsField.setStringValue(authorsString); bookCategoryField.setStringValue(bookCategory); facetFields.addFields(document, categoryPaths); document.add(idField); document.add(titleField); document.add(authorsField); document.add(bookCategoryField); indexWriter.addDocument(document); System.out.printf("Book: id=%d, title=%s, book_category=%s, authors=%s\n", id, title, bookCategory, authors); } taxonomyWriter.prepareCommit(); try { taxonomyWriter.commit(); } catch (Exception e) { taxonomyWriter.rollback(); } // taxonomyWriter.close(); // // indexWriter.commit(); // indexWriter.close(); String query = "story"; IndexReader indexReader = DirectoryReader.open(indexWriter, false); IndexReader indexReader2 = DirectoryReader.open(indexWriter, false); System.out.println(indexReader == indexReader2); IndexSearcher indexSearcher = new IndexSearcher(indexReader); TaxonomyReader newTaxonomyReader = DirectoryTaxonomyReader.openIfChanged(taxonomyReader); if (newTaxonomyReader != null) { TaxonomyReader tmp = taxonomyReader; taxonomyReader = newTaxonomyReader; tmp.close(); } else { System.out.println("null"); } ArrayList<FacetRequest> facetRequests = new ArrayList<FacetRequest>(); facetRequests.add(new CountFacetRequest(new CategoryPath("author"), 100)); facetRequests.add(new CountFacetRequest(new CategoryPath("book_category"), 100)); FacetSearchParams searchParams = new FacetSearchParams(facetRequests); ComplexPhraseQueryParser queryParser = new ComplexPhraseQueryParser(LUCENE_VERSION, "title", new StandardAnalyzer(LUCENE_VERSION)); Query luceneQuery = queryParser.parse(query); // Collectors to get top results and facets TopScoreDocCollector topScoreDocCollector = TopScoreDocCollector.create(10, true); FacetsCollector facetsCollector = FacetsCollector.create(searchParams, indexReader, taxonomyReader); indexSearcher.search(luceneQuery, MultiCollector.wrap(topScoreDocCollector, facetsCollector)); System.out.println("Found:"); for (ScoreDoc scoreDoc : topScoreDocCollector.topDocs().scoreDocs) { Document document = indexReader.document(scoreDoc.doc); System.out.printf("- book: id=%s, title=%s, book_category=%s, authors=%s, score=%f\n", document.get("id"), document.get("title"), document.get("book_category"), document.get("authors"), scoreDoc.score); } System.out.println("Facets:"); for (FacetResult facetResult : facetsCollector.getFacetResults()) { System.out.println("- " + facetResult.getFacetResultNode().label); for (FacetResultNode facetResultNode : facetResult.getFacetResultNode().subResults) { System.out.printf(" - %s (%f)\n", facetResultNode.label.toString(), facetResultNode.value); for (FacetResultNode subFacetResultNode : facetResultNode.subResults) { System.out.printf(" - %s (%f)\n", subFacetResultNode.label.toString(), subFacetResultNode.value); } } } taxonomyReader.close(); indexReader.close(); taxonomyWriter.commit(); taxonomyWriter.close(); indexWriter.commit(); indexWriter.close(); }
From source file:com.jixstreet.temanusaha.gcm.GcmSender.java
public static void main(String[] args) { if (args.length < 1 || args.length > 2 || args[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println(//from www. ja v a 2 s . c o m "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(1); } try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); try { jData.put("message", args[0].trim()); } catch (JSONException e) { e.printStackTrace(); } // Where to send GCM message. if (args.length > 1 && args[1] != null) { try { jGcmData.put("to", args[1].trim()); } catch (JSONException e) { e.printStackTrace(); } } else { try { jGcmData.put("to", "/topics/global"); } catch (JSONException e) { e.printStackTrace(); } } // What to send in GCM message. try { JSONObject data = jGcmData.put("data", jData); } catch (JSONException e) { e.printStackTrace(); } // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); e.printStackTrace(); } }
From source file:cli.Main.java
public static void main(String[] args) { // Workaround for BKS truststore Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); Namespace ns = parseArgs(args); if (ns == null) { System.exit(1);//ww w.j a v a2 s.c om } final String username = ns.getString("username"); final Manager m = new Manager(username); if (m.userExists()) { try { m.load(); } catch (Exception e) { System.err.println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage()); System.exit(2); } } switch (ns.getString("command")) { case "register": if (!m.userHasKeys()) { m.createNewIdentity(); } try { m.register(ns.getBoolean("voice")); } catch (IOException e) { System.err.println("Request verify error: " + e.getMessage()); System.exit(3); } break; case "verify": if (!m.userHasKeys()) { System.err.println("User has no keys, first call register."); System.exit(1); } if (m.isRegistered()) { System.err.println("User registration is already verified"); System.exit(1); } try { m.verifyAccount(ns.getString("verificationCode")); } catch (IOException e) { System.err.println("Verify error: " + e.getMessage()); System.exit(3); } break; case "send": if (!m.isRegistered()) { System.err.println("User is not registered."); System.exit(1); } String messageText = ns.getString("message"); if (messageText == null) { try { messageText = IOUtils.toString(System.in); } catch (IOException e) { System.err.println("Failed to read message from stdin: " + e.getMessage()); System.exit(1); } } final List<String> attachments = ns.getList("attachment"); List<TextSecureAttachment> textSecureAttachments = null; if (attachments != null) { textSecureAttachments = new ArrayList<>(attachments.size()); for (String attachment : attachments) { try { File attachmentFile = new File(attachment); InputStream attachmentStream = new FileInputStream(attachmentFile); final long attachmentSize = attachmentFile.length(); String mime = Files.probeContentType(Paths.get(attachment)); textSecureAttachments .add(new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null)); } catch (IOException e) { System.err.println("Failed to add attachment \"" + attachment + "\": " + e.getMessage()); System.err.println("Aborting sending."); System.exit(1); } } } List<TextSecureAddress> recipients = new ArrayList<>(ns.<String>getList("recipient").size()); for (String recipient : ns.<String>getList("recipient")) { try { recipients.add(m.getPushAddress(recipient)); } catch (InvalidNumberException e) { System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage()); System.err.println("Aborting sending."); System.exit(1); } } sendMessage(m, messageText, textSecureAttachments, recipients); break; case "receive": if (!m.isRegistered()) { System.err.println("User is not registered."); System.exit(1); } try { m.receiveMessages(5, true, new ReceiveMessageHandler(m)); } catch (IOException e) { System.err.println("Error while receiving message: " + e.getMessage()); System.exit(3); } catch (AssertionError e) { System.err.println("Failed to receive message (Assertion): " + e.getMessage()); System.err.println(e.getStackTrace()); System.err.println( "If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README"); System.exit(1); } break; } m.save(); System.exit(0); }
From source file:com.athena.peacock.agent.Starter.java
/** * <pre>//from w w w.j a v a 2 s.co m * * </pre> * @param args */ @SuppressWarnings("resource") public static void main(String[] args) { int rand = (int) (Math.random() * 100) % 50; System.setProperty("random.seconds", Integer.toString(rand)); String configFile = null; try { configFile = PropertyUtil.getProperty(PeacockConstant.CONFIG_FILE_KEY); } catch (Exception e) { // nothing to do. } finally { if (StringUtils.isEmpty(configFile)) { configFile = "/peacock/agent/config/agent.conf"; } } /** * ${peacock.agent.config.file.name} ?? load ? ?? ? ? ? . */ String errorMsg = "\n\"" + configFile + "\" file does not exist or cannot read.\n" + "Please check \"" + configFile + "\" file exists and can read."; Assert.isTrue(AgentConfigUtil.exception == null, errorMsg); Assert.notNull(AgentConfigUtil.getConfig(PeacockConstant.SERVER_IP), "ServerIP cannot be empty."); Assert.notNull(AgentConfigUtil.getConfig(PeacockConstant.SERVER_PORT), "ServerPort cannot be empty."); /** * Agent ID ?? ${peacock.agent.agent.file.name} ? ?, * ?? ? Agent ID ? ?? . */ String agentFile = null; String agentId = null; try { agentFile = PropertyUtil.getProperty(PeacockConstant.AGENT_ID_FILE_KEY); } catch (Exception e) { // nothing to do. } finally { if (StringUtils.isEmpty(agentFile)) { agentFile = "/peacock/agent/.agent"; } } File file = new File(agentFile); boolean isNew = false; if (file.exists()) { try { agentId = IOUtils.toString(file.toURI()); // ? ? agent ID agent ID? ? 36? ? ?. if (StringUtils.isEmpty(agentId) || agentId.length() != 36) { throw new IOException(); } } catch (IOException e) { logger.error(agentFile + " file cannot read or saved invalid agent ID.", e); agentId = PeacockAgentIDGenerator.generateId(); isNew = true; } } else { agentId = PeacockAgentIDGenerator.generateId(); isNew = true; } if (isNew) { logger.info("New Agent-ID({}) be generated.", agentId); try { file.setWritable(true); OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(file)); output.write(agentId); file.setReadOnly(); IOUtils.closeQuietly(output); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException has occurred : ", e); } catch (FileNotFoundException e) { logger.error("FileNotFoundException has occurred : ", e); } catch (IOException e) { logger.error("IOException has occurred : ", e); } } // Spring Application Context Loading logger.debug("Starting application context..."); AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext( "classpath:spring/context-*.xml"); applicationContext.registerShutdownHook(); }
From source file:edu.toronto.cs.xcurator.cli.CLIRunner.java
public static void main(String[] args) { Options options = setupOptions();//w w w . j a v a2 s. co m CommandLineParser parser = new BasicParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption('t')) { fileType = line.getOptionValue('t'); } else { fileType = XML; } if (line.hasOption('o')) { tdbDirectory = line.getOptionValue('o'); File d = new File(tdbDirectory); if (!d.exists() || !d.isDirectory()) { throw new Exception("TDB directory does not exist, please create."); } } if (line.hasOption('h')) { domain = line.getOptionValue('h'); try { URL url = new URL(domain); } catch (MalformedURLException ex) { throw new Exception("The domain name is ill-formed"); } } else { printHelpAndExit(options); } if (line.hasOption('m')) { serializeMapping = true; mappingFilename = line.getOptionValue('m'); } if (line.hasOption('d')) { dirLocation = line.getOptionValue('d'); inputStreams = new ArrayList<>(); final List<String> files = Util.getFiles(dirLocation); for (String inputfile : files) { File f = new File(inputfile); if (f.isFile() && f.exists()) { System.out.println("Adding document to mapping discoverer: " + inputfile); inputStreams.add(new FileInputStream(f)); } // If it is a URL download link for the document from SEC else if (inputfile.startsWith("http") && inputfile.contains("://")) { // Download System.out.println("Adding remote document to mapping discoverer: " + inputfile); try { URL url = new URL(inputfile); InputStream remoteDocumentStream = url.openStream(); inputStreams.add(remoteDocumentStream); } catch (MalformedURLException ex) { throw new Exception("The document URL is ill-formed: " + inputfile); } catch (IOException ex) { throw new Exception("Error in downloading remote document: " + inputfile); } } else { throw new Exception("Cannot open XBRL document: " + f.getName()); } } } if (line.hasOption('f')) { fileLocation = line.getOptionValue('f'); inputStreams = new ArrayList<>(); File f = new File(fileLocation); if (f.isFile() && f.exists()) { System.out.println("Adding document to mapping discoverer: " + fileLocation); inputStreams.add(new FileInputStream(f)); } // If it is a URL download link for the document from SEC else if (fileLocation.startsWith("http") && fileLocation.contains("://")) { // Download System.out.println("Adding remote document to mapping discoverer: " + fileLocation); try { URL url = new URL(fileLocation); InputStream remoteDocumentStream = url.openStream(); inputStreams.add(remoteDocumentStream); } catch (MalformedURLException ex) { throw new Exception("The document URL is ill-formed: " + fileLocation); } catch (IOException ex) { throw new Exception("Error in downloading remote document: " + fileLocation); } } else { throw new Exception("Cannot open XBRL document: " + f.getName()); } } setupDocumentBuilder(); RdfFactory rdfFactory = new RdfFactory(new RunConfig(domain)); List<Document> documents = new ArrayList<>(); for (InputStream inputStream : inputStreams) { Document dataDocument = null; if (fileType.equals(JSON)) { String json = IOUtils.toString(inputStream); final String xml = Util.json2xml(json); final InputStream xmlInputStream = IOUtils.toInputStream(xml); dataDocument = createDocument(xmlInputStream); } else { dataDocument = createDocument(inputStream); } documents.add(dataDocument); } if (serializeMapping) { System.out.println("Mapping file will be saved to: " + new File(mappingFilename).getAbsolutePath()); rdfFactory.createRdfs(documents, tdbDirectory, mappingFilename); } else { rdfFactory.createRdfs(documents, tdbDirectory); } } catch (Exception ex) { ex.printStackTrace(); System.err.println("Unexpected exception: " + ex.getMessage()); System.exit(1); } }
From source file:com.doculibre.constellio.lang.html.HtmlLangDetector.java
public static void main(String[] args) throws Exception { //java.net.URL url = new java.net.URL("http://www.gouv.qc.ca"); java.net.URL url = new java.net.URL("http://andrew.triumf.ca/multilingual/samples/french.meta.html"); java.net.URLConnection connection = url.openConnection(); java.io.InputStream is = null; String content = null;/* w ww . jav a2 s.c o m*/ try { is = connection.getInputStream(); content = IOUtils.toString(is); } finally { IOUtils.closeQuietly(is); } HtmlLangDetector langDetector = new HtmlLangDetector(); System.out.println(langDetector.getLang(content)); }
From source file:com.mycompany.ssms.dao.ClobHelperClass.java
public static String ClobToString(Clob c) { try {//from w w w . j a v a 2 s.com return IOUtils.toString(c.getAsciiStream()); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.aestheticsw.jobkeywords.utils.FileUtils.java
public static <T> String getClassResourceAsString(String resourcePath, T clazz) { try (final InputStream is = clazz.getClass().getResourceAsStream(resourcePath)) { return IOUtils.toString(is); } catch (IOException e) { throw new RuntimeException("Exception reading resource file: " + resourcePath + " for class: " + clazz.getClass().getName(), e); }//from ww w . j ava 2 s .co m }