List of usage examples for java.util SortedSet add
boolean add(E e);
From source file:com.atlassian.jira.bc.group.DefaultGroupService.java
@Override public Collection<String> getParentGroupNames(com.atlassian.crowd.embedded.api.Group group) { final com.atlassian.crowd.search.query.membership.MembershipQuery<com.atlassian.crowd.embedded.api.Group> membershipQuery = QueryBuilder .queryFor(com.atlassian.crowd.embedded.api.Group.class, EntityDescriptor.group()) .parentsOf(EntityDescriptor.group()).withName(group.getName()) .returningAtMost(EntityQuery.ALL_RESULTS); final SortedSet<String> setOfGroups = new TreeSet<String>(); Iterable<com.atlassian.crowd.embedded.api.Group> parents = crowdService.search(membershipQuery); for (com.atlassian.crowd.embedded.api.Group parent : parents) { if (crowdService.isGroupDirectGroupMember(group, parent)) { setOfGroups.add(parent.getName()); }/*from w ww.ja v a 2s . co m*/ } return Collections.unmodifiableSortedSet(setOfGroups); }
From source file:org.guiceyfruit.spring.support.AutowiredMemberProvider.java
protected Set<Binding<?>> getSortedBindings(Class<?> type, Predicate<Binding> filter) { SortedSet<Binding<?>> answer = new TreeSet<Binding<?>>(new Comparator<Binding<?>>() { public int compare(Binding<?> b1, Binding<?> b2) { int answer = typeName(b1).compareTo(typeName(b2)); if (answer == 0) { // TODO would be nice to use google colletions here but its excluded from guice String n1 = annotationName(b1); String n2 = annotationName(b2); if (n1 != null || n2 != null) { if (n1 == null) { return -1; }//from ww w . jav a 2 s .co m if (n2 == null) { return 1; } return n1.compareTo(n2); } } return answer; } }); Set<Binding<?>> bindings = Injectors.getBindingsOf(injector, type); for (Binding<?> binding : bindings) { if (isValidAutowireBinding(binding) && filter.matches(binding)) { answer.add(binding); } } /* if (answer.isEmpty() && bindings.size() == 1) { // if we have no matches on the filter, but we have a single static value, lets return it return bindings; } */ return answer; }
From source file:net.pms.dlna.protocolinfo.DeviceProtocolInfo.java
/** * Tries to parse {@code protocolInfoString} and add the resulting * {@link ProtocolInfo} instances.//from ww w.j a v a 2 s. c om * * @param type The {@link DeviceProtocolInfoSource} that identifies the * source of these {@code protocolInfo}s. * @param protocolInfoString a comma separated string of * {@code protocolInfo} representations whose presence is to be * ensured. * @return {@code true} if this changed as a result of the call. Returns * {@code false} this already contains the specified element(s). */ public boolean add(DeviceProtocolInfoSource<?> type, String protocolInfoString) { if (StringUtils.isBlank(protocolInfoString)) { return false; } String[] elements = protocolInfoString.trim().split(COMMA_SPLIT_REGEX); boolean result = false; setsLock.writeLock().lock(); try { SortedSet<ProtocolInfo> currentSet; if (protocolInfoSets.containsKey(type)) { currentSet = protocolInfoSets.get(type); } else { currentSet = new TreeSet<ProtocolInfo>(); protocolInfoSets.put(type, currentSet); } SortedSet<ProtocolInfo> tempSet = null; for (String element : elements) { try { tempSet = handleSpecialCaseString(element); if (tempSet == null) { // No special handling result |= currentSet.add(new ProtocolInfo(unescapeString(element))); } else { // Add the special handling results result |= currentSet.addAll(tempSet); tempSet = null; } } catch (ParseException e) { LOGGER.warn("Unable to parse protocolInfo from \"{}\", this profile will not be registered: {}", element, e.getMessage()); LOGGER.trace("", e); } } updateImageProfiles(); } finally { setsLock.writeLock().unlock(); } return result; }
From source file:net.sourceforge.fenixedu.domain.Lesson.java
public SortedSet<YearMonthDay> getAllLessonInstanceDatesUntil(YearMonthDay day) { SortedSet<YearMonthDay> result = new TreeSet<YearMonthDay>(); if (day != null) { for (LessonInstance instance : getLessonInstancesSet()) { YearMonthDay instanceDay = instance.getDay(); if (!instanceDay.isAfter(day)) { result.add(instanceDay); }/* w w w. j a v a 2s . com*/ } } return result; }
From source file:org.sakaiproject.lessonbuildertool.service.ForumEntity.java
public String importObject(String title, String topicTitle, String text, boolean texthtml, String base, String baseDir, String siteId, List<String> attachmentHrefs, boolean hide) { DiscussionForum ourForum = null;/*from www. j av a 2 s . com*/ DiscussionTopic ourTopic = null; int forumtry = 0; int topictry = 0; for (;;) { ourForum = null; SortedSet<DiscussionForum> forums = new TreeSet<DiscussionForum>( new ForumBySortIndexAscAndCreatedDateDesc()); for (DiscussionForum forum : discussionForumManager.getForumsForMainPage()) forums.add(forum); for (DiscussionForum forum : forums) { if (forum.getTitle().equals(title)) { ourForum = forum; break; } } if (ourForum == null) { if (forumtry > 0) { System.out.println("oops, forum still not there the second time"); return null; } forumtry++; // if a new site, may need to create the area or we'll get a backtrace when creating forum areaManager.getDiscussionArea(siteId); ourForum = discussionForumManager.createForum(); ourForum.setTitle(title); discussionForumManager.saveForum(siteId, ourForum); continue; // reread, better be there this time } // forum now exists, and was just reread ourTopic = null; for (Object o : ourForum.getTopicsSet()) { DiscussionTopic topic = (DiscussionTopic) o; if (topic.getTitle().equals(topicTitle)) { ourTopic = topic; break; } } if (ourTopic != null) // ok, forum and topic exist break; if (topictry > 0) { System.out.println("oops, topic still not there the second time"); return null; } topictry++; // create it ourTopic = discussionForumManager.createTopic(ourForum); ourTopic.setTitle(topicTitle); if (attachmentHrefs != null && attachmentHrefs.size() > 0) { for (String href : attachmentHrefs) { // we don't have any real label for attachments. About all we can do is use the filename, without path String label = href; int slash = label.lastIndexOf("/"); if (slash >= 0) label = label.substring(slash + 1); if (label.equals("")) label = "Attachment"; // basedir is a folder in contenthosting starting with /group/ where our content has been loaded // discussionForum needs a Sakai content resource ID for the attachment Attachment thisDFAttach = discussionForumManager .createDFAttachment(removeDotDot(baseDir + href), label); ourTopic.addAttachment(thisDFAttach); } } String shortText = null; if (texthtml) { ourTopic.setExtendedDescription(text.replaceAll("\\$IMS-CC-FILEBASE\\$", base)); shortText = FormattedText.convertFormattedTextToPlaintext(text); } else { ourTopic.setExtendedDescription(FormattedText.convertPlaintextToFormattedText(text)); shortText = text; } shortText = org.apache.commons.lang.StringUtils.abbreviate(shortText, 254); ourTopic.setShortDescription(shortText); // there's a better way to do attachments, but it's too complex for now if (hide) discussionForumManager.saveTopicAsDraft(ourTopic); else discussionForumManager.saveTopic(ourTopic); // now go back and mmake sure everything is there } return "/" + FORUM_TOPIC + "/" + ourTopic.getId(); }
From source file:com.springsource.hq.plugin.tcserver.plugin.appmgmt.TomcatJmxApplicationManager.java
private SortedSet<Application> extractApplications(Object applicationsObject) { SortedSet<Application> applications = new TreeSet<Application>(); if (isTcRuntime25OrLater(applicationsObject)) { @SuppressWarnings("unchecked") Set<? extends Map<String, String>> applicationsSet = (Set<? extends Map<String, String>>) applicationsObject; for (Map<String, String> item : applicationsSet) { Application application = new Application(); application.setName(TomcatNameUtils.convertPathToName(item.get("path"))); String versionString = item.get("version"); if (versionString.length() > 0) { application.setVersion(Integer.parseInt(versionString)); } else { application.setVersion(0); }/*from w w w.j a v a 2s.com*/ applications.add(application); } } else { for (String applicationPath : (String[]) applicationsObject) { Application application = new Application(); application.setName(TomcatNameUtils.convertPathToName(applicationPath)); application.setVersion(0); applications.add(application); } } return applications; }
From source file:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java
@RequestMapping(value = "/encounters", method = RequestMethod.GET) @ResponseBody/*from w w w .j ava 2s.c om*/ public Object getEncounters(@RequestParam(value = "patientId", required = true) String patientId, @RequestParam(value = "idType", required = true) String idType, @RequestParam(value = "encounterUniqueId", required = false) String encounterUniqueId, @RequestParam(value = "elid", required = false) String enterpriseLocationIdentifier, @RequestParam(value = "dateStart", required = false) String dateStart, @RequestParam(value = "dateEnd", required = false) String dateEnd, HttpServletRequest request, HttpServletResponse response) { LogEncounterService service = Context.getService(LogEncounterService.class); XmlMessageWriter xmlMessagewriter = new XmlMessageWriter(); String hl7Msg = null; Date fromDate = null; Date toDate = null; Patient p = null; ORU_R01 r01 = null; log.info("RHEA Controller call detected..."); log.info("Enterprise Patient Id is :" + patientId); log.info("Enterprise Id type is :" + idType); log.info("encounterUniqueId is :" + encounterUniqueId); GetEncounterLog getEncounterLog = new GetEncounterLog(); getEncounterLog.setLogTime(new Date()); getEncounterLog.setPatientId(patientId); getEncounterLog.setEncounterUniqueId(encounterUniqueId); // first, we create from and to data objects out of the String // parameters response.setContentType("text/xml"); if (!idType.equals("ECID")) { // Later on we may need to manage multiple // types of ID's. In such a case, this // will become more complex log.info(RHEAErrorCodes.INVALID_ID_TYPE); getEncounterLog = util.getLogger(getEncounterLog, RHEAErrorCodes.INVALID_ID_TYPE, RHEAErrorCodes.ID_TYPE_DETAIL, RequestOutcome.BAD_REQUEST.getResultType(), null, null, null); service.saveGetEncounterLog(getEncounterLog); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); try { xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(), RHEAErrorCodes.ID_TYPE_DETAIL); } catch (IOException e) { e.printStackTrace(); } return null; } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); try { if (dateStart != null) fromDate = format.parse(dateStart); } catch (ParseException e) { log.info(RHEAErrorCodes.INVALID_START_DATE + dateStart); getEncounterLog = util.getLogger(getEncounterLog, RHEAErrorCodes.INVALID_START_DATE, null, RequestOutcome.BAD_REQUEST.getResultType(), null, null, e); service.saveGetEncounterLog(getEncounterLog); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); try { xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(), e.toString()); } catch (IOException e1) { e1.printStackTrace(); } return null; } log.info("fromDate is :" + fromDate); getEncounterLog.setDateStart(fromDate); try { if (dateEnd != null) toDate = format.parse(dateEnd); } catch (ParseException e) { log.info(RHEAErrorCodes.INVALID_END_DATE + dateEnd); getEncounterLog = util.getLogger(getEncounterLog, RHEAErrorCodes.INVALID_END_DATE, null, RequestOutcome.BAD_REQUEST.getResultType(), fromDate, null, e); service.saveGetEncounterLog(getEncounterLog); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); try { xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(), e.toString()); } catch (Exception e1) { e1.printStackTrace(); } return null; } log.info("toDate is :" + toDate); getEncounterLog.setDateEnd(toDate); // Next, we try to retrieve the matching patient object if (patientId != null) { PatientIdentifierType patientIdentifierType = Context.getPatientService() .getPatientIdentifierTypeByName(idType); List<PatientIdentifierType> identifierTypeList = new ArrayList<PatientIdentifierType>(); identifierTypeList.add(patientIdentifierType); List<Patient> patients = Context.getPatientService().getPatients(null, patientId, identifierTypeList, false); if (patients.size() == 1) { p = patients.get(0); } else { log.info(RHEAErrorCodes.INVALID_RESULTS + patientId); getEncounterLog = util.getLogger(getEncounterLog, RHEAErrorCodes.INVALID_RESULTS, RHEAErrorCodes.INVALID_RESULTS_DETAIL, RequestOutcome.BAD_REQUEST.getResultType(), fromDate, toDate, null); service.saveGetEncounterLog(getEncounterLog); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); try { xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(), RHEAErrorCodes.INVALID_RESULTS); } catch (Exception e1) { e1.printStackTrace(); } return null; } } // if the patient doesn't exist, we need to return 400-BAD REQUEST if (p != null) { log.info("Patient id : " + p.getPatientId() + "was retreived..."); if (p != null) { // get all the encounters for this patient List<Encounter> encounterList = Context.getEncounterService().getEncounters(p, null, fromDate, toDate, null, null, null, false); // if the enconteruniqueId is not null, we can isolate the given // encounter if (encounterUniqueId != null) { Iterator<Encounter> i = encounterList.iterator(); while (i.hasNext()) { if (!i.next().getUuid().equals(encounterUniqueId)) i.remove(); } } if (enterpriseLocationIdentifier != null) { getEncounterLog.setEnterpriseLocationId(enterpriseLocationIdentifier); Iterator<Encounter> i = encounterList.iterator(); while (i.hasNext()) { String elidString = i.next().getLocation().getDescription(); String elid = null; if (elidString != null) { final Matcher matcher = Pattern.compile(":").matcher(elidString); if (matcher.find()) { elid = elidString.substring(matcher.end()).trim(); } if (elid != null) { if (elid.equals(enterpriseLocationIdentifier)) { i.remove(); } } } } } log.info("Calling the ORU_R01 parser..."); SortedSet<MatchingEncounters> encounterSet = new TreeSet<MatchingEncounters>(); for (Encounter e : encounterList) { MatchingEncounters matchingEncounters = new MatchingEncounters(); matchingEncounters.setGetEncounterLog(getEncounterLog); matchingEncounters.setEncounterId(e.getEncounterId()); encounterSet.add(matchingEncounters); } if (encounterList.size() > 0) getEncounterLog.setResult(RequestOutcome.RESULTS_RETRIEVED.getResultType()); if (encounterList.size() == 0) { getEncounterLog.setResult(RequestOutcome.NO_RESULTS.getResultType()); // Terrible logging methods ! getEncounterLog = util.getLogger(getEncounterLog, RHEAErrorCodes.INVALID_RESULTS, RHEAErrorCodes.INVALID_RESULTS_DETAIL, RequestOutcome.NO_RESULTS.getResultType(), fromDate, toDate, null); service.saveGetEncounterLog(getEncounterLog); response.setStatus(HttpServletResponse.SC_OK); // If no // matching // encounters // were // retrived, // we // display // 200. OK. // Is this // correct ? return null; } // Now we will generate the HL7 message GenerateORU_R01 R01Util = new GenerateORU_R01(); try { r01 = R01Util.generateORU_R01Message(p, encounterList); hl7Msg = R01Util.getMessage(r01); } catch (Exception e) { getEncounterLog = util.getLogger(getEncounterLog, RequestOutcome.BAD_REQUEST.getResultType(), null, RequestOutcome.BAD_REQUEST.getResultType(), fromDate, toDate, e); service.saveGetEncounterLog(getEncounterLog); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); try { xmlMessagewriter.parseMessage(response.getWriter(), RequestOutcome.BAD_REQUEST.getResultType(), e.toString()); } catch (Exception e2) { e2.printStackTrace(); } return null; } getEncounterLog.getMatchingEncounters().clear(); getEncounterLog.setMatchingEncounters(encounterSet); } try { service.saveGetEncounterLog(getEncounterLog); response.setStatus(HttpServletResponse.SC_OK); return hl7Msg; } catch (Exception e) { e.printStackTrace(); } } return null; }
From source file:org.jahia.modules.rolesmanager.RolesAndPermissionsHandler.java
private RoleBean createRoleBean(JCRNodeWrapper role, boolean getPermissions, boolean getSubRoles) throws RepositoryException { RoleBean roleBean = new RoleBean(); JCRNodeWrapper parentRole = JCRContentUtils.getParentOfType(role, "jnt:role"); final String uuid = role.getIdentifier(); roleBean.setUuid(uuid);//from w w w .j a v a 2 s . c om roleBean.setParentUuid(parentRole != null ? parentRole.getIdentifier() : null); roleBean.setName(role.getName()); roleBean.setPath(role.getPath()); roleBean.setDepth(role.getDepth()); JCRNodeWrapper n; Map<String, I18nRoleProperties> i18nRoleProperties = new TreeMap<String, I18nRoleProperties>(); for (Locale l : role.getExistingLocales()) { n = getSession(l).getNodeByIdentifier(uuid); if (!n.hasProperty(Constants.JCR_TITLE) && !n.hasProperty(Constants.JCR_DESCRIPTION)) { i18nRoleProperties.put(l.getLanguage(), null); continue; } I18nRoleProperties properties = new I18nRoleProperties(); properties.setLanguage(l.getDisplayName(LocaleContextHolder.getLocale())); if (n.hasProperty(Constants.JCR_TITLE)) { properties.setTitle(n.getProperty(Constants.JCR_TITLE).getString()); } if (n.hasProperty(Constants.JCR_DESCRIPTION)) { properties.setDescription(n.getProperty(Constants.JCR_DESCRIPTION).getString()); } i18nRoleProperties.put(l.getLanguage(), properties); } roleBean.setI18nProperties(i18nRoleProperties); if (role.hasProperty("j:hidden")) { roleBean.setHidden(role.getProperty("j:hidden").getBoolean()); } String roleGroup = "edit-role"; if (role.hasProperty("j:roleGroup")) { roleGroup = role.getProperty("j:roleGroup").getString(); } RoleType roleType = roleTypes.get(roleGroup); roleBean.setRoleType(roleType); if (getPermissions) { List<String> tabs = new ArrayList<String>(roleBean.getRoleType().getScopes()); Map<String, List<String>> permIdsMap = new HashMap<String, List<String>>(); fillPermIds(role, tabs, permIdsMap, false); Map<String, List<String>> inheritedPermIdsMap = new HashMap<String, List<String>>(); fillPermIds(role.getParent(), tabs, inheritedPermIdsMap, true); Map<String, Map<String, Map<String, PermissionBean>>> permsForRole = new LinkedHashMap<String, Map<String, Map<String, PermissionBean>>>(); roleBean.setPermissions(permsForRole); for (String tab : tabs) { addPermissionsForScope(roleBean, tab, permIdsMap, inheritedPermIdsMap); } if (roleType.getAvailableNodeTypes() != null) { List<String> nodeTypesOnRole = new ArrayList<String>(); if (role.hasProperty("j:nodeTypes")) { for (Value value : role.getProperty("j:nodeTypes").getValues()) { nodeTypesOnRole.add(value.getString()); } } SortedSet<NodeType> nodeTypes = new TreeSet<NodeType>(); for (String s : roleType.getAvailableNodeTypes()) { boolean includeSubtypes = false; if (s.endsWith("/*")) { s = StringUtils.substringBeforeLast(s, "/*"); includeSubtypes = true; } ExtendedNodeType t = NodeTypeRegistry.getInstance().getNodeType(s); nodeTypes.add(new NodeType(t.getName(), t.getLabel(LocaleContextHolder.getLocale()), nodeTypesOnRole.contains(t.getName()))); if (includeSubtypes) { for (ExtendedNodeType sub : t.getSubtypesAsList()) { nodeTypes.add(new NodeType(sub.getName(), sub.getLabel(LocaleContextHolder.getLocale()), nodeTypesOnRole.contains(sub.getName()))); } } } roleBean.setNodeTypes(nodeTypes); } } // sub-roles if (getSubRoles) { final List<JCRNodeWrapper> subRoles = JCRContentUtils.getNodes(role, "jnt:role"); final List<RoleBean> subRoleBeans = new ArrayList<RoleBean>(subRoles.size()); for (JCRNodeWrapper subRole : subRoles) { subRoleBeans.add(createRoleBean(subRole, false, false)); } roleBean.setSubRoles(subRoleBeans); } return roleBean; }
From source file:org.jahia.tools.maven.plugins.LegalArtifactAggregator.java
private void processJarFile(InputStream inputStream, String jarFilePath, JarMetadata contextJarMetadata, boolean processMavenPom, int level, boolean lookForNotice, boolean lookForLicense, boolean processingSources) throws IOException { // if we don't need to find either a license or notice, don't process the jar at all if (!lookForLicense && !lookForNotice) { return;//from w w w. j a va 2 s.c om } final String indent = getIndent(level); output(indent, "Processing JAR " + jarFilePath + "...", false, true); // JarFile realJarFile = new JarFile(jarFile); JarInputStream jarInputStream = new JarInputStream(inputStream); String bundleLicense = null; Manifest manifest = jarInputStream.getManifest(); if (manifest != null && manifest.getMainAttributes() != null) { bundleLicense = manifest.getMainAttributes().getValue("Bundle-License"); if (bundleLicense != null) { output(indent, "Found Bundle-License attribute with value:" + bundleLicense); KnownLicense knownLicense = getKnowLicenseByName(bundleLicense); // this data is not reliable, especially on the ServiceMix repackaged bundles } } String pomFilePath = null; byte[] pomByteArray = null; final String jarFileName = getJarFileName(jarFilePath); if (contextJarMetadata == null) { contextJarMetadata = jarDatabase.get(jarFileName); if (contextJarMetadata == null) { // compute project name contextJarMetadata = new JarMetadata(jarFilePath, jarFileName); } jarDatabase.put(jarFileName, contextJarMetadata); } Notice notice; JarEntry curJarEntry = null; while ((curJarEntry = jarInputStream.getNextJarEntry()) != null) { if (!curJarEntry.isDirectory()) { final String fileName = curJarEntry.getName(); if (lookForNotice && isNotice(fileName, jarFilePath)) { output(indent, "Processing notice found in " + curJarEntry + "..."); InputStream noticeInputStream = jarInputStream; List<String> noticeLines = IOUtils.readLines(noticeInputStream); notice = new Notice(noticeLines); Map<String, Notice> notices = contextJarMetadata.getNoticeFiles(); if (notices == null) { notices = new TreeMap<>(); notices.put(fileName, notice); output(indent, "Found first notice " + curJarEntry); } else if (!notices.containsValue(notice)) { output(indent, "Found additional notice " + curJarEntry); notices.put(fileName, notice); } else { output(indent, "Duplicated notice in " + curJarEntry); notices.put(fileName, notice); duplicatedNotices.add(jarFilePath); } // IOUtils.closeQuietly(noticeInputStream); } else if (processMavenPom && fileName.endsWith("pom.xml")) { // remember pom file path in case we need it pomFilePath = curJarEntry.getName(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(jarInputStream, byteArrayOutputStream); pomByteArray = byteArrayOutputStream.toByteArray(); } else if (lookForLicense && isLicense(fileName, jarFilePath)) { output(indent, "Processing license found in " + curJarEntry + "..."); InputStream licenseInputStream = jarInputStream; List<String> licenseLines = IOUtils.readLines(licenseInputStream); LicenseFile licenseFile = new LicenseFile(jarFilePath, fileName, jarFilePath, licenseLines); resolveKnownLicensesByText(licenseFile); if (StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText()) && StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText().trim())) { KnownLicense knownLicense = new KnownLicense(); knownLicense.setId(FilenameUtils.getBaseName(jarFilePath) + "-additional-terms"); knownLicense .setName("Additional license terms from " + FilenameUtils.getBaseName(jarFilePath)); List<TextVariant> textVariants = new ArrayList<>(); TextVariant textVariant = new TextVariant(); textVariant.setId("default"); textVariant.setDefaultVariant(true); textVariant.setText(Pattern.quote(licenseFile.getAdditionalLicenseText())); textVariants.add(textVariant); knownLicense.setTextVariants(textVariants); knownLicense.setTextToUse(licenseFile.getAdditionalLicenseText()); knownLicense.setViral(licenseFile.getText().toLowerCase().contains("gpl")); knownLicenses.getLicenses().put(knownLicense.getId(), knownLicense); licenseFile.getKnownLicenses().add(knownLicense); licenseFile.getKnownLicenseKeys().add(knownLicense.getId()); } for (KnownLicense knownLicense : licenseFile.getKnownLicenses()) { SortedSet<LicenseFile> licenseFiles = knownLicensesFound.get(knownLicense); if (licenseFiles != null) { if (!licenseFiles.contains(licenseFile)) { licenseFiles.add(licenseFile); } knownLicensesFound.put(knownLicense, licenseFiles); } else { licenseFiles = new TreeSet<>(); licenseFiles.add(licenseFile); knownLicensesFound.put(knownLicense, licenseFiles); } } Map<String, LicenseFile> licenseFiles = contextJarMetadata.getLicenseFiles(); if (licenseFiles == null) { licenseFiles = new TreeMap<>(); } if (licenseFiles.containsKey(fileName)) { // warning we already have a license file here, what should we do ? output(indent, "License file already exists for " + jarFilePath + " will override it !", true, false); licenseFiles.remove(fileName); } licenseFiles.put(fileName, licenseFile); // IOUtils.closeQuietly(licenseInputStream); } else if (fileName.endsWith(".jar")) { InputStream embeddedJarInputStream = jarInputStream; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(embeddedJarInputStream, byteArrayOutputStream); final JarMetadata embeddedJarMetadata = new JarMetadata(jarFilePath, getJarFileName(fileName)); if (embeddedJarMetadata != null) { embeddedJarMetadata.setJarContents(byteArrayOutputStream.toByteArray()); contextJarMetadata.getEmbeddedJars().add(embeddedJarMetadata); } } else if (fileName.endsWith(".class")) { String className = fileName.substring(0, fileName.length() - ".class".length()).replaceAll("/", "."); int lastPoint = className.lastIndexOf("."); String packageName = null; if (lastPoint > 0) { packageName = className.substring(0, lastPoint); SortedSet<String> currentJarPackages = jarDatabase .get(FilenameUtils.getBaseName(jarFilePath)).getPackages(); if (currentJarPackages == null) { currentJarPackages = new TreeSet<>(); } currentJarPackages.add(packageName); } } } jarInputStream.closeEntry(); } jarInputStream.close(); jarInputStream = null; if (!contextJarMetadata.getEmbeddedJars().isEmpty()) { for (JarMetadata embeddedJarMetadata : contextJarMetadata.getEmbeddedJars()) { if (embeddedJarMetadata.getJarContents() != null) { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( embeddedJarMetadata.getJarContents()); processJarFile(byteArrayInputStream, contextJarMetadata.toString(), null, true, level, true, true, processingSources); } else { output(indent, "Couldn't find dependency for embedded JAR " + contextJarMetadata, true, false); } } } if (processMavenPom) { if (pomFilePath == null) { output(indent, "No POM found in " + jarFilePath); } else { output(indent, "Processing POM found at " + pomFilePath + " in " + jarFilePath + "..."); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(pomByteArray); processJarPOM(byteArrayInputStream, pomFilePath, jarFilePath, contextJarMetadata, lookForNotice, lookForLicense, contextJarMetadata.getEmbeddedJars(), level + 1, processingSources); } } if (lookForLicense || lookForNotice) { if (lookForLicense) { output(indent, "No license found in " + jarFilePath); } if (lookForNotice) { output(indent, "No notice found in " + jarFilePath); } if (pomFilePath == null && lookForLicense && lookForNotice) { if (StringUtils.isBlank(contextJarMetadata.getVersion())) { output(indent, "Couldn't resolve version for JAR " + contextJarMetadata + ", can't query Maven Central repository without version !"); } else { List<Artifact> mavenCentralArtifacts = findArtifactInMavenCentral(contextJarMetadata.getName(), contextJarMetadata.getVersion(), contextJarMetadata.getClassifier()); if (mavenCentralArtifacts != null && mavenCentralArtifacts.size() == 1) { Artifact mavenCentralArtifact = mavenCentralArtifacts.get(0); Artifact resolvedArtifact = resolveArtifact(mavenCentralArtifact, level); if (resolvedArtifact != null) { // we have a copy of the local artifact, let's request the sources for it. if (!processingSources && !"sources".equals(contextJarMetadata.getClassifier())) { final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(), resolvedArtifact.getArtifactId(), "sources", "jar", resolvedArtifact.getVersion()); File sourceJar = getArtifactFile(artifact, level); if (sourceJar != null && sourceJar.exists()) { FileInputStream sourceJarInputStream = new FileInputStream(sourceJar); processJarFile(sourceJarInputStream, sourceJar.getPath(), contextJarMetadata, false, level + 1, lookForNotice, lookForLicense, true); IOUtils.closeQuietly(sourceJarInputStream); } } else { // we are already processing a sources artifact, we need to load the pom artifact to extract information from there final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(), resolvedArtifact.getArtifactId(), null, "pom", resolvedArtifact.getVersion()); File artifactPom = getArtifactFile(artifact, level); if (artifactPom != null && artifactPom.exists()) { output(indent, "Processing POM for " + artifact + "..."); processPOM(lookForNotice, lookForLicense, jarFilePath, contextJarMetadata, contextJarMetadata.getEmbeddedJars(), level + 1, new FileInputStream(artifactPom), processingSources); } } } else { output(indent, "===> Couldn't resolve artifact " + mavenCentralArtifact + " in Maven Central. Please resolve license and notice files manually!", false, true); } } else { output(indent, "===> Couldn't find nor POM, license or notice. Please check manually!", false, true); } } } } output(indent, "Done processing JAR " + jarFilePath + ".", false, true); }