Example usage for java.util LinkedHashMap remove

List of usage examples for java.util LinkedHashMap remove

Introduction

In this page you can find the example usage for java.util LinkedHashMap remove.

Prototype

V remove(Object key);

Source Link

Document

Removes the mapping for a key from this map if it is present (optional operation).

Usage

From source file:Main.java

public static void main(String[] args) {
    LinkedHashMap<String, String> lHashMap = new LinkedHashMap<String, String>();

    System.out.println(lHashMap.size());

    lHashMap.put("1", "One");
    lHashMap.put("2", "Two");
    lHashMap.put("3", "Three");

    System.out.println(lHashMap.size());

    Object obj = lHashMap.remove("2");
    System.out.println(lHashMap.size());

}

From source file:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {//  w  w  w  .j  a  v a2  s.  com
        String lang = Locale.getDefault().getLanguage();
        GnuParser cmdparser = new GnuParser();
        Options cmdopts = new Options();
        for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) {
            // hack for printOptions
            java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld);
            fieldopt.setAccessible(true);
            fieldopt.set(cmdopts, new LinkedHashMap<>());
        }
        cmdopts.addOption("h", "help", false, "Help");
        cmdopts.addOption("t", "test", false, "Show only report");
        cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg()
                .withDescription("Path to ADB from Android SDK").create("a"));
        cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg()
                .withDescription("Select device (\"adb devices\")").create("d"));
        cmdopts.addOption(null, "restore", false,
                "If packages have not yet removed and are disabled, " + "you can activate them again");
        cmdopts.addOption(null, "google", false, "Delete packages are in the Google section");
        cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex"
                + System.lineSeparator() + "(It is required to repeat command execution)");
        cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]");
        //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)");
        cmdopts.addOption(null, "scanlibs", false,
                "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib");

        cmdopts.addOptionGroup(new OptionGroup() {
            {
                addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired()
                        .withDescription("Create file with list packages").create());
                addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create());
            }
        });
        cmdopts.getOption("lang").setDescription(
                "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market");
        CommandLine cmd = cmdparser.parse(cmdopts, args);

        if (args.length == 0 || cmd.hasOption("help")) {
            PrintWriter console = new PrintWriter(System.out);
            HelpFormatter cmdhelp = new HelpFormatter();
            cmdhelp.setOptionComparator(new Comparator<Option>() {
                @Override
                public int compare(Option o1, Option o2) {
                    return 0;
                }
            });
            console.println("WARNING: Before use make a backup with ClockworkMod Recovery!");
            console.println();
            console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]");
            cmdhelp.printOptions(console, 80, cmdopts, 3, 2);
            console.flush();
            return;
        }

        String adb = cmd.getOptionValue("adb", "adb");
        try {
            run(adb, "start-server");
        } catch (IOException e) {
            System.out.println("Error: Not found ADB! Use -a or --adb");
            return;
        }

        final boolean NotTest = !cmd.hasOption("test");

        String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev"));
        if (!deverror.isEmpty()) {
            System.out.println(deverror);
            return;
        }

        System.out.println("Getting list packages:");
        LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>();
        for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) {
            // "pm list packages" give list sorted by packages ;)
            String pckg = ln.substring("package:".length());
            String pckgname = ln.substring(ln.lastIndexOf('=') + 1);
            pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1);
            if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) {
                apklist.put(pckg, pckgname);
            }
        }
        for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) {
            String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk");
            if (!apklist.containsKey(path)) {
                apklist.put(path, "");
            }
        }
        apklist.remove("/system/app/mcRegistry");
        for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        String genfile = cmd.getOptionValue("genfile");
        if (genfile != null) {
            Path genpath = Paths.get(genfile);
            try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8,
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                            StandardOpenOption.WRITE })) {
                if (cmd.getOptionValue("lang") != null) {
                    lang = cmd.getOptionValue("lang");
                }

                LinkedHashSet<String> listsystem = new LinkedHashSet<String>() {
                    {
                        add("com.android");
                        add("com.google.android");
                        //add("com.sec.android.app");
                        add("com.monotype.android");
                        add("eu.chainfire.supersu");
                    }
                };

                // \r\n for Windows Notepad
                gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                gen.write("<!-- & raplace with &amp; or use <![CDATA[ ]]> -->\r\n");
                gen.write("<AndroidUninstallStock>\r\n\r\n");
                gen.write("<Normal>\r\n");
                System.out.println();
                System.out.println("\tNormal:");
                writeInfo(gen, apklist, lang, listsystem, true);
                gen.write("\t<apk name=\"Exclude Google and etc\">\r\n");
                for (String exc : listsystem) {
                    gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n");
                }
                gen.write("\t</apk>\r\n");
                gen.write("</Normal>\r\n\r\n");
                gen.write("<Google>\r\n");
                System.out.println();
                System.out.println("\tGoogle:");
                writeInfo(gen, apklist, lang, listsystem, false);
                gen.write("</Google>\r\n\r\n");
                gen.write("</AndroidUninstallStock>\r\n");
                System.out.println("File " + genpath.toAbsolutePath() + " created.");
            }
            return;
        }

        String[] FileName = cmd.getArgs();
        if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) {
            System.out.println("Error: File " + FileName[0] + " not found!");
            return;
        }

        DocumentBuilderFactory xmlfactory = getXmlDocFactory();

        // DocumentBuilder.setErrorHandler() for print errors
        Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0]));

        LinkedList<AusInfo> Normal = new LinkedList<AusInfo>();
        LinkedList<AusInfo> Google = new LinkedList<AusInfo>();

        NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes();
        for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) {
            Node ndnow = ndaus.item(ndausx);
            NodeList nd = ndnow.getChildNodes();
            String ndname = ndnow.getNodeName();
            for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) {
                if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) {
                    continue;
                }
                if (ndname.equalsIgnoreCase("Normal")) {
                    Normal.add(getApkInfo(nd.item(ndx)));
                } else if (ndname.equalsIgnoreCase("Google")) {
                    Google.add(getApkInfo(nd.item(ndx)));
                }
            }
        }

        // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages.
        //       Now requires a restart.
        System.out.println();
        System.out.println("Include and Exclude packages (Normal):");
        LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false);
        System.out.println();
        System.out.println("Global Exclude packages (Normal):");
        apkNormal = getApkFromPattern(apkNormal, Normal, true);
        System.out.println();
        System.out.println("Final list packages (Normal):");
        for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>();
        if (cmd.hasOption("google")) {
            System.out.println();
            System.out.println("Include and Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apklist, Google, false);
            System.out.println();
            System.out.println("Global Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apkGoogle, Google, true);
            System.out.println();
            System.out.println("Final list packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) {
                System.out.println(info.getValue() + " = " + info.getKey());
            }
        }

        if (NotTest) {
            if (!hasRoot(adb)) {
                System.out.println("No Root");
                System.out.println();
                System.out.println("FINISH :)");
                return;
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println();
            System.out.println("Enable (Restore) packages (Normal):");
            damage(adb, "pm enable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Enable (Restore) packages (Google):");
                damage(adb, "pm enable ", NotTest, apkGoogle, 2);
            }
            System.out.println();
            System.out.println("FINISH :)");
            return;
        } else {
            System.out.println();
            System.out.println("Disable packages (Normal):");
            damage(adb, "pm disable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Disable packages (Google):");
                damage(adb, "pm disable ", NotTest, apkGoogle, 2);
            }
        }

        if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) {
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }

        // Reboot now not needed
        /*if (NotTest) {
        reboot(adb, "-s", lastdevice, "reboot");
        if (!hasRoot(adb)) {
            System.out.println("No Root");
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }
        }*/

        if (cmd.hasOption("unlib")) {
            // "find" not found
            System.out.println();
            System.out.println("Getting list libraries:");
            LinkedList<String> liblist = new LinkedList<String>();
            liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/"));
            String dircur = "/system/lib/";
            for (int x = 0; x < liblist.size(); x++) {
                if (liblist.get(x).startsWith("scan:")) {
                    dircur = liblist.get(x).substring("scan:".length());
                    liblist.remove(x);
                    x--;
                } else if (liblist.get(x).startsWith("d")) {
                    String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/";
                    liblist.remove(x);
                    x--;
                    liblist.add("scan:/system/lib/" + dir);
                    liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir));
                    continue;
                }
                liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4));
                System.out.println(liblist.get(x));
            }

            final boolean scanlibs = cmd.hasOption("scanlibs");
            LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal,
                    "Normal", scanlibs);
            libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal");
            System.out.println();
            System.out.println("Final list libraries (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                System.out.println(info.getKey() + " = " + info.getValue());
            }

            LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>();
            if (cmd.hasOption("google")) {
                libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs);
                libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google");
                System.out.println();
                System.out.println("Final list libraries (Google):");
                for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                    System.out.println(info.getKey() + " = " + info.getValue());
                }
            }

            LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist);
            for (String key : apkNormal.keySet()) {
                apkExclude.remove(key);
            }
            for (String key : apkGoogle.keySet()) {
                apkExclude.remove(key);
            }

            System.out.println();
            System.out.println("Include libraries from Exclude packages:");
            LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude);
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libNormal.remove(info.getKey());
                }
            }
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libGoogle.remove(info.getKey());
                }
            }

            System.out.println();
            System.out.println("Delete libraries (Normal):");
            damage(adb, "rm ", NotTest, libNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete libraries (Google):");
                damage(adb, "rm ", NotTest, libGoogle, 1);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Cleaning data packages (Normal):");
            damage(adb, "pm clear ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Cleaning data packages (Google):");
                damage(adb, "pm clear ", NotTest, apkGoogle, 2);
            }

            System.out.println();
            System.out.println("Uninstall packages (Normal):");
            damage(adb, "pm uninstall ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Uninstall packages (Google):");
                damage(adb, "pm uninstall ", NotTest, apkGoogle, 2);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Delete packages (Normal):");
            LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>();
            for (Map.Entry<String, String> apk : apkNormal.entrySet()) {
                dexNormal.put(apk.getKey(), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
            }
            damage(adb, "rm ", NotTest, dexNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete packages (Google):");
                LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>();
                for (Map.Entry<String, String> apk : apkGoogle.entrySet()) {
                    dexGoogle.put(apk.getKey(), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
                }
                damage(adb, "rm ", NotTest, dexGoogle, 1);
            }
        }

        if (NotTest) {
            run(adb, "-s", lastdevice, "reboot");
        }
        System.out.println();
        System.out.println("FINISH :)");
    } catch (SAXException e) {
        System.out.println("Error parsing list: " + e);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:org.sonatype.nexus.plugins.p2.repository.metadata.AbstractP2MetadataSource.java

protected static Map<String, StorageFileItem> createMetadataItems(final Repository repository,
        final String path, final String pathCompressed, final AbstractMetadata metadata, final String hack,
        final RequestContext context) throws IOException {
    LinkedHashMap<String, String> properties = metadata.getProperties();
    properties.remove(P2Constants.PROP_COMPRESSED);
    metadata.setProperties(properties);//from   w  w w.  ja v  a 2 s  .  c o  m

    Map<String, StorageFileItem> metadataItems = Maps.newHashMap();
    metadataItems.put(path, createMetadataItem(repository, path, metadata.getDom(), hack, context));

    properties = metadata.getProperties();
    properties.put(P2Constants.PROP_COMPRESSED, Boolean.TRUE.toString());
    metadata.setProperties(properties);

    metadataItems.put(pathCompressed, compressMetadataItem(repository, pathCompressed,
            createMetadataItem(repository, path, metadata.getDom(), hack, context)));
    return metadataItems;
}

From source file:com.espertech.esper.epl.spec.PatternStreamSpecRaw.java

private static void recursiveCompile(EvalFactoryNode evalNode, StatementContext context,
        ExprEvaluatorContext evaluatorContext, Set<String> eventTypeReferences, boolean isInsertInto,
        MatchEventSpec tags, Deque<Integer> subexpressionIdStack, Stack<EvalFactoryNode> parentNodeStack,
        LinkedHashSet<String> allTagNamesOrdered) throws ExprValidationException {
    int counter = 0;
    parentNodeStack.push(evalNode);//from w ww. j  a v a 2 s .  c  o  m
    for (EvalFactoryNode child : evalNode.getChildNodes()) {
        subexpressionIdStack.addLast(counter++);
        recursiveCompile(child, context, evaluatorContext, eventTypeReferences, isInsertInto, tags,
                subexpressionIdStack, parentNodeStack, allTagNamesOrdered);
        subexpressionIdStack.removeLast();
    }
    parentNodeStack.pop();

    LinkedHashMap<String, Pair<EventType, String>> newTaggedEventTypes = null;
    LinkedHashMap<String, Pair<EventType, String>> newArrayEventTypes = null;

    if (evalNode instanceof EvalFilterFactoryNode) {
        EvalFilterFactoryNode filterNode = (EvalFilterFactoryNode) evalNode;
        String eventName = filterNode.getRawFilterSpec().getEventTypeName();
        EventType resolvedEventType = FilterStreamSpecRaw.resolveType(context.getEngineURI(), eventName,
                context.getEventAdapterService(), context.getPlugInTypeResolutionURIs());
        EventType finalEventType = resolvedEventType;
        String optionalTag = filterNode.getEventAsName();
        boolean isPropertyEvaluation = false;
        boolean isParentMatchUntil = isParentMatchUntil(evalNode, parentNodeStack);

        // obtain property event type, if final event type is properties
        if (filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec() != null) {
            PropertyEvaluator optionalPropertyEvaluator = PropertyEvaluatorFactory.makeEvaluator(
                    filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec(), resolvedEventType,
                    filterNode.getEventAsName(), context.getEventAdapterService(),
                    context.getMethodResolutionService(), context.getSchedulingService(),
                    context.getVariableService(), context.getEngineURI(), context.getStatementId(),
                    context.getStatementName(), context.getAnnotations(), subexpressionIdStack,
                    context.getConfigSnapshot());
            finalEventType = optionalPropertyEvaluator.getFragmentEventType();
            isPropertyEvaluation = true;
        }

        if (finalEventType instanceof EventTypeSPI) {
            eventTypeReferences.add(((EventTypeSPI) finalEventType).getMetadata().getPrimaryName());
        }

        // If a tag was supplied for the type, the tags must stay with this type, i.e. a=BeanA -> b=BeanA -> a=BeanB is a no
        if (optionalTag != null) {
            Pair<EventType, String> pair = tags.getTaggedEventTypes().get(optionalTag);
            EventType existingType = null;
            if (pair != null) {
                existingType = pair.getFirst();
            }
            if (existingType == null) {
                pair = tags.getArrayEventTypes().get(optionalTag);
                if (pair != null) {
                    throw new ExprValidationException("Tag '" + optionalTag + "' for event '" + eventName
                            + "' used in the repeat-until operator cannot also appear in other filter expressions");
                }
            }
            if ((existingType != null) && (existingType != finalEventType)) {
                throw new ExprValidationException("Tag '" + optionalTag + "' for event '" + eventName
                        + "' has already been declared for events of type "
                        + existingType.getUnderlyingType().getName());
            }
            pair = new Pair<EventType, String>(finalEventType, eventName);

            // add tagged type
            if (isPropertyEvaluation || isParentMatchUntil) {
                newArrayEventTypes = new LinkedHashMap<String, Pair<EventType, String>>();
                newArrayEventTypes.put(optionalTag, pair);
            } else {
                newTaggedEventTypes = new LinkedHashMap<String, Pair<EventType, String>>();
                newTaggedEventTypes.put(optionalTag, pair);
            }
        }

        // For this filter, filter types are all known tags at this time,
        // and additionally stream 0 (self) is our event type.
        // Stream type service allows resolution by property name event if that name appears in other tags.
        // by defaulting to stream zero.
        // Stream zero is always the current event type, all others follow the order of the map (stream 1 to N).
        String selfStreamName = optionalTag;
        if (selfStreamName == null) {
            selfStreamName = "s_" + UuidGenerator.generate();
        }
        LinkedHashMap<String, Pair<EventType, String>> filterTypes = new LinkedHashMap<String, Pair<EventType, String>>();
        Pair<EventType, String> typePair = new Pair<EventType, String>(finalEventType, eventName);
        filterTypes.put(selfStreamName, typePair);
        filterTypes.putAll(tags.getTaggedEventTypes());

        // for the filter, specify all tags used
        LinkedHashMap<String, Pair<EventType, String>> filterTaggedEventTypes = new LinkedHashMap<String, Pair<EventType, String>>(
                tags.getTaggedEventTypes());
        filterTaggedEventTypes.remove(optionalTag);

        // handle array tags (match-until clause)
        LinkedHashMap<String, Pair<EventType, String>> arrayCompositeEventTypes = null;
        if (tags.getArrayEventTypes() != null && !tags.getArrayEventTypes().isEmpty()) {
            arrayCompositeEventTypes = new LinkedHashMap<String, Pair<EventType, String>>();
            String patternSubexEventType = getPatternSubexEventType(context.getStatementId(), "pattern",
                    subexpressionIdStack);

            for (Map.Entry<String, Pair<EventType, String>> entry : tags.getArrayEventTypes().entrySet()) {
                LinkedHashMap<String, Pair<EventType, String>> specificArrayType = new LinkedHashMap<String, Pair<EventType, String>>();
                specificArrayType.put(entry.getKey(), entry.getValue());
                EventType arrayTagCompositeEventType = context.getEventAdapterService()
                        .createSemiAnonymousMapType(patternSubexEventType,
                                Collections.<String, Pair<EventType, String>>emptyMap(), specificArrayType,
                                isInsertInto);

                String tag = entry.getKey();
                if (!filterTypes.containsKey(tag)) {
                    Pair<EventType, String> pair = new Pair<EventType, String>(arrayTagCompositeEventType, tag);
                    filterTypes.put(tag, pair);
                    arrayCompositeEventTypes.put(tag, pair);
                }
            }
        }

        StreamTypeService streamTypeService = new StreamTypeServiceImpl(filterTypes, context.getEngineURI(),
                true, false);
        List<ExprNode> exprNodes = filterNode.getRawFilterSpec().getFilterExpressions();

        FilterSpecCompiled spec = FilterSpecCompiler.makeFilterSpec(resolvedEventType, eventName, exprNodes,
                filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec(), filterTaggedEventTypes,
                arrayCompositeEventTypes, streamTypeService, null, context, subexpressionIdStack);
        filterNode.setFilterSpec(spec);
    } else if (evalNode instanceof EvalObserverFactoryNode) {
        EvalObserverFactoryNode observerNode = (EvalObserverFactoryNode) evalNode;
        try {
            ObserverFactory observerFactory = context.getPatternResolutionService()
                    .create(observerNode.getPatternObserverSpec());

            StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(),
                    context.getStatementId(), context.getEventAdapterService(), tags.getTaggedEventTypes(),
                    tags.getArrayEventTypes(), subexpressionIdStack, "observer");
            ExprValidationContext validationContext = new ExprValidationContext(streamTypeService,
                    context.getMethodResolutionService(), null, context.getSchedulingService(),
                    context.getVariableService(), evaluatorContext, context.getEventAdapterService(),
                    context.getStatementName(), context.getStatementId(), context.getAnnotations(),
                    context.getContextDescriptor());
            List<ExprNode> validated = validateExpressions(
                    observerNode.getPatternObserverSpec().getObjectParameters(), validationContext);

            MatchedEventConvertor convertor = new MatchedEventConvertorImpl(tags.getTaggedEventTypes(),
                    tags.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService());

            observerNode.setObserverFactory(observerFactory);
            observerFactory.setObserverParameters(validated, convertor);
        } catch (ObserverParameterException e) {
            throw new ExprValidationException("Invalid parameter for pattern observer: " + e.getMessage(), e);
        } catch (PatternObjectException e) {
            throw new ExprValidationException("Failed to resolve pattern observer: " + e.getMessage(), e);
        }
    } else if (evalNode instanceof EvalGuardFactoryNode) {
        EvalGuardFactoryNode guardNode = (EvalGuardFactoryNode) evalNode;
        try {
            GuardFactory guardFactory = context.getPatternResolutionService()
                    .create(guardNode.getPatternGuardSpec());

            StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(),
                    context.getStatementId(), context.getEventAdapterService(), tags.getTaggedEventTypes(),
                    tags.getArrayEventTypes(), subexpressionIdStack, "guard");
            ExprValidationContext validationContext = new ExprValidationContext(streamTypeService,
                    context.getMethodResolutionService(), null, context.getSchedulingService(),
                    context.getVariableService(), evaluatorContext, context.getEventAdapterService(),
                    context.getStatementName(), context.getStatementId(), context.getAnnotations(),
                    context.getContextDescriptor());
            List<ExprNode> validated = validateExpressions(
                    guardNode.getPatternGuardSpec().getObjectParameters(), validationContext);

            MatchedEventConvertor convertor = new MatchedEventConvertorImpl(tags.getTaggedEventTypes(),
                    tags.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService());

            guardNode.setGuardFactory(guardFactory);
            guardFactory.setGuardParameters(validated, convertor);
        } catch (GuardParameterException e) {
            throw new ExprValidationException("Invalid parameter for pattern guard: " + e.getMessage(), e);
        } catch (PatternObjectException e) {
            throw new ExprValidationException("Failed to resolve pattern guard: " + e.getMessage(), e);
        }
    } else if (evalNode instanceof EvalEveryDistinctFactoryNode) {
        EvalEveryDistinctFactoryNode distinctNode = (EvalEveryDistinctFactoryNode) evalNode;
        MatchEventSpec matchEventFromChildNodes = analyzeMatchEvent(distinctNode);
        StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(),
                context.getStatementId(), context.getEventAdapterService(),
                matchEventFromChildNodes.getTaggedEventTypes(), matchEventFromChildNodes.getArrayEventTypes(),
                subexpressionIdStack, "every-distinct");
        ExprValidationContext validationContext = new ExprValidationContext(streamTypeService,
                context.getMethodResolutionService(), null, context.getSchedulingService(),
                context.getVariableService(), evaluatorContext, context.getEventAdapterService(),
                context.getStatementName(), context.getStatementId(), context.getAnnotations(),
                context.getContextDescriptor());
        List<ExprNode> validated;
        try {
            validated = validateExpressions(distinctNode.getExpressions(), validationContext);
        } catch (ExprValidationPropertyException ex) {
            throw new ExprValidationPropertyException(ex.getMessage()
                    + ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct",
                    ex.getCause());
        }

        MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                matchEventFromChildNodes.getTaggedEventTypes(), matchEventFromChildNodes.getArrayEventTypes(),
                allTagNamesOrdered, context.getEventAdapterService());

        distinctNode.setConvertor(convertor);

        // Determine whether some expressions are constants or time period
        List<ExprNode> distinctExpressions = new ArrayList<ExprNode>();
        Long msecToExpire = null;
        for (ExprNode expr : validated) {
            if (expr instanceof ExprTimePeriod) {
                Double secondsExpire = (Double) ((ExprTimePeriod) expr).evaluate(null, true, evaluatorContext);
                if ((secondsExpire != null) && (secondsExpire > 0)) {
                    msecToExpire = Math.round(1000d * secondsExpire);
                }
                log.debug("Setting every-distinct msec-to-expire to " + msecToExpire);
            } else if (expr.isConstantResult()) {
                log.warn(
                        "Every-distinct node utilizes an expression returning a constant value, please check expression '"
                                + expr.toExpressionString()
                                + "', not adding expression to distinct-value expression list");
            } else {
                distinctExpressions.add(expr);
            }
        }
        if (distinctExpressions.isEmpty()) {
            throw new ExprValidationException(
                    "Every-distinct node requires one or more distinct-value expressions that each return non-constant result values");
        }
        distinctNode.setDistinctExpressions(distinctExpressions, msecToExpire);
    } else if (evalNode instanceof EvalMatchUntilFactoryNode) {
        EvalMatchUntilFactoryNode matchUntilNode = (EvalMatchUntilFactoryNode) evalNode;

        // compile bounds expressions, if any
        MatchEventSpec untilMatchEventSpec = new MatchEventSpec(tags.getTaggedEventTypes(),
                tags.getArrayEventTypes());
        StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(),
                context.getStatementId(), context.getEventAdapterService(),
                untilMatchEventSpec.getTaggedEventTypes(), untilMatchEventSpec.getArrayEventTypes(),
                subexpressionIdStack, "until");
        ExprValidationContext validationContext = new ExprValidationContext(streamTypeService,
                context.getMethodResolutionService(), null, context.getSchedulingService(),
                context.getVariableService(), evaluatorContext, context.getEventAdapterService(),
                context.getStatementName(), context.getStatementId(), context.getAnnotations(),
                context.getContextDescriptor());

        String message = "Match-until bounds value expressions must return a numeric value";
        if (matchUntilNode.getLowerBounds() != null) {
            ExprNode validated = ExprNodeUtility.getValidatedSubtree(matchUntilNode.getLowerBounds(),
                    validationContext);
            matchUntilNode.setLowerBounds(validated);
            if ((validated.getExprEvaluator().getType() == null)
                    || (!JavaClassHelper.isNumeric(validated.getExprEvaluator().getType()))) {
                throw new ExprValidationException(message);
            }
        }

        if (matchUntilNode.getUpperBounds() != null) {
            ExprNode validated = ExprNodeUtility.getValidatedSubtree(matchUntilNode.getUpperBounds(),
                    validationContext);
            matchUntilNode.setUpperBounds(validated);
            if ((validated.getExprEvaluator().getType() == null)
                    || (!JavaClassHelper.isNumeric(validated.getExprEvaluator().getType()))) {
                throw new ExprValidationException(message);
            }
        }

        MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                untilMatchEventSpec.getTaggedEventTypes(), untilMatchEventSpec.getArrayEventTypes(),
                allTagNamesOrdered, context.getEventAdapterService());
        matchUntilNode.setConvertor(convertor);

        // compile new tag lists
        Set<String> arrayTags = null;
        EvalNodeAnalysisResult matchUntilAnalysisResult = EvalNodeUtil
                .recursiveAnalyzeChildNodes(matchUntilNode.getChildNodes().get(0));
        for (EvalFilterFactoryNode filterNode : matchUntilAnalysisResult.getFilterNodes()) {
            String optionalTag = filterNode.getEventAsName();
            if (optionalTag != null) {
                if (arrayTags == null) {
                    arrayTags = new HashSet<String>();
                }
                arrayTags.add(optionalTag);
            }
        }

        if (arrayTags != null) {
            for (String arrayTag : arrayTags) {
                if (!tags.getArrayEventTypes().containsKey(arrayTag)) {
                    tags.getArrayEventTypes().put(arrayTag, tags.getTaggedEventTypes().get(arrayTag));
                    tags.getTaggedEventTypes().remove(arrayTag);
                }
            }
        }
        matchUntilNode.setTagsArrayedSet(getIndexesForTags(allTagNamesOrdered, arrayTags));
    } else if (evalNode instanceof EvalFollowedByFactoryNode) {
        EvalFollowedByFactoryNode followedByNode = (EvalFollowedByFactoryNode) evalNode;
        StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.getEngineURI(), false);
        ExprValidationContext validationContext = new ExprValidationContext(streamTypeService,
                context.getMethodResolutionService(), null, context.getSchedulingService(),
                context.getVariableService(), evaluatorContext, context.getEventAdapterService(),
                context.getStatementName(), context.getStatementId(), context.getAnnotations(),
                context.getContextDescriptor());

        if (followedByNode.getOptionalMaxExpressions() != null) {
            List<ExprNode> validated = new ArrayList<ExprNode>();
            for (ExprNode maxExpr : followedByNode.getOptionalMaxExpressions()) {
                if (maxExpr == null) {
                    validated.add(null);
                } else {
                    ExprNodeSummaryVisitor visitor = new ExprNodeSummaryVisitor();
                    maxExpr.accept(visitor);
                    if (!visitor.isPlain()) {
                        String errorMessage = "Invalid maximum expression in followed-by, "
                                + visitor.getMessage() + " are not allowed within the expression";
                        log.error(errorMessage);
                        throw new ExprValidationException(errorMessage);
                    }

                    ExprNode validatedExpr = ExprNodeUtility.getValidatedSubtree(maxExpr, validationContext);
                    validated.add(validatedExpr);
                    if ((validatedExpr.getExprEvaluator().getType() == null)
                            || (!JavaClassHelper.isNumeric(validatedExpr.getExprEvaluator().getType()))) {
                        String message = "Invalid maximum expression in followed-by, the expression must return an integer value";
                        throw new ExprValidationException(message);
                    }
                }
            }
            followedByNode.setOptionalMaxExpressions(validated);
        }
    }

    if (newTaggedEventTypes != null) {
        tags.getTaggedEventTypes().putAll(newTaggedEventTypes);
    }
    if (newArrayEventTypes != null) {
        tags.getArrayEventTypes().putAll(newArrayEventTypes);
    }
}

From source file:org.apache.hadoop.hive.ql.exec.ExecDriver.java

/**
 * Handle a empty/null path for a given alias.
 *//*from   w  w  w. j a  v  a 2 s . c  o m*/
private static int addInputPath(String path, JobConf job, MapredWork work, String hiveScratchDir,
        int numEmptyPaths, boolean isEmptyPath, String alias) throws Exception {
    // either the directory does not exist or it is empty
    assert path == null || isEmptyPath;

    // The input file does not exist, replace it by a empty file
    Class<? extends HiveOutputFormat> outFileFormat = null;
    boolean nonNative = true;
    Properties props;
    if (isEmptyPath) {
        PartitionDesc partDesc = work.getPathToPartitionInfo().get(path);
        props = partDesc.getProperties();
        outFileFormat = partDesc.getOutputFileFormatClass();
        nonNative = partDesc.getTableDesc().isNonNative();
    } else {
        TableDesc tableDesc = work.getAliasToPartnInfo().get(alias).getTableDesc();
        props = tableDesc.getProperties();
        outFileFormat = tableDesc.getOutputFileFormatClass();
        nonNative = tableDesc.isNonNative();
    }

    if (nonNative) {
        FileInputFormat.addInputPaths(job, path);
        LOG.info("Add a non-native table " + path);
        return numEmptyPaths;
    }

    // create a dummy empty file in a new directory
    String newDir = hiveScratchDir + File.separator + (++numEmptyPaths);
    Path newPath = new Path(newDir);
    FileSystem fs = newPath.getFileSystem(job);
    fs.mkdirs(newPath);
    //Qualify the path against the filesystem. The user configured path might contain default port which is skipped
    //in the file status. This makes sure that all paths which goes into PathToPartitionInfo are always listed status
    //filepath.
    newPath = fs.makeQualified(newPath);
    String newFile = newDir + File.separator + "emptyFile";
    Path newFilePath = new Path(newFile);

    LOG.info("Changed input file to " + newPath.toString());

    // toggle the work

    LinkedHashMap<String, ArrayList<String>> pathToAliases = work.getPathToAliases();

    if (isEmptyPath) {
        assert path != null;
        pathToAliases.put(newPath.toUri().toString(), pathToAliases.get(path));
        pathToAliases.remove(path);
    } else {
        assert path == null;
        ArrayList<String> newList = new ArrayList<String>();
        newList.add(alias);
        pathToAliases.put(newPath.toUri().toString(), newList);
    }

    work.setPathToAliases(pathToAliases);

    LinkedHashMap<String, PartitionDesc> pathToPartitionInfo = work.getPathToPartitionInfo();
    if (isEmptyPath) {
        pathToPartitionInfo.put(newPath.toUri().toString(), pathToPartitionInfo.get(path));
        pathToPartitionInfo.remove(path);
    } else {
        PartitionDesc pDesc = work.getAliasToPartnInfo().get(alias).clone();
        pathToPartitionInfo.put(newPath.toUri().toString(), pDesc);
    }
    work.setPathToPartitionInfo(pathToPartitionInfo);

    String onefile = newPath.toString();
    RecordWriter recWriter = outFileFormat.newInstance().getHiveRecordWriter(job, newFilePath, Text.class,
            false, props, null);
    recWriter.close(false);
    FileInputFormat.addInputPaths(job, onefile);
    return numEmptyPaths;
}

From source file:org.sonatype.nexus.plugins.p2.repository.proxy.P2ProxyMetadataSource.java

@Override
protected Map<String, StorageFileItem> doRetrieveContentFileItems(final RequestContext context,
        final P2ProxyRepository repository) throws RemoteStorageException, ItemNotFoundException {
    Xpp3Dom dom;//from   ww w.  ja  v a 2s  .  co m

    try {
        final File metadataRepositoryDir = File.createTempFile("content", "");
        DirSupport.delete(metadataRepositoryDir.toPath());
        DirSupport.mkdir(metadataRepositoryDir.toPath());

        try {
            String username = null;
            String password = null;
            final RemoteAuthenticationSettings remoteAuthenticationSettings = repository
                    .getRemoteAuthenticationSettings();
            if (remoteAuthenticationSettings instanceof UsernamePasswordRemoteAuthenticationSettings) {
                final UsernamePasswordRemoteAuthenticationSettings upras = (UsernamePasswordRemoteAuthenticationSettings) remoteAuthenticationSettings;
                username = upras.getUsername();
                password = upras.getPassword();
            }

            try {
                metadataRepository.createProxyRepository(new URI(repository.getRemoteUrl()), username, password,
                        metadataRepositoryDir.toURI());
            } catch (RuntimeException e) {
                // another implementation detail: M2 proxy with bad URL would just bore you with 404s
                // while P2 would return HTTP 500 Internal Error
                // while the path will not be quite exact (we are NOT asking for XML but P2 engine does multiple
                // queries, but the meaning is fine for now
                throw new P2RuntimeExceptionMaskedAsINFException(
                        new ResourceStoreRequest(repository.getRemoteUrl() + "content.xml"), repository, e);
            }

            dom = Xpp3DomBuilder.build(new XmlStreamReader(new File(metadataRepositoryDir, "content.xml")));
        } finally {
            FileUtils.deleteDirectory(metadataRepositoryDir);
        }
    } catch (final XmlPullParserException e) {
        throw new RemoteStorageException(e);
    } catch (final URISyntaxException e) {
        throw new RemoteStorageException(e);
    } catch (final IOException e) {
        throw new RemoteStorageException(e);
    }

    final Content metadata = new Content(dom);
    metadata.setRepositoryAttributes(repository.getName());
    final LinkedHashMap<String, String> properties = metadata.getProperties();
    properties.remove(P2Constants.PROP_MIRRORS_URL);
    metadata.setProperties(properties);

    try {
        return createMetadataItems(repository, P2Constants.CONTENT_XML, P2Constants.CONTENT_JAR, metadata,
                P2Constants.XMLPI_CONTENT, context);
    } catch (IOException e) {
        throw new RemoteStorageException(e);
    }
}

From source file:com.nextdoor.bender.ipc.s3.S3Transport.java

@Override
public void sendBatch(TransportBuffer buffer, LinkedHashMap<String, String> partitions, Context context)
        throws TransportException {
    S3TransportBuffer buf = (S3TransportBuffer) buffer;

    /*/*from  w  w w . j av  a2s  .  c o m*/
     * Create s3 key (filepath + filename)
     */
    LinkedHashMap<String, String> parts = new LinkedHashMap<String, String>(partitions);

    String filename = parts.remove(FILENAME_KEY);

    if (filename == null) {
        filename = context.getAwsRequestId();
    }

    String key = parts.entrySet().stream().map(s -> s.getKey() + "=" + s.getValue())
            .collect(Collectors.joining("/"));

    key = (key.equals("") ? filename : key + '/' + filename);

    if (this.basePath.endsWith("/")) {
        key = this.basePath + key;
    } else if (!this.basePath.equals("")) {
        key = this.basePath + '/' + key;
    }

    // TODO: make this dynamic
    if (key.endsWith(".gz")) {
        key = key.substring(0, key.length() - 3);
    }

    /*
     * Add or strip out compression format extension
     *
     * TODO: get this based on the compression codec
     */
    if (this.compress || buf.isCompressed()) {
        key += ".bz2";
    }

    ByteArrayOutputStream os = buf.getInternalBuffer();

    /*
     * Compress stream if needed. Don't compress a compressed stream.
     */
    ByteArrayOutputStream payload;
    if (this.compress && !buf.isCompressed()) {
        payload = compress(os);
    } else {
        payload = os;
    }

    /*
     * For memory efficiency convert the output stream into an InputStream. This is done using the
     * easystream library but under the hood it uses piped streams to facilitate this process. This
     * avoids copying the entire contents of the OutputStream to populate the InputStream. Note that
     * this process creates another thread to consume from the InputStream.
     */
    final String s3Key = key;

    /*
     * Write to OutputStream
     */
    final InputStreamFromOutputStream<String> isos = new InputStreamFromOutputStream<String>() {
        public String produce(final OutputStream dataSink) throws Exception {
            /*
             * Note this is executed in a different thread
             */
            payload.writeTo(dataSink);
            return null;
        }
    };

    /*
     * Consume InputStream
     */
    try {
        sendStream(isos, s3Key, payload.size());
    } finally {
        try {
            isos.close();
        } catch (IOException e) {
            throw new TransportException(e);
        } finally {
            buf.close();
        }
    }
}

From source file:guru.qas.martini.scope.ScenarioScope.java

protected void runDestructionCallbacks() {
    LinkedHashMap<String, Runnable> index = DESTRUCTION_CALLBACKS.get();
    DESTRUCTION_CALLBACKS.remove();/*from  w w w.  j  a  va2 s  .  c  o m*/
    List<String> names = Lists.reverse(Lists.newArrayList(index.keySet()));
    for (String name : names) {
        Runnable callback = index.remove(name);
        run(name, callback);
    }
}

From source file:edu.csun.ecs.cs.multitouchj.ui.event.ObjectEventManager.java

protected void handleObjectObserverEvent(ObjectType objectType, ObjectObserverEvent event) {
    if (isRunning()) {
        synchronized (activeObjects) {
            LinkedHashMap<Integer, ObjectObserverEvent> objects = activeObjects.get(objectType);
            // remove is needed to keep its order
            if (objects.containsKey(event.getId())) {
                objects.remove(event.getId());
            }/*from ww w  .java2s  .  c  o  m*/
            objects.put(event.getId(), event);

            setUpdated(true);
        }
    }
}

From source file:AndroidUninstallStock.java

public static LinkedHashMap<String, String> getLibFromPatternInclude(String adb, LinkedList<String> liblist,
        LinkedHashMap<String, String> apklist, LinkedList<AusInfo> section, String sectionname,
        boolean scanlibs) throws IOException {
    LinkedHashMap<String, String> libinclude = new LinkedHashMap<String, String>();
    if (scanlibs) {
        System.out.println();// w  w  w  . ja  va 2 s .c  o  m
        System.out.println("Include libraries from packages (" + sectionname + "):");
        libinclude = getLibFromPackage(adb, liblist, apklist);
    }

    System.out.println();
    System.out.println("Include libraries from section (" + sectionname + "):");
    LinkedHashMap<String, String> maplist = new LinkedHashMap<String, String>();
    for (String path : liblist) {
        maplist.put(path, "");
    }
    for (AusInfo info : section) {
        System.out.println("* " + info.apk.get("name"));
        LinkedHashMap<String, String> inc = new LinkedHashMap<String, String>();
        for (HashMap<String, String> pattern : info.include) {
            inc.putAll(_getListFromPattern(maplist, pattern, info, "include: ", true));
        }
        for (HashMap<String, String> pattern : info.exclude) {
            if (getBoolean(pattern.get("global"))) {
                continue;
            }
            for (Map.Entry<String, String> exc : _getListFromPattern(inc, pattern, info, "exclude: ", true)
                    .entrySet()) {
                inc.remove(exc.getKey());
            }
        }
        libinclude.putAll(inc);
    }

    return libinclude;
}