Example #1
1
  /**
   * Create job arguments that are used by CrowdClient to build a POST request for a new job on
   * Crowdflower
   */
  void createArgumentMaps() {
    argumentMap = new LinkedMultiValueMap<String, String>();
    includedCountries = new Vector<String>();
    excludedCountries = new Vector<String>();

    Iterator<Map.Entry<String, JsonNode>> jsonRootIt = template.fields();

    for (Map.Entry<String, JsonNode> elt; jsonRootIt.hasNext(); ) {
      elt = jsonRootIt.next();

      JsonNode currentNode = elt.getValue();
      String currentKey = elt.getKey();

      if (currentNode.isContainerNode()) {
        // special processing for these arrays:
        if (currentKey.equals(includedCountriesKey) || currentKey.equals(excludedCountriesKey)) {
          Iterator<JsonNode> jsonSubNodeIt = currentNode.elements();
          for (JsonNode subElt; jsonSubNodeIt.hasNext(); ) {
            subElt = jsonSubNodeIt.next();
            (currentKey.equals(includedCountriesKey) ? includedCountries : excludedCountries)
                .addElement(subElt.path(countryCodeKey).asText());
          }
        }
      } else if (!currentNode.isNull() && argumentFilterSet.contains(currentKey)) {
        argumentMap.add(jobKey + "[" + currentKey + "]", currentNode.asText());
      }
      if (currentKey == idKey) {
        this.id = currentNode.asText();
      }
    }
  }
  /*
   * Returns list of sensors currently loaded in the system
   * */
  public static String getListOfSensors() {
    StringBuilder s = new StringBuilder();
    Iterator iter = Mappings.getAllVSensorConfigs();

    sensors.clear();
    coordinates.clear();

    while (iter.hasNext()) {
      VSensorConfig sensorConfig = (VSensorConfig) iter.next();
      Double longitude = sensorConfig.getLongitude();
      Double latitude = sensorConfig.getLatitude();
      Double altitude = sensorConfig.getAltitude();
      String sensor = sensorConfig.getName();

      if ((latitude != null) && (longitude != null) && (altitude != null)) {
        Point point = new Point(latitude, longitude, altitude);
        coordinates.add(point);
        sensors.add(sensor);
        s.append(sensor)
            .append(" => ")
            .append(longitude)
            .append(" : ")
            .append(latitude)
            .append("\n");
      }
    }
    return s.toString();
  }
  /**
   * Returns submap of x and y values according to the given start and end
   *
   * @param start start x value
   * @param stop stop x value
   * @return a submap of x and y values
   */
  public synchronized SortedMap<Double, Double> getRange(
      double start, double stop, int beforeAfterPoints) {
    // we need to add one point before the start and one point after the end (if
    // there are any)
    // to ensure that line doesn't end before the end of the screen

    // this would be simply: start = mXY.lowerKey(start) but NavigableMap is
    // available since API 9
    SortedMap<Double, Double> headMap = mXY.headMap(start);
    if (!headMap.isEmpty()) {
      start = headMap.lastKey();
    }

    // this would be simply: end = mXY.higherKey(end) but NavigableMap is
    // available since API 9
    // so we have to do this hack in order to support older versions
    SortedMap<Double, Double> tailMap = mXY.tailMap(stop);
    if (!tailMap.isEmpty()) {
      Iterator<Double> tailIterator = tailMap.keySet().iterator();
      Double next = tailIterator.next();
      if (tailIterator.hasNext()) {
        stop = tailIterator.next();
      } else {
        stop += next;
      }
    }
    return new TreeMap<Double, Double>(mXY.subMap(start, stop));
  }
  private void listAll() {
    ViewGroup root = mList;
    root.removeAllViews();

    // 列出所有已经安装的插件
    Collection<PluginDescriptor> plugins = PluginLoader.getPlugins();
    Iterator<PluginDescriptor> itr = plugins.iterator();
    while (itr.hasNext()) {
      final PluginDescriptor pluginDescriptor = itr.next();
      Button button = new Button(this);
      button.setPadding(10, 10, 10, 10);
      button.setText("插件id:" + pluginDescriptor.getPackageName() + ",点击查看");
      button.setOnClickListener(
          new View.OnClickListener() {

            @Override
            public void onClick(View v) {
              Intent intent = new Intent(PluginListActivity.this, PluginDetailActivity.class);
              intent.putExtra("plugin_id", pluginDescriptor.getPackageName());
              startActivity(intent);
            }
          });

      LayoutParams layoutParam =
          new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      layoutParam.topMargin = 10;
      layoutParam.bottomMargin = 10;
      layoutParam.gravity = Gravity.LEFT;
      root.addView(button, layoutParam);
    }
  }
 /** Initialize the (java.bean) PropertyDescriptors for the properties */
 private void initPropertyDescriptor() {
   for (Iterator<String> it = orderedExportedProperties.iterator(); it.hasNext(); ) {
     String propertyName = it.next();
     try {
       // we're using this specialized constructor since we want to allow properties that are
       // read-only (such as creationDate).
       // with the simpler constructor (String,Class) that would result in an Exception.
       // also note that we're using "is"+propertyName rather than get - that's the way the
       // PropertyDescriptor itself
       // does it in the constructor (String,Class) - resulting in a lookup of an is Method first
       // and then the get Method
       // this seems to be the correct standard here.
       PropertyDescriptor pd =
           new PropertyDescriptor(
               propertyName, LoggingObject.class, "is" + capitalize(propertyName), null);
       orderedExportedPropertyDescriptors.add(pd);
     } catch (IntrospectionException e) {
       log_.error(
           "initPropertyDescriptor: Could not retrieve property "
               + propertyName
               + " from LoggingObject, configuration error?",
           e);
     }
   }
 }
  /**
   * Loads the contents of the given locations into memory.
   *
   * @param locations locations to add (of type {@link java.io.File &lt;File&gt;}).
   * @throws IOException if an I/O error occurred.
   */
  public synchronized void loadAll(List locations) throws IOException {
    if (locations == null) {
      return;
    }

    Set data = new HashSet(1000);

    for (Iterator i = locations.iterator(); i.hasNext(); ) {
      File location = (File) i.next();
      ClassRepositoryEntry entry = loadEntry(location);

      if (entry != null) {
        data.addAll(entry.getData());

        if (Loggers.IO.isDebugEnabled()) {
          Loggers.IO.debug("ClassRepository: Loaded " + data.size() + " classes from " + location);
        }
      }
    }

    if (!data.isEmpty()) {
      data.addAll(Arrays.asList(_content));
      _content = (String[]) data.toArray(EMPTY_STRING_ARRAY);
      Arrays.sort(_content);
    }
  }
Example #7
1
  /**
   * Retrieves the access token used for interacting with Twitter.
   *
   * @return
   */
  public static AccessToken getAccessToken() {
    // Try to grab the token from the cache.
    StoredAccessToken storedToken = (StoredAccessToken) cache.get(ACCESS_TOKEN_KEY);

    if (storedToken != null) {
      return storedToken.getAccessToken();
    }

    // Now try to grab it from the datastore
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Extent<StoredAccessToken> extent = pm.getExtent(StoredAccessToken.class, false);

    try {
      Iterator<StoredAccessToken> itr = extent.iterator();
      storedToken = itr.next();

      // If the token was found, cache it and return.
      if (storedToken != null) {
        cache.put(ACCESS_TOKEN_KEY, storedToken);
        return storedToken.getAccessToken();
      }
    } finally {
      extent.closeAll();
      pm.close();
    }

    return null;
  }
Example #8
1
  /**
   * 是否财付通签名,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
   *
   * @return boolean
   */
  public boolean isTenpaySign() {
    StringBuffer sb = new StringBuffer();
    Set es = this.parameters.entrySet();
    Iterator it = es.iterator();
    while (it.hasNext()) {
      Map.Entry entry = (Map.Entry) it.next();
      String k = (String) entry.getKey();
      String v = (String) entry.getValue();
      if (!"sign".equals(k) && null != v && !"".equals(v)) {
        sb.append(k + "=" + v + "&");
      }
    }

    sb.append("key=" + this.getKey());

    // 算出摘要
    String enc = "UTF-8";
    String sign = MD5Util.MD5Encode(sb.toString(), enc).toLowerCase();

    String tenpaySign = this.getParameter("sign").toLowerCase();

    // debug信息
    this.setDebugInfo(sb.toString() + " => sign:" + sign + " tenpaySign:" + tenpaySign);

    return tenpaySign.equals(sign);
  }
  private static void filterBadAddresses(
      final Address address, final List<MapquestResult.Result> filtered) {
    boolean wasZipMatch = false;
    boolean wasCityMatch = false;
    boolean wasStreetMatch = false;

    for (MapquestResult.Result result : filtered) {

      if (address.getZipcode() != null && address.getZipcode().equals(result.getZip())) {
        wasZipMatch = true;
      }
      if (address.getMunicipality() != null && address.getMunicipality().equals(result.getCity())) {
        wasCityMatch = true;
      }
      if (address.getStreet() != null && result.getStreet().matches(".*" + address.getStreet())) {
        wasStreetMatch = true;
      }
    }

    final Iterator<MapquestResult.Result> it = filtered.iterator();
    while (it.hasNext()) {
      final MapquestResult.Result result = it.next();

      final boolean zip = wasZipMatch && !address.getZipcode().equals(result.getZip());
      final boolean city = wasCityMatch && !address.getMunicipality().equals(result.getCity());
      final boolean street =
          wasStreetMatch && !result.getStreet().matches(".*" + address.getStreet());

      if (zip || city || street) it.remove();
    }
  }
Example #10
1
 /**
  * Run the consistency check and validate the result against expectations.
  *
  * @param rf The factory for the reasoner to test
  */
 @Override
 public void runTest() {
   ValidityReport report = testResults();
   switch (expected) {
     case INCONSISTENT:
       assertTrue("expected inconsistent", !report.isValid());
       break;
     case WARNINGS:
       assertTrue("expected just warnings but reports not valid", report.isValid());
       assertFalse("expected warnings but reports clean", report.isClean());
       break;
     case CLEAN:
       assertTrue("expected clean", report.isClean());
   }
   if (culprit != null) {
     boolean foundit = false;
     for (Iterator<Report> i = report.getReports(); i.hasNext(); ) {
       ValidityReport.Report r = i.next();
       if (r.getExtension() != null && r.getExtension().equals(culprit)) {
         foundit = true;
         break;
       }
     }
     if (!foundit) {
       assertTrue("Expcted to find a culprint " + culprit, false);
     }
   }
 }
Example #11
0
  public UMOMessage getResponse(UMOMessage message) throws RoutingException {
    UMOMessage result = null;
    if (routers.size() == 0) {
      result = message;
    } else {
      UMOResponseRouter router = null;
      for (Iterator iterator = getRouters().iterator(); iterator.hasNext(); ) {
        router = (UMOResponseRouter) iterator.next();
        result = router.getResponse(message);
      }

      if (result == null) {
        // Update stats
        if (getStatistics().isEnabled()) {
          getStatistics().incrementNoRoutedMessage();
        }
      }
    }

    if (result != null && transformer != null) {
      try {
        result =
            new MuleMessage(transformer.transform(result.getPayload()), result.getProperties());
      } catch (TransformerException e) {
        throw new RoutingException(result, null);
      }
    }
    return result;
  }
Example #12
0
  private void processMessages(Iterator messages, AxisOperation operation)
      throws DeploymentException {
    while (messages.hasNext()) {
      OMElement messageElement = (OMElement) messages.next();
      OMAttribute label = messageElement.getAttribute(new QName(TAG_LABEL));

      if (label == null) {
        throw new DeploymentException(Messages.getMessage("messagelabelcannotfound"));
      }

      AxisMessage message = operation.getMessage(label.getAttributeValue());

      Iterator parameters = messageElement.getChildrenWithName(new QName(TAG_PARAMETER));

      // processing <wsp:Policy> .. </..> elements
      Iterator policyElements =
          messageElement.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY));

      if (policyElements != null) {
        processPolicyElements(policyElements, message.getPolicySubject());
      }

      // processing <wsp:PolicyReference> .. </..> elements
      Iterator policyRefElements =
          messageElement.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY_REF));

      if (policyRefElements != null) {
        processPolicyRefElements(policyRefElements, message.getPolicySubject());
      }

      processParameters(parameters, message, operation);
    }
  }
Example #13
0
  static void itTest4(Map s, int size, int pos) {
    IdentityHashMap seen = new IdentityHashMap(size);
    reallyAssert(s.size() == size);
    int sum = 0;
    timer.start("Iter XEntry            ", size);
    Iterator it = s.entrySet().iterator();
    Object k = null;
    Object v = null;
    for (int i = 0; i < size - pos; ++i) {
      Map.Entry x = (Map.Entry) (it.next());
      k = x.getKey();
      v = x.getValue();
      seen.put(k, k);
      if (x != MISSING) ++sum;
    }
    reallyAssert(s.containsKey(k));
    it.remove();
    reallyAssert(!s.containsKey(k));
    while (it.hasNext()) {
      Map.Entry x = (Map.Entry) (it.next());
      Object k2 = x.getKey();
      seen.put(k2, k2);
      if (x != MISSING) ++sum;
    }

    reallyAssert(s.size() == size - 1);
    s.put(k, v);
    reallyAssert(seen.size() == size);
    timer.finish();
    reallyAssert(sum == size);
    reallyAssert(s.size() == size);
  }
  /**
   * Create the ValueObject collection to hold the set of DomainObjects.
   *
   * @param map - maps DomainObjects to created ValueObjects
   * @param domainObjectSet - Set of ims.core.clinical.domain.objects.PatientDiagnosis objects.
   */
  public static ims.core.vo.PatientDiagnosisEDischargeVoCollection
      createPatientDiagnosisEDischargeVoCollectionFromPatientDiagnosis(
          DomainObjectMap map, java.util.Set domainObjectSet) {
    ims.core.vo.PatientDiagnosisEDischargeVoCollection voList =
        new ims.core.vo.PatientDiagnosisEDischargeVoCollection();
    if (null == domainObjectSet) {
      return voList;
    }
    int rieCount = 0;
    int activeCount = 0;
    java.util.Iterator iterator = domainObjectSet.iterator();
    while (iterator.hasNext()) {
      ims.core.clinical.domain.objects.PatientDiagnosis domainObject =
          (ims.core.clinical.domain.objects.PatientDiagnosis) iterator.next();
      ims.core.vo.PatientDiagnosisEDischargeVo vo = create(map, domainObject);

      if (vo != null) voList.add(vo);

      if (domainObject != null) {
        if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
          rieCount++;
        else activeCount++;
      }
    }
    voList.setRieCount(rieCount);
    voList.setActiveCount(activeCount);
    return voList;
  }
Example #15
0
 @Override
 public Map<Vendor, List<Notebook>> getNotebooksStorePresent() {
   Session session = factory.openSession();
   try {
     Query query = session.createQuery("select n from Store s join s.notebook n");
     List results = query.list();
     Map<Vendor, List<Notebook>> resMap = new HashMap<>();
     for (Iterator iter = results.iterator(); iter.hasNext(); ) {
       Notebook notebook = (Notebook) iter.next();
       Vendor key = notebook.getVendor();
       if (resMap.containsKey(key)) {
         List<Notebook> notebooks = resMap.get(key);
         notebooks.add(notebook);
         resMap.replace(key, notebooks);
       } else {
         List<Notebook> notebooks = new ArrayList<>();
         notebooks.add(notebook);
         resMap.put(key, notebooks);
       }
     }
     return resMap;
   } finally {
     if (session != null) {
       session.close();
     }
   }
 }
Example #16
0
  public void findEdge(List dirEdgeList) {
    /**
     * Check all forward DirectedEdges only. This is still general, because each edge has a forward
     * DirectedEdge.
     */
    for (Iterator i = dirEdgeList.iterator(); i.hasNext(); ) {
      DirectedEdge de = (DirectedEdge) i.next();
      if (!de.isForward()) continue;
      checkForRightmostCoordinate(de);
    }

    /**
     * If the rightmost point is a node, we need to identify which of the incident edges is
     * rightmost.
     */
    Assert.isTrue(
        minIndex != 0 || minCoord.equals(minDe.getCoordinate()),
        "inconsistency in rightmost processing");
    if (minIndex == 0) {
      findRightmostEdgeAtNode();
    } else {
      findRightmostEdgeAtVertex();
    }
    /** now check that the extreme side is the R side. If not, use the sym instead. */
    orientedDe = minDe;
    int rightmostSide = getRightmostSide(minDe, minIndex);
    if (rightmostSide == Position.LEFT) {
      orientedDe = minDe.getSym();
    }
  }
  public static Bundle convertToBundle(JSONObject jsonObject) throws JSONException {
    Bundle bundle = new Bundle();
    @SuppressWarnings("unchecked")
    Iterator<String> jsonIterator = jsonObject.keys();
    while (jsonIterator.hasNext()) {
      String key = jsonIterator.next();
      Object value = jsonObject.get(key);
      if (value == null || value == JSONObject.NULL) {
        // Null is not supported.
        continue;
      }

      // Special case JSONObject as it's one way, on the return it would be Bundle.
      if (value instanceof JSONObject) {
        bundle.putBundle(key, convertToBundle((JSONObject) value));
        continue;
      }

      Setter setter = SETTERS.get(value.getClass());
      if (setter == null) {
        throw new IllegalArgumentException("Unsupported type: " + value.getClass());
      }
      setter.setOnBundle(bundle, key, value);
    }

    return bundle;
  }
 private void appendScanRow(StringBuilder buf, Bound bound) {
   ScanRanges scanRanges = context.getScanRanges();
   KeyRange minMaxRange = context.getMinMaxRange();
   Iterator<byte[]> minMaxIterator = Iterators.emptyIterator();
   if (minMaxRange != null) {
     RowKeySchema schema = tableRef.getTable().getRowKeySchema();
     if (!minMaxRange.isUnbound(bound)) {
       minMaxIterator = new RowKeyValueIterator(schema, minMaxRange.getRange(bound));
     }
   }
   int nRanges = scanRanges.getRanges().size();
   for (int i = 0, minPos = 0; minPos < nRanges || minMaxIterator.hasNext(); i++) {
     List<KeyRange> ranges = minPos >= nRanges ? EVERYTHING : scanRanges.getRanges().get(minPos++);
     KeyRange range = bound == Bound.LOWER ? ranges.get(0) : ranges.get(ranges.size() - 1);
     byte[] b = range.getRange(bound);
     Boolean isNull =
         KeyRange.IS_NULL_RANGE == range
             ? Boolean.TRUE
             : KeyRange.IS_NOT_NULL_RANGE == range ? Boolean.FALSE : null;
     if (minMaxIterator.hasNext()) {
       byte[] bMinMax = minMaxIterator.next();
       int cmp = Bytes.compareTo(bMinMax, b) * (bound == Bound.LOWER ? 1 : -1);
       if (cmp > 0) {
         minPos = nRanges;
         b = bMinMax;
         isNull = null;
       } else if (cmp < 0) {
         minMaxIterator = Iterators.emptyIterator();
       }
     }
     appendPKColumnValue(buf, b, isNull, i);
     buf.append(',');
   }
 }
 @Override
 public void fillContextMenu(IMenuManager menu) {
   // MOD mzhao user readonly role on svn repository mode.
   if (!isShowMenu()) {
     return;
   }
   TreeSelection treeSelection = ((TreeSelection) this.getContext().getSelection());
   if (!treeSelection.isEmpty()) {
     Iterator iterator = treeSelection.iterator();
     while (iterator.hasNext()) {
       Object obj = iterator.next();
       if (obj instanceof ReportAnalysisRepNode) {
         ReportAnalysisRepNode repAnaNode = (ReportAnalysisRepNode) obj;
         TDQReportItem reportItem = repAnaNode.getReportItem();
         if (CorePlugin.getDefault().itemIsOpening(reportItem, false)) {
           // if the report's editor is opening, don't show the menu
           return;
         }
       } else {
         // if include other type node, don't show the menu
         return;
       }
     }
   }
   // show the menu
   menu.add(new RemoveAnalysisAction());
 }
  /** Synchs in-core transactions to data file and opens a fresh log */
  private void synchronizeLogFromMemory() throws IOException {
    close();

    TreeSet<BlockIo> blockList = new TreeSet<BlockIo>(new BlockIoComparator());

    int numBlocks = 0;
    int writtenBlocks = 0;
    for (int i = 0; i < _maxTxns; i++) {
      if (txns[i] == null) continue;
      // Add each block to the blockList, replacing the old copy of this
      // block if necessary, thus avoiding writing the same block twice
      for (Iterator<BlockIo> k = txns[i].iterator(); k.hasNext(); ) {
        BlockIo block = k.next();
        if (blockList.contains(block)) {
          block.decrementTransactionCount();
        } else {
          writtenBlocks++;
          boolean result = blockList.add(block);
        }
        numBlocks++;
      }

      txns[i] = null;
    }
    // Write the blocks from the blockList to disk
    synchronizeBlocks(blockList, true);

    owner.sync();
    open();
  }
  @Override
  public void authRequest(Uri url, HashMap<String, String> doneSoFar) {
    if (mProgressDialog.isShowing()) {
      // should always be showing here
      mProgressDialog.dismiss();
    }

    // add our list of completed uploads to "completed"
    // and remove them from our toSend list.
    ArrayList<Long> workingSet = new ArrayList<Long>();
    Collections.addAll(workingSet, mInstancesToSend);
    if (doneSoFar != null) {
      Set<String> uploadedInstances = doneSoFar.keySet();
      Iterator<String> itr = uploadedInstances.iterator();

      while (itr.hasNext()) {
        Long removeMe = Long.valueOf(itr.next());
        boolean removed = workingSet.remove(removeMe);
        if (removed) {
          Log.i(t, removeMe + " was already sent, removing from queue before restarting task");
        }
      }
      mUploadedInstances.putAll(doneSoFar);
    }

    // and reconstruct the pending set of instances to send
    Long[] updatedToSend = new Long[workingSet.size()];
    for (int i = 0; i < workingSet.size(); ++i) {
      updatedToSend[i] = workingSet.get(i);
    }
    mInstancesToSend = updatedToSend;

    mUrl = url.toString();
    showDialog(AUTH_DIALOG);
  }
  /** 编辑转换配置XML文件 ; */
  public void editConfigXml() {
    ISelection selection = tableViewer.getSelection();
    if (!selection.isEmpty() && selection != null && selection instanceof IStructuredSelection) {
      IStructuredSelection structuredSelection = (IStructuredSelection) selection;
      @SuppressWarnings("unchecked")
      Iterator<String[]> iter = structuredSelection.iterator();
      String convertXml = iter.next()[1];

      AddOrEditXmlConvertConfigDialog dialog =
          new AddOrEditXmlConvertConfigDialog(getShell(), false);
      dialog.create();
      String convertXmlLoaction =
          root.getLocation()
              .append(ADConstants.AD_xmlConverterConfigFolder)
              .append(convertXml)
              .toOSString();
      if (dialog.setInitEditData(convertXmlLoaction)) {
        int result = dialog.open();
        // 如果点击的是确定按钮,那么更新列表
        if (result == IDialogConstants.OK_ID) {
          String curentConvertXMl = dialog.getCurentConverXML();
          refreshTable();
          setTableSelection(curentConvertXMl);
        }
      }
    } else {
      MessageDialog.openInformation(
          getShell(),
          Messages.getString("dialogs.XmlConverterConfigurationDialog.msgTitle"),
          Messages.getString("dialogs.XmlConverterConfigurationDialog.msg2"));
    }
  }
 /**
  * Remove mission from compare by id.
  *
  * @param id the id of mission to remove
  */
 public static void removeMission(long id) {
   for (Iterator<CompareItem> i = ITEMS.iterator(); i.hasNext(); ) {
     if (i.next().mission.getId() == id) {
       i.remove();
     }
   }
 }
Example #24
0
  protected static EditableFeatureAttributeDescriptor addGeometryColumn(EditableFeatureType fType) {

    EditableFeatureAttributeDescriptor attrTmp = null;
    EditableFeatureAttributeDescriptor attr = null;
    Iterator iter = fType.iterator();
    while (iter.hasNext()) {
      attrTmp = (EditableFeatureAttributeDescriptor) iter.next();
      if (attrTmp.getDataType() == DataTypes.GEOMETRY) {
        if (attr != null) {
          // Two geom fields not allowed
          fType.remove(attrTmp.getName());
        } else {
          attr = attrTmp;
          attr.setName(GEOMETRY_ATTIBUTE_NAME);
        }
      }
    }

    if (attr == null) {
      attr = fType.add(GEOMETRY_ATTIBUTE_NAME, DataTypes.GEOMETRY);
      try {
        attr.setDefaultValue(geomManager.createNullGeometry(SUBTYPES.GEOM2D));
      } catch (CreateGeometryException e) {
        logger.error("Error creating the envelope", e);
      }
    }

    fType.setDefaultGeometryAttributeName(attr.getName());
    return attr;
  }
Example #25
0
  protected static StorageStats getStorageStats() {
    // Try to grab the token from the cache.
    StorageStats stats = (StorageStats) cache.get(STORAGE_STATS_KEY);

    if (stats != null) {
      return stats;
    }

    // Now try to grab it from the datastore
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Extent<StorageStats> extent = pm.getExtent(StorageStats.class, false);

    try {
      Iterator<StorageStats> itr = extent.iterator();

      if (itr.hasNext()) {
        stats = itr.next();
      } else {
        stats = new StorageStats();
        pm.makePersistent(stats);
      }

      return stats;
    } finally {
      extent.closeAll();
      pm.close();

      cache.put(STORAGE_STATS_KEY, stats);
    }
  }
Example #26
0
  public void performNext() {
    if (true == pages.isEmpty()) {
      return;
    }

    if (null == currentPage) {
      IWizardPage page = (IWizardPage) pages.values().iterator().next();
      showPage(page.getPageID());
    } else {
      boolean foundCurrent = false;
      for (Iterator iterator = pages.values().iterator(); iterator.hasNext(); ) {
        IWizardPage page = (IWizardPage) iterator.next();
        if (true == foundCurrent) {
          showPage(page.getPageID());
          return;
        }

        if (page.getPageID().equals(currentPage.getPageID())) {
          foundCurrent = true;
        }
      }

      if (false == foundCurrent) {
        Debug.out("MultipageWizard:: there is no more page to go to");
      }
    }
  }
  /**
   * Returns a textual description of this classifier.
   *
   * @return a textual description of this classifier.
   */
  @Override
  public String toString() {

    if (m_probOfClass == null) {
      return "NaiveBayesMultinomialText: No model built yet.\n";
    }

    StringBuffer result = new StringBuffer();

    // build a master dictionary over all classes
    HashSet<String> master = new HashSet<String>();
    for (int i = 0; i < m_data.numClasses(); i++) {
      LinkedHashMap<String, Count> classDict = m_probOfWordGivenClass.get(i);

      for (String key : classDict.keySet()) {
        master.add(key);
      }
    }

    result.append("Dictionary size: " + master.size()).append("\n\n");

    result.append("The independent frequency of a class\n");
    result.append("--------------------------------------\n");

    for (int i = 0; i < m_data.numClasses(); i++) {
      result
          .append(m_data.classAttribute().value(i))
          .append("\t")
          .append(Double.toString(m_probOfClass[i]))
          .append("\n");
    }

    result.append("\nThe frequency of a word given the class\n");
    result.append("-----------------------------------------\n");

    for (int i = 0; i < m_data.numClasses(); i++) {
      result.append(Utils.padLeft(m_data.classAttribute().value(i), 11)).append("\t");
    }

    result.append("\n");

    Iterator<String> masterIter = master.iterator();
    while (masterIter.hasNext()) {
      String word = masterIter.next();

      for (int i = 0; i < m_data.numClasses(); i++) {
        LinkedHashMap<String, Count> classDict = m_probOfWordGivenClass.get(i);
        Count c = classDict.get(word);
        if (c == null) {
          result.append("<laplace=1>\t");
        } else {
          result.append(Utils.padLeft(Double.toString(c.m_count), 11)).append("\t");
        }
      }
      result.append(word);
      result.append("\n");
    }

    return result.toString();
  }
Example #28
0
  private boolean generateWsdl(AxisService axisService) {
    Iterator operatins = axisService.getOperations();
    if (operatins.hasNext()) {
      while (operatins.hasNext()) {
        AxisOperation axisOperation = (AxisOperation) operatins.next();

        if (axisOperation.isControlOperation()) {
          continue;
        }

        if (axisOperation.getMessageReceiver() == null) {
          continue;
        }
        String messageReceiverClass = axisOperation.getMessageReceiver().getClass().getName();
        if (!("org.apache.axis2.rpc.receivers.RPCMessageReceiver".equals(messageReceiverClass)
            || "org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"
                .equals(messageReceiverClass)
            || "org.apache.axis2.rpc.receivers.RPCInOutAsyncMessageReceiver"
                .equals(messageReceiverClass)
            || "org.apache.axis2.jaxws.server.JAXWSMessageReceiver".equals(messageReceiverClass))) {
          return false;
        }
      }
    }
    return true;
  }
  /**
   * Returns a CSV line for the given LoggingObject - containing all properties in the exact same
   * way as in the config file - excluding those which could not be retrieved, i.e. for which no
   * PropertyDescriptor could be created
   *
   * @param loggingObject the LoggingObject for which a CSV line should be created
   * @return the CSV line representing the given LoggingObject
   */
  public String getCSVRow(LoggingObject loggingObject, boolean anonymize, Long resourceableId) {
    List<String> loggingObjectList = new ArrayList<String>();
    for (Iterator<PropertyDescriptor> it = orderedExportedPropertyDescriptors.iterator();
        it.hasNext(); ) {
      PropertyDescriptor pd = it.next();

      String strValue = "";
      try {
        Object value = pd.getReadMethod().invoke(loggingObject, (Object[]) null);
        if (value != null) {
          strValue = String.valueOf(value);
        }
        if (anonymize && anonymizedProperties.contains(pd.getName())) {
          // do anonymization
          strValue = makeAnonymous(String.valueOf(value), resourceableId);
        }
      } catch (IllegalArgumentException e) {
        // nothing to do
      } catch (IllegalAccessException e) {
        // nothing to do
      } catch (InvocationTargetException e) {
        // nothing to do
      }
      loggingObjectList.add(strValue);
    }

    return StringHelper.formatAsCSVString(loggingObjectList);
  }
  /**
   * Checks if is scope valid.
   *
   * @param scope the scope
   * @param response the response
   * @return true, if is scope valid
   */
  private boolean isScopeValid(String scope, String response) {
    boolean isValid = true;
    JSONObject obj;
    try {
      obj = new JSONObject(response);

      if (obj.toString().equals("{}")) {
        System.out.println("No claims have not null values in the scope : " + scope);
        return true;
      }

      Iterator keys = obj.keys();
      List xmlScopeList = scopes.get(scope).getClaims().getClaimValues();

      while (keys.hasNext()) {
        String key = (String) keys.next();
        if (!xmlScopeList.contains(key)) {
          log.info("Response contains a claim value that is not belongs to scope " + scope);
          isValid = false;
          break;
        }
      }
    } catch (JSONException e) {
      e.printStackTrace();
      return false;
    }
    return isValid;
  }