List of usage examples for java.util List get
E get(int index);
From source file:com.atlbike.etl.service.ClientFormLogin.java
/** * @param args//www .j av a 2s. co m * @throws Exception */ public static void main(String[] args) throws Exception { String authenticityToken = ""; BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore) .setRedirectStrategy(new LaxRedirectStrategy()).build(); try { HttpGet httpget = new HttpGet("https://atlbike.nationbuilder.com/login"); CloseableHttpResponse response1 = httpclient.execute(httpget); try { HttpEntity entity = response1.getEntity(); System.out.println("Content Length: " + entity.getContentLength()); System.out.println("Login form get: " + response1.getStatusLine()); // EntityUtils.consume(entity); String content = EntityUtils.toString(entity); Document doc = Jsoup.parse(content); Elements metaElements = doc.select("META"); for (Element elem : metaElements) { System.out.println(elem); if (elem.hasAttr("name") && "csrf-token".equals(elem.attr("name"))) { System.out.println("Value: " + elem.attr("content")); authenticityToken = elem.attr("content"); } } System.out.println("Initial set of cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response1.close(); } HttpUriRequest login = RequestBuilder.post() .setUri(new URI("https://atlbike.nationbuilder.com/forms/user_sessions")) .addParameter("email_address", "").addParameter("user_session[email]", "email@domain") .addParameter("user_session[password]", "magicCookie") .addParameter("user_session[remember_me]", "1").addParameter("commit", "Sign in with email") .addParameter("authenticity_token", authenticityToken).build(); CloseableHttpResponse response2 = httpclient.execute(login); try { HttpEntity entity = response2.getEntity(); // for (Header h : response2.getAllHeaders()) { // System.out.println(h); // } System.out.println("Content Length: " + entity.getContentLength()); System.out.println("Login form get: " + response2.getStatusLine()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response2.close(); } httpget = new HttpGet( // HttpUriRequest file = RequestBuilder // .post() // .setUri(new URI( "https://atlbike.nationbuilder.com/admin/membership_types/14/download"); // .build(); // CloseableHttpResponse response3 = httpclient.execute(file); CloseableHttpResponse response3 = httpclient.execute(httpget); try { HttpEntity entity = response3.getEntity(); System.out.println("Content Length: " + entity.getContentLength()); System.out.println("File Get: " + response3.getStatusLine()); saveEntity(entity); // EntityUtils.consume(entity); System.out.println("Post file get cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response3.close(); } } finally { httpclient.close(); } }
From source file:cn.jumper.study.http.ClientFormLogin.java
public static void main(String[] args) throws Exception { BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); HttpHost proxy = new HttpHost("192.168.10.3", 8080, "http"); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); try {/*from w w w. j a v a2s . co m*/ HttpGet httpget = new HttpGet("http://www.ksf-food.com/admin/Login.asp"); httpget.setConfig(config); CloseableHttpResponse response1 = httpclient.execute(httpget); try { HttpEntity entity = response1.getEntity(); System.out.println("Login form get: " + response1.getStatusLine()); EntityUtils.consume(entity); System.out.println("Initial set of cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response1.close(); } String code = ""; try { HttpUriRequest httpgetCode = RequestBuilder.get() .setUri("http://www.ksf-food.com/admin/inc/checkcode.asp").setConfig(config).build(); /* * HttpGet httpgetCode = new HttpGet( * "http://www.qufuev.com/admin/inc/checkcode.asp"); * httpgetCode.setConfig(config); */ System.out.println("Executing request " + httpgetCode.getRequestLine()); System.out.println("========================================================"); System.out.println("==httpget header =="); for (Header header : httpgetCode.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } System.out.println("==httpget header =="); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); System.out.println("==respons header =="); for (Header header : response.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } System.out.println("==respons header =="); String fileName = System.currentTimeMillis() + ""; DataOutputStream dataOutputStream = new DataOutputStream( new FileOutputStream("d://test//e3//" + fileName + ".jpg")); dataOutputStream.write(EntityUtils.toByteArray(entity)); dataOutputStream.close(); return ImageTest.getAllOcr("d://test//e3//" + fileName + ".jpg"); } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; code = httpclient.execute(httpgetCode, responseHandler); System.out.println("ClientFormLogin.main()-CheckCode:" + code); System.out.println("----------------------------------------"); } catch (IOException e) { e.printStackTrace(); } HttpUriRequest login = RequestBuilder.post() .setUri(new URI("http://www.ksf-food.com/admin/Admin_ChkLogin.asp")) .addParameter("UserName", "username").addParameter("Password", "password") .addParameter("CheckCode", code).setConfig(config).build(); System.out.println("========================================================"); System.out.println("==httpget header =="); for (Header header : login.getAllHeaders()) { System.out.println(header.getName() + ":" + header.getValue()); } CloseableHttpResponse response2 = httpclient.execute(login); try { HttpEntity entity = response2.getEntity(); System.out.println("Login form post: " + response2.getStatusLine()); // EntityUtils.consume(entity); System.out.println("ClientFormLogin.main():\\n" + EntityUtils.toString(entity, "GBK")); System.out.println("Post logon cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response2.close(); } } finally { httpclient.close(); } }
From source file:Main.java
public static void main(String[] args) { List list = new LinkedList(); DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getMonths(); for (int i = 0; i < months.length; i++) { String month = months[i]; list.add(month);/*w ww.j a v a2 s . c o m*/ } Collections.sort(list); System.out.println("Month Names = " + list); int index = Collections.binarySearch(list, "October"); if (index > 0) { System.out.println("Found at index = " + index); String month = (String) list.get(index); System.out.println("Month = " + month); } }
From source file:com.twentyn.chemicalClassifier.Runner.java
public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(args[0])); BufferedWriter writer = new BufferedWriter(new FileWriter(args[1])); try {/* ww w . j a va 2s . c om*/ Oscar oscar = new Oscar(); String line = null; /* NOTE: this is exactly the wrong way to write a TSV reader. Caveat emptor. * See http://tburette.github.io/blog/2014/05/25/so-you-want-to-write-your-own-CSV-code/ * and then use org.apache.commons.csv.CSVParser instead. */ while ((line = reader.readLine()) != null) { // TSV means split on tabs! Nothing else will do. List<String> fields = Arrays.asList(line.split("\t")); // Choke if our invariants aren't satisfied. We expect ever line to have a name and an InChI. if (fields.size() != 2) { throw new RuntimeException( String.format("Found malformed line (all lines must have two fields: %s", line)); } String name = fields.get(1); List<ResolvedNamedEntity> entities = oscar.findAndResolveNamedEntities(name); System.out.println("**********"); System.out.println("Name: " + name); List<String> outputFields = new ArrayList<>(fields.size() + 1); outputFields.addAll(fields); if (entities.size() == 0) { System.out.println("No match"); outputFields.add("noMatch"); } else if (entities.size() == 1) { ResolvedNamedEntity entity = entities.get(0); NamedEntity ne = entity.getNamedEntity(); if (ne.getStart() != 0 || ne.getEnd() != name.length()) { System.out.println("Partial match"); printEntity(entity); outputFields.add("partialMatch"); } else { System.out.println("Exact match"); printEntity(entity); outputFields.add("exactMatch"); List<ChemicalStructure> structures = entity.getChemicalStructures(FormatType.STD_INCHI); for (ChemicalStructure s : structures) { outputFields.add(s.getValue()); } } } else { // Multiple matches found! System.out.println("Multiple matches"); for (ResolvedNamedEntity e : entities) { printEntity(e); } outputFields.add("multipleMatches"); } writer.write(String.join("\t", outputFields)); writer.newLine(); } } finally { writer.flush(); writer.close(); } }
From source file:net.itransformers.postDiscoverer.core.ReportManager.java
public static void main(String[] args) throws IOException { File projectDir = new File("."); File scriptPath = new File("postDiscoverer/src/main/resources/postDiscoverer/conf/groovy/"); ResourceManagerFactory resourceManagerFactory = new XmlResourceManagerFactory( "iDiscover/resourceManager/xmlResourceManager/src/main/resources/xmlResourceManager/conf/xml/resource.xml"); Map<String, String> resourceManagerParams = new HashMap<>(); resourceManagerParams.put("projectPath", projectDir.getAbsolutePath()); ResourceManager resourceManager = resourceManagerFactory.createResourceManager("xml", resourceManagerParams);/* w w w.j av a 2s. c om*/ Map<String, String> params = new HashMap<String, String>(); params.put("protocol", "telnet"); params.put("deviceName", "R1"); params.put("deviceType", "CISCO"); params.put("address", "10.17.1.5"); params.put("port", "23"); ResourceType resource = resourceManager.findFirstResourceBy(params); List connectParameters = resource.getConnectionParams(); for (int i = 0; i < connectParameters.size(); i++) { ConnectionParamsType connParamsType = (ConnectionParamsType) connectParameters.get(i); String connectionType = connParamsType.getConnectionType(); if (connectionType.equalsIgnoreCase(params.get("protocol"))) { for (ParamType param : connParamsType.getParam()) { params.put(param.getName(), param.getValue()); } } } File postDiscoveryConfing = new File( projectDir + "/postDiscoverer/src/main/resources/postDiscoverer/conf/xml/reportGenerator.xml"); if (!postDiscoveryConfing.exists()) { System.out.println("File missing: " + postDiscoveryConfing.getAbsolutePath()); return; } ReportGeneratorType reportGenerator = null; FileInputStream is = new FileInputStream(postDiscoveryConfing); try { reportGenerator = JaxbMarshalar.unmarshal(ReportGeneratorType.class, is); } catch (JAXBException e) { logger.info(e); //To change body of catch statement use File | Settings | File Templates. } finally { is.close(); } ReportManager reportManager = new ReportManager(reportGenerator, scriptPath.getPath(), projectDir, "postDiscoverer/conf/xslt/table_creator.xslt"); StringBuffer report = null; HashMap<String, Object> groovyExecutorParams = new HashMap<String, Object>(); for (String s : params.keySet()) { groovyExecutorParams.put(s, params.get(s)); } try { report = reportManager.reportExecutor( new File("/Users/niau/Projects/Projects/netTransformer10/version1/post-discovery"), groovyExecutorParams); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } if (report != null) { System.out.println(report.toString()); } else { System.out.println("Report generation failed!"); } }
From source file:com.bluepixel.security.manager.ServerClient_test.java
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, Base64DecoderException, InvalidKeySpecException { // TODO Auto-generated method stub // ServerClient_test test = new ServerClient_test(); // Key key = test.getSecretKey(); // String plainKey = Base64.encodeWebSafe(key.getEncoded(), false); // String cipherMessage = test.encryptMessage(key, message); ///* w w w .j a v a 2 s .c o m*/ // System.out.println("*********** Sender *************"); // System.out.println("Plain Text : " + cipherMessage); // System.out.println("cipher Text : " + cipherMessage); // System.out.println("secret key : " + plainKey); // // KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); // keyGen.initialize(1024); // KeyPair keyPair = keyGen.generateKeyPair(); // Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); // String cipherText = Base64.encodeWebSafe(cipher.doFinal(plainKey.getBytes()), false); // System.out.println("secret key (encrypted with PKI): " + cipherText); // // // cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic()); // byte[] plainKeyByte = cipher.doFinal(Base64.decodeWebSafe(cipherText)); // String original = test.decryptMessage(getKeyFromString(new String(plainKeyByte)), cipherMessage); // // System.out.println("\n*********** Receiver *************"); // System.out.println("secret key (encrypted with PKI): " + cipherText); // System.out.println("secret key : " + new String(plainKey)); // System.out.println("original message : " + original); // // // System.out.println("cipher key : " + cipherText); // System.out.println("cipher message : " + cipherMessage); System.out.println("\n*********** Test Client authentication *************"); //Server.init(); // try { // Client.connect(); // } catch (NoSuchProviderException e) { // // } List<String> str = decodePoly( "ie}Fq}wxRj@uBFUd@yBLm@h@_C^mBp@sC`AeEH[BENq@?AFYDO?C?AFW@A@IFUPy@TcAFWF[~@aEhAgF@S?M?aAAQ?YAe@?]?e@"); for (int i = 0; i < str.size(); i++) { System.out.println(i + " " + str.get(i)); } }
From source file:Main.java
public static void main(String args[]) { List<Character> ll = new LinkedList<Character>(); for (char n = 'A'; n <= 'Z'; n++) ll.add(n);//from w w w .j a v a2 s. c om Collections.shuffle(ll); for (Character x : ll) System.out.print(x + " "); Collections.sort(ll); for (Character x : ll) System.out.print(x + " "); System.out.println("Searching for F."); int i = Collections.binarySearch(ll, 'F'); if (i >= 0) { System.out.println("Found at index " + i); System.out.println("Object is " + ll.get(i)); } }
From source file:glacierpipe.GlacierPipeMain.java
public static void main(String[] args) throws IOException, ParseException { CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(OPTIONS, args); if (cmd.hasOption("help")) { try (PrintWriter writer = new PrintWriter(System.err)) { printHelp(writer);/*from w w w . j ava 2 s . c o m*/ } System.exit(0); } else if (cmd.hasOption("upload")) { // Turn the CommandLine into Properties Properties cliProperties = new Properties(); for (Iterator<?> i = cmd.iterator(); i.hasNext();) { Option o = (Option) i.next(); String opt = o.getLongOpt(); opt = opt != null ? opt : o.getOpt(); String value = o.getValue(); value = value != null ? value : ""; cliProperties.setProperty(opt, value); } // Build up a configuration ConfigBuilder configBuilder = new ConfigBuilder(); // Archive name List<?> archiveList = cmd.getArgList(); if (archiveList.size() > 1) { throw new ParseException("Too many arguments"); } else if (archiveList.isEmpty()) { throw new ParseException("No archive name provided"); } configBuilder.setArchive(archiveList.get(0).toString()); // All other arguments on the command line configBuilder.setFromProperties(cliProperties); // Load any config from the properties file Properties fileProperties = new Properties(); try (InputStream in = new FileInputStream(configBuilder.propertiesFile)) { fileProperties.load(in); } catch (IOException e) { System.err.printf("Warning: unable to read properties file %s; %s%n", configBuilder.propertiesFile, e); } configBuilder.setFromProperties(fileProperties); // ... Config config = new Config(configBuilder); IOBuffer buffer = new MemoryIOBuffer(config.partSize); AmazonGlacierClient client = new AmazonGlacierClient( new BasicAWSCredentials(config.accessKey, config.secretKey)); client.setEndpoint(config.endpoint); // Actual upload try (InputStream in = new BufferedInputStream(System.in, 4096); PrintWriter writer = new PrintWriter(System.err); ObservableProperties configMonitor = config.reloadProperties ? new ObservableProperties(config.propertiesFile) : null; ProxyingThrottlingStrategy throttlingStrategy = new ProxyingThrottlingStrategy(config);) { TerminalGlacierPipeObserver observer = new TerminalGlacierPipeObserver(writer); if (configMonitor != null) { configMonitor.registerObserver(throttlingStrategy); } GlacierPipe pipe = new GlacierPipe(buffer, observer, config.maxRetries, throttlingStrategy); pipe.pipe(client, config.vault, config.archive, in); } catch (Exception e) { e.printStackTrace(System.err); } System.exit(0); } else { try (PrintWriter writer = new PrintWriter(System.err)) { writer.println("No action specified."); printHelp(writer); } System.exit(-1); } }
From source file:fr.ign.cogit.simplu3d.exe.DistributionGeneration.java
/** * @param args// ww w . ja v a 2 s. c om * @throws Exception */ public static void main(String[] args) throws Exception { IFeatureCollection<IFeature> featC = new FT_FeatureCollection<>(); /* * < Retrieve the singleton instance of the parameters object... * initialize the parameters object with the default values provided... * parse the command line to eventually change the values > */ Parameters p = Parameters .unmarshall(new File("./src/main/resources/scenario/building_parameters_project_expthese_1.xml")); EnvironnementOCL env = LoaderSHPOCL.load(p.getString("folder")); BasicPropertyUnit bpu = env.getBpU().get(1); ModelInstanceGraphConfigurationPredicate<Cuboid> pred = new ModelInstanceGraphConfigurationPredicate<Cuboid>( bpu, env.getUrbaZoneOCL().get(0)); ModelInstanceGraphConfiguration<Cuboid> config = new ModelInstanceGraphConfiguration<>(bpu, pred.getRuleChecker().getlModeInstance().get(0), new ConstantEnergy<Cuboid, Cuboid>(0), new ConstantEnergy<Cuboid, Cuboid>(0)); Sampler<ModelInstanceGraphConfiguration<Cuboid>, ModelInstanceModification<Cuboid>> samp = create_sampler(p, bpu, pred); // int count = 0; int testC = 5000; // int countTrue = 0; for (int i = 0; i < testC; i++) { // count++; ModelInstanceModification<Cuboid> modif = config.newModification(); KernelFunctor<ModelInstanceGraphConfiguration<Cuboid>, ModelInstanceModification<Cuboid>> kf = new KernelFunctor<>( Random.random(), config, modif); RandomApply.randomApply(0, samp.getKernels(), kf); boolean test = true; // samp.checkNonUpdateConfiguration(kf); List<Cuboid> lAB = (List<Cuboid>) kf.getModif().getBirth(); if (test) { // countTrue++; if (lAB.size() != 1) { System.out.println("Probabilit suprieure 1 ?"); return; } Cuboid c1 = lAB.get(0); IFeature f = new DefaultFeature(); f.setGeom(new GM_Point(new DirectPosition(c1.centerx, c1.centery))); AttributeManager.addAttribute(f, "l", c1.length, "Double"); AttributeManager.addAttribute(f, "w", c1.width, "Double"); AttributeManager.addAttribute(f, "h", c1.height, "Double"); AttributeManager.addAttribute(f, "o", c1.orientation, "Double"); featC.add(f); } } ShapefileWriter.write(featC, "H:/Distrib/dist.shp"); ShapefileWriter.write(featCD, "H:/Distrib/distdeb.shp"); }
From source file:airnowgrib2tojson.AirNowGRIB2toJSON.java
/** * @param args the command line arguments *//*from w w w.j a v a2 s .c o m*/ public static void main(String[] args) { SimpleDateFormat GMT = new SimpleDateFormat("yyMMddHH"); GMT.setTimeZone(TimeZone.getTimeZone("GMT-2")); System.out.println(GMT.format(new Date())); FTPClient ftpClient = new FTPClient(); FileOutputStream fos = null; try { //Connecting to AirNow FTP server to get the fresh AQI data ftpClient.connect("ftp.airnowapi.org"); ftpClient.login("pixelshade", "GZDN8uqduwvk"); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //downloading .grib2 file File of = new File("US-" + GMT.format(new Date()) + "_combined.grib2"); OutputStream outstr = new BufferedOutputStream(new FileOutputStream(of)); InputStream instr = ftpClient .retrieveFileStream("GRIB2/US-" + GMT.format(new Date()) + "_combined.grib2"); byte[] bytesArray = new byte[4096]; int bytesRead = -1; while ((bytesRead = instr.read(bytesArray)) != -1) { outstr.write(bytesArray, 0, bytesRead); } //Close used resources ftpClient.completePendingCommand(); outstr.close(); instr.close(); // logout the user ftpClient.logout(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { //disconnect from AirNow server ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } try { //Open .grib2 file final File AQIfile = new File("US-" + GMT.format(new Date()) + "_combined.grib2"); final GridDataset gridDS = GridDataset.open(AQIfile.getAbsolutePath()); //The data type needed - AQI; since it isn't defined in GRIB2 standard, //Aerosol type is used instead; look AirNow API documentation for details. GridDatatype AQI = gridDS.findGridDatatype("Aerosol_type_msl"); //Get the coordinate system for selected data type; //cut the rectangle to work with - time and height axes aren't present in these files //and latitude/longitude go "-1", which means all the data provided. GridCoordSystem AQIGCS = AQI.getCoordinateSystem(); List<CoordinateAxis> AQI_XY = AQIGCS.getCoordinateAxes(); Array AQIslice = AQI.readDataSlice(0, 0, -1, -1); //Variables for iterating through coordinates VariableDS var = AQI.getVariable(); Index index = AQIslice.getIndex(); //Variables for counting lat/long from the indices provided double stepX = (AQI_XY.get(2).getMaxValue() - AQI_XY.get(2).getMinValue()) / index.getShape(1); double stepY = (AQI_XY.get(1).getMaxValue() - AQI_XY.get(1).getMinValue()) / index.getShape(0); double curX = AQI_XY.get(2).getMinValue(); double curY = AQI_XY.get(1).getMinValue(); //Output details OutputStream ValLog = new FileOutputStream("USA_AQI.json"); Writer ValWriter = new OutputStreamWriter(ValLog); for (int j = 0; j < index.getShape(0); j++) { for (int i = 0; i < index.getShape(1); i++) { float val = AQIslice.getFloat(index.set(j, i)); //Write the AQI value and its coordinates if it's present by i/j indices if (!Float.isNaN(val)) ValWriter.write("{\r\n\"lat\":" + curX + ",\r\n\"lng\":" + curY + ",\r\n\"AQI\":" + val + ",\r\n},\r\n"); curX += stepX; } curY += stepY; curX = AQI_XY.get(2).getMinValue(); } } catch (Exception e) { e.printStackTrace(); } }