protected boolean sortInfoChanged(List<SortInfo> oldSortInfos, List<SortInfo> newSortInfos) {
   if (oldSortInfos == null && newSortInfos == null) {
     return false;
   } else if (oldSortInfos == null) {
     oldSortInfos = Collections.emptyList();
   } else if (newSortInfos == null) {
     newSortInfos = Collections.emptyList();
   }
   if (oldSortInfos.size() != newSortInfos.size()) {
     return true;
   }
   for (int i = 0; i < oldSortInfos.size(); i++) {
     SortInfo oldSort = oldSortInfos.get(i);
     SortInfo newSort = newSortInfos.get(i);
     if (oldSort == null && newSort == null) {
       continue;
     } else if (oldSort == null || newSort == null) {
       return true;
     }
     if (!oldSort.equals(newSort)) {
       return true;
     }
   }
   return false;
 }
  /**
   * Returns the {@link AccessibilityServiceInfo}s of the enabled accessibility services for a given
   * feedback type.
   *
   * @param feedbackTypeFlags The feedback type flags.
   * @return An unmodifiable list with {@link AccessibilityServiceInfo}s.
   * @see AccessibilityServiceInfo#FEEDBACK_AUDIBLE
   * @see AccessibilityServiceInfo#FEEDBACK_GENERIC
   * @see AccessibilityServiceInfo#FEEDBACK_HAPTIC
   * @see AccessibilityServiceInfo#FEEDBACK_SPOKEN
   * @see AccessibilityServiceInfo#FEEDBACK_VISUAL
   * @see AccessibilityServiceInfo#FEEDBACK_BRAILLE
   */
  public List<AccessibilityServiceInfo> getEnabledAccessibilityServiceList(int feedbackTypeFlags) {
    final IAccessibilityManager service;
    final int userId;
    synchronized (mLock) {
      service = getServiceLocked();
      if (service == null) {
        return Collections.emptyList();
      }
      userId = mUserId;
    }

    List<AccessibilityServiceInfo> services = null;
    try {
      services = service.getEnabledAccessibilityServiceList(feedbackTypeFlags, userId);
      if (DEBUG) {
        Log.i(LOG_TAG, "Installed AccessibilityServices " + services);
      }
    } catch (RemoteException re) {
      Log.e(LOG_TAG, "Error while obtaining the installed AccessibilityServices. ", re);
    }
    if (services != null) {
      return Collections.unmodifiableList(services);
    } else {
      return Collections.emptyList();
    }
  }
  private MethodDeclaration createOptionSetter(PropertyDeclaration property) {
    assert property != null;
    SimpleName paramName = context.createVariableName("option"); // $NON-NLS-1$

    Type optionType = context.getFieldType(property);
    return f.newMethodDeclaration(
        new JavadocBuilder(f)
            .text(
                Messages.getString("ProjectiveModelEmitter.javadocOptionSetter"), // $NON-NLS-1$
                context.getDescription(property))
            .param(paramName)
            .text(
                Messages.getString(
                    "ProjectiveModelEmitter.javadocOptionSetterParameter"), //$NON-NLS-1$
                context.getDescription(property))
            .toJavadoc(),
        new AttributeBuilder(f).toAttributes(),
        Collections.emptyList(),
        context.resolve(void.class),
        context.getOptionSetterName(property),
        Arrays.asList(
            new FormalParameterDeclaration[] {
              f.newFormalParameterDeclaration(optionType, paramName)
            }),
        0,
        Collections.emptyList(),
        null);
  }
Exemplo n.º 4
0
    private void materializeResults(Results r, boolean startOver) throws IOException {
      if (driver.getPlan().getFetchTask() == null) {
        // This query is never going to return anything.
        r.has_more = false;
        r.setData(Collections.<String>emptyList());
        r.setColumns(Collections.<String>emptyList());
        return;
      }

      if (startOver) {
        // This is totally inappropriately reaching into internals.
        driver.getPlan().getFetchTask().initialize(hiveConf, driver.getPlan(), null);
        startRow = 0;
      }

      ArrayList<String> v = new ArrayList<String>();
      r.setData(v);
      r.has_more = driver.getResults(v);
      r.start_row = startRow;
      startRow += v.size();

      r.setColumns(new ArrayList<String>());
      try {
        for (FieldSchema f : driver.getSchema().getFieldSchemas()) {
          r.addToColumns(f.getName());
        }
      } catch (Exception e) {
        // An empty partitioned table may not have table description
        LOG.error("Error getting column names of results.", e);
      }
    }
Exemplo n.º 5
0
 public CaseStageInstanceImpl(String id, String name) {
   this.id = id;
   this.name = name;
   this.adHocFragments = Collections.emptyList();
   this.activeNodes = Collections.emptyList();
   this.status = StageStatus.Active;
 }
Exemplo n.º 6
0
 public static List<Event> delta(
     File baseDirectory, List<File> created, List<File> removed, List<File> modified) {
   if (created == null) {
     created = Collections.emptyList();
   }
   if (removed == null) {
     removed = Collections.emptyList();
   }
   if (modified == null) {
     modified = Collections.emptyList();
   }
   int size = created.size() + removed.size() + modified.size();
   if (size == 0) {
     return null;
   }
   List<Event> delta = new ArrayList<Event>(size);
   for (File file : created) {
     String newPath = Paths.convert(baseDirectory, file);
     delta.add(new Event(newPath, Kind.ENTRY_CREATE));
   }
   for (File file : removed) {
     String deletePath = Paths.convert(baseDirectory, file);
     delta.add(new Event(deletePath, Kind.ENTRY_DELETE));
   }
   for (File file : modified) {
     String changedPath = Paths.convert(baseDirectory, file);
     delta.add(new Event(changedPath, Kind.ENTRY_MODIFY));
   }
   return delta;
 }
Exemplo n.º 7
0
  private List<DEREncodable> listPolicies(X509Certificate eec) throws AuthenticationException {
    byte[] encoded;
    try {
      encoded = getExtensionBytes(eec, OID_CERTIFICATE_POLICIES);
    } catch (IOException e) {
      LOG.warn(
          "Malformed policy extension {}: {}",
          eec.getIssuerX500Principal().getName(),
          e.getMessage());
      return Collections.emptyList();
    }

    if (encoded == null) { // has no Certificate Policies extension.
      return Collections.emptyList();
    }

    Enumeration<DEREncodable> policySource = ASN1Sequence.getInstance(encoded).getObjects();
    List<DEREncodable> policies = new ArrayList();
    while (policySource.hasMoreElements()) {
      DEREncodable policy = policySource.nextElement();
      if (!policy.equals(ANY_POLICY)) {
        policies.add(policy);
      }
    }
    return policies;
  }
Exemplo n.º 8
0
  @Override
  public List<Cookie> loadForRequest(HttpUrl url) {
    // The RI passes all headers. We don't have 'em, so we don't pass 'em!
    Map<String, List<String>> headers = Collections.emptyMap();
    Map<String, List<String>> cookieHeaders;
    try {
      cookieHeaders = cookieHandler.get(url.uri(), headers);
    } catch (IOException e) {
      Internal.logger.log(WARNING, "Loading cookies failed for " + url.resolve("/..."), e);
      return Collections.emptyList();
    }

    List<Cookie> cookies = null;
    for (Map.Entry<String, List<String>> entry : cookieHeaders.entrySet()) {
      String key = entry.getKey();
      if (("Cookie".equalsIgnoreCase(key) || "Cookie2".equalsIgnoreCase(key))
          && !entry.getValue().isEmpty()) {
        for (String header : entry.getValue()) {
          if (cookies == null) cookies = new ArrayList<>();
          cookies.addAll(decodeHeaderAsJavaNetCookies(url, header));
        }
      }
    }

    return cookies != null
        ? Collections.unmodifiableList(cookies)
        : Collections.<Cookie>emptyList();
  }
  @NotNull
  @Override
  public List<? extends GotoRelatedItem> getItems(@NotNull DataContext context) {
    final Editor editor = CommonDataKeys.EDITOR.getData(context);
    final Project project = CommonDataKeys.PROJECT.getData(context);
    final PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(context);
    if (editor == null || element == null || project == null) {
      return Collections.emptyList();
    }

    PsiMethod method = null;
    for (PsiElement e = element; e != null; e = e.getParent()) {
      if (e instanceof PsiMethod) {
        method = (PsiMethod) e;
        break;
      }
    }
    if (method == null) {
      return Collections.emptyList();
    }

    final List<String> testDataFiles = NavigateToTestDataAction.findTestDataFiles(context);
    if (testDataFiles == null || testDataFiles.isEmpty()) {
      return Collections.emptyList();
    }
    return Collections.singletonList(new TestDataRelatedItem(method, editor, testDataFiles));
  }
  @Test
  public void testParsingDispositions() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Admit")
            .get();
    when(emrConceptService.getConcept("test:admit")).thenReturn(admit);
    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.admit",
                "Admit",
                "test:admit",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);
    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Admit"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) Collections.emptyList()));
  }
  @NotNull
  @Override
  public List<? extends SoftWrap> getSoftWrapsForRange(int start, int end) {
    if (!isSoftWrappingEnabled() || end < start) {
      return Collections.emptyList();
    }

    List<? extends SoftWrap> softWraps = myStorage.getSoftWraps();

    int startIndex = myStorage.getSoftWrapIndex(start);
    if (startIndex < 0) {
      startIndex = -startIndex - 1;
      if (startIndex >= softWraps.size() || softWraps.get(startIndex).getStart() > end) {
        return Collections.emptyList();
      }
    }

    int endIndex = myStorage.getSoftWrapIndex(end);
    if (endIndex >= 0) {
      return softWraps.subList(startIndex, endIndex + 1);
    } else {
      endIndex = -endIndex - 1;
      return softWraps.subList(startIndex, endIndex);
    }
  }
Exemplo n.º 12
0
 public List<Label> getLocation() {
   FlowInformation info = flow.getFlowInformation();
   if (info == null) return Collections.emptyList();
   Geography geo = info.getGeography();
   if (geo == null) return Collections.emptyList();
   else return geo.getLocation();
 }
Exemplo n.º 13
0
  private static Collection<FqName> computeSuggestions(@NotNull JetSimpleNameExpression element) {
    final PsiFile file = element.getContainingFile();
    if (!(file instanceof JetFile)) {
      return Collections.emptyList();
    }

    final String referenceName = element.getReferencedName();

    if (!StringUtil.isNotEmpty(referenceName)) {
      return Collections.emptyList();
    }

    assert referenceName != null;

    List<FqName> result = Lists.newArrayList();
    result.addAll(getClassNames(referenceName, (JetFile) file));
    result.addAll(getJetTopLevelFunctions(referenceName, element, file.getProject()));
    result.addAll(getJetExtensionFunctions(referenceName, element, file.getProject()));

    return Collections2.filter(
        result,
        new Predicate<FqName>() {
          @Override
          public boolean apply(@Nullable FqName fqName) {
            assert fqName != null;
            return ImportInsertHelper.doNeedImport(
                new ImportPath(fqName, false), null, (JetFile) file);
          }
        });
  }
  @NotNull
  private static List<RatedResolveResult> resolveInDirectory(
      @NotNull final String referencedName,
      @Nullable final PsiFile containingFile,
      final PsiDirectory dir,
      boolean isFileOnly,
      boolean checkForPackage) {
    final PsiDirectory subdir = dir.findSubdirectory(referencedName);
    if (subdir != null && (!checkForPackage || PyUtil.isPackage(subdir, containingFile))) {
      return ResolveResultList.to(subdir);
    }

    final PsiFile module = findPyFileInDir(dir, referencedName);
    if (module != null) {
      return ResolveResultList.to(module);
    }

    if (!isFileOnly) {
      // not a subdir, not a file; could be a name in parent/__init__.py
      final PsiFile initPy = dir.findFile(PyNames.INIT_DOT_PY);
      if (initPy == containingFile) {
        return Collections.emptyList(); // don't dive into the file we're in
      }
      if (initPy instanceof PyFile) {
        return ((PyFile) initPy).multiResolveName(referencedName);
      }
    }
    return Collections.emptyList();
  }
 @Override
 public List<File> loadInBackground() {
   if (path == null || !path.isDirectory()) return Collections.emptyList();
   final File[] listed_files = path.listFiles();
   if (listed_files == null) return Collections.emptyList();
   final List<File> dirs = new ArrayList<File>();
   final List<File> files = new ArrayList<File>();
   for (final File file : listed_files) {
     if (!file.canRead() || file.isHidden()) {
       continue;
     }
     if (file.isDirectory()) {
       dirs.add(file);
     } else if (file.isFile()) {
       final String name = file.getName();
       final int idx = name.lastIndexOf(".");
       if (extensions == null
           || extensions.length == 0
           || idx == -1
           || idx > -1 && extensions_regex.matcher(name.substring(idx + 1)).matches()) {
         files.add(file);
       }
     }
   }
   Collections.sort(dirs, NAME_COMPARATOR);
   Collections.sort(files, NAME_COMPARATOR);
   final List<File> list = new ArrayList<File>();
   final File parent = path.getParentFile();
   if (path.getParentFile() != null) {
     list.add(parent);
   }
   list.addAll(dirs);
   list.addAll(files);
   return list;
 }
Exemplo n.º 16
0
 private TypeDeclaration createType() {
   SimpleName name = factory.newSimpleName(Naming.getCombineClass());
   importer.resolvePackageMember(name);
   List<TypeBodyDeclaration> members = Lists.create();
   members.addAll(prepareFields());
   members.add(createSetup());
   members.add(createCleanup());
   members.add(createGetRendezvous());
   return factory.newClassDeclaration(
       new JavadocBuilder(factory)
           .text("ステージ{0}の処理を担当するコンバイナープログラム。", shuffle.getStageBlock().getStageNumber())
           .toJavadoc(),
       new AttributeBuilder(factory)
           .annotation(t(SuppressWarnings.class), v("deprecation"))
           .Public()
           .Final()
           .toAttributes(),
       name,
       Collections.<TypeParameterDeclaration>emptyList(),
       importer.resolve(
           factory.newParameterizedType(
               Models.toType(factory, SegmentedCombiner.class),
               Arrays.asList(
                   importer.toType(shuffle.getCompiled().getKeyTypeName()),
                   importer.toType(shuffle.getCompiled().getValueTypeName())))),
       Collections.<Type>emptyList(),
       members);
 }
  @Override
  public List<UserGroup> getGroupUserUserGroups(long groupId, long userId) throws PortalException {

    long[] groupUserGroupIds = groupPersistence.getUserGroupPrimaryKeys(groupId);

    if (groupUserGroupIds.length == 0) {
      return Collections.emptyList();
    }

    long[] userUserGroupIds = userPersistence.getUserGroupPrimaryKeys(userId);

    if (userUserGroupIds.length == 0) {
      return Collections.emptyList();
    }

    Set<Long> userGroupIds = SetUtil.intersect(groupUserGroupIds, userUserGroupIds);

    if (userGroupIds.isEmpty()) {
      return Collections.emptyList();
    }

    List<UserGroup> userGroups = new ArrayList<>(userGroupIds.size());

    for (Long userGroupId : userGroupIds) {
      userGroups.add(userGroupPersistence.findByPrimaryKey(userGroupId));
    }

    return userGroups;
  }
Exemplo n.º 18
0
  /**
   * Test method for {@link
   * net.sf.hajdbc.balancer.AbstractBalancer#containsAll(java.util.Collection)}.
   */
  @Test
  public void containsAll() {
    Balancer<Void, MockDatabase> balancer =
        this.factory.createBalancer(Collections.<MockDatabase>emptySet());

    assertTrue(balancer.containsAll(Collections.emptyList()));
    assertFalse(balancer.containsAll(Collections.singletonList(this.databases[0])));
    assertFalse(balancer.containsAll(Arrays.asList(this.databases[0], this.databases[1])));
    assertFalse(balancer.containsAll(Arrays.asList(this.databases)));

    balancer = this.factory.createBalancer(Collections.singleton(this.databases[0]));

    assertTrue(balancer.containsAll(Collections.emptyList()));
    assertTrue(balancer.containsAll(Collections.singletonList(this.databases[0])));
    assertFalse(balancer.containsAll(Arrays.asList(this.databases[0], this.databases[1])));
    assertFalse(balancer.containsAll(Arrays.asList(this.databases)));

    balancer =
        this.factory.createBalancer(
            new HashSet<MockDatabase>(Arrays.asList(this.databases[0], this.databases[1])));

    assertTrue(balancer.containsAll(Collections.emptyList()));
    assertTrue(balancer.containsAll(Collections.singletonList(this.databases[0])));
    assertTrue(balancer.containsAll(Arrays.asList(this.databases[0], this.databases[1])));
    assertFalse(balancer.containsAll(Arrays.asList(this.databases)));

    balancer =
        this.factory.createBalancer(new HashSet<MockDatabase>(Arrays.asList(this.databases)));

    assertTrue(balancer.containsAll(Collections.emptyList()));
    assertTrue(balancer.containsAll(Collections.singletonList(this.databases[0])));
    assertTrue(balancer.containsAll(Arrays.asList(this.databases[0], this.databases[1])));
    assertTrue(balancer.containsAll(Arrays.asList(this.databases)));
  }
Exemplo n.º 19
0
 @Test
 public void testJoin() {
   assertArrayEquals(
       array(1, 2, 3, 4, 5, 6),
       toArray(Integer.class, toList(join(list(1, 2, 3).iterator(), list(4, 5, 6).iterator()))));
   assertArrayEquals(
       array(1, 2, 3),
       toArray(
           Integer.class,
           toList(
               join(
                   list(1, 2, 3).iterator(),
                   java.util.Collections.<Integer>emptyList().iterator()))));
   assertArrayEquals(
       array(1, 2, 3),
       toArray(
           Integer.class,
           toList(
               join(
                   java.util.Collections.<Integer>emptyList().iterator(),
                   list(1, 2, 3).iterator()))));
   assertEquals(
       0,
       toArray(
               Object.class,
               toList(
                   join(
                       java.util.Collections.emptyList().iterator(),
                       java.util.Collections.emptyList().iterator())))
           .length);
 }
    @Override
    public List<DataRecord> visit(StagingBlockKey stagingBlockKey) {
      FieldMetadata blockField =
          new SimpleTypeFieldMetadata(
              explicitProjection,
              false,
              false,
              false,
              "blockKey", //$NON-NLS-1$
              new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING),
              Collections.<String>emptyList(),
              Collections.<String>emptyList(),
              Collections.<String>emptyList(),
              StringUtils.EMPTY);
      lastField = blockField;
      recordProjection.put(
          blockField,
          new ValueBuilder() {

            @Override
            public Object getValue(DataRecord record) {
              return record
                  .getRecordMetadata()
                  .getRecordProperties()
                  .get(StagingStorage.METADATA_STAGING_BLOCK_KEY);
            }
          });
      return records;
    }
  @Test
  public void shouldEvalScriptWithMapBindingsAndLanguageThenConsume() throws Exception {
    final GremlinExecutor gremlinExecutor =
        GremlinExecutor.build()
            .addEngineSettings(
                "nashorn",
                Collections.emptyList(),
                Collections.emptyList(),
                Collections.emptyList(),
                Collections.emptyMap())
            .create();
    final Map<String, Object> b = new HashMap<>();
    b.put("x", 1);

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger result = new AtomicInteger(0);
    assertEquals(
        2.0,
        gremlinExecutor
            .eval(
                "1+x",
                "nashorn",
                b,
                r -> {
                  result.set(((Double) r).intValue() * 2);
                  latch.countDown();
                })
            .get());

    latch.await();
    assertEquals(4, result.get());
    gremlinExecutor.close();
  }
Exemplo n.º 22
0
 @NotNull
 @Override
 public Collection<? extends JetType> getSupertypes() {
   if (supertypes == null) {
     if (resolveSession.isClassSpecial(DescriptorUtils.getFQName(LazyClassDescriptor.this))) {
       this.supertypes = Collections.emptyList();
     } else {
       JetClassOrObject classOrObject =
           declarationProvider.getOwnerInfo().getCorrespondingClassOrObject();
       if (classOrObject == null) {
         this.supertypes = Collections.emptyList();
       } else {
         List<JetType> allSupertypes =
             resolveSession
                 .getInjector()
                 .getDescriptorResolver()
                 .resolveSupertypes(
                     getScopeForClassHeaderResolution(),
                     LazyClassDescriptor.this,
                     classOrObject,
                     resolveSession.getTrace());
         List<JetType> validSupertypes =
             Lists.newArrayList(Collections2.filter(allSupertypes, VALID_SUPERTYPE));
         this.supertypes = validSupertypes;
         findAndDisconnectLoopsInTypeHierarchy(validSupertypes);
       }
     }
   }
   return supertypes;
 }
 @Test
 public void removeAllElements() throws Exception {
   List<ParserFeature> features = Collections.emptyList();
   document =
       XmlHelper.parse(
           getClass()
               .getResourceAsStream(
                   "/com/google/code/configprocessor/data/xml-target-config-2.xml"),
           features);
   RemoveAction action =
       new RemoveAction("/root/property[@attribute='value3']", NodeSetPolicy.ALL);
   XmlActionProcessingAdvisor advisor =
       new XmlRemoveActionProcessingAdvisor(
           action, expressionResolver, namespaceContext, Collections.<ParserFeature>emptyList());
   String expected =
       "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
           + LINE_SEPARATOR
           + "<root>"
           + LINE_SEPARATOR
           + " <property5>"
           + LINE_SEPARATOR
           + "  <nested1 a=\"1\"/>"
           + LINE_SEPARATOR
           + " </property5>"
           + LINE_SEPARATOR
           + "</root>"
           + LINE_SEPARATOR;
   executeTest(advisor, expected);
 }
Exemplo n.º 24
0
public abstract class TransportTest extends SessionTest {

  private static final Serializer CONTRACT_SERIALIZER =
      new SimpleFastSerializer(
          FastReflector.FACTORY,
          Arrays.asList(BaseTypeHandlers.INTEGER, BaseTypeHandlers.BYTE_ARRAY),
          Collections.emptyList(),
          Collections.singletonList(DivisionByZeroException.class),
          Collections.emptyList());

  protected static final Serializer MESSAGE_SERIALIZER = new MessageSerializer(CONTRACT_SERIALIZER);

  protected static TransportSetup invokeTransportSetup(
      final boolean invoke, final boolean createException, final Executor dispatchExecutor) {
    return TransportSetup.ofContractSerializer(
        CONTRACT_SERIALIZER, invokeSessionFactory(invoke, createException, dispatchExecutor));
  }

  protected static TransportSetup performanceTransportSetup(
      final Executor dispatchExecutor,
      final @Nullable CountDownLatch latch,
      final int samples,
      final int bytes) {
    return TransportSetup.ofContractSerializer(
        CONTRACT_SERIALIZER, performanceSessionFactory(dispatchExecutor, latch, samples, bytes));
  }

  protected static TransportSetup performanceTransportSetup(final Executor dispatchExecutor) {
    return TransportSetup.ofContractSerializer(
        CONTRACT_SERIALIZER, performanceSessionFactory(dispatchExecutor));
  }
}
Exemplo n.º 25
0
 /**
  * Gets application element name for full path of it's primary file from index
  *
  * @param aFile Primary file object.
  * @return application element name
  */
 public static String file2AppElementId(FileObject aFile) {
   if (aFile != null) {
     try {
       final Collection<FileObject> roots =
           new ArrayList<>(
               QuerySupport.findRoots(
                   (Project) null,
                   null,
                   Collections.<String>emptyList(),
                   Collections.<String>emptyList()));
       QuerySupport q =
           QuerySupport.forRoots(
               FileIndexer.INDEXER_NAME,
               FileIndexer.INDEXER_VERSION,
               roots.toArray(new FileObject[roots.size()]));
       Collection<? extends IndexResult> results =
           q.query(FileIndexer.FULL_PATH, aFile.getPath(), QuerySupport.Kind.EXACT);
       if (results.size() == 1) {
         IndexResult result = results.iterator().next();
         return result.getValue(FileIndexer.APP_ELEMENT_NAME);
       }
     } catch (IOException ex) {
       Logger.getLogger(IndexerQuery.class.getName()).log(Level.WARNING, null, ex);
     }
   }
   return null;
 }
Exemplo n.º 26
0
  private Collection<Artifact> getSelectedArtifacts() {
    IStructuredSelection selection = (IStructuredSelection) getViewer().getSelection();

    Object[] objects = selection.toArray();
    if (objects.length == 0) {
      return Collections.emptyList();
    }

    AbstractArtifactSearchResult resultInput = getInput();
    if (resultInput == null) {
      return Collections.emptyList();
    }

    Set<Artifact> artifacts = new LinkedHashSet<>();
    for (Object object : objects) {
      Artifact toAdd = null;
      if (object instanceof AttributeLineElement) {
        toAdd = (Artifact) ((IAdaptable) object).getAdapter(Artifact.class);
        artifacts.add(toAdd);
      } else if (object instanceof IAdaptable) {
        toAdd = (Artifact) ((IAdaptable) object).getAdapter(Artifact.class);
      } else if (object instanceof Match) {
        toAdd = (Artifact) ((Match) object).getElement();
      }
      if (toAdd != null) {
        artifacts.add(toAdd);
      }
    }
    return artifacts;
  }
 @Test
 public void testParse() throws Exception {
   OperationsJsonParser parser = new OperationsJsonParser();
   Operations actual =
       parser.parse(ResourceUtil.getJsonObjectFromResource("/json/operations/valid.json"));
   assertThat(
       actual,
       is(
           new Operations(
               Collections.singleton(
                   new OperationGroup(
                       "opsbar-transitions",
                       Collections.singleton(
                           new OperationLink(
                               "action_id_4",
                               "issueaction-workflow-transition",
                               "Start Progress",
                               "Start work on the issue",
                               "/secure/WorkflowUIDispatcher.jspa?id=93813&action=4&atl_token=",
                               10,
                               null)),
                       Collections.singleton(
                           new OperationGroup(
                               null,
                               Collections.<OperationLink>emptyList(),
                               Collections.<OperationGroup>emptyList(),
                               new OperationHeader(
                                   "opsbar-transitions_more", "Workflow", null, null),
                               null)),
                       null,
                       20)))));
 }
  private static List<XmlElementDescriptor> computeRequiredSubTags(XmlElementsGroup group) {

    if (group.getMinOccurs() < 1) return Collections.emptyList();
    switch (group.getGroupType()) {
      case LEAF:
        XmlElementDescriptor descriptor = group.getLeafDescriptor();
        return descriptor == null
            ? Collections.<XmlElementDescriptor>emptyList()
            : Collections.singletonList(descriptor);
      case CHOICE:
        LinkedHashSet<XmlElementDescriptor> set = null;
        for (XmlElementsGroup subGroup : group.getSubGroups()) {
          List<XmlElementDescriptor> descriptors = computeRequiredSubTags(subGroup);
          if (set == null) {
            set = new LinkedHashSet<XmlElementDescriptor>(descriptors);
          } else {
            set.retainAll(descriptors);
          }
        }
        if (set == null || set.isEmpty()) {
          return Collections.singletonList(null); // placeholder for smart completion
        }
        return new ArrayList<XmlElementDescriptor>(set);

      default:
        ArrayList<XmlElementDescriptor> list = new ArrayList<XmlElementDescriptor>();
        for (XmlElementsGroup subGroup : group.getSubGroups()) {
          list.addAll(computeRequiredSubTags(subGroup));
        }
        return list;
    }
  }
Exemplo n.º 29
0
  private List<Future<?>> loadSavedMetricsToCaches(String accessLevelName) {
    String storage = metricStorage + "/" + accessLevelName;
    Path storageFile = Paths.get(storage);
    if (!Files.exists(storageFile)) {
      log.info("Cannot pre-load cache {} - file {} doesn't exist", accessLevelName, storage);
      return Collections.emptyList();
    }

    try (BufferedReader fromStorageFile =
        new BufferedReader(
            new InputStreamReader(
                new GZIPInputStream(Files.newInputStream(storageFile)),
                Charset.forName("UTF-8")))) {
      boolean firstLine = true;
      String metricName;
      List<Future<?>> futures = new ArrayList<>();
      while ((metricName = fromStorageFile.readLine()) != null) {
        if (firstLine) {
          firstLine = false;
        } else {
          futures.add(createNewCacheLines(metricName));
        }
      }
      return futures;
    } catch (IOException e) {
      log.info("could not find file for accessLevel " + accessLevelName, e);
      return Collections.emptyList();
    }
  }
Exemplo n.º 30
0
 public List<? extends TypeMirror> getParameterTypes() {
   MethodBinding binding = (MethodBinding) this._binding;
   TypeBinding[] parameters = binding.parameters;
   int length = parameters.length;
   boolean isEnumConstructor =
       binding.isConstructor()
           && binding.declaringClass.isEnum()
           && binding.declaringClass.isBinaryBinding()
           && ((binding.modifiers & ExtraCompilerModifiers.AccGenericSignature) == 0);
   if (isEnumConstructor) {
     if (length == 2) {
       return Collections.emptyList();
     }
     ArrayList<TypeMirror> list = new ArrayList<TypeMirror>();
     for (int i = 2; i < length; i++) {
       list.add(_env.getFactory().newTypeMirror(parameters[i]));
     }
     return Collections.unmodifiableList(list);
   }
   if (length != 0) {
     ArrayList<TypeMirror> list = new ArrayList<TypeMirror>();
     for (TypeBinding typeBinding : parameters) {
       list.add(_env.getFactory().newTypeMirror(typeBinding));
     }
     return Collections.unmodifiableList(list);
   }
   return Collections.emptyList();
 }