List of usage examples for java.net URL URL
public URL(String spec) throws MalformedURLException
From source file:Server_socket.java
public static void main(String argv[]) throws Exception { int puerto = Integer.parseInt(argv[0]); //String username = argv[1]; //String password = argv[2]; String clientformat;//from w w w . j a v a 2s . com String clientdata; String clientresult; String clientresource; String url_login = "http://localhost:3000/users/sign_in"; ServerSocket welcomeSocket = new ServerSocket(puerto); /*HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_login); // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); // nameValuePairs.add(new BasicNameValuePair("utf8", Character.toString('\u2713'))); nameValuePairs.add(new BasicNameValuePair("username", username)); nameValuePairs.add(new BasicNameValuePair("password", password)); // nameValuePairs.add(new BasicNameValuePair("commit", "Sign in")); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpClient.execute(httpPost); String ret = EntityUtils.tostring(response.getEntity()); System.out.println(ret); */ while (true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientformat = inFromClient.readLine(); System.out.println("FORMAT: " + clientformat); BufferedReader inFromClient1 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientdata = inFromClient1.readLine(); System.out.println("DATA: " + clientdata); BufferedReader inFromClient2 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresult = inFromClient2.readLine(); System.out.println("RESULT: " + clientresult); BufferedReader inFromClient3 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresource = inFromClient3.readLine(); System.out.println("RESOURCE: " + clientresource); System.out.println("no pasas de aqui"); String url = "http://localhost:3000/" + clientresource + "/" + clientdata + "." + clientformat; System.out.println(url); try (InputStream is = new URL(url).openStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String stb = sb.toString(); System.out.println("estas aqui"); String output = null; String jsonText = stb; output = jsonText.replace("[", "").replace("]", ""); JSONObject json = new JSONObject(output); System.out.println(json.toString()); System.out.println("llegaste al final"); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); outToClient.writeBytes(json.toString()); } connectionSocket.close(); } }
From source file:BookRank.java
/** Grab the sales rank off the web page and log it. */ public static void main(String[] args) throws Exception { Properties p = new Properties(); String title = p.getProperty("title", "NO TITLE IN PROPERTIES"); // The url must have the "isbn=" at the very end, or otherwise // be amenable to being string-catted to, like the default. String url = p.getProperty("url", "http://test.ing/test.cgi?isbn="); // The 10-digit ISBN for the book. String isbn = p.getProperty("isbn", "0000000000"); // The RE pattern (MUST have ONE capture group for the number) String pattern = p.getProperty("pattern", "Rank: (\\d+)"); // Looking for something like this in the input: // <b>QuickBookShop.web Sales Rank: </b> // 26,252// w w w . j a v a 2 s. com // </font><br> Pattern r = Pattern.compile(pattern); // Open the URL and get a Reader from it. BufferedReader is = new BufferedReader(new InputStreamReader(new URL(url + isbn).openStream())); // Read the URL looking for the rank information, as // a single long string, so can match RE across multi-lines. String input = "input from console"; // System.out.println(input); // If found, append to sales data file. Matcher m = r.matcher(input); if (m.find()) { PrintWriter pw = new PrintWriter(new FileWriter(DATA_FILE, true)); String date = // `date +'%m %d %H %M %S %Y'`; new SimpleDateFormat("MM dd hh mm ss yyyy ").format(new Date()); // Paren 1 is the digits (and maybe ','s) that matched; remove comma Matcher noComma = Pattern.compile(",").matcher(m.group(1)); pw.println(date + noComma.replaceAll("")); pw.close(); } else { System.err.println("WARNING: pattern `" + pattern + "' did not match in `" + url + isbn + "'!"); } // Whether current data found or not, draw the graph, using // external plotting program against all historical data. // Could use gnuplot, R, any other math/graph program. // Better yet: use one of the Java plotting APIs. String gnuplot_cmd = "set term png\n" + "set output \"" + GRAPH_FILE + "\"\n" + "set xdata time\n" + "set ylabel \"Book sales rank\"\n" + "set bmargin 3\n" + "set logscale y\n" + "set yrange [1:60000] reverse\n" + "set timefmt \"%m %d %H %M %S %Y\"\n" + "plot \"" + DATA_FILE + "\" using 1:7 title \"" + title + "\" with lines\n"; Process proc = Runtime.getRuntime().exec("/usr/local/bin/gnuplot"); PrintWriter gp = new PrintWriter(proc.getOutputStream()); gp.print(gnuplot_cmd); gp.close(); }
From source file:Pathway2RDFv2.java
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, ServiceException, ClassNotFoundException, IDMapperException, ParseException { int softwareVersion = 0; int schemaVersion = 0; int latestRevision = 0; BioDataSource.init();/* www .j ava2 s. co m*/ Class.forName("org.bridgedb.rdb.IDMapperRdb"); File dir = new File("/Users/andra/Downloads/bridge"); File[] bridgeDbFiles = dir.listFiles(); IDMapperStack mapper = new IDMapperStack(); for (File bridgeDbFile : bridgeDbFiles) { System.out.println(bridgeDbFile.getAbsolutePath()); mapper.addIDMapper("idmapper-pgdb:" + bridgeDbFile.getAbsolutePath()); } Model bridgeDbmodel = ModelFactory.createDefaultModel(); InputStream in = new FileInputStream("/tmp/BioDataSource.ttl"); bridgeDbmodel.read(in, "", "TURTLE"); WikiPathwaysClient client = new WikiPathwaysClient( new URL("http://www.wikipathways.org/wpi/webservice/webservice.php")); basicCalls.printMemoryStatus(); //Map wikipathway organisms to NCBI organisms HashMap<String, String> organismTaxonomy = wpRelatedCalls.getOrganismsTaxonomyMapping(); //HashMap<String, String> miriamSources = new HashMap<String, String>(); // HashMap<String, Str ing> miriamLinks = basicCalls.getMiriamUriBridgeDb(); //Document wikiPathwaysDom = basicCalls.openXmlFile(args[0]); Document wikiPathwaysDom = basicCalls.openXmlFile("/tmp/WpGPML.xml"); //initiate the Jena model to be populated Model model = ModelFactory.createDefaultModel(); Model voidModel = ModelFactory.createDefaultModel(); voidModel.setNsPrefix("xsd", XSD.getURI()); voidModel.setNsPrefix("void", Void.getURI()); voidModel.setNsPrefix("wprdf", "http://rdf.wikipathways.org/"); voidModel.setNsPrefix("pav", Pav.getURI()); voidModel.setNsPrefix("prov", Prov.getURI()); voidModel.setNsPrefix("dcterms", DCTerms.getURI()); voidModel.setNsPrefix("biopax", Biopax_level3.getURI()); voidModel.setNsPrefix("gpml", Gpml.getURI()); voidModel.setNsPrefix("wp", Wp.getURI()); voidModel.setNsPrefix("foaf", FOAF.getURI()); voidModel.setNsPrefix("hmdb", "http://identifiers.org/hmdb/"); voidModel.setNsPrefix("freq", Freq.getURI()); voidModel.setNsPrefix("dc", DC.getURI()); setModelPrefix(model); //Populate void.ttl Calendar now = Calendar.getInstance(); Literal nowLiteral = voidModel.createTypedLiteral(now); Literal titleLiteral = voidModel.createLiteral("WikiPathways-RDF VoID Description", "en"); Literal descriptionLiteral = voidModel .createLiteral("This is the VoID description for a WikiPathwyas-RDF dataset.", "en"); Resource voidBase = voidModel.createResource("http://rdf.wikipathways.org/"); Resource identifiersOrg = voidModel.createResource("http://identifiers.org"); Resource wpHomeBase = voidModel.createResource("http://www.wikipathways.org/"); Resource authorResource = voidModel .createResource("http://semantics.bigcat.unimaas.nl/figshare/search_author.php?author=waagmeester"); Resource apiResource = voidModel .createResource("http://www.wikipathways.org/wpi/webservice/webservice.php"); Resource mainDatadump = voidModel.createResource("http://rdf.wikipathways.org/wpContent.ttl.gz"); Resource license = voidModel.createResource("http://creativecommons.org/licenses/by/3.0/"); Resource instituteResource = voidModel.createResource("http://dbpedia.org/page/Maastricht_University"); voidBase.addProperty(RDF.type, Void.Dataset); voidBase.addProperty(DCTerms.title, titleLiteral); voidBase.addProperty(DCTerms.description, descriptionLiteral); voidBase.addProperty(FOAF.homepage, wpHomeBase); voidBase.addProperty(DCTerms.license, license); voidBase.addProperty(Void.uriSpace, voidBase); voidBase.addProperty(Void.uriSpace, identifiersOrg); voidBase.addProperty(Pav.importedBy, authorResource); voidBase.addProperty(Pav.importedFrom, apiResource); voidBase.addProperty(Pav.importedOn, nowLiteral); voidBase.addProperty(Void.dataDump, mainDatadump); voidBase.addProperty(Voag.frequencyOfChange, Freq.Irregular); voidBase.addProperty(Pav.createdBy, authorResource); voidBase.addProperty(Pav.createdAt, instituteResource); voidBase.addLiteral(Pav.createdOn, nowLiteral); voidBase.addProperty(DCTerms.subject, Biopax_level3.Pathway); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/ncbigene/2678")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/pubmed/15215856")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/hmdb/HMDB02005")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://rdf.wikipathways.org/WP15")); voidBase.addProperty(Void.exampleResource, voidModel.createResource("http://identifiers.org/obo.chebi/17242")); for (String organism : organismTaxonomy.values()) { voidBase.addProperty(DCTerms.subject, voidModel.createResource("http://dbpedia.org/page/" + organism.replace(" ", "_"))); } voidBase.addProperty(Void.vocabulary, Biopax_level3.NAMESPACE); voidBase.addProperty(Void.vocabulary, voidModel.createResource(Wp.getURI())); voidBase.addProperty(Void.vocabulary, voidModel.createResource(Gpml.getURI())); voidBase.addProperty(Void.vocabulary, FOAF.NAMESPACE); voidBase.addProperty(Void.vocabulary, Pav.NAMESPACE); //Custom Properties String baseUri = "http://rdf.wikipathways.org/"; NodeList pathwayElements = wikiPathwaysDom.getElementsByTagName("Pathway"); //BioDataSource.init(); for (int i = 0; i < pathwayElements.getLength(); i++) { Model pathwayModel = createPathwayModel(); String wpId = pathwayElements.item(i).getAttributes().getNamedItem("identifier").getTextContent(); String revision = pathwayElements.item(i).getAttributes().getNamedItem("revision").getTextContent(); String pathwayOrganism = ""; if (pathwayElements.item(i).getAttributes().getNamedItem("Organism") != null) pathwayOrganism = pathwayElements.item(i).getAttributes().getNamedItem("Organism").getTextContent() .trim(); if (Integer.valueOf(revision) > latestRevision) { latestRevision = Integer.valueOf(revision); } File f = new File("/tmp/" + args[0] + "/" + wpId + "_r" + revision + ".ttl"); System.out.println(f.getName()); if (!f.exists()) { Resource voidPwResource = wpRelatedCalls.addVoidTriples(voidModel, voidBase, pathwayElements.item(i), client); Resource pwResource = wpRelatedCalls.addPathwayLevelTriple(pathwayModel, pathwayElements.item(i), organismTaxonomy); // Get the comments NodeList commentElements = ((Element) pathwayElements.item(i)).getElementsByTagName("Comment"); wpRelatedCalls.addCommentTriples(pathwayModel, pwResource, commentElements, wpId, revision); // Get the Groups NodeList groupElements = ((Element) pathwayElements.item(i)).getElementsByTagName("Group"); for (int n = 0; n < groupElements.getLength(); n++) { wpRelatedCalls.addGroupTriples(pathwayModel, pwResource, groupElements.item(n), wpId, revision); } // Get all the Datanodes NodeList dataNodesElement = ((Element) pathwayElements.item(i)).getElementsByTagName("DataNode"); for (int j = 0; j < dataNodesElement.getLength(); j++) { wpRelatedCalls.addDataNodeTriples(pathwayModel, pwResource, dataNodesElement.item(j), wpId, revision, bridgeDbmodel, mapper); } // Get all the lines NodeList linesElement = ((Element) pathwayElements.item(i)).getElementsByTagName("Line"); for (int k = 0; k < linesElement.getLength(); k++) { wpRelatedCalls.addLineTriples(pathwayModel, pwResource, linesElement.item(k), wpId, revision); } //Get all the labels NodeList labelsElement = ((Element) pathwayElements.item(i)).getElementsByTagName("Label"); for (int l = 0; l < labelsElement.getLength(); l++) { wpRelatedCalls.addLabelTriples(pathwayModel, pwResource, labelsElement.item(l), wpId, revision); } NodeList referenceElements = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:PublicationXref"); for (int m = 0; m < referenceElements.getLength(); m++) { wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements.item(m), wpId, revision); } NodeList referenceElements2 = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:publicationXref"); for (int m = 0; m < referenceElements2.getLength(); m++) { wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements2.item(m), wpId, revision); } NodeList referenceElements3 = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:PublicationXRef"); for (int m = 0; m < referenceElements3.getLength(); m++) { wpRelatedCalls.addReferenceTriples(pathwayModel, pwResource, referenceElements3.item(m), wpId, revision); } NodeList ontologyElements = ((Element) pathwayElements.item(i)) .getElementsByTagName("bp:openControlledVocabulary"); for (int n = 0; n < ontologyElements.getLength(); n++) { wpRelatedCalls.addPathwayOntologyTriples(pathwayModel, pwResource, ontologyElements.item(n)); } System.out.println(wpId); basicCalls.saveRDF2File(pathwayModel, "/tmp/" + args[0] + "/" + wpId + "_r" + revision + ".ttl", "TURTLE"); model.add(pathwayModel); pathwayModel.removeAll(); } } Date myDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String myDateString = sdf.format(myDate); FileUtils.writeStringToFile(new File("latestVersion.txt"), "v" + schemaVersion + "." + softwareVersion + "." + latestRevision + "_" + myDateString); basicCalls.saveRDF2File(model, "/tmp/wpContent_v" + schemaVersion + "." + softwareVersion + "." + latestRevision + "_" + myDateString + ".ttl", "TURTLE"); basicCalls.saveRDF2File(voidModel, "/tmp/void.ttl", "TURTLE"); }
From source file:net.semanticmetadata.lire.solr.SearchImages.java
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException { // http://localhost:8080/solr/lire/query?q=hashes%3A1152++hashes%3A605++hashes%3A96++hashes%3A275++&wt=xml String hashes = "1152 605 96 275 2057 3579 3950 2831 2367 3169 3292 974 2465 1573 2933 3125 314 2158 3532 974 2198 2315 3013 3302 3316 1467 2213 818 3 1083 18 2604 327 1370 593 3677 464 79 256 984 2496 1124 855 2091 780 1941 1887 1145 1396 4016 2406 2227 1532 2598 215 1375 171 2516 1698 368 2350 3799 223 1471 2083 1051 3015 3789 3374 1442 3991 3575 1452 751 428 3103 1182 2241 474 275 3678 3970 559 3394 2662 2361 2048 1083 181 1483 3903 3331 2363 756 558 2838 3984 1878 2667 3333 1473 2136 3499 3873 1437 3091 1287 948 46 3660 3003 1572 1185 2231 2622 257 3538 3632 3989 1180 3928 3144 1492 3941 3253 3498 2721 1036 22 1020 725 1431 3821 2248 2542 3659 2849 524 2967 1 2493 3620 2951 3584 1641 3873 2087 1506 1489 3064"; String[] split = hashes.split(" "); String query = ""; for (int i = 0; i < split.length; i++) { String s = split[i];//from w w w. ja v a2 s. c o m if (s.trim().length() > 0) query += " cl_ha:" + s.trim(); } URL u = new URL(baseURL + "?q=" + URLEncoder.encode(query, "utf-8") + "&wt=xml&rows=500"); InputStream in = u.openStream(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); SolrResponseHandler dh = new SolrResponseHandler(); saxParser.parse(in, dh); ArrayList<ResultItem> results = dh.getResults(); // re-rank: }
From source file:gov.nasa.jpl.celgene.labkey.LabkeyDumper.java
public static void main(String[] args) throws Exception { String url = null;/* ww w. j a va 2 s.c o m*/ String user = null; String pass = null; String projectName = null; String usage = "java LabkeyDumper [--url <url>] [--user <user/email>] [--pass <pass>] [--project <Project Name>]\n"; for (int i = 0; i < args.length; i++) { if (args[i].equals("--url")) { url = args[++i]; } else if (args[i].equals("--user")) { user = args[++i]; } else if (args[i].equals("--pass")) { pass = args[++i]; } else if (args[i].equals("--project")) { projectName = args[++i]; } } if (isEmpty(url) || isEmpty(user) || isEmpty(pass) || isEmpty(projectName)) { System.err.println(usage); System.exit(1); } LabkeyDumper dumper = new LabkeyDumper(new URL(url), user, pass); dumper.generateJSON(dumper.dumpStudies(projectName)); }
From source file:com.centurylink.mdw.util.HttpHelper.java
public static void main(String[] args) { try {//w w w . j a v a2 s. c o m HttpHelper helper = new HttpHelper(new URL(args[0])); System.out.println(helper.get()); } catch (Exception ex) { throw new RuntimeException(ex.getMessage(), ex); } }
From source file:OCRRestAPI.java
public static void main(String[] args) throws Exception { /*//ww w .j a v a 2 s . c o m Sample project for OCRWebService.com (REST API). Extract text from scanned images and convert into editable formats. Please create new account with ocrwebservice.com via http://www.ocrwebservice.com/account/signup and get license code */ // Provide your user name and license code String license_code = "88EF173D-CDEA-41B6-8D64-C04578ED8C4D"; String user_name = "FERGOID"; /* You should specify OCR settings. See full description http://www.ocrwebservice.com/service/restguide Input parameters: [language] - Specifies the recognition language. This parameter can contain several language names separated with commas. For example "language=english,german,spanish". Optional parameter. By default:english [pagerange] - Enter page numbers and/or page ranges separated by commas. For example "pagerange=1,3,5-12" or "pagerange=allpages". Optional parameter. By default:allpages [tobw] - Convert image to black and white (recommend for color image and photo). For example "tobw=false" Optional parameter. By default:false [zone] - Specifies the region on the image for zonal OCR. The coordinates in pixels relative to the left top corner in the following format: top:left:height:width. This parameter can contain several zones separated with commas. For example "zone=0:0:100:100,50:50:50:50" Optional parameter. [outputformat] - Specifies the output file format. Can be specified up to two output formats, separated with commas. For example "outputformat=pdf,txt" Optional parameter. By default:doc [gettext] - Specifies that extracted text will be returned. For example "tobw=true" Optional parameter. By default:false [description] - Specifies your task description. Will be returned in response. Optional parameter. !!!! For getting result you must specify "gettext" or "outputformat" !!!! */ // Build your OCR: // Extraction text with English language String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true"; // Extraction text with English and German language using zonal OCR ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english,german&zone=0:0:600:400,500:1000:150:400"; // Convert first 5 pages of multipage document into doc and txt // ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english&pagerange=1-5&outputformat=doc,txt"; // Full path to uploaded document String filePath = "sarah-morgan.jpg"; byte[] fileContent = Files.readAllBytes(Paths.get(filePath)); URL url = new URL(ocrURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes())); // Specify Response format to JSON or XML (application/json or application/xml) connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length)); int httpCode; try (OutputStream stream = connection.getOutputStream()) { // Send POST request stream.write(fileContent); stream.close(); } catch (Exception e) { System.out.println(e.toString()); } httpCode = connection.getResponseCode(); System.out.println("HTTP Response code: " + httpCode); // Success request if (httpCode == HttpURLConnection.HTTP_OK) { // Get response stream String jsonResponse = GetResponseToString(connection.getInputStream()); // Parse and print response from OCR server PrintOCRResponse(jsonResponse); } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("OCR Error Message: Unauthorizied request"); } else { // Error occurred String jsonResponse = GetResponseToString(connection.getErrorStream()); JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse); // Error message System.out.println("Error Message: " + jsonObj.get("ErrorMessage")); } connection.disconnect(); }
From source file:net.securnetwork.itebooks.downloader.EbookDownloader.java
/** * Program main method.//from w w w .j a v a2s . c o m * * @param args the program arguments */ public static void main(String[] args) { if (validateArguments(args)) { int start = MIN_EBOOK_INDEX; int end = getLastEbookIndex(); String destinationFolder = null; // Check if resume mode if (args.length == 1 && args[0].equals(RESUME_ARG)) { start = Integer.parseInt(prefs.get(LAST_SAVED_EBOOK_PREF, MIN_EBOOK_INDEX - 1 + "")) + 1; //$NON-NLS-1$ destinationFolder = prefs.get(OUTPUT_FOLDER_PREF, null); } else { destinationFolder = getDestinationFolder(args); } if (destinationFolder == null) { System.err.println(Messages.getString("EbookDownloader.NoDestinationFolderFound")); //$NON-NLS-1$ return; } else { // Possibly fix the destination folder path destinationFolder = destinationFolder.replace("\\", "/"); if (!destinationFolder.endsWith("/")) { destinationFolder += "/"; } prefs.put(OUTPUT_FOLDER_PREF, destinationFolder); } if (args.length == 3) { start = getStartIndex(args); end = getEndIndex(args); } try { for (int i = start; i <= end; i++) { String ebookPage = BASE_EBOOK_URL + i + SLASH; Source sourceHTML = new Source(new URL(ebookPage)); List<Element> allTables = sourceHTML.getAllElements(HTMLElementName.TABLE); Element detailsTable = allTables.get(0); // Try to build an info bean for the ebook String bookTitle = EbookPageParseUtils.getTitle(detailsTable); if (bookTitle != null) { EbookInfo ebook = createEbookInfo(bookTitle, i, detailsTable); String filename = destinationFolder + Misc.getValidFilename(ebook.getTitle(), ebook.getSubTitle(), ebook.getYear(), ebook.getFileFormat()); System.out.print(MessageFormat.format(Messages.getString("EbookDownloader.InfoDownloading"), //$NON-NLS-1$ new Object[] { ebook.getSiteId() })); try { URL ebookPageURL = new URL(ebook.getDownloadLink()); HttpURLConnection con = (HttpURLConnection) ebookPageURL.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Referer", ebookPage); InputStream conIS = con.getInputStream(); FileUtils.copyInputStreamToFile(conIS, new File(filename)); System.out.println(Messages.getString("EbookDownloader.DownloadingOK")); //$NON-NLS-1$ prefs.put(LAST_SAVED_EBOOK_PREF, i + ""); //$NON-NLS-1$ conIS.close(); } catch (Exception e) { System.out.println(Messages.getString("EbookDownloader.DownloadingKO")); //$NON-NLS-1$ } } } } catch (Exception e) { System.err.println(Messages.getString("EbookDownloader.FatalError")); //$NON-NLS-1$ e.printStackTrace(); } } else { printHelp(); } }
From source file:com.jaeksoft.searchlib.util.LinkUtils.java
public final static void main(String[] args) throws MalformedURLException { System.out.println(getLink(new URL("http://www.example.com/test/in-75?l=75&co=FR&start=20"), "?l=75&co=FR&start=20", null, false)); System.out.println(lastPart("/my+folder/")); System.out.println(lastPart("my folder/")); System.out.println(lastPart("my folder/my+sub-folder/")); System.out.println(lastPart("/my+file.png")); System.out.println(lastPart("my+file.png")); System.out.println(lastPart("my+folder/my+sub-folder/my+file.png")); }
From source file:de.petendi.ethereum.secure.proxy.Application.java
public static void main(String[] args) { try {/*from w w w.ja va2 s. com*/ cmdLineResult = new CmdLineResult(); cmdLineResult.parseArguments(args); } catch (CmdLineException e) { System.out.println(e.getMessage()); System.out.println("Usage:"); cmdLineResult.printExample(); System.exit(-1); return; } File workingDirectory = new File(System.getProperty("user.home")); if (cmdLineResult.getWorkingDirectory().length() > 0) { workingDirectory = new File(cmdLineResult.getWorkingDirectory()).getAbsoluteFile(); } ArgumentList argumentList = new ArgumentList(); argumentList.setWorkingDirectory(workingDirectory); File certificate = new File(workingDirectory, "seccoco-secured/cert.p12"); if (certificate.exists()) { char[] passwd = null; if (cmdLineResult.getPassword() != null) { System.out.println("Using password from commandline argument - DON'T DO THIS IN PRODUCTION !!"); passwd = cmdLineResult.getPassword().toCharArray(); } else { Console console = System.console(); if (console != null) { passwd = console.readPassword("[%s]", "Enter application password:"); } else { System.out.print("No suitable console found for entering password"); System.exit(-1); } } argumentList.setTokenPassword(passwd); } try { SeccocoFactory seccocoFactory = new SeccocoFactory("seccoco-secured", argumentList); seccoco = seccocoFactory.create(); } catch (InitializationException e) { System.out.println(e.getMessage()); System.exit(-1); } try { System.out.println("Connecting to Ethereum RPC at " + cmdLineResult.getUrl()); URL url = new URL(cmdLineResult.getUrl()); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); String additionalHeaders = cmdLineResult.getAdditionalHeaders(); if (additionalHeaders != null) { StringTokenizer tokenizer = new StringTokenizer(additionalHeaders, ","); while (tokenizer.hasMoreTokens()) { String keyValue = tokenizer.nextToken(); StringTokenizer innerTokenizer = new StringTokenizer(keyValue, ":"); headers.put(innerTokenizer.nextToken(), innerTokenizer.nextToken()); } } settings = new Settings(cmdLineResult.isExposeWhisper(), headers); jsonRpcHttpClient = new JsonRpcHttpClient(url); jsonRpcHttpClient.setRequestListener(new JsonRpcRequestListener()); jsonRpcHttpClient.invoke("eth_protocolVersion", null, Object.class, headers); if (cmdLineResult.isExposeWhisper()) { jsonRpcHttpClient.invoke("shh_version", null, Object.class, headers); } System.out.println("Connection succeeded"); } catch (Throwable e) { System.out.println("Connection failed: " + e.getMessage()); System.exit(-1); } SpringApplication app = new SpringApplication(Application.class); app.setBanner(new Banner() { @Override public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) { //send the Spring Boot banner to /dev/null } }); app.run(new String[] {}); }