Ejemplo n.º 1
0
 void LoadConfig() {
   String id = Long.toString(robot_uid);
   limit_top = Double.valueOf(prefs.get(id + "_limit_top", "0"));
   limit_bottom = Double.valueOf(prefs.get(id + "_limit_bottom", "0"));
   limit_left = Double.valueOf(prefs.get(id + "_limit_left", "0"));
   limit_right = Double.valueOf(prefs.get(id + "_limit_right", "0"));
   m1invert = Boolean.parseBoolean(prefs.get(id + "_m1invert", "false"));
   m2invert = Boolean.parseBoolean(prefs.get(id + "_m2invert", "false"));
 }
Ejemplo n.º 2
0
  public static String[] exec(String command, String interpret) {

    log.info("RListener - calling DirectJNI.getInstance().exec(" + command + ")");

    String[] result =
        DirectJNI.getInstance()
            .exec(command, Boolean.parseBoolean(interpret), !Boolean.parseBoolean(interpret));

    log.info("RListener - DirectJNI returned");

    return result;
  }
  /**
   * Parses the arguments table from the GATK Report and creates a RAC object with the proper
   * initialization values
   *
   * @param table the GATKReportTable containing the arguments and its corresponding values
   * @return a RAC object properly initialized with all the objects in the table
   */
  private RecalibrationArgumentCollection initializeArgumentCollectionTable(GATKReportTable table) {
    final RecalibrationArgumentCollection RAC = new RecalibrationArgumentCollection();

    for (int i = 0; i < table.getNumRows(); i++) {
      final String argument = table.get(i, "Argument").toString();
      Object value = table.get(i, RecalUtils.ARGUMENT_VALUE_COLUMN_NAME);
      if (value.equals("null"))
        value =
            null; // generic translation of null values that were printed out as strings | todo --
                  // add this capability to the GATKReport

      if (argument.equals("covariate") && value != null)
        RAC.COVARIATES = value.toString().split(",");
      else if (argument.equals("standard_covs"))
        RAC.DO_NOT_USE_STANDARD_COVARIATES = Boolean.parseBoolean((String) value);
      else if (argument.equals("solid_recal_mode"))
        RAC.SOLID_RECAL_MODE = RecalUtils.SOLID_RECAL_MODE.recalModeFromString((String) value);
      else if (argument.equals("solid_nocall_strategy"))
        RAC.SOLID_NOCALL_STRATEGY =
            RecalUtils.SOLID_NOCALL_STRATEGY.nocallStrategyFromString((String) value);
      else if (argument.equals("mismatches_context_size"))
        RAC.MISMATCHES_CONTEXT_SIZE = Integer.parseInt((String) value);
      else if (argument.equals("indels_context_size"))
        RAC.INDELS_CONTEXT_SIZE = Integer.parseInt((String) value);
      else if (argument.equals("mismatches_default_quality"))
        RAC.MISMATCHES_DEFAULT_QUALITY = Byte.parseByte((String) value);
      else if (argument.equals("insertions_default_quality"))
        RAC.INSERTIONS_DEFAULT_QUALITY = Byte.parseByte((String) value);
      else if (argument.equals("deletions_default_quality"))
        RAC.DELETIONS_DEFAULT_QUALITY = Byte.parseByte((String) value);
      else if (argument.equals("maximum_cycle_value"))
        RAC.MAXIMUM_CYCLE_VALUE = Integer.parseInt((String) value);
      else if (argument.equals("low_quality_tail"))
        RAC.LOW_QUAL_TAIL = Byte.parseByte((String) value);
      else if (argument.equals("default_platform")) RAC.DEFAULT_PLATFORM = (String) value;
      else if (argument.equals("force_platform")) RAC.FORCE_PLATFORM = (String) value;
      else if (argument.equals("quantizing_levels"))
        RAC.QUANTIZING_LEVELS = Integer.parseInt((String) value);
      else if (argument.equals("recalibration_report"))
        RAC.existingRecalibrationReport = (value == null) ? null : new File((String) value);
      else if (argument.equals("binary_tag_name"))
        RAC.BINARY_TAG_NAME = (value == null) ? null : (String) value;
      else if (argument.equals("sort_by_all_columns"))
        RAC.SORT_BY_ALL_COLUMNS = Boolean.parseBoolean((String) value);
    }

    return RAC;
  }
Ejemplo n.º 4
0
 /**
  * Convert the string input param value to its typed object value.
  *
  * @param value The string value of the input param
  * @param type The type of the input value, defined at DBConstants.DataTypes.
  * @return The typed object value of the input param
  */
 public static Object convertInputParamValue(String value, String type) throws DataServiceFault {
   try {
     if (DBConstants.DataTypes.INTEGER.equals(type)) {
       return Integer.parseInt(value);
     } else if (DBConstants.DataTypes.LONG.equals(type)) {
       return Long.parseLong(value);
     } else if (DBConstants.DataTypes.FLOAT.equals(type)) {
       return Float.parseFloat(value);
     } else if (DBConstants.DataTypes.DOUBLE.equals(type)) {
       return Double.parseDouble(value);
     } else if (DBConstants.DataTypes.BOOLEAN.equals(type)) {
       return Boolean.parseBoolean(value);
     } else if (DBConstants.DataTypes.DATE.equals(type)) {
       return new java.util.Date(DBUtils.getDate(value).getTime());
     } else if (DBConstants.DataTypes.TIME.equals(type)) {
       Calendar cal = Calendar.getInstance();
       cal.setTimeInMillis(DBUtils.getTime(value).getTime());
       return cal;
     } else if (DBConstants.DataTypes.TIMESTAMP.equals(type)) {
       Calendar cal = Calendar.getInstance();
       cal.setTimeInMillis(DBUtils.getTimestamp(value).getTime());
       return cal;
     } else {
       return value;
     }
   } catch (Exception e) {
     throw new DataServiceFault(e);
   }
 }
Ejemplo n.º 5
0
 public boolean getBoolean(String key, boolean def) {
   try {
     String v = getValue(key);
     if (v != null) return Boolean.parseBoolean(v);
   } catch (Exception e) {
   }
   return def;
 }
Ejemplo n.º 6
0
  private boolean resolveBooleanArg(String arg, boolean defaultValue) {
    if (arg == null) return defaultValue;

    try {
      return Boolean.parseBoolean(arg);
    } catch (Exception e) {
      return defaultValue;
    }
  }
Ejemplo n.º 7
0
 protected Boolean getDisplayTime(OWLOntology o, OWLEntity owlEntity) {
   String val =
       getAnnotationValueByUri(
           o, owlEntity, OntologyLumifyProperties.DISPLAY_TIME.getPropertyName());
   if (val == null) {
     return null;
   }
   return Boolean.parseBoolean(val);
 }
Ejemplo n.º 8
0
 @Before
 public void setUp() {
   if (!Boolean.parseBoolean(System.getProperty("test.solr.verbose"))) {
     java.util.logging.Logger.getLogger("org.apache.solr")
         .setLevel(java.util.logging.Level.SEVERE);
     Utils.setLog4jLogLevel(org.apache.log4j.Level.WARN);
   }
   testDataParentPath = System.getProperty("test.data.path");
   testConfigFname = System.getProperty("test.config.file");
   // System.out.println("-----testDataParentPath = "+testDataParentPath);
 }
 /*
  * Clean up the temporary data used to run the tests.
  * This method is not intended to be called by clients, it will be called
  * automatically when the clients use a ReconcilerTestSuite.
  */
 public void cleanup() throws Exception {
   // rm -rf eclipse sub-dir
   boolean leaveDirty =
       Boolean.parseBoolean(TestActivator.getContext().getProperty("p2.tests.doNotClean"));
   if (leaveDirty) return;
   for (Iterator iter = toRemove.iterator(); iter.hasNext(); ) {
     File next = (File) iter.next();
     delete(next);
   }
   output = null;
   toRemove.clear();
 }
  public void readExternal(Element element) throws InvalidDataException {
    //noinspection unchecked

    final String showRecycled = element.getAttributeValue(ATTRIBUTE_SHOW_RECYCLED);
    if (showRecycled != null) {
      myShowRecycled = Boolean.parseBoolean(showRecycled);
    } else {
      myShowRecycled = true;
    }

    readExternal(element, myShelvedChangeLists, myRecycledShelvedChangeLists);
  }
Ejemplo n.º 11
0
  @Override
  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just connected to " + server.getRemoteSocketAddress());
        DataInputStream in = new DataInputStream(server.getInputStream());

        DataOutputStream out = new DataOutputStream(server.getOutputStream());

        String request = in.readUTF();
        String[] split = request.split("#");
        if (split[0].compareTo("login") == 0) {
          if (db.checkLogin(split[1], split[2])) {
            out.writeUTF("true#" + System.currentTimeMillis());
          } else {
            out.writeUTF("false");
          }
        } else if (split[0].compareTo("sync") == 0) {
          List<Tugas> tasks = db.getTugas(split[1]);
          out.flush();
          out.writeInt(serialize(tasks).length);
          out.flush();
          for (int i = 0; i < tasks.size(); i++) {
            System.out.println(i);
            System.out.println(
                tasks.get(i).getId()
                    + tasks.get(i).getNama()
                    + tasks.get(i).getDeadline().toString()
                    + tasks.get(i).isStatus()
                    + tasks.get(i).getLast_mod()
                    + tasks.get(i).getKategori()
                    + tasks.get(i).getAssignee()
                    + tasks.get(i).getTag());
          }
          out.write(serialize(tasks), 0, serialize(tasks).length);
          System.out.print(serialize(tasks).length);
        } else if (split[0].compareTo("update") == 0) {
          db.Update(
              Integer.parseInt(split[1]),
              Boolean.parseBoolean(split[2]),
              Long.parseLong(split[3], 10));
          System.out.println("update");
        }

        server.close();
      } catch (IOException e) {

      }
    }
  }
Ejemplo n.º 12
0
  protected void doWatchOutputDir() throws ServletException, IOException {
    String sOutputDirToWatch = Consts.getOutputTempDirectory();
    String sFileExtToWatch = Consts.getOutputWatchDirectoryFileExtension();
    final String sOutputDir = Consts.getOutputWatchDirectory();
    final String sArchiveOutputDir = Consts.getOutputArchiveDirectory();
    final boolean bEncryptOutput = Boolean.parseBoolean(Consts.getDoEncrypt());

    // fire up the watcher
    TimerTask task =
        new DirWatcher(sOutputDirToWatch, sFileExtToWatch) {
          protected void onChange(File file, String action, BufferedOutputStream log) {
            // here we code the action on a change - only process add situations
            if (action.equalsIgnoreCase(Consts.FILE_ACTION_ADD)) {
              try {
                // Load up the BouncyCastle Crypto engine
                Security.addProvider(new BouncyCastleProvider());
                Writer writer = new Writer();
                FileUtils.writeLog("Encrypting File " + file.getName(), log);
                writer.encryptOutput(file, sOutputDir, bEncryptOutput, sArchiveOutputDir);
              } catch (Exception e) {
                try {
                  FileUtils.writeLog("Exception in doWatchOutputDir(): " + e.toString(), log);
                  FileUtils.writeLog(
                      "Exception in doWatchOutputDir() Stack Trace: " + FileUtils.getStackTrace(e),
                      log);
                  // TODO - need to find a way to notify this error
                } catch (Exception ex) {
                  // eat this error
                }
              }
            }
          }
        };

    Timer timer = new Timer();
    //        timer.schedule( task , new Date(), 200000);

    // run every hour at 15 minutes after the hour to give time for connector to process it
    // (connector runs at *:50)
    // once per hour - in milliseconds
    long ONCE_PER_HOUR = 1000 * 60 * 60;

    // set this to current hour 15 minutes or next hour 15 minutes
    Calendar rightNow = new GregorianCalendar();
    if (rightNow.get(Calendar.MINUTE) >= 15) {
      rightNow.add(Calendar.HOUR, 1);
    }
    rightNow.set(Calendar.MINUTE, 1);
    rightNow.set(Calendar.SECOND, 1);

    timer.scheduleAtFixedRate(task, rightNow.getTime(), ONCE_PER_HOUR);
  }
Ejemplo n.º 13
0
  static {
    ConfigurationService cfg = LibJitsi.getConfigurationService();
    boolean dropUnencryptedPkts = false;

    if (cfg == null) {
      String s = System.getProperty(DROP_UNENCRYPTED_PKTS_PNAME);

      if (s != null) dropUnencryptedPkts = Boolean.parseBoolean(s);
    } else {
      dropUnencryptedPkts = cfg.getBoolean(DROP_UNENCRYPTED_PKTS_PNAME, dropUnencryptedPkts);
    }
    DROP_UNENCRYPTED_PKTS = dropUnencryptedPkts;
  }
Ejemplo n.º 14
0
 public void load(InputStream inputStream) throws Exception {
   BufferedReader bur = new BufferedReader(new InputStreamReader(inputStream));
   while (bur.ready()) {
     User user = new User();
     user.setFirstName(bur.readLine());
     user.setLastName(bur.readLine());
     user.setBirthDate(new Date(Long.parseLong(bur.readLine())));
     user.setMale(Boolean.parseBoolean(bur.readLine()));
     user.setCountry(User.Country.valueOf(bur.readLine()));
     users.add(user);
   }
   bur.close();
 }
Ejemplo n.º 15
0
  private void getConfig() throws IOException {
    Properties configFile = new Properties();
    configFile.load(
        this.getClass().getClassLoader().getResourceAsStream("./config/net_config.txt"));

    this.STATUS_DELAY = Integer.parseInt(configFile.getProperty("statusDelay"));
    this.TRACKS_DELAY = Integer.parseInt(configFile.getProperty("tracksDelay"));
    this.IMAGE_DELAY = Integer.parseInt(configFile.getProperty("imageDelay"));
    this.MAIN_RUNTIME = Integer.parseInt(configFile.getProperty("mainRunTime"));
    this.VERBOSE = Boolean.parseBoolean(configFile.getProperty("verbose"));
    this.sizeX = Integer.parseInt(configFile.getProperty("sizeX"));
    this.sizeY = Integer.parseInt(configFile.getProperty("sizeY"));
    this.channels = Integer.parseInt(configFile.getProperty("channels"));
  }
Ejemplo n.º 16
0
 private static Object parseAttributeValue(String type, String value) {
   switch (type) {
     case "bool":
       return Boolean.parseBoolean(value);
     case "int":
       return Integer.parseInt(value);
     case "long":
       return Long.parseLong(value);
     case "float":
       return Float.parseFloat(value);
     case "double":
       return Double.parseDouble(value);
   }
   return value;
 }
Ejemplo n.º 17
0
  private void doReincarnation() throws RDCException {
    try {
      // TODO JavaClassRunner is very simple and primitive.
      // Feel free to beef it up...

      String[] props = normalProps;

      if (Boolean.parseBoolean(System.getenv("AS_SUPER_DEBUG")))
        props = debuggerProps; // very very difficult to debug this stuff otherwise!

      new JavaClassRunner(classpath, props, classname, args);
    } catch (Exception e) {
      logger.severe(strings.get("restart.server.jvmError", e));
      throw new RDCException();
    }
  }
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        String isEncryptHeader =  httpRequest.getHeader("data-encrypt");
        if(!StringUtils.isEmpty(isEncryptHeader)){
            Boolean isEncrypt =  Boolean.parseBoolean(isEncryptHeader);
            if(isEncrypt){
                processEncrypt(servletRequest, httpRequest, servletResponse, filterChain);
            }

        }else{
            throw new ServletException("Encrypt key not found");
        }


    }
Ejemplo n.º 19
0
  public static void loadSettings() {

    if (!new File("/plugins/config/WorldTools/MySQL.properties").exists()) {
      try {
        File f = new File("plugins/config/WorldTools/MySQL.properties");
        BufferedWriter out = new BufferedWriter(new FileWriter(f));
        out.write("############################");
        out.newLine();
        out.write("# THIS IS CURRENTLY UNUSED #");
        out.newLine();
        out.write("############################");
        out.newLine();
        out.write("useCanarySQL=true");
        out.newLine();
        out.newLine();
        out.write("SQLdriver=com.mysql.jdbc.Driver");
        out.newLine();
        out.newLine();
        out.write("SQLuser=root");
        out.newLine();
        out.newLine();
        out.write("SQLpass=root");
        out.newLine();
        out.newLine();
        out.write("SQLdb=jdbc:mysql://localhost:3306/minecraft");
        out.newLine();
        out.newLine();
      } catch (IOException e) {
        log.info("[WorldTools] - Error during creating SQL propertiesfile!");
        e.printStackTrace();
      }
    }
    PropertiesFile properties = new PropertiesFile("/plugins/config/WorldTools/MySQL.properties");
    try {
      SQLdriver = properties.getProperty("SQLdriver");
      SQLusername = properties.getProperty("SQLuser");
      SQLpassword = properties.getProperty("SQLpass");
      SQLdb = properties.getProperty("SQLdb");
      useSql = Boolean.parseBoolean(properties.getProperty("UseCanarySQL"));
    } catch (Exception e) {
      log.log(Level.SEVERE, "Exception while reading from the mysql properties", e);
    }
    getConnection();
  }
Ejemplo n.º 20
0
    @Override
    protected void read(InputStream input) throws XMLStreamException {
      parser = getXMLInputFactory().createXMLStreamReader(input);

      skipRoot("weblogic-web-app");

      int event = 0;
      while (parser.hasNext() && (event = parser.next()) != END_DOCUMENT) {
        if (event == START_ELEMENT) {
          String name = parser.getLocalName();
          if ("prefer-web-inf-classes".equals(name)) {
            // weblogic DD has default "false" for perfer-web-inf-classes
            delegate = !Boolean.parseBoolean(parser.getElementText());
            break;
          } else if (!"container-descriptor".equals(name)) {
            skipSubTree(name);
          }
        }
      }
    }
Ejemplo n.º 21
0
  @Override
  public void parse(InputStream in, OutputStream out) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
    CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
    Date startTime = Settings.getInstance().getStartTime();
    Date endTime = Settings.getInstance().getEndTime();
    long startTimeVal = startTime == null ? -1 : startTime.getTime();
    long endTimeVal = endTime == null ? -1 : endTime.getTime();

    String line;
    while ((line = reader.readLine()) != null) {
      String[] fields = line.split(",");
      long timestamp = Long.parseLong(fields[0]);
      if (timestamp == 0) {
        LOGGER.warning("Skip invalid data row: " + line);
        continue;
      }
      int rt = Integer.parseInt(fields[1]);
      if (startTimeVal > 0 && timestamp + rt < startTimeVal
          || endTimeVal > 0 && timestamp + rt > endTimeVal) continue;
      String label = fields[2];
      int skip = 0;
      if (fields[4].startsWith("\"")) ++skip;
      if (fields[skip + 5].startsWith("\"")) ++skip;
      int latency = Integer.parseInt(fields[skip + 9]);
      int threads = 0;
      int bytes = Integer.parseInt(fields[skip + 8]);
      boolean error = !Boolean.parseBoolean(fields[skip + 7]);
      csvPrinter.printRecord(
          "TX-" + label + (error ? "-F" : "-S"),
          timestamp,
          threads,
          error ? '1' : '0',
          latency,
          rt,
          bytes);
    }
    writer.flush();
  }
Ejemplo n.º 22
0
  @Override
  public void init() {
    try {
      this.debug = Boolean.parseBoolean(this.getInitParameter("debug"));

      if (!this.debug) this.pageInfoCache = new HashMap<String, PageInfo>();

      String routesParameter = this.getInitParameter("routes");
      if (routesParameter != null) {
        this.routes = new Properties();
        routes.load(new StringReader(routesParameter));
      }

      String sourceParameter = this.getInitParameter("source");
      if (sourceParameter == null) throw new RuntimeException("Missing init parameter 'source'");
      // automatically insert a reference to our PageServlet.js if not present
      String sourceDelimiter = ";";
      if (sourceParameter.indexOf("PageServlet.js") < 0)
        sourceParameter =
            "jar:file:WEB-INF/lib/glasspages.jar!/glasspages/PageServlet.js"
                + sourceDelimiter
                + sourceParameter;
      this.errorPath = this.getInitParameter("error");
      String[] sourceFiles = sourceParameter.split(sourceDelimiter);
      URL[] sourceUrls = new URL[sourceFiles.length];
      for (int i = 0; i < sourceFiles.length; i++) {
        String sourceFile = sourceFiles[i];
        if (sourceFile.indexOf(':') < 0) sourceFile = "file:" + sourceFile;
        try {
          sourceUrls[i] = new URL(sourceFile);
        } catch (MalformedURLException e) {
          throw new RuntimeException(e);
        }
      }
      this.contextCache = new ScriptContextCache(sourceUrls);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 23
0
  // read enemy launchers and their missiles form XML
  protected void readEnemyLaunchers() {
    NodeList launchers = root.getElementsByTagName("launcher");

    for (int i = 0; i < launchers.getLength(); i++) {
      Element tempLauncher = (Element) launchers.item(i);

      String idLauncher = tempLauncher.getAttribute("id");
      boolean isHidden = Boolean.parseBoolean(tempLauncher.getAttribute("isHidden"));

      // add to the war
      war.addEnemyLauncher(idLauncher, isHidden);
      IdGenerator.updateEnemyLauncherId(idLauncher);

      NodeList missiles = tempLauncher.getElementsByTagName("missile");

      // read all missiles
      readMissilesForGivenLauncher(missiles, idLauncher);
    }

    // update the id's in the war
    IdGenerator.updateFinalEnemyMissileId();
    IdGenerator.updateFinalEnemyLauncherId();
  }
Ejemplo n.º 24
0
 private static Boolean isInMemory() {
   if (inMemory == null) {
     Properties properties = new Properties();
     URL resource = PropertiesReader.class.getClassLoader().getResource("properties.properties");
     if (resource != null) {
       try (InputStream input = new FileInputStream(Paths.get(resource.toURI()).toFile())) {
         properties.load(input);
         String property = properties.getProperty("inMemory");
         URL = properties.getProperty("URL");
         LOGIN = properties.getProperty("LOGIN");
         PASSWORD = properties.getProperty("PASSWORD");
         DRIVER_CLASS = properties.getProperty("DRIVER_CLASS");
         if (property != null) {
           inMemory = Boolean.parseBoolean(property);
         }
         System.out.println(inMemory);
       } catch (IOException | URISyntaxException e) {
         e.printStackTrace();
       }
     }
   }
   return (inMemory != null && inMemory);
 }
Ejemplo n.º 25
0
  public static void main(String[] args) throws IOException {

    // open file output stream
    File outFile = new File("data");
    FileOutputStream outStream = new FileOutputStream(outFile);
    PrintWriter pWriter = new PrintWriter(outStream);

    // write an int, boolean, double
    pWriter.println("44");
    pWriter.println("true");
    pWriter.println("7.2");

    pWriter.close();

    // open file input stream
    File inFile = new File("data");
    FileReader fileReader = new FileReader(inFile);
    BufferedReader buffReader = new BufferedReader(fileReader);

    // read an int, boolean, double
    String in = buffReader.readLine();
    int n = Integer.parseInt(in);
    String bool = buffReader.readLine();
    boolean b = Boolean.parseBoolean(bool);
    String doub = buffReader.readLine();
    double d = Double.parseDouble(doub);

    buffReader.close();

    // what did we get?
    System.out.println("n = " + n);
    System.out.println("b = " + b);
    System.out.println("d = " + d);

    // can we add n to d?
    System.out.println("n + d = " + (n + d));
  }
Ejemplo n.º 26
0
  protected void processConfiguration(FilterConfig filterConfig) {
    InputStream is;

    if (isNullOrEmpty(this.configFile)) {
      is = servletContext.getResourceAsStream(CONFIG_FILE_LOCATION);
    } else {
      try {
        is = new FileInputStream(this.configFile);
      } catch (FileNotFoundException e) {
        throw logger.samlIDPConfigurationError(e);
      }
    }

    PicketLinkType picketLinkType;

    String configurationProviderName = filterConfig.getInitParameter(CONFIGURATION_PROVIDER);

    if (configurationProviderName != null) {
      try {
        Class<?> clazz = SecurityActions.loadClass(getClass(), configurationProviderName);

        if (clazz == null) {
          throw new ClassNotFoundException(ErrorCodes.CLASS_NOT_LOADED + configurationProviderName);
        }

        this.configProvider = (SAMLConfigurationProvider) clazz.newInstance();
      } catch (Exception e) {
        throw new RuntimeException(
            "Could not create configuration provider [" + configurationProviderName + "].", e);
      }
    }

    try {
      // Work on the IDP Configuration
      if (configProvider != null) {
        try {
          if (is == null) {
            // Try the older version
            is =
                servletContext.getResourceAsStream(
                    GeneralConstants.DEPRECATED_CONFIG_FILE_LOCATION);

            // Additionally parse the deprecated config file
            if (is != null && configProvider instanceof AbstractSAMLConfigurationProvider) {
              ((AbstractSAMLConfigurationProvider) configProvider).setConfigFile(is);
            }
          } else {
            // Additionally parse the consolidated config file
            if (is != null && configProvider instanceof AbstractSAMLConfigurationProvider) {
              ((AbstractSAMLConfigurationProvider) configProvider).setConsolidatedConfigFile(is);
            }
          }

          picketLinkType = configProvider.getPicketLinkConfiguration();
          picketLinkType.setIdpOrSP(configProvider.getSPConfiguration());
        } catch (ProcessingException e) {
          throw logger.samlSPConfigurationError(e);
        } catch (ParsingException e) {
          throw logger.samlSPConfigurationError(e);
        }
      } else {
        if (is != null) {
          try {
            picketLinkType = ConfigurationUtil.getConfiguration(is);
          } catch (ParsingException e) {
            logger.trace(e);
            throw logger.samlSPConfigurationError(e);
          }
        } else {
          is = servletContext.getResourceAsStream(GeneralConstants.DEPRECATED_CONFIG_FILE_LOCATION);
          if (is == null) {
            throw logger.configurationFileMissing(configFile);
          }

          picketLinkType = new PicketLinkType();

          picketLinkType.setIdpOrSP(ConfigurationUtil.getSPConfiguration(is));
        }
      }

      // Close the InputStream as we no longer need it
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          // ignore
        }
      }

      Boolean enableAudit = picketLinkType.isEnableAudit();

      // See if we have the system property enabled
      if (!enableAudit) {
        String sysProp = SecurityActions.getSystemProperty(GeneralConstants.AUDIT_ENABLE, "NULL");
        if (!"NULL".equals(sysProp)) {
          enableAudit = Boolean.parseBoolean(sysProp);
        }
      }

      if (enableAudit) {
        if (auditHelper == null) {
          String securityDomainName = PicketLinkAuditHelper.getSecurityDomainName(servletContext);

          auditHelper = new PicketLinkAuditHelper(securityDomainName);
        }
      }

      SPType spConfiguration = (SPType) picketLinkType.getIdpOrSP();
      processIdPMetadata(spConfiguration);

      this.serviceURL = spConfiguration.getServiceURL();
      this.canonicalizationMethod = spConfiguration.getCanonicalizationMethod();
      this.picketLinkConfiguration = picketLinkType;

      this.issuerID = filterConfig.getInitParameter(ISSUER_ID);
      this.characterEncoding = filterConfig.getInitParameter(CHARACTER_ENCODING);
      this.samlHandlerChainClass = filterConfig.getInitParameter(SAML_HANDLER_CHAIN_CLASS);

      logger.samlSPSettingCanonicalizationMethod(canonicalizationMethod);
      XMLSignatureUtil.setCanonicalizationMethodType(canonicalizationMethod);

      try {
        this.initKeyProvider();
        this.initializeHandlerChain(picketLinkType);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }

      logger.trace("Identity Provider URL=" + getConfiguration().getIdentityURL());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 27
0
  private RMResult processIfComposite(String requestString) {
    // Execute a composite method for this request if necessary.
    // Returns a result, or null if the request corresponds to
    // no composite action.
    RMResult result = null;
    String[] parts = requestString.split(",");

    switch (parts[0]) {
      case Command.INTERFACE_DELETE_CUSTOMER:
        {
          for (int i = 0; i < 4; ++i) {
            result = processAtomicRequest(requestString, _rmIps[i], _rmPorts[i]);
          }
        }
        break;
      case Command.INTERFACE_RESERVE_ITINERARY:
        {
          // requestString = "command, id, cid, flight1, ..., flightn, location, isCarDesired,
          // isRoomDesired"
          ArrayList<String> flightNumbers =
              new ArrayList<>(Arrays.asList(requestString.split(",")));
          flightNumbers.remove(0);
          String id = flightNumbers.remove(0).trim();
          String customerId = flightNumbers.remove(0).trim();
          boolean isRoomDesired =
              Boolean.parseBoolean(flightNumbers.remove(flightNumbers.size() - 1).trim());
          boolean isCarDesired =
              Boolean.parseBoolean(flightNumbers.remove(flightNumbers.size() - 1).trim());
          String location = flightNumbers.remove(flightNumbers.size() - 1).trim();

          for (String flightNumber : flightNumbers) {
            result =
                processAtomicRequest(
                    Command.INTERFACE_QUERY_FLIGHT + ", " + id + ", " + flightNumber.trim(),
                    _rmIps[0],
                    _rmPorts[0]);
            if (result.AsInt() <= 0) {
              return new RMResult(false);
            }
          }

          if (isCarDesired) {
            result =
                processAtomicRequest(
                    Command.INTERFACE_QUERY_CARS + ", " + id + ", " + location,
                    _rmIps[1],
                    _rmPorts[1]);
            if (result.AsInt() <= 0) {
              return new RMResult(false);
            }
          }

          if (isRoomDesired) {
            result =
                processAtomicRequest(
                    Command.INTERFACE_QUERY_ROOMS + ", " + id + ", " + location,
                    _rmIps[2],
                    _rmPorts[2]);
            if (result.AsInt() <= 0) {
              return new RMResult(false);
            }
          }

          for (String flightNumber : flightNumbers) {
            String command =
                Command.INTERFACE_RESERVE_FLIGHT
                    + ", "
                    + id
                    + ", "
                    + customerId
                    + ", "
                    + flightNumber.trim();
            result = processIfCIDRequired(command);
            if (!result.AsBool()) {
              return result;
            }
          }

          if (isCarDesired) {
            String command =
                Command.INTERFACE_RESERVE_CAR + ", " + id + ", " + customerId + ", " + location;
            result = processIfCIDRequired(command);
            if (!result.AsBool()) {
              return result;
            }
          }

          if (isRoomDesired) {
            String command =
                Command.INTERFACE_RESERVE_ROOM + ", " + id + ", " + customerId + ", " + location;
            result = processIfCIDRequired(command);
            if (!result.AsBool()) {
              return result;
            }
          }
        }
        break;
      case Command.INTERFACE_QUERY_CUSTOMER_INFO:
        {
          ArrayList<String> finalBill = new ArrayList<>();

          // i < 3 to exclude customer rm
          for (int i = 0; i < 3; ++i) {
            result = processAtomicRequest(requestString, _rmIps[i], _rmPorts[i]);
            if (!(result.AsString().equals(""))) {
              finalBill = addToBill(finalBill, result);
            }
          }

          String resultString =
              "Customer either does not exist or has not made any reservation yet.";

          if (finalBill.size() != 0) {
            finalBill = addBillTotal(finalBill);

            finalBill.add(finalBill.size(), "}");

            resultString = String.join("\n", finalBill);
          }

          result = new RMResult(resultString);
        }
        break;
      default:
        break;
    }

    return result;
  }
Ejemplo n.º 28
0
 ////////////////////////////////////////////////////////////////////////////
 ////////////////////////////////////////////////////////////////////////////
 /////////               ALL PRIVATE BELOW               ////////////////////
 ////////////////////////////////////////////////////////////////////////////
 ////////////////////////////////////////////////////////////////////////////
 private void init(AdminCommandContext context) throws IOException {
   logger = context.getLogger();
   props = Globals.get(StartupContext.class).getArguments();
   verbose = Boolean.parseBoolean(props.getProperty("-verbose", "false"));
   logger.info(strings.get("restart.server.init"));
 }
Ejemplo n.º 29
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOG.info("Try to install MyCollab");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "-1");
    PrintWriter out = response.getWriter();
    String sitename = request.getParameter("sitename");
    String serverAddress = request.getParameter("serverAddress");
    String databaseName = request.getParameter("databaseName");
    String dbUserName = request.getParameter("dbUserName");
    String dbPassword = request.getParameter("dbPassword");
    String databaseServer = request.getParameter("databaseServer");
    String smtpUserName = request.getParameter("smtpUserName");
    String smtpPassword = request.getParameter("smtpPassword");
    String smtpHost = request.getParameter("smtpHost");
    String smtpPort = request.getParameter("smtpPort");
    String tls = request.getParameter("tls");
    String ssl = request.getParameter("ssl");

    String dbUrl =
        String.format(
            "jdbc:mysql://%s/%s?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&rewriteBatchedStatements=true&useCompression=true&useServerPrepStmts=false",
            databaseServer, databaseName);

    try {
      Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
      LOG.error("Can not load mysql driver", e);
      return;
    }

    try (Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword)) {
      LOG.debug("Check database config");
      connection.getMetaData();
    } catch (Exception e) {
      String rootCause = (e.getCause() == null) ? e.getMessage() : e.getCause().getMessage();
      out.write(
          "Cannot establish connection to database. Make sure your inputs are correct. Root cause is "
              + rootCause);
      LOG.error("Can not connect database", e);
      return;
    }

    int mailServerPort;
    try {
      mailServerPort = Integer.parseInt(smtpPort);
    } catch (Exception e) {
      mailServerPort = 0;
    }

    boolean isStartTls = Boolean.parseBoolean(tls);
    boolean isSsl = Boolean.parseBoolean(ssl);
    try {
      InstallUtils.checkSMTPConfig(
          smtpHost, mailServerPort, smtpUserName, smtpPassword, true, isStartTls, isSsl);
    } catch (UserInvalidInputException e) {
      LOG.warn("Cannot authenticate mail server successfully. Make sure your inputs are correct.");
    }

    VelocityContext templateContext = new VelocityContext();
    templateContext.put("sitename", sitename);
    templateContext.put("serveraddress", serverAddress);
    templateContext.put("dbUrl", dbUrl);
    templateContext.put("dbUser", dbUserName);
    templateContext.put("dbPassword", dbPassword);
    templateContext.put("smtpAddress", smtpHost);
    templateContext.put("smtpPort", mailServerPort + "");
    templateContext.put("smtpUserName", smtpUserName);
    templateContext.put("smtpPassword", smtpPassword);
    templateContext.put("smtpTLSEnable", tls);
    templateContext.put("smtpSSLEnable", ssl);

    File confFolder =
        FileUtils.getDesireFile(System.getProperty("user.dir"), "conf", "src/main/conf");
    if (confFolder == null) {
      throw new MyCollabException("The conf folder is not existed");
    }

    try {
      File templateFile = new File(confFolder, "mycollab.properties.template");
      FileReader templateReader = new FileReader(templateFile);

      StringWriter writer = new StringWriter();

      VelocityEngine engine = new VelocityEngine();
      engine.evaluate(templateContext, writer, "log task", templateReader);

      FileOutputStream outStream =
          new FileOutputStream(new File(confFolder, "mycollab.properties"));
      outStream.write(writer.toString().getBytes());
      outStream.flush();
      outStream.close();

      while (waitFlag) {
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          throw new MyCollabException(e);
        }
      }

    } catch (Exception e) {
      LOG.error("Error while set up MyCollab", e);
      out.write(
          "Can not write the settings to the file system. You should check our knowledge base system or contact us at [email protected] to solve this issue.");
      return;
    }
  }
Ejemplo n.º 30
0
  /**
   * Creates REST request.
   *
   * @param cmd Command.
   * @param params Parameters.
   * @return REST request.
   * @throws GridException If creation failed.
   */
  @Nullable
  private GridRestRequest createRequest(
      GridRestCommand cmd, Map<String, Object> params, ServletRequest req) throws GridException {
    GridRestRequest restReq;

    switch (cmd) {
      case CACHE_GET:
      case CACHE_GET_ALL:
      case CACHE_PUT:
      case CACHE_PUT_ALL:
      case CACHE_REMOVE:
      case CACHE_REMOVE_ALL:
      case CACHE_ADD:
      case CACHE_CAS:
      case CACHE_METRICS:
      case CACHE_REPLACE:
      case CACHE_DECREMENT:
      case CACHE_INCREMENT:
      case CACHE_APPEND:
      case CACHE_PREPEND:
        {
          GridRestCacheRequest restReq0 = new GridRestCacheRequest();

          restReq0.cacheName((String) params.get("cacheName"));
          restReq0.key(params.get("key"));
          restReq0.value(params.get("val"));
          restReq0.value2(params.get("val2"));

          Object val1 = params.get("val1");

          if (val1 != null) restReq0.value(val1);

          restReq0.cacheFlags(intValue("cacheFlags", params, 0));
          restReq0.ttl(longValue("exp", params, null));
          restReq0.initial(longValue("init", params, null));
          restReq0.delta(longValue("delta", params, null));

          if (cmd == CACHE_GET_ALL || cmd == CACHE_PUT_ALL || cmd == CACHE_REMOVE_ALL) {
            List<Object> keys = values("k", params);
            List<Object> vals = values("v", params);

            if (keys.size() < vals.size())
              throw new GridException(
                  "Number of keys must be greater or equals to number of values.");

            Map<Object, Object> map = U.newHashMap(keys.size());

            Iterator<Object> keyIt = keys.iterator();
            Iterator<Object> valIt = vals.iterator();

            while (keyIt.hasNext()) map.put(keyIt.next(), valIt.hasNext() ? valIt.next() : null);

            restReq0.values(map);
          }

          restReq = restReq0;

          break;
        }

      case TOPOLOGY:
      case NODE:
        {
          GridRestTopologyRequest restReq0 = new GridRestTopologyRequest();

          restReq0.includeMetrics(Boolean.parseBoolean((String) params.get("mtr")));
          restReq0.includeAttributes(Boolean.parseBoolean((String) params.get("attr")));

          restReq0.nodeIp((String) params.get("ip"));

          restReq0.nodeId(uuidValue("id", params));

          restReq = restReq0;

          break;
        }

      case EXE:
      case RESULT:
      case NOOP:
        {
          GridRestTaskRequest restReq0 = new GridRestTaskRequest();

          restReq0.taskId((String) params.get("id"));
          restReq0.taskName((String) params.get("name"));

          restReq0.params(values("p", params));

          restReq0.async(Boolean.parseBoolean((String) params.get("async")));

          restReq0.timeout(longValue("timeout", params, 0L));

          restReq = restReq0;

          break;
        }

      case LOG:
        {
          GridRestLogRequest restReq0 = new GridRestLogRequest();

          restReq0.path((String) params.get("path"));

          restReq0.from(intValue("from", params, -1));
          restReq0.to(intValue("to", params, -1));

          restReq = restReq0;

          break;
        }

      case VERSION:
        {
          restReq = new GridRestRequest();

          break;
        }

      default:
        throw new GridException("Invalid command: " + cmd);
    }

    restReq.address(new InetSocketAddress(req.getRemoteAddr(), req.getRemotePort()));

    restReq.command(cmd);

    if (params.containsKey("gridgain.login") || params.containsKey("gridgain.password")) {
      GridSecurityCredentials cred =
          new GridSecurityCredentials(
              (String) params.get("gridgain.login"), (String) params.get("gridgain.password"));

      restReq.credentials(cred);
    }

    String clientId = (String) params.get("clientId");

    try {
      if (clientId != null) restReq.clientId(UUID.fromString(clientId));
    } catch (Exception ignored) {
      // Ignore invalid client id. Rest handler will process this logic.
    }

    String destId = (String) params.get("destId");

    try {
      if (destId != null) restReq.destinationId(UUID.fromString(destId));
    } catch (IllegalArgumentException ignored) {
      // Don't fail - try to execute locally.
    }

    String sesTokStr = (String) params.get("sessionToken");

    try {
      if (sesTokStr != null) restReq.sessionToken(U.hexString2ByteArray(sesTokStr));
    } catch (IllegalArgumentException ignored) {
      // Ignore invalid session token.
    }

    return restReq;
  }