Пример #1
1
  /**
   * Checks if our WPS can really handle this process inputs and outputs
   *
   * @param pf
   * @param name
   * @return
   */
  Set<Name> getProcessBlacklist() {
    synchronized (PROCESS_BLACKLIST) {
      if (PROCESS_BLACKLIST == Collections.EMPTY_SET) {

        Set<Name> blacklist = new HashSet<Name>();

        for (ProcessFactory pf : Processors.getProcessFactories()) {
          int count = 0;
          for (Name name : pf.getNames()) {
            try {
              // check inputs
              for (Parameter<?> p : pf.getParameterInfo(name).values()) {
                List<ProcessParameterIO> ppios = ProcessParameterIO.findAll(p, context);
                if (ppios.isEmpty()) {
                  LOGGER.log(
                      Level.INFO,
                      "Blacklisting process "
                          + name.getURI()
                          + " as the input "
                          + p.key
                          + " of type "
                          + p.type
                          + " cannot be handled");
                  blacklist.add(name);
                }
              }

              // check outputs
              for (Parameter<?> p : pf.getResultInfo(name, null).values()) {
                List<ProcessParameterIO> ppios = ProcessParameterIO.findAll(p, context);
                if (ppios.isEmpty()) {
                  LOGGER.log(
                      Level.INFO,
                      "Blacklisting process "
                          + name.getURI()
                          + " as the output "
                          + p.key
                          + " of type "
                          + p.type
                          + " cannot be handled");
                  blacklist.add(name);
                }
              }
            } catch (Throwable t) {
              blacklist.add(name);
            }

            if (!blacklist.contains(name)) {
              count++;
            }
          }
          LOGGER.info("Found " + count + " bindable processes in " + pf.getTitle());
        }

        PROCESS_BLACKLIST = blacklist;
      }
    }

    return PROCESS_BLACKLIST;
  }
  /** {@inheritDoc} */
  public synchronized void removeColumn(TalendColumn column) {

    ResourceBundle rb = ResourceBundle.getBundle("TalendBridge", Locale.getDefault());

    int index = columnsList.indexOf(column);
    if (index == -1) {
      return;
    }

    if (columnImpls.get(column).isKey() && (!rowList.isEmpty() || !rowdraft.isEmpty())) {
      throw new IllegalStateException(
          String.format(
              Locale.getDefault(),
              rb.getString("exception.cannotRemoveKey"),
              column.getName(),
              name));
    }

    TalendColumnImpl c;
    for (index = index + 1; index < columnsList.size(); index++) {
      c = columnsList.get(index);
      c.index--;
    }

    for (TalendRowImpl row : rowList) {
      row.setValue(column, null, true);
    }

    columnsList.remove((TalendColumnImpl) column);
    columns.remove(column.getName());
    columnImpls.remove(column);
  }
Пример #3
0
  /*
   * It is a idempotent function to add various intermediate files as the source
   * for the union. The plan has already been created.
   */
  public static void initUnionPlan(
      GenMRProcContext opProcCtx, Task<? extends Serializable> currTask, boolean local) {
    MapredWork plan = (MapredWork) currTask.getWork();
    UnionOperator currUnionOp = opProcCtx.getCurrUnionOp();
    assert currUnionOp != null;
    GenMRUnionCtx uCtx = opProcCtx.getUnionTask(currUnionOp);
    assert uCtx != null;

    List<String> taskTmpDirLst = uCtx.getTaskTmpDir();
    List<TableDesc> tt_descLst = uCtx.getTTDesc();
    assert !taskTmpDirLst.isEmpty() && !tt_descLst.isEmpty();
    assert taskTmpDirLst.size() == tt_descLst.size();
    int size = taskTmpDirLst.size();
    assert local == false;

    for (int pos = 0; pos < size; pos++) {
      String taskTmpDir = taskTmpDirLst.get(pos);
      TableDesc tt_desc = tt_descLst.get(pos);
      if (plan.getPathToAliases().get(taskTmpDir) == null) {
        plan.getPathToAliases().put(taskTmpDir, new ArrayList<String>());
        plan.getPathToAliases().get(taskTmpDir).add(taskTmpDir);
        plan.getPathToPartitionInfo().put(taskTmpDir, new PartitionDesc(tt_desc, null));
        plan.getAliasToWork().put(taskTmpDir, currUnionOp);
      }
    }
  }
Пример #4
0
  public MatchResultWrap findCoverProject(MapPoint currPoint, String distance) {
    double lng = currPoint.getLng().doubleValue();
    double lat = currPoint.getLat().doubleValue();
    double dis = 5000;
    if (distance != null) {
      try {
        dis = Double.parseDouble(distance);
      } catch (NumberFormatException e) {

      }
    }
    Map<String, Object> map = MathUtils.square(lng, lat, dis);
    List<MatchResultVo> projectList = myRentalDao.selectCoverProject(map);
    List<MatchResultVo> selectedProjectList = extractMatchResult(projectList);

    if (selectedProjectList == null || selectedProjectList.isEmpty()) {
      return new MatchResultWrap();
    }
    String staticUrl = StringUtils.EMPTY;
    if (selectedProjectList == null || selectedProjectList.isEmpty()) {
      return new MatchResultWrap();
    } else {
      return new MatchResultWrap(selectedProjectList, currPoint, staticUrl);
    }
  }
 /**
  * Normalize the provided reference, filling missing names, and gaps in the parent chain.
  *
  * @param referenceToResolve the reference to normalize, if the first parameter is an entity
  *     reference, it is used to compute default names.
  * @param parameters optional parameters,
  * @return a normalized reference chain
  */
 private EntityReference normalizeReference(
     EntityReference referenceToResolve, Object[] parameters) {
   EntityReference normalizedReference = referenceToResolve;
   EntityReference reference = normalizedReference;
   while (reference != null) {
     List<EntityType> types = this.nextAllowedEntityTypes.get(reference.getType());
     if (reference.getParent() != null
         && !types.isEmpty()
         && !types.contains(reference.getParent().getType())) {
       // The parent reference isn't the allowed parent: insert an allowed reference
       EntityReference newReference =
           new EntityReference(
               resolveDefaultValue(types.get(0), parameters), types.get(0), reference.getParent());
       normalizedReference =
           normalizedReference.replaceParent(reference.getParent(), newReference);
       reference = newReference;
     } else if (reference.getParent() == null && !types.isEmpty()) {
       // The top reference isn't the allowed top level reference, add a parent reference
       EntityReference newReference =
           new EntityReference(resolveDefaultValue(types.get(0), parameters), types.get(0));
       normalizedReference = normalizedReference.appendParent(newReference);
       reference = newReference;
     } else if (reference.getParent() != null && types.isEmpty()) {
       // There's a parent but no one is allowed
       throw new InvalidEntityReferenceException();
     } else {
       // Parent is ok, check next
       reference = reference.getParent();
     }
   }
   return normalizedReference;
 }
Пример #6
0
 protected boolean updateSubAwardBudgetDetails(Budget budget, BudgetSubAwards subAward)
     throws Exception {
   List<String[]> errorMessages = new ArrayList<String[]>();
   boolean success =
       getKcBusinessRulesEngine().applyRules(new BudgetSubAwardsEvent(subAward, budget, ""));
   if (subAward.getNewSubAwardFile().getBytes().length == 0) {
     success = false;
   }
   if (success) {
     getPropDevBudgetSubAwardService()
         .updateSubAwardBudgetDetails(budget, subAward, errorMessages);
   }
   if (!errorMessages.isEmpty()) {
     for (String[] message : errorMessages) {
       String[] messageParameters = null;
       if (message.length > 1) {
         messageParameters = Arrays.copyOfRange(message, 1, message.length);
       }
       if (success) {
         GlobalVariables.getMessageMap()
             .putWarning(Constants.SUBAWARD_FILE_FIELD_NAME, message[0], messageParameters);
       } else {
         GlobalVariables.getMessageMap()
             .putError(Constants.SUBAWARD_FILE_FIELD_NAME, message[0], messageParameters);
       }
     }
   }
   if (success && errorMessages.isEmpty()) {
     GlobalVariables.getMessageMap()
         .putInfo(Constants.SUBAWARD_FILE_FIELD_NAME, Constants.SUBAWARD_FILE_DETAILS_UPDATED);
   }
   return success;
 }
Пример #7
0
  /** This operation sets the input of the resourceTreeViewer. */
  private void setTreeContent() {

    // If currently playing, stop.
    if (playAction.isInPlayState()) {
      playAction.stop();
    }
    // If there are no files, but there are images, set to the images tab.
    // Otherwise, default to the files tab.
    if (textList.isEmpty() && !imageList.isEmpty()) {
      resourceTreeViewer.setInput(imageList);
      tabFolder.setSelection(1);
      playable = true;

      // Select the first available image resource.
      resourceTreeViewer.setSelection(new StructuredSelection(imageList.get(0)), true);
    } else {
      resourceTreeViewer.setInput(textList);
      tabFolder.setSelection(0);
      playable = false;

      // Select the first available text resource.
      if (!textList.isEmpty()) {
        resourceTreeViewer.setSelection(new StructuredSelection(textList.get(0)), true);
      }
    }

    return;
  }
Пример #8
0
  /** Returns an HttpEntity containing all request parameters */
  public HttpEntity getEntity() {

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

    HttpEntity result = null;

    if (fileParams != null && !fileParams.isEmpty()) {

      MultipartEntity multipartEntity =
          new MultipartEntity(HttpMultipartMode.STRICT, boundary, Charset.forName(charset));

      if (bodyParams != null && !bodyParams.isEmpty()) {
        for (NameValuePair param : bodyParams) {
          try {
            multipartEntity.addPart(param.getName(), new StringBody(param.getValue()));
          } catch (UnsupportedEncodingException e) {
            LogUtils.e(e.getMessage(), e);
          }
        }
      }

      for (ConcurrentHashMap.Entry<String, ContentBody> entry : fileParams.entrySet()) {
        multipartEntity.addPart(entry.getKey(), entry.getValue());
      }

      result = multipartEntity;
    } else if (bodyParams != null && !bodyParams.isEmpty()) {
      result = new BodyParamsEntity(bodyParams, charset);
    }

    return result;
  }
  public ModelAndView postFeedback(
      HttpServletRequest request, HttpServletResponse response, ProjectFeedbackVo feedbackVo)
      throws Exception {
    if (logger.isDebugEnabled()) {
      logger.debug(
          "postExperienceAndFb(HttpServletRequest, HttpServletResponse, ProjectInfoVo) - start");
    }

    ProjectVo projectVo = (ProjectVo) modelAndView.getModel().get("projectVo");

    modelAndView = new ModelAndView("volunteer/viewProject");

    if (!StringUtil.isNullOrEmpty(feedbackVo.getTitle())) {

      feedbackVo.setPrjId(projectVo.getPrjId());
      projectFeedbackService.createProjectFeedback(feedbackVo);
      modelAndView.addObject(
          "riMsg",
          Messages.getString("message.common.submitreview.msg", new String[] {"Project Feedback"}));
    }
    List<ProjectMemberVo> memberList =
        memberManagementService.getMemberListbyProject(projectVo.getPrjId());

    List<ProjectExperienceVo> experienceList =
        projectExperienceService.getProjectExperienceListbyProjectId(projectVo.getPrjId());
    List<ProjectFeedbackVo> feedbackList =
        projectFeedbackService.getProjectFeedbackListbyProjectId(projectVo.getPrjId());

    PagedListHolder feedbackPagedListHolder = new PagedListHolder(feedbackList);

    if (!feedbackList.isEmpty()) {
      int page = ServletRequestUtils.getIntParameter(request, "p1", 0);
      feedbackPagedListHolder.setPage(page);
      feedbackPagedListHolder.setPageSize(100);
    }

    PagedListHolder exPagedListHolder = new PagedListHolder(experienceList);
    if (!experienceList.isEmpty()) {
      int page = ServletRequestUtils.getIntParameter(request, "p2", 0);
      exPagedListHolder.setPage(page);
      exPagedListHolder.setPageSize(100);
    }

    modelAndView.addObject("fbPagedListHolder", feedbackPagedListHolder);

    modelAndView.addObject("exPagedListHolder", exPagedListHolder);

    modelAndView.addObject("memberList", memberList);
    modelAndView.addObject("experienceList", experienceList);
    modelAndView.addObject("feedbackList", feedbackList);
    modelAndView.addObject("projectVo", projectVo);
    modelAndView.addObject("feedbackVo", new ProjectFeedbackVo());
    modelAndView.addObject("experienceVo", new ProjectExperienceVo());

    if (logger.isDebugEnabled()) {
      logger.debug(
          "postExperienceAndFb(HttpServletRequest, HttpServletResponse, ProjectInfoVo) - end");
    }
    return modelAndView;
  }
  @Override
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final EEModuleDescription eeModuleDescription =
        deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
    final CompositeIndex index =
        deploymentUnit.getAttachment(
            org.jboss.as.server.deployment.Attachments.COMPOSITE_ANNOTATION_INDEX);
    final EEApplicationClasses applicationClasses =
        deploymentUnit.getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION);

    // @PersistenceContext
    List<AnnotationInstance> persistenceContexts =
        index.getAnnotations(PERSISTENCE_CONTEXT_ANNOTATION_NAME);
    // create binding and injection configurations out of the @PersistenceContext annotations
    this.processPersistenceAnnotations(
        deploymentUnit, eeModuleDescription, persistenceContexts, applicationClasses);

    // @PersistenceUnit
    List<AnnotationInstance> persistenceUnits =
        index.getAnnotations(PERSISTENCE_UNIT_ANNOTATION_NAME);
    // create binding and injection configurations out of the @PersistenceUnit annotaitons
    this.processPersistenceAnnotations(
        deploymentUnit, eeModuleDescription, persistenceUnits, applicationClasses);

    // if we found any @PersistenceContext or @PersistenceUnit annotations then mark this as a JPA
    // deployment
    if (!persistenceContexts.isEmpty() || !persistenceUnits.isEmpty()) {
      JPADeploymentMarker.mark(deploymentUnit);
    }
  }
 public void add(Diagnostic diagnostic) {
   if (diagnostic == null) return;
   List<Diagnostic> kids = diagnostic.getChildren();
   if (!kids.isEmpty()) {
     for (Diagnostic kid : kids) add(kid);
   } else {
     List<?> objects = diagnostic.getData();
     CSTNode cstNode = null;
     if (!objects.isEmpty()) {
       Object object = objects.get(0);
       if (object != null) {
         if (environment != null) cstNode = environment.getASTMapping(object);
         else if (object instanceof CSTNode) cstNode = (CSTNode) object;
       }
     }
     int startOffset = cstNode != null ? cstNode.getStartOffset() : 0;
     int endOffset = cstNode != null ? cstNode.getEndOffset() : 0;
     Severity problemSeverity = Severity.INFO;
     if (diagnostic.getSeverity() >= Diagnostic.ERROR) problemSeverity = Severity.ERROR;
     else if (diagnostic.getSeverity() >= Diagnostic.WARNING) problemSeverity = Severity.WARNING;
     String problemMessage = diagnostic.getMessage();
     String problemContext = diagnostic.getSource();
     handleProblem(problemSeverity, problemMessage, problemContext, startOffset, endOffset);
   }
 }
Пример #12
0
 /**
  * Iterate through list of installed vocabularies. Update each one, indicating if it is the latest
  * version or not.
  */
 @VisibleForTesting
 protected void updateIsLatest(List<Vocabulary> vocabularies, List<Vocabulary> registered) {
   if (!vocabularies.isEmpty() && !registered.isEmpty()) {
     for (Vocabulary vocabulary : vocabularies) {
       // is this the latest version?
       for (Vocabulary rVocabulary : registered) {
         if (vocabulary.getUriString() != null && rVocabulary.getUriString() != null) {
           String idOne = vocabulary.getUriString();
           String idTwo = rVocabulary.getUriString();
           // first compare on identifier
           if (idOne.equalsIgnoreCase(idTwo)) {
             Date issuedOne = vocabulary.getIssued();
             Date issuedTwo = rVocabulary.getIssued();
             // next compare on issued date: can both be null, or issued date must be same
             if ((issuedOne == null && issuedTwo == null)
                 || (issuedOne != null
                     && issuedTwo != null
                     && issuedOne.compareTo(issuedTwo) == 0)) {
               vocabulary.setLatest(rVocabulary.isLatest());
             }
           }
         }
       }
       log.debug(
           "Installed vocabulary with identifier "
               + vocabulary.getUriString()
               + " latest="
               + vocabulary.isLatest());
     }
   }
 }
Пример #13
0
 public DataDeleteRequest build() {
   label0:
   {
     boolean flag3 = false;
     boolean flag;
     boolean flag1;
     boolean flag2;
     if (zzMS > 0L && zzann > zzMS) {
       flag2 = true;
     } else {
       flag2 = false;
     }
     zzx.zza(flag2, "Must specify a valid time interval");
     if (zzapI || !zzapG.isEmpty() || !zzanw.isEmpty()) {
       flag = true;
     } else {
       flag = false;
     }
     if (zzapJ || !zzapH.isEmpty()) {
       flag1 = true;
     } else {
       flag1 = false;
     }
     if (!flag) {
       flag2 = flag3;
       if (!flag1) {
         break label0;
       }
     }
     flag2 = true;
   }
   zzx.zza(flag2, "No data or session marked for deletion");
   zzsf();
   return new DataDeleteRequest(this);
 }
Пример #14
0
  private static void appendClassSignature(final StringBuilder builder, final DartClass dartClass) {
    if (dartClass.isEnum()) {
      builder.append("enum <b>").append(dartClass.getName()).append("</b>");
      return;
    }

    if (dartClass.isAbstract()) {
      builder.append("abstract ");
    }

    builder.append("class <b>").append(dartClass.getName()).append("</b>");
    appendTypeParams(builder, dartClass.getTypeParameters());

    final List<DartType> mixins = dartClass.getMixinsList();
    final DartType superClass = dartClass.getSuperClass();
    if (superClass != null) {
      builder.append(" extends ").append(StringUtil.escapeXml(superClass.getText()));
    }

    if (!mixins.isEmpty()) {
      builder.append(" with ");
      appendDartTypeList(builder, mixins);
    }

    final List<DartType> implementsList = dartClass.getImplementsList();
    if (!implementsList.isEmpty()) {
      builder.append(" implements ");
      appendDartTypeList(builder, implementsList);
    }
  }
  public void mapEdgeColumn(final EncoreInteraction interaction, final CyRow row) {

    final Set<String> exp = interaction.getExperimentToPubmed().keySet();
    row.set(DETECTION_METHOD_ID, new ArrayList<String>(exp));

    final List<CrossReference> pubIDs = interaction.getPublicationIds();
    final List<String> pubIdList = new ArrayList<String>();
    final List<String> pubDBList = new ArrayList<String>();
    for (CrossReference pub : pubIDs) {
      pubIdList.add(pub.getIdentifier());
      pubDBList.add(pub.getDatabase());
    }
    if (pubIdList.isEmpty() == false) row.set(PUB_ID, pubIdList);
    if (pubDBList.isEmpty() == false) row.set(PUB_DB, pubDBList);

    // Interaction (use UniqueID)
    row.set(CyEdge.INTERACTION, interaction.getMappingIdDbNames());

    final List<Confidence> scores = interaction.getConfidenceValues();
    for (Confidence c : scores) {
      String type = c.getType();
      String value = c.getValue();

      if (row.getTable().getColumn(type) == null)
        row.getTable().createColumn(type, Double.class, true);

      try {
        double doubleVal = Double.parseDouble(value);
        row.set(type, doubleVal);
      } catch (NumberFormatException e) {
        // logger.warn("Invalid number string: " + value);
        // Ignore invalid number
      }
    }
  }
 private void removeFilesInIndex(
     List<Object> filesToRemove,
     List<IIndexFragmentFile> indexFilesToRemove,
     IProgressMonitor monitor)
     throws InterruptedException, CoreException {
   if (!filesToRemove.isEmpty() || !indexFilesToRemove.isEmpty()) {
     fIndex.acquireWriteLock();
     try {
       for (Object tu : filesToRemove) {
         if (monitor.isCanceled()) {
           return;
         }
         IIndexFileLocation ifl = fResolver.resolveFile(tu);
         if (ifl == null) continue;
         IIndexFragmentFile[] ifiles = fIndex.getWritableFiles(ifl);
         for (IIndexFragmentFile ifile : ifiles) {
           fIndex.clearFile(ifile);
         }
         incrementRequestedFilesCount(-1);
       }
       for (IIndexFragmentFile ifile : indexFilesToRemove) {
         if (monitor.isCanceled()) {
           return;
         }
         fIndex.clearFile(ifile);
         incrementRequestedFilesCount(-1);
       }
     } finally {
       fIndex.releaseWriteLock();
     }
   }
   filesToRemove.clear();
 }
Пример #17
0
  @Override
  public ClassLoader getClassLoader(ClassLoader fallbackLoader, String... classpathEntries) {
    List<String> urls = new ArrayList<String>();
    if (classpathEntries != null) {
      for (String url : classpathEntries) {
        if (!StringUtil.isBlank(url)) {
          urls.add(url);
        }
      }
    }
    List<ClassLoader> delegatesList = new ArrayList<ClassLoader>();
    if (!urls.isEmpty()) {
      StringURLClassLoader urlClassLoader = new StringURLClassLoader(urls);
      // only if any custom urls were parsed add this loader
      if (urlClassLoader.getURLs().length > 0) {
        delegatesList.add(urlClassLoader);
      }
    }

    ClassLoader currentLoader = getClass().getClassLoader();
    if (fallbackLoader != null && !fallbackLoader.equals(currentLoader)) {
      // if the parent of fallback is the same as the current loader, just use that
      if (fallbackLoader.getParent().equals(currentLoader)) {
        currentLoader = fallbackLoader;
      } else {
        delegatesList.add(fallbackLoader);
      }
    }

    return delegatesList.isEmpty()
        ? currentLoader
        : new DelegatingClassLoader(currentLoader, delegatesList);
  }
  // 消耗
  @Test
  public void testUseUp() throws BusinessException, SQLException {
    StockActionDao.getStockAndDetail(mStaff, null, null);
    Department deptIn;
    List<Department> depts = DepartmentDao.getDepartments4Inventory(mStaff);
    if (depts.isEmpty()) {
      throw new BusinessException(DeptError.DEPT_NOT_EXIST);
    } else {
      deptIn = depts.get(2);
    }

    //		Map<Object, Object> params = new HashMap<Object, Object>();
    //		params.put(SQLUtil.SQL_PARAMS_EXTRA, " AND M.restaurant_id = " + mStaff.getRestaurantId());
    List<Material> materials = MaterialDao.getByCond(mStaff, null);
    if (materials.isEmpty()) {
      throw new BusinessException(MaterialError.SELECT_NOT_ADD);
    }

    InsertBuilder builder =
        StockAction.InsertBuilder.newDamage(mStaff.getRestaurantId())
            .setOperatorId((int) mStaff.getId())
            .setOperator(mStaff.getName())
            .setOriStockId("bbb111")
            .setOriStockDate(DateUtil.parseDate("2013-09-26 12:12:12"))
            .setComment("use_up")
            .setDeptIn(deptIn.getId())
            .setCateType(MaterialCate.Type.MATERIAL)
            .addDetail(new StockActionDetail(materials.get(0).getId(), 1.5f, 10))
            .addDetail(new StockActionDetail(materials.get(2).getId(), 1.5f, 8));

    testInsert(builder);
  }
Пример #19
0
  private void scanDir(File dir, List<Pattern> includes) {
    if (!dir.canRead()) return;

    // See if patterns are specific enough to avoid scanning every file in the directory.
    boolean scanAll = false;
    for (Pattern include : includes) {
      if (include.value.indexOf('*') != -1 || include.value.indexOf('?') != -1) {
        scanAll = true;
        break;
      }
    }

    if (!scanAll) {
      // If not scanning all the files, we know exactly which ones to include.
      List matchingIncludes = new ArrayList(1);
      for (Pattern include : includes) {
        if (matchingIncludes.isEmpty()) matchingIncludes.add(include);
        else matchingIncludes.set(0, include);
        process(dir, include.value, matchingIncludes);
      }
    } else {
      // Scan every file.
      for (String fileName : dir.list()) {
        // Get all include patterns that match.
        List<Pattern> matchingIncludes = new ArrayList(includes.size());
        for (Pattern include : includes)
          if (include.matches(fileName)) matchingIncludes.add(include);
        if (matchingIncludes.isEmpty()) continue;
        process(dir, fileName, matchingIncludes);
      }
    }
  }
Пример #20
0
 protected void correctPosition(
     BasicModelData obj, PositionSettings pos, List<HeightInfo> positions) {
   double xVar = xRatio;
   double zVar = zRatio;
   double x = obj.getX();
   double z = obj.getZ();
   if (!positions.isEmpty() || collisionTree != null) {
     HeightInfo actual = new HeightInfo(obj.getX(), 0, obj.getZ());
     HeightInfo nearest = new HeightInfo(Double.MAX_VALUE, 0, Double.MAX_VALUE);
     if (!positions.isEmpty()) {
       nearest = findNearest(positions, actual, nearest);
       x = nearest.getX();
       z = nearest.getZ();
     }
     if (collisionTree != null) {
       actual.setSx(obj.getSx());
       actual.setSz(obj.getSz());
       TreeNode place = collisionTree.findPlace(actual);
       if (place != null) {
         x = place.getMid()[0];
         z = place.getMid()[1];
         double nodeRange = place.getRange();
         xVar = nodeRange + 1 - actual.getSx();
         zVar = nodeRange + 1 - actual.getSz();
         TreeNode.mark(place);
       } else {
         collisionDetected = true;
       }
     }
   }
   obj.setX(x + randomizeDouble(-xVar, xVar));
   obj.setZ(z + randomizeDouble(-zVar, zVar));
   correctPosition(obj, pos);
 }
  static void logPlugins() {
    List<String> loadedBundled = new ArrayList<String>();
    List<String> disabled = new ArrayList<String>();
    List<String> loadedCustom = new ArrayList<String>();

    for (IdeaPluginDescriptor descriptor : ourPlugins) {
      final String version = descriptor.getVersion();
      String s = descriptor.getName() + (version != null ? " (" + version + ")" : "");
      if (descriptor.isEnabled()) {
        if (descriptor.isBundled() || SPECIAL_IDEA_PLUGIN.equals(descriptor.getName()))
          loadedBundled.add(s);
        else loadedCustom.add(s);
      } else {
        disabled.add(s);
      }
    }

    Collections.sort(loadedBundled);
    Collections.sort(loadedCustom);
    Collections.sort(disabled);

    getLogger().info("Loaded bundled plugins: " + StringUtil.join(loadedBundled, ", "));
    if (!loadedCustom.isEmpty()) {
      getLogger().info("Loaded custom plugins: " + StringUtil.join(loadedCustom, ", "));
    }
    if (!disabled.isEmpty()) {
      getLogger().info("Disabled plugins: " + StringUtil.join(disabled, ", "));
    }
  }
Пример #22
0
  public static Map<Sensor, List<Move>> makeSameLength(Map<Sensor, List<Location>> paths) {
    int maxSize = 1;

    for (List<Location> path : paths.values()) {
      maxSize = Math.max(maxSize, path.size());
    }

    Map<Sensor, List<Move>> result = new HashMap<Sensor, List<Move>>();
    for (Sensor sensor : paths.keySet()) {
      List<Location> path = paths.get(sensor);

      Location last;
      if (!path.isEmpty()) {
        last = path.get(path.size() - 1);
        path = path.subList(1, path.size());
      } else last = sensor.getLocation();

      int currentSize = path.size();
      if (path.isEmpty()) currentSize--;

      for (int i = 0; i < maxSize - currentSize - 1; i++) {
        path.add(last);
      }

      result.put(sensor, Move.convertToMoves(path));
    }

    for (List<Location> path : paths.values()) {
      Validate.isTrue(path.size() == maxSize);
    }

    return result;
  }
Пример #23
0
 /**
  * Whether a system option from list appears as custom attribute The reflection does not work
  * because an additional condition should be satisfied (no direct foreign key relationship exists)
  *
  * @param objectIDs
  * @param fieldID
  */
 @Override
 public boolean isSystemOptionAttribute(List<Integer> objectIDs, Integer fieldID) {
   if (objectIDs == null || objectIDs.isEmpty()) {
     return false;
   }
   List attributes = null;
   Criteria selectCriteria;
   List<int[]> chunkList = GeneralUtils.getListOfChunks(objectIDs);
   Iterator<int[]> iterator = chunkList.iterator();
   while (iterator.hasNext()) {
     int[] idChunk = iterator.next();
     selectCriteria = new Criteria();
     selectCriteria.addIn(SYSTEMOPTIONID, idChunk);
     selectCriteria.add(SYSTEMOPTIONTYPE, fieldID);
     selectCriteria.setDistinct();
     try {
       attributes = doSelect(selectCriteria);
     } catch (Exception e) {
       LOGGER.error(
           "Verifiying the dependent "
               + "oldPersonIDs "
               + objectIDs.size()
               + " for the user picker failed with "
               + e.getMessage(),
           e);
     }
     if (attributes != null && !attributes.isEmpty()) {
       return true;
     }
   }
   return false;
 }
Пример #24
0
  private void parseProperties(Document doc, CsvProperties properties) {
    try {

      ArrayList<String> els;

      // Get unique times
      List<Element> timeList = XPath.selectNodes(doc, ".//gml:timePosition");
      if (!timeList.isEmpty()) {
        ArrayList<String> times = new ArrayList<String>(timeList.size());
        for (Element e : timeList) {
          times.add(e.getValue());
        }
        els = new ArrayList(new HashSet(times));
        Collections.sort(els);
        properties.setTimesteps(els);
      }

      // Get unique variable names
      List<Element> varList = XPath.selectNodes(doc, ".//ioos:Quantity");
      if (!varList.isEmpty()) {
        ArrayList<String> vars = new ArrayList<String>(varList.size());
        for (Element e : varList) {
          vars.add(e.getAttributeValue("name"));
        }
        els = new ArrayList(new HashSet(vars));
        properties.setVariableHeaders(els);
      }

    } catch (JDOMException e1) {
      e1.printStackTrace();
    }
  }
  @Test
  public void testOnlyOptional() {
    config.put("optional.foo", "ch1 ch2");
    config.put("optional.zebra", "ch2 ch3");
    selector = ChannelSelectorFactory.create(channels, config);
    Assert.assertTrue(selector instanceof MultiplexingChannelSelector);

    Event event1 = new MockEvent();
    Map<String, String> header1 = new HashMap<String, String>();
    header1.put("myheader", "foo"); // should match ch1 ch2
    event1.setHeaders(header1);

    List<Channel> reqCh1 = selector.getRequiredChannels(event1);
    Assert.assertTrue(reqCh1.isEmpty());
    List<Channel> optCh1 = selector.getOptionalChannels(event1);
    Assert.assertEquals(2, optCh1.size());
    // ch2 should not be there -- since it is a required channel

    Event event4 = new MockEvent();
    Map<String, String> header4 = new HashMap<String, String>();
    header4.put("myheader", "zebra");
    event4.setHeaders(header4);

    List<Channel> reqCh4 = selector.getRequiredChannels(event4);
    Assert.assertTrue(reqCh4.isEmpty());
    List<Channel> optCh4 = selector.getOptionalChannels(event4);
    Assert.assertEquals(2, optCh4.size());
    Assert.assertEquals("ch2", optCh4.get(0).getName());
    Assert.assertEquals("ch3", optCh4.get(1).getName());
  }
  public boolean rulesExist() {

    NodeRef nodeUserHomes = alfrescoUtilsService.getNodeRef("/app:company_home/app:user_homes");

    boolean ruleNodeUserExit = false;
    List<Rule> listRulesExistantes = ruleService.getRules(nodeUserHomes);
    if (null != listRulesExistantes && !listRulesExistantes.isEmpty()) {
      for (Rule ruleExistant : listRulesExistantes) {
        if (ruleExistant.getTitle().equals(CreateRulesWebScript.NOM_REGLE_NODE_USER)) {
          ruleNodeUserExit = true;
        }
      }
    }

    NodeRef nodeSites = alfrescoUtilsService.getNodeRef("/app:company_home/site:sites");

    boolean ruleNodeSitesExit = false;
    listRulesExistantes = ruleService.getRules(nodeSites);
    if (null != listRulesExistantes && !listRulesExistantes.isEmpty()) {
      for (Rule ruleExistant : listRulesExistantes) {
        if (ruleExistant.getTitle().equals(CreateRulesWebScript.NOM_REGLE_SITE_SIRH)) {
          ruleNodeSitesExit = true;
        }
      }
    }

    return ruleNodeSitesExit && ruleNodeUserExit;
  }
Пример #27
0
 @Override
 public void cleanup() {
   endAnimationsForElapsed(durationSeconds());
   if (!waitingAnimations.isEmpty() || !activeAnimations.isEmpty()) {
     throw new IllegalStateException();
   }
 }
Пример #28
0
  public static List<? extends PsiElement> resolveSimpleReference(
      PsiElement scopeElement, String name) {
    final List<DartComponentName> result = new ArrayList<DartComponentName>();
    // local
    final ResolveScopeProcessor resolveScopeProcessor =
        new ResolveScopeProcessor(result, name, DartResolveUtil.isLValue(scopeElement));
    PsiTreeUtil.treeWalkUp(resolveScopeProcessor, scopeElement, null, new ResolveState());
    // supers
    final DartClass dartClass = PsiTreeUtil.getParentOfType(scopeElement, DartClass.class);
    final boolean inClass =
        PsiTreeUtil.getParentOfType(scopeElement, DartClassBody.class, false) != null;
    if (result.isEmpty() && dartClass != null && inClass) {
      final DartComponent field = filterAccess(scopeElement, dartClass.findMembersByName(name));
      if (field != null) {
        return toResult(field.getComponentName());
      }
    }
    // global
    if (result.isEmpty()) {
      final List<VirtualFile> libraryFiles =
          DartResolveUtil.findLibrary(scopeElement.getContainingFile());
      DartResolveUtil.processTopLevelDeclarations(
          scopeElement, resolveScopeProcessor, libraryFiles, name);
    }
    // dart:core
    if (result.isEmpty() && !"void".equals(name)) {
      final List<VirtualFile> libraryFiles =
          DartLibraryIndex.findLibraryClass(scopeElement, "dart:core");
      DartResolveUtil.processTopLevelDeclarations(
          scopeElement, resolveScopeProcessor, libraryFiles, name);
    }

    return result;
  }
Пример #29
0
  @Override
  public synchronized int temPartida(Integer idJogador) throws RemoteException {
    if (partidas.isEmpty()) return 0;
    if (partidas.size() > 49)
      throw new RemoteException(
          "O jogo atingiu seu limite de 50 partidas simultâneas, por favor tente mais tarde.");

    List<Partida> partidasAux =
        partidas
            .stream()
            .filter(p -> (p.getJogadores() != null && p.getJogadores().size() < 2))
            .collect(Collectors.toList());

    if (partidasAux.isEmpty()) return 0;

    Partida partida = partidasAux.get(0);
    if (partida == null || partida.getJogadores().isEmpty()) return 0;

    partida.getJogadores().add(idJogador);
    partida.setJogadorDaVez(1);

    Jogador jogador = jogadores.get(idJogador);
    jogador.setStatus(0);
    jogador.setOrdemJogada(partida.getJogadores().size());

    return partida.getJogadores().size();
  }
  public static synchronized int[] getIntCache(int par0) {
    int[] aint;

    if (par0 <= 256) {
      if (freeSmallArrays.isEmpty()) {
        aint = new int[256];
        inUseSmallArrays.add(aint);
        return aint;
      } else {
        aint = (int[]) freeSmallArrays.remove(freeSmallArrays.size() - 1);
        inUseSmallArrays.add(aint);
        return aint;
      }
    } else if (par0 > intCacheSize) {
      intCacheSize = par0;
      freeLargeArrays.clear();
      inUseLargeArrays.clear();
      aint = new int[intCacheSize];
      inUseLargeArrays.add(aint);
      return aint;
    } else if (freeLargeArrays.isEmpty()) {
      aint = new int[intCacheSize];
      inUseLargeArrays.add(aint);
      return aint;
    } else {
      aint = (int[]) freeLargeArrays.remove(freeLargeArrays.size() - 1);
      inUseLargeArrays.add(aint);
      return aint;
    }
  }