List of usage examples for java.util Properties getProperty
public String getProperty(String key)
From source file:edu.umd.cs.submit.CommandLineSubmit.java
public static void main(String[] args) { try {/*ww w .j a v a 2 s . c o m*/ Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443); File home = args.length > 0 ? new File(args[0]) : new File("."); Protocol.registerProtocol("easyhttps", easyhttps); File submitFile = new File(home, ".submit"); File submitUserFile = new File(home, ".submitUser"); File submitIgnoreFile = new File(home, ".submitIgnore"); File cvsIgnoreFile = new File(home, ".cvsignore"); if (!submitFile.canRead()) { System.out.println("Must perform submit from a directory containing a \".submit\" file"); System.out.println("No such file found at " + submitFile.getCanonicalPath()); System.exit(1); } Properties p = new Properties(); p.load(new FileInputStream(submitFile)); String submitURL = p.getProperty("submitURL"); if (submitURL == null) { System.out.println(".submit file does not contain a submitURL"); System.exit(1); } String courseName = p.getProperty("courseName"); String courseKey = p.getProperty("courseKey"); String semester = p.getProperty("semester"); String projectNumber = p.getProperty("projectNumber"); String authenticationType = p.getProperty("authentication.type"); String baseURL = p.getProperty("baseURL"); System.out.println("Submitting contents of " + home.getCanonicalPath()); System.out.println(" as project " + projectNumber + " for course " + courseName); FilesToIgnore ignorePatterns = new FilesToIgnore(); addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns); addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns); FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern()); Collection<File> files = find.getAllFiles(); boolean createdSubmitUser = false; Properties userProps = new Properties(); if (submitUserFile.canRead()) { userProps.load(new FileInputStream(submitUserFile)); } if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null || userProps.getProperty("oneTimePassword") == null) { System.out.println(); System.out.println( "We need to authenticate you and create a .submitUser file so you can submit your project"); createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL); createdSubmitUser = true; userProps.load(new FileInputStream(submitUserFile)); } MultipartPostMethod filePost = createFilePost(p, find, files, userProps); HttpClient client = new HttpClient(); client.setConnectionTimeout(HTTP_TIMEOUT); int status = client.executeMethod(filePost); System.out.println(filePost.getResponseBodyAsString()); if (status == 500 && !createdSubmitUser) { System.out.println("Let's try reauthenticating you"); System.out.println(); createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL); userProps.load(new FileInputStream(submitUserFile)); filePost = createFilePost(p, find, files, userProps); client = new HttpClient(); client.setConnectionTimeout(HTTP_TIMEOUT); status = client.executeMethod(filePost); System.out.println(filePost.getResponseBodyAsString()); } if (status != HttpStatus.SC_OK) { System.out.println("Status code: " + status); System.exit(1); } System.out.println("Submission accepted"); } catch (Exception e) { System.out.println(); System.out.println("An Error has occured during submission!"); System.out.println(); System.out.println("[DETAILS]"); System.out.println(e.getMessage()); e.printStackTrace(System.out); System.out.println(); } }
From source file:com.mirth.connect.server.launcher.MirthLauncher.java
public static void main(String[] args) { try {/* w w w.j a va 2 s . c o m*/ try { uninstallPendingExtensions(); installPendingExtensions(); } catch (Exception e) { logger.error("Error uninstalling or installing pending extensions.", e); } Properties mirthProperties = new Properties(); String includeCustomLib = null; try { mirthProperties.load(new FileInputStream(new File(MIRTH_PROPERTIES_FILE))); includeCustomLib = mirthProperties.getProperty(PROPERTY_INCLUDE_CUSTOM_LIB); createAppdataDir(mirthProperties); } catch (Exception e) { logger.error("Error creating the appdata directory.", e); } ManifestFile mirthServerJar = new ManifestFile("server-lib/mirth-server.jar"); ManifestFile mirthClientCoreJar = new ManifestFile("server-lib/mirth-client-core.jar"); ManifestDirectory serverLibDir = new ManifestDirectory("server-lib"); serverLibDir.setExcludes(new String[] { "mirth-client-core.jar" }); List<ManifestEntry> manifestList = new ArrayList<ManifestEntry>(); manifestList.add(mirthServerJar); manifestList.add(mirthClientCoreJar); manifestList.add(serverLibDir); // We want to include custom-lib if the property isn't found, or if it equals "true" if (includeCustomLib == null || Boolean.valueOf(includeCustomLib)) { manifestList.add(new ManifestDirectory("custom-lib")); } ManifestEntry[] manifest = manifestList.toArray(new ManifestEntry[manifestList.size()]); // Get the current server version JarFile mirthClientCoreJarFile = new JarFile(mirthClientCoreJar.getName()); Properties versionProperties = new Properties(); versionProperties.load(mirthClientCoreJarFile .getInputStream(mirthClientCoreJarFile.getJarEntry("version.properties"))); String currentVersion = versionProperties.getProperty("mirth.version"); List<URL> classpathUrls = new ArrayList<URL>(); addManifestToClasspath(manifest, classpathUrls); addExtensionsToClasspath(classpathUrls, currentVersion); URLClassLoader classLoader = new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()])); Class<?> mirthClass = classLoader.loadClass("com.mirth.connect.server.Mirth"); Thread mirthThread = (Thread) mirthClass.newInstance(); mirthThread.setContextClassLoader(classLoader); mirthThread.start(); } catch (Exception e) { e.printStackTrace(); } }
From source file:net.padlocksoftware.padlock.licensevalidator.Main.java
/** * @param args the command line arguments *//*from ww w . ja v a 2 s . c om*/ public static void main(String[] args) { parse(args); Date currentDate = new Date(); Validator v = new Validator(license, new String(Hex.encodeHex(pair.getPublic().getEncoded()))); v.setIgnoreFloatTime(true); boolean ex = false; LicenseState state; try { state = v.validate(); } catch (ValidatorException e) { state = e.getLicenseState(); } // Show test status System.out.println("\nValidation Test Results:"); System.out.println("========================\n"); for (TestResult result : state.getTests()) { System.out.println( "\t" + result.getTest().getName() + "\t\t\t" + (result.passed() ? "Passed" : "Failed")); } System.out.println("\nLicense state: " + (state.isValid() ? "Valid" : "Invalid")); // // Cycle through any dates // Date d = license.getCreationDate(); System.out.println("\nCreation date: \t\t" + d); d = license.getStartDate(); System.out.println("Start date: \t\t" + d); d = license.getExpirationDate(); System.out.println("Expiration date: \t" + d); Long floatPeroid = license.getFloatingExpirationPeriod(); if (floatPeroid != null) { long seconds = floatPeroid / 1000L; System.out.println("\nExpire after first run: " + seconds + " seconds"); } if (floatPeroid != null || license.getExpirationDate() != null) { long remaining = v.getTimeRemaining(currentDate) / 1000L; System.out.println("\nTime remaining: " + remaining + " seconds"); } // // License properties // System.out.println("\nLicense Properties"); Properties p = license.getProperties(); if (p.size() == 0) { System.out.println("None"); } for (final Enumeration propNames = p.propertyNames(); propNames.hasMoreElements();) { final String key = (String) propNames.nextElement(); System.out.println("Property: " + key + " = " + p.getProperty(key)); } // // Hardware locking // for (String address : license.getHardwareAddresses()) { System.out.println("\nHardware lock: " + address); } System.out.println("\n"); }
From source file:com.yahoo.pulsar.testclient.PerformanceConsumer.java
public static void main(String[] args) throws Exception { final Arguments arguments = new Arguments(); JCommander jc = new JCommander(arguments); jc.setProgramName("pulsar-perf-consumer"); try {/*w w w. jav a 2s.c om*/ jc.parse(args); } catch (ParameterException e) { System.out.println(e.getMessage()); jc.usage(); System.exit(-1); } if (arguments.help) { jc.usage(); System.exit(-1); } if (arguments.topic.size() != 1) { System.out.println("Only one destination name is allowed"); jc.usage(); System.exit(-1); } if (arguments.confFile != null) { Properties prop = new Properties(System.getProperties()); prop.load(new FileInputStream(arguments.confFile)); if (arguments.serviceURL == null) { arguments.serviceURL = prop.getProperty("brokerServiceUrl"); } if (arguments.serviceURL == null) { arguments.serviceURL = prop.getProperty("webServiceUrl"); } // fallback to previous-version serviceUrl property to maintain backward-compatibility if (arguments.serviceURL == null) { arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/"); } if (arguments.authPluginClassName == null) { arguments.authPluginClassName = prop.getProperty("authPlugin", null); } if (arguments.authParams == null) { arguments.authParams = prop.getProperty("authParams", null); } } // Dump config variables ObjectMapper m = new ObjectMapper(); ObjectWriter w = m.writerWithDefaultPrettyPrinter(); log.info("Starting Pulsar performance consumer with config: {}", w.writeValueAsString(arguments)); final DestinationName prefixDestinationName = DestinationName.get(arguments.topic.get(0)); final RateLimiter limiter = arguments.rate > 0 ? RateLimiter.create(arguments.rate) : null; MessageListener listener = new MessageListener() { public void received(Consumer consumer, Message msg) { messagesReceived.increment(); bytesReceived.add(msg.getData().length); if (limiter != null) { limiter.acquire(); } consumer.acknowledgeAsync(msg); } }; EventLoopGroup eventLoopGroup; if (SystemUtils.IS_OS_LINUX) { eventLoopGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2, new DefaultThreadFactory("pulsar-perf-consumer")); } else { eventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("pulsar-perf-consumer")); } ClientConfiguration clientConf = new ClientConfiguration(); clientConf.setConnectionsPerBroker(arguments.maxConnections); clientConf.setStatsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS); if (isNotBlank(arguments.authPluginClassName)) { clientConf.setAuthentication(arguments.authPluginClassName, arguments.authParams); } PulsarClient pulsarClient = new PulsarClientImpl(arguments.serviceURL, clientConf, eventLoopGroup); List<Future<Consumer>> futures = Lists.newArrayList(); ConsumerConfiguration consumerConfig = new ConsumerConfiguration(); consumerConfig.setMessageListener(listener); consumerConfig.setReceiverQueueSize(arguments.receiverQueueSize); for (int i = 0; i < arguments.numDestinations; i++) { final DestinationName destinationName = (arguments.numDestinations == 1) ? prefixDestinationName : DestinationName.get(String.format("%s-%d", prefixDestinationName, i)); log.info("Adding {} consumers on destination {}", arguments.numConsumers, destinationName); for (int j = 0; j < arguments.numConsumers; j++) { String subscriberName; if (arguments.numConsumers > 1) { subscriberName = String.format("%s-%d", arguments.subscriberName, j); } else { subscriberName = arguments.subscriberName; } futures.add( pulsarClient.subscribeAsync(destinationName.toString(), subscriberName, consumerConfig)); } } for (Future<Consumer> future : futures) { future.get(); } log.info("Start receiving from {} consumers on {} destinations", arguments.numConsumers, arguments.numDestinations); long oldTime = System.nanoTime(); while (true) { try { Thread.sleep(10000); } catch (InterruptedException e) { break; } long now = System.nanoTime(); double elapsed = (now - oldTime) / 1e9; double rate = messagesReceived.sumThenReset() / elapsed; double throughput = bytesReceived.sumThenReset() / elapsed * 8 / 1024 / 1024; log.info("Throughput received: {} msg/s -- {} Mbit/s", dec.format(rate), dec.format(throughput)); oldTime = now; } pulsarClient.close(); }
From source file:cht.Parser.java
public static void main(String[] args) throws IOException { // TODO get from google drive boolean isUnicode = false; boolean isRemoveInputFileOnComplete = false; int rowNum;/*from www . j av a2 s .c om*/ int colNum; Gson gson = new GsonBuilder().setPrettyPrinting().create(); Properties prop = new Properties(); try { prop.load(new FileInputStream("config.txt")); } catch (IOException ex) { ex.printStackTrace(); } String inputFilePath = prop.getProperty("inputFile"); String outputDirectory = prop.getProperty("outputDirectory"); System.out.println(outputDirectory); // optional String unicode = prop.getProperty("unicode"); String removeInputFileOnComplete = prop.getProperty("removeInputFileOnComplete"); inputFilePath = inputFilePath.trim(); outputDirectory = outputDirectory.trim(); if (unicode != null) { isUnicode = Boolean.parseBoolean(unicode.trim()); } if (removeInputFileOnComplete != null) { isRemoveInputFileOnComplete = Boolean.parseBoolean(removeInputFileOnComplete.trim()); } Writer out = null; FileInputStream in = null; final String newLine = System.getProperty("line.separator").toString(); final String separator = File.separator; try { in = new FileInputStream(inputFilePath); Workbook workbook = new XSSFWorkbook(in); Sheet sheet = workbook.getSheetAt(0); rowNum = sheet.getLastRowNum() + 1; colNum = sheet.getRow(0).getPhysicalNumberOfCells(); for (int j = 1; j < colNum; ++j) { String outputFilename = sheet.getRow(0).getCell(j).getStringCellValue(); // guess directory int slash = outputFilename.indexOf('/'); if (slash != -1) { // has directory outputFilename = outputFilename.substring(0, slash) + separator + outputFilename.substring(slash + 1); } String outputPath = FilenameUtils.concat(outputDirectory, outputFilename); System.out.println("--Writing " + outputPath); out = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8"); TreeMap<String, Object> map = new TreeMap<String, Object>(); for (int i = 1; i < rowNum; i++) { try { String key = sheet.getRow(i).getCell(0).getStringCellValue(); //String value = ""; Cell tmp = sheet.getRow(i).getCell(j); if (tmp != null) { // not empty string! value = sheet.getRow(i).getCell(j).getStringCellValue(); } if (!key.equals("") && !key.startsWith("#") && !key.startsWith(".")) { value = isUnicode ? StringEscapeUtils.escapeJava(value) : value; int firstdot = key.indexOf("."); String keyName, keyAttribute; if (firstdot > 0) {// a.b.c.d keyName = key.substring(0, firstdot); // a keyAttribute = key.substring(firstdot + 1); // b.c.d TreeMap oldhash = null; Object old = null; if (map.get(keyName) != null) { old = map.get(keyName); if (old instanceof TreeMap == false) { System.out.println("different type of key:" + key); continue; } oldhash = (TreeMap) old; } else { oldhash = new TreeMap(); } int firstdot2 = keyAttribute.indexOf("."); String rootName, childName; if (firstdot2 > 0) {// c, d.f --> d, f rootName = keyAttribute.substring(0, firstdot2); childName = keyAttribute.substring(firstdot2 + 1); } else {// c, d -> d, null rootName = keyAttribute; childName = null; } TreeMap<String, Object> object = myPut(oldhash, rootName, childName); map.put(keyName, object); } else {// c, d -> d, null keyName = key; keyAttribute = null; // simple string mode map.put(key, value); } } } catch (Exception e) { // just ingore empty rows } } String json = gson.toJson(map); // output json out.write(json + newLine); out.close(); } in.close(); System.out.println("\n---Complete!---"); System.out.println("Read input file from " + inputFilePath); System.out.println(colNum - 1 + " output files ate generated at " + outputDirectory); System.out.println(rowNum + " records are generated for each output file."); System.out.println("output file is ecoded as unicode? " + (isUnicode ? "yes" : "no")); if (isRemoveInputFileOnComplete) { File input = new File(inputFilePath); input.deleteOnExit(); System.out.println("Deleted " + inputFilePath); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { in.close(); } } }
From source file:com.cloud.test.utils.SubmitCert.java
public static void main(String[] args) { // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); if (arg.equals("-c")) { certFileName = iter.next();/*from w ww . ja v a2 s. co m*/ } if (arg.equals("-s")) { secretKey = iter.next(); } if (arg.equals("-a")) { apiKey = iter.next(); } if (arg.equals("-action")) { url = "Action=" + iter.next(); } } Properties prop = new Properties(); try { prop.load(new FileInputStream("conf/tool.properties")); } catch (IOException ex) { s_logger.error("Error reading from conf/tool.properties", ex); System.exit(2); } host = prop.getProperty("host"); port = prop.getProperty("port"); if (url.equals("Action=SetCertificate") && certFileName == null) { s_logger.error("Please set path to certificate (including file name) with -c option"); System.exit(1); } if (secretKey == null) { s_logger.error("Please set secretkey with -s option"); System.exit(1); } if (apiKey == null) { s_logger.error("Please set apikey with -a option"); System.exit(1); } if (host == null) { s_logger.error("Please set host in tool.properties file"); System.exit(1); } if (port == null) { s_logger.error("Please set port in tool.properties file"); System.exit(1); } TreeMap<String, String> param = new TreeMap<String, String>(); String req = "GET\n" + host + ":" + prop.getProperty("port") + "\n/" + prop.getProperty("accesspoint") + "\n"; String temp = ""; if (certFileName != null) { cert = readCert(certFileName); param.put("cert", cert); } param.put("AWSAccessKeyId", apiKey); param.put("Expires", prop.getProperty("expires")); param.put("SignatureMethod", prop.getProperty("signaturemethod")); param.put("SignatureVersion", "2"); param.put("Version", prop.getProperty("version")); StringTokenizer str1 = new StringTokenizer(url, "&"); while (str1.hasMoreTokens()) { String newEl = str1.nextToken(); StringTokenizer str2 = new StringTokenizer(newEl, "="); String name = str2.nextToken(); String value = str2.nextToken(); param.put(name, value); } //sort url hash map by key Set c = param.entrySet(); Iterator it = c.iterator(); while (it.hasNext()) { Map.Entry me = (Map.Entry) it.next(); String key = (String) me.getKey(); String value = (String) me.getValue(); try { temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&"; } catch (Exception ex) { s_logger.error("Unable to set parameter " + value + " for the command " + param.get("command"), ex); } } temp = temp.substring(0, temp.length() - 1); String requestToSign = req + temp; String signature = UtilsForTest.signRequest(requestToSign, secretKey); String encodedSignature = ""; try { encodedSignature = URLEncoder.encode(signature, "UTF-8"); } catch (Exception ex) { ex.printStackTrace(); } String url = "http://" + host + ":" + prop.getProperty("port") + "/" + prop.getProperty("accesspoint") + "?" + temp + "&Signature=" + encodedSignature; s_logger.info("Sending request with url: " + url + "\n"); sendRequest(url); }
From source file:POP3Mail.java
public static void main(String[] args) { try {/*from w w w . ja v a 2 s .c o m*/ LogManager.getLogManager().readConfiguration(new FileInputStream("logging.properties")); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String server = null; String username = null; String password = null; if (new File("mail.properties").exists()) { Properties properties = new Properties(); try { properties.load(new FileInputStream(new File("mail.properties"))); server = properties.getProperty("server"); username = properties.getProperty("username"); password = properties.getProperty("password"); ArrayList<String> list = new ArrayList<String>( Arrays.asList(new String[] { server, username, password })); list.addAll(Arrays.asList(args)); args = list.toArray(new String[list.size()]); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (args.length < 3) { System.err .println("Usage: POP3Mail <pop3 server hostname> <username> <password> [TLS [true=implicit]]"); System.exit(1); } server = args[0]; username = args[1]; password = args[2]; String proto = null; int messageid = -1; boolean implicit = false; for (int i = 3; i < args.length; ++i) { if (args[i].equals("-m")) { i += 1; messageid = Integer.parseInt(args[i]); } } // String proto = args.length > 3 ? args[3] : null; // boolean implicit = args.length > 4 ? Boolean.parseBoolean(args[4]) // : false; POP3Client pop3; if (proto != null) { System.out.println("Using secure protocol: " + proto); pop3 = new POP3SClient(proto, implicit); } else { pop3 = new POP3Client(); } pop3.setDefaultPort(110); System.out.println("Connecting to server " + server + " on " + pop3.getDefaultPort()); // We want to timeout if a response takes longer than 60 seconds pop3.setDefaultTimeout(60000); // suppress login details pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); try { pop3.connect(server); } catch (IOException e) { System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } try { if (!pop3.login(username, password)) { System.err.println("Could not login to server. Check password."); pop3.disconnect(); System.exit(1); } PrintWriter printWriter = new PrintWriter(new FileWriter("messages.csv"), true); POP3MessageInfo[] messages = null; POP3MessageInfo[] identifiers = null; if (messageid == -1) { messages = pop3.listMessages(); identifiers = pop3.listUniqueIdentifiers(); } else { messages = new POP3MessageInfo[] { pop3.listMessage(messageid) }; } if (messages == null) { System.err.println("Could not retrieve message list."); pop3.disconnect(); return; } else if (messages.length == 0) { System.out.println("No messages"); pop3.logout(); pop3.disconnect(); return; } new File("../json").mkdirs(); int count = 0; for (POP3MessageInfo msginfo : messages) { if (msginfo.number != identifiers[count].number) { throw new RuntimeException(); } msginfo.identifier = identifiers[count].identifier; BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0); ++count; if (count % 100 == 0) { logger.finest(String.format("%d %s", msginfo.number, msginfo.identifier)); } System.out.println(String.format("%d %s", msginfo.number, msginfo.identifier)); if (reader == null) { System.err.println("Could not retrieve message header."); pop3.disconnect(); System.exit(1); } if (printMessageInfo(reader, msginfo.number, printWriter)) { } } printWriter.close(); pop3.logout(); pop3.disconnect(); } catch (IOException e) { e.printStackTrace(); return; } }
From source file:com.wso2.rfid.Main.java
public static void main(String[] args) throws IOException { Properties configs = new Properties(); configs.load(/*from w w w . java2s. c o m*/ new FileInputStream(System.getProperty("rpi.agent.home") + File.separator + "config.properties")); Server server = new Server(InetSocketAddress.createUnresolved("127.0.0.1", 8084)); ServletHandler handler = new ServletHandler(); server.setHandler(handler); handler.addServletWithMapping(RFIDReaderServlet.class, "/rfid"); String controlCenterURL = configs.getProperty("control.center.url"); System.out.println("Using RPi Control Center: " + controlCenterURL); String tokenEndpoint = configs.getProperty("token.endpoint"); System.out.println("Using token endpoint: " + tokenEndpoint); APICall.setTokenEndpoint(tokenEndpoint); String primaryNwInterface = configs.getProperty("primary.nw.interface"); String userRegEndpoint = configs.getProperty("user.registration.endpoint"); System.out.println("Using user registration endpoint: " + userRegEndpoint); APICall.setUserRegistrationEndpoint(userRegEndpoint); scheduler.scheduleWithFixedDelay(new MonitoringTask(controlCenterURL, primaryNwInterface), 0, 10, TimeUnit.SECONDS); try { server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); } }
From source file:cn.webank.ecif.index.server.EcifIndexServer.java
/** * @param args//ww w .j a va2 s.c o m */ public static void main(String[] args) { final EcifIndexServer server = new EcifIndexServer(); // start spring context; final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(); context.getEnvironment().setActiveProfiles("product"); context.setConfigLocation("application.xml"); context.refresh(); context.start(); // thread pool construct ThreadPoolTaskExecutor taskThreadPool = context.getBean("taskExecutor", ThreadPoolTaskExecutor.class); server.setTaskThreadPool(taskThreadPool); ExecutorService fixedThreadPool = context.getBean("fixedTaskExecutor", ExecutorService.class); server.setSchedulerThreadPool(fixedThreadPool); EcifThreadFactory threadFactory = context.getBean("cn.webank.ecif.index.async.EcifThreadFactory", EcifThreadFactory.class); server.setThreadFactory(threadFactory); Properties props = context.getBean("ecifProperties", java.util.Properties.class); WeBankServiceDispatcher serviceDispatcher = context.getBean( "cn.webank.framework.biz.service.support.WeBankServiceDispatcher", WeBankServiceDispatcher.class); ReloadableResourceBundleMessageSource bundleMessageSource = context.getBean("messageSource", ReloadableResourceBundleMessageSource.class); String topics = props.getProperty("listener.topics"); String[] splits = topics.split(","); SolaceManager solaceManager = context.getBean("cn.webank.framework.message.SolaceManager", SolaceManager.class); MessageListener messageLisener = new MessageListener( // props.getProperty("listener.queue"), Arrays.asList(splits), Integer.parseInt(props.getProperty("listener.scanintervalseconds", "5")), taskThreadPool, Integer.parseInt(props.getProperty("listener.timeoutseconds", "5")), serviceDispatcher, solaceManager, bundleMessageSource); server.addListenerOnSchedule(messageLisener); // register shutdownhook Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { // close resource if (context != null) { context.close(); } } catch (Exception e) { LOG.error("shutdown error", e); } } }); // hold server try { LOG.info("ecif-index server start ok!"); server.start(); } catch (Exception e) { try { // close resource server.shutDown(); if (context != null) { context.close(); } } catch (Exception ex) { LOG.error("shutdown error", ex); } } LOG.info("ecif-index server stop !"); }
From source file:MondrianService.java
public static void main(String[] arg) { System.out.println("Starting Mondrian Connector for Infoveave"); Properties prop = new Properties(); InputStream input = null;//from w w w. ja v a 2 s . c o m int listenPort = 9998; int threads = 100; try { System.out.println("Staring from :" + getSettingsPath()); input = new FileInputStream(getSettingsPath() + File.separator + "MondrianService.properties"); prop.load(input); listenPort = Integer.parseInt(prop.getProperty("port")); threads = Integer.parseInt(prop.getProperty("maxThreads")); if (input != null) { input.close(); } System.out.println("Found MondrianService.Properties"); } catch (FileNotFoundException e) { } catch (IOException e) { } port(listenPort); threadPool(threads); enableCORS("*", "*", "*"); ObjectMapper mapper = new ObjectMapper(); MondrianConnector connector = new MondrianConnector(); get("/ping", (request, response) -> { response.type("application/json"); return "\"Here\""; }); post("/cubes", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetCubes(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/measures", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetMeasures(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/dimensions", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.GetDimensions(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/cleanCache", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); return mapper.writeValueAsString(connector.CleanCubeCache(queryObject)); } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); post("/executeQuery", (request, response) -> { response.type("application/json"); try { Query queryObject = mapper.readValue(request.body(), Query.class); response.status(200); String content = mapper.writeValueAsString(connector.ExecuteQuery2(queryObject)); return content; } catch (JsonParseException ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } catch (Exception ex) { response.status(400); return mapper.writeValueAsString(new Error(ex.getMessage())); } }); }