Example usage for java.util Map put

List of usage examples for java.util Map put

Introduction

In this page you can find the example usage for java.util Map put.

Prototype

V put(K key, V value);

Source Link

Document

Associates the specified value with the specified key in this map (optional operation).

Usage

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFMapQuerySpecificInvisibleMethodDeclarations.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//  w ww  .  j a va2  s  . c o m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = NeoEMFMapQuerySpecificInvisibleMethodDeclarations.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        // Add the LoadedObjectCounter store
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        //         storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING);
        storeOptions.add(MapResourceOptions.EStoreMapOption.AUTOCOMMIT);
        storeOptions.add(PersistentResourceOptions.EStoreOption.ESTRUCUTRALFEATURE_CACHING);
        storeOptions.add(PersistentResourceOptions.EStoreOption.IS_SET_CACHING);
        storeOptions.add(PersistentResourceOptions.EStoreOption.SIZE_CACHING);
        loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions);
        resource.load(loadOpts);
        {
            Runtime.getRuntime().gc();
            long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                    MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<MethodDeclaration> list = ASE2015JavaQueries.getSpecificInvisibleMethodDeclarations(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            Runtime.getRuntime().gc();
            long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
            LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:de.tu_berlin.dima.oligos.Oligos.java

public static void main(String[] args) throws TypeNotSupportedException {
    BasicConfigurator.configure();/*from   ww  w  . j a va 2s  .  c  o m*/

    // TODO create cmdline option for setting logger level
    Logger.getRootLogger().setLevel(Level.INFO);
    CommandLineInterface cli = new CommandLineInterface(args);
    try {
        // TODO hard exit if the parsing fails!
        // better catch exceptions and log them
        if (!cli.parse()) {
            System.exit(2);
        }

        Properties props = new Properties();
        props.setProperty("user", cli.getUsername());
        props.setProperty("password", cli.getPassword());
        Connection connection = DriverManager.getConnection(cli.getConnectionString(), props);
        JdbcConnector jdbcConnector = new JdbcConnector(connection);
        MetaConnector metaConnector = null;
        Driver dbDriver = cli.dbDriver;
        switch (dbDriver.driverName) {
        case db2:
            LOGGER.trace("metaConnector = Db2MetaConnector");
            metaConnector = new Db2MetaConnector(jdbcConnector);
            break;
        case oracle:
            metaConnector = new OracleMetaConnector(jdbcConnector);
            break;
        default:
            LOGGER.error("Unknown database driver. Supported drivers are: " + DriverName.values());
        }

        // validating schema
        LOGGER.info("Validating input schema ...");
        SparseSchema sparseSchema = cli.getInputSchema();
        LOGGER.trace("User specified schema " + sparseSchema);
        DenseSchema inputSchema = DbUtils.populateSchema(sparseSchema, jdbcConnector, metaConnector);
        LOGGER.trace("Populated and validated schema " + inputSchema);

        // obtaining type information/ column meta data
        LOGGER.info("Retrieving column meta data ...");
        Map<ColumnId, TypeInfo> columnTypes = Maps.newLinkedHashMap();
        for (ColumnId columnId : inputSchema) {
            TypeInfo type = metaConnector.getColumnType(columnId);
            columnTypes.put(columnId, type);
        }

        // creating connectors and profilers
        LOGGER.info("Establashing database connection ...");
        SchemaConnector schemaConnector = null;
        TableConnector tableConnector = null;
        switch (dbDriver.driverName) {
        case db2:
            schemaConnector = new Db2SchemaConnector(jdbcConnector);
            tableConnector = new Db2TableConnector(jdbcConnector);
            break;
        case oracle:
            schemaConnector = new OracleSchemaConnector(jdbcConnector);
            tableConnector = new OracleTableConnector(jdbcConnector);
        }
        Set<SchemaProfiler> profilers = Sets.newLinkedHashSet();
        for (String schema : inputSchema.schemas()) {
            SchemaProfiler schemaProfiler = new SchemaProfiler(schema, schemaConnector);
            profilers.add(schemaProfiler);
            for (String table : inputSchema.tablesIn(schema)) {
                TableProfiler tableProfiler = new TableProfiler(schema, table, tableConnector);
                schemaProfiler.add(tableProfiler);
                for (String column : inputSchema.columnsIn(schema, table)) {
                    ColumnId columnId = new ColumnId(schema, table, column);
                    TypeInfo type = columnTypes.get(columnId);
                    ColumnProfiler<?> columnProfiler = null;
                    switch (dbDriver.driverName) {
                    case db2:
                        columnProfiler = getProfiler(schema, table, column, type, jdbcConnector, metaConnector);
                        break;
                    case oracle:
                        columnProfiler = getProfilerOracle(schema, table, column, type, jdbcConnector,
                                metaConnector);
                    }
                    tableProfiler.addColumnProfiler(columnProfiler);
                }
            }
        }
        // profiling statistical data
        LOGGER.info("Profiling schema ...");
        Set<Schema> profiledSchemas = Sets.newLinkedHashSet();
        for (SchemaProfiler schemaProfiler : profilers) {
            Schema profiledSchema = schemaProfiler.profile();
            profiledSchemas.add(profiledSchema);
        }

        LOGGER.info("Generating generator specification ...");
        File outputDir = cli.getOutputDirectory();
        String generatorName = cli.getGeneratorName();
        LOGGER.info("Writing generator specification ...");
        for (Schema schema : profiledSchemas) {
            MyriadWriter writer = new MyriadWriter(schema, outputDir, generatorName);
            writer.write();
        }
        LOGGER.info("Closing database connection ...");
        connection.close();
    } catch (SQLException e) {
        LOGGER.error(e.getLocalizedMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (IOException e) {
        LOGGER.error(e.getLocalizedMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } catch (ParseException e) {
        LOGGER.error(e.getMessage());
        cli.printHelpMessage();
    }
}

From source file:ca.uqac.info.monitor.BeepBeepMonitor.java

public static void main(String[] args) {
    int verbosity = 1, slowdown = 0, tcp_port = 0;
    boolean show_stats = false, to_stdout = false;
    String trace_filename = "", pipe_filename = "", event_name = "message";
    final MonitorFactory mf = new MonitorFactory();

    // In case we open a socket
    ServerSocket m_serverSocket = null;
    Socket m_connection = null;/*from w  w  w .  ja va2 s . c om*/

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2008-2013 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file COPYING for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("version")) {
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("slowdown")) {
        slowdown = Integer.parseInt(c_line.getOptionValue("slowdown"));
        if (verbosity > 0)
            System.err.println("Slowdown factor: " + slowdown + " ms");
    }
    if (c_line.hasOption("stats")) {
        show_stats = true;
    }
    if (c_line.hasOption("csv")) {
        // Will output data in CSV format to stdout
        to_stdout = true;
    }
    if (c_line.hasOption("eventname")) {
        // Set event name
        event_name = c_line.getOptionValue("eventname");
    }
    if (c_line.hasOption("t")) {
        // Read events from a trace
        trace_filename = c_line.getOptionValue("t");
    }
    if (c_line.hasOption("p")) {
        // Read events from a pipe
        pipe_filename = c_line.getOptionValue("p");
    }
    if (c_line.hasOption("k")) {
        // Read events from a TCP port
        tcp_port = Integer.parseInt(c_line.getOptionValue("k"));
    }
    if (!trace_filename.isEmpty() && !pipe_filename.isEmpty()) {
        System.err.println("ERROR: you must specify at most one of trace file or named pipe");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no input formula specified");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    // Instantiate the event notifier
    boolean notify = (verbosity > 0);
    EventNotifier en = new EventNotifier(notify);
    en.m_slowdown = slowdown;
    en.m_csvToStdout = to_stdout;
    // Create one monitor for each input file and add it to the notifier 
    for (String formula_filename : remaining_args) {
        try {
            String formula_contents = FileReadWrite.readFile(formula_filename);
            Operator op = Operator.parseFromString(formula_contents);
            op.accept(mf);
            Monitor mon = mf.getMonitor();
            Map<String, String> metadata = getMetadata(formula_contents);
            metadata.put("Filename", formula_filename);
            en.addMonitor(mon, metadata);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(ERR_IO);
        } catch (Operator.ParseException e) {
            System.err.println("Error parsing input formula");
            System.exit(ERR_PARSE);
        }
    }

    // Read trace and iterate
    // Opens file
    PipeReader pr = null;
    try {
        if (!pipe_filename.isEmpty()) {
            // We tell the pipe reader we read a pipe
            File f = new File(pipe_filename);
            if (verbosity > 0)
                System.err.println("Reading from pipe named " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, false);
        } else if (!trace_filename.isEmpty()) {
            // We tell the pipe reader we read a regular file
            File f = new File(trace_filename);
            if (verbosity > 0)
                System.err.println("Reading from file " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, true);
        } else if (tcp_port > 0) {
            // We tell the pipe reader we read from a socket
            if (verbosity > 0)
                System.err.println("Reading from TCP port " + tcp_port);
            m_serverSocket = new ServerSocket(tcp_port);
            m_connection = m_serverSocket.accept();
            pr = new PipeReader(m_connection.getInputStream(), en, false);
        } else {
            // We tell the pipe reader we read from standard input
            if (verbosity > 0)
                System.err.println("Reading from standard input");
            pr = new PipeReader(System.in, en, false);
        }
    } catch (FileNotFoundException ex) {
        // We print both trace and pipe since one of them must be empty
        System.err.println("ERROR: file not found " + trace_filename + pipe_filename);
        System.exit(ERR_IO);
    } catch (IOException e) {
        // Caused by socket error
        e.printStackTrace();
        System.exit(ERR_IO);
    }
    pr.setSeparator("<" + event_name + ">", "</" + event_name + ">");

    // Check parameters for the event notifier
    if (c_line.hasOption("no-trigger")) {
        en.m_notifyOnVerdict = false;
    } else {
        en.m_notifyOnVerdict = true;
    }
    if (c_line.hasOption("mirror")) {
        en.m_mirrorEventsOnStdout = true;
    }

    // Start event notifier
    en.reset();
    Thread th = new Thread(pr);
    long clock_start = System.nanoTime();
    th.start();
    try {
        th.join(); // Wait for thread to finish
    } catch (InterruptedException e1) {
        // Thread is finished
    }
    if (tcp_port > 0 && m_serverSocket != null) {
        // We opened a socket; now we close it
        try {
            m_serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    long clock_end = System.nanoTime();
    int ret_code = pr.getReturnCode();
    switch (ret_code) {
    case PipeReader.ERR_EOF:
        if (verbosity > 0)
            System.err.println("\nEnd of file reached");
        break;
    case PipeReader.ERR_EOT:
        if (verbosity > 0)
            System.err.println("\nEOT received on pipe: closing");
        break;
    case PipeReader.ERR_OK:
        // Do nothing
        break;
    default:
        // An error
        System.err.println("Runtime error");
        System.exit(ERR_RUNTIME);
        break;
    }
    if (show_stats) {
        if (verbosity > 0) {
            System.out.println("Messages:   " + en.m_numEvents);
            System.out.println("Time:       " + (int) (en.m_totalTime / 1000000f) + " ms");
            System.out.println("Clock time: " + (int) ((clock_end - clock_start) / 1000000f) + " ms");
            System.out.println("Max heap:   " + (int) (en.heapSize / 1048576f) + " MB");
        } else {
            // If stats are asked but verbosity = 0, only show time value
            // (both monitor and wall clock) 
            System.out.print((int) (en.m_totalTime / 1000000f));
            System.out.print(",");
            System.out.print((int) ((clock_end - clock_start) / 1000000f));
        }
    }
    System.exit(ERR_OK);
}

From source file:com.me.jvmi.Main.java

public static void main(String[] args) throws IOException {

    final Path localProductImagesPath = Paths.get("/Volumes/jvmpubfs/WEB/images/products/");
    final Path uploadCSVFile = Paths.get("/Users/jbabic/Documents/products/upload.csv");
    final Config config = new Config(Paths.get("../config.properties"));

    LuminateOnlineClient luminateClient2 = new LuminateOnlineClient("https://secure2.convio.net/jvmi/admin/",
            3);//from w  ww. ja  v a 2s.c om
    luminateClient2.login(config.luminateUser(), config.luminatePassword());

    Set<String> completed = new HashSet<>(
            IOUtils.readLines(Files.newBufferedReader(Paths.get("completed.txt"))));

    try (InputStream is = Files.newInputStream(Paths.get("donforms.csv"));
            PrintWriter pw = new PrintWriter(new FileOutputStream(new File("completed.txt"), true))) {

        for (String line : IOUtils.readLines(is)) {
            if (completed.contains(line)) {
                System.out.println("completed: " + line);
                continue;
            }
            try {
                luminateClient2.editDonationForm(line, "-1");
                pw.println(line);
                System.out.println("done: " + line);
                pw.flush();
            } catch (Exception e) {
                System.out.println("skipping: " + line);
                e.printStackTrace();
            }
        }
    }

    //        luminateClient2.editDonationForm("8840", "-1");
    //        Collection<String> ids = luminateClient2.donFormSearch("", true);
    //        
    //        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
    //        try (FileWriter fileWriter = new FileWriter(new File("donforms.csv"));
    //                CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);) {
    //
    //            for (String id : ids) {
    //                csvFilePrinter.printRecord(id);
    //            }
    //        }
    //        

    if (true) {
        return;
    }

    Collection<InputRecord> records = parseInput(uploadCSVFile);

    LuminateFTPClient ftp = new LuminateFTPClient("customerftp.convio.net");
    ftp.login(config.ftpUser(), config.ftpPassword());

    ProductImages images = new ProductImages(localProductImagesPath, ftp);

    validateImages(records, images);

    Map<String, DPCSClient> dpcsClients = new HashMap<>();
    dpcsClients.put("us", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvm"));
    dpcsClients.put("ca", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvcn"));
    dpcsClients.put("uk", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvuk"));

    for (DPCSClient client : dpcsClients.values()) {
        client.login(config.dpcsUser(), config.dpcsPassword());
    }

    Map<String, LuminateOnlineClient> luminateClients = new HashMap<>();
    luminateClients.put("us", new LuminateOnlineClient("https://secure2.convio.net/jvmi/admin/", 10));
    luminateClients.put("ca", new LuminateOnlineClient("https://secure3.convio.net/jvmica/admin/", 10));
    luminateClients.put("uk", new LuminateOnlineClient("https://secure3.convio.net/jvmiuk/admin/", 10));

    Map<String, EcommerceProductFactory> ecommFactories = new HashMap<>();
    ecommFactories.put("us", new EcommerceProductFactory(dpcsClients.get("us"), images, Categories.us));
    ecommFactories.put("ca", new EcommerceProductFactory(dpcsClients.get("ca"), images, Categories.ca));
    ecommFactories.put("uk", new EcommerceProductFactory(dpcsClients.get("uk"), images, Categories.uk));

    List<String> countries = Arrays.asList("us", "ca", "uk");

    boolean error = false;
    for (InputRecord record : records) {
        for (String country : countries) {
            if (record.ignore(country)) {
                System.out.println("IGNORE: " + country + " " + record);
                continue;
            }
            try {
                EcommerceProductFactory ecommFactory = ecommFactories.get(country);
                LuminateOnlineClient luminateClient = luminateClients.get(country);
                luminateClient.login(config.luminateUser(), config.luminatePassword());

                ECommerceProduct product = ecommFactory.createECommerceProduct(record);
                luminateClient.createOrUpdateProduct(product);
            } catch (Exception e) {
                System.out.println("ERROR: " + country + " " + record);
                //System.out.println(e.getMessage());
                error = true;
                e.printStackTrace();
            }
        }
    }

    if (!error) {
        for (String country : countries) {
            LuminateOnlineClient luminateClient = luminateClients.get(country);
            DPCSClient dpcsClient = dpcsClients.get(country);
            luminateClient.close();
            dpcsClient.close();
        }
    }
}

From source file:com.nick.bpit.CcsClient.java

public static void main(String... args) {
    RegIdManager idManager = new RegIdManager();
    String message = args[0];//from   ww  w.  j a va  2  s .  c  om
    String regId = "";
    CcsClient ccsClient = CcsClient.prepareClient(PROJET_NUMBER, SERVER_KEY, true);
    try {
        regId = idManager.getAdmin();
    } catch (Exception e) {
        System.out.println("Reading failed.\n" + e);
    }
    try {
        ccsClient.connect();
    } catch (XMPPException e) {
        System.out.println("Could not connect to CCS.\n" + e);
    }

    // Send a sample downstream message to a device.
    String messageId = ccsClient.getRandomMessageId();
    Map<String, String> payload = new HashMap<>();
    Map<String, String> notification = new HashMap<>();

    payload.put(MESSAGE, message);
    payload.put(EMAIL, "SERVER");
    payload.put(TIMESTAMP, TimeStamp.getTimeStamp());
    payload.put(ACTION, "BROADCAST");
    /*
    notification.put("title", "Nick's Server");
    notification.put("body", payload.get(Config.MESSAGE));
    notification.put("click_action", "MAIN");
    notification.put("icon", "small_icon");
    */
    String collapseKey = "sample";
    Long timeToLive = 10000L;
    Boolean delayWhileIdle = true;

    ccsClient.send(createJsonMessage(regId, messageId, payload, null, collapseKey, timeToLive, delayWhileIdle));
}

From source file:mvm.rya.indexing.external.ExternalIndexMain.java

public static void main(String[] args) throws Exception {
    Preconditions.checkArgument(args.length == 6, "java " + ExternalIndexMain.class.getCanonicalName()
            + " sparqlFile cbinstance cbzk cbuser cbpassword rdfTablePrefix.");

    final String sparqlFile = args[0];

    instStr = args[1];/*from www . j av  a  2s. com*/
    zooStr = args[2];
    userStr = args[3];
    passStr = args[4];
    tablePrefix = args[5];

    String queryString = FileUtils.readFileToString(new File(sparqlFile));

    // Look for Extra Indexes
    Instance inst = new ZooKeeperInstance(instStr, zooStr);
    Connector c = inst.getConnector(userStr, passStr.getBytes());

    System.out.println("Searching for Indexes");
    Map<String, String> indexTables = Maps.newLinkedHashMap();
    for (String table : c.tableOperations().list()) {
        if (table.startsWith(tablePrefix + "INDEX_")) {
            Scanner s = c.createScanner(table, new Authorizations());
            s.setRange(Range.exact(new Text("~SPARQL")));
            for (Entry<Key, Value> e : s) {
                indexTables.put(table, e.getValue().toString());
            }
        }
    }

    List<ExternalTupleSet> index = Lists.newArrayList();

    if (indexTables.isEmpty()) {
        System.out.println("No Index found");
    } else {
        for (String table : indexTables.keySet()) {
            String indexSparqlString = indexTables.get(table);
            System.out.println("====================== INDEX FOUND ======================");
            System.out.println(" table : " + table);
            System.out.println(" sparql : ");
            System.out.println(indexSparqlString);

            index.add(new AccumuloIndexSet(indexSparqlString, c, table));
        }
    }

    // Connect to Rya
    Sail s = getRyaSail();
    SailRepository repo = new SailRepository(s);
    repo.initialize();

    // Perform Query

    CountingTupleQueryResultHandler count = new CountingTupleQueryResultHandler();

    SailRepositoryConnection conn;
    if (index.isEmpty()) {
        conn = repo.getConnection();

    } else {
        ExternalProcessor processor = new ExternalProcessor(index);

        Sail processingSail = new ExternalSail(s, processor);
        SailRepository smartSailRepo = new SailRepository(processingSail);
        smartSailRepo.initialize();

        conn = smartSailRepo.getConnection();
    }

    startTime = System.currentTimeMillis();
    lastTime = startTime;
    System.out.println("Query Started");
    conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString).evaluate(count);

    System.out.println("Count of Results found : " + count.i);
    System.out.println("Total query time (s) : " + (System.currentTimeMillis() - startTime) / 1000.);
}

From source file:net.itransformers.idiscover.core.DiscoveryManager.java

public static void main(String[] args) throws Exception, IllegalAccessException, JAXBException {
    Map<String, String> params = CmdLineParser.parseCmdLine(args);
    if (params == null) {
        printUsage("mibDir");
        return;/*from  ww  w . jav  a 2s  . com*/
    }
    final String fileName = params.get("-f");
    if (fileName == null) {
        printUsage("fileName");
        return;
    }
    File file = new File(fileName);

    DiscoveryManager manager = createDiscoveryManager(file.getParentFile(), file.getName(), "network", true);

    String mode = params.get("-d");
    if (mode == null) {
        //Set default snmpDiscovery mode to discover network!!!
        mode = "network";
    }

    Map<String, String> resourceSelectionParams = new HashMap<String, String>();
    resourceSelectionParams.put("protocol", "SNMP");
    ResourceType snmp = manager.discoveryResource.returnResourceByParam(resourceSelectionParams);

    Map<String, String> snmpConnParams = new HashMap<String, String>();
    snmpConnParams = manager.discoveryResource.getParamMap(snmp, "snmp");

    String host = params.get("-h");
    IPv4Address initialIPaddress = new IPv4Address(host, null);
    snmpConnParams.put("status", "initial");
    String mibDir = params.get("-m");
    snmpConnParams.put("mibDir", mibDir);

    snmpConnParams.get("port");
    Resource resource = new Resource(initialIPaddress, null, Integer.parseInt(snmpConnParams.get("port")),
            snmpConnParams);

    if (resource == null)
        ;

    String[] discoveryTypes = new String[] { "PHYSICAL", "NEXT_HOP", "OSPF", "ISIS", "BGP", "RIP", "ADDITIONAL",
            "IPV6" };

    //        DiscovererFactory.init(new SimulSnmpWalker(resource, new File("logs.log")));
    //        DiscovererFactory.init();
    //        Discoverer discoverer = new SnmpWalker(resource);
    NetworkType network = manager.discoverNetwork(resource, mode, discoveryTypes);

    for (DiscoveredDeviceData data : network.getDiscoveredDevice()) {
        System.out.println(data.getName() + "\n");
        for (ObjectType object : data.getObject()) {
            for (ObjectType innterObject : object.getObject()) {
                System.out.println(innterObject.getObjectType());
            }
        }

    }
    //        List<DiscoveredDeviceData> discoveredDeviceDatas = network.getDiscoveredDevice();
    //        for (DiscoveredDeviceData discoveredDeviceData : discoveredDeviceDatas) {
    //            discoveredDeviceData.getName();
    //            ParametersType parameters = discoveredDeviceData.getParameters();
    //            List<ParameterType> paras =   parameters.getParameter();
    //            for (ParameterType para : paras) {
    //
    //            }
    //
    //        }

}

From source file:com.joymove.service.impl.JOYUserServiceImpl.java

public static void main(String[] args) throws Exception {

    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:test.xml");
    Map<String, Object> likeCondition = new HashMap<String, Object>();
    JOYUser user = new JOYUser();
    DateFormat formatWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    user.registerTime = formatWithTime.parse("2013-04-29 15:08:41");

    JOYUserDao dao = (JOYUserDao) context.getBean("JOYUserDao");
    likeCondition.putAll(user.toMap());/*www.  j av a 2 s. c o m*/
    likeCondition.put("filter", user);
    List<Map<String, Object>> mapList = dao.getPagedRecordList(likeCondition);
    for (int i = 0; i < mapList.size(); i++) {
        JOYUser userObj = new JOYUser();
        user.fromMap(mapList.get(i));
        System.out.println(user);
    }

    /*
            
            
    JOYPayHistoryService service = (JOYPayHistoryService)context.getBean("JOYPayHistoryService");
    JOYPayHistory payHistoryNew = new JOYPayHistory();
    payHistoryNew.balance = 0.2;
    payHistoryNew.type = 2;
    service.deleteByProperties(payHistoryNew);
            
            
    /*
    JOYUserService service = (JOYUserService)context.getBean("JOYUserService");
    JOYUser user = new JOYUser();
    user.mobileNo = "18500217642";
    List<Map<String,Object>> mapList = service.getExtendInfoPagedList(" select u.*, m.driverLicenseNumber  from JOY_Users u left join JOY_DriverLicense m on u.mobileNo = m.mobileNo ",user);
            
            
    //   JOYUser user2 = new JOYUser();
    Map<String,Object> t = mapList.get(0);
    Iterator i =t.entrySet().iterator();
    JSONObject tt = new JSONObject();
    while(i.hasNext()) {
            
       Map.Entry<String,Object> haha = (Map.Entry<String,Object>)i.next();
        if(String.valueOf(haha.getValue()).equals("null")) {
    logger.trace(haha.getKey()+" is null");
       }
    }
            
    /*
    user2.username = "?";
    user.mobileNo="18500217642";
    service.updateRecord(user2,user);
    user = service.getNeededRecord(user);
      logger.trace(user);
            
    /*
    JOYOrderService service = (JOYOrderService) context.getBean("JOYOrderService");
    JOYOrder order = new JOYOrder();
    order = service.getNeededRecord(order);
    JOYOrder order2 = new JOYOrder();
    order2.startTime = order.startTime;
    order = new JOYOrder();
    order.startTime = new Date(System.currentTimeMillis());
    service.updateRecord(order,order2);
       /*
    JOYNReserveOrderService  service  = (JOYNReserveOrderService)context.getBean("JOYNReserveOrderService");
    JOYReserveOrder order = new JOYReserveOrder();
    //service.insertRecord(order);
    JOYReserveOrder order2 = new JOYReserveOrder();
    order2.mobileNo = "18500217642";
    order2.startTime = new Date(System.currentTimeMillis());
      service.insertRecord(order2);
    order2.startTime = null;
    order = service.getNeededRecord(order2);
     order.startTime = new Date(System.currentTimeMillis());
    service.updateRecord(order,order2);
      order2.startTime = order.startTime;
    order2.mobileNo = null;
    order = service.getNeededRecord(order2);
    logger.trace(order);
    /*
    order.delFlag = 1;
    order.startTime = new Date(System.currentTimeMillis()+30);
    service.updateRecord(order,order2);
            
    order2.mobileNo = null;
    order2.startTime = order.startTime;
    order = service.getNeededRecord(order2);
    logger.trace(order);
    //service.deleteByProperties(order);
            
            
    /*
    JOYIdAuthInfoService service  = (JOYIdAuthInfoService)context.getBean("JOYIdAuthInfoService");
    JOYIdAuthInfo dl = new JOYIdAuthInfo();
    dl.idAuthInfo = "nihao".getBytes();
    dl.idAuthInfo_back = "Hello world".getBytes();
    JOYIdAuthInfo dl2 = new JOYIdAuthInfo();
    dl2.mobileNo = "15577586649";
    service.updateRecord(dl,dl2);
            
            
    service.getNeededList(dl2,null,null);
            
            
            
    List<JOYIdAuthInfo> dList = service.getNeededList(dl,null,null);
    logger.trace(dList.get(0));
            
    for(int i=0;i<dList.get(0).idAuthInfo.length;i++)
    System.out.format("%c",dList.get(0).idAuthInfo[i]);
    /*
    JOYUser user = new JOYUser();
    JOYUser user1 = new JOYUser();
    user.mobileNo = ("18500217642");
    List<JOYUser> userList =  service.getNeededList(user,0,10);
      logger.trace("sdfdsdsf :"+userList.size());
    JOYUser u = userList.get(0);
    logger.trace(u);
     */
}

From source file:com.saggezza.jtracker.track.TrackerC.java

public static void main(String[] args) throws IOException, JSONException, URISyntaxException {
    ///// Setup//from ww  w.java2s. com

    ///// CONFIGURATIONS
    TrackerC.debug = true;
    TrackerC.track = false;
    TrackerC.singleVar = true;

    ///// EmitterC
    Emitter emitter = new Emitter("localhost:80", "/javaplow");

    ///// REGULAR TRACKER
    Tracker t1 = new TrackerC(emitter, "Tracker Test", "JavaPlow", "com.com.saggezza", true, true);
    //        t1.setUserID("User1");
    t1.setLanguage("eng");
    t1.setPlatform("pc");
    t1.setScreenResolution(1260, 1080);
    String context = "{'Zone':'USA', 'Phone':'Droid', 'Time':'2pm'}";

    ///// E COMMERCE TEST
    Map<String, String> items = new HashMap<String, String>();
    items.put("sku", "SKUVAL");
    items.put("quantity", "2");
    items.put("price", "19.99");
    List<Map<String, String>> lst = new LinkedList<Map<String, String>>();
    lst.add(items);

    ///// GENERICS
    GenericTracker t2 = new TrackerC(emitter, "GenericTracker Test", "JavaPlow", "com.com.saggezza", true,
            true);
    t2.setLanguage("English");
    t2.setPlatform("pc");
    t2.setScreenResolution(1200, 1080);

    ///// GENERIC MAP
    Map<String, Object> dict = new LinkedHashMap<String, Object>();

    dict.put("Username", System.getProperty("user.name"));
    dict.put("OperatingSystem", System.getProperty("os.name"));
    dict.put("OS_Version", System.getProperty("os.version"));
    dict.put("JRE_Version", System.getProperty("java.version"));

    /////TRACK TEST
    for (int i = 0; i < 15; i++) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
        }
        System.out.println("Loop " + i);
        dict.put("Iteration", i);

        //            System.out.println(dict.toString() + "\n" + t2.getPayload().toString());
        //            t2.setupTrack("Kevin");
        //            t2.trackGenericEvent("Lube Insights", "Data Loop", dict, context);
        t1.setupTrack("Kevin", new JSONObject());
        //            t1.trackEcommerceTransactionItem("IT1023", "SKUVAL", 29.99, 2, "boots", "Shoes","USD",null,null);
        t1.trackEcommerceTransaction("OID", 19.99, "Kohls", 2.50, 1.99, "Chagrin", "OH", "USA", "USD", lst,
                context);
    }
}

From source file:com.avego.oauth.migration.OauthDataMigrator.java

/**
 * This migrates spring security oauth 2 token data in m6 form to 1.0.5 release form
 * @param args//from   ww  w . ja  v a 2  s .c om
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    if (args.length < 3) {
        System.err.println("Usage <db_jdbc_url> <db_user> <db_pw>");
        System.err.println("Or <db_jdbc_url> <db_user> <db_pw>"
                + " <remove_refresh_tokens> <serialize_new_token_values> <oauth_access_token_table> <oauth_refresh_token_table>");
        System.exit(1);
    }

    Boolean removeRefreshTokens = Boolean.FALSE;
    if (args.length > 3) {
        removeRefreshTokens = Boolean.parseBoolean(args[3]);
    }
    Boolean serializeNewTokenValues = Boolean.FALSE;
    if (args.length > 4) {
        serializeNewTokenValues = Boolean.parseBoolean(args[4]);
    }

    Map<String, Object> params = new HashMap<String, Object>(3);
    params.put(JdbcOauthMigrationDao.JDBC_URL_KEY, args[0]);
    params.put(JdbcOauthMigrationDao.USER_KEY, args[1]);
    params.put(JdbcOauthMigrationDao.PASS_KEY, args[2]);
    params.put(REMOVE_REFRESH_TOKENS_PARAM, removeRefreshTokens);
    params.put(SERIALIZE_NEW_TOKEN_VALUES_PARAM, serializeNewTokenValues);

    if (args.length > 5) {
        params.put(JdbcOauthMigrationDao.ACCESS_TOKEN_TABLE, args[5]);
    }
    if (args.length > 6) {
        params.put(JdbcOauthMigrationDao.REFRESH_TOKEN_TABLE, args[6]);
    }
    OauthDataMigrator migrator = new OauthDataMigrator(params);
    migrator.migrateData();
}