List of usage examples for org.apache.commons.configuration HierarchicalConfiguration getBoolean
public boolean getBoolean(String key)
From source file:Cresendo.java
public static void main(String[] args) { String cfgFileReceiver = null; // Path to config file for eif receiver agent String cfgFileEngine = null; // Path to config file for xml event engine Options opts = null; // Command line options HelpFormatter hf = null; // Command line help formatter // Setup the message record which will contain text written to the log file ///*from w ww. java2 s . c o m*/ // The message logger object is created when the "-l" is processed // as this object need to be associated with a log file // LogRecord msg = new LogRecord(LogRecord.TYPE_INFO, "Cresendo", "main", "", "", "", "", ""); // Get the directory separator (defaults to "/") // dirSep = System.getProperty("file.separator", "/"); // Initialise the structure containing the event handler objects // Vector<IEventHandler> eventHandler = new Vector<IEventHandler>(10, 10); // Process the command line arguments // try { opts = new Options(); hf = new HelpFormatter(); opts.addOption("h", "help", false, "Command line arguments help"); opts.addOption("i", "instance name", true, "Name of cresendo instance"); opts.addOption("l", "log dir", true, "Path to log file directory"); opts.addOption("c", "config dir", true, "Path to configuarion file directory"); opts.getOption("l").setRequired(true); opts.getOption("c").setRequired(true); BasicParser parser = new BasicParser(); CommandLine cl = parser.parse(opts, args); // Print out some help and exit // if (cl.hasOption('h')) { hf.printHelp("Options", opts); System.exit(0); } // Set the instance name // if (cl.hasOption('i')) { instanceName = cl.getOptionValue('i'); // Set to something other than "default" } // Setup the message and trace logging objects for the EventEngine // if (cl.hasOption('l')) { // Setup the the paths to the message, trace and status log files // logDir = cl.getOptionValue("l"); logPath = logDir + dirSep + instanceName + "-engine.log"; tracePath = logDir + dirSep + instanceName + "-engine.trace"; statusPath = logDir + dirSep + instanceName + "-engine.status"; } else { // NOTE: This should be picked up by the MissingOptionException catch below // but I couldn't get this to work so I added the following code: // hf.printHelp("Option 'l' is a required option", opts); System.exit(1); } // Read the receiver and engine config files in the config directory // if (cl.hasOption('c')) { // Setup and check path to eif config file for TECAgent receiver object // configDir = cl.getOptionValue("c"); cfgFileReceiver = configDir + dirSep + instanceName + ".conf"; checkConfigFile(cfgFileReceiver); // Setup and check path to xml config file for the EventEngine // cfgFileEngine = cl.getOptionValue("c") + dirSep + instanceName + ".xml"; checkConfigFile(cfgFileEngine); } else { // NOTE: This should be picked up by the MissingOptionException catch below // but I couldn't get this to work so I added the following code: // hf.printHelp("Option 'c' is a required option", opts); System.exit(1); } } catch (UnrecognizedOptionException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (MissingOptionException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (MissingArgumentException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (ParseException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Main program // try { // ===================================================================== // Setup the message, trace and status logger objects // try { msgHandler = new FileHandler("cresendo", "message handler", logPath); msgHandler.openDevice(); msgLogger = new MessageLogger("cresendo", "message log"); msgLogger.addHandler(msgHandler); trcHandler = new FileHandler("cresendo", "trace handler", tracePath); trcHandler.openDevice(); trcLogger = new TraceLogger("cresendo", "trace log"); trcLogger.addHandler(trcHandler); statLogger = new StatusLogger(statusPath); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Add the shutdown hook // Runtime.getRuntime().addShutdownHook(new ShutdownThread(msgLogger, instanceName)); // --------------------------------------------------------------------- // ===================================================================== // Load and parse the xml event engine configuration file // // msg.setText("Loading xml engine from: '" + cfgFileEngine + "'"); try { XMLConfiguration xmlProcessor = new XMLConfiguration(); xmlProcessor.setFileName(cfgFileEngine); // Validate the xml against a document type declaration // xmlProcessor.setValidating(true); // Don't interpolate the tag contents by splitting them on a delimiter // (ie by default a comma) // xmlProcessor.setDelimiterParsingDisabled(true); // This will throw a ConfigurationException if the xml document does not // conform to its dtd. By doing this we hopefully catch any errors left // behind after the xml configuration file has been edited. // xmlProcessor.load(); // Setup the trace flag // ConfigurationNode engine = xmlProcessor.getRootNode(); List rootAttribute = engine.getAttributes(); for (Iterator it = rootAttribute.iterator(); it.hasNext();) { ConfigurationNode attr = (ConfigurationNode) it.next(); String attrName = attr.getName(); String attrValue = (String) attr.getValue(); if (attrValue == null || attrValue == "") { System.err.println("\n Error: The value of the attribute '" + attrName + "'" + "\n in the xml file '" + cfgFileEngine + "'" + "\n is not set"); System.exit(1); } if (attrName.matches("trace")) { if (attrValue.matches("true") || attrValue.matches("on")) { trcLogger.setLogging(true); } } if (attrName.matches("status")) { if (attrValue.matches("true") || attrValue.matches("on")) { statLogger.setLogging(true); } else { statLogger.setLogging(false); } } if (attrName.matches("interval")) { if (!attrValue.matches("[0-9]+")) { System.err.println("\n Error: The value of the interval attribute in: '" + cfgFileEngine + "'" + "\n should only contain digits from 0 to 9." + "\n It currently contains: '" + attrValue + "'"); System.exit(1); } statLogger.setInterval(Integer.parseInt(attrValue)); } } // Now build and instantiate the list of classes that will process events // received by the TECAgent receiver in a chain like manner. // List classes = xmlProcessor.configurationsAt("class"); for (Iterator it = classes.iterator(); it.hasNext();) { HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next(); // sub contains now all data contained in a single <class></class> tag set // String className = sub.getString("name"); // Log message // msg.setText(msg.getText() + "\n Instantiated event handler class: '" + className + "'"); // The angle brackets describing the class of object held by the // Vector are implemented by Java 1.5 and have 2 effects. // // 1. The list accepts only elements of that class and nothing else // (Of course thanks to Auto-Wrap you can also add double-values) // // 2. the get(), firstElement() ... Methods don't return a Object, but // they deliver an element of the class. // Vector<Class> optTypes = new Vector<Class>(10, 10); Vector<Object> optValues = new Vector<Object>(10, 10); for (int i = 0; i <= sub.getMaxIndex("option"); i++) { Object optValue = null; String optVarName = sub.getString("option(" + i + ")[@varname]"); String optJavaType = sub.getString("option(" + i + ")[@javatype]"); // Use the specified java type in order to make the method call // to the heirarchical sub object [painful :-((] // if (optJavaType.matches("byte")) { optTypes.addElement(byte.class); optValue = sub.getByte("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("short")) { optTypes.addElement(byte.class); optValue = sub.getShort("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("int")) { optTypes.addElement(int.class); optValue = sub.getInt("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("long")) { optTypes.addElement(long.class); optValue = sub.getLong("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("float")) { optTypes.addElement(float.class); optValue = sub.getFloat("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0.0; // Set to something nullish } } else if (optJavaType.matches("double")) { optTypes.addElement(double.class); optValue = sub.getDouble("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0.0; // Set to something nullish } } else if (optJavaType.matches("boolean")) { optTypes.addElement(boolean.class); optValue = sub.getBoolean("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = false; // Set to something nullish } } else if (optJavaType.matches("String")) { optTypes.addElement(String.class); optValue = sub.getString("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = ""; // Set it to something nullish } } else { System.err.println( "Error: Unsupported java type found in xml config: '" + optJavaType + "'"); System.exit(1); } // Add option value element // // System.out.println("Option value is: '" + optValue.toString() + "'\n"); // optValues.addElement(optValue); // Append to message text // String msgTemp = msg.getText(); msgTemp += "\n option name: '" + optVarName + "'"; msgTemp += "\n option type: '" + optJavaType + "'"; msgTemp += "\n option value: '" + optValues.lastElement().toString() + "'"; msg.setText(msgTemp); } try { // Instantiate the class with the java reflection api // Class klass = Class.forName(className); // Setup an array of paramater types in order to retrieve the matching constructor // Class[] types = optTypes.toArray(new Class[optTypes.size()]); // Get the constructor for the class which matches the parameter types // Constructor konstruct = klass.getConstructor(types); // Create an instance of the event handler // IEventHandler eventProcessor = (IEventHandler) konstruct.newInstance(optValues.toArray()); // Add the instance to the list of event handlers // eventHandler.addElement(eventProcessor); } catch (InvocationTargetException e) { System.err.println("Error: " + e.toString()); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: class name not found: '" + className + "' \n" + e.toString()); System.exit(1); } catch (Exception e) { System.err.println( "Error: failed to instantiate class: '" + className + "' \n" + e.toString()); System.exit(1); } } } catch (ConfigurationException cex) // Something went wrong loading the xml file { System.err.println("\n" + "Error loading XML file: " + cfgFileEngine + "\n" + cex.toString()); System.exit(1); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // --------------------------------------------------------------------- // ===================================================================== // Setup the TECAgent receiver // Reader cfgIn = null; try { cfgIn = new FileReader(cfgFileReceiver); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Start the TECAgent receiver and register the event engine handler // TECAgent receiver = new TECAgent(cfgIn, TECAgent.RECEIVER_MODE, false); EventEngine ee = new EventEngine(eventHandler, msgLogger, trcLogger); receiver.registerListener(ee); // Construct message and send it to the message log // String text = "\n Cresendo instance '" + instanceName + "' listening for events on port '" + receiver.getConfigVal("ServerPort") + "'"; msg.setText(msg.getText() + text); msgLogger.log(msg); // Send message to log // --------------------------------------------------------------------- // ===================================================================== // Initiate status logging // if (statLogger.isLogging()) { int seconds = statLogger.getInterval(); while (true) { try { statLogger.log(); } catch (Exception ex) { System.err.println("\n An error occurred while writing to '" + statusPath + "'" + "\n '" + ex.toString() + "'"); } Thread.sleep(seconds * 1000); // Convert sleep time to milliseconds } } // --------------------------------------------------------------------- } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } }
From source file:com.moviejukebox.reader.MovieJukeboxLibraryReader.java
public static Collection<MediaLibraryPath> parse(File libraryFile) { Collection<MediaLibraryPath> mlp = new ArrayList<>(); if (!libraryFile.exists() || libraryFile.isDirectory()) { LOG.error("The moviejukebox library input file you specified is invalid: {}", libraryFile.getName()); return mlp; }//from w ww . j a v a 2 s . com try { XMLConfiguration c = new XMLConfiguration(libraryFile); List<HierarchicalConfiguration> fields = c.configurationsAt("library"); for (HierarchicalConfiguration sub : fields) { // sub contains now all data about a single medialibrary node String path = sub.getString("path"); String nmtpath = sub.getString("nmtpath"); // This should be depreciated String playerpath = sub.getString("playerpath"); String description = sub.getString("description"); boolean scrapeLibrary = true; String scrapeLibraryString = sub.getString("scrapeLibrary"); if (StringTools.isValidString(scrapeLibraryString)) { try { scrapeLibrary = sub.getBoolean("scrapeLibrary"); } catch (Exception ignore) { /* ignore */ } } long prebuf = -1; String prebufString = sub.getString("prebuf"); if (prebufString != null && !prebufString.isEmpty()) { try { prebuf = Long.parseLong(prebufString); } catch (NumberFormatException ignore) { /* ignore */ } } // Note that the nmtpath should no longer be used in the library file and instead "playerpath" should be used. // Check that the nmtpath terminates with a "/" or "\" if (nmtpath != null) { if (!(nmtpath.endsWith("/") || nmtpath.endsWith("\\"))) { // This is the NMTPATH so add the unix path separator rather than File.separator nmtpath = nmtpath + "/"; } } // Check that the playerpath terminates with a "/" or "\" if (playerpath != null) { if (!(playerpath.endsWith("/") || playerpath.endsWith("\\"))) { // This is the PlayerPath so add the Unix path separator rather than File.separator playerpath = playerpath + "/"; } } List<Object> excludes = sub.getList("exclude[@name]"); File medialibfile = new File(path); if (medialibfile.exists()) { MediaLibraryPath medlib = new MediaLibraryPath(); medlib.setPath(medialibfile.getCanonicalPath()); if (playerpath == null || StringUtils.isBlank(playerpath)) { medlib.setPlayerRootPath(nmtpath); } else { medlib.setPlayerRootPath(playerpath); } medlib.setExcludes(excludes); medlib.setDescription(description); medlib.setScrapeLibrary(scrapeLibrary); medlib.setPrebuf(prebuf); mlp.add(medlib); if (description != null && !description.isEmpty()) { LOG.info("Found media library: {}", description); } else { LOG.info("Found media library: {}", path); } // Save the media library to the log file for reference. LOG.debug("Media library: {}", medlib); } else { LOG.info("Skipped invalid media library: {}", path); } } } catch (ConfigurationException | IOException ex) { LOG.error("Failed parsing moviejukebox library input file: {}", libraryFile.getName()); LOG.error(SystemTools.getStackTrace(ex)); } return mlp; }
From source file:edu.uw.sig.frames2owl.util.ConfigReader.java
private void init() { /*//from w w w . j a v a 2 s . c om <iri project='cho'> <value_source>FMAID</value_source> <value_comp>{value}</value_comp> <fragment_separator>#</fragment_separator> </iri> */ // read iri config info List<HierarchicalConfiguration> iriConfs = config.configurationsAt("iri"); for (HierarchicalConfiguration iriConf : iriConfs) { // get the project name String projectName = iriConf.getString("[@project]"); String iriDomain = iriConf.getString("iri_domain"); String valSource = iriConf.getString("value_source"); String valComp = iriConf.getString("value_comp"); String fragSep = iriConf.getString("fragment_separator"); IRIConf currIriConf = new IRIConf(valSource, iriDomain, valComp, fragSep); proj2IriConfMap.put(projectName, currIriConf); } // read config flags and add to map HierarchicalConfiguration flags = config.configurationAt("conf-flags"); if (flags != null) { Iterator<String> flagsIt = flags.getKeys(); while (flagsIt.hasNext()) { // get the name of the flag String flagName = flagsIt.next(); // get flag value as string boolean flagVal = flags.getBoolean(flagName); // put in flag map configFlags.put(flagName, flagVal); } } //System.err.println(configFlags); // read general configuration parameters List<HierarchicalConfiguration> reifExcl = config.configurationsAt("general_conv_args.reif_exclusion"); for (HierarchicalConfiguration exclusion : reifExcl) { // get slot name and conversion class name String excludedSlots = exclusion.getString("[@excluded_slots]"); for (String excl : excludedSlots.split(",")) reifExclusions.add(excl); } List<HierarchicalConfiguration> slotAnnotExcl = config .configurationsAt("general_conv_args.slot_annot_exclusion"); for (HierarchicalConfiguration exclusion : slotAnnotExcl) { // get slot name and conversion class name String excludedSlots = exclusion.getString("[@excluded_slots]"); for (String excl : excludedSlots.split(",")) slotAnnotExclusions.add(excl); } // name and location of class that will be used to contruct named domain classes for annotation props List<HierarchicalConfiguration> domainConfs = config.configurationsAt("general_conv_args.domain"); for (HierarchicalConfiguration domainConf : domainConfs) { // get slot name and conversion class name domainClsName = domainConf.getString("[@cls-name]"); domainSuperClsName = domainConf.getString("[@super-cls-name]"); } // name and location of class that will be used to contruct named range classes for annotation props List<HierarchicalConfiguration> rangeConfs = config.configurationsAt("general_conv_args.range"); for (HierarchicalConfiguration rangeConf : rangeConfs) { // get slot name and conversion class name rangeClsName = rangeConf.getString("[@cls-name]"); rangeSuperClsName = rangeConf.getString("[@super-cls-name]"); } // read config file to determine which Java classes to use for which slot conversion List<HierarchicalConfiguration> slotConverters = config .configurationsAt("slot_conv_classes.slot_conv_class"); for (HierarchicalConfiguration slotConverter : slotConverters) { // get slot name and conversion class name String slotName = slotConverter.getString("[@slot_name]"); String convClsName = slotConverter.getString("[@conv_cls_name]"); try { Class convClass = Class.forName(convClsName); slotConvMap.put(slotName, convClass); } catch (ClassNotFoundException e) { e.printStackTrace(); continue; } // gather additional arguments if there are any Iterator<String> iter = slotConverter.getKeys(); Map<String, String> attrMap = new HashMap<String, String>(); while (iter.hasNext()) { String key = iter.next(); if (!key.equals("[@slot_name]") && !key.equals("[@conv_cls_name]")) { //System.err.println("found key for init args = "+key+" for slot "+slotName); String attrVal = slotConverter.getString(key); key = key.replaceAll("^\\[@", ""); key = key.replaceAll("\\]$", ""); attrMap.put(key, attrVal); } } convInitArgsMap.put(slotName, attrMap); } /* <inst_conv_classes> <inst_conv_class type="Mapping" conv_cls_name="edu.uw.sig.frames2owl.instconv.impl.MappingConverter" source_slot="source" target_slot="target" direct_property_name="mapsTo" excluded_slots=""/> </inst_conv_classes> */ // read config file to determine which Java classes to use for which slot conversion List<HierarchicalConfiguration> instConverters = config .configurationsAt("inst_conv_classes.inst_conv_class"); for (HierarchicalConfiguration instConverter : instConverters) { String typeName = instConverter.getString("[@type_name]"); String convClsName = instConverter.getString("[@conv_cls_name]"); try { Class convClass = Class.forName(convClsName); instConvMap.put(typeName, convClass); } catch (ClassNotFoundException e) { e.printStackTrace(); continue; } // gather additional arguments if there are any Iterator<String> iter = instConverter.getKeys(); Map<String, String> attrMap = new HashMap<String, String>(); while (iter.hasNext()) { String key = iter.next(); if (!key.equals("[@type]") && !key.equals("[@conv_cls_name]")) { //System.err.println("found key for init args = "+key+" for slot "+slotName); String attrVal = instConverter.getString(key); key = key.replaceAll("^\\[@", ""); key = key.replaceAll("\\]$", ""); attrMap.put(key, attrVal); } } instConvInitArgsMap.put(typeName, attrMap); } }
From source file:edu.psu.citeseerx.messaging.MsgService.java
/** * Configures an individual channel to be handled by a specified provider. * Channels are created for consumption or production based on their * descriptions, and execution is passed to other handlers to build * specific channel implementations./*from ww w . j a va 2s . com*/ * @param provider * @param config * @param type * @throws Exception */ protected void processChannel(JMSProvider provider, HierarchicalConfiguration config, int type) throws Exception { String name = config.getString("name"); String role = config.getString("role"); String modeStr = config.getString("acknowledgeMode"); int mode = getAckMode(modeStr); if (role.equalsIgnoreCase("consumer")) { boolean durable = false; if (type == TOPIC) { try { durable = config.getBoolean("durable"); } catch (Exception e) { /* ignore */ } } if (durable) { String durableID = config.getString("durableID"); createDurableSubscriber(provider, name, mode, durableID); } else { createConsumer(provider, name, type, mode); } } else if (role.equalsIgnoreCase("producer")) { createProducer(provider, name, type, mode); } }
From source file:ching.icecreaming.action.ViewAction.java
@Action(value = "view", results = { @Result(name = "login", location = "edit.jsp"), @Result(name = "input", location = "view.jsp"), @Result(name = "success", location = "view.jsp"), @Result(name = "error", location = "error.jsp") }) public String execute() throws Exception { Enumeration enumerator = null; String[] array1 = null, array2 = null; int int1 = -1, int2 = -1, int3 = -1; InputStream inputStream1 = null; OutputStream outputStream1 = null; java.io.File file1 = null, file2 = null, dir1 = null; List<File> files = null; HttpHost httpHost1 = null;//from w w w. jav a 2 s .c om HttpGet httpGet1 = null, httpGet2 = null; HttpPut httpPut1 = null; URI uri1 = null; URL url1 = null; DefaultHttpClient httpClient1 = null; URIBuilder uriBuilder1 = null, uriBuilder2 = null; HttpResponse httpResponse1 = null, httpResponse2 = null; HttpEntity httpEntity1 = null, httpEntity2 = null; List<NameValuePair> nameValuePair1 = null; String string1 = null, string2 = null, string3 = null, string4 = null, return1 = LOGIN; XMLConfiguration xmlConfiguration = null; List<HierarchicalConfiguration> list1 = null, list2 = null; HierarchicalConfiguration hierarchicalConfiguration2 = null; DataModel1 dataModel1 = null; DataModel2 dataModel2 = null; List<DataModel1> listObject1 = null, listObject3 = null; org.joda.time.DateTime dateTime1 = null, dateTime2 = null; org.joda.time.Period period1 = null; PeriodFormatter periodFormatter1 = new PeriodFormatterBuilder().appendYears() .appendSuffix(String.format(" %s", getText("year")), String.format(" %s", getText("years"))) .appendSeparator(" ").appendMonths() .appendSuffix(String.format(" %s", getText("month")), String.format(" %s", getText("months"))) .appendSeparator(" ").appendWeeks() .appendSuffix(String.format(" %s", getText("week")), String.format(" %s", getText("weeks"))) .appendSeparator(" ").appendDays() .appendSuffix(String.format(" %s", getText("day")), String.format(" %s", getText("days"))) .appendSeparator(" ").appendHours() .appendSuffix(String.format(" %s", getText("hour")), String.format(" %s", getText("hours"))) .appendSeparator(" ").appendMinutes() .appendSuffix(String.format(" %s", getText("minute")), String.format(" %s", getText("minutes"))) .appendSeparator(" ").appendSeconds().minimumPrintedDigits(2) .appendSuffix(String.format(" %s", getText("second")), String.format(" %s", getText("seconds"))) .printZeroNever().toFormatter(); if (StringUtils.isBlank(urlString) || StringUtils.isBlank(wsType)) { urlString = portletPreferences.getValue("urlString", "/"); wsType = portletPreferences.getValue("wsType", "folder"); } Configuration propertiesConfiguration1 = new PropertiesConfiguration("system.properties"); timeZone1 = portletPreferences.getValue("timeZone", TimeZone.getDefault().getID()); enumerator = portletPreferences.getNames(); if (enumerator.hasMoreElements()) { array1 = portletPreferences.getValues("server", null); if (array1 != null) { if (ArrayUtils.isNotEmpty(array1)) { for (int1 = 0; int1 < array1.length; int1++) { switch (int1) { case 0: sid = array1[int1]; break; case 1: uid = array1[int1]; break; case 2: pid = array1[int1]; break; case 3: alias1 = array1[int1]; break; default: break; } } sid = new String(Base64.decodeBase64(sid.getBytes())); uid = new String(Base64.decodeBase64(uid.getBytes())); pid = new String(Base64.decodeBase64(pid.getBytes())); } return1 = INPUT; } else { return1 = LOGIN; } } else { return1 = LOGIN; } if (StringUtils.equals(urlString, "/")) { if (listObject1 != null) { listObject1.clear(); } if (session.containsKey("breadcrumbs")) { session.remove("breadcrumbs"); } } else { array2 = StringUtils.split(urlString, "/"); listObject1 = (session.containsKey("breadcrumbs")) ? (List<DataModel1>) session.get("breadcrumbs") : new ArrayList<DataModel1>(); int2 = array2.length - listObject1.size(); if (int2 > 0) { listObject1.add(new DataModel1(urlString, label1)); } else { int2 += listObject1.size(); for (int1 = listObject1.size() - 1; int1 >= int2; int1--) { listObject1.remove(int1); } } session.put("breadcrumbs", listObject1); } switch (wsType) { case "folder": break; case "reportUnit": try { dateTime1 = new org.joda.time.DateTime(); return1 = INPUT; httpClient1 = new DefaultHttpClient(); if (StringUtils.equals(button1, getText("Print"))) { nameValuePair1 = new ArrayList<NameValuePair>(); if (listObject2 != null) { if (listObject2.size() > 0) { for (DataModel2 dataObject2 : listObject2) { listObject3 = dataObject2.getOptions(); if (listObject3 == null) { string2 = dataObject2.getValue1(); if (StringUtils.isNotBlank(string2)) nameValuePair1.add(new BasicNameValuePair(dataObject2.getId(), string2)); } else { for (int1 = listObject3.size() - 1; int1 >= 0; int1--) { dataModel1 = (DataModel1) listObject3.get(int1); string2 = dataModel1.getString2(); if (StringUtils.isNotBlank(string2)) nameValuePair1 .add(new BasicNameValuePair(dataObject2.getId(), string2)); } } } } } url1 = new URL(sid); uriBuilder1 = new URIBuilder(sid); uriBuilder1.setUserInfo(uid, pid); if (StringUtils.isBlank(format1)) format1 = "pdf"; uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "." + format1); if (StringUtils.isNotBlank(locale2)) { nameValuePair1.add(new BasicNameValuePair("userLocale", locale2)); } if (StringUtils.isNotBlank(page1)) { if (NumberUtils.isNumber(page1)) { nameValuePair1.add(new BasicNameValuePair("page", page1)); } } if (nameValuePair1.size() > 0) { uriBuilder1.setQuery(URLEncodedUtils.format(nameValuePair1, "UTF-8")); } uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); if (int1 == HttpStatus.SC_OK) { string3 = System.getProperty("java.io.tmpdir") + File.separator + httpServletRequest.getSession().getId(); dir1 = new File(string3); if (!dir1.exists()) { dir1.mkdir(); } httpEntity1 = httpResponse1.getEntity(); file1 = new File(string3, StringUtils.substringAfterLast(urlString, "/") + "." + format1); if (StringUtils.equalsIgnoreCase(format1, "html")) { result1 = EntityUtils.toString(httpEntity1); FileUtils.writeStringToFile(file1, result1); array1 = StringUtils.substringsBetween(result1, "<img src=\"", "\""); if (ArrayUtils.isNotEmpty(array1)) { dir1 = new File( string3 + File.separator + FilenameUtils.getBaseName(file1.getName())); if (dir1.exists()) { FileUtils.deleteDirectory(dir1); } file2 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName()) + ".zip"); if (file2.exists()) { if (FileUtils.deleteQuietly(file2)) { } } for (int2 = 0; int2 < array1.length; int2++) { try { string2 = url1.getPath() + "/rest_v2/reports" + urlString + "/" + StringUtils.substringAfter(array1[int2], "/"); uriBuilder1.setPath(string2); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); } finally { if (int1 == HttpStatus.SC_OK) { try { string2 = StringUtils.substringBeforeLast(array1[int2], "/"); dir1 = new File(string3 + File.separator + string2); if (!dir1.exists()) { dir1.mkdirs(); } httpEntity1 = httpResponse1.getEntity(); inputStream1 = httpEntity1.getContent(); } finally { string1 = StringUtils.substringAfterLast(array1[int2], "/"); file2 = new File(string3 + File.separator + string2, string1); outputStream1 = new FileOutputStream(file2); IOUtils.copy(inputStream1, outputStream1); } } } } outputStream1 = new FileOutputStream( FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName()) + ".zip"); ArchiveOutputStream archiveOutputStream1 = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream1); archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file1, file1.getName())); IOUtils.copy(new FileInputStream(file1), archiveOutputStream1); archiveOutputStream1.closeArchiveEntry(); dir1 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName())); files = (List<File>) FileUtils.listFiles(dir1, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); for (File file3 : files) { archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file3, StringUtils .substringAfter(file3.getCanonicalPath(), string3 + File.separator))); IOUtils.copy(new FileInputStream(file3), archiveOutputStream1); archiveOutputStream1.closeArchiveEntry(); } archiveOutputStream1.close(); } bugfixGateIn = propertiesConfiguration1.getBoolean("bugfixGateIn", false); string4 = bugfixGateIn ? String.format("<img src=\"%s/namespace1/file-link?sessionId=%s&fileName=", portletRequest.getContextPath(), httpServletRequest.getSession().getId()) : String.format("<img src=\"%s/namespace1/file-link?fileName=", portletRequest.getContextPath()); result1 = StringUtils.replace(result1, "<img src=\"", string4); } else { inputStream1 = httpEntity1.getContent(); outputStream1 = new FileOutputStream(file1); IOUtils.copy(inputStream1, outputStream1); result1 = file1.getAbsolutePath(); } return1 = SUCCESS; } else { addActionError(String.format("%s %d: %s", getText("Error"), int1, getText(Integer.toString(int1)))); } dateTime2 = new org.joda.time.DateTime(); period1 = new Period(dateTime1, dateTime2.plusSeconds(1)); message1 = getText("Execution.time") + ": " + periodFormatter1.print(period1); } else { url1 = new URL(sid); uriBuilder1 = new URIBuilder(sid); uriBuilder1.setUserInfo(uid, pid); uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "/inputControls"); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); switch (int1) { case HttpStatus.SC_NO_CONTENT: break; case HttpStatus.SC_OK: httpEntity1 = httpResponse1.getEntity(); if (httpEntity1 != null) { inputStream1 = httpEntity1.getContent(); if (inputStream1 != null) { xmlConfiguration = new XMLConfiguration(); xmlConfiguration.load(inputStream1); list1 = xmlConfiguration.configurationsAt("inputControl"); if (list1.size() > 0) { listObject2 = new ArrayList<DataModel2>(); for (HierarchicalConfiguration hierarchicalConfiguration1 : list1) { string2 = hierarchicalConfiguration1.getString("type"); dataModel2 = new DataModel2(); dataModel2.setId(hierarchicalConfiguration1.getString("id")); dataModel2.setLabel1(hierarchicalConfiguration1.getString("label")); dataModel2.setType1(string2); dataModel2.setMandatory(hierarchicalConfiguration1.getBoolean("mandatory")); dataModel2.setReadOnly(hierarchicalConfiguration1.getBoolean("readOnly")); dataModel2.setVisible(hierarchicalConfiguration1.getBoolean("visible")); switch (string2) { case "bool": case "singleValueText": case "singleValueNumber": case "singleValueDate": case "singleValueDatetime": hierarchicalConfiguration2 = hierarchicalConfiguration1 .configurationAt("state"); dataModel2.setValue1(hierarchicalConfiguration2.getString("value")); break; case "singleSelect": case "singleSelectRadio": case "multiSelect": case "multiSelectCheckbox": hierarchicalConfiguration2 = hierarchicalConfiguration1 .configurationAt("state"); list2 = hierarchicalConfiguration2.configurationsAt("options.option"); if (list2.size() > 0) { listObject3 = new ArrayList<DataModel1>(); for (HierarchicalConfiguration hierarchicalConfiguration3 : list2) { dataModel1 = new DataModel1( hierarchicalConfiguration3.getString("label"), hierarchicalConfiguration3.getString("value")); if (hierarchicalConfiguration3.getBoolean("selected")) { dataModel2.setValue1( hierarchicalConfiguration3.getString("value")); } listObject3.add(dataModel1); } dataModel2.setOptions(listObject3); } break; default: break; } listObject2.add(dataModel2); } } } } break; default: addActionError(String.format("%s %d: %s", getText("Error"), int1, getText(Integer.toString(int1)))); break; } if (httpEntity1 != null) { EntityUtils.consume(httpEntity1); } uriBuilder1.setPath(url1.getPath() + "/rest/resource" + urlString); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int2 = httpResponse1.getStatusLine().getStatusCode(); if (int2 == HttpStatus.SC_OK) { httpEntity1 = httpResponse1.getEntity(); inputStream1 = httpEntity1.getContent(); xmlConfiguration = new XMLConfiguration(); xmlConfiguration.load(inputStream1); list1 = xmlConfiguration.configurationsAt("resourceDescriptor"); for (HierarchicalConfiguration hierarchicalConfiguration4 : list1) { if (StringUtils.equalsIgnoreCase( StringUtils.trim(hierarchicalConfiguration4.getString("[@wsType]")), "prop")) { if (map1 == null) map1 = new HashMap<String, String>(); string2 = StringUtils.substringBetween( StringUtils.substringAfter( hierarchicalConfiguration4.getString("[@uriString]"), "_files/"), "_", ".properties"); map1.put(string2, StringUtils.isBlank(string2) ? getText("Default") : getText(string2)); } } } if (httpEntity1 != null) { EntityUtils.consume(httpEntity1); } } } catch (IOException | ConfigurationException | URISyntaxException exception1) { exception1.printStackTrace(); addActionError(exception1.getLocalizedMessage()); httpGet1.abort(); return ERROR; } finally { httpClient1.getConnectionManager().shutdown(); IOUtils.closeQuietly(inputStream1); } break; default: addActionError(getText("This.file.type.is.not.supported")); break; } if (return1 != LOGIN) { sid = new String(Base64.encodeBase64(sid.getBytes())); uid = new String(Base64.encodeBase64(uid.getBytes())); pid = new String(Base64.encodeBase64(pid.getBytes())); } return return1; }
From source file:com.bytelightning.opensource.pokerface.PokerFace.java
/** * Configures all the needed components, but does not actually start the server. * @param config Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy. * @throws Exception Yeah, a lot can go wrong here, but at least it will be caught immediately :-) *///from w w w. j a va2s .c o m public void config(HierarchicalConfiguration config) throws Exception { List<HierarchicalConfiguration> lconf; HttpAsyncRequester executor = null; BasicNIOConnPool connPool = null; ObjectPool<ByteBuffer> byteBufferPool = null; LinkedHashMap<String, TargetDescriptor> mappings = null; ConcurrentMap<String, HttpHost> hosts = null; handlerRegistry = new UriHttpAsyncRequestHandlerMapper(); // Initialize the keystore (if one was specified) KeyStore keystore = null; char[] keypass = null; String keystoreUri = config.getString("keystore"); if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) { Path keystorePath = Utils.MakePath(keystoreUri); if (!Files.exists(keystorePath)) throw new ConfigurationException("Keystore does not exist."); if (Files.isDirectory(keystorePath)) throw new ConfigurationException("Keystore is not a file"); String storepass = config.getString("storepass"); if ((storepass != null) && "null".equals(storepass)) storepass = null; keystore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) { keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray()); } catch (IOException ex) { Logger.error("Unable to load https server keystore from " + keystoreUri); return; } keypass = config.getString("keypass").trim().toCharArray(); } // Wire up the listening reactor lconf = config.configurationsAt("server"); if ((lconf == null) || (lconf.size() != 1)) throw new ConfigurationException("One (and only one) server configuration element is allowed."); else { Builder builder = IOReactorConfig.custom(); builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667))); builder.setSoTimeout(config.getInt("server[@soTimeout]", 0)); builder.setSoLinger(config.getInt("server[@soLinger]", -1)); builder.setSoReuseAddress(true); builder.setTcpNoDelay(false); builder.setSelectInterval(100); IOReactorConfig rconfig = builder.build(); Logger.info("Configuring server with options: " + rconfig.toString()); listeningReactor = new DefaultListeningIOReactor(rconfig); lconf = config.configurationsAt("server.listen"); InetSocketAddress addr; boolean hasNonWildcardSecure = false; LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>(); if ((lconf == null) || (lconf.size() == 0)) { addr = new InetSocketAddress("127.0.0.1", 8080); ListenerEndpoint ep = listeningReactor.listen(addr); Logger.warn("Configured " + ep.getAddress()); } else { TrustManager[] trustManagers = null; KeyManagerFactory kmf = null; // Create all the specified listeners. for (HierarchicalConfiguration hc : lconf) { String addrStr = hc.getString("[@address]"); if ((addrStr == null) || (addrStr.length() == 0)) addrStr = "0.0.0.0"; String alias = hc.getString("[@alias]"); int port = hc.getInt("[@port]", alias != null ? 443 : 80); addr = new InetSocketAddress(addrStr, port); ListenerEndpoint ep = listeningReactor.listen(addr); String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null; Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null; if ((alias != null) && (secure == null)) secure = true; if ((protocol != null) && (secure == null)) secure = true; if ((secure != null) && secure) { if (protocol == null) protocol = "TLS"; if (keystore == null) throw new ConfigurationException( "An https listening socket was requested, but no keystore was specified."); if (kmf == null) { kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, keypass); } // Are we going to trust all clients or just specific ones? if (hc.getBoolean("[@trustAny]", true)) trustManagers = new TrustManager[] { new X509TrustAllManager() }; else { TrustManagerFactory instance = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); instance.init(keystore); trustManagers = instance.getTrustManagers(); } KeyManager[] keyManagers = kmf.getKeyManagers(); if (alias != null) for (int i = 0; i < keyManagers.length; i++) { if (keyManagers[i] instanceof X509ExtendedKeyManager) keyManagers[i] = new PokerFaceKeyManager(alias, (X509ExtendedKeyManager) keyManagers[i]); } SSLContext sslCtx = SSLContext.getInstance(protocol); sslCtx.init(keyManagers, trustManagers, new SecureRandom()); if (addr.getAddress().isAnyLocalAddress()) { // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card. for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { addr = new InetSocketAddress(enumIpAddr.nextElement(), port); addrSSLContext.put(addr, sslCtx); } } } else { addrSSLContext.put(addr, sslCtx); hasNonWildcardSecure = true; } } Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress()); } } // We will need an HTTP protocol processor for the incoming connections String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version); HttpProcessor inhttpproc = new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent), new ResponseContent(), new ResponseConnControl() }); HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(), null, handlerRegistry, null) { public void exception(final NHttpServerConnection conn, final Exception cause) { Logger.warn(cause.getMessage()); super.exception(conn, cause); } }; if (addrSSLContext.size() > 0) { final SSLContext defaultCtx = addrSSLContext.values().iterator().next(); final Map<SocketAddress, SSLContext> sslMap; if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1)) sslMap = null; else sslMap = addrSSLContext; listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) { protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext, SSLSetupHandler sslHandler) { SSLIOSession retVal; SSLContext sktCtx = sslcontext; if (sslMap != null) { SocketAddress la = iosession.getLocalAddress(); if (la != null) { sktCtx = sslMap.get(la); if (sktCtx == null) sktCtx = sslcontext; } retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler); } else retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler); if (sktCtx != null) retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true); return retVal; } }); } else listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT); } // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets. lconf = config.configurationsAt("targets"); if ((lconf != null) && (lconf.size() > 0)) { HierarchicalConfiguration conf = lconf.get(0); Builder builder = IOReactorConfig.custom(); builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667))); builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0)); builder.setSoLinger(config.getInt("targets[@soLinger]", -1)); builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0)); builder.setSoReuseAddress(true); builder.setTcpNoDelay(false); connectingReactor = new DefaultConnectingIOReactor(builder.build()); final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024; byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() { @Override public ByteBuffer create() throws Exception { return ByteBuffer.allocateDirect(bufferSize); } @Override public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) { return new DefaultPooledObject<ByteBuffer>(buffer); } }); KeyManager[] keyManagers = null; TrustManager[] trustManagers = null; if (keystore != null) { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, keypass); keyManagers = kmf.getKeyManagers(); } // Will the httpclient's trust any remote target, or only specific ones. if (conf.getBoolean("targets[@trustAny]", false)) trustManagers = new TrustManager[] { new X509TrustAllManager() }; else if (keystore != null) { TrustManagerFactory instance = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); instance.init(keystore); trustManagers = instance.getTrustManagers(); } SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS")); clientSSLContext.init(keyManagers, trustManagers, new SecureRandom()); // Setup an SSL capable connection pool for the httpclients. connPool = new BasicNIOConnPool(connectingReactor, new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT), conf.getInt("targets[@connectTimeout]", 0)); connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023)); connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023)); // Set up HTTP protocol processor for outgoing connections String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version); HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(userAgent), new RequestExpectContinue(true) }); executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy()); // Now set up all the configured targets. mappings = new LinkedHashMap<String, TargetDescriptor>(); hosts = new ConcurrentHashMap<String, HttpHost>(); String[] scheme = { null }; String[] host = { null }; int[] port = { 0 }; String[] path = { null }; int[] stripPrefixCount = { 0 }; for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) { String match = targetConfig.getString("[@pattern]"); if ((match == null) || (match.trim().length() < 1)) { Logger.error("Unable to configure target; Invalid url match pattern"); continue; } String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host, port, path, stripPrefixCount); if (key == null) { Logger.error("Unable to configure target"); continue; } HttpHost targetHost = hosts.get(key); if (targetHost == null) { targetHost = new HttpHost(host[0], port[0], scheme[0]); hosts.put(key, targetHost); } TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]); mappings.put(match, desc); } connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(), ConnectionConfig.DEFAULT); } // Allocate the script map which will be populated by it's own executor thread. if (config.containsKey("scripts.rootDirectory")) { Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory")); if (!Files.exists(tmp)) throw new FileNotFoundException("Scripts directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'scripts' path is not a directory."); scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>(); boolean watch = config.getBoolean("scripts.dynamicWatch", false); List<Path> jsLibs; Object prop = config.getProperty("scripts.library"); if (prop != null) { jsLibs = new ArrayList<Path>(); if (prop instanceof Collection<?>) { @SuppressWarnings("unchecked") Collection<Object> oprop = (Collection<Object>) prop; for (Object obj : oprop) jsLibs.add(Utils.MakePath(obj)); } else { jsLibs.add(Utils.MakePath(prop)); } } else jsLibs = null; lconf = config.configurationsAt("scripts.scriptConfig"); if (lconf != null) { if (lconf.size() > 1) throw new ConfigurationException("Only one scriptConfig element is allowed."); if (lconf.size() == 0) lconf = null; } HierarchicalConfiguration scriptConfig; if (lconf == null) scriptConfig = new HierarchicalConfiguration(); else scriptConfig = lconf.get(0); scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString()); configureScripts(jsLibs, scriptConfig, tmp, watch); if (watch) ScriptDirectoryWatcher = new DirectoryWatchService(); } // Configure the static file directory (if any) Path staticFilesPath = null; if (config.containsKey("files.rootDirectory")) { Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory")); if (!Files.exists(tmp)) throw new FileNotFoundException("Files directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'files' path is not a directory."); staticFilesPath = tmp; List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry"); if (mimeEntries != null) { for (HierarchicalConfiguration entry : mimeEntries) { entry.setDelimiterParsingDisabled(true); String type = entry.getString("[@type]", "").trim(); if (type.length() == 0) throw new ConfigurationException("Invalid mime type entry"); String extensions = entry.getString("[@extensions]", "").trim(); if (extensions.length() == 0) throw new ConfigurationException("Invalid mime extensions for: " + type); ScriptHelperImpl.AddMimeEntry(type, extensions); } } } handlerRegistry.register("/*", new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings, scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null, config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null)); }
From source file:com.houghtonassociates.bamboo.plugins.GerritRepositoryAdapter.java
@Override public void populateFromConfig(HierarchicalConfiguration config) { super.populateFromConfig(config); hostname = StringUtils.trimToEmpty(config.getString(REPOSITORY_GERRIT_REPOSITORY_HOSTNAME)); username = config.getString(REPOSITORY_GERRIT_USERNAME); userEmail = config.getString(REPOSITORY_GERRIT_EMAIL); sshKey = config.getString(REPOSITORY_GERRIT_SSH_KEY, ""); sshPassphrase = encryptionService.decrypt(config.getString(REPOSITORY_GERRIT_SSH_PASSPHRASE)); port = config.getInt(REPOSITORY_GERRIT_REPOSITORY_PORT, 29418); project = config.getString(REPOSITORY_GERRIT_PROJECT); String strDefBranch = config.getString(REPOSITORY_GERRIT_DEFAULT_BRANCH, ""); String strCustBranch = config.getString(REPOSITORY_GERRIT_CUSTOM_BRANCH, ""); if (strDefBranch.equals(MASTER_BRANCH.getName()) || strDefBranch.equals(ALL_BRANCH.getName())) { vcsBranch = new VcsBranchImpl(strDefBranch); } else {/*ww w . j a va 2 s . com*/ vcsBranch = new VcsBranchImpl(strCustBranch); } useShallowClones = config.getBoolean(REPOSITORY_GERRIT_USE_SHALLOW_CLONES); useSubmodules = config.getBoolean(REPOSITORY_GERRIT_USE_SUBMODULES); commandTimeout = config.getInt(REPOSITORY_GERRIT_COMMAND_TIMEOUT, DEFAULT_COMMAND_TIMEOUT_IN_MINUTES); verboseLogs = config.getBoolean(REPOSITORY_GERRIT_VERBOSE_LOGS, false); String gitRepoUrl = "ssh://" + username + "@" + hostname + ":" + port + "/" + project; String tmpCP = config.getString(REPOSITORY_GERRIT_CONFIG_DIR); if (tmpCP == null || tmpCP.isEmpty()) { tmpCP = GerritService.SYSTEM_DIRECTORY + File.separator + GerritService.CONFIG_DIRECTORY; } relativeConfigPath = tmpCP.replace("\\", "/"); absConfigPath = prepareConfigDir(relativeConfigPath).getAbsolutePath(); String tmpSSHKFP = config.getString(REPOSITORY_GERRIT_SSH_KEY_FILE); if (tmpSSHKFP == null || tmpSSHKFP.isEmpty()) { tmpSSHKFP = GerritService.SYSTEM_DIRECTORY + File.separator + GerritService.CONFIG_DIRECTORY; } relativeSSHKeyFilePath = tmpSSHKFP.replace("\\", "/"); String decryptedKey = encryptionService.decrypt(sshKey); sshKeyFile = prepareSSHKeyFile(relativeSSHKeyFilePath, decryptedKey); gc.setHost(hostname); gc.setPort(port); gc.setRepositoryUrl(gitRepoUrl); gc.setWorkingDirectory(absConfigPath); gc.setSshKeyFile(sshKeyFile); gc.setSshKey(decryptedKey); gc.setSshPassphrase(sshPassphrase); gc.setUsername(username); gc.setUserEmail(userEmail); gc.setUseShallowClones(useShallowClones); gc.setUseSubmodules(useSubmodules); gc.setVerboseLogs(verboseLogs); gc.setCommandTimeout(commandTimeout); try { initializeGerritService(); if (this.isOnLocalAgent()) { if (isRemoteTriggeringReop()) { getGerritDAO().addListener(this); } else { getGerritDAO().removeListener(this); } } } catch (RepositoryException e) { log.error(e.getMessage()); } }
From source file:jsprit.core.problem.io.VrpXMLReader.java
private void readVehiclesAndTheirTypes(XMLConfiguration vrpProblem) { //read vehicle-types Map<String, VehicleType> types = new HashMap<String, VehicleType>(); List<HierarchicalConfiguration> typeConfigs = vrpProblem.configurationsAt("vehicleTypes.type"); for (HierarchicalConfiguration typeConfig : typeConfigs) { String typeId = typeConfig.getString("id"); if (typeId == null) throw new IllegalStateException("typeId is missing."); String capacityString = typeConfig.getString("capacity"); boolean capacityDimensionsExist = typeConfig.containsKey("capacity-dimensions.dimension(0)"); if (capacityString == null && !capacityDimensionsExist) { throw new IllegalStateException("capacity of type is not set. use 'capacity-dimensions'"); }//from w ww.j av a 2 s . c o m if (capacityString != null && capacityDimensionsExist) { throw new IllegalStateException( "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'."); } VehicleTypeImpl.Builder typeBuilder; if (capacityString != null) { typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId).addCapacityDimension(0, Integer.parseInt(capacityString)); } else { typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId); List<HierarchicalConfiguration> dimensionConfigs = typeConfig .configurationsAt("capacity-dimensions.dimension"); for (HierarchicalConfiguration dimension : dimensionConfigs) { Integer index = dimension.getInt("[@index]"); Integer value = dimension.getInt(""); typeBuilder.addCapacityDimension(index, value); } } Double fix = typeConfig.getDouble("costs.fixed"); Double timeC = typeConfig.getDouble("costs.time"); Double distC = typeConfig.getDouble("costs.distance"); if (fix != null) typeBuilder.setFixedCost(fix); if (timeC != null) typeBuilder.setCostPerTime(timeC); if (distC != null) typeBuilder.setCostPerDistance(distC); VehicleType type = typeBuilder.build(); String id = type.getTypeId(); types.put(id, type); } //read vehicles List<HierarchicalConfiguration> vehicleConfigs = vrpProblem.configurationsAt("vehicles.vehicle"); boolean doNotWarnAgain = false; for (HierarchicalConfiguration vehicleConfig : vehicleConfigs) { String vehicleId = vehicleConfig.getString("id"); if (vehicleId == null) throw new IllegalStateException("vehicleId is missing."); Builder builder = VehicleImpl.Builder.newInstance(vehicleId); String typeId = vehicleConfig.getString("typeId"); if (typeId == null) throw new IllegalStateException("typeId is missing."); String vType = vehicleConfig.getString("[@type]"); if (vType != null) { if (vType.equals("penalty")) { typeId += "_penalty"; } } VehicleType type = types.get(typeId); if (type == null) throw new IllegalStateException("vehicleType with typeId " + typeId + " is missing."); builder.setType(type); //read startlocation Location.Builder startLocationBuilder = Location.Builder.newInstance(); String locationId = vehicleConfig.getString("location.id"); if (locationId == null) { locationId = vehicleConfig.getString("startLocation.id"); } startLocationBuilder.setId(locationId); String coordX = vehicleConfig.getString("location.coord[@x]"); String coordY = vehicleConfig.getString("location.coord[@y]"); if (coordX == null || coordY == null) { coordX = vehicleConfig.getString("startLocation.coord[@x]"); coordY = vehicleConfig.getString("startLocation.coord[@y]"); } if (coordX == null || coordY == null) { if (!doNotWarnAgain) { logger.debug("location.coord is missing. will not warn you again."); doNotWarnAgain = true; } } else { Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(coordX), Double.parseDouble(coordY)); startLocationBuilder.setCoordinate(coordinate); } String index = vehicleConfig.getString("startLocation.index"); if (index == null) index = vehicleConfig.getString("location.index"); if (index != null) { startLocationBuilder.setIndex(Integer.parseInt(index)); } builder.setStartLocation(startLocationBuilder.build()); //read endlocation Location.Builder endLocationBuilder = Location.Builder.newInstance(); boolean hasEndLocation = false; String endLocationId = vehicleConfig.getString("endLocation.id"); if (endLocationId != null) { hasEndLocation = true; endLocationBuilder.setId(endLocationId); } String endCoordX = vehicleConfig.getString("endLocation.coord[@x]"); String endCoordY = vehicleConfig.getString("endLocation.coord[@y]"); if (endCoordX == null || endCoordY == null) { if (!doNotWarnAgain) { logger.debug("endLocation.coord is missing. will not warn you again."); doNotWarnAgain = true; } } else { Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(endCoordX), Double.parseDouble(endCoordY)); hasEndLocation = true; endLocationBuilder.setCoordinate(coordinate); } String endLocationIndex = vehicleConfig.getString("endLocation.index"); if (endLocationIndex != null) { hasEndLocation = true; endLocationBuilder.setIndex(Integer.parseInt(endLocationIndex)); } if (hasEndLocation) builder.setEndLocation(endLocationBuilder.build()); //read timeSchedule String start = vehicleConfig.getString("timeSchedule.start"); String end = vehicleConfig.getString("timeSchedule.end"); if (start != null) builder.setEarliestStart(Double.parseDouble(start)); if (end != null) builder.setLatestArrival(Double.parseDouble(end)); //read return2depot String returnToDepot = vehicleConfig.getString("returnToDepot"); if (returnToDepot != null) { builder.setReturnToDepot(vehicleConfig.getBoolean("returnToDepot")); } //read skills String skillString = vehicleConfig.getString("skills"); if (skillString != null) { String cleaned = skillString.replaceAll("\\s", ""); String[] skillTokens = cleaned.split("[,;]"); for (String skill : skillTokens) builder.addSkill(skill.toLowerCase()); } //build vehicle VehicleImpl vehicle = builder.build(); vrpBuilder.addVehicle(vehicle); vehicleMap.put(vehicleId, vehicle); } }
From source file:com.graphhopper.jsprit.core.problem.io.VrpXMLReader.java
private void readVehiclesAndTheirTypes(XMLConfiguration vrpProblem) { //read vehicle-types Map<String, VehicleType> types = new HashMap<String, VehicleType>(); List<HierarchicalConfiguration> typeConfigs = vrpProblem.configurationsAt("vehicleTypes.type"); for (HierarchicalConfiguration typeConfig : typeConfigs) { String typeId = typeConfig.getString("id"); if (typeId == null) throw new IllegalStateException("typeId is missing."); String capacityString = typeConfig.getString("capacity"); boolean capacityDimensionsExist = typeConfig.containsKey("capacity-dimensions.dimension(0)"); if (capacityString == null && !capacityDimensionsExist) { throw new IllegalStateException("capacity of type is not set. use 'capacity-dimensions'"); }/*from w w w . j a va 2s . c o m*/ if (capacityString != null && capacityDimensionsExist) { throw new IllegalStateException( "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'."); } VehicleTypeImpl.Builder typeBuilder; if (capacityString != null) { typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId).addCapacityDimension(0, Integer.parseInt(capacityString)); } else { typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId); List<HierarchicalConfiguration> dimensionConfigs = typeConfig .configurationsAt("capacity-dimensions.dimension"); for (HierarchicalConfiguration dimension : dimensionConfigs) { Integer index = dimension.getInt("[@index]"); Integer value = dimension.getInt(""); typeBuilder.addCapacityDimension(index, value); } } Double fix = typeConfig.getDouble("costs.fixed"); Double timeC = typeConfig.getDouble("costs.time"); Double distC = typeConfig.getDouble("costs.distance"); if (fix != null) typeBuilder.setFixedCost(fix); if (timeC != null) typeBuilder.setCostPerTime(timeC); if (distC != null) typeBuilder.setCostPerDistance(distC); VehicleType type = typeBuilder.build(); String id = type.getTypeId(); types.put(id, type); } //read vehicles List<HierarchicalConfiguration> vehicleConfigs = vrpProblem.configurationsAt("vehicles.vehicle"); boolean doNotWarnAgain = false; for (HierarchicalConfiguration vehicleConfig : vehicleConfigs) { String vehicleId = vehicleConfig.getString("id"); if (vehicleId == null) throw new IllegalStateException("vehicleId is missing."); Builder builder = VehicleImpl.Builder.newInstance(vehicleId); String typeId = vehicleConfig.getString("typeId"); if (typeId == null) throw new IllegalStateException("typeId is missing."); String vType = vehicleConfig.getString("[@type]"); if (vType != null) { if (vType.equals("penalty")) { typeId += "_penalty"; } } VehicleType type = types.get(typeId); if (type == null) throw new IllegalStateException("vehicleType with typeId " + typeId + " is missing."); builder.setType(type); //read startlocation Location.Builder startLocationBuilder = Location.Builder.newInstance(); String locationId = vehicleConfig.getString("location.id"); if (locationId == null) { locationId = vehicleConfig.getString("startLocation.id"); } startLocationBuilder.setId(locationId); String coordX = vehicleConfig.getString("location.coord[@x]"); String coordY = vehicleConfig.getString("location.coord[@y]"); if (coordX == null || coordY == null) { coordX = vehicleConfig.getString("startLocation.coord[@x]"); coordY = vehicleConfig.getString("startLocation.coord[@y]"); } if (coordX == null || coordY == null) { if (!doNotWarnAgain) { logger.debug("location.coord is missing. will not warn you again."); doNotWarnAgain = true; } } else { Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(coordX), Double.parseDouble(coordY)); startLocationBuilder.setCoordinate(coordinate); } String index = vehicleConfig.getString("startLocation.index"); if (index == null) index = vehicleConfig.getString("location.index"); if (index != null) { startLocationBuilder.setIndex(Integer.parseInt(index)); } builder.setStartLocation(startLocationBuilder.build()); //read endlocation Location.Builder endLocationBuilder = Location.Builder.newInstance(); boolean hasEndLocation = false; String endLocationId = vehicleConfig.getString("endLocation.id"); if (endLocationId != null) { hasEndLocation = true; endLocationBuilder.setId(endLocationId); } String endCoordX = vehicleConfig.getString("endLocation.coord[@x]"); String endCoordY = vehicleConfig.getString("endLocation.coord[@y]"); if (endCoordX == null || endCoordY == null) { if (!doNotWarnAgain) { logger.debug("endLocation.coord is missing. will not warn you again."); doNotWarnAgain = true; } } else { Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(endCoordX), Double.parseDouble(endCoordY)); hasEndLocation = true; endLocationBuilder.setCoordinate(coordinate); } String endLocationIndex = vehicleConfig.getString("endLocation.index"); if (endLocationIndex != null) { hasEndLocation = true; endLocationBuilder.setIndex(Integer.parseInt(endLocationIndex)); } if (hasEndLocation) builder.setEndLocation(endLocationBuilder.build()); //read timeSchedule String start = vehicleConfig.getString("timeSchedule.start"); String end = vehicleConfig.getString("timeSchedule.end"); if (start != null) builder.setEarliestStart(Double.parseDouble(start)); if (end != null) builder.setLatestArrival(Double.parseDouble(end)); //read return2depot String returnToDepot = vehicleConfig.getString("returnToDepot"); if (returnToDepot != null) { builder.setReturnToDepot(vehicleConfig.getBoolean("returnToDepot")); } //read skills String skillString = vehicleConfig.getString("skills"); if (skillString != null) { String cleaned = skillString.replaceAll("\\s", ""); String[] skillTokens = cleaned.split("[,;]"); for (String skill : skillTokens) builder.addSkill(skill.toLowerCase()); } // read break List<HierarchicalConfiguration> breakTWConfigs = vehicleConfig .configurationsAt("break.timeWindows.timeWindow"); if (!breakTWConfigs.isEmpty()) { String breakDurationString = vehicleConfig.getString("breaks.duration"); Break.Builder current_break = Break.Builder.newInstance(vehicleId); current_break.setServiceTime(Double.parseDouble(breakDurationString)); for (HierarchicalConfiguration twConfig : breakTWConfigs) { current_break.addTimeWindow( TimeWindow.newInstance(twConfig.getDouble("start"), twConfig.getDouble("end"))); } builder.setBreak(current_break.build()); } //build vehicle VehicleImpl vehicle = builder.build(); vrpBuilder.addVehicle(vehicle); vehicleMap.put(vehicleId, vehicle); } }
From source file:com.graphhopper.jsprit.io.problem.VrpXMLReader.java
private void readVehiclesAndTheirTypes(XMLConfiguration vrpProblem) { //read vehicle-types Map<String, VehicleType> types = new HashMap<String, VehicleType>(); List<HierarchicalConfiguration> typeConfigs = vrpProblem.configurationsAt("vehicleTypes.type"); for (HierarchicalConfiguration typeConfig : typeConfigs) { String typeId = typeConfig.getString("id"); if (typeId == null) throw new IllegalArgumentException("typeId is missing."); String capacityString = typeConfig.getString("capacity"); boolean capacityDimensionsExist = typeConfig.containsKey("capacity-dimensions.dimension(0)"); if (capacityString == null && !capacityDimensionsExist) { throw new IllegalArgumentException("capacity of type is not set. use 'capacity-dimensions'"); }//from w w w. j a v a 2s. c om if (capacityString != null && capacityDimensionsExist) { throw new IllegalArgumentException( "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'."); } VehicleTypeImpl.Builder typeBuilder; if (capacityString != null) { typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId).addCapacityDimension(0, Integer.parseInt(capacityString)); } else { typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId); List<HierarchicalConfiguration> dimensionConfigs = typeConfig .configurationsAt("capacity-dimensions.dimension"); for (HierarchicalConfiguration dimension : dimensionConfigs) { Integer index = dimension.getInt("[@index]"); Integer value = dimension.getInt(""); typeBuilder.addCapacityDimension(index, value); } } Double fix = typeConfig.getDouble("costs.fixed"); Double timeC = typeConfig.getDouble("costs.time"); Double distC = typeConfig.getDouble("costs.distance"); if (typeConfig.containsKey("costs.service")) { Double serviceC = typeConfig.getDouble("costs.service"); if (serviceC != null) typeBuilder.setCostPerServiceTime(serviceC); } if (typeConfig.containsKey("costs.wait")) { Double waitC = typeConfig.getDouble("costs.wait"); if (waitC != null) typeBuilder.setCostPerWaitingTime(waitC); } if (fix != null) typeBuilder.setFixedCost(fix); if (timeC != null) typeBuilder.setCostPerTransportTime(timeC); if (distC != null) typeBuilder.setCostPerDistance(distC); VehicleType type = typeBuilder.build(); String id = type.getTypeId(); types.put(id, type); } //read vehicles List<HierarchicalConfiguration> vehicleConfigs = vrpProblem.configurationsAt("vehicles.vehicle"); boolean doNotWarnAgain = false; for (HierarchicalConfiguration vehicleConfig : vehicleConfigs) { String vehicleId = vehicleConfig.getString("id"); if (vehicleId == null) throw new IllegalArgumentException("vehicleId is missing."); Builder builder = VehicleImpl.Builder.newInstance(vehicleId); String typeId = vehicleConfig.getString("typeId"); if (typeId == null) throw new IllegalArgumentException("typeId is missing."); String vType = vehicleConfig.getString("[@type]"); if (vType != null) { if (vType.equals("penalty")) { typeId += "_penalty"; } } VehicleType type = types.get(typeId); if (type == null) throw new IllegalArgumentException("vehicleType with typeId " + typeId + " is missing."); builder.setType(type); //read startlocation Location.Builder startLocationBuilder = Location.Builder.newInstance(); String locationId = vehicleConfig.getString("location.id"); if (locationId == null) { locationId = vehicleConfig.getString("startLocation.id"); } startLocationBuilder.setId(locationId); String coordX = vehicleConfig.getString("location.coord[@x]"); String coordY = vehicleConfig.getString("location.coord[@y]"); if (coordX == null || coordY == null) { coordX = vehicleConfig.getString("startLocation.coord[@x]"); coordY = vehicleConfig.getString("startLocation.coord[@y]"); } if (coordX == null || coordY == null) { if (!doNotWarnAgain) { logger.debug("location.coord is missing. will not warn you again."); doNotWarnAgain = true; } } else { Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(coordX), Double.parseDouble(coordY)); startLocationBuilder.setCoordinate(coordinate); } String index = vehicleConfig.getString("startLocation.index"); if (index == null) index = vehicleConfig.getString("location.index"); if (index != null) { startLocationBuilder.setIndex(Integer.parseInt(index)); } builder.setStartLocation(startLocationBuilder.build()); //read endlocation Location.Builder endLocationBuilder = Location.Builder.newInstance(); boolean hasEndLocation = false; String endLocationId = vehicleConfig.getString("endLocation.id"); if (endLocationId != null) { hasEndLocation = true; endLocationBuilder.setId(endLocationId); } String endCoordX = vehicleConfig.getString("endLocation.coord[@x]"); String endCoordY = vehicleConfig.getString("endLocation.coord[@y]"); if (endCoordX == null || endCoordY == null) { if (!doNotWarnAgain) { logger.debug("endLocation.coord is missing. will not warn you again."); doNotWarnAgain = true; } } else { Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(endCoordX), Double.parseDouble(endCoordY)); hasEndLocation = true; endLocationBuilder.setCoordinate(coordinate); } String endLocationIndex = vehicleConfig.getString("endLocation.index"); if (endLocationIndex != null) { hasEndLocation = true; endLocationBuilder.setIndex(Integer.parseInt(endLocationIndex)); } if (hasEndLocation) builder.setEndLocation(endLocationBuilder.build()); //read timeSchedule String start = vehicleConfig.getString("timeSchedule.start"); String end = vehicleConfig.getString("timeSchedule.end"); if (start != null) builder.setEarliestStart(Double.parseDouble(start)); if (end != null) builder.setLatestArrival(Double.parseDouble(end)); //read return2depot String returnToDepot = vehicleConfig.getString("returnToDepot"); if (returnToDepot != null) { builder.setReturnToDepot(vehicleConfig.getBoolean("returnToDepot")); } //read skills String skillString = vehicleConfig.getString("skills"); if (skillString != null) { String cleaned = skillString.replaceAll("\\s", ""); String[] skillTokens = cleaned.split("[,;]"); for (String skill : skillTokens) builder.addSkill(skill.toLowerCase()); } // read break List<HierarchicalConfiguration> breakTWConfigs = vehicleConfig .configurationsAt("breaks.timeWindows.timeWindow"); if (!breakTWConfigs.isEmpty()) { String breakDurationString = vehicleConfig.getString("breaks.duration"); Break.Builder current_break = Break.Builder.newInstance(vehicleId); current_break.setServiceTime(Double.parseDouble(breakDurationString)); for (HierarchicalConfiguration twConfig : breakTWConfigs) { current_break.addTimeWindow( TimeWindow.newInstance(twConfig.getDouble("start"), twConfig.getDouble("end"))); } builder.setBreak(current_break.build()); } //build vehicle VehicleImpl vehicle = builder.build(); vrpBuilder.addVehicle(vehicle); vehicleMap.put(vehicleId, vehicle); } }