List of usage examples for java.util Vector size
public synchronized int size()
From source file:com.sittinglittleduck.DirBuster.workGenerators.WorkerGenerator.java
/** Thread run method */ public void run() { String currentDir = "/"; int failcode = 404; String line;//from w ww .j a v a2 s .c o m Vector extToCheck = new Vector(10, 5); boolean recursive = true; int passTotal = 0; // -------------------------------------------------- try { // find the total number of requests to be made, per pass // based on the fact there is a single entry per line BufferedReader d = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); passTotal = 0; while ((line = d.readLine()) != null) { if (!line.startsWith("#")) { passTotal++; } } manager.setTotalPass(passTotal); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } // ------------------------------------------------- // checks if the server surports heads requests if (manager.getAuto()) { try { URL headurl = new URL(firstPart); HeadMethod httphead = new HeadMethod(headurl.toString()); // set the custom HTTP headers Vector HTTPheaders = manager.getHTTPHeaders(); for (int a = 0; a < HTTPheaders.size(); a++) { HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a); /* * Host header has to be set in a different way! */ if (httpHeader.getHeader().startsWith("Host:")) { httphead.getParams().setVirtualHost(httpHeader.getValue()); } else { httphead.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue()); } } httphead.setFollowRedirects(Config.followRedirects); int responceCode = httpclient.executeMethod(httphead); if (Config.debug) { System.out.println("DEBUG WokerGen: responce code for head check = " + responceCode); } // if the responce code is method not implemented or if the head requests return // 400! if (responceCode == 501 || responceCode == 400 || responceCode == 405) { if (Config.debug) { System.out.println( "DEBUG WokerGen: Changing to GET only HEAD test returned 501(method no implmented) or a 400"); } // switch the mode to just GET requests manager.setAuto(false); } } catch (MalformedURLException e) { // TODO deal with error } catch (IOException e) { // TODO deal with error } } // end of checks to see if server surpports head requests int counter = 0; while ((!dirQueue.isEmpty() || !workQueue.isEmpty() || !manager.areWorkersAlive()) && recursive) { // get the dir we are about to process String baseResponce = null; recursive = manager.isRecursive(); BaseCase baseCaseObj = null; // rest the skip skipCurrent = false; // deal with the dirs try { // get item from queue // System.out.println("gen about to take"); DirToCheck tempDirToCheck = dirQueue.take(); // System.out.println("gen taken"); // get dir name currentDir = tempDirToCheck.getName(); // get any extention that need to be checked extToCheck = tempDirToCheck.getExts(); manager.setCurrentlyProcessing(currentDir); } catch (InterruptedException e) { e.printStackTrace(); } started = currentDir; // generate the list of dirs if (manager.getDoDirs()) { // find the fail case for the dir URL failurl = null; try { baseResponce = null; baseCaseObj = GenBaseCase.genBaseCase(manager, firstPart + currentDir, true, null); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // end of dir fail case if (stopMe) { return; } // generate work links try { // readin dir names BufferedReader d = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))); if (Config.debug) { System.out.println("DEBUG WokerGen: Generating dir list for " + firstPart); } URL currentURL; // add the first item while doing dir's if (counter == 0) { try { String method; if (manager.getAuto() && !baseCaseObj.useContentAnalysisMode() && !baseCaseObj.isUseRegexInstead()) { method = "HEAD"; } else { method = "GET"; } currentURL = new URL(firstPart + currentDir); // System.out.println("first part = " + firstPart); // System.out.println("current dir = " + currentDir); workQueue.put(new WorkUnit(currentURL, true, "GET", baseCaseObj, null)); if (Config.debug) { System.out.println("DEBUG WokerGen: 1 adding dir to work list " + method + " " + currentDir.toString()); } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (InterruptedException ex) { ex.printStackTrace(); } } // end of dealing with first item int dirsProcessed = 0; // add the rest of the dirs while ((line = d.readLine()) != null) { // code to skip the current work load if (skipCurrent) { // add the totalnumber per pass - the amount process this pass to the // work correction total manager.addToWorkCorrection(passTotal - dirsProcessed); break; } // if the line is not empty or starts with a # if (!line.equalsIgnoreCase("") && !line.startsWith("#")) { line = line.trim(); line = makeItemsafe(line); try { String method; if (manager.getAuto() && !baseCaseObj.useContentAnalysisMode() && !baseCaseObj.isUseRegexInstead()) { method = "HEAD"; } else { method = "GET"; } currentURL = new URL(firstPart + currentDir + line + "/"); // BaseCase baseCaseObj = new BaseCase(currentURL, failcode, true, // failurl, baseResponce); // if the base case is null then we need to switch to content // anylsis mode // System.out.println("Gen about to add to queue"); workQueue.put(new WorkUnit(currentURL, true, method, baseCaseObj, line)); // System.out.println("Gen finshed adding to queue"); if (Config.debug) { System.out.println("DEBUG WokerGen: 2 adding dir to work list " + method + " " + currentURL.toString()); } } catch (MalformedURLException e) { // TODO deal with bad line // e.printStackTrace(); // do nothing if it's malformed, I dont care about them! } catch (InterruptedException e) { e.printStackTrace(); } // if there is a call to stop the work gen then stop! if (stopMe) { return; } dirsProcessed++; } } // end of while } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // generate the list of files if (manager.getDoFiles()) { baseResponce = null; URL failurl = null; // loop for all the different file extentions for (int b = 0; b < extToCheck.size(); b++) { // only test if we are surposed to ExtToCheck extTemp = (ExtToCheck) extToCheck.elementAt(b); if (extTemp.toCheck()) { fileExtention = ""; if (extTemp.getName().equals(ExtToCheck.BLANK_EXT)) { fileExtention = ""; } else { fileExtention = "." + extTemp.getName(); } try { // get the base for this extention baseCaseObj = GenBaseCase.genBaseCase(manager, firstPart + currentDir, false, fileExtention); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // if the manager has sent the stop command then exit if (stopMe) { return; } try { BufferedReader d = new BufferedReader( new InputStreamReader(new FileInputStream(inputFile))); // if(failcode != 200) // { int filesProcessed = 0; while ((line = d.readLine()) != null) { // code to skip the current work load if (skipCurrent) { manager.addToWorkCorrection(passTotal - filesProcessed); break; } // dont process is the line empty for starts with a # if (!line.equalsIgnoreCase("") && !line.startsWith("#")) { line = line.trim(); line = makeItemsafe(line); try { String method; if (manager.getAuto() && !baseCaseObj.useContentAnalysisMode() && !baseCaseObj.isUseRegexInstead()) { method = "HEAD"; } else { method = "GET"; } URL currentURL = new URL(firstPart + currentDir + line + fileExtention); // BaseCase baseCaseObj = new BaseCase(currentURL, true, // failurl, baseResponce); workQueue.put(new WorkUnit(currentURL, false, method, baseCaseObj, line)); if (Config.debug) { System.out.println("DEBUG WokerGen: adding file to work list " + method + " " + currentURL.toString()); } } catch (MalformedURLException e) { // e.printStackTrace(); // again do nothing as I dont care } catch (InterruptedException e) { e.printStackTrace(); } if (stopMe) { return; } filesProcessed++; } } // end of while // } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } // end of file ext loop } // end of if files finished = started; counter++; try { Thread.sleep(200); } catch (InterruptedException ex) { ex.printStackTrace(); } } // end of main while // System.out.println("Gen FINISHED!"); // manager.youAreFinished(); }
From source file:net.sf.jabref.exporter.layout.LayoutEntry.java
public LayoutEntry(Vector<StringInt> parsedEntries, final String classPrefix_, int layoutType) { classPrefix = classPrefix_;//from w ww . j a v a2s .c o m Vector<StringInt> blockEntries = null; Vector<LayoutEntry> tmpEntries = new Vector<>(); LayoutEntry le; String blockStart = parsedEntries.get(0).s; String blockEnd = parsedEntries.get(parsedEntries.size() - 1).s; if (!blockStart.equals(blockEnd)) { LOGGER.warn("Field start and end entry must be equal."); } type = layoutType; text = blockEnd; for (StringInt parsedEntry : parsedEntries.subList(1, parsedEntries.size() - 1)) { if ((parsedEntry.i == LayoutHelper.IS_LAYOUT_TEXT) || (parsedEntry.i == LayoutHelper.IS_SIMPLE_FIELD)) { // Do nothing } else if ((parsedEntry.i == LayoutHelper.IS_FIELD_START) || (parsedEntry.i == LayoutHelper.IS_GROUP_START)) { blockEntries = new Vector<>(); blockStart = parsedEntry.s; } else if ((parsedEntry.i == LayoutHelper.IS_FIELD_END) || (parsedEntry.i == LayoutHelper.IS_GROUP_END)) { if (blockStart.equals(parsedEntry.s)) { blockEntries.add(parsedEntry); if (parsedEntry.i == LayoutHelper.IS_GROUP_END) { le = new LayoutEntry(blockEntries, classPrefix, LayoutHelper.IS_GROUP_START); } else { le = new LayoutEntry(blockEntries, classPrefix, LayoutHelper.IS_FIELD_START); } tmpEntries.add(le); blockEntries = null; } else { LOGGER.warn("Nested field entries are not implemented !!!"); } } else if (parsedEntry.i == LayoutHelper.IS_OPTION_FIELD) { // Do nothing } if (blockEntries == null) { tmpEntries.add(new LayoutEntry(parsedEntry, classPrefix)); } else { blockEntries.add(parsedEntry); } } layoutEntries = new LayoutEntry[tmpEntries.size()]; for (int i = 0; i < tmpEntries.size(); i++) { layoutEntries[i] = tmpEntries.get(i); // Note if one of the entries has an invalid formatter: if (layoutEntries[i].isInvalidFormatter()) { if (invalidFormatter == null) { invalidFormatter = new ArrayList<>(1); } invalidFormatter.addAll(layoutEntries[i].getInvalidFormatters()); } } }
From source file:org.martus.client.swingui.PureFxMainWindow.java
protected File[] showMultiFileOpenDialog(String title, File directory, Vector<FormatFilter> filters) { FileChooser fileChooser = createFileChooser(title, directory, filters.toArray(new FormatFilter[filters.size()])); List<File> files = fileChooser.showOpenMultipleDialog(getActiveStage()); if (files == null) return new File[0]; return files.toArray(new File[files.size()]); }
From source file:edu.ku.brc.specify.datamodel.Address.java
@Override @Transient//from w w w.ja v a 2 s.c om public Integer getParentId() { if (agent != null) { parentTblId = Agent.getClassTableId(); return agent.getId(); } Vector<Object> ids = BasicSQLUtils .querySingleCol("SELECT InstitutionID FROM institution WHERE AddressID = " + addressId); if (ids.size() == 1) { parentTblId = Institution.getClassTableId(); return (Integer) ids.get(0); } ids = BasicSQLUtils.querySingleCol("SELECT DivisionID FROM division WHERE AddressID = " + addressId); if (ids.size() == 1) { parentTblId = Division.getClassTableId(); return (Integer) ids.get(0); } parentTblId = null; return null; }
From source file:com.netscape.cmstools.client.ClientCertRequestCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); String[] cmdArgs = cmd.getArgs(); if (cmd.hasOption("help")) { printHelp();/*from www. j a v a2 s.c o m*/ return; } if (cmdArgs.length > 1) { throw new Exception("Too many arguments specified."); } String certRequestUsername = cmd.getOptionValue("username"); String subjectDN; if (cmdArgs.length == 0) { if (certRequestUsername == null) { throw new Exception("Missing subject DN or request username."); } subjectDN = "UID=" + certRequestUsername; } else { subjectDN = cmdArgs[0]; } // pkcs10, crmf String requestType = cmd.getOptionValue("type", "pkcs10"); boolean attributeEncoding = cmd.hasOption("attribute-encoding"); // rsa, ec String algorithm = cmd.getOptionValue("algorithm", "rsa"); int length = Integer.parseInt(cmd.getOptionValue("length", "1024")); String curve = cmd.getOptionValue("curve", "nistp256"); boolean sslECDH = cmd.hasOption("ssl-ecdh"); boolean temporary = !cmd.hasOption("permanent"); String s = cmd.getOptionValue("sensitive"); int sensitive; if (s == null) { sensitive = -1; } else { if (!s.equalsIgnoreCase("true") && !s.equalsIgnoreCase("false")) { throw new IllegalArgumentException("Invalid sensitive parameter: " + s); } sensitive = Boolean.parseBoolean(s) ? 1 : 0; } s = cmd.getOptionValue("extractable"); int extractable; if (s == null) { extractable = -1; } else { if (!s.equalsIgnoreCase("true") && !s.equalsIgnoreCase("false")) { throw new IllegalArgumentException("Invalid extractable parameter: " + s); } extractable = Boolean.parseBoolean(s) ? 1 : 0; } String transportCertFilename = cmd.getOptionValue("transport"); String profileID = cmd.getOptionValue("profile"); if (profileID == null) { if (algorithm.equals("rsa")) { profileID = "caUserCert"; } else if (algorithm.equals("ec")) { profileID = "caECUserCert"; } } boolean withPop = !cmd.hasOption("without-pop"); AuthorityID aid = null; if (cmd.hasOption("issuer-id")) { String aidString = cmd.getOptionValue("issuer-id"); try { aid = new AuthorityID(aidString); } catch (IllegalArgumentException e) { throw new Exception("Invalid issuer ID: " + aidString, e); } } X500Name adn = null; if (cmd.hasOption("issuer-dn")) { String adnString = cmd.getOptionValue("issuer-dn"); try { adn = new X500Name(adnString); } catch (IOException e) { throw new Exception("Invalid issuer DN: " + adnString, e); } } if (aid != null && adn != null) { throw new Exception("--issuer-id and --issuer-dn options are mutually exclusive"); } MainCLI mainCLI = (MainCLI) parent.getParent(); File certDatabase = mainCLI.certDatabase; String password = mainCLI.config.getNSSPassword(); if (password == null) { throw new Exception("Missing security database password."); } String csr; PKIClient client; if ("pkcs10".equals(requestType)) { if ("rsa".equals(algorithm)) { csr = generatePkcs10Request(certDatabase, password, algorithm, Integer.toString(length), subjectDN); } else if ("ec".equals(algorithm)) { csr = generatePkcs10Request(certDatabase, password, algorithm, curve, subjectDN); } else { throw new Exception("Error: Unknown algorithm: " + algorithm); } // initialize database after PKCS10Client to avoid conflict mainCLI.init(); client = getClient(); } else if ("crmf".equals(requestType)) { // initialize database before CRMFPopClient to load transport certificate mainCLI.init(); client = getClient(); String encoded; if (transportCertFilename == null) { SystemCertClient certClient = new SystemCertClient(client, "ca"); encoded = certClient.getTransportCert().getEncoded(); } else { encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename))); } byte[] transportCertData = Cert.parseCertificate(encoded); CryptoManager manager = CryptoManager.getInstance(); X509Certificate transportCert = manager.importCACertPackage(transportCertData); // get archival and key wrap mechanisms from CA String kwAlg = CRMFPopClient.getKeyWrapAlgotihm(client); KeyWrapAlgorithm keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg); csr = generateCrmfRequest(transportCert, subjectDN, attributeEncoding, algorithm, length, curve, sslECDH, temporary, sensitive, extractable, withPop, keyWrapAlgorithm); } else { throw new Exception("Unknown request type: " + requestType); } if (verbose) { System.out.println("CSR:"); System.out.println(csr); } CAClient caClient = new CAClient(client); CACertClient certClient = new CACertClient(caClient); if (verbose) { System.out.println("Retrieving " + profileID + " profile."); } CertEnrollmentRequest request = certClient.getEnrollmentTemplate(profileID); // Key Generation / Dual Key Generation for (ProfileInput input : request.getInputs()) { ProfileAttribute typeAttr = input.getAttribute("cert_request_type"); if (typeAttr != null) { typeAttr.setValue(requestType); } ProfileAttribute csrAttr = input.getAttribute("cert_request"); if (csrAttr != null) { csrAttr.setValue(csr); } } // parse subject DN and put the values in a map DN dn = new DN(subjectDN); Vector<?> rdns = dn.getRDNs(); Map<String, String> subjectAttributes = new HashMap<String, String>(); for (int i = 0; i < rdns.size(); i++) { RDN rdn = (RDN) rdns.elementAt(i); String type = rdn.getTypes()[0].toLowerCase(); String value = rdn.getValues()[0]; subjectAttributes.put(type, value); } ProfileInput sn = request.getInput("Subject Name"); if (sn != null) { if (verbose) System.out.println("Subject Name:"); for (ProfileAttribute attribute : sn.getAttributes()) { String name = attribute.getName(); String value = null; if (name.equals("subject")) { // get the whole subject DN value = subjectDN; } else if (name.startsWith("sn_")) { // get value from subject DN value = subjectAttributes.get(name.substring(3)); } else { // unknown attribute, ignore if (verbose) System.out.println(" - " + name); continue; } if (value == null) continue; if (verbose) System.out.println(" - " + name + ": " + value); attribute.setValue(value); } } if (certRequestUsername != null) { request.setAttribute("uid", certRequestUsername); } if (cmd.hasOption("password")) { Console console = System.console(); String certRequestPassword = new String(console.readPassword("Password: ")); request.setAttribute("pwd", certRequestPassword); } if (verbose) { System.out.println("Sending certificate request."); } CertRequestInfos infos = certClient.enrollRequest(request, aid, adn); MainCLI.printMessage("Submitted certificate request"); CACertCLI.printCertRequestInfos(infos); }
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.control.MonitorServ.java
/** Works like MetricsUpdates, except for offer backlog updates. These updates tell the server administrator * how many offers are waiting to be processed. When this number reaches some critical amount, the server * should temporarily stop accepting offers */ private void startOfferBacklogThread() { offerBacklogUpdates = new Vector(); Runnable updater = new Runnable() { public void run() { try { while (!offerBacklogDone) { OfferBacklogUpdate update = getNextUpdate(); if (update.backlog == -1) { log.debug("Shutting down auxiliary offer backlog update thread"); break; }/* w w w . ja va2s . c o m*/ Enumeration sessionIds = sessionMonitors.keys(); while (sessionIds.hasMoreElements()) { Integer key = (Integer) sessionIds.nextElement(); Vector monitors = (Vector) sessionMonitors.get(key); for (int i = 0; i < monitors.size(); i++) { MonitorTransmitter ui = (MonitorTransmitter) monitors.get(i); try { ui.setOfferBacklog(update.backlog, update.rejecting); } catch (MonitorDisconnectedException e) { log.error( "Failed to establish connection with MonitorTransmitter -- disconnecting from failed monitor"); disconnectMonitor(key.intValue(), ui); } } } } } catch (Exception e) { log.error("MonitorServ failed to update admin screen with offer backlog information", e); } } private synchronized OfferBacklogUpdate getNextUpdate() throws InterruptedException { try { if (offerBacklogDone) { log.info("offerBacklogUpdate ending... returning from getNextUpdate()..."); return new OfferBacklogUpdate(0, false); } if (!offerBacklogUpdates.isEmpty() && offerBacklogUpdates.size() > 0) return (OfferBacklogUpdate) offerBacklogUpdates.remove(0); else wait(1000); return getNextUpdate(); } catch (Exception e) { log.debug("Offer backlog updates lost synchronization -- resynchronizing"); return getNextUpdate(); } } }; Thread updateThr = new Thread(updater); updateThr.setDaemon(true); updateThr.start(); }
From source file:fsi_admin.JAwsS3Conn.java
@SuppressWarnings("rawtypes") private boolean subirArchivo(StringBuffer msj, AmazonS3 s3, String S3BUKT, String nombre, Vector archivos) { //System.out.println("AwsConn SubirArchivo:" + nombre + ":nombre"); if (!archivos.isEmpty()) { FileItem actual = null;/* w w w . j a v a2 s . c o m*/ try { for (int i = 0; i < archivos.size(); i++) { InputStream inputStream = null; try { actual = (FileItem) archivos.elementAt(i); ///////////////////////////////////////////////////////// //Obtain the Content length of the Input stream for S3 header InputStream is = actual.getInputStream(); byte[] contentBytes = IOUtils.toByteArray(is); Long contentLength = Long.valueOf(contentBytes.length); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(contentLength); //Reobtain the tmp uploaded file as input stream inputStream = actual.getInputStream(); //Put the object in S3 //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-')); //System.out.println("BUCKET: " + S3BUKT + " OBJETO: " + nombre.replace('_', '-')); s3.putObject(new PutObjectRequest(S3BUKT, nombre, inputStream, metadata)); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } //////////////////////////////////////////////////////////// } return true; } catch (AmazonServiceException ase) { ase.printStackTrace(); msj.append("Error de AmazonServiceException al subir archivo a S3.<br>"); msj.append("Mensaje: " + ase.getMessage() + "<br>"); msj.append("Cdigo de Estatus HTTP: " + ase.getStatusCode() + "<br>"); msj.append("Cdigo de Error AWS: " + ase.getErrorCode() + "<br>"); msj.append("Tipo de Error: " + ase.getErrorType() + "<br>"); msj.append("Request ID: " + ase.getRequestId()); return false; } catch (AmazonClientException ace) { ace.printStackTrace(); msj.append("Error de AmazonClientException al subir archivo a S3.<br>"); msj.append("Mensaje: " + ace.getMessage()); return false; } catch (IOException e) { e.printStackTrace(); msj.append("Error de Entrada/Salida al subir archivo a S3: " + e.getMessage()); return false; } } else { msj.append("Error al subir archivo a la nube: No se envi ningun archivo"); return false; } }
From source file:com.ricemap.spateDB.util.CommandLineArguments.java
public Path[] getPaths() { Vector<Path> inputPaths = new Vector<Path>(); for (String arg : args) { if (arg.startsWith("-") && arg.length() > 1) { // Skip } else if (arg.indexOf(':') != -1 && arg.indexOf(":/") == -1) { // Skip } else {// w w w. ja v a 2 s. c om inputPaths.add(new Path(arg)); } } return inputPaths.toArray(new Path[inputPaths.size()]); }