/**
   * Start at the given nesting level - read lines until you get to line with equal to or greater
   * than the current one.
   */
  public static String[] getArtifactLines(Pointer startingIndex, String... lines) {
    List<String> lineList = new ArrayList<>();
    int index = startingIndex.getIndex();
    String topLine = lines[index];

    lineList.add(
        topLine); // add the line which defines this object - all others, if they exist, are
                  // children.

    int nestingLevel = parseNestingLevel(topLine);

    for (int i = index + 1; i < lines.length; i++) {
      String line = lines[i];

      // we return if the nesting level of the line in question is the same as the "parent" level
      int childNestingLevel = parseNestingLevel(line);

      if (childNestingLevel == nestingLevel) {
        startingIndex.increment(lineList.size());

        // return new array of startIndex to i
        return lineList.toArray(new String[lineList.size()]);
      } else {
        lineList.add(line);
      }
    }

    startingIndex.increment(lineList.size());

    return lineList.toArray(new String[lineList.size()]);
  }
Пример #2
0
  protected int call(Process process, ObjectName objectName, MBeanOperationInfo operationInfo)
      throws ReflectionException, InstanceNotFoundException, MBeanException {
    List<Object> params = new ArrayList<Object>();
    List<String> sig = new ArrayList<String>();
    MBeanParameterInfo[] signature = operationInfo.getSignature();

    for (int i = 0; i < signature.length; i += 1) {
      try {
        params.add(convert(signature[i].getType(), process.args.consumeString()));
        sig.add(signature[i].getType());
      } catch (Exception e) {
        throw new ArgumentException(
            String.format("Invalid argument #%d: %s", (i + 1), e.toString()));
      }
    }

    Object result =
        server.invoke(
            objectName,
            operationInfo.getName(),
            params.toArray(),
            sig.toArray(new String[sig.size()]));

    if ("void".equals(operationInfo.getReturnType())) {
      process.out.println("Invocation successful.");
    } else {
      process.out.println(toString(result));
    }

    return -1;
  }
Пример #3
0
  /**
   * Scales the given string array.
   *
   * @param values
   * @param length The resulting length
   * @return
   */
  private String[] getScaledValues(String[] values, int length) {

    // Init
    AggregateFunction<String> function =
        AggregateFunction.forType(DataType.STRING).createSetFunction();
    double factor = (double) length / (double) values.length;
    String[] result = new String[length];

    // Aggregate
    int previous = 0;
    List<String> toAggregate = new ArrayList<String>();
    for (int i = 0; i < values.length; i++) {

      checkInterrupt();

      int index = (int) Math.round((double) i * factor);
      index = index < length ? index : length - 1;

      if (index != previous) {
        result[previous] = function.aggregate(toAggregate.toArray(new String[toAggregate.size()]));
        toAggregate.clear();
        previous = index;
      }
      toAggregate.add(values[i]);
    }

    result[length - 1] = function.aggregate(toAggregate.toArray(new String[toAggregate.size()]));
    return result;
  }
  public String[] getOrderedTags(
      List<String> words, List<String> tags, int index, double[] tprobs) {

    if (modelPackage.getPosModel() != null) {

      MaxentModel posModel = modelPackage.getPosModel();

      double[] probs =
          posModel.eval(
              contextGen.getContext(
                  index,
                  words.toArray(new String[words.size()]),
                  tags.toArray(new String[tags.size()]),
                  null));

      String[] orderedTags = new String[probs.length];
      for (int i = 0; i < probs.length; i++) {
        int max = 0;
        for (int ti = 1; ti < probs.length; ti++) {
          if (probs[ti] > probs[max]) {
            max = ti;
          }
        }
        orderedTags[i] = posModel.getOutcome(max);
        if (tprobs != null) {
          tprobs[i] = probs[max];
        }
        probs[max] = 0;
      }
      return orderedTags;
    } else {
      throw new UnsupportedOperationException(
          "This method can only be called if the " + "classifcation model is an event model!");
    }
  }
Пример #5
0
  /**
   * Checks if the two entries represent the same publication.
   *
   * @param one BibEntry
   * @param two BibEntry
   * @return boolean
   */
  public static boolean isDuplicate(BibEntry one, BibEntry two, BibDatabaseMode bibDatabaseMode) {

    // First check if they are of the same type - a necessary condition:
    if (!one.getType().equals(two.getType())) {
      return false;
    }
    EntryType type = EntryTypes.getTypeOrDefault(one.getType(), bibDatabaseMode);

    // The check if they have the same required fields:
    java.util.List<String> var = type.getRequiredFieldsFlat();
    String[] fields = var.toArray(new String[var.size()]);
    double[] req;
    if (fields == null) {
      req = new double[] {0., 0.};
    } else {
      req = DuplicateCheck.compareFieldSet(fields, one, two);
    }

    if (Math.abs(req[0] - DuplicateCheck.duplicateThreshold) > DuplicateCheck.DOUBT_RANGE) {
      // Far from the threshold value, so we base our decision on the req. fields only
      return req[0] >= DuplicateCheck.duplicateThreshold;
    }
    // Close to the threshold value, so we take a look at the optional fields, if any:
    java.util.List<String> optionalFields = type.getOptionalFields();
    fields = optionalFields.toArray(new String[optionalFields.size()]);
    if (fields != null) {
      double[] opt = DuplicateCheck.compareFieldSet(fields, one, two);
      double totValue =
          ((DuplicateCheck.REQUIRED_WEIGHT * req[0] * req[1]) + (opt[0] * opt[1]))
              / ((req[1] * DuplicateCheck.REQUIRED_WEIGHT) + opt[1]);
      return totValue >= DuplicateCheck.duplicateThreshold;
    }
    return req[0] >= DuplicateCheck.duplicateThreshold;
  }
Пример #6
0
  @Test
  public void testToString() {
    List<Integer> is = new ArrayList<>();
    is.add(1);
    is.add(2);
    is.add(3);
    is.add(4);
    is.add(5);
    assertEquals("Array<Integer>(1,2,3,4,5)", FunctionUtils.toString(is.toArray()));

    is.add(6);
    assertEquals("Array<Integer>(1,2,3,4,5,...)", FunctionUtils.toString(is.toArray()));

    Map<String, Integer> m = new TreeMap<>();
    m.put("Hello", 99);
    m.put("World", -237);
    assertEquals("TreeMap(Entry(Hello,99),Entry(World,-237))", FunctionUtils.toString(m));

    m.put("x", 3);
    m.put("y", 2);
    m.put("z", 1);
    m.put("zz", 0);

    assertEquals(
        "TreeMap(Entry(Hello,99),Entry(World,-237),Entry(x,3),Entry(y,2),Entry(z,1),...)",
        FunctionUtils.toString(m));
  }
  public Object[] getChildren(Object parentElement) {
    Object[] result = new Object[0];

    if (parentElement instanceof String) {
      if (BndEditor.COMPONENTS_PAGE.equals(parentElement)) {
        Collection<ServiceComponent> components = model.getServiceComponents();
        if (components != null)
          result = components.toArray(new ServiceComponent[components.size()]);
      } else if (EXPORTS.equals(parentElement)) {
        List<ExportedPackage> exports = model.getExportedPackages();
        if (exports != null) result = exports.toArray(new Object[exports.size()]);
      } else if (PRIVATE_PKGS.equals(parentElement)) {
        List<String> packages = model.getPrivatePackages();
        if (packages != null) {
          List<PrivatePkg> wrapped = new ArrayList<PrivatePkg>(packages.size());
          for (String pkg : packages) {
            wrapped.add(new PrivatePkg(pkg));
          }
          result = wrapped.toArray(new Object[wrapped.size()]);
        }
      } else if (IMPORT_PATTERNS.equals(parentElement)) {
        List<ImportPattern> imports = model.getImportPatterns();
        if (imports != null) result = imports.toArray(new Object[imports.size()]);
      }
    }
    return result;
  }
Пример #8
0
 /**
  * Create a new client mode SSL engine, configured from an option map.
  *
  * @param sslContext the SSL context
  * @param optionMap the SSL options
  * @param peerAddress the peer address of the connection
  * @return the configured SSL engine
  */
 public static SSLEngine createSSLEngine(
     SSLContext sslContext, OptionMap optionMap, InetSocketAddress peerAddress) {
   final SSLEngine engine =
       sslContext.createSSLEngine(
           optionMap.get(Options.SSL_PEER_HOST_NAME, getHostNameNoResolve(peerAddress)),
           optionMap.get(Options.SSL_PEER_PORT, peerAddress.getPort()));
   engine.setUseClientMode(true);
   engine.setEnableSessionCreation(optionMap.get(Options.SSL_ENABLE_SESSION_CREATION, true));
   final Sequence<String> cipherSuites = optionMap.get(Options.SSL_ENABLED_CIPHER_SUITES);
   if (cipherSuites != null) {
     final Set<String> supported =
         new HashSet<String>(Arrays.asList(engine.getSupportedCipherSuites()));
     final List<String> finalList = new ArrayList<String>();
     for (String name : cipherSuites) {
       if (supported.contains(name)) {
         finalList.add(name);
       }
     }
     engine.setEnabledCipherSuites(finalList.toArray(new String[finalList.size()]));
   }
   final Sequence<String> protocols = optionMap.get(Options.SSL_ENABLED_PROTOCOLS);
   if (protocols != null) {
     final Set<String> supported =
         new HashSet<String>(Arrays.asList(engine.getSupportedProtocols()));
     final List<String> finalList = new ArrayList<String>();
     for (String name : protocols) {
       if (supported.contains(name)) {
         finalList.add(name);
       }
     }
     engine.setEnabledProtocols(finalList.toArray(new String[finalList.size()]));
   }
   return engine;
 }
Пример #9
0
  @Override
  public void RemoveStoredKeyValuePairs(String[] keynames) {
    List<String> successfullKeyPairs = new ArrayList<String>();
    List<String> failedKeyPairs = new ArrayList<String>();
    SharedPreferences settings = GetOtherAppSharedPreferences();
    if (settings != null) {
      for (String keyname : keynames) {
        if (settings.contains(keyname)) {
          Editor ed = settings.edit();
          ed.remove(keyname);
          ed.commit();
          successfullKeyPairs.add(keyname);
        } else failedKeyPairs.add(keyname);
      }
    } else {
      LOGGER.logError("RemoveStoredKeyValuePairs", "Storage Unit is null.");
    }

    LOGGER.logInfo(
        "RemoveStoredKeyValuePairs",
        "Keys removed from storage unit: "
            + successfullKeyPairs.size()
            + "; Keys Not removed from storage unit: "
            + failedKeyPairs.size());
    IActivityManager am =
        (IActivityManager)
            AndroidServiceLocator.GetInstance()
                .GetService(AndroidServiceLocator.SERVICE_ANDROID_ACTIVITY_MANAGER);
    am.executeJS(
        "Unity.OnKeyValuePairsRemoveCompleted",
        new Object[] {successfullKeyPairs.toArray(), failedKeyPairs.toArray()});
  }
Пример #10
0
  private void processFormLoadBindings(Component comp, String formId, Annotation ann) {
    String loadExpr = null;
    final List<String> beforeCmds = new ArrayList<String>();
    final List<String> afterCmds = new ArrayList<String>();

    Map<String, String[]> args = null;
    for (final Iterator<Entry<String, String[]>> it = ann.getAttributes().entrySet().iterator();
        it.hasNext(); ) {
      final Entry<String, String[]> entry = it.next();
      final String tag = entry.getKey();
      final String[] tagExpr = entry.getValue();
      if ("value".equals(tag)) {
        loadExpr = testString(comp, formId, tag, tagExpr);
      } else if ("before".equals(tag)) {
        addCommand(comp, beforeCmds, tagExpr);
      } else if ("after".equals(tag)) {
        addCommand(comp, afterCmds, tagExpr);
      } else { // other unknown tag, keep as arguments
        if (args == null) {
          args = new HashMap<String, String[]>();
        }
        args.put(tag, tagExpr);
      }
    }
    final Map<String, Object> parsedArgs = args == null ? null : parsedArgs(args);
    _binder.addFormLoadBindings(
        comp,
        formId,
        loadExpr,
        beforeCmds.size() == 0 ? null : beforeCmds.toArray(new String[beforeCmds.size()]),
        afterCmds.size() == 0 ? null : afterCmds.toArray(new String[afterCmds.size()]),
        parsedArgs);
  }
  private void updateWorkspace() {
    String name =
        availableWorkspacesListBox.getItemText(availableWorkspacesListBox.getSelectedIndex());

    List<String> selectedModulesList = new ArrayList<String>(selectedModulesListBox.getItemCount());
    for (int i = 0; i < selectedModulesListBox.getItemCount(); i++) {
      selectedModulesList.add(selectedModulesListBox.getItemText(i));
    }
    List<String> availableModuleList =
        new ArrayList<String>(availableModulesListBox.getItemCount());
    for (int i = 0; i < availableModulesListBox.getItemCount(); i++) {
      availableModuleList.add(availableModulesListBox.getItemText(i));
    }
    availableModuleList.removeAll(selectedModulesList);
    LoadingPopup.showMessage(constants.LoadingStatuses());

    repositoryService.updateWorkspace(
        name,
        selectedModulesList.toArray(new String[selectedModulesList.size()]),
        availableModuleList.toArray(new String[availableModuleList.size()]),
        new GenericCallback<java.lang.Void>() {
          public void onSuccess(Void v) {
            Window.alert(constants.WorkspaceUpdated());
            refreshWorkspaceList();
          }
        });
  }
Пример #12
0
  public Object load() {
    Object result = new JSONArray();

    try {
      GenericBasicFileFilter jsonFilter = new GenericBasicFileFilter(null, ".cdfde");

      List<IBasicFile> defaultTemplatesList =
          CdeEnvironment.getPluginSystemReader(SYSTEM_CDF_DD_TEMPLATES)
              .listFiles(null, jsonFilter, IReadAccess.DEPTH_ALL);

      if (defaultTemplatesList != null) {
        loadFiles(defaultTemplatesList.toArray(new IBasicFile[] {}), (JSONArray) result, "default");
      } else {
        result = Messages.getString("CdfTemplates.ERROR_002_LOADING_TEMPLATES_EXCEPTION");
      }

      List<IBasicFile> customTemplatesList =
          CdeEnvironment.getPluginRepositoryReader(REPOSITORY_CDF_DD_TEMPLATES_CUSTOM)
              .listFiles(null, jsonFilter, IReadAccess.DEPTH_ALL);
      if (customTemplatesList != null) {
        loadFiles(customTemplatesList.toArray(new IBasicFile[] {}), (JSONArray) result, "custom");
      }

    } catch (IOException e) {
      logger.error(e);
      result = Messages.getString("CdfTemplates.ERROR_002_LOADING_EXCEPTION");
    }
    return result;
  }
Пример #13
0
 public void start(DataInputStream in, OutputStream out, String[] parameters) throws Exception {
   boolean go = false;
   List /* <String> */ stagerParameters = new ArrayList();
   List /* <String> */ currentParameters = new ArrayList();
   for (int i = 0; i < parameters.length; i++) {
     if (!go) {
       stagerParameters.add(parameters[i]);
       if (parameters[i].equals("--")) {
         go = true;
         i++;
       }
       continue;
     }
     if (parameters[i].equals("---")) {
       currentParameters.addAll(0, stagerParameters);
       String[] params =
           (String[]) currentParameters.toArray(new String[currentParameters.size()]);
       currentParameters.clear();
       byte[] bytes = new byte[in.readInt()];
       in.readFully(bytes);
       new MultiStageClassLoader(
           params, new ByteArrayInputStream(bytes), new ByteArrayOutputStream(), true);
     } else if (parameters[i].startsWith("---")) {
       currentParameters.add(parameters[i].substring(1));
     } else {
       currentParameters.add(parameters[i]);
     }
   }
   currentParameters.addAll(0, stagerParameters);
   String[] params = (String[]) currentParameters.toArray(new String[currentParameters.size()]);
   new MultiStageClassLoader(params, in, out, false);
 }
 // Prepares and adds channels to list for selection
 private void prepareChannels() {
   readableFDs.add(sourcefd);
   List<SelectionKey> readChannelList = new ArrayList<SelectionKey>();
   readChannelList.add(source.keyFor(this));
   List<SelectionKey> writeChannelList = new ArrayList<SelectionKey>();
   synchronized (keysLock) {
     for (Iterator<SelectionKey> i = keys.iterator(); i.hasNext(); ) {
       SelectionKeyImpl key = (SelectionKeyImpl) i.next();
       key.oldInterestOps = key.interestOps();
       boolean isReadableChannel =
           ((SelectionKey.OP_ACCEPT | SelectionKey.OP_READ) & key.oldInterestOps) != 0;
       boolean isWritableChannel =
           ((SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE) & key.oldInterestOps) != 0;
       SelectableChannel channel = key.channel();
       if (isReadableChannel) {
         readChannelList.add(channel.keyFor(this));
         readableFDs.add(((FileDescriptorHandler) channel).getFD());
       }
       if (isWritableChannel) {
         writeChannelList.add(channel.keyFor(this));
         writableFDs.add(((FileDescriptorHandler) channel).getFD());
       }
     }
   }
   readableChannels = readChannelList.toArray(new SelectionKey[0]);
   writableChannels = writeChannelList.toArray(new SelectionKey[0]);
   readable = readableFDs.toArray(new FileDescriptor[0]);
   writable = writableFDs.toArray(new FileDescriptor[0]);
 }
  @Override
  public PhysicalOperator getPhysicalOperator(PhysicalPlanCreator creator) throws IOException {
    // Prel child = (Prel) this.getChild();

    final List<String> childFields = getChild().getRowType().getFieldNames();
    final List<String> fields = getRowType().getFieldNames();
    List<NamedExpression> keys = Lists.newArrayList();
    List<NamedExpression> exprs = Lists.newArrayList();

    for (int group : BitSets.toIter(groupSet)) {
      FieldReference fr = new FieldReference(childFields.get(group), ExpressionPosition.UNKNOWN);
      keys.add(new NamedExpression(fr, fr));
    }

    for (Ord<AggregateCall> aggCall : Ord.zip(aggCalls)) {
      FieldReference ref = new FieldReference(fields.get(groupSet.cardinality() + aggCall.i));
      LogicalExpression expr = toDrill(aggCall.e, childFields, new DrillParseContext());
      exprs.add(new NamedExpression(expr, ref));
    }

    Prel child = (Prel) this.getChild();
    StreamingAggregate g =
        new StreamingAggregate(
            child.getPhysicalOperator(creator),
            keys.toArray(new NamedExpression[keys.size()]),
            exprs.toArray(new NamedExpression[exprs.size()]),
            1.0f);

    return g;
  }
Пример #16
0
 @Override
 public void StoreKeyValuePairs(KeyPair[] keypairs) {
   List<String> successfullKeyPairs = new ArrayList<String>();
   List<String> failedKeyPairs = new ArrayList<String>();
   SharedPreferences settings = GetOtherAppSharedPreferences();
   if (settings != null) {
     for (int i = 0; i < keypairs.length; i++) {
       try {
         String keyname = keypairs[i].getKey();
         String keyvalue = keypairs[i].getValue();
         Editor ed = settings.edit();
         ed.putString(keyname, keyvalue);
         ed.commit();
         successfullKeyPairs.add(keyname);
       } catch (Exception ex) {
         failedKeyPairs.add(keypairs[i].getKey());
       }
     }
   } else {
     LOGGER.logError("StoreKeyValuePairs", "Storage Unit is null.");
   }
   LOGGER.logInfo(
       "StoredKeyValuePairs",
       "Key stored in storage unit: "
           + successfullKeyPairs.size()
           + "; Keys Not stored in storage unit: "
           + failedKeyPairs.size());
   IActivityManager am =
       (IActivityManager)
           AndroidServiceLocator.GetInstance()
               .GetService(AndroidServiceLocator.SERVICE_ANDROID_ACTIVITY_MANAGER);
   am.executeJS(
       "Unity.OnKeyValuePairsStoreCompleted",
       new Object[] {successfullKeyPairs.toArray(), failedKeyPairs.toArray()});
 }
Пример #17
0
    protected void clausify(
        OWLAxioms.DisjunctiveRule rule, boolean restrictToNamed, OWLAxiom originalAxiom) {
      m_headAtoms.clear();
      m_bodyAtoms.clear();
      m_abstractVariables.clear();
      for (SWRLAtom atom : rule.m_body) m_bodyAtoms.add(atom.accept(this));
      for (SWRLAtom atom : rule.m_head) m_headAtoms.add(atom.accept(this));
      if (restrictToNamed) {
        for (Variable variable : m_abstractVariables)
          m_bodyAtoms.add(Atom.create(AtomicConcept.INTERNAL_NAMED, variable));
      }
      DLClause dlClause =
          DLClause.create(
              m_headAtoms.toArray(new Atom[m_headAtoms.size()]),
              m_bodyAtoms.toArray(new Atom[m_bodyAtoms.size()]));

      Collection<OWLAxiom> originalAxioms = m_dlClauses_map.get(dlClause);
      if (originalAxioms == null) {
        originalAxioms = new ArrayList<OWLAxiom>();
        m_dlClauses_map.put(dlClause, originalAxioms);
      }
      originalAxioms.add(originalAxiom);

      m_headAtoms.clear();
      m_bodyAtoms.clear();
      m_abstractVariables.clear();
    }
  @Override
  protected IContributionItem[] getItems() {

    Object selection = contextProvider.getContext().get(ESelectionService.class).getSelection();
    if (!(selection instanceof IBindingManager) || !((IBindingManager) selection).wIsSet("self"))
      return new IContributionItem[0];

    IBindingManager bm = (IBindingManager) selection;
    String languageURI = bm.wGet("self").wGetLanguageKit().getURI();

    Map<GuardedAction, String> actionsMap = new HashMap<GuardedAction, String>();
    IResourceRegistry<Resource> registry = ActionsRegistry.instance();
    for (IResource resource : registry.getResources(false)) {
      LanguageActionFactory actionsModule = resource.getEntity();
      URI targetLanguage = actionsModule.getTargetLanguage();
      if (DataTypeUtils.getDataKind(targetLanguage).isString()
          && !languageURI.equals(targetLanguage.getValue())) continue;

      for (GuardedAction guardedAction :
          Matcher.findAll(
              ActionsEntityDescriptorEnum.GuardedAction, getActions(actionsModule), false)) {
        String actionName = guardedAction.getName().getValue();
        String functionUri = resource.getURI() + '#' + actionName;
        actionsMap.put(guardedAction, functionUri);
      }
    }

    List<IAction> actions = new ArrayList<IAction>();
    List<GuardedAction> guardedActions = new ArrayList<GuardedAction>(actionsMap.keySet());
    Collections.sort(
        guardedActions,
        new Comparator<GuardedAction>() {
          public int compare(GuardedAction a1, GuardedAction a2) {
            return a1.getName().getValue().compareTo(a2.getName().getValue());
          }
        });

    for (GuardedAction guardedAction : guardedActions) {
      String actionName = guardedAction.getName().getValue();
      String functionUri = actionsMap.get(guardedAction);
      IUpdatableAction action =
          contextProvider
              .getActionRegistry()
              .getActionFactory()
              .createActionCallAction(
                  actionName, isAnalyze(), guardedAction.getEnablerPredicate(), functionUri);
      action.update();
      actions.add(action);
    }

    List<IContributionItem> items = new ArrayList<IContributionItem>();
    HierarchicalFillMenuStrategy.instance()
        .fillMenu(
            ActionListContainer.create(items),
            ActionSet.create(actions.toArray(new IAction[actions.size()])),
            0,
            actions.size());

    return items.toArray(new IContributionItem[items.size()]);
  }
  /**
   * @see org.openmrs.logic.Rule#eval(org.openmrs.logic.LogicContext, java.lang.Integer,
   *     java.util.Map)
   */
  public Result eval(LogicContext context, Integer patientId, Map<String, Object> parameters)
      throws LogicException {
    Integer index = null;
    List<Result> results = null;
    Result distinctResult = null;

    if (parameters != null) {
      Object param1Obj = parameters.get("param1");
      if (param1Obj != null) {
        index = Integer.parseInt((String) param1Obj);
      }

      results = (List<Result>) parameters.get("param2");
    }

    if (index != null && results != null && index < results.toArray().length) {
      // Sort the results by date
      Collections.sort(results, new ResultDateComparator());
      // Reverse the list
      Collections.reverse(results);
      distinctResult = (Result) results.toArray()[index];
    }

    if (distinctResult == null) {
      distinctResult = new Result();
    }

    if (distinctResult.toString() == null) {
      distinctResult.setValueText(String.valueOf(distinctResult.toNumber()));
    }

    return distinctResult;
  }
    private void addUserDefinedMethods(TopLevelClass exampleClass, Interface mapperClass, IntrospectedTable introspectedTable, MyBatisClasses cls) {
        for (Method action : mapperClass.getMethods()) {
            if (!userDefinedMethods.matcher(action.getName()).matches()) continue;
            StringBuilder args = new StringBuilder();
            List<Parameter> params = new ArrayList<Parameter>();
            boolean example = false;
            if (action.getParameters() != null)
                for (Parameter param : action.getParameters()) {
                    String name;
                    if (Objects.equals(param.getType(), exampleClass.getType())) {
                        example = true;
                        name = "this";
                    } else {
                        name = param.getName();
                        params.add(new Parameter(param.getType(), name));
                    }
                    if (args.length() > 0)
                        args.append(", ");
                    args.append(name);
                }
            if (!example) {
                //System.err.println("Invalid user-defined mapper method: "+action.getName());
                continue;
            }

            exampleClass.addMethod(method(
                PUBLIC, INT, action.getName(), _(sqlSession, "sql"), params.toArray(new Parameter[params.size()]), __(
                    "return sql.getMapper(" + cls.names.mapper + ".class)."+action.getName()+"("+args+");"
            )));
            exampleClass.addMethod(method(
                PUBLIC, INT, action.getName(), _(cls.types.mapper, "mapper"), params.toArray(new Parameter[params.size()]), __(
                    "return mapper."+action.getName()+"("+args+");"
            )));
        }
    }
Пример #21
0
  @Override
  protected JPopupMenu createPopup(Point p) {
    final List<Node> selectedElements = elementsDataTable.getElementsFromSelectedRows();
    final Node clickedElement = elementsDataTable.getElementFromRow(table.rowAtPoint(p));
    JPopupMenu contextMenu = new JPopupMenu();

    // First add edges manipulators items:
    DataLaboratoryHelper dlh = DataLaboratoryHelper.getDefault();
    Integer lastManipulatorType = null;
    for (NodesManipulator em : dlh.getNodesManipulators()) {
      em.setup(selectedElements.toArray(new Node[0]), clickedElement);
      if (lastManipulatorType == null) {
        lastManipulatorType = em.getType();
      }
      if (lastManipulatorType != em.getType()) {
        contextMenu.addSeparator();
      }
      lastManipulatorType = em.getType();
      if (em.isAvailable()) {
        contextMenu.add(
            PopupMenuUtils.createMenuItemFromNodesManipulator(
                em, clickedElement, selectedElements.toArray(new Node[0])));
      }
    }

    // Add AttributeValues manipulators submenu:
    Column column = elementsDataTable.getColumnAtIndex(table.columnAtPoint(p));
    if (column != null) {
      contextMenu.add(PopupMenuUtils.createSubMenuFromRowColumn(clickedElement, column));
    }
    return contextMenu;
  }
  private void doTestEARResourceRetrieval(boolean recursive, String rootDir) {
    ModuleClassLoader classLoader = (ModuleClassLoader) getClass().getClassLoader();
    List<String> foundResources =
        ResourceListingUtils.listResources(classLoader, rootDir, recursive);

    // only resources in EAR library should be listed
    List<String> resourcesInDeployment = new ArrayList<>();
    resourcesInDeployment.add(ResourceListingUtils.classToPath(EarResourceListingTestCase.class));
    resourcesInDeployment.add(ResourceListingUtils.classToPath(ResourceListingUtils.class));
    resourcesInDeployment.add("META-INF/emptyJarLibResource.properties");
    resourcesInDeployment.add("META-INF/properties/nestedJarLib.properties");

    ResourceListingUtils.filterResources(resourcesInDeployment, rootDir, !recursive);

    Collections.sort(foundResources);
    Collections.sort(resourcesInDeployment);

    log.info("List of expected resources:");
    for (String expectedResource : resourcesInDeployment) {
      log.info(expectedResource);
    }
    log.info("List of found resources: ");
    for (String foundResource : foundResources) {
      log.info(foundResource);
    }

    Assert.assertArrayEquals(
        "Not all resources from EAR archive are correctly listed",
        resourcesInDeployment.toArray(),
        foundResources.toArray());
  }
Пример #23
0
  public static DataSchema extractDataSchema(
      List<SelectionSort> sortSequence, List<String> selectionColumns, IndexSegment indexSegment) {
    final List<String> columns = new ArrayList<String>();

    if (sortSequence != null && !sortSequence.isEmpty()) {
      for (final SelectionSort selectionSort : sortSequence) {
        columns.add(selectionSort.getColumn());
      }
    }
    String[] selectionColumnArray = selectionColumns.toArray(new String[selectionColumns.size()]);
    Arrays.sort(selectionColumnArray);
    for (int i = 0; i < selectionColumnArray.length; ++i) {
      String selectionColumn = selectionColumnArray[i];
      if (!columns.contains(selectionColumn)) {
        columns.add(selectionColumn);
      }
    }
    final DataType[] dataTypes = new DataType[columns.size()];
    for (int i = 0; i < dataTypes.length; ++i) {
      DataSource ds = indexSegment.getDataSource(columns.get(i));
      DataSourceMetadata m = ds.getDataSourceMetadata();
      dataTypes[i] = m.getDataType();
      if (!m.isSingleValue()) {
        dataTypes[i] = DataType.valueOf(dataTypes[i] + "_ARRAY");
      }
    }
    return new DataSchema(columns.toArray(new String[0]), dataTypes);
  }
Пример #24
0
  public MInfoColumn[] getInfoColumns(boolean requery, boolean checkDisplay) {
    if ((this.m_infocolumns != null) && (!requery)) {
      set_TrxName(this.m_infocolumns, get_TrxName());
      return this.m_infocolumns;
    }
    if (checkDisplay) {
      List<MInfoColumn> list =
          new Query(
                  getCtx(),
                  MInfoColumn.Table_Name,
                  "AD_InfoWindow_ID=? AND IsDisplayed='Y'",
                  get_TrxName())
              .setParameters(get_ID())
              .setOrderBy("SeqNo")
              .list();
      this.m_infocolumns = list.toArray(new MInfoColumn[list.size()]);
    } else {
      List<MInfoColumn> list =
          new Query(getCtx(), MInfoColumn.Table_Name, "AD_InfoWindow_ID=?", get_TrxName())
              .setParameters(get_ID())
              .setOrderBy("SeqNo")
              .list();
      this.m_infocolumns = list.toArray(new MInfoColumn[list.size()]);
    }

    return this.m_infocolumns;
  }
Пример #25
0
  public void recordHits(Hits hits, long groupId, boolean privateLayout) throws Exception {

    setSearcher(((HitsImpl) hits).getSearcher());

    // This can later be optimized according to LEP-915.

    List docs = new ArrayList(hits.getLength());
    List scores = new ArrayList(hits.getLength());

    for (int i = 0; i < hits.getLength(); i++) {
      Document doc = hits.doc(i);

      String articleId = doc.get("articleId");
      long articleGroupId = GetterUtil.getLong(doc.get(LuceneFields.GROUP_ID));

      if (JournalContentSearchLocalServiceUtil.getLayoutIdsCount(groupId, privateLayout, articleId)
          > 0) {

        docs.add(hits.doc(i));
        scores.add(new Float(hits.score(i)));
      } else if (!isShowListed() && (articleGroupId == groupId)) {
        docs.add(hits.doc(i));
        scores.add(new Float(hits.score(i)));
      }
    }

    setLength(docs.size());
    setDocs((Document[]) docs.toArray(new Document[0]));
    setScores((Float[]) scores.toArray(new Float[0]));

    setSearchTime((float) (System.currentTimeMillis() - getStart()) / Time.SECOND);
  }
Пример #26
0
  @Test
  public void testNForIndicesMatchThoseOfActualForLoop() throws Exception {
    List<Integer[]> fromActualLoopList = new ArrayList<>();
    for (Integer i = -5; i < 3; i++) {
      for (Integer j = 0; j >= -6; j--) {
        for (Integer k = 4; k != 10; k += 2) {
          for (Integer l = -1; l > -9; l -= 3) {
            fromActualLoopList.add(new Integer[] {i, j, k, l});
          }
        }
      }
    }

    List<Integer[]> fromNForLoopList = new ArrayList<>();
    NFor<Integer> nfor =
        NFor.of(Integer.class)
            .from(-5, 0, 4, -1)
            .by(1, -1, 2, -3)
            .to(lessThan(3), greaterThanOrEqualTo(-6), notEqualTo(10), greaterThan(-9));
    for (Integer[] indices : nfor) {
      fromNForLoopList.add(indices);
    }

    Assert.assertEquals(
        "Lengths did not match", fromActualLoopList.size(), fromNForLoopList.size());
    Assert.assertArrayEquals(
        "Values did not match", fromActualLoopList.toArray(), fromNForLoopList.toArray());
  }
Пример #27
0
 /**
  * @param types
  * @param type
  * @param worlds worlds or null for all
  * @return All entities of this type in the given worlds
  */
 @SuppressWarnings({"null", "unchecked"})
 public static final <E extends Entity> E[] getAll(
     final EntityData<?>[] types, final Class<E> type, @Nullable World[] worlds) {
   assert types.length > 0;
   if (type == Player.class) {
     if (worlds == null
         && types.length == 1
         && types[0] instanceof PlayerData
         && ((PlayerData) types[0]).op == 0) return (E[]) Bukkit.getOnlinePlayers();
     final List<Player> list = new ArrayList<Player>();
     for (final Player p : Bukkit.getOnlinePlayers()) {
       if (worlds != null && !CollectionUtils.contains(worlds, p.getWorld())) continue;
       for (final EntityData<?> t : types) {
         if (t.isInstance(p)) {
           list.add(p);
           break;
         }
       }
     }
     return (E[]) list.toArray(new Player[list.size()]);
   }
   final List<E> list = new ArrayList<E>();
   if (worlds == null) worlds = Bukkit.getWorlds().toArray(new World[0]);
   for (final World w : worlds) {
     for (final E e : w.getEntitiesByClass(type)) {
       for (final EntityData<?> t : types) {
         if (t.isInstance(e)) {
           list.add(e);
           break;
         }
       }
     }
   }
   return list.toArray((E[]) Array.newInstance(type, list.size()));
 }
  @Test
  public void canCreateHTMLHybridApplication() {
    // Project is created within setup method
    assertTrue(new ProjectExplorer().containsProject(CORDOVA_PROJECT_NAME));
    // Check there is no error/warning on Hybrid Mobile Project
    new ProjectExplorer().selectProjects(CORDOVA_PROJECT_NAME);

    ProblemsView pview = new ProblemsView();
    pview.open();

    List<Problem> errors =
        pview.getProblems(
            ProblemType.ERROR,
            new ProblemsPathMatcher(new RegexMatcher("(/" + CORDOVA_PROJECT_NAME + "/)(.*)")));
    List<Problem> warnings =
        pview.getProblems(
            ProblemType.WARNING,
            new ProblemsPathMatcher(new RegexMatcher("(/" + CORDOVA_PROJECT_NAME + "/)(.*)")));

    assertTrue(
        "There were these errors for "
            + CORDOVA_PROJECT_NAME
            + " project "
            + Arrays.toString(errors.toArray()),
        errors == null || errors.size() == 0);

    assertTrue(
        "There were these warnings for "
            + CORDOVA_PROJECT_NAME
            + " project "
            + Arrays.toString(warnings.toArray()),
        warnings == null || warnings.size() == 0);
  }
  public BoundStatementWrapper bindForUpdate(
      PersistentStateHolder context, PreparedStatement ps, List<PropertyMeta> pms) {
    EntityMeta entityMeta = context.getEntityMeta();
    Object entity = context.getEntity();

    log.trace(
        "Bind prepared statement {} for properties {} update of entity {}",
        ps.getQueryString(),
        pms,
        entity);

    ConsistencyLevel consistencyLevel = overrider.getWriteLevel(context);

    List<Object> values = new ArrayList<>();

    final int staticColumnsCount =
        FluentIterable.from(pms).filter(PropertyMeta.STATIC_COLUMN_FILTER).size();
    final boolean onlyStaticColumns = staticColumnsCount > 0 && pms.size() == staticColumnsCount;

    values.addAll(fetchTTLAndTimestampValues(context));
    values.addAll(fetchPropertiesValues(pms, entity));
    values.addAll(fetchPrimaryKeyValues(entityMeta, entity, onlyStaticColumns));
    values.addAll(fetchCASConditionsValues(context, entityMeta));
    BoundStatement bs = ps.bind(values.toArray());

    return new BoundStatementWrapper(
        context.getEntityClass(),
        bs,
        values.toArray(),
        getCQLLevel(consistencyLevel),
        context.getCASResultListener(),
        context.getSerialConsistencyLevel());
  }
Пример #30
0
  private void updateGeometry() {
    final List<Geometry> geoms = new ArrayList<>();
    if (coords.size() == 1) {
      // single point
      final Geometry geom = GEOMETRY_FACTORY.createPoint(coords.get(0));
      JTS.setCRS(geom, map.getCanvas().getObjectiveCRS2D());
      geoms.add(geom);
    } else if (coords.size() == 2) {
      // line
      final Geometry geom =
          GEOMETRY_FACTORY.createLineString(coords.toArray(new Coordinate[coords.size()]));
      JTS.setCRS(geom, map.getCanvas().getObjectiveCRS2D());
      geoms.add(geom);
    } else if (coords.size() > 2) {
      // polygon
      final Coordinate[] ringCoords = coords.toArray(new Coordinate[coords.size() + 1]);
      ringCoords[coords.size()] = coords.get(0);
      final LinearRing ring = GEOMETRY_FACTORY.createLinearRing(ringCoords);
      final Geometry geom = GEOMETRY_FACTORY.createPolygon(ring, new LinearRing[0]);
      JTS.setCRS(geom, map.getCanvas().getObjectiveCRS2D());
      geoms.add(geom);
    }
    layer.getGeometries().setAll(geoms);

    if (geoms.isEmpty()) {
      uiArea.setText("-");
    } else {
      uiArea.setText(
          NumberFormat.getNumberInstance()
              .format(
                  MeasureUtilities.calculateArea(
                      geoms.get(0), map.getCanvas().getObjectiveCRS2D(), uiUnit.getValue())));
    }
  }