private Map<Integer, Set<Integer>> getKillMap(
      List<Assertion> assertions, Map<Mutation, ExecutionResult> mutationResults) {
    Map<Integer, Set<Integer>> killMap = new HashMap<Integer, Set<Integer>>();

    int num = 0;
    for (Assertion assertion : assertions) {
      Set<Integer> killedMutations = new HashSet<Integer>();
      for (Mutation m : mutationResults.keySet()) {

        boolean isKilled = false;
        for (OutputTrace<?> trace : mutationResults.get(m).getTraces()) {
          if (trace.isDetectedBy(assertion)) {
            isKilled = true;
            break;
          }
        }
        if (isKilled) {
          killedMutations.add(m.getId());
          assertion.addKilledMutation(m);
        }
      }
      killMap.put(num, killedMutations);
      num++;
    }

    return killMap;
  }
Example #2
0
 public void haveAttr(String attrName) {
   try {
     selenWebElement.getAttribute(attrName);
     Assertion.test(expect, true, "Test for Attribute availability");
   } catch (Exception e) {
     Assertion.test(expect, false, "Test for Attribute availability");
   }
 }
Example #3
0
 public void readonly() {
   String x = selenWebElement.getAttribute("readonly");
   if (x == null) {
     Assertion.test(expect, false, "readonly");
   } else if (x.equals("true")) {
     Assertion.test(expect, true, "readonly");
   }
 }
Example #4
0
 public void focused() {
   WebElement elm = (WebElement) driver.executeScript("return document.activeElement");
   if (elm != null && elm.equals(selenWebElement.getWebElement())) {
     Assertion.test(expect, true, "Test for elment foucsed");
   } else {
     Assertion.test(expect, false, "Test for elment foucsed");
   }
 }
Example #5
0
 public void disabled() {
   String x = selenWebElement.getAttribute("disabled");
   if (x == null) {
     Assertion.test(expect, false, "disabled");
   } else if (x.equals("true")) {
     Assertion.test(expect, true, "disabled");
   }
 }
Example #6
0
 public void haveAttrVal(String attrName, String attrValue, boolean caseSensitive) {
   String attibValue = selenWebElement.getAttribute(attrName);
   if (!caseSensitive) {
     Assertion.test(
         expect, attrValue.toLowerCase(), attibValue.toLowerCase(), "Have Attribute value");
   } else {
     Assertion.test(expect, attrValue, attibValue, "Have Attribute value");
   }
 }
Example #7
0
  public void haveText(String regex, boolean caseSensitive) {
    String txt = selenWebElement.getText();
    if (!caseSensitive) {
      regex = regex.toLowerCase();
      txt = txt.toLowerCase();
    }

    boolean res = Assertion.test(expect, txt.matches(regex), "Test for Text matching");
    if (!res) {
      Assertion.printDetails(expect, regex, txt);
    }
  }
Example #8
0
 @SuppressWarnings("unchecked")
 private static <T extends Comparable<T>> void expectFail(Assertion assertion, T... args)
     throws Exception {
   try {
     Assertion.run(assertion, args);
   } catch (RuntimeException e) {
     return;
   }
   throw new Exception(
       "Expected "
           + Assertion.format(assertion, (Object[]) args)
           + " to throw a RuntimeException");
 }
  public void testSpecial() {
    LinkedList<Assertion> asserts = new LinkedList();
    asserts.add(Assertion.create("John lives around here."));
    asserts.add(Assertion.create("Mary lives around here."));
    asserts.add(Assertion.create("The plumber lives in the yellow house."));

    PuzzleSolver testS = new PuzzleSolver(asserts);
    LinkedList<String> names = testS.getNames();
    LinkedList<String> occupations = testS.getOccupations();
    LinkedList<String> colors = testS.getColors();

    assertEquals("[John, Mary]", names.toString());
    assertEquals("[plumber, #u]", occupations.toString());
    assertEquals("[yellow, #u]", colors.toString());
  }
Example #10
0
  private void directory_to_directory(
      String source_base_name, String destination_base_name, String directory_name)
      throws IOException, InterruptedException {
    // E.g.
    // source_base_name:        /foo/bar
    // destination_base_name:   /x/y
    // directory_name:     abc
    //
    // - Create /x/y/abc
    // - Copy /foo/bar/abc/* to /x/y/abc/*

    // Get source directory.
    String source_directory_name = Path.concatenate(source_base_name, directory_name);
    File source_directory = File.create(source_directory_name);
    Assertion.check(source_directory.isDirectory());

    // Get destination directory, creating it if
    // necessary.
    String destination_directory_name = Path.concatenate(destination_base_name, directory_name);
    File destination_directory = File.create(destination_directory_name);
    destination_directory.mkdirs();

    // Get files in source directory
    String[] source_file_names = source_directory.list();
    Vector source_files = new Vector();
    for (int i = 0; i < source_file_names.length; i++)
      source_files.addElement(File.create(source_directory_name, source_file_names[i]));

    // Copy
    to_directory(source_files, destination_directory);
  }
Example #11
0
  public boolean imp() {
    boolean res = false;

    DbVariable dbVariable = null;
    String fullFileName = "";
    String errMessage = null;
    DbImportFile dbInFile = new DbImportFile();
    try {
      dbVariable = new DbVariable();

      // Store the file on server filesystem
      fullFileName = dbInFile.storeImportFileBLOB(conn_viss, ifid);

      FileParser fileParser = new FileParser(fullFileName);
      fileParser.Parse(
          FileTypeDefinitionList.matchingDefinitions(
              FileTypeDefinition.VARIABLE, FileTypeDefinition.LIST));

      dbVariable.CreateVariables(fileParser, connection, sampleUnitId, Integer.parseInt(userId));

      errMessage = dbVariable.getErrorMessage();
      Assertion.assertMsg(errMessage == null || errMessage.trim().equals(""), errMessage);

      dbInFile.setStatus(conn_viss, ifid, "IMPORTED");
      // dbInFile.UpdateImportFile(connection,null,null,"Done",Integer.parseInt(ifid),Integer.parseInt(userId));

      // Add a message to the log
      dbInFile.addErrMsg(
          conn_viss,
          ifid,
          "File imported to sampling unit "
              + DbSamplingUnit.getSUName(conn_viss, Integer.toString(sampleUnitId))
              + "Note: Markers is always imported in Create mode.");
      res = true;
    } catch (Exception e) {
      Errors.logError("ImportVariables.imp(...)" + e.getMessage());

      dbInFile.setStatus(conn_viss, ifid, "ERROR");
      // dbInFile.UpdateImportFile(connection,null,null,e.getMessage(),Integer.parseInt(ifid),Integer.parseInt(userId));

      // Add a message to the log
      dbInFile.addErrMsg(conn_viss, ifid, e.getMessage());

      e.printStackTrace(System.err);
      if (errMessage == null) {
        errMessage = e.getMessage();
      }
    } finally {
      try {
        /*
         * Delete files uploaded
         */
        File tmp = new File(fullFileName);
        tmp.delete();
      } catch (Exception ignore) {
      }
    }

    return res;
  }
Example #12
0
  /**
   * Get all possible assertions
   *
   * @param test a {@link org.evosuite.testcase.TestCase} object.
   * @return a int.
   */
  public int getAllAssertions(TestCase test, int statement) {
    int num = 0;

    if (!trace.containsKey(statement)) return 0;

    for (Integer var : trace.get(statement).keySet()) {
      for (Assertion assertion : trace.get(statement).get(var).getAssertions()) {
        assert (assertion.isValid())
            : "Invalid assertion: " + assertion.getCode() + ", " + assertion.value;
        test.getStatement(statement).addAssertion(assertion);
        num++;
      }
    }

    return num;
  }
  /**
   * For the specified expected and actual tables (and excluding and including the specified
   * columns), verify the actual data is as expected.
   *
   * @param expectedTable The expected table to compare the actual table to.
   * @param actualTable The actual table to compare to the expected table.
   * @param excludeColumns The column names to exclude from comparison. See {@link
   *     org.dbunit.dataset.filter.DefaultColumnFilter#excludeColumn(String)} .
   * @param includeColumns The column names to only include in comparison. See {@link
   *     org.dbunit.dataset.filter.DefaultColumnFilter#includeColumn(String)} .
   * @throws DatabaseUnitException
   */
  public void verifyData(
      ITable expectedTable, ITable actualTable, String[] excludeColumns, String[] includeColumns)
      throws DatabaseUnitException {
    final String method = "verifyData: ";
    // Filter out the columns from the expected and actual results
    LOG.debug(method + "Applying filters to expected table");
    ITable expectedFilteredTable =
        applyColumnFilters(expectedTable, excludeColumns, includeColumns);
    LOG.debug(method + "Applying filters to actual table");
    ITable actualFilteredTable = applyColumnFilters(actualTable, excludeColumns, includeColumns);

    LOG.debug(method + "Sorting expected table");
    SortedTable expectedSortedTable = new SortedTable(expectedFilteredTable);
    LOG.debug(method + "Sorted expected table={}", expectedSortedTable);

    LOG.debug(method + "Sorting actual table");
    SortedTable actualSortedTable =
        new SortedTable(actualFilteredTable, expectedFilteredTable.getTableMetaData());
    LOG.debug(method + "Sorted actual table={}", actualSortedTable);

    LOG.debug(method + "Comparing expected table to actual table");
    Column[] additionalColumnInfo = expectedTable.getTableMetaData().getColumns();

    Assertion.assertEquals(expectedSortedTable, actualSortedTable, additionalColumnInfo);
  }
Example #14
0
 public void haveStyle(String styleProperty, String styleValue) {
   String val = selenWebElement.getCssValue(styleProperty);
   Assertion.test(
       expect,
       styleValue.toLowerCase(),
       val.toLowerCase(),
       "Test for css Style property matching");
 }
Example #15
0
 /**
  * Returns the definition of the selected attribute / object class OID.
  *
  * @param schemaEntry The selected schema entry to search on.
  * @param type The type of the research. ("objectClasses" or "attributeTypes")
  * @param oid The OID of the element to search for.
  * @return The byte string definition of the element.
  */
 private static ByteString getSchemaElement(
     final Entry schemaEntry, final String type, final String oid) {
   final Attribute attribute = schemaEntry.getAttribute(type);
   final MatchingRule mrule = CoreSchema.getObjectIdentifierFirstComponentMatchingRule();
   Assertion assertion;
   try {
     assertion = mrule.getAssertion(ByteString.valueOfUtf8(oid));
     for (final ByteString value : attribute) {
       final ByteString nvalue = mrule.normalizeAttributeValue(value);
       if (assertion.matches(nvalue).toBoolean()) {
         return value;
       }
     }
   } catch (DecodeException e) {
     throw new IllegalStateException(e);
   }
   throw new IllegalStateException(ERR_UPGRADE_UNKNOWN_OC_ATT.get(type, oid).toString());
 }
Example #16
0
  /**
   * Get all possible assertions
   *
   * @param test a {@link org.evosuite.testcase.TestCase} object.
   * @return a int.
   */
  public int getAllAssertions(TestCase test) {
    int num = 0;

    for (Integer statement : trace.keySet()) {
      for (Integer var : trace.get(statement).keySet()) {
        for (Assertion assertion : trace.get(statement).get(var).getAssertions()) {
          assert (assertion.isValid())
              : "Invalid assertion: " + assertion.getCode() + ", " + assertion.value;
          if (test.sizeWithAssertions() >= Properties.MAX_LENGTH_TEST_CASE) {
            return num;
          }
          test.getStatement(statement).addAssertion(assertion);
          num++;
        }
      }
    }

    return num;
  }
Example #17
0
  @Override
  public void close() throws SQLException {
    Statement stmt = conn.createStatement();
    try {
      stmt.execute("PRAGMA journal_mode=DELETE");
      {
        ResultSet rs = stmt.executeQuery("PRAGMA journal_mode");
        Assertion.assertAssertionError(rs.next());
        Assertion.assertAssertionError(
            rs.getString("journal_mode").equals("delete"),
            "journal_mode=" + rs.getString("journal_mode"));
        rs.close();
      }
    } finally {
      stmt.close();
    }

    super.close();
  }
Example #18
0
  @Test
  public void testBeamFactoryGaussian() {
    BeamFactory bf = new BeamFactory();

    Beam b = bf.createBeam("gaussian", defaultProperties());
    assertTrue(b instanceof BeamGaussian);
    Assertion.equals(b.getPhotonEnergy(), BEAMENERGYMARKER, "Beam Energy");

    System.out.println("@Test - testBeamFactoryGaussian");
  }
Example #19
0
  /**
   * Check if this trace makes the assertion fail
   *
   * @param assertion a {@link org.evosuite.assertion.Assertion} object.
   * @return a boolean.
   */
  public boolean isDetectedBy(Assertion assertion) {
    assert (assertion.isValid());

    for (Integer statement : trace.keySet()) {
      for (Integer var : trace.get(statement).keySet()) {
        if (trace.get(statement).get(var).isDetectedBy(assertion)) return true;
      }
    }

    return false;
  }
Example #20
0
  /**
   * Get all assertions based on trace differences
   *
   * @param test a {@link org.evosuite.testcase.TestCase} object.
   * @param other a {@link org.evosuite.assertion.OutputTrace} object.
   * @return a int.
   */
  public int getAssertions(TestCase test, OutputTrace<?> other) {
    int num = 0;

    for (Integer statement : trace.keySet()) {
      if (other.trace.containsKey(statement)) {
        logger.debug("Other trace contains " + statement);
        for (Integer var : trace.get(statement).keySet()) {
          logger.debug("Variable " + var);
          for (Assertion assertion :
              trace.get(statement).get(var).getAssertions(other.trace.get(statement).get(var))) {
            assert (assertion.isValid())
                : "Invalid assertion: " + assertion.getCode() + ", " + assertion.value;
            test.getStatement(statement).addAssertion(assertion);
            num++;
          }
        }
      }
    }

    return num;
  }
  @Test
  public void checkElementDB() {
    ElementDatabase edb = ElementDatabase.getInstance();

    Element s = edb.getElement("S");
    Assertion.isNotNull(s, "Could not find sulphur by name");

    Element s16 = edb.getElement(16);
    Assertion.isNotNull(s16, "Could not find sulphur by element number");

    assertSame(s, s16);

    ElementTest et = new ElementTest();
    et.sulphurTests(s);

    Element o = edb.getElement("o");
    Assertion.isNotNull(o, "Could not find oxygen by name");

    Element o8 = edb.getElement(8);
    Assertion.isNotNull(o8, "Could not find oxygen by element number");

    assertSame(o, o8);

    for (int i = 1; i <= 83; i++) {
      Element e = edb.getElement(i);
      Assertion.isNotNull(e, "Could not find element no. " + i);
    }

    Element mg = edb.getElement("Mg");
    Assertion.isNotNull(mg, "Could not find manganese by name");

    et.manganeseTests(mg);
  }
  public void testAssociation() {

    LinkedList<Assertion> asserts = new LinkedList();
    asserts.add(Assertion.create("John lives around here."));
    asserts.add(Assertion.create("Mary lives around here."));
    asserts.add(Assertion.create("Simon lives around here."));
    asserts.add(Assertion.create("Mary lives in the blue house."));
    asserts.add(Assertion.create("The plumber lives in the yellow house."));
    asserts.add(Assertion.create("The carpenter lives around here."));

    PuzzleSolver testS = new PuzzleSolver(asserts);

    PermutationPairs testP = new PermutationPairs(3);

    String[][] possibility = testS.associatePermsWithStrings(testP.nextPair());

    assertEquals("John", possibility[0][0]);
    assertEquals("plumber", possibility[0][1]);
    assertEquals("blue", possibility[0][2]);

    assertEquals("Mary", possibility[1][0]);
    assertEquals("carpenter", possibility[1][1]);
    assertEquals("yellow", possibility[1][2]);

    assertEquals("Simon", possibility[2][0]);
    assertEquals("#u", possibility[2][1]);
    assertEquals("#u", possibility[2][2]);
  }
  public void testOne() {
    LinkedList<Assertion> asserts = new LinkedList();
    asserts.add(Assertion.create("John lives around here."));

    PuzzleSolver testS = new PuzzleSolver(asserts);
    LinkedList<String> names = testS.getNames();
    LinkedList<String> occupations = testS.getOccupations();
    LinkedList<String> colors = testS.getColors();

    assertEquals("[John]", names.toString());
    assertEquals("[#u]", occupations.toString());
    assertEquals("[#u]", colors.toString());
  }
  private Map<String, Object> getUserAttributes(ResponseImpl samlResponse) {

    Map<String, Object> userAttributes = new HashMap<>();

    // Add 'Subject'
    Assertion assertion = samlResponse.getAssertions().get(0);
    userAttributes.put(
        SAMLConstants.SAML2_ASSERTION_SUBJECT, assertion.getSubject().getNameID().getValue());

    // Add other user attributes.
    List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
    if (attributeStatements != null) {
      for (AttributeStatement attributeStatement : attributeStatements) {
        List<Attribute> attributes = attributeStatement.getAttributes();
        for (Attribute attribute : attributes) {
          userAttributes.put(
              attribute.getName(), attribute.getAttributeValues().get(0).getDOM().getTextContent());
        }
      }
    }

    return userAttributes;
  }
Example #25
0
 private void to_directory(Vector sources, File destination_directory)
     throws IOException, InterruptedException {
   Assertion.check(destination_directory.exists());
   for (Enumeration source_scan = sources.elements(); source_scan.hasMoreElements(); ) {
     File source = (File) source_scan.nextElement();
     if (source.isFile()) {
       File destination = File.create(destination_directory.getPath(), source.getName());
       file_to_file(source, destination);
     } else if (_recursive) {
       String source_base = source.getParent();
       if (source_base == null) source_base = ".";
       String destination_base = destination_directory.getCanonicalPath();
       directory_to_directory(source_base, destination_base, source.getName());
     }
   }
 }
 @Override
 protected boolean isSatisfiedByInternal(final Assertion assertion) {
   return (assertion.getChainedAuthentications().size() == 1);
 }
Example #27
0
 public void doAssert(Assertion assertion) throws TimeoutException {
   withCondition(assertion.getCondition()).poll();
 }
  private Assertion buildSAMLAssertion(
      SAMLSSOAuthnReqDTO authReqDTO, DateTime notOnOrAfter, String sessionId)
      throws IdentityException {
    try {
      DateTime currentTime = new DateTime();
      Assertion samlAssertion = new AssertionBuilder().buildObject();
      samlAssertion.setID(SAMLSSOUtil.createID());
      samlAssertion.setVersion(SAMLVersion.VERSION_20);
      samlAssertion.setIssuer(SAMLSSOUtil.getIssuer());
      samlAssertion.setIssueInstant(currentTime);
      Subject subject = new SubjectBuilder().buildObject();

      NameID nameId = new NameIDBuilder().buildObject();
      if (authReqDTO.getUseFullyQualifiedUsernameAsSubject()) {
        nameId.setValue(authReqDTO.getUsername());
        nameId.setFormat(NameIdentifier.EMAIL);
      } else {
        nameId.setValue(MultitenantUtils.getTenantAwareUsername(authReqDTO.getUsername()));
        nameId.setFormat(authReqDTO.getNameIDFormat());
      }

      subject.setNameID(nameId);

      SubjectConfirmation subjectConfirmation = new SubjectConfirmationBuilder().buildObject();
      subjectConfirmation.setMethod(SAMLSSOConstants.SUBJECT_CONFIRM_BEARER);

      SubjectConfirmationData scData = new SubjectConfirmationDataBuilder().buildObject();
      scData.setRecipient(authReqDTO.getAssertionConsumerURL());
      scData.setNotOnOrAfter(notOnOrAfter);
      scData.setInResponseTo(authReqDTO.getId());
      subjectConfirmation.setSubjectConfirmationData(scData);

      subject.getSubjectConfirmations().add(subjectConfirmation);

      samlAssertion.setSubject(subject);

      AuthnStatement authStmt = new AuthnStatementBuilder().buildObject();
      authStmt.setAuthnInstant(new DateTime());

      AuthnContext authContext = new AuthnContextBuilder().buildObject();
      AuthnContextClassRef authCtxClassRef = new AuthnContextClassRefBuilder().buildObject();
      authCtxClassRef.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX);
      authContext.setAuthnContextClassRef(authCtxClassRef);
      authStmt.setAuthnContext(authContext);
      if (authReqDTO.isDoSingleLogout()) {
        authStmt.setSessionIndex(sessionId);
      }
      samlAssertion.getAuthnStatements().add(authStmt);

      /*
       * If <AttributeConsumingServiceIndex> element is in the
       * <AuthnRequest> and
       * according to the spec 2.0 the subject MUST be in the assertion
       */
      Map<String, String> claims = SAMLSSOUtil.getAttributes(authReqDTO);
      if (claims != null) {
        samlAssertion.getAttributeStatements().add(buildAttributeStatement(claims));
      }

      AudienceRestriction audienceRestriction = new AudienceRestrictionBuilder().buildObject();
      Audience issuerAudience = new AudienceBuilder().buildObject();
      issuerAudience.setAudienceURI(authReqDTO.getIssuer());
      audienceRestriction.getAudiences().add(issuerAudience);
      if (authReqDTO.getRequestedAudiences() != null) {
        for (String requestedAudience : authReqDTO.getRequestedAudiences()) {
          Audience audience = new AudienceBuilder().buildObject();
          audience.setAudienceURI(requestedAudience);
          audienceRestriction.getAudiences().add(audience);
        }
      }
      Conditions conditions = new ConditionsBuilder().buildObject();
      conditions.setNotBefore(currentTime);
      conditions.setNotOnOrAfter(notOnOrAfter);
      conditions.getAudienceRestrictions().add(audienceRestriction);
      samlAssertion.setConditions(conditions);

      if (authReqDTO.getDoSignAssertions()) {
        SAMLSSOUtil.setSignature(
            samlAssertion,
            XMLSignature.ALGO_ID_SIGNATURE_RSA,
            new SignKeyDataHolder(authReqDTO.getUsername()));
      }

      return samlAssertion;
    } catch (Exception e) {
      log.error("Error when reading claim values for generating SAML Response", e);
      throw new IdentityException(
          "Error when reading claim values for generating SAML Response", e);
    }
  }
Example #29
0
  public boolean imp() {
    boolean res = false;
    String errMessage = null;

    DbImportFile dbInFile = new DbImportFile();
    DbPhenotype dbp = new DbPhenotype();
    String fullFileName = null;

    try {
      Errors.logInfo("CheckPhenotype started");
      // connection.setAutoCommit(false);
      dbInFile.setStatus(conn_viss, ifid, "0%");

      fullFileName = dbInFile.storeImportFileBLOB(conn_viss, ifid);

      FileHeader header = FileParser.scanFileHeader(fullFileName);
      FileParser fileParser = new FileParser(fullFileName);

      // Set status
      dbInFile.setStatus(conn_viss, ifid, "10%");

      // Ensure file format is list or matrix
      Assertion.assertMsg(
          header.formatTypeName().equalsIgnoreCase(FileTypeDefinition.LIST)
              || header.formatTypeName().equalsIgnoreCase(FileTypeDefinition.MATRIX),
          "Format type name should be list or matrix "
              + "but found found "
              + header.formatTypeName());

      // If file is a list
      if (header.formatTypeName().equalsIgnoreCase(FileTypeDefinition.LIST)) {
        fileParser.Parse(
            FileTypeDefinitionList.matchingDefinitions(
                FileTypeDefinition.PHENOTYPE, FileTypeDefinition.LIST));
        dbInFile.setStatus(conn_viss, ifid, "20%");

        if (updateMethod.equals("CREATE")) {
          dbp.CreatePhenotypesList(
              fileParser, connection, sampleUnitId, Integer.valueOf(userId).intValue());
        } else if (updateMethod.equals("UPDATE")) {
          dbp.UpdatePhenotypesList(
              fileParser, connection, sampleUnitId, Integer.valueOf(userId).intValue());
        } else if (updateMethod.equals("CREATE_OR_UPDATE")) {
          dbp.CreateOrUpdatePhenotypesList(
              fileParser, connection, sampleUnitId, Integer.valueOf(userId).intValue());
        }
      }

      // If file is a matrix
      else if (header.formatTypeName().equalsIgnoreCase(FileTypeDefinition.MATRIX)) {
        fileParser.Parse(
            FileTypeDefinitionList.matchingDefinitions(
                FileTypeDefinition.PHENOTYPE, FileTypeDefinition.MATRIX));
        dbInFile.setStatus(conn_viss, ifid, "20%");

        if (updateMethod.equals("CREATE")) {
          dbp.CreatePhenotypesMatrix(
              fileParser, connection, sampleUnitId, Integer.valueOf(userId).intValue());
        } else if (updateMethod.equals("UPDATE")) {
          dbp.UpdatePhenotypesMatrix(
              fileParser, connection, sampleUnitId, Integer.valueOf(userId).intValue());
        } else if (updateMethod.equals("CREATE_OR_UPDATE")) {
          dbp.CreateOrUpdatePhenotypesMatrix(
              fileParser, connection, sampleUnitId, Integer.valueOf(userId).intValue());
        }
      }
      errMessage = dbp.getErrorMessage();

      Assertion.assertMsg(errMessage == null || errMessage.trim().equals(""), errMessage);

      dbInFile.setStatus(conn_viss, ifid, "IMPORTED");

      // Add a message to the log
      dbInFile.addErrMsg(
          conn_viss,
          ifid,
          "File imported for sampling unit "
              + DbSamplingUnit.getSUName(conn_viss, Integer.toString(sampleUnitId)));
      res = true;

      Errors.logInfo("Check Phenotype ended");
    } catch (Exception e) {
      // Flag for error and set the errMessage if it has not been set
      // isOk = false;
      dbInFile.setStatus(conn_viss, ifid, "ERROR");

      // Add a message to the log
      dbInFile.addErrMsg(conn_viss, ifid, e.getMessage());

      e.printStackTrace(System.err);
      if (errMessage == null) {
        errMessage = e.getMessage();
      }
    }

    return res;
  }
Example #30
0
  SqliteDirTreeDb(String filename) throws SQLException, ClassNotFoundException {
    Class.forName("org.sqlite.JDBC");

    File fileobj = new File(filename);
    boolean fileExists = fileobj.exists();

    SQLiteConfig config = new SQLiteConfig();
    config.setBusyTimeout(String.valueOf(60 * 1000));
    conn = DriverManager.getConnection("jdbc:sqlite:" + filename, config.toProperties());
    conn.setAutoCommit(true);
    Statement stmt = conn.createStatement();
    try {
      stmt.execute("PRAGMA synchronous=OFF");
      {
        ResultSet rs = stmt.executeQuery("PRAGMA synchronous");
        Assertion.assertAssertionError(rs.next());
        Assertion.assertAssertionError(
            rs.getInt("synchronous") == 0, "synchronous=" + rs.getInt("synchronous"));
        rs.close();
      }
      stmt.execute("PRAGMA journal_mode=PERSIST");
      {
        ResultSet rs = stmt.executeQuery("PRAGMA journal_mode");
        Assertion.assertAssertionError(rs.next());
        Assertion.assertAssertionError(
            rs.getString("journal_mode").equals("persist"),
            "journal_mode=" + rs.getString("journal_mode"));
        rs.close();
      }

      if (!fileExists) {
        stmt.executeUpdate(
            "CREATE TABLE IF NOT EXISTS directory (pathid INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "parentid INTEGER NOT NULL, rootid INTEGER, datelastmodified TEXT NOT NULL, "
                + "size INTEGER NOT NULL, compressedsize INTEGER NOT NULL, csum INTEGER, "
                + "path TEXT UNIQUE NOT NULL, type INTEGER NOT NULL, status INTEGER NOT NULL, "
                + "duplicate INTEGER NOT NULL, dedupablesize INTEGER NOT NULL, "
                + "CONSTRAINT pathid_size_csum UNIQUE (pathid, size, csum))");
        stmt.executeUpdate("CREATE INDEX IF NOT EXISTS directory_parentid ON directory (parentid)");
        stmt.executeUpdate("CREATE INDEX IF NOT EXISTS directory_rootid ON directory (rootid)");
        stmt.executeUpdate(
            "CREATE INDEX IF NOT EXISTS directory_datelastmodified ON directory (datelastmodified)");
        stmt.executeUpdate("CREATE INDEX IF NOT EXISTS directory_size ON directory (size)");
        stmt.executeUpdate(
            "CREATE INDEX IF NOT EXISTS directory_compressedsize ON directory (compressedsize)");
        stmt.executeUpdate("CREATE INDEX IF NOT EXISTS directory_csum ON directory (csum)");
        stmt.executeUpdate(
            "CREATE INDEX IF NOT EXISTS directory_size_csum ON directory (size, csum)");
        stmt.executeUpdate("CREATE INDEX IF NOT EXISTS directory_type ON directory (type)");
        stmt.executeUpdate("CREATE INDEX IF NOT EXISTS directory_status ON directory (status)");
        stmt.executeUpdate(
            "CREATE INDEX IF NOT EXISTS directory_duplicate ON directory (duplicate)");
        stmt.executeUpdate(
            "CREATE INDEX IF NOT EXISTS directory_dedupablesize ON directory (dedupablesize)");

        stmt.executeUpdate(
            "INSERT OR IGNORE INTO directory (path, parentid, datelastmodified, size, "
                + "compressedsize, type, status, duplicate, dedupablesize) "
                + "VALUES ('C:\\', 0, '2000-01-01 00:00:00', 0, 0, 0, 1, 0, 0)");

        stmt.executeUpdate(
            "CREATE TABLE IF NOT EXISTS upperlower (upper INTEGER NOT NULL, "
                + "lower INTEGER NOT NULL, distance INTEGER NOT NULL, PRIMARY KEY (upper, lower))");
        stmt.executeUpdate(
            "CREATE INDEX IF NOT EXISTS upperlower_distance ON upperlower (distance)");

        stmt.executeUpdate(
            "CREATE TABLE IF NOT EXISTS equality ("
                + "pathid1 INTEGER NOT NULL, pathid2 INTEGER NOT NULL, "
                + "size INTEGER NOT NULL, csum INTEGER NOT NULL, "
                + "datelasttested TEXT NOT NULL, PRIMARY KEY (pathid1, pathid2))");
      }
      stmt.executeUpdate(
          "UPDATE directory SET rootid=pathid WHERE rootid IS NULL AND pathid IS NOT NULL");
    } finally {
      stmt.close();
    }
  }