Example usage for java.util HashSet addAll

List of usage examples for java.util HashSet addAll

Introduction

In this page you can find the example usage for java.util HashSet addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java

/**
 * Get the contents of a redirect URL and use as reponse for the provided HttpServletResponse.
 * If possible, pass in error responses as well.
 * @param redirectURIStr  &emsp;  /*from ww  w  .  j  av  a  2s.  c o  m*/
 * @param resp  HttpServletResponse 
 * @throws IOException  &emsp; 
 */
public static void proxyURL(String redirectURIStr, HttpServletResponse resp) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet getMethod = new HttpGet(redirectURIStr);
    getMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/
    try (CloseableHttpResponse response = httpclient.execute(getMethod)) {
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();

            HashSet<String> proxiedHeaders = new HashSet<String>();
            proxiedHeaders.addAll(Arrays.asList(MimeResponse.PROXIED_HEADERS));
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                if (proxiedHeaders.contains(header.getName())) {
                    logger.debug("Adding headerName " + header.getName() + " and value " + header.getValue()
                            + " when proxying request");
                    resp.addHeader(header.getName(), header.getValue());
                }
            }

            if (entity != null) {
                logger.debug("Obtained a HTTP entity of length " + entity.getContentLength());
                try (OutputStream os = resp.getOutputStream();
                        InputStream is = new BufferedInputStream(entity.getContent())) {
                    byte buf[] = new byte[10 * 1024];
                    int bytesRead = is.read(buf);
                    while (bytesRead > 0) {
                        os.write(buf, 0, bytesRead);
                        resp.flushBuffer();
                        bytesRead = is.read(buf);
                    }
                }
            } else {
                throw new IOException("HTTP response did not have an entity associated with it");
            }
        } else {
            logger.error("Invalid status code " + response.getStatusLine().getStatusCode()
                    + " when connecting to URL " + redirectURIStr + ". Sending the errorstream across");
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                try (InputStream is = new BufferedInputStream(response.getEntity().getContent())) {
                    byte buf[] = new byte[10 * 1024];
                    int bytesRead = is.read(buf);
                    while (bytesRead > 0) {
                        os.write(buf, 0, bytesRead);
                        bytesRead = is.read(buf);
                    }
                }
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(response.getStatusLine().getStatusCode(), new String(os.toByteArray()));
            }
        }
    }
}

From source file:disko.DU.java

@SuppressWarnings("unchecked")
public static HGHandle toSynRel(HyperGraph graph, HGHandle h) {
    RelOccurrence o = graph.get(h);//  w  w  w .j a  va2 s.  c  om
    HGHandle[] targets = HGUtils.toHandleArray(o);
    HashSet<HGHandle> L = new HashSet<HGHandle>();
    L.addAll((List<HGHandle>) (List<?>) hg.findAll(graph,
            hg.and(hg.type(ScopeLink.class), hg.orderedLink(new HGHandle[] { hg.anyHandle(), h }))));
    if (L.isEmpty()) // scope unknown?!!?
        return null;
    HGHandle synRelHandle = hg.findOne(graph, hg.and(hg.type(SynRel.class), hg.link(targets)));
    if (synRelHandle == null)
        synRelHandle = graph.add(new SynRel(targets));
    for (HGHandle scopeHandle : L) {
        ScopeLink scopeLink = graph.get(scopeHandle);
        HGHandle scoping = scopeLink.getTargetAt(0);
        if (hg.findOne(graph, hg.and(hg.type(ScopeLink.class), hg.orderedLink(scoping, synRelHandle))) == null)
            graph.add(new ScopeLink(scoping, synRelHandle));
    }
    return synRelHandle;
}

From source file:de.schaeuffelhut.android.openvpn.Preferences.java

public final static ArrayList<File> listKnownConfigs(Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    HashSet<File> configs = new HashSet<File>();
    for (String key : preferences.getAll().keySet())
        if (isConfigKey(key))
            configs.add(configOf(key));//from   w w w  .  j  a  va2  s. c om
    configs.addAll(configs(getConfigDir(context, preferences)));
    ArrayList<File> sortedConfigs = new ArrayList<File>(configs);
    Collections.sort(sortedConfigs);
    return sortedConfigs;
}

From source file:org.kuali.student.enrollment.class2.courseoffering.controller.CourseOfferingControllerPopulateUIForm.java

protected static void continueFromCreateCopyCourseOfferingInfo(CourseOfferingCreateWrapper coWrapper,
        CourseInfo course, TermInfo term) {

    ContextInfo contextInfo = ContextUtils.createDefaultContextInfo();
    int firstValue = 0;

    try {/*from   w  w w  .j  a va  2  s .co  m*/
        List<CourseOfferingInfo> courseOfferingInfos = CourseOfferingManagementUtil.getCourseOfferingService()
                .getCourseOfferingsByCourseAndTerm(course.getId(), term.getId(), contextInfo);

        coWrapper.setCourse(course);
        coWrapper
                .setCreditCount(
                        CourseOfferingViewHelperUtil
                                .trimTrailing0(CourseOfferingManagementUtil.getLrcService()
                                        .getResultValue(course.getCreditOptions().get(firstValue)
                                                .getResultValueKeys().get(firstValue), contextInfo)
                                        .getValue()));
        coWrapper.setShowAllSections(true);
        coWrapper.setShowCopyCourseOffering(false);
        coWrapper.setShowTermOfferingLink(true);

        coWrapper.setContextBar(CourseOfferingContextBar.NEW_INSTANCE(coWrapper.getTerm(),
                coWrapper.getSocInfo(), CourseOfferingManagementUtil.getStateService(),
                CourseOfferingManagementUtil.getAcademicCalendarService(), contextInfo));

        coWrapper.getExistingTermOfferings().clear();
        coWrapper.getExistingOfferingsInCurrentTerm().clear();

        for (CourseOfferingInfo courseOfferingInfo : courseOfferingInfos) {
            if (StringUtils.equals(courseOfferingInfo.getStateKey(),
                    LuiServiceConstants.LUI_CO_STATE_OFFERED_KEY)) {
                CourseOfferingEditWrapper co = new CourseOfferingEditWrapper(courseOfferingInfo);
                co.setGradingOption(
                        CourseOfferingManagementUtil.getGradingOption(courseOfferingInfo.getGradingOptionId()));
                coWrapper.getExistingOfferingsInCurrentTerm().add(co);
            }
        }

        //Get past 5 years CO
        Calendar termStart = Calendar.getInstance();
        termStart.setTime(term.getStartDate());
        String termYear = Integer.toString(termStart.get(Calendar.YEAR));
        String termMonth = Integer.toString((termStart.get(Calendar.MONTH) + 1));
        String termDayOfMonth = Integer.toString((termStart.getActualMaximum(Calendar.DAY_OF_MONTH)));

        org.kuali.student.r2.core.search.dto.SearchRequestInfo searchRequest = new org.kuali.student.r2.core.search.dto.SearchRequestInfo(
                CourseOfferingHistorySearchImpl.PAST_CO_SEARCH.getKey());
        searchRequest.addParam(CourseOfferingHistorySearchImpl.COURSE_ID, coWrapper.getCourse().getId());

        searchRequest.addParam(CourseOfferingHistorySearchImpl.TARGET_DAY_OF_MONTH_PARAM, termDayOfMonth);
        searchRequest.addParam(CourseOfferingHistorySearchImpl.TARGET_MONTH_PARAM, termMonth);
        searchRequest.addParam(CourseOfferingHistorySearchImpl.TARGET_YEAR_PARAM, termYear);
        searchRequest.addParam(CourseOfferingHistorySearchImpl.SearchParameters.CROSS_LIST_SEARCH_ENABLED,
                BooleanUtils.toStringTrueFalse(true));
        org.kuali.student.r2.core.search.dto.SearchResultInfo searchResult = CourseOfferingManagementUtil
                .getSearchService().search(searchRequest, null);

        List<String> courseOfferingIds = new ArrayList<String>(searchResult.getTotalResults());

        /* Checks whether the course is cross-listed and Set the codes that are cross listed to the cross-listed list */

        for (org.kuali.student.r2.core.search.dto.SearchResultRowInfo row : searchResult.getRows()) {
            for (SearchResultCellInfo cellInfo : row.getCells()) {
                String value = StringUtils.EMPTY;
                if (cellInfo.getValue() != null) {
                    value = cellInfo.getValue();
                }
                if (CourseOfferingHistorySearchImpl.SearchResultColumns.CO_ID.equals(cellInfo.getKey())) {
                    courseOfferingIds.add(value);
                } else if (CourseOfferingHistorySearchImpl.SearchResultColumns.IS_CROSS_LISTED
                        .equals(cellInfo.getValue())) {
                    coWrapper.setCrossListedCo(BooleanUtils.toBoolean(value));
                } else if (CourseOfferingHistorySearchImpl.SearchResultColumns.CROSS_LISTED_COURSES
                        .equals(cellInfo.getKey())) {
                    coWrapper.setAlternateCOCodes(Arrays.asList(StringUtils.split(value, ",")));
                }

            }
        }

        /*
         * Avoid duplicates in case there is a cross Listed
         */
        HashSet hs = new HashSet();
        hs.addAll(courseOfferingIds);
        courseOfferingIds.clear();
        courseOfferingIds.addAll(hs);

        courseOfferingInfos = CourseOfferingManagementUtil.getCourseOfferingService()
                .getCourseOfferingsByIds(courseOfferingIds, contextInfo);

        for (CourseOfferingInfo courseOfferingInfo : courseOfferingInfos) {
            CourseOfferingEditWrapper co = new CourseOfferingEditWrapper(courseOfferingInfo);
            TermInfo termInfo = CourseOfferingManagementUtil.getAcademicCalendarService()
                    .getTerm(courseOfferingInfo.getTermId(), contextInfo);
            co.setTerm(termInfo);
            co.setGradingOption(
                    CourseOfferingManagementUtil.getGradingOption(courseOfferingInfo.getGradingOptionId()));
            co.setAlternateCOCodes(coWrapper.getAlternateCOCodes());
            coWrapper.getExistingTermOfferings().add(co);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:och.comp.ops.BillingOps.java

/** ? ?  ?       (? ? ) */
public static Pair<Integer, Integer> reinitAccsBlocked(Props props, MainDb db, Cache cache) {
    try {/*from  w  ww.j  a va  2  s  . c  o m*/

        UniversalQueries universal = db.universal;

        log.info("reinitAccsBlockedCache...");

        HashSet<ChatAccount> blockedAccs = new HashSet<>();
        HashSet<ChatAccount> unblockedAccs = new HashSet<>();

        List<ChatAccount> accs = universal.select(new GetAllChatAccounts());

        HashSet<String> blockedUids = new HashSet<>();
        List<UserBalance> blockedUsers = universal.select(new GetAllBlockedUsers());
        for (UserBalance user : blockedUsers) {
            List<String> blocked = db.chats.getOwnerAccs(user.userId);
            blockedUids.addAll(blocked);
        }

        for (ChatAccount acc : accs) {
            if (blockedUids.contains(acc.uid))
                blockedAccs.add(acc);
            else
                unblockedAccs.add(acc);
        }

        int unblockedCount = unblockedAccs.size();
        int blockedCount = blockedAccs.size();
        log.info("found blocked accs: " + blockedCount + ", unblocked accs: " + unblockedCount);

        Map<Long, ServerRow> servers = getServersMap(universal);

        //send reqs
        sendBlockedReqs(props, blockedAccs, servers, true);
        sendBlockedReqs(props, unblockedAccs, servers, false);

        //update cache
        for (ChatAccount acc : blockedAccs) {
            cache.tryPutCache(getBlockedAccFlag(acc.uid), "true");
        }
        for (ChatAccount acc : unblockedAccs) {
            cache.tryRemoveCache(getBlockedAccFlag(acc.uid));
        }

        log.info("done");

        return new Pair<>(unblockedCount, blockedCount);

    } catch (Exception e) {
        log.error("can't reinitAccsBlockedCache: " + e);
        return null;
    }
}

From source file:com.baasbox.controllers.Push.java

public static Result sendUsers() throws Exception {
    boolean verbose = false;
    try {/*w  w w  . ja v  a 2s  . com*/

        if (BaasBoxLogger.isTraceEnabled())
            BaasBoxLogger.trace("Method Start");
        PushLogger pushLogger = PushLogger.getInstance().init();
        if (UserService.isAnAdmin(DbHelper.currentUsername())) {
            pushLogger.enable();
        } else {
            pushLogger.disable();
        }
        if (request().getQueryString("verbose") != null
                && request().getQueryString("verbose").equalsIgnoreCase("true"))
            verbose = true;

        Http.RequestBody body = request().body();
        JsonNode bodyJson = body.asJson(); //{"message":"Text"}
        if (BaasBoxLogger.isTraceEnabled())
            BaasBoxLogger.trace("send bodyJson: " + bodyJson);
        if (bodyJson == null)
            return status(CustomHttpCode.JSON_PAYLOAD_NULL.getBbCode(),
                    CustomHttpCode.JSON_PAYLOAD_NULL.getDescription());
        pushLogger.addMessage("Payload received: %s", bodyJson.toString());
        JsonNode messageNode = bodyJson.findValue("message");
        pushLogger.addMessage("Payload message received: %s",
                messageNode == null ? "null" : messageNode.asText());
        if (messageNode == null)
            return status(CustomHttpCode.PUSH_MESSAGE_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_MESSAGE_INVALID.getDescription());
        if (!messageNode.isTextual())
            return status(CustomHttpCode.PUSH_MESSAGE_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_MESSAGE_INVALID.getDescription());

        String message = messageNode.asText();

        JsonNode usernamesNodes = bodyJson.get("users");
        pushLogger.addMessage("users: %s", usernamesNodes == null ? "null" : usernamesNodes.toString());

        List<String> usernames = new ArrayList<String>();

        if (!(usernamesNodes == null)) {

            if (!(usernamesNodes.isArray()))
                return status(CustomHttpCode.PUSH_USERS_FORMAT_INVALID.getBbCode(),
                        CustomHttpCode.PUSH_USERS_FORMAT_INVALID.getDescription());

            for (JsonNode usernamesNode : usernamesNodes) {
                usernames.add(usernamesNode.asText());
            }

            HashSet<String> hs = new HashSet<String>();
            hs.addAll(usernames);
            usernames.clear();
            usernames.addAll(hs);
            pushLogger.addMessage("Users extracted: %s", Joiner.on(",").join(usernames));
        } else {
            return status(CustomHttpCode.PUSH_NOTFOUND_KEY_USERS.getBbCode(),
                    CustomHttpCode.PUSH_NOTFOUND_KEY_USERS.getDescription());
        }

        JsonNode pushProfilesNodes = bodyJson.get("profiles");
        pushLogger.addMessage("profiles: %s",
                pushProfilesNodes == null ? "null" : pushProfilesNodes.toString());

        List<Integer> pushProfiles = new ArrayList<Integer>();
        if (!(pushProfilesNodes == null)) {
            if (!(pushProfilesNodes.isArray()))
                return status(CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getBbCode(),
                        CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getDescription());
            for (JsonNode pushProfileNode : pushProfilesNodes) {
                if (pushProfileNode.isTextual())
                    return status(CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getBbCode(),
                            CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getDescription());
                pushProfiles.add(pushProfileNode.asInt());
            }

            HashSet<Integer> hs = new HashSet<Integer>();
            hs.addAll(pushProfiles);
            pushProfiles.clear();
            pushProfiles.addAll(hs);
        } else {
            pushProfiles.add(1);
        }
        pushLogger.addMessage("Profiles computed: %s", Joiner.on(",").join(pushProfiles));

        boolean[] withError = new boolean[6];
        PushService ps = new PushService();
        Result toRet = null;
        try {
            boolean isValid = (ps.validate(pushProfiles));
            pushLogger.addMessage("Profiles validation: %s", isValid);
            if (isValid)
                withError = ps.send(message, usernames, pushProfiles, bodyJson, withError);
            pushLogger.addMessage("Service result: %s", Booleans.join(", ", withError));
        } catch (UserNotFoundException e) {
            return notFound("Username not found");
        } catch (SqlInjectionException e) {
            return badRequest("The supplied name appears invalid (Sql Injection Attack detected)");
        } catch (PushNotInitializedException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_CONFIG_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_CONFIG_INVALID.getDescription());
        } catch (PushProfileDisabledException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_PROFILE_DISABLED.getBbCode(),
                    CustomHttpCode.PUSH_PROFILE_DISABLED.getDescription());
        } catch (PushProfileInvalidException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getDescription());
        } catch (PushInvalidApiKeyException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_INVALID_APIKEY.getBbCode(),
                    CustomHttpCode.PUSH_INVALID_APIKEY.getDescription());
        } catch (UnknownHostException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_HOST_UNREACHABLE.getBbCode(),
                    CustomHttpCode.PUSH_HOST_UNREACHABLE.getDescription());
        } catch (InvalidRequestException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_INVALID_REQUEST.getBbCode(),
                    CustomHttpCode.PUSH_INVALID_REQUEST.getDescription());
        } catch (IOException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return badRequest(ExceptionUtils.getMessage(e));
        } catch (PushSoundKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_SOUND_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_SOUND_FORMAT_INVALID.getDescription());
        } catch (PushBadgeFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_BADGE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_BADGE_FORMAT_INVALID.getDescription());
        } catch (PushActionLocalizedKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_ACTION_LOCALIZED_KEY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_ACTION_LOCALIZED_KEY_FORMAT_INVALID.getDescription());
        } catch (PushLocalizedKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_LOCALIZED_KEY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_LOCALIZED_ARGUMENTS_FORMAT_INVALID.getDescription());
        } catch (PushLocalizedArgumentsFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_LOCALIZED_ARGUMENTS_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_LOCALIZED_ARGUMENTS_FORMAT_INVALID.getDescription());
        } catch (PushCollapseKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_COLLAPSE_KEY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_COLLAPSE_KEY_FORMAT_INVALID.getDescription());
        } catch (PushTimeToLiveFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_TIME_TO_LIVE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_TIME_TO_LIVE_FORMAT_INVALID.getDescription());
        } catch (PushContentAvailableFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_CONTENT_AVAILABLE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_CONTENT_AVAILABLE_FORMAT_INVALID.getDescription());
        } catch (PushCategoryFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_CATEGORY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_CATEGORY_FORMAT_INVALID.getDescription());
        }
        if (BaasBoxLogger.isTraceEnabled())
            BaasBoxLogger.trace("Method End");

        for (int i = 0; i < withError.length; i++) {
            if (withError[i] == true)
                return status(CustomHttpCode.PUSH_SENT_WITH_ERROR.getBbCode(),
                        CustomHttpCode.PUSH_SENT_WITH_ERROR.getDescription());
        }
        PushLogger.getInstance().messages();
        if (UserService.isAnAdmin(DbHelper.currentUsername()) && verbose) {
            return ok(toJson(PushLogger.getInstance().messages()));
        } else {
            return ok("Push Notification(s) has been sent");
        }
    } finally {
        if (UserService.isAnAdmin(DbHelper.currentUsername()) && verbose) {
            return ok(toJson(PushLogger.getInstance().messages()));
        }
        BaasBoxLogger.debug("Push execution flow:\n{}", PushLogger.getInstance().toString());
    }
}

From source file:org.droidparts.util.PersistUtils.java

public static boolean dropTables(SQLiteDatabase db, String... optionalTableNames) {
    HashSet<String> tableNames = new HashSet<String>();
    if (optionalTableNames.length == 0) {
        Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
        while (c.moveToNext()) {
            tableNames.add(c.getString(0));
        }//  w w w.j av  a  2 s  .com
        c.close();
    } else {
        tableNames.addAll(asList(optionalTableNames));
    }
    ArrayList<String> statements = new ArrayList<String>();
    for (String tableName : tableNames) {
        statements.add("DROP TABLE IF EXISTS " + tableName + ";");
    }
    return executeStatements(db, statements);
}

From source file:com.dtolabs.rundeck.core.dispatcher.DataContextUtils.java

/**
 * Generate a dataset for a INodeEntry/*from w w w.  j  a v  a 2s . co  m*/
 * @param nodeentry node
 * @return dataset
 */
public static Map<String, String> nodeData(final INodeEntry nodeentry) {
    final HashMap<String, String> data = new HashMap<String, String>();
    if (null != nodeentry) {
        HashSet<String> skipProps = new HashSet<String>();
        skipProps.addAll(Arrays.asList("nodename", "osName", "osVersion", "osArch", "osFamily"));
        data.put("name", notNull(nodeentry.getNodename()));
        data.put("hostname", notNull(nodeentry.getHostname()));
        data.put("os-name", notNull(nodeentry.getOsName()));
        data.put("os-version", notNull(nodeentry.getOsVersion()));
        data.put("os-arch", notNull(nodeentry.getOsArch()));
        data.put("os-family", notNull(nodeentry.getOsFamily()));
        data.put("username", notNull(nodeentry.getUsername()));
        data.put("description", notNull(nodeentry.getDescription()));
        data.put("tags", null != nodeentry.getTags() ? join(nodeentry.getTags(), ",") : "");
        //include attributes data
        if (null != nodeentry.getAttributes()) {
            for (final String name : nodeentry.getAttributes().keySet()) {
                if (null != nodeentry.getAttributes().get(name) && !data.containsKey(name)
                        && !skipProps.contains(name)) {

                    data.put(name, notNull(nodeentry.getAttributes().get(name)));
                }
            }
        }
    }
    return data;
}

From source file:com.dtolabs.rundeck.plugin.resources.ec2.InstanceToNodeMapper.java

/**
 * Convert an AWS EC2 Instance to a RunDeck INodeEntry based on the mapping input
 *///from w w w . j  a  v  a 2s.  c o  m
@SuppressWarnings("unchecked")
static INodeEntry instanceToNode(final Instance inst, final Properties mapping) throws GeneratorException {
    final NodeEntryImpl node = new NodeEntryImpl();

    //evaluate single settings.selector=tags/* mapping
    if ("tags/*".equals(mapping.getProperty("attributes.selector"))) {
        //iterate through instance tags and generate settings
        for (final Tag tag : inst.getTags()) {
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            node.getAttributes().put(tag.getKey(), tag.getValue());
        }
    }
    if (null != mapping.getProperty("tags.selector")) {
        final String selector = mapping.getProperty("tags.selector");
        final String value = applySelector(inst, selector, mapping.getProperty("tags.default"), true);
        if (null != value) {
            final String[] values = value.split(",");
            final HashSet<String> tagset = new HashSet<String>();
            for (final String s : values) {
                tagset.add(s.trim());
            }
            if (null == node.getTags()) {
                node.setTags(tagset);
            } else {
                final HashSet orig = new HashSet(node.getTags());
                orig.addAll(tagset);
                node.setTags(orig);
            }
        }
    }
    if (null == node.getTags()) {
        node.setTags(new HashSet());
    }
    final HashSet orig = new HashSet(node.getTags());
    //apply specific tag selectors
    final Pattern tagPat = Pattern.compile("^tag\\.(.+?)\\.selector$");
    //evaluate tag selectors
    for (final Object o : mapping.keySet()) {
        final String key = (String) o;
        final String selector = mapping.getProperty(key);
        //split selector by = if present
        final String[] selparts = selector.split("=");
        final Matcher m = tagPat.matcher(key);
        if (m.matches()) {
            final String tagName = m.group(1);
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            final String value = applySelector(inst, selparts[0], null);
            if (null != value) {
                if (selparts.length > 1 && !value.equals(selparts[1])) {
                    continue;
                }
                //use add the tag if the value is not null
                orig.add(tagName);
            }
        }
    }
    node.setTags(orig);

    //apply default values which do not have corresponding selector
    final Pattern attribDefPat = Pattern.compile("^([^.]+?)\\.default$");
    //evaluate selectors
    for (final Object o : mapping.keySet()) {
        final String key = (String) o;
        final String value = mapping.getProperty(key);
        final Matcher m = attribDefPat.matcher(key);
        if (m.matches() && (!mapping.containsKey(key + ".selector")
                || "".equals(mapping.getProperty(key + ".selector")))) {
            final String attrName = m.group(1);
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            if (null != value) {
                node.getAttributes().put(attrName, value);
            }
        }
    }

    final Pattern attribPat = Pattern.compile("^([^.]+?)\\.selector$");
    //evaluate selectors
    for (final Object o : mapping.keySet()) {
        final String key = (String) o;
        final String selector = mapping.getProperty(key);
        final Matcher m = attribPat.matcher(key);
        if (m.matches()) {
            final String attrName = m.group(1);
            if (attrName.equals("tags")) {
                //already handled
                continue;
            }
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            final String value = applySelector(inst, selector, mapping.getProperty(attrName + ".default"));
            if (null != value) {
                //use nodename-settingname to make the setting unique to the node
                node.getAttributes().put(attrName, value);
            }
        }
    }
    //        String hostSel = mapping.getProperty("hostname.selector");
    //        String host = applySelector(inst, hostSel, mapping.getProperty("hostname.default"));
    //        if (null == node.getHostname()) {
    //            System.err.println("Unable to determine hostname for instance: " + inst.getInstanceId());
    //            return null;
    //        }
    String name = node.getNodename();
    if (null == name || "".equals(name)) {
        name = node.getHostname();
    }
    if (null == name || "".equals(name)) {
        name = inst.getInstanceId();
    }
    node.setNodename(name);

    // Set ssh port on hostname if not 22
    String sshport = node.getAttributes().get("sshport");
    if (sshport != null && !sshport.equals("") && !sshport.equals("22")) {
        node.setHostname(node.getHostname() + ":" + sshport);
    }

    return node;
}

From source file:net.dries007.coremod.Coremod.java

public static HashSet<? extends IDependency> getDependencies(IDependency dependency) {
    final HashSet<IDependency> set = new HashSet<IDependency>();

    for (final IDependency nd : dependency.getTransitiveDependencies()) {
        set.add(nd);//  www  . ja va  2  s  .c  om
        if (dependency.getTransitiveDependencies() != null && !dependency.getTransitiveDependencies().isEmpty())
            set.addAll(getDependencies(nd));
    }

    return set;
}