List of usage examples for java.io IOException getMessage
public String getMessage()
From source file:org.dcm4che3.tool.unvscp.UnvSCP.java
public static void main(String[] args) { try {// w ww . j a va 2s. c o m CommandLine cl = parseComandLine(args); final UnvSCP main = new UnvSCP(!cl.hasOption("dicomdir")); CLIUtils.configure(main.fsInfo, cl); CLIUtils.configureBindServer(main.conn, main.ae, cl); CLIUtils.configure(main.conn, cl); configureDicomFileSet(main, cl); configureLog(main, cl); configureAsyncMode(main, cl); configureManualUploading(main, cl); configureCompression(main, cl); configurePushMethod(main, cl); configureTransferCapability(main, cl); configureRoleSelectionsAndExtendedNegotiations(main, cl); configureInstanceAvailability(main, cl); configureStgCmt(main, cl); configureSendPending(main, cl); configureDestinationOverride(main, cl); configureSession(main, cl); configureRemoteConnections(main, cl); configureVisualInterface(main, cl); ExecutorService executorService = Executors.newCachedThreadPool(); ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); main.device.setScheduledExecutor(scheduledExecutorService); main.device.setExecutor(executorService); main.device.bindConnections(); main.device.setAssociationHandler(new AssociationHandler() { @Override protected AAssociateAC negotiate(Association as, AAssociateRQ rq) throws IOException { //as.getCallingAET(); as.getRemoteAET(); // show the same result LOG.info("{} >> A-ASSOCIATE-RQ {}", "Association" + as.toString().replaceFirst("\\b[^+^-]*", ""), (rq != null ? rq.getCallingAET() : "")); try { UnvWebClient webClient = new UnvWebClient(main.dicomUrl.toString()); webClient.addListener(main, new DicomClientMetaInfo(as)); webClient.setBasicParams(main.emsowUsername, main.emsowPassword, "EMSOW-AUTH", as); if (main.notConcurrent) { synchronized (main) { webClient.sendPostRequest(); } } else { webClient.sendPostRequest(); } CAuthWebResponse cawr = webClient.parseJsonResponse(CAuthWebResponse.class); Collection<CAuthWebResponse.AERecord> ae_client_list = cawr.getClientsData(); if (ae_client_list != null) { synchronized (main.emsowClientAets) { main.emsowServerAeMeta = cawr.getServerData(); main.emsowClientAets.clear(); for (CAuthWebResponse.AERecord aerec : ae_client_list) { main.emsowClientAets.put(aerec.getAET(), aerec); } main.isPullForUnknownEnabled = cawr.isPullForUnknownEnabled(); main.isPushForUnknownEnabled = cawr.isPushForUnknownEnabled(); } if (UnvSCP.isDynamicAEList) { synchronized (main.remoteConnections) { main.remoteConnections.clear(); for (CAuthWebResponse.AERecord aerec : ae_client_list) { String host = (aerec.getHost() == null) ? "" : aerec.getHost(); String port = (aerec.getHost() == null || "".equals(aerec.getPort().trim())) ? "104" : aerec.getPort(); main.addRemoteConnection(aerec.getAET(), UnvSCP.createAllowedConnection(host + ":" + port)); } } } } } catch (IOException ioe) { throw new UnvAAssociateRJ(UnvAAssociateRJ.RESULT_REJECTED_PERMANENT, UnvAAssociateRJ.SOURCE_SERVICE_USER, UnvAAssociateRJ.REASON_CALLING_AET_NOT_RECOGNIZED, ioe.getMessage()); } catch (Exception e) { throw new UnvAAssociateRJ(UnvAAssociateRJ.RESULT_REJECTED_PERMANENT, UnvAAssociateRJ.SOURCE_SERVICE_USER, UnvAAssociateRJ.REASON_USER_DEFINED, e.getMessage()); } AAssociateAC ac = super.negotiate(as, rq); for (RoleSelection rs : main.roleSelections) { ac.addRoleSelection(rs); } for (ExtendedNegotiation extNeg : main.extendedNegotiaions) { ac.addExtendedNegotiation(extNeg); } return ac; } }); if (main.async) { AsyncSenderTask asyncSenderTask = new AsyncSenderTask(main.dicomUrl, main.emsowUsername, main.emsowPassword, main.storageDir, main.tmpDir, main.badFilesDir, main.sleepTime, main.notConcurrent, main.compressionLevel, main); asyncSenderTask.addSenderTaskListener(main.activityWindow); main.asyncSender = new Thread(asyncSenderTask, "ASYNC"); main.asyncSender.setDaemon(true); main.asyncSender.start(); } if (main.uplDir != null && main.uplBadFilesDir != null) { Properties params = UnvWebClient.getUploadParams(main.ae, main.conn); DcmFileSenderTask dcmFileSenderTask = new DcmFileSenderTask(main.dicomUrl, main.emsowUsername, main.emsowPassword, main.uplDir, main.tmpDir, main.uplBadFilesDir, main.uplSleepTime, main.notConcurrent, main.compressionLevel, main, params); dcmFileSenderTask.addSenderTaskListener(main.activityWindow); main.dcmFileSender = new Thread(dcmFileSenderTask, "UPL"); main.dcmFileSender.setDaemon(true); main.dcmFileSender.start(); } } catch (ParseException e) { System.err.println("unvscp: " + e.getMessage()); System.err.println(rb.getString("try")); System.exit(2); } catch (Exception e) { System.err.println("unvscp: " + e.getMessage()); e.printStackTrace(); System.exit(2); } }
From source file:edu.usc.goffish.gopher.impl.Main.java
public static void main(String[] args) { Properties properties = new Properties(); try {// w w w . j a va2 s . c om properties.load(new FileInputStream(CONFIG_FILE)); } catch (IOException e) { String message = "Error while loading Container Configuration from " + CONFIG_FILE + " Cause -" + e.getCause(); log.warning(message); } if (args.length == 4) { PropertiesConfiguration propertiesConfiguration; String url = null; URI uri = URI.create(args[3]); String dataDir = uri.getPath(); String currentHost = uri.getHost(); try { propertiesConfiguration = new PropertiesConfiguration(dataDir + "/gofs.config"); propertiesConfiguration.load(); url = (String) propertiesConfiguration.getString(DataNode.DATANODE_NAMENODE_LOCATION_KEY); } catch (ConfigurationException e) { String message = " Error while reading gofs-config cause -" + e.getCause(); handleException(message); } URI nameNodeUri = URI.create(url); INameNode nameNode = new RemoteNameNode(nameNodeUri); int partition = -1; try { for (URI u : nameNode.getDataNodes()) { if (URIHelper.isLocalURI(u)) { IDataNode dataNode = DataNode.create(u); IntCollection partitions = dataNode.getLocalPartitions(args[2]); partition = partitions.iterator().nextInt(); break; } } if (partition == -1) { String message = "Partition not loaded from uri : " + nameNodeUri; handleException(message); } properties.setProperty(GopherInfraHandler.PARTITION, String.valueOf(partition)); } catch (Exception e) { String message = "Error while loading Partitions from " + nameNodeUri + " Cause -" + e.getMessage(); e.printStackTrace(); handleException(message); } properties.setProperty(Constants.STATIC_PELLET_COUNT, String.valueOf(1)); FloeRuntimeEnvironment environment = FloeRuntimeEnvironment.getEnvironment(); environment.setSystemConfig(properties); properties.setProperty(Constants.CURRET_HOST, currentHost); String managerHost = args[0]; int managerPort = Integer.parseInt(args[1]); Container container = environment.getContainer(); container.setManager(managerHost, managerPort); DefaultClientConfig config = new DefaultClientConfig(); config.getProperties().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true); config.getFeatures().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true); Client c = Client.create(config); if (managerHost == null || managerPort == 0) { handleException("Manager Host / Port have to be configured in " + args[0]); } WebResource r = c.resource("http://" + managerHost + ":" + managerPort + "/Manager/addContainerInfo/Container=" + container.getContainerInfo().getContainerId() + "/Host=" + container.getContainerInfo().getContainerHost()); c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); r.post(); log.log(Level.INFO, "Container started "); } else { String message = "Invalid arguments , arg[0]=Manager host, " + "arg[1] = mamanger port,arg[2]=graph id,arg[3]=partition uri"; message += "\n Current Arguments...." + args.length + "\n"; for (int i = 0; i < args.length; i++) { message += "arg " + i + " : " + args[i] + "\n"; } handleException(message); } }
From source file:com.mycompany.sparkrentals.Main.java
public static void main(String[] args) { initializeSolrCqlHostsFromArgs(args); // Configure Solr connection RentalSolrClient solrClient = new RentalSolrClient(); solrClient.connect(solrUrl);// w ww .ja v a 2 s .co m // Configure Cassandra connection CqlClient cqlClient = new CqlClient(); cqlClient.connect(cqlHost); cqlClient.setCqlKeyspace(cqlKeyspace); // Configure the view directory Configuration viewConfig = new Configuration(); viewConfig.setClassForTemplateLoading(Main.class, "/views"); FreeMarkerEngine freeMarkerEngine = new FreeMarkerEngine(viewConfig); // Configure the static files directory staticFileLocation("/public"); //exception handling exception(DriverException.class, (exception, request, response) -> { //handle exception for cassandra serve exception response.body("Something wrong for cassandra server " + exception.getMessage()); }); exception(Exception.class, (exception, request, response) -> { //handle exception response.body("Sorry something went wrong. Please try again later."); }); //start setting up routes here get("/add", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("data", new HashMap<>()); fillFormSelectionOption(attributes); return new ModelAndView(attributes, "add.ftl"); }, freeMarkerEngine); post("/add", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); AddRentalForm form = new AddRentalForm(); form.setQueryMap(request.queryMap()); if (form.validate()) { //valid rental data, so will insert into database and solr // or it'll update if one recrod already exists with the same key Rental rental = new Rental(); rental.SetValuesFromMap(form.getCleanedData()); //Assuming for now there's only one currency $ //so we don't need to ask the user to select, we preset it here rental.setCurrency("$"); rental.setUpdated(new Date()); //insert into cql db cqlClient.insertOrUpdateRental(rental); //add index to solr at the same time try { solrClient.addRental(rental); } catch (IOException e) { attributes.put("message", "exception connecting to solr server"); return new ModelAndView(attributes, "exception.ftl"); } catch (SolrServerException e) { attributes.put("message", "solr server exception"); return new ModelAndView(attributes, "exception.ftl"); } return new ModelAndView(attributes, "add_done.ftl"); } // form contains errors attributes.put("errorMessages", form.getErrorMessages()); attributes.put("data", form.getDataToDisplay()); fillFormSelectionOption(attributes); return new ModelAndView(attributes, "add.ftl"); }, freeMarkerEngine); //index is the search page get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); SearchRentalForm form = new SearchRentalForm(); form.setQueryMap(request.queryMap()); int perPage = 20; //number of results per page if (form.validate()) { Map<String, Object> cleanedData = form.getCleanedData(); //get the search results from SOLR try { QueryResponse queryResponse = solrClient.searchRentals(cleanedData, perPage); List<Rental> rentalList = queryResponse.getBeans(Rental.class); //these are for pagination purpose long resultsTotal = queryResponse.getResults().getNumFound(); attributes.put("resultsTotal", resultsTotal); int currentPage = (int) cleanedData.getOrDefault("page", 1); attributes.put("currentPage", currentPage); long maxPage = (resultsTotal % perPage > 0 ? 1 : 0) + resultsTotal / perPage; attributes.put("maxPage", maxPage); attributes.put("rentalList", rentalList); attributes.put("errorMessages", new ArrayList<>()); } catch (IOException e) { attributes.put("errorMessages", Arrays.asList("Exception when connecting to Solr!" + e.getMessage())); } catch (SolrException e) { //there is an error for querying attributes.put("errorMessages", Arrays.asList("Solr query error!")); } } else { //search form not valid attributes.put("rentalList", new ArrayList<>()); attributes.put("errorMessages", form.getErrorMessages()); } if (!attributes.containsKey("rentalList")) { attributes.put("rentalList", new ArrayList<>()); } //for disply back to user entered data attributes.put("data", form.getDataToDisplay()); fillFormSelectionOption(attributes); return new ModelAndView(attributes, "index.ftl"); }, freeMarkerEngine); }
From source file:de.ipbhalle.metfrag.main.CommandLineTool.java
/** * @param args/* ww w .j a v a 2 s . c om*/ * @throws Exception */ public static void main(String[] args) { CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption("d", "database", true, "database: " + Databases.getString() + " (default: kegg)"); options.addOption("l", "localdb", true, "use a local database together with a settings file for candidate search (default: not used) note: only usable if pubchem database is selected (-d)"); options.addOption("a", "mzabs", true, "allowed absolute (Da) mass deviation of fragment and peak masses (default: 0.01)"); options.addOption("p", "mzppm", true, "allowed relative (ppm) mass deviation of fragment and peak masses (default: 10)"); options.addOption("s", "searchppm", true, "relative (ppm) mass deviation used for candidate search in given compound database (-d) (default: 10; not used by default if sdf database is selected (-d))\n"); options.addOption("n", "exactmass", true, "neutral mass of measured compound used for candidate search in database (-d) (mandatory)"); options.addOption("b", "biological", false, "only consider compounds including CHNOPS atoms (not used by default)"); options.addOption("i", "databaseids", true, "database ids of compounds used for in silico fragmentation (separated by ,) (not used by default; not used if sdf database is selected (-d)) note: given ids must be valid ids of given database (-d)"); options.addOption("t", "treedepth", true, "treedepth used for in silico fragmentation (default: 2) note: high values result in high computation time"); options.addOption("M", "mode", true, "mode used for measured ms/ms spectrum:\n" + Modes.getString() + "(default: 3)"); options.addOption("f", "formula", true, "molecular formula of measured compound used for candidate search in database (-d) (not used by default; not used if sdf database is selected (-d))"); options.addOption("B", "breakrings", false, "allow splitting of aromatic rings of candidate structures during in silico fragmentation (not used by default)"); options.addOption("F", "storefragments", false, "store in silico generated fragments of candidate molecules (not used by default)"); options.addOption("R", "resultspath", true, "directory where result files are stored (default: /tmp)"); options.addOption("L", "sdffile", true, "location of the local sdf file (mandatory if sdf database (-d) is selected)"); options.addOption("h", "help", false, "print help"); options.addOption("D", "spectrumfile", true, "file containing peak data (mandatory) note: commandline options overwrite parameters given in the spectrum data file"); options.addOption("T", "threads", true, "number of threads used for fragment calculation (default: number of available cpu cores)"); options.addOption("c", "chemspidertoken", true, "Token for ChemSpider database search (not used by default; only necessary (mandatory) if ChemSpider database (-d) is selected)"); options.addOption("v", "verbose", false, "get more output information during the processing (not used by default)"); options.addOption("S", "samplename", true, "name of the sample measured (mandatory) note: result files are stored with given value"); options.addOption("P", "saveparameters", false, "save used parameters (not used by default)"); options.addOption("e", "printexamplespecfile", false, "print an example spectrum data file (not used by default)"); options.addOption("C", "charge", true, "charge used in combination with mode (-M):\n" + Charges.getString() + " (default: 1)"); options.addOption("r", "range", true, "range of candidates that will be processed: N (first N), M-N (from M to N), M- (from M), -N (till N); if N is greater than the number of candidates it will be set accordingly"); // parse the command line arguments CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException e1) { System.out.println(e1.getMessage()); System.out.println("Error: Could not parse option parameters."); System.out.println("Use help -h (--help) for information."); System.exit(1); } if (line == null) { System.out.println("Error: Could not parse option parameters."); System.out.println("Use help -h (--help) for information."); System.exit(1); } if (checkInitialParamsPresent(line, options)) System.exit(0); if (!checkSpectrumFile(line)) { System.out.println("Error: Option parameters are not set correctly."); System.out.println("Use help -h (--help) for information."); System.exit(1); } if (!parseSpectrumFile(spectrumfile)) { System.out.println("Error: Could not correctly parse the spectrum data file."); System.out.println("Use help -h (--help) for information."); System.exit(1); } int successfulSet = setParameters(line, options); if (successfulSet == 2) System.exit(0); if (successfulSet != 0) { System.out.println("Error: Option parameters are not set correctly."); System.out.println("Use help -h (--help) for information."); System.exit(1); } boolean successfulChecked = true; if (successfulSet == 0) successfulChecked = checkParameters(); if (saveParametersIsSet) { try { BufferedWriter bwriter = new BufferedWriter(new FileWriter(new File( resultspath + System.getProperty("file.separator") + "parameters_" + sampleName + ".txt"))); bwriter.write(getParameters()); bwriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { boolean isPositive = true; if (charge.getValue() == 2) isPositive = false; spec = new WrapperSpectrum(peaksString, mode.getValueWithOffset(), exactMass.getValue(), isPositive); } catch (Exception e) { System.out.println("Error: Could not parse spectrum correctly. Check the given peak list."); System.exit(1); } if (!successfulChecked) { System.out.println("Error: Option parameters are not set correctly."); System.out.println("Use help -h (--help) for information."); System.exit(1); } List<MetFragResult> results = null; String pathToStoreFrags = ""; if (storeFragments) pathToStoreFrags = resultspath; //run metfrag when all checks were successful if (usesdf) { try { if (verbose) { System.out.println("start fragmenter with local database"); System.out.println("using database " + database); } results = MetFrag.startConvenienceSDF(spec, mzabs.getValue(), mzppm.getValue(), searchppm.getValue(), true, breakRings, treeDepth.getValue(), true, true, true, false, Integer.MAX_VALUE, true, sdfFile, "", null, searchppmIsSet, pathToStoreFrags, numberThreads.getValue(), verbose, sampleName, onlyBiologicalCompounds); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); System.out.println("Error: Could not perform in silico fragmentation step."); System.exit(1); } } else { try { if (verbose) { if (!localdbIsSet) System.out.println("start fragmenter with web database"); else System.out.println("start fragmenter with local database"); System.out.println("using database " + database); } results = MetFrag.startConvenience(database, databaseIDs, formula, exactMass.getValue(), spec, useProxy, mzabs.getValue(), mzppm.getValue(), searchppm.getValue(), true, breakRings, treeDepth.getValue(), true, false, true, false, startindex.getValue(), endindex.getValue(), true, pathToStoreFrags, numberThreads.getValue(), chemSpiderToken, verbose, sampleName, localdb, onlyBiologicalCompounds, dblink, dbuser, dbpass, uniquebyinchi); } catch (Exception e) { e.printStackTrace(); System.out.println("Error: " + e.getMessage()); System.out.println("Error: Could not perform in silico fragmentation step."); System.exit(1); } } saveResults(results); }
From source file:btrplace.fromEntropy.Converter.java
public static void main(String[] args) { String src, dst = null, output, scriptDC = null, dirScriptsCL = null; if (args.length < 5 || args.length > 6 || !args[args.length - 2].equals("-o")) { usage(1);//from w w w.j a va 2s .co m } src = args[0]; output = args[args.length - 1]; if (args.length > 5) { dst = args[1]; } scriptDC = args[args.length - 4]; dirScriptsCL = args[args.length - 3]; OutputStreamWriter out = null; try { // Convert the src file ConfigurationConverter conv = new ConfigurationConverter(src); Instance i = conv.getInstance(); // Read the dst file, deduce and add the states constraints if (dst != null) { i.getSatConstraints().addAll(conv.getNextStates(dst)); } // Read the script files ScriptBuilder scriptBuilder = new ScriptBuilder(i.getModel()); //scriptBuilder.setIncludes(new PathBasedIncludes(scriptBuilder, // new File("src/test/resources"))); // Read the datacenter script file if exists if (scriptDC != null) { String strScriptDC = null; try { strScriptDC = readFile(scriptDC); } catch (IOException e) { e.printStackTrace(); } Script scrDC = null; try { // Build the DC script scrDC = scriptBuilder.build(strScriptDC); } catch (ScriptBuilderException sbe) { System.out.println(sbe); } // Set the DC script as an include BasicIncludes bi = new BasicIncludes(); bi.add(scrDC); scriptBuilder.setIncludes(bi); } // Read all the client script files String scriptCL = null, strScriptCL = null; Script scrCL = null; Iterator it = FileUtils.iterateFiles(new File(dirScriptsCL), null, false); while (it.hasNext()) { scriptCL = dirScriptsCL + "/" + ((File) it.next()).getName(); if (scriptCL != null) { // Read try { strScriptCL = readFile(scriptCL); } catch (IOException e) { e.printStackTrace(); } // Parse try { scrCL = scriptBuilder.build(strScriptCL); } catch (ScriptBuilderException sbe) { System.out.println(sbe); sbe.printStackTrace(); } // Add the resulting constraints if (scrCL.getConstraints() != null) { i.getSatConstraints().addAll(scrCL.getConstraints()); } } } /************** PATCH **************/ // State constraints; for (Node n : i.getModel().getMapping().getOnlineNodes()) { i.getSatConstraints().add(new Online(n)); } for (Node n : i.getModel().getMapping().getOfflineNodes()) { i.getSatConstraints().add(new Offline(n)); } // Remove preserve constraints for (Iterator<SatConstraint> ite = i.getSatConstraints().iterator(); ite.hasNext();) { SatConstraint s = ite.next(); if (s instanceof Preserve && src.contains("nr")) { ite.remove(); } } /************************************/ // Convert to JSON InstanceConverter iConv = new InstanceConverter(); JSONObject o = iConv.toJSON(i); // Check for gzip extension if (output.endsWith(".gz")) { out = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(output))); } else { out = new FileWriter(output); } // Write the output file o.writeJSONString(out); out.close(); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); } finally { if (out != null) { try { out.close(); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } } } }
From source file:com.adobe.aem.demomachine.communities.Loader.java
public static void main(String[] args) { String hostname = null;/*from w ww. j a v a2 s .c om*/ String port = null; String altport = null; String csvfile = null; String analytics = null; String adminPassword = "admin"; boolean reset = false; boolean configure = false; boolean minimize = false; boolean noenablement = true; int maxretries = MAXRETRIES; // Command line options for this tool Options options = new Options(); options.addOption("h", true, "Hostname"); options.addOption("p", true, "Port"); options.addOption("a", true, "Alternate Port"); options.addOption("f", true, "CSV file"); options.addOption("r", false, "Reset"); options.addOption("u", true, "Admin Password"); options.addOption("c", false, "Configure"); options.addOption("m", false, "Minimize"); options.addOption("e", false, "No Enablement"); options.addOption("s", true, "Analytics Endpoint"); options.addOption("t", false, "Analytics"); options.addOption("w", false, "Retry"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { hostname = cmd.getOptionValue("h"); } if (cmd.hasOption("p")) { port = cmd.getOptionValue("p"); } if (cmd.hasOption("a")) { altport = cmd.getOptionValue("a"); } if (cmd.hasOption("f")) { csvfile = cmd.getOptionValue("f"); } if (cmd.hasOption("u")) { adminPassword = cmd.getOptionValue("u"); } if (cmd.hasOption("t")) { if (cmd.hasOption("s")) { analytics = cmd.getOptionValue("s"); } } if (cmd.hasOption("r")) { reset = true; } if (cmd.hasOption("w")) { maxretries = Integer.parseInt(cmd.getOptionValue("w")); } if (cmd.hasOption("c")) { configure = true; } if (cmd.hasOption("m")) { minimize = true; } if (cmd.hasOption("e")) { noenablement = false; } if (csvfile == null || port == null || hostname == null) { System.out.println( "Request parameters: -h hostname -p port -a alternateport -u adminPassword -f path_to_CSV_file -r (true|false, delete content before import) -c (true|false, post additional properties)"); System.exit(-1); } } catch (ParseException ex) { logger.error(ex.getMessage()); } logger.debug("AEM Demo Loader: Processing file " + csvfile); try { // Reading and processing the CSV file, stand alone or as part of a ZIP file if (csvfile != null && csvfile.toLowerCase().endsWith(".zip")) { ZipFile zipFile = new ZipFile(csvfile); ZipInputStream stream = new ZipInputStream(new FileInputStream(csvfile)); ZipEntry zipEntry; while ((zipEntry = stream.getNextEntry()) != null) { if (!zipEntry.isDirectory() && zipEntry.getName().toLowerCase().endsWith(".csv")) { InputStream is = zipFile.getInputStream(zipEntry); BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); processLoading(null, in, hostname, port, altport, adminPassword, analytics, reset, configure, minimize, noenablement, csvfile, maxretries); } } try { stream.close(); zipFile.close(); } catch (IOException ioex) { //omitted. } } else if (csvfile.toLowerCase().endsWith(".csv")) { Reader in = new FileReader(csvfile); processLoading(null, in, hostname, port, altport, adminPassword, analytics, reset, configure, minimize, noenablement, csvfile, maxretries); } } catch (IOException e) { logger.error(e.getMessage()); } }
From source file:com.zimbra.cs.zclient.ZMailboxUtil.java
public static void main(String args[]) throws IOException, ServiceException { CliUtil.toolSetup();//from w w w . j a v a2s .co m SoapTransport.setDefaultUserAgent("zmmailbox", BuildInfo.VERSION); ZMailboxUtil pu = new ZMailboxUtil(); CommandLineParser parser = new GnuParser(); Options options = new Options(); options.addOption("a", "admin", true, "admin account name to auth as"); options.addOption("z", "zadmin", false, "use zimbra admin name/password from localconfig for admin/password"); options.addOption("h", "help", false, "display usage"); options.addOption("f", "file", true, "use file as input stream"); options.addOption("u", "url", true, "http[s]://host[:port] of server to connect to"); options.addOption("r", "protocol", true, "protocol to use for request/response [soap11, soap12, json]"); options.addOption("m", "mailbox", true, "mailbox to open"); options.addOption(null, "auth", true, "account name to auth as; defaults to -m unless -A is used"); options.addOption("A", "admin-priv", false, "execute requests with admin privileges"); options.addOption("p", "password", true, "auth password"); options.addOption("P", "passfile", true, "filename with password in it"); options.addOption("t", "timeout", true, "timeout (in seconds)"); options.addOption("v", "verbose", false, "verbose mode"); options.addOption("d", "debug", false, "debug mode"); options.addOption(SoapCLI.OPT_AUTHTOKEN); options.addOption(SoapCLI.OPT_AUTHTOKENFILE); CommandLine cl = null; boolean err = false; try { cl = parser.parse(options, args, true); } catch (ParseException pe) { stderr.println("error: " + pe.getMessage()); err = true; } if (err || cl.hasOption('h')) { pu.usage(); } try { boolean isAdmin = false; pu.setVerbose(cl.hasOption('v')); if (cl.hasOption('a')) { pu.setAdminAccountName(cl.getOptionValue('a')); pu.setUrl(DEFAULT_ADMIN_URL, true); isAdmin = true; } if (cl.hasOption('z')) { pu.setAdminAccountName(LC.zimbra_ldap_user.value()); pu.setPassword(LC.zimbra_ldap_password.value()); pu.setUrl(DEFAULT_ADMIN_URL, true); isAdmin = true; } if (cl.hasOption(SoapCLI.O_AUTHTOKEN) && cl.hasOption(SoapCLI.O_AUTHTOKENFILE)) pu.usage(); if (cl.hasOption(SoapCLI.O_AUTHTOKEN)) { pu.setAdminAuthToken(ZAuthToken.fromJSONString(cl.getOptionValue(SoapCLI.O_AUTHTOKEN))); pu.setUrl(DEFAULT_ADMIN_URL, true); isAdmin = true; } if (cl.hasOption(SoapCLI.O_AUTHTOKENFILE)) { String authToken = StringUtil.readSingleLineFromFile(cl.getOptionValue(SoapCLI.O_AUTHTOKENFILE)); pu.setAdminAuthToken(ZAuthToken.fromJSONString(authToken)); pu.setUrl(DEFAULT_ADMIN_URL, true); isAdmin = true; } String authAccount, targetAccount; if (cl.hasOption('m')) { if (!cl.hasOption('p') && !cl.hasOption('P') && !cl.hasOption('y') && !cl.hasOption('Y') && !cl.hasOption('z')) { throw ZClientException.CLIENT_ERROR("-m requires one of the -p/-P/-y/-Y/-z options", null); } targetAccount = cl.getOptionValue('m'); } else { targetAccount = null; } if ((cl.hasOption("A") || cl.hasOption("auth")) && !cl.hasOption('m')) { throw ZClientException.CLIENT_ERROR("-A/--auth requires -m", null); } if (cl.hasOption("A")) { if (!isAdmin) { throw ZClientException.CLIENT_ERROR("-A requires admin auth", null); } if (cl.hasOption("auth")) { throw ZClientException.CLIENT_ERROR("-A cannot be combined with --auth", null); } authAccount = null; } else if (cl.hasOption("auth")) { authAccount = cl.getOptionValue("auth"); } else { // default case authAccount = targetAccount; } if (!StringUtil.isNullOrEmpty(authAccount)) pu.setAuthAccountName(authAccount); if (!StringUtil.isNullOrEmpty(targetAccount)) pu.setTargetAccountName(targetAccount); if (cl.hasOption('u')) pu.setUrl(cl.getOptionValue('u'), isAdmin); if (cl.hasOption('p')) pu.setPassword(cl.getOptionValue('p')); if (cl.hasOption('P')) { pu.setPassword(StringUtil.readSingleLineFromFile(cl.getOptionValue('P'))); } if (cl.hasOption('d')) pu.setDebug(true); if (cl.hasOption('t')) pu.setTimeout(cl.getOptionValue('t')); args = cl.getArgs(); pu.setInteractive(args.length < 1); pu.initMailbox(); if (args.length < 1) { InputStream is = null; if (cl.hasOption('f')) { is = new FileInputStream(cl.getOptionValue('f')); } else { if (LC.command_line_editing_enabled.booleanValue()) { try { CliUtil.enableCommandLineEditing(LC.zimbra_home.value() + "/.zmmailbox_history"); } catch (IOException e) { System.err.println("Command line editing will be disabled: " + e); if (pu.mGlobalVerbose) { e.printStackTrace(System.err); } } } is = System.in; // This has to happen last because JLine modifies System.in. } pu.interactive(new BufferedReader(new InputStreamReader(is, "UTF-8"))); } else { pu.execute(args); } } catch (ServiceException e) { Throwable cause = e.getCause(); stderr.println("ERROR: " + e.getCode() + " (" + e.getMessage() + ")" + (cause == null ? "" : " (cause: " + cause.getClass().getName() + " " + cause.getMessage() + ")")); if (pu.mGlobalVerbose) e.printStackTrace(stderr); System.exit(2); } }
From source file:com.zimbra.cs.account.ProvUtil.java
public static void main(String args[]) throws IOException, ServiceException { CliUtil.setCliSoapHttpTransportTimeout(); ZimbraLog.toolSetupLog4jConsole("INFO", true, false); // send all logs to stderr SocketFactories.registerProtocols(); SoapTransport.setDefaultUserAgent("zmprov", BuildInfo.VERSION); ProvUtil pu = new ProvUtil(); CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "display usage"); options.addOption("f", "file", true, "use file as input stream"); options.addOption("s", "server", true, "host[:port] of server to connect to"); options.addOption("l", "ldap", false, "provision via LDAP"); options.addOption("L", "logpropertyfile", true, "log4j property file"); options.addOption("a", "account", true, "account name (not used with --ldap)"); options.addOption("p", "password", true, "password for account"); options.addOption("P", "passfile", true, "filename with password in it"); options.addOption("z", "zadmin", false, "use zimbra admin name/password from localconfig for account/password"); options.addOption("v", "verbose", false, "verbose mode"); options.addOption("d", "debug", false, "debug mode (SOAP request and response payload)"); options.addOption("D", "debughigh", false, "debug mode (SOAP req/resp payload and http headers)"); options.addOption("m", "master", false, "use LDAP master (has to be used with --ldap)"); options.addOption("t", "temp", false, "write binary values to files in temporary directory specified in localconfig key zmprov_tmp_directory"); options.addOption("r", "replace", false, "allow replacement of multi-valued attr value"); options.addOption("fd", "forcedisplay", false, "force display attr value"); options.addOption(SoapCLI.OPT_AUTHTOKEN); options.addOption(SoapCLI.OPT_AUTHTOKENFILE); CommandLine cl = null;/*from w w w.j a v a 2s. c o m*/ boolean err = false; try { cl = parser.parse(options, args, true); } catch (ParseException pe) { printError("error: " + pe.getMessage()); err = true; } if (err || cl.hasOption('h')) { pu.usage(); } if (cl.hasOption('l') && cl.hasOption('s')) { printError("error: cannot specify both -l and -s at the same time"); System.exit(2); } pu.setVerbose(cl.hasOption('v')); if (cl.hasOption('l')) { pu.setUseLdap(true, cl.hasOption('m')); } if (cl.hasOption('L')) { if (cl.hasOption('l')) { ZimbraLog.toolSetupLog4j("INFO", cl.getOptionValue('L')); } else { printError("error: cannot specify -L when -l is not specified"); System.exit(2); } } if (cl.hasOption('z')) { pu.setAccount(LC.zimbra_ldap_user.value()); pu.setPassword(LC.zimbra_ldap_password.value()); } if (cl.hasOption(SoapCLI.O_AUTHTOKEN) && cl.hasOption(SoapCLI.O_AUTHTOKENFILE)) { printError("error: cannot specify " + SoapCLI.O_AUTHTOKEN + " when " + SoapCLI.O_AUTHTOKENFILE + " is specified"); System.exit(2); } if (cl.hasOption(SoapCLI.O_AUTHTOKEN)) { ZAuthToken zat = ZAuthToken.fromJSONString(cl.getOptionValue(SoapCLI.O_AUTHTOKEN)); pu.setAuthToken(zat); } if (cl.hasOption(SoapCLI.O_AUTHTOKENFILE)) { String authToken = StringUtil.readSingleLineFromFile(cl.getOptionValue(SoapCLI.O_AUTHTOKENFILE)); ZAuthToken zat = ZAuthToken.fromJSONString(authToken); pu.setAuthToken(zat); } if (cl.hasOption('s')) { pu.setServer(cl.getOptionValue('s')); } if (cl.hasOption('a')) { pu.setAccount(cl.getOptionValue('a')); } if (cl.hasOption('p')) { pu.setPassword(cl.getOptionValue('p')); } if (cl.hasOption('P')) { pu.setPassword(StringUtil.readSingleLineFromFile(cl.getOptionValue('P'))); } if (cl.hasOption('d') && cl.hasOption('D')) { printError("error: cannot specify both -d and -D at the same time"); System.exit(2); } if (cl.hasOption('D')) { pu.setDebug(SoapDebugLevel.high); } else if (cl.hasOption('d')) { pu.setDebug(SoapDebugLevel.normal); } if (!pu.useLdap() && cl.hasOption('m')) { printError("error: cannot specify -m when -l is not specified"); System.exit(2); } if (cl.hasOption('t')) { pu.setOutputBinaryToFile(true); } if (cl.hasOption('r')) { pu.setAllowMultiValuedAttrReplacement(true); } if (cl.hasOption("fd")) { pu.setForceDisplayAttrValue(true); } args = recombineDecapitatedAttrs(cl.getArgs(), options, args); try { if (args.length < 1) { pu.initProvisioning(); InputStream is = null; if (cl.hasOption('f')) { pu.setBatchMode(true); is = new FileInputStream(cl.getOptionValue('f')); } else { if (LC.command_line_editing_enabled.booleanValue()) { try { CliUtil.enableCommandLineEditing(LC.zimbra_home.value() + "/.zmprov_history"); } catch (IOException e) { errConsole.println("Command line editing will be disabled: " + e); if (pu.verboseMode) { e.printStackTrace(errConsole); } } } // This has to happen last because JLine modifies System.in. is = System.in; } pu.interactive(new BufferedReader(new InputStreamReader(is, "UTF-8"))); } else { Command cmd = pu.lookupCommand(args[0]); if (cmd == null) { pu.usage(); } if (cmd.isDeprecated()) { pu.deprecated(); } if (pu.forceLdapButDontRequireUseLdapOption(cmd)) { pu.setUseLdap(true, false); } if (pu.needProvisioningInstance(cmd)) { pu.initProvisioning(); } try { if (!pu.execute(args)) { pu.usage(); } } catch (ArgException e) { pu.usage(); } } } catch (ServiceException e) { Throwable cause = e.getCause(); String errText = "ERROR: " + e.getCode() + " (" + e.getMessage() + ")" + (cause == null ? "" : " (cause: " + cause.getClass().getName() + " " + cause.getMessage() + ")"); printError(errText); if (pu.verboseMode) { e.printStackTrace(errConsole); } System.exit(2); } }
From source file:Main.java
public static int getWidthFromImage(String filename) { BufferedImage image;//from w w w .j av a 2 s.c om try { image = ImageIO.read(new File(filename)); return image.getWidth(); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } return -1; }
From source file:com.ctt.sshlistener.Main.java
public static void appendLog(String log) { try {//from www . j a va2 s . c om FileUtils.write(new File(Main.prop.getProperty("log") + "log.log"), "\n" + log, true); } catch (IOException ex) { System.out.println(ex.getMessage()); } }