/**
  * Is MIME type supported
  *
  * @param mime MIME-Type
  * @return Boolean
  */
 public static boolean isMimeTypeSupported(String mime) {
   if (mime.equals("*")) { // Changed by Deutsche Telekom AG    	
     return true;
   } else {
     return mimeTable.containsValue(mime);
   }
 }
  public void add(LogicalClient client) {
    if (!table.containsValue(client)) {
      table.put(client.getPort(), client);

      for (LogicalClientsContainerListener listener : listeners) {
        listener.clientAdded(client.getPort());
      }
    }
  }
 /**
  * get the Enum Value of a stocky code.
  *
  * @param code
  * @return
  */
 public SexeValues convertToValue(String code) {
   SexeValues result = SexeValues.inconnu;
   if (sexeCodification.containsValue(code)) {
     for (SexeValues sVal : sexeCodification.keySet()) {
       if (sexeCodification.get(sVal).equals(code)) {
         result = sVal;
       }
     }
   }
   return result;
 }
Example #4
0
  /**
   * Returns the SimpleType associated with the given name, or null if no such SimpleType exists.
   *
   * @return the SimpleType associated with the given name, or null if no such SimpleType exists.
   */
  public SimpleType getSimpleType(String name) {

    // -- Null?
    if (name == null) {
      String err = NULL_ARGUMENT + "getSimpleType: ";
      err += "'name' cannot be null.";
      throw new IllegalArgumentException(err);
    }

    // -- Namespace prefix?
    String canonicalName = name;
    String nsPrefix = "";
    String ns = null;
    int colon = name.indexOf(':');
    if (colon >= 0) {
      canonicalName = name.substring(colon + 1);
      nsPrefix = name.substring(0, colon);
      ns = (String) namespaces.get(nsPrefix);
      if (ns == null) {
        String err = "getSimpleType: ";
        err += "Namespace prefix not recognised '" + name + "'";
        throw new IllegalArgumentException(err);
      }
    }

    // -- Get SimpleType object
    SimpleType result = null;
    if (ns == null) {
      // -- first try built-in types
      result = simpleTypesFactory.getBuiltInType(name);
      // if we have a built-in type not declared in the good namespace -> Exception
      if ((result != null) && (namespaces.containsValue(DEFAULT_SCHEMA_NS))) {
        String err =
            "getSimpleType: the simple type '"
                + name
                + "' has not been declared in XML Schema namespace.";
        throw new IllegalArgumentException(err);
      }

      // -- otherwise check user-defined types
      if (result == null) result = (SimpleType) simpleTypes.get(name);
    } else if (ns.equals(schemaNS)) result = simpleTypesFactory.getBuiltInType(canonicalName);
    else if (ns.equals(targetNS)) result = (SimpleType) simpleTypes.get(canonicalName);
    else {
      Schema schema = getImportedSchema(ns);
      if (schema != null) result = schema.getSimpleType(canonicalName);
    }

    // -- Result could be a deferredSimpleType => getType will resolve it
    if (result != null) result = (SimpleType) result.getType();

    return result;
  } // -- getSimpleType
  private int getCategoryide(String type) {

    Categories.containsValue(type);

    for (Iterator iterator = Categories.entrySet().iterator(); iterator.hasNext(); ) {
      Entry<Integer, String> cat = (Entry<Integer, String>) iterator.next();
      if (cat.getValue().equals(type)) {
        return cat.getKey();
      }
    }

    return -1;
  }
 /* (non-Javadoc)
  * @see SketchMaster.system.Recogniziers.RecognizierSystem#addNewCategory(java.lang.String)
  */
 @Override
 public void addNewCategory(String Name) {
   this.CurrentCategory = Name;
   // check if exist
   if (Categories.containsValue(Name)) return;
   else {
     // it does not exist
     // get size
     int temp = Categories.size();
     Categories.put(temp, Name);
   }
   trained = false;
 }
Example #7
0
  public Hashtable<String, Object> respond(Hashtable<String, Object> req) {
    Hashtable<String, String> messageHeader = new Hashtable<String, String>();

    if (req.containsValue("GET")) {
      resp.put("status-line", ResponseStatusLine.get("200", req.get("HTTP-Version")));
    } else if (req.get("Method").equals("OPTIONS")) {
      resp.put("status-line", ResponseStatusLine.get("200", req.get("HTTP-Version")));
      messageHeader.put("Allow", "HEAD,POST,OPTIONS,PUT,GET");
    } else {
      resp.put("status-line", ResponseStatusLine.get("404", req.get("HTTP-Version")));
    }
    messageHeader.put("Content-Type", "text/html");
    messageHeader.put("Connection", "close");
    resp.put("message-header", messageHeader);
    resp.put("message-body", body.getBytes(Charset.forName("utf-8")));
    return resp;
  }
 /**
  * Process Query request
  *
  * @param request
  * @return
  */
 public Response QueryRequestProcess(Request request) {
   ArrayList<String> responseMessage = new ArrayList<String>();
   String msg = request.getMessage().get(0).trim();
   int key = PeerNode.getAscii(msg) % this.getMaxId();
   Hashtable<Integer, String> hashtbl = this.getHashtable();
   if (hashtbl.containsValue(msg)) {
     return new Response(Settings.Version, "QUERY", "0", "200", "OK", responseMessage);
   } else if (getInt(this.getID()) <= key && key < getInt(this.getNextPeerID())
       || getInt(this.getID()) <= key && getInt(this.getID()) > getInt(this.getNextPeerID())
       || getInt(this.getNextPeerID()) > key
           && getInt(this.getID()) > getInt(this.getNextPeerID())) {
     return new Response(Settings.Version, "ADD", "0", "201", "NotPresent", responseMessage);
   } else {
     responseMessage.add(msg);
     return new Response(Settings.Version, "ADD", "0", "400", "NotResponsible", responseMessage);
   }
 }
  /* (non-Javadoc)
   * @see SketchMaster.system.Recogniziers.RecognizierSystem#deleteCategory(java.lang.String)
   */
  @Override
  public void deleteCategory(String Name) {

    //		 check if exist
    if (Categories.containsValue(Name)) {
      Set<Entry<Integer, String>> collection = Categories.entrySet();
      for (Iterator iter = collection.iterator(); iter.hasNext(); ) {
        Entry element = (Entry) iter.next();
        if (element.getValue().equals(Name)) {
          iter.remove();
          break;
        }
      }
      // now remove all entries of this category from the train set.
      trainSet.removeType(Name);
      if (Interactive) TrainSetStrokes.removeType(Name);

      return;
    }
    trained = false;
  }
  private String setValueForClass(String value, JTextComponent component) {

    Iterator iter = getAllJavaClasses(component);
    ArrayList<String> li = new ArrayList<String>();
    Hashtable ht = new Hashtable();

    String entry = "";

    if (iter != null) {
      while (iter.hasNext()) {
        entry = (String) iter.next();

        if (entry != null) ht.put(entry, getPkgPart(entry));
      }
    }

    if (ht.containsKey(value)) value = getClassPart(value);

    if (ht.containsValue(getPkgPart(value))) hasPkg = true;

    return value;
  }
 /**
  * Process Add query request
  *
  * @param request
  * @return
  */
 public Response AddQueryRequestProcess(Request request) {
   ArrayList<String> responseMessage = new ArrayList<String>();
   String msg = request.getMessage().get(0).trim();
   int key =
       PeerNode.getAscii(msg)
           % this
               .getMaxId(); // get the Ascii value and convert it to the range of ids by modula
                            // maxId
   Hashtable<Integer, String> hashtbl = this.getHashtable();
   if (hashtbl.containsValue(msg)) {
     return new Response(Settings.Version, "ADD", "0", "202", "duplicate", responseMessage);
   } else if (getInt(this.getID()) <= key && key < getInt(this.getNextPeerID())
       || getInt(this.getID()) <= key && getInt(this.getID()) > getInt(this.getNextPeerID())
       || getInt(this.getNextPeerID()) > key
           && getInt(this.getID()) > getInt(this.getNextPeerID())) {
     hashtbl.put(key, msg);
     return new Response(Settings.Version, "ADD", "0", "200", "ok", responseMessage);
   } else {
     responseMessage.add(msg);
     nextClient(new Request("ADD", Settings.Version, 0, this.getID(), responseMessage).toString());
     return new Response(Settings.Version, "ADD", "0", "400", "NotResponsible", responseMessage);
   }
 }
 public boolean containsValue(Object value) {
   return m_delegatee.containsValue(value);
 }
  /** @see Runnable#run() */
  public void run() {

    if ((mzWeight == 0) && (rtWeight == 0)) {
      setStatus(TaskStatus.ERROR);
      errorMessage = "Cannot run alignment, all the weight parameters are zero";
      return;
    }

    setStatus(TaskStatus.PROCESSING);
    logger.info("Running join aligner");

    // Remember how many rows we need to process. Each row will be processed
    // twice, first for score calculation, second for actual alignment.
    for (int i = 0; i < peakLists.length; i++) {
      totalRows += peakLists[i].getNumberOfRows() * 2;
    }

    // Collect all data files
    Vector<RawDataFile> allDataFiles = new Vector<RawDataFile>();
    for (PeakList peakList : peakLists) {

      for (RawDataFile dataFile : peakList.getRawDataFiles()) {

        // Each data file can only have one column in aligned peak list
        if (allDataFiles.contains(dataFile)) {
          setStatus(TaskStatus.ERROR);
          errorMessage =
              "Cannot run alignment, because file "
                  + dataFile
                  + " is present in multiple peak lists";
          return;
        }

        allDataFiles.add(dataFile);
      }
    }

    // Create a new aligned peak list
    alignedPeakList = new SimplePeakList(peakListName, allDataFiles.toArray(new RawDataFile[0]));

    // Iterate source peak lists
    for (PeakList peakList : peakLists) {

      // Create a sorted set of scores matching
      TreeSet<RowVsRowScore> scoreSet = new TreeSet<RowVsRowScore>();

      PeakListRow allRows[] = peakList.getRows();

      // Calculate scores for all possible alignments of this row
      for (PeakListRow row : allRows) {

        if (isCanceled()) return;

        // Calculate limits for a row with which the row can be aligned
        Range mzRange = mzTolerance.getToleranceRange(row.getAverageMZ());
        Range rtRange = rtTolerance.getToleranceRange(row.getAverageRT());

        // Get all rows of the aligned peaklist within parameter limits
        PeakListRow candidateRows[] = alignedPeakList.getRowsInsideScanAndMZRange(rtRange, mzRange);

        // Calculate scores and store them
        for (PeakListRow candidate : candidateRows) {

          if (sameChargeRequired) {
            if (!PeakUtils.compareChargeState(row, candidate)) continue;
          }

          if (sameIDRequired) {
            if (!PeakUtils.compareIdentities(row, candidate)) continue;
          }

          if (compareIsotopePattern) {
            IsotopePattern ip1 = row.getBestIsotopePattern();
            IsotopePattern ip2 = candidate.getBestIsotopePattern();

            if ((ip1 != null) && (ip2 != null)) {
              ParameterSet isotopeParams =
                  parameters
                      .getParameter(JoinAlignerParameters.compareIsotopePattern)
                      .getEmbeddedParameters();

              if (!IsotopePatternScoreCalculator.checkMatch(ip1, ip2, isotopeParams)) {
                continue;
              }
            }
          }

          RowVsRowScore score =
              new RowVsRowScore(
                  row, candidate, mzRange.getSize() / 2, mzWeight, rtRange.getSize() / 2, rtWeight);

          scoreSet.add(score);
        }

        processedRows++;
      }

      // Create a table of mappings for best scores
      Hashtable<PeakListRow, PeakListRow> alignmentMapping =
          new Hashtable<PeakListRow, PeakListRow>();

      // Iterate scores by descending order
      Iterator<RowVsRowScore> scoreIterator = scoreSet.iterator();
      while (scoreIterator.hasNext()) {

        RowVsRowScore score = scoreIterator.next();

        // Check if the row is already mapped
        if (alignmentMapping.containsKey(score.getPeakListRow())) continue;

        // Check if the aligned row is already filled
        if (alignmentMapping.containsValue(score.getAlignedRow())) continue;

        alignmentMapping.put(score.getPeakListRow(), score.getAlignedRow());
      }

      // Align all rows using mapping
      for (PeakListRow row : allRows) {

        PeakListRow targetRow = alignmentMapping.get(row);

        // If we have no mapping for this row, add a new one
        if (targetRow == null) {
          targetRow = new SimplePeakListRow(newRowID);
          newRowID++;
          alignedPeakList.addRow(targetRow);
        }

        // Add all peaks from the original row to the aligned row
        for (RawDataFile file : row.getRawDataFiles()) {
          targetRow.addPeak(file, row.getPeak(file));
        }

        // Add all non-existing identities from the original row to the
        // aligned row
        PeakUtils.copyPeakListRowProperties(row, targetRow);

        processedRows++;
      }
    } // Next peak list

    // Add new aligned peak list to the project
    MZmineProject currentProject = MZmineCore.getCurrentProject();
    currentProject.addPeakList(alignedPeakList);

    // Add task description to peakList
    alignedPeakList.addDescriptionOfAppliedTask(
        new SimplePeakListAppliedMethod("Join aligner", parameters));

    logger.info("Finished join aligner");
    setStatus(TaskStatus.FINISHED);
  }
  public static void main(String args[]) {
    // Use correct Semantria API credentias here
    String key = "f4a9add2-627c-4cd9-bf3d-08dba99cc048";
    String secret = "fb17fecf-6919-4c98-994d-a0cee0730c00";

    if (args != null && args.length == 2) {
      key = args[0];
      secret = args[1];
    }

    Hashtable<String, TaskStatus> docsTracker = new Hashtable<String, TaskStatus>();
    List<String> initialTexts = new ArrayList<String>();

    System.out.println("Semantria service demo.");

    // File file = new File(
    // DetailedModeTestApp.class.getProtectionDomain().getCodeSource().getLocation().toString().replace("/target/classes", "/src/main/java/" + DiscoveryModeTestApp.class.getPackage().getName().replace(".","/")).replace("file:/", "")+ "/source.txt");
    File file = new File(System.getProperty("user.dir") + "/source.txt");

    if (!file.exists()) {
      System.out.println("Source file isn't available.");
      return;
    }

    // Reads dataset from the source file
    try {
      FileInputStream fstream = new FileInputStream(file);
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

      while ((strLine = br.readLine()) != null) {
        if (StringUtils.isEmpty(strLine) || strLine.length() < 3) {
          continue;
        }

        initialTexts.add(strLine);
      }
      in.close();
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
    }

    // Creates JSON serializer instance
    // ISerializer jsonSerializer = new JsonSerializer();
    // Initializes new session with the serializer object and the keys.
    ISerializer serializer = new JsonSerializer();
    Session session = Session.createSession(key, secret, serializer, true);
    session.setCallbackHandler(new CallbackHandler());

    // Obtaining subscription object to get user limits applicable on server side
    Subscription subscription = session.getSubscription();

    List<Document> outgoingBatch =
        new ArrayList<Document>(subscription.getBasicSettings().getBatchLimit());

    for (Iterator<String> iterator = initialTexts.iterator(); iterator.hasNext(); ) {
      String uid = UUID.randomUUID().toString();
      Document doc = new Document(uid, iterator.next());
      // System.out.println("doc content = \n\n\n\n\n"+doc.toString()+"\n\n\n\n");
      outgoingBatch.add(doc);
      docsTracker.put(uid, TaskStatus.QUEUED);

      if (outgoingBatch.size() == subscription.getBasicSettings().getBatchLimit()) {
        if (session.queueBatch(outgoingBatch) == 202) {
          System.out.println("\"" + outgoingBatch.size() + "\" documents queued successfully.");
          outgoingBatch.clear();
        }
      }
    }

    if (outgoingBatch.size() > 0) {
      if (session.queueBatch(outgoingBatch) == 202) {
        System.out.println("\"" + outgoingBatch.size() + "\" documents queued successfully.");
        outgoingBatch.clear();
      }
    }

    // System.out.println();
    try {
      List<DocAnalyticData> processed = new ArrayList<DocAnalyticData>();

      while (docsTracker.containsValue(TaskStatus.QUEUED)) {
        // As Semantria isn't real-time solution you need to wait some time before getting of the
        // processed results
        // In real application here can be implemented two separate jobs, one for queuing of source
        // data another one for retrieving
        // Wait half of second while Semantria process queued document
        Thread.currentThread().sleep(TIMEOUT_BEFORE_GETTING_RESPONSE);

        // Requests processed results from Semantria service
        List<DocAnalyticData> temp = session.getProcessedDocuments();
        for (Iterator<DocAnalyticData> i = temp.iterator(); i.hasNext(); ) {
          DocAnalyticData item = i.next();

          if (docsTracker.containsKey(item.getId())) {
            processed.add(item);
            docsTracker.put(item.getId(), TaskStatus.PROCESSED);
          }
        }

        System.out.println("Retrieving your processed results...");
      }

      StringBuffer sbr = new StringBuffer();
      sbr.append(
          "\ndoc_id,doc_sentiment_score,doc_sentiment_polarity,cat_topic,cat_strength_score,theme_title,theme_sentiment_score,theme_sentiment_polarity,entity_title,entity_sentiment_score,entity_sentiment_polarity");
      // Output results
      for (DocAnalyticData doc : processed) {
        // (!"".isEmpty() && null!="") ? return "" : "";

        // String str="";
        // System.out.println((str.isEmpty() && str.length()>0) ? str : "null");

        sbr.append(
            "\n"
                + (checkNull(doc.getId())
                    + ","
                    + checkNull(Float.toString(doc.getSentimentScore()))
                    + ","
                    + checkNull(doc.getSentimentPolarity())
                    + ","));

        System.out.println(
            "Document:\n\tid: "
                + doc.getId()
                + "\n\tsentiment score: "
                + Float.toString(doc.getSentimentScore())
                + "\n\tsentiment polarity: "
                + doc.getSentimentPolarity());
        System.out.println();
        if (doc.getAutoCategories() != null) {
          System.out.println("\tdocument categories:");
          for (DocCategory category : doc.getAutoCategories()) {
            System.out.println(
                "\t\ttopic: "
                    + category.getTitle()
                    + " \n\t\tStrength score: "
                    + Float.toString(category.getStrengthScore()));
            System.out.println();
            sbr.append(
                checkNull(category.getTitle())
                    + ","
                    + checkNull(Float.toString(category.getStrengthScore()))
                    + ",");
          }
        } else {
          sbr.append("null," + "null,");
        }
        if (doc.getThemes() != null) {
          System.out.println("\tdocument themes:");
          for (DocTheme theme : doc.getThemes()) {
            System.out.println(
                "\t\ttitle: "
                    + theme.getTitle()
                    + " \n\t\tsentiment: "
                    + Float.toString(theme.getSentimentScore())
                    + "\n\t\tsentiment polarity: "
                    + theme.getSentimentPolarity());
            System.out.println();
            sbr.append(
                checkNull(theme.getTitle())
                    + ","
                    + checkNull(Float.toString(theme.getStrengthScore()))
                    + ","
                    + checkNull(theme.getSentimentPolarity())
                    + ",");
          }
        } else {
          sbr.append("null," + "null," + "null,");
        }
        if (doc.getEntities() != null) {
          System.out.println("\tentities:");
          for (DocEntity entity : doc.getEntities()) {
            System.out.println(
                "\t\ttitle: "
                    + entity.getTitle()
                    + "\n\t\tsentiment: "
                    + Float.toString(entity.getSentimentScore())
                    + "\n\t\tsentiment polarity: "
                    + entity.getSentimentPolarity());
            System.out.println();
            sbr.append(
                checkNull(entity.getTitle())
                    + ","
                    + checkNull(Float.toString(entity.getSentimentScore()))
                    + ","
                    + checkNull(entity.getSentimentPolarity()));
          }
        } else {
          sbr.append("null," + "null," + "null");
        }
      }
      System.out.println("processed results : \n" + sbr.toString());
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }