Search in sources :

Example 56 with Collections

use of java.util.Collections in project nifi by apache.

the class SnippetUtils method populateFlowSnippet.

/**
 * Populates the specified snippet and returns the details.
 *
 * @param snippet snippet
 * @param recurse recurse
 * @param includeControllerServices whether or not to include controller services in the flow snippet dto
 * @return snippet
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public FlowSnippetDTO populateFlowSnippet(final Snippet snippet, final boolean recurse, final boolean includeControllerServices, boolean removeInstanceId) {
    final FlowSnippetDTO snippetDto = new FlowSnippetDTO(removeInstanceId);
    final String groupId = snippet.getParentGroupId();
    final ProcessGroup processGroup = flowController.getGroup(groupId);
    // ensure the group could be found
    if (processGroup == null) {
        throw new IllegalStateException("The parent process group for this snippet could not be found.");
    }
    // We need to ensure that the Controller Services that are added get added to the proper group.
    // This can potentially get a little bit tricky. Consider this scenario:
    // We have a Process Group G1. Within Process Group G1 is a Controller Service C1.
    // Also within G1 is a child Process Group, G2. Within G2 is a child Process Group, G3.
    // Within G3 are two child Process Groups: G4 and G5. Within each of these children,
    // we have a Processor (P1, P2) that references the Controller Service C1, defined 3 levels above.
    // Now, we create a template that encompasses only Process Groups G4 and G5. We need to ensure
    // that the Controller Service C1 is included at the 'root' of the template so that those
    // Processors within G4 and G5 both have access to the same Controller Service. This can be drawn
    // out thus:
    // 
    // G1 -- C1
    // |
    // |
    // G2
    // |
    // |
    // G3
    // |  \
    // |   \
    // G4   G5
    // |    |
    // |    |
    // P1   P2
    // 
    // Both P1 and P2 reference C1.
    // 
    // In order to accomplish this, we maintain two collections. First, we keep a Set of all Controller Services that have
    // been added. If we add a new Controller Service to the set, then we know it hasn't been added anywhere in the Snippet.
    // In that case, we determine the service's group ID. In the flow described above, if we template just groups G4 and G5,
    // then we need to include the Controller Service defined at G1. So we also keep a Map of Group ID to controller services
    // in that group. If the ParentGroupId of a Controller Service is not in our snippet, then we instead update the parent
    // ParentGroupId to be that of our highest-level process group (in this case G3, as that's where the template is created)
    // and then add the controller services to that group (NOTE: here, when we say we change the group ID and add to that group,
    // we are talking only about the DTO objects that make up the snippet. We do not actually modify the Process Group or the
    // Controller Services in our flow themselves!)
    final Set<ControllerServiceDTO> allServicesReferenced = new HashSet<>();
    final Map<String, FlowSnippetDTO> contentsByGroup = new HashMap<>();
    contentsByGroup.put(processGroup.getIdentifier(), snippetDto);
    // add any processors
    final Set<ControllerServiceDTO> controllerServices = new HashSet<>();
    final Set<ProcessorDTO> processors = new LinkedHashSet<>();
    if (!snippet.getProcessors().isEmpty()) {
        for (final String processorId : snippet.getProcessors().keySet()) {
            final ProcessorNode processor = processGroup.getProcessor(processorId);
            if (processor == null) {
                throw new IllegalStateException("A processor in this snippet could not be found.");
            }
            processors.add(dtoFactory.createProcessorDto(processor));
            if (includeControllerServices) {
                // Include all referenced services that are not already included in this snippet.
                getControllerServices(processor.getProperties()).stream().filter(svc -> allServicesReferenced.add(svc)).forEach(svc -> {
                    final String svcGroupId = svc.getParentGroupId();
                    final String destinationGroupId = contentsByGroup.containsKey(svcGroupId) ? svcGroupId : processGroup.getIdentifier();
                    svc.setParentGroupId(destinationGroupId);
                    controllerServices.add(svc);
                });
            }
        }
    }
    // add any connections
    final Set<ConnectionDTO> connections = new LinkedHashSet<>();
    if (!snippet.getConnections().isEmpty()) {
        for (final String connectionId : snippet.getConnections().keySet()) {
            final Connection connection = processGroup.getConnection(connectionId);
            if (connection == null) {
                throw new IllegalStateException("A connection in this snippet could not be found.");
            }
            connections.add(dtoFactory.createConnectionDto(connection));
        }
    }
    // add any funnels
    final Set<FunnelDTO> funnels = new LinkedHashSet<>();
    if (!snippet.getFunnels().isEmpty()) {
        for (final String funnelId : snippet.getFunnels().keySet()) {
            final Funnel funnel = processGroup.getFunnel(funnelId);
            if (funnel == null) {
                throw new IllegalStateException("A funnel in this snippet could not be found.");
            }
            funnels.add(dtoFactory.createFunnelDto(funnel));
        }
    }
    // add any input ports
    final Set<PortDTO> inputPorts = new LinkedHashSet<>();
    if (!snippet.getInputPorts().isEmpty()) {
        for (final String inputPortId : snippet.getInputPorts().keySet()) {
            final Port inputPort = processGroup.getInputPort(inputPortId);
            if (inputPort == null) {
                throw new IllegalStateException("An input port in this snippet could not be found.");
            }
            inputPorts.add(dtoFactory.createPortDto(inputPort));
        }
    }
    // add any labels
    final Set<LabelDTO> labels = new LinkedHashSet<>();
    if (!snippet.getLabels().isEmpty()) {
        for (final String labelId : snippet.getLabels().keySet()) {
            final Label label = processGroup.getLabel(labelId);
            if (label == null) {
                throw new IllegalStateException("A label in this snippet could not be found.");
            }
            labels.add(dtoFactory.createLabelDto(label));
        }
    }
    // add any output ports
    final Set<PortDTO> outputPorts = new LinkedHashSet<>();
    if (!snippet.getOutputPorts().isEmpty()) {
        for (final String outputPortId : snippet.getOutputPorts().keySet()) {
            final Port outputPort = processGroup.getOutputPort(outputPortId);
            if (outputPort == null) {
                throw new IllegalStateException("An output port in this snippet could not be found.");
            }
            outputPorts.add(dtoFactory.createPortDto(outputPort));
        }
    }
    // add any process groups
    final Set<ProcessGroupDTO> processGroups = new LinkedHashSet<>();
    if (!snippet.getProcessGroups().isEmpty()) {
        for (final String childGroupId : snippet.getProcessGroups().keySet()) {
            final ProcessGroup childGroup = processGroup.getProcessGroup(childGroupId);
            if (childGroup == null) {
                throw new IllegalStateException("A process group in this snippet could not be found.");
            }
            final ProcessGroupDTO childGroupDto = dtoFactory.createProcessGroupDto(childGroup, recurse);
            processGroups.add(childGroupDto);
            // maintain a listing of visited groups starting with each group in the snippet. this is used to determine
            // whether a referenced controller service should be included in the resulting snippet. if the service is
            // defined at groupId or one of it's ancestors, its considered outside of this snippet and will only be included
            // when the includeControllerServices is set to true. this happens above when considering the processors in this snippet
            final Set<String> visitedGroupIds = new HashSet<>();
            addControllerServices(childGroup, childGroupDto, allServicesReferenced, includeControllerServices, visitedGroupIds, contentsByGroup, processGroup.getIdentifier());
        }
    }
    // add any remote process groups
    final Set<RemoteProcessGroupDTO> remoteProcessGroups = new LinkedHashSet<>();
    if (!snippet.getRemoteProcessGroups().isEmpty()) {
        for (final String remoteProcessGroupId : snippet.getRemoteProcessGroups().keySet()) {
            final RemoteProcessGroup remoteProcessGroup = processGroup.getRemoteProcessGroup(remoteProcessGroupId);
            if (remoteProcessGroup == null) {
                throw new IllegalStateException("A remote process group in this snippet could not be found.");
            }
            remoteProcessGroups.add(dtoFactory.createRemoteProcessGroupDto(remoteProcessGroup));
        }
    }
    // Normalize the coordinates based on the locations of the other components
    final List<? extends ComponentDTO> components = new ArrayList<>();
    components.addAll((Set) processors);
    components.addAll((Set) connections);
    components.addAll((Set) funnels);
    components.addAll((Set) inputPorts);
    components.addAll((Set) labels);
    components.addAll((Set) outputPorts);
    components.addAll((Set) processGroups);
    components.addAll((Set) remoteProcessGroups);
    normalizeCoordinates(components);
    Set<ControllerServiceDTO> updatedControllerServices = snippetDto.getControllerServices();
    if (updatedControllerServices == null) {
        updatedControllerServices = new HashSet<>();
    }
    updatedControllerServices.addAll(controllerServices);
    snippetDto.setControllerServices(updatedControllerServices);
    snippetDto.setProcessors(processors);
    snippetDto.setConnections(connections);
    snippetDto.setFunnels(funnels);
    snippetDto.setInputPorts(inputPorts);
    snippetDto.setLabels(labels);
    snippetDto.setOutputPorts(outputPorts);
    snippetDto.setProcessGroups(processGroups);
    snippetDto.setRemoteProcessGroups(remoteProcessGroups);
    return snippetDto;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) RemoteProcessGroupContentsDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupContentsDTO) ProcessGroup(org.apache.nifi.groups.ProcessGroup) ProcessorConfigDTO(org.apache.nifi.web.api.dto.ProcessorConfigDTO) ConnectableType(org.apache.nifi.connectable.ConnectableType) LoggerFactory(org.slf4j.LoggerFactory) Port(org.apache.nifi.connectable.Port) ConnectionDTO(org.apache.nifi.web.api.dto.ConnectionDTO) StringUtils(org.apache.commons.lang3.StringUtils) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ResourceType(org.apache.nifi.authorization.resource.ResourceType) PositionDTO(org.apache.nifi.web.api.dto.PositionDTO) SecureRandom(java.security.SecureRandom) LabelDTO(org.apache.nifi.web.api.dto.LabelDTO) ProcessGroupDTO(org.apache.nifi.web.api.dto.ProcessGroupDTO) PropertyDescriptorDTO(org.apache.nifi.web.api.dto.PropertyDescriptorDTO) TenantEntity(org.apache.nifi.web.api.entity.TenantEntity) Map(java.util.Map) Connection(org.apache.nifi.connectable.Connection) FunnelDTO(org.apache.nifi.web.api.dto.FunnelDTO) ComponentIdGenerator(org.apache.nifi.util.ComponentIdGenerator) Label(org.apache.nifi.controller.label.Label) ControllerServiceDTO(org.apache.nifi.web.api.dto.ControllerServiceDTO) AccessPolicyDAO(org.apache.nifi.web.dao.AccessPolicyDAO) Collection(java.util.Collection) Set(java.util.Set) UUID(java.util.UUID) RemoteProcessGroupPortDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupPortDTO) Snippet(org.apache.nifi.controller.Snippet) Collectors(java.util.stream.Collectors) ResourceFactory(org.apache.nifi.authorization.resource.ResourceFactory) FlowController(org.apache.nifi.controller.FlowController) StandardCharsets(java.nio.charset.StandardCharsets) PortDTO(org.apache.nifi.web.api.dto.PortDTO) List(java.util.List) ScheduledState(org.apache.nifi.controller.ScheduledState) RemoteProcessGroup(org.apache.nifi.groups.RemoteProcessGroup) ProcessorDTO(org.apache.nifi.web.api.dto.ProcessorDTO) Entry(java.util.Map.Entry) ControllerServiceState(org.apache.nifi.controller.service.ControllerServiceState) DtoFactory(org.apache.nifi.web.api.dto.DtoFactory) Resource(org.apache.nifi.authorization.Resource) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) RemoteProcessGroupDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupDTO) ProcessorNode(org.apache.nifi.controller.ProcessorNode) Funnel(org.apache.nifi.connectable.Funnel) ControllerServiceNode(org.apache.nifi.controller.service.ControllerServiceNode) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AccessPolicyDTO(org.apache.nifi.web.api.dto.AccessPolicyDTO) LinkedHashSet(java.util.LinkedHashSet) Logger(org.slf4j.Logger) RequestAction(org.apache.nifi.authorization.RequestAction) ComponentDTO(org.apache.nifi.web.api.dto.ComponentDTO) AccessPolicy(org.apache.nifi.authorization.AccessPolicy) Collections(java.util.Collections) ConnectableDTO(org.apache.nifi.web.api.dto.ConnectableDTO) Funnel(org.apache.nifi.connectable.Funnel) FlowSnippetDTO(org.apache.nifi.web.api.dto.FlowSnippetDTO) ControllerServiceDTO(org.apache.nifi.web.api.dto.ControllerServiceDTO) HashMap(java.util.HashMap) ConnectionDTO(org.apache.nifi.web.api.dto.ConnectionDTO) Port(org.apache.nifi.connectable.Port) Label(org.apache.nifi.controller.label.Label) ArrayList(java.util.ArrayList) ProcessorNode(org.apache.nifi.controller.ProcessorNode) ProcessGroupDTO(org.apache.nifi.web.api.dto.ProcessGroupDTO) RemoteProcessGroupDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupDTO) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) RemoteProcessGroup(org.apache.nifi.groups.RemoteProcessGroup) RemoteProcessGroupPortDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupPortDTO) PortDTO(org.apache.nifi.web.api.dto.PortDTO) Connection(org.apache.nifi.connectable.Connection) RemoteProcessGroupDTO(org.apache.nifi.web.api.dto.RemoteProcessGroupDTO) FunnelDTO(org.apache.nifi.web.api.dto.FunnelDTO) ProcessorDTO(org.apache.nifi.web.api.dto.ProcessorDTO) ProcessGroup(org.apache.nifi.groups.ProcessGroup) RemoteProcessGroup(org.apache.nifi.groups.RemoteProcessGroup) LabelDTO(org.apache.nifi.web.api.dto.LabelDTO)

Example 57 with Collections

use of java.util.Collections in project Gargoyle by callakrsos.

the class DimList method list.

/********************************
	 * 작성일 : 2017. 4. 24. 작성자 : KYJ
	 *
	 * path에 속하는 하위 구성정보 조회
	 *
	 * @param path
	 * @param revision
	 * @param exceptionHandler
	 * @return
	 ********************************/
public <T> List<T> list(String projSpec, String path, String fileName, String revision, Function<ItemRevision, T> convert, Consumer<Exception> exceptionHandler) {
    List<T> collections = Collections.emptyList();
    DimensionsConnection conn = null;
    try {
        conn = getConnection();
        Project projObj = getProject(conn, projSpec);
        RepositoryFolder findRepositoryFolderByPath = projObj.findRepositoryFolderByPath(path);
        Filter filter = new Filter();
        if (ValueUtil.isNotEmpty(fileName))
            filter.criteria().add(new Filter.Criterion(SystemAttributes.ITEMFILE_FILENAME, fileName, Filter.Criterion.EQUALS));
        if (ValueUtil.equals("-1", revision)) {
            filter.criteria().add(new Filter.Criterion(SystemAttributes.IS_LATEST_REV, "Y", 0));
        } else {
            filter.criteria().add(new Filter.Criterion(SystemAttributes.REVISION, revision, Filter.Criterion.EQUALS));
        }
        List allChildFolders = findRepositoryFolderByPath.getAllChildFolders();
        List<DimensionsRelatedObject> childItems = findRepositoryFolderByPath.getChildItems(filter);
        //			Stream.concat(allChildFolders, childItems);
        List<ItemRevision> collect = childItems.stream().map(i -> (ItemRevision) i.getObject()).collect(Collectors.toList());
        collections = collect.stream().map(convert).collect(Collectors.toList());
    } catch (Exception e) {
        exceptionHandler.accept(e);
    } finally {
        manager.close(conn);
    }
    return collections;
}
Also used : Arrays(java.util.Arrays) Properties(java.util.Properties) Logger(org.slf4j.Logger) ScmDirHandler(com.kyj.scm.manager.core.commons.ScmDirHandler) DimensionsConnection(com.serena.dmclient.api.DimensionsConnection) LoggerFactory(org.slf4j.LoggerFactory) ValueUtil(com.kyj.fx.voeditor.visual.util.ValueUtil) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) DimensionsRelatedObject(com.serena.dmclient.api.DimensionsRelatedObject) ArrayList(java.util.ArrayList) Consumer(java.util.function.Consumer) DimensionsObjectFactory(com.serena.dmclient.api.DimensionsObjectFactory) Project(com.serena.dmclient.api.Project) List(java.util.List) IListCommand(com.kyj.scm.manager.core.commons.IListCommand) RepositoryFolder(com.serena.dmclient.api.RepositoryFolder) ItemRevision(com.serena.dmclient.api.ItemRevision) Collections(java.util.Collections) SystemAttributes(com.serena.dmclient.api.SystemAttributes) Filter(com.serena.dmclient.api.Filter) DimensionsRelatedObject(com.serena.dmclient.api.DimensionsRelatedObject) DimensionsConnection(com.serena.dmclient.api.DimensionsConnection) Project(com.serena.dmclient.api.Project) RepositoryFolder(com.serena.dmclient.api.RepositoryFolder) Filter(com.serena.dmclient.api.Filter) ArrayList(java.util.ArrayList) List(java.util.List) ItemRevision(com.serena.dmclient.api.ItemRevision)

Example 58 with Collections

use of java.util.Collections in project ORCID-Source by ORCID.

the class SalesForceManagerImplTest method testUpdateContact2.

@Test
public void testUpdateContact2() {
    // Switch from main to technical contact
    Contact contact = new Contact();
    contact.setId("contact2Id");
    contact.setAccountId("account1Id");
    ContactRole role = new ContactRole(ContactRoleType.TECHNICAL_CONTACT);
    role.setId("contact2Idrole1Id");
    contact.setRole(role);
    ((SalesForceManagerImpl) salesForceManager).updateContact(contact, Collections.<Contact>emptyList());
    verify(salesForceDao, times(1)).updateContactRole(argThat(r -> {
        return "contact2Idrole1Id".equals(r.getId()) && "contact2Id".equals(r.getContactId()) && ContactRoleType.MAIN_CONTACT.equals(r.getRoleType()) && !r.isCurrent();
    }));
    verify(salesForceDao, times(1)).createContactRole(argThat(r -> {
        return "contact2Id".equals(r.getContactId()) && "account1Id".equals(r.getAccountId()) && ContactRoleType.TECHNICAL_CONTACT.equals(r.getRoleType());
    }));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) SalesForceManager(org.orcid.core.manager.SalesForceManager) SalesForceConnectionDao(org.orcid.persistence.dao.SalesForceConnectionDao) TargetProxyHelper(org.orcid.test.TargetProxyHelper) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) URL(java.net.URL) Mock(org.mockito.Mock) Member(org.orcid.core.salesforce.model.Member) EmailManager(org.orcid.core.manager.EmailManager) ContactPermission(org.orcid.core.salesforce.model.ContactPermission) ArrayList(java.util.ArrayList) MockitoAnnotations(org.mockito.MockitoAnnotations) ProfileLastModifiedAspect(org.orcid.persistence.aop.ProfileLastModifiedAspect) SalesForceConnectionEntity(org.orcid.persistence.jpa.entities.SalesForceConnectionEntity) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) ContactRole(org.orcid.core.salesforce.model.ContactRole) Before(org.junit.Before) SelfPopulatingCache(net.sf.ehcache.constructs.blocking.SelfPopulatingCache) MalformedURLException(java.net.MalformedURLException) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) OrcidUnauthorizedException(org.orcid.core.exception.OrcidUnauthorizedException) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) List(java.util.List) Assert.assertFalse(org.junit.Assert.assertFalse) SourceManager(org.orcid.core.manager.SourceManager) Contact(org.orcid.core.salesforce.model.Contact) Email(org.orcid.jaxb.model.record_v2.Email) ContactRoleType(org.orcid.core.salesforce.model.ContactRoleType) Emails(org.orcid.jaxb.model.record_v2.Emails) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) SalesForceDao(org.orcid.core.salesforce.dao.SalesForceDao) ContactRole(org.orcid.core.salesforce.model.ContactRole) Contact(org.orcid.core.salesforce.model.Contact) Test(org.junit.Test)

Example 59 with Collections

use of java.util.Collections in project dataverse by IQSS.

the class OrcidOAuth2AP method getNodes.

private List<Node> getNodes(Node node, List<String> path) {
    NodeList childs = node.getChildNodes();
    final Stream<Node> nodeStream = IntStream.range(0, childs.getLength()).mapToObj(childs::item).filter(n -> n.getNodeName().equals(path.get(0)));
    if (path.size() == 1) {
        // accumulate and return mode
        return nodeStream.collect(Collectors.toList());
    } else {
        // dig-in mode.
        return nodeStream.findFirst().map(n -> getNodes(n, path.subList(1, path.size()))).orElse(Collections.<Node>emptyList());
    }
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) XPath(javax.xml.xpath.XPath) XPathConstants(javax.xml.xpath.XPathConstants) AuthenticationProviderDisplayInfo(edu.harvard.iq.dataverse.authorization.AuthenticationProviderDisplayInfo) OAuth20Service(com.github.scribejava.core.oauth.OAuth20Service) XPathExpression(javax.xml.xpath.XPathExpression) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) BaseApi(com.github.scribejava.core.builder.api.BaseApi) AbstractOAuth2AuthenticationProvider(edu.harvard.iq.dataverse.authorization.providers.oauth2.AbstractOAuth2AuthenticationProvider) OAuth2AccessToken(com.github.scribejava.core.model.OAuth2AccessToken) OAuth2TokenData(edu.harvard.iq.dataverse.authorization.providers.oauth2.OAuth2TokenData) Document(org.w3c.dom.Document) BundleUtil(edu.harvard.iq.dataverse.util.BundleUtil) Node(org.w3c.dom.Node) OAuth2Exception(edu.harvard.iq.dataverse.authorization.providers.oauth2.OAuth2Exception) Json(javax.json.Json) OAuth2UserRecord(edu.harvard.iq.dataverse.authorization.providers.oauth2.OAuth2UserRecord) JsonObject(javax.json.JsonObject) JsonReader(javax.json.JsonReader) InputSource(org.xml.sax.InputSource) NodeList(org.w3c.dom.NodeList) Verb(com.github.scribejava.core.model.Verb) IOException(java.io.IOException) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Collectors.joining(java.util.stream.Collectors.joining) Objects(java.util.Objects) XPathFactory(javax.xml.xpath.XPathFactory) List(java.util.List) Stream(java.util.stream.Stream) OAuthRequest(com.github.scribejava.core.model.OAuthRequest) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXException(org.xml.sax.SAXException) Response(com.github.scribejava.core.model.Response) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Collections(java.util.Collections) AuthenticatedUserDisplayInfo(edu.harvard.iq.dataverse.authorization.AuthenticatedUserDisplayInfo) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node)

Example 60 with Collections

use of java.util.Collections in project meghanada-server by mopemope.

the class ASMReflector method reflectAll.

private List<MemberDescriptor> reflectAll(final File file, final String targetClass, final List<String> targetClasses) throws IOException {
    if (ModuleHelper.isJrtFsFile(file)) {
        final List<MemberDescriptor> results = new ArrayList<>(64);
        ModuleHelper.walkModule(path -> {
            ModuleHelper.pathToClassData(path).ifPresent(cd -> {
                String className = cd.getClassName();
                String moduleName = cd.getModuleName();
                if (this.ignorePackage(className)) {
                    return;
                }
                final Iterator<String> classIterator = targetClasses.iterator();
                while (classIterator.hasNext()) {
                    final String nameWithTP = classIterator.next();
                    if (nonNull(nameWithTP)) {
                        final boolean isSuper = !targetClass.equals(nameWithTP);
                        final String nameWithoutTP = ClassNameUtils.removeTypeParameter(nameWithTP);
                        if (className.equals(nameWithoutTP)) {
                            try (final InputStream in = cd.getInputStream()) {
                                final ClassReader classReader = new ClassReader(in);
                                final List<MemberDescriptor> members = getMemberFromJar(file, classReader, nameWithoutTP, nameWithTP);
                                if (isSuper) {
                                    replaceDescriptorsType(nameWithTP, members);
                                }
                                results.addAll(members);
                                classIterator.remove();
                                break;
                            } catch (IOException e) {
                                throw new UncheckedIOException(e);
                            }
                        }
                        final String innerClassName = ClassNameUtils.replaceInnerMark(className);
                        if (innerClassName.equals(nameWithoutTP)) {
                            try (final InputStream in = cd.getInputStream()) {
                                final ClassReader classReader = new ClassReader(in);
                                final List<MemberDescriptor> members = this.getMemberFromJar(file, classReader, innerClassName, nameWithTP);
                                if (isSuper) {
                                    replaceDescriptorsType(nameWithTP, members);
                                }
                                results.addAll(members);
                                classIterator.remove();
                                break;
                            } catch (IOException e) {
                                throw new UncheckedIOException(e);
                            }
                        }
                    }
                }
            });
        });
        return results;
    } else if (file.isFile() && file.getName().endsWith(".jar")) {
        try (final JarFile jarFile = new JarFile(file)) {
            final Enumeration<JarEntry> entries = jarFile.entries();
            final List<MemberDescriptor> results = new ArrayList<>(64);
            while (entries.hasMoreElements()) {
                if (targetClasses.isEmpty()) {
                    break;
                }
                final JarEntry jarEntry = entries.nextElement();
                final String entryName = jarEntry.getName();
                if (!entryName.endsWith(".class")) {
                    continue;
                }
                final String className = ClassNameUtils.replaceSlash(entryName.substring(0, entryName.length() - 6));
                if (this.ignorePackage(className)) {
                    continue;
                }
                final Iterator<String> classIterator = targetClasses.iterator();
                while (classIterator.hasNext()) {
                    final String nameWithTP = classIterator.next();
                    if (nonNull(nameWithTP)) {
                        final boolean isSuper = !targetClass.equals(nameWithTP);
                        final String nameWithoutTP = ClassNameUtils.removeTypeParameter(nameWithTP);
                        if (className.equals(nameWithoutTP)) {
                            try (final InputStream in = jarFile.getInputStream(jarEntry)) {
                                final ClassReader classReader = new ClassReader(in);
                                final List<MemberDescriptor> members = this.getMemberFromJar(file, classReader, nameWithoutTP, nameWithTP);
                                if (isSuper) {
                                    replaceDescriptorsType(nameWithTP, members);
                                }
                                results.addAll(members);
                                classIterator.remove();
                                break;
                            }
                        }
                        final String innerClassName = ClassNameUtils.replaceInnerMark(className);
                        if (innerClassName.equals(nameWithoutTP)) {
                            try (final InputStream in = jarFile.getInputStream(jarEntry)) {
                                final ClassReader classReader = new ClassReader(in);
                                final List<MemberDescriptor> members = this.getMemberFromJar(file, classReader, innerClassName, nameWithTP);
                                if (isSuper) {
                                    replaceDescriptorsType(nameWithTP, members);
                                }
                                results.addAll(members);
                                classIterator.remove();
                                break;
                            }
                        }
                    }
                }
            }
            return results;
        }
    } else if (file.isFile() && file.getName().endsWith(".class")) {
        for (String nameWithTP : targetClasses) {
            final boolean isSuper = !targetClass.equals(nameWithTP);
            final String fqcn = ClassNameUtils.removeTypeParameter(nameWithTP);
            final List<MemberDescriptor> members = getMembersFromClassFile(file, file, fqcn, false);
            if (nonNull(members)) {
                // 1 file
                if (isSuper) {
                    replaceDescriptorsType(nameWithTP, members);
                }
                return members;
            }
        }
        return Collections.emptyList();
    } else if (file.isDirectory()) {
        try (final Stream<Path> pathStream = Files.walk(file.toPath());
            final Stream<File> stream = pathStream.map(Path::toFile).filter(f -> f.isFile() && f.getName().endsWith(".class")).collect(Collectors.toList()).stream()) {
            return stream.map(wrapIO(f -> {
                final String rootPath = file.getCanonicalPath();
                final String path = f.getCanonicalPath();
                final String className = ClassNameUtils.replaceSlash(path.substring(rootPath.length() + 1, path.length() - 6));
                final Iterator<String> stringIterator = targetClasses.iterator();
                while (stringIterator.hasNext()) {
                    final String nameWithTP = stringIterator.next();
                    final boolean isSuper = !targetClass.equals(nameWithTP);
                    final String fqcn = ClassNameUtils.removeTypeParameter(nameWithTP);
                    if (!className.equals(fqcn)) {
                        continue;
                    }
                    final List<MemberDescriptor> members = getMembersFromClassFile(file, f, fqcn, false);
                    if (nonNull(members)) {
                        if (isSuper) {
                            replaceDescriptorsType(nameWithTP, members);
                        }
                        // found
                        stringIterator.remove();
                        return members;
                    }
                }
                return Collections.<MemberDescriptor>emptyList();
            })).filter(memberDescriptors -> nonNull(memberDescriptors) && memberDescriptors.size() > 0).flatMap(Collection::stream).collect(Collectors.toList());
        }
    }
    return Collections.emptyList();
}
Also used : Path(java.nio.file.Path) Enumeration(java.util.Enumeration) HashMap(java.util.HashMap) JarFile(java.util.jar.JarFile) FunctionUtils.wrapIOConsumer(meghanada.utils.FunctionUtils.wrapIOConsumer) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) JarEntry(java.util.jar.JarEntry) Map(java.util.Map) CandidateUnit(meghanada.reflect.CandidateUnit) Objects.isNull(java.util.Objects.isNull) Path(java.nio.file.Path) FunctionUtils.wrapIO(meghanada.utils.FunctionUtils.wrapIO) Opcodes(org.objectweb.asm.Opcodes) Iterator(java.util.Iterator) Files(java.nio.file.Files) ClassIndex(meghanada.reflect.ClassIndex) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) File(java.io.File) UncheckedIOException(java.io.UncheckedIOException) MemberDescriptor(meghanada.reflect.MemberDescriptor) List(java.util.List) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) ClassReader(org.objectweb.asm.ClassReader) ClassNameUtils(meghanada.utils.ClassNameUtils) ModuleHelper(meghanada.module.ModuleHelper) Optional(java.util.Optional) Objects.nonNull(java.util.Objects.nonNull) Collections(java.util.Collections) Config(meghanada.config.Config) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) Enumeration(java.util.Enumeration) MemberDescriptor(meghanada.reflect.MemberDescriptor) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) Iterator(java.util.Iterator) ClassReader(org.objectweb.asm.ClassReader) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) FileInputStream(java.io.FileInputStream) Stream(java.util.stream.Stream) InputStream(java.io.InputStream)

Aggregations

Collections (java.util.Collections)113 List (java.util.List)59 ArrayList (java.util.ArrayList)41 Test (org.junit.Test)39 Map (java.util.Map)37 Collectors (java.util.stream.Collectors)34 Arrays (java.util.Arrays)28 HashMap (java.util.HashMap)26 Set (java.util.Set)25 HashSet (java.util.HashSet)23 IOException (java.io.IOException)19 Collection (java.util.Collection)19 Optional (java.util.Optional)19 TimeUnit (java.util.concurrent.TimeUnit)16 URI (java.net.URI)13 Assert (org.junit.Assert)13 Function (java.util.function.Function)12 Stream (java.util.stream.Stream)12 Before (org.junit.Before)12 Logger (org.slf4j.Logger)12