Example usage for java.util List get

List of usage examples for java.util List get

Introduction

In this page you can find the example usage for java.util List get.

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:mod.org.dcm4che2.tool.DcmQR.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    CommandLine cl = parse(args);//from   ww  w .j a  v  a 2 s  .  co m
    DcmQR dcmqr = new DcmQR(cl.hasOption("device") ? cl.getOptionValue("device") : "DCMQR");
    final List<String> argList = cl.getArgList();
    String remoteAE = argList.get(0);
    String[] calledAETAddress = split(remoteAE, '@');
    dcmqr.setCalledAET(calledAETAddress[0], cl.hasOption("reuseassoc"));
    if (calledAETAddress[1] == null) {
        dcmqr.setRemoteHost("127.0.0.1");
        dcmqr.setRemotePort(104);
    } else {
        String[] hostPort = split(calledAETAddress[1], ':');
        dcmqr.setRemoteHost(hostPort[0]);
        dcmqr.setRemotePort(toPort(hostPort[1]));
    }
    if (cl.hasOption("L")) {
        String localAE = cl.getOptionValue("L");
        String[] localPort = split(localAE, ':');
        if (localPort[1] != null) {
            dcmqr.setLocalPort(toPort(localPort[1]));
        }
        String[] callingAETHost = split(localPort[0], '@');
        dcmqr.setCalling(callingAETHost[0]);
        if (callingAETHost[1] != null) {
            dcmqr.setLocalHost(callingAETHost[1]);
        }
    }
    if (cl.hasOption("username")) {
        String username = cl.getOptionValue("username");
        UserIdentity userId;
        if (cl.hasOption("passcode")) {
            String passcode = cl.getOptionValue("passcode");
            userId = new UserIdentity.UsernamePasscode(username, passcode.toCharArray());
        } else {
            userId = new UserIdentity.Username(username);
        }
        userId.setPositiveResponseRequested(cl.hasOption("uidnegrsp"));
        dcmqr.setUserIdentity(userId);
    }
    if (cl.hasOption("connectTO"))
        dcmqr.setConnectTimeout(parseInt(cl.getOptionValue("connectTO"),
                "illegal argument of option -connectTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("reaper"))
        dcmqr.setAssociationReaperPeriod(parseInt(cl.getOptionValue("reaper"),
                "illegal argument of option -reaper", 1, Integer.MAX_VALUE));
    if (cl.hasOption("cfindrspTO"))
        dcmqr.setDimseRspTimeout(parseInt(cl.getOptionValue("cfindrspTO"),
                "illegal argument of option -cfindrspTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("cmoverspTO"))
        dcmqr.setRetrieveRspTimeout(parseInt(cl.getOptionValue("cmoverspTO"),
                "illegal argument of option -cmoverspTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("cgetrspTO"))
        dcmqr.setRetrieveRspTimeout(parseInt(cl.getOptionValue("cgetrspTO"),
                "illegal argument of option -cgetrspTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("acceptTO"))
        dcmqr.setAcceptTimeout(parseInt(cl.getOptionValue("acceptTO"), "illegal argument of option -acceptTO",
                1, Integer.MAX_VALUE));
    if (cl.hasOption("releaseTO"))
        dcmqr.setReleaseTimeout(parseInt(cl.getOptionValue("releaseTO"),
                "illegal argument of option -releaseTO", 1, Integer.MAX_VALUE));
    if (cl.hasOption("soclosedelay"))
        dcmqr.setSocketCloseDelay(parseInt(cl.getOptionValue("soclosedelay"),
                "illegal argument of option -soclosedelay", 1, 10000));
    if (cl.hasOption("rcvpdulen"))
        dcmqr.setMaxPDULengthReceive(
                parseInt(cl.getOptionValue("rcvpdulen"), "illegal argument of option -rcvpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sndpdulen"))
        dcmqr.setMaxPDULengthSend(
                parseInt(cl.getOptionValue("sndpdulen"), "illegal argument of option -sndpdulen", 1, 10000)
                        * KB);
    if (cl.hasOption("sosndbuf"))
        dcmqr.setSendBufferSize(
                parseInt(cl.getOptionValue("sosndbuf"), "illegal argument of option -sosndbuf", 1, 10000) * KB);
    if (cl.hasOption("sorcvbuf"))
        dcmqr.setReceiveBufferSize(
                parseInt(cl.getOptionValue("sorcvbuf"), "illegal argument of option -sorcvbuf", 1, 10000) * KB);
    if (cl.hasOption("filebuf"))
        dcmqr.setFileBufferSize(
                parseInt(cl.getOptionValue("filebuf"), "illegal argument of option -filebuf", 1, 10000) * KB);
    dcmqr.setPackPDV(!cl.hasOption("pdv1"));
    dcmqr.setTcpNoDelay(!cl.hasOption("tcpdelay"));
    dcmqr.setMaxOpsInvoked(cl.hasOption("async")
            ? parseInt(cl.getOptionValue("async"), "illegal argument of option -async", 0, 0xffff)
            : 1);
    dcmqr.setMaxOpsPerformed(cl.hasOption("cstoreasync")
            ? parseInt(cl.getOptionValue("cstoreasync"), "illegal argument of option -cstoreasync", 0, 0xffff)
            : 0);
    if (cl.hasOption("C"))
        dcmqr.setCancelAfter(
                parseInt(cl.getOptionValue("C"), "illegal argument of option -C", 1, Integer.MAX_VALUE));
    if (cl.hasOption("lowprior"))
        dcmqr.setPriority(CommandUtils.LOW);
    if (cl.hasOption("highprior"))
        dcmqr.setPriority(CommandUtils.HIGH);
    if (cl.hasOption("cstore")) {
        String[] storeTCs = cl.getOptionValues("cstore");
        for (String storeTC : storeTCs) {
            String cuid;
            String[] tsuids;
            int colon = storeTC.indexOf(':');
            if (colon == -1) {
                cuid = storeTC;
                tsuids = DEF_TS;
            } else {
                cuid = storeTC.substring(0, colon);
                String ts = storeTC.substring(colon + 1);
                try {
                    tsuids = TS.valueOf(ts).uids;
                } catch (IllegalArgumentException e) {
                    tsuids = ts.split(",");
                }
            }
            try {
                cuid = CUID.valueOf(cuid).uid;
            } catch (IllegalArgumentException e) {
                // assume cuid already contains UID
            }
            dcmqr.addStoreTransferCapability(cuid, tsuids);
        }
        if (cl.hasOption("cstoredest"))
            dcmqr.setStoreDestination(cl.getOptionValue("cstoredest"));
    }
    dcmqr.setCFind(!cl.hasOption("nocfind"));
    dcmqr.setCGet(cl.hasOption("cget"));
    if (cl.hasOption("cmove"))
        dcmqr.setMoveDest(cl.getOptionValue("cmove"));
    if (cl.hasOption("evalRetrieveAET"))
        dcmqr.setEvalRetrieveAET(true);
    dcmqr.setQueryLevel(cl.hasOption("P") ? QueryRetrieveLevel.PATIENT
            : cl.hasOption("S") ? QueryRetrieveLevel.SERIES
                    : cl.hasOption("I") ? QueryRetrieveLevel.IMAGE : QueryRetrieveLevel.STUDY);
    if (cl.hasOption("noextneg"))
        dcmqr.setNoExtNegotiation(true);
    if (cl.hasOption("rel"))
        dcmqr.setRelationQR(true);
    if (cl.hasOption("datetime"))
        dcmqr.setDateTimeMatching(true);
    if (cl.hasOption("fuzzy"))
        dcmqr.setFuzzySemanticPersonNameMatching(true);
    if (!cl.hasOption("P")) {
        if (cl.hasOption("retall"))
            dcmqr.addPrivate(UID.PrivateStudyRootQueryRetrieveInformationModelFIND);
        if (cl.hasOption("blocked"))
            dcmqr.addPrivate(UID.PrivateBlockedStudyRootQueryRetrieveInformationModelFIND);
        if (cl.hasOption("vmf"))
            dcmqr.addPrivate(UID.PrivateVirtualMultiframeStudyRootQueryRetrieveInformationModelFIND);
    }
    if (cl.hasOption("cfind")) {
        String[] cuids = cl.getOptionValues("cfind");
        for (int i = 0; i < cuids.length; i++)
            dcmqr.addPrivate(cuids[i]);
    }
    if (!cl.hasOption("nodefret"))
        dcmqr.addDefReturnKeys();
    if (cl.hasOption("r")) {
        String[] returnKeys = cl.getOptionValues("r");
        for (int i = 0; i < returnKeys.length; i++)
            dcmqr.addReturnKey(Tag.toTagPath(returnKeys[i]));
    }
    if (cl.hasOption("q")) {
        String[] matchingKeys = cl.getOptionValues("q");
        for (int i = 1; i < matchingKeys.length; i++, i++)
            dcmqr.addMatchingKey(Tag.toTagPath(matchingKeys[i - 1]), matchingKeys[i]);
    }

    dcmqr.configureTransferCapability(cl.hasOption("ivrle"));

    int repeat = cl.hasOption("repeat")
            ? parseInt(cl.getOptionValue("repeat"), "illegal argument of option -repeat", 1, Integer.MAX_VALUE)
            : 0;
    int interval = cl.hasOption("repeatdelay")
            ? parseInt(cl.getOptionValue("repeatdelay"), "illegal argument of option -repeatdelay", 1,
                    Integer.MAX_VALUE)
            : 0;
    boolean closeAssoc = cl.hasOption("closeassoc");

    if (cl.hasOption("tls")) {
        String cipher = cl.getOptionValue("tls");
        if ("NULL".equalsIgnoreCase(cipher)) {
            dcmqr.setTlsWithoutEncyrption();
        } else if ("3DES".equalsIgnoreCase(cipher)) {
            dcmqr.setTls3DES_EDE_CBC();
        } else if ("AES".equalsIgnoreCase(cipher)) {
            dcmqr.setTlsAES_128_CBC();
        } else {
            exit("Invalid parameter for option -tls: " + cipher);
        }
        if (cl.hasOption("tls1")) {
            dcmqr.setTlsProtocol(TLS1);
        } else if (cl.hasOption("ssl3")) {
            dcmqr.setTlsProtocol(SSL3);
        } else if (cl.hasOption("no_tls1")) {
            dcmqr.setTlsProtocol(NO_TLS1);
        } else if (cl.hasOption("no_ssl3")) {
            dcmqr.setTlsProtocol(NO_SSL3);
        } else if (cl.hasOption("no_ssl2")) {
            dcmqr.setTlsProtocol(NO_SSL2);
        }
        dcmqr.setTlsNeedClientAuth(!cl.hasOption("noclientauth"));
        if (cl.hasOption("keystore")) {
            dcmqr.setKeyStoreURL(cl.getOptionValue("keystore"));
        }
        if (cl.hasOption("keystorepw")) {
            dcmqr.setKeyStorePassword(cl.getOptionValue("keystorepw"));
        }
        if (cl.hasOption("keypw")) {
            dcmqr.setKeyPassword(cl.getOptionValue("keypw"));
        }
        if (cl.hasOption("truststore")) {
            dcmqr.setTrustStoreURL(cl.getOptionValue("truststore"));
        }
        if (cl.hasOption("truststorepw")) {
            dcmqr.setTrustStorePassword(cl.getOptionValue("truststorepw"));
        }
        long t1 = System.currentTimeMillis();
        try {
            dcmqr.initTLS();
        } catch (Exception e) {
            System.err.println("ERROR: Failed to initialize TLS context:" + e.getMessage());
            System.exit(2);
        }
        long t2 = System.currentTimeMillis();
        LOG.info("Initialize TLS context in {} s", Float.valueOf((t2 - t1) / 1000f));
    }
    try {
        dcmqr.start();
    } catch (Exception e) {
        System.err.println(
                "ERROR: Failed to start server for receiving " + "requested objects:" + e.getMessage());
        System.exit(2);
    }
    try {
        long t1 = System.currentTimeMillis();
        try {
            dcmqr.open();
        } catch (Exception e) {
            LOG.error("Failed to establish association:", e);
            System.exit(2);
        }
        long t2 = System.currentTimeMillis();
        LOG.info("Connected to {} in {} s", remoteAE, Float.valueOf((t2 - t1) / 1000f));

        for (;;) {
            List<DicomObject> result;
            if (dcmqr.isCFind()) {
                result = dcmqr.query();
                long t3 = System.currentTimeMillis();
                LOG.info("Received {} matching entries in {} s", Integer.valueOf(result.size()),
                        Float.valueOf((t3 - t2) / 1000f));
                t2 = t3;
            } else {
                result = Collections.singletonList(dcmqr.getKeys());
            }
            if (dcmqr.isCMove() || dcmqr.isCGet()) {
                if (dcmqr.isCMove())
                    dcmqr.move(result);
                else
                    dcmqr.get(result);
                long t4 = System.currentTimeMillis();
                LOG.info("Retrieved {} objects (warning: {}, failed: {}) in {}s",
                        new Object[] { Integer.valueOf(dcmqr.getTotalRetrieved()),
                                Integer.valueOf(dcmqr.getWarning()), Integer.valueOf(dcmqr.getFailed()),
                                Float.valueOf((t4 - t2) / 1000f) });
            }
            if (repeat == 0 || closeAssoc) {
                try {
                    dcmqr.close();
                } catch (InterruptedException e) {
                    LOG.error(e.getMessage(), e);
                }
                LOG.info("Released connection to {}", remoteAE);
            }
            if (repeat-- == 0)
                break;
            Thread.sleep(interval);
            long t4 = System.currentTimeMillis();
            dcmqr.open();
            t2 = System.currentTimeMillis();
            LOG.info("Reconnect or reuse connection to {} in {} s", remoteAE, Float.valueOf((t2 - t4) / 1000f));
        }
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    } catch (InterruptedException e) {
        LOG.error(e.getMessage(), e);
    } catch (ConfigurationException e) {
        LOG.error(e.getMessage(), e);
    } finally {
        dcmqr.stop();
    }
}

From source file:com.makkajai.ObjCToCpp.java

/**
 * Main Method/* w  w w.  j av a 2 s .  com*/
 *
 * @param args - First argument is the input directory to scan and second is the output directory to write files to.
 * @throws IOException
 */
public static void main(String[] args) throws IOException {

    if (args.length < 2) {
        System.out.println("Invalid Arguments!");
        System.out.println(
                "Usage: java com.makkajai.ObjCToCpp \"<directory to scan for .h and .m files>\" \"<directory to write .h and .cpp files>\"");
        return;
    }

    String inputDirectory = args[0];
    String outputDirectory = args[1];
    //     String inputDirectory = "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/scenes";
    //     String outputDirectory = "/Users/administrator/playground/projarea/monster-math-cross-platform/monster-math-2/Classes/Makkajai/scenes";

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

    if (args.length == 3) {
        BufferedReader bufferedInputStream = new BufferedReader(new FileReader(args[2]));
        String exceptFile = null;
        while ((exceptFile = bufferedInputStream.readLine()) != null) {
            if (exceptFile.equals(""))
                continue;
            exceptFiles.add(exceptFile);
        }
    }

    //Getting all the files from the input directory.
    final List<File> files = new ArrayList<File>(FileUtils.listFiles(new File(inputDirectory),
            new RegexFileFilter(FILE_NAME_WITH_H_OR_M), DirectoryFileFilter.DIRECTORY));

    //        String fileName =
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Utils/MakkajaiEnum"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Utils/MakkajaiUtil"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Home"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Activities/gnumchmenu/PlayStrategy"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Characters/Character"
    //                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/Activities/gnumchmenu/GnumchScene"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/ParentScene"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/BaseSkillView"
    ////                "/Users/administrator/playground/projarea/math-monsters-2/makkajai-number-muncher/makkajai-ios/Makkajai/Makkajai/YDLayerBase"
    //                ;
    //The instance of the translator.
    ObjCToCppTranslator visitor = new ObjCToCppTranslator();

    for (int i = 0; i < files.size();) {
        File currentFile = files.get(i);
        String filePathRelativeToInput = currentFile.getAbsolutePath().replace(inputDirectory, "");
        Date startTime = new Date();
        try {
            final TranslateFileInput translateFileInput = new TranslateFileInput(inputDirectory,
                    outputDirectory, filePathRelativeToInput, false);
            if (nextFileIsM(currentFile, files, i)) {
                try {
                    if (isIgnoredFile(filePathRelativeToInput, exceptFiles))
                        continue;
                    translateFileInput.dryRun = true;
                    visitor.translateFile(translateFileInput);
                    Date stopTime = new Date();
                    System.out.println("Dry run File: " + translateFileInput.filePathRelativeToInput
                            + " Time Taken: " + getDelta(startTime, stopTime));

                    Date startTime1 = new Date();
                    translateFileInput.filePathRelativeToInput = filePathRelativeToInput.replace(H, M);
                    translateFileInput.dryRun = false;
                    visitor.translateFile(translateFileInput);
                    stopTime = new Date();
                    System.out.println("Processed File: " + translateFileInput.filePathRelativeToInput
                            + " Time Taken: " + getDelta(startTime1, stopTime));

                    Date startTime2 = new Date();
                    translateFileInput.filePathRelativeToInput = filePathRelativeToInput;
                    translateFileInput.dryRun = false;
                    visitor.translateFile(translateFileInput);
                    stopTime = new Date();
                    System.out.println("Processed File: " + translateFileInput.filePathRelativeToInput
                            + " Time Taken: " + getDelta(startTime2, stopTime));
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("###########################Error Processing: " + filePathRelativeToInput
                            + ", Continuing with next set of tiles");
                } finally {
                    i += 2;
                }
                continue;
            }
            if (!isIgnoredFile(filePathRelativeToInput, exceptFiles))
                visitor.translateFile(translateFileInput);
            i++;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("###########################Error Processing: " + filePathRelativeToInput
                    + ", Continuing with next set of tiles");
        } finally {
            Date stopTime = new Date();
            //                System.out.println("Processed File(s): " + filePathRelativeToInput.replaceAll(H_OR_M, "") + " Time Taken: " + getDelta(startTime, stopTime));
        }
    }
}

From source file:gridrover.GridRover.java

/**
* This method does the work of getting our application started.
*
* @param args Command line arguments/*from   www.j  ava 2  s  .  c o m*/
*/
public static void main(String[] args) {
    System.out.println("GridRover Copyright (C) 2008-2009 Lucas Adam M. Paul");
    System.out.println("This program comes with ABSOLUTELY NO WARRANTY; for details see LICENSE.TXT.");
    System.out.println("This is free software, and you are welcome to redistribute it");
    System.out.println("under certain conditions; see LICENSE.TXT for details.\n");

    log.info("Loading preferences...");
    Preferences prefs = Preferences.userNodeForPackage(GridRover.class);
    int width = prefs.getInt(MAP_WIDTH, 10);
    int length = prefs.getInt(MAP_HEIGHT, 10);
    double maxElevation = prefs.getDouble(MAX_ELEVATION, 25.0);
    int precision = prefs.getInt(ELEVATION_PRECISION, 2);

    log.info("Loading data files...");

    XmlFileParser fileParser = new XmlFileParser(new ResourceLocater(null));
    List<Spectrum> spectra = fileParser.getSpectra("spectrum_types.xml");
    log.debug("Checking we got our spectra.");
    for (Spectrum spec : spectra) {
        log.debug("Type: " + spec.getName());
        List<String> list = spec.getColors();
        for (String color : list)
            log.debug("\tColor: " + color);
        list = spec.getShapes();
        for (String shape : list)
            log.debug("\tShape: " + shape);
    }
    //List<Thing> itemPrototypes = fileParser.getThings("physical_objects.xml");
    List<ThingBean> itemPrototypes = fileParser.getThings("physical_objects.xml", spectra);
    log.debug("Checking we got our Things.");
    for (ThingBean tb : itemPrototypes) {
        log.debug("Name: " + tb.getName());
        log.debug("Mass: " + tb.getMinMass() + " - " + tb.getMaxMass());
        log.debug("Density: " + tb.getMinDensity() + " - " + tb.getMaxDensity());
        List<AppearanceBean> appearance = tb.getAppearanceBeans();
        for (AppearanceBean ab : appearance) {
            log.debug("Under the " + ab.getStimulus() + " spectrum, " + tb.getName() + " reacts with:");
            List<ResponseBean> responses = ab.getResponseBeans();
            for (ResponseBean rb : responses) {
                log.debug(rb.getSpectrumAction().toString() + " " + rb.getColor() + " " + rb.getShape()
                        + " in spectrum " + rb.getSpectrum());
            }
        }
    }

    log.info("Initializing GridRover...");
    GameEngine engine = new GameEngine(width, length, maxElevation, precision);
    Rover rover = new Rover("Rover", 185.0, 5.52, 100.0, new CommandlineRoverControl()); // Mass 185.0 kg, 1.5 meters tall by 2.3 meters wide by 1.6 meters long
    engine.addRover(rover, width / 2, length / 2); // Add a single rover in the middle of the map
    engine.addAmbientLighting(spectra.get(0));
    engine.scatterItemsRandomly(itemPrototypes, 0.5, 5); // 50% chance of items in a given square, up to 5 items per square

    log.info("Running GridRover...");
    engine.eventLoop();
    System.out.println("All events completed.  GridRover now terminating.");
}

From source file:com.sds.acube.ndisc.xadmin.XNDiscAdminUtil.java

public static void main(String args[]) {

    if (args.length == 0) {
        XNDiscAdminUtil.printAdminUsage(null, null);
        // System.exit(0);
    }/* ww  w.j a va2 s.co m*/

    XNDiscAdminFile file = new XNDiscAdminFile(printlog, out, logger);
    XNDiscAdminMedia media = new XNDiscAdminMedia(printlog, out, logger);
    XNDiscAdminVolume volume = new XNDiscAdminVolume(printlog, out, logger);
    XNDiscAdminEnDecrypt endecrypt = new XNDiscAdminEnDecrypt(printlog, out, logger);

    Scanner in = new Scanner(System.in);
    String input = "";
    List<String> options = null;
    Scanner part = null;
    do {
        input = in.nextLine();
        part = new Scanner(input).useDelimiter(" ");
        options = new ArrayList<String>();
        while (part.hasNext()) {
            String val = part.next().trim();
            if (StringUtils.isEmpty(val)) {
                continue;
            }
            options.add(val);
        }
        if (options.size() < 2 || input.equalsIgnoreCase("q")) {
            if (input != null && input.trim().equalsIgnoreCase("q")) {
                System.out.println(LINE_SEPERATOR + "XNDiscAdminUtil quit!!!" + LINE_SEPERATOR);
            } else {
                System.out
                        .println(LINE_SEPERATOR + "XNDiscAdminUtil are invalid parameters!!!" + LINE_SEPERATOR);
            }
            System.exit(0);
        }

        String main_op = (StringUtils.isEmpty(options.get(0))) ? "" : options.get(0);
        String process_op = (StringUtils.isEmpty(options.get(1))) ? "" : options.get(1);
        if (main_op.equals("clear")) {
            if (process_op.equals("screen")) {
                clearConsoleOutput();
            }
        } else if (main_op.equals("file")) {
            if (process_op.equals("ls")) {
                String fileid = "";
                if (options.size() > 2) {
                    fileid = options.get(2);
                }
                if (StringUtils.isEmpty(fileid)) {
                    file.selectFileList();
                } else {
                    file.selectFileById(fileid);
                }
            } else if (process_op.equals("reg")) {
                String host = "";
                int port = -1;
                String filepath = "";
                int vol = -1;
                if (options.size() == 4) {
                    host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST);
                    port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT);
                    filepath = options.get(2);
                    if (isInteger(options.get(3))) {
                        vol = Integer.parseInt(options.get(3));
                    }
                } else if (options.size() > 5) {
                    host = options.get(2);
                    port = Integer.parseInt(options.get(3));
                    filepath = options.get(4);
                    if (isInteger(options.get(5))) {
                        vol = Integer.parseInt(options.get(5));
                    }
                }
                if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(filepath) && port > 0 && vol > 0) {
                    file.regFile(host, port, filepath, vol, "0");
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("get")) {
                String host = "";
                int port = -1;
                String fileid = "";
                String filepath = "";
                if (options.size() == 4) {
                    host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST);
                    port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT);
                    fileid = options.get(2);
                    filepath = options.get(3);
                } else if (options.size() > 5) {
                    host = options.get(2);
                    if (isInteger(options.get(3))) {
                        port = Integer.parseInt(options.get(3));
                    }
                    fileid = options.get(4);
                    filepath = options.get(5);
                }
                if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(fileid) && !StringUtils.isEmpty(filepath)
                        && port > 0) {
                    file.getFile(host, port, fileid, filepath);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("wh")) {
                String fileid = "";
                if (options.size() > 2) {
                    fileid = options.get(2);
                }
                if (!StringUtils.isEmpty(fileid)) {
                    file.getFilePathByFileId(fileid);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("rm")) {
                String host = "";
                int port = -1;
                String fileid = "";
                if (options.size() == 3) {
                    host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST);
                    port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT);
                    fileid = options.get(2);
                } else if (options.size() > 4) {
                    host = options.get(2);
                    if (isInteger(options.get(3))) {
                        port = Integer.parseInt(options.get(3));
                    }
                    fileid = options.get(4);
                }
                if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(fileid) && port > 0) {
                    file.removeFile(host, port, fileid);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            }
        } else if (main_op.equals("media")) {
            if (process_op.equals("mk")) {
                String host = "";
                int port = -1;
                String name = "";
                int type = 0;
                String path = "";
                String desc = " ";
                int maxsize = -1;
                int vol = -1;
                if (options.size() == 7) {
                    host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST);
                    port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT);
                    name = options.get(2);
                    if (isInteger(options.get(3))) {
                        type = Integer.parseInt(options.get(3));
                    }
                    path = options.get(4);
                    if (isInteger(options.get(5))) {
                        maxsize = Integer.parseInt(options.get(5));
                    }
                    if (isInteger(options.get(6))) {
                        vol = Integer.parseInt(options.get(6));
                    }
                } else if (options.size() == 8) {
                    host = XNDiscAdminConfig.getString(XNDiscAdminConfig.HOST);
                    port = XNDiscAdminConfig.getInt(XNDiscAdminConfig.PORT);
                    name = options.get(2);
                    if (isInteger(options.get(3))) {
                        type = Integer.parseInt(options.get(3));
                    }
                    path = options.get(4);
                    desc = options.get(5) + " ";
                    if (isInteger(options.get(6))) {
                        maxsize = Integer.parseInt(options.get(6));
                    }
                    if (isInteger(options.get(7))) {
                        vol = Integer.parseInt(options.get(7));
                    }
                } else if (options.size() == 9) {
                    host = options.get(2);
                    if (isInteger(options.get(3))) {
                        port = Integer.parseInt(options.get(3));
                    }
                    name = options.get(4);
                    if (isInteger(options.get(5))) {
                        type = Integer.parseInt(options.get(5));
                    }
                    path = options.get(6);
                    if (isInteger(options.get(7))) {
                        maxsize = Integer.parseInt(options.get(7));
                    }
                    if (isInteger(options.get(8))) {
                        vol = Integer.parseInt(options.get(8));
                    }
                } else if (options.size() > 9) {
                    host = options.get(2);
                    if (isInteger(options.get(3))) {
                        port = Integer.parseInt(options.get(3));
                    }
                    name = options.get(4);
                    if (isInteger(options.get(5))) {
                        type = Integer.parseInt(options.get(5));
                    }
                    path = options.get(6);
                    desc = options.get(7) + " ";
                    if (isInteger(options.get(8))) {
                        maxsize = Integer.parseInt(options.get(8));
                    }
                    if (isInteger(options.get(9))) {
                        vol = Integer.parseInt(options.get(9));
                    }
                }
                if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(name) && !StringUtils.isEmpty(path)
                        && port > 0 && vol > 0 && maxsize > 0) {
                    media.makeMedia(host, port, name, type, path, desc, maxsize, vol);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("ls")) {
                String mediaid = "-1";
                if (options.size() > 2) {
                    mediaid = options.get(2);
                }
                if (StringUtils.isEmpty(mediaid) || mediaid.equals("-1")) {
                    media.selectMediaList();
                } else {
                    int id = -1;
                    if (isInteger(mediaid)) {
                        id = Integer.parseInt(mediaid);
                    }
                    if (id > 0) {
                        media.selectMediaById(id);
                    } else {
                        XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                    }
                }
            } else if (process_op.equals("rm")) {
                String mediaid = "-1";
                if (options.size() > 2) {
                    mediaid = options.get(2);
                }
                if (!StringUtils.isEmpty(mediaid)) {
                    int id = -1;
                    if (isInteger(mediaid)) {
                        id = Integer.parseInt(options.get(2));
                    }
                    if (id > 0) {
                        media.removeMedia(id);
                    } else {
                        XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                    }
                }
            } else if (process_op.equals("ch")) {
                int mediaid = -1;
                String name = "";
                int type = 0;
                String path = "";
                String desc = "";
                int maxsize = -1;
                int vol = -1;
                if (options.size() == 8) {
                    if (isInteger(options.get(2))) {
                        mediaid = Integer.parseInt(options.get(2));
                    }
                    name = options.get(3);
                    if (isInteger(options.get(4))) {
                        type = Integer.parseInt(options.get(4));
                    }
                    path = options.get(5);
                    if (isInteger(options.get(6))) {
                        maxsize = Integer.parseInt(options.get(6));
                    }
                    if (isInteger(options.get(7))) {
                        vol = Integer.parseInt(options.get(7));
                    }
                } else if (options.size() > 8) {
                    if (isInteger(options.get(2))) {
                        mediaid = Integer.parseInt(options.get(2));
                    }
                    name = options.get(3);
                    if (isInteger(options.get(4))) {
                        type = Integer.parseInt(options.get(4));
                    }
                    path = options.get(5);
                    desc = options.get(6);
                    if (isInteger(options.get(7))) {
                        maxsize = Integer.parseInt(options.get(7));
                    }
                    if (isInteger(options.get(8))) {
                        vol = Integer.parseInt(options.get(8));
                    }
                }
                if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(path) && mediaid > 0 && maxsize > 0
                        && vol > 0) {
                    media.changeMedia(mediaid, name, type, path, desc, maxsize, vol);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            }
        } else if (main_op.equals("vol")) {
            if (process_op.equals("mk")) {
                String name = "";
                String access = "";
                String desc = " ";
                if (options.size() == 4) {
                    name = options.get(2);
                    access = options.get(3);
                } else if (options.size() > 4) {
                    name = options.get(2);
                    access = options.get(3);
                    desc = options.get(4) + " ";
                }
                if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(access)) {
                    volume.makeVolume(name, access, desc);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("ls")) {
                String volid = "-1";
                if (options.size() > 2) {
                    volid = options.get(2);
                }
                if (StringUtils.isEmpty(volid) || volid.equals("-1")) {
                    volume.selectVolumeList();
                } else {
                    int volumeid = -1;
                    if (isInteger(volid)) {
                        volumeid = Integer.parseInt(volid);
                    }
                    if (volumeid > 0) {
                        volume.selectVolumeById(volumeid);
                    } else {
                        XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                    }
                }
            } else if (process_op.equals("rm")) {
                String volid = "-1";
                if (options.size() > 2) {
                    volid = options.get(2);
                }
                if (!StringUtils.isEmpty(volid)) {
                    int volumeid = -1;
                    if (isInteger(volid)) {
                        volumeid = Integer.parseInt(volid);
                    }
                    if (volumeid > 0) {
                        volume.removeVolume(volumeid);
                    }
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("ch")) {
                int volumeid = -1;
                String name = "";
                String access = "";
                String desc = "";
                if (options.size() == 5) {
                    if (isInteger(options.get(2))) {
                        volumeid = Integer.parseInt(options.get(2));
                    }
                    name = options.get(3);
                    access = options.get(4);
                } else if (options.size() > 5) {
                    if (isInteger(options.get(2))) {
                        volumeid = Integer.parseInt(options.get(2));
                    }
                    name = options.get(3);
                    access = options.get(4);
                    desc = options.get(5) + " ";
                }
                if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(access) && volumeid > 0) {
                    volume.changeVolume(volumeid, name, access, desc);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            }
        } else if (main_op.equals("id")) {
            String id = "";
            if (options.size() > 2) {
                id = options.get(2);
            }
            if (process_op.equals("enc")) {
                if (!StringUtils.isEmpty(id)) {
                    endecrypt.encrypt(id);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            } else if (process_op.equals("dec")) {
                if (!StringUtils.isEmpty(id)) {
                    endecrypt.decrypt(id);
                } else {
                    XNDiscAdminUtil.printAdminUsage(main_op, process_op);
                }
            }
        }
        part.close();
    } while (!input.equalsIgnoreCase("q"));
    in.close();
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5GoldLabelEstimator.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    String inputDir = args[0];/*  w w  w . j a v a  2  s. co m*/
    File outputDir = new File(args[1]);

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    // we will process only a subset first
    List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>();

    Collection<File> files = IOHelper.listXmlFiles(new File(inputDir));

    for (File file : files) {
        allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file));
    }

    // collect turkers and csv
    List<String> turkerIDs = extractAndSortTurkerIDs(allArgumentPairs);
    String preparedCSV = prepareCSV(allArgumentPairs, turkerIDs);

    // save CSV and run MACE
    Path tmpDir = Files.createTempDirectory("mace");
    File maceInputFile = new File(tmpDir.toFile(), "input.csv");
    FileUtils.writeStringToFile(maceInputFile, preparedCSV, "utf-8");

    File outputPredictions = new File(tmpDir.toFile(), "predictions.txt");
    File outputCompetence = new File(tmpDir.toFile(), "competence.txt");

    // run MACE
    MACE.main(new String[] { "--iterations", "500", "--threshold", String.valueOf(MACE_THRESHOLD), "--restarts",
            "50", "--outputPredictions", outputPredictions.getAbsolutePath(), "--outputCompetence",
            outputCompetence.getAbsolutePath(), maceInputFile.getAbsolutePath() });

    // read back the predictions and competence
    List<String> predictions = FileUtils.readLines(outputPredictions, "utf-8");

    // check the output
    if (predictions.size() != allArgumentPairs.size()) {
        throw new IllegalStateException("Wrong size of the predicted file; expected " + allArgumentPairs.size()
                + " lines but was " + predictions.size());
    }

    String competenceRaw = FileUtils.readFileToString(outputCompetence, "utf-8");
    String[] competence = competenceRaw.split("\t");
    if (competence.length != turkerIDs.size()) {
        throw new IllegalStateException(
                "Expected " + turkerIDs.size() + " competence number, got " + competence.length);
    }

    // rank turkers by competence
    Map<String, Double> turkerIDCompetenceMap = new TreeMap<>();
    for (int i = 0; i < turkerIDs.size(); i++) {
        turkerIDCompetenceMap.put(turkerIDs.get(i), Double.valueOf(competence[i]));
    }

    // sort by value descending
    Map<String, Double> sortedCompetences = IOHelper.sortByValue(turkerIDCompetenceMap, false);
    System.out.println("Sorted turker competences: " + sortedCompetences);

    // assign the gold label and competence

    for (int i = 0; i < allArgumentPairs.size(); i++) {
        AnnotatedArgumentPair annotatedArgumentPair = allArgumentPairs.get(i);
        String goldLabel = predictions.get(i).trim();

        // might be empty
        if (!goldLabel.isEmpty()) {
            // so far the gold label has format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal
            // strip now only the gold label
            annotatedArgumentPair.setGoldLabel(goldLabel);
        }

        // update turker competence
        for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) {
            String turkID = assignment.getTurkID();

            int turkRank = getTurkerRank(turkID, sortedCompetences);
            assignment.setTurkRank(turkRank);

            double turkCompetence = turkerIDCompetenceMap.get(turkID);
            assignment.setTurkCompetence(turkCompetence);
        }
    }

    // now sort the data back according to their original file name
    Map<String, List<AnnotatedArgumentPair>> fileNameAnnotatedPairsMap = new HashMap<>();
    for (AnnotatedArgumentPair argumentPair : allArgumentPairs) {
        String fileName = IOHelper.createFileName(argumentPair.getDebateMetaData(),
                argumentPair.getArg1().getStance());

        if (!fileNameAnnotatedPairsMap.containsKey(fileName)) {
            fileNameAnnotatedPairsMap.put(fileName, new ArrayList<AnnotatedArgumentPair>());
        }

        fileNameAnnotatedPairsMap.get(fileName).add(argumentPair);
    }

    // and save them to the output file
    for (Map.Entry<String, List<AnnotatedArgumentPair>> entry : fileNameAnnotatedPairsMap.entrySet()) {
        String fileName = entry.getKey();
        List<AnnotatedArgumentPair> argumentPairs = entry.getValue();

        File outputFile = new File(outputDir, fileName);

        // and save all sampled pairs into a XML file
        XStreamTools.toXML(argumentPairs, outputFile);

        System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile);
    }

}

From source file:com.peewah.distribuidosfinal.EntryPoint.java

public static void main(String[] args) {
    //1. Conexin con la base de datos
    String dbUrl = "jdbc:postgresql://localhost:5432/distribuidosfinal";
    try {/* w w w . j ava  2  s  . c o  m*/
        connectionSource = new JdbcConnectionSource(dbUrl);
        ((JdbcConnectionSource) connectionSource).setUsername("csacanam");
        ((JdbcConnectionSource) connectionSource).setPassword("12345678");
    } catch (SQLException ex) {
        System.out.println("Error en la conexin a la base de datos");
    }

    // 2. Data Acces Object (DAO) pattern
    usuarioDao = null;
    sistemaOperativoDao = null;
    maquinaVirtualDao = null;
    maquinaAppDao = null;
    appDao = null;
    cookbookDao = null;
    cookbookAppDao = null;
    nodoDao = null;

    if (connectionSource != null) {
        try {
            usuarioDao = DaoManager.createDao(connectionSource, Usuario.class);
            sistemaOperativoDao = DaoManager.createDao(connectionSource, SistemaOperativo.class);
            maquinaVirtualDao = DaoManager.createDao(connectionSource, MaquinaVirtual.class);
            maquinaAppDao = DaoManager.createDao(connectionSource, MaquinaApp.class);
            appDao = DaoManager.createDao(connectionSource, App.class);
            cookbookDao = DaoManager.createDao(connectionSource, Cookbook.class);
            cookbookAppDao = DaoManager.createDao(connectionSource, CookbookApp.class);
            nodoDao = DaoManager.createDao(connectionSource, Nodo.class);

        } catch (SQLException ex) {
            System.out.println("Error en la creacin del DAO");
            System.err.println(ex.getMessage());
        }
    }

    // 3. Crear tabla Usuario si no existe
    try {
        TableUtils.createTableIfNotExists(connectionSource, Usuario.class);
        TableUtils.createTableIfNotExists(connectionSource, SistemaOperativo.class);
        TableUtils.createTableIfNotExists(connectionSource, MaquinaVirtual.class);
        TableUtils.createTableIfNotExists(connectionSource, App.class);
        TableUtils.createTableIfNotExists(connectionSource, MaquinaApp.class);
        TableUtils.createTableIfNotExists(connectionSource, Cookbook.class);
        TableUtils.createTableIfNotExists(connectionSource, CookbookApp.class);
        TableUtils.createTableIfNotExists(connectionSource, Nodo.class);

    } catch (SQLException ex) {
        System.out.println("Error creando las tablas");
    }

    //4. Asignacin de puerto
    ProcessBuilder process = new ProcessBuilder();
    Integer puerto;
    if (process.environment().get("PORT") != null) {
        puerto = Integer.parseInt(process.environment().get("PORT"));
    } else {
        puerto = 8080;
    }
    spark.SparkBase.port(puerto);

    //5. Habilitar Cross-origin resource sharing (CORS)
    options("/*", (Request rqst, Response rspns) -> {
        String accessControlRequestHeaders = rqst.headers("Access-Control-Request-Headers");
        if (accessControlRequestHeaders != null) {
            rspns.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
        }

        String accessControlRequestMethod = rqst.headers("Access-Control-Request-Method");
        if (accessControlRequestMethod != null) {
            rspns.header("Access-Control-Allow-Methods", accessControlRequestMethod);
        }
        return "OK";
    });

    before((Request rqst, Response rspns) -> {
        rspns.header("Access-Control-Allow-Origin", "*");
    });

    after((Request rqst, Response rspns) -> {
        rspns.type("application/json");
    });

    //6. Web services
    //Crear usuario
    post("/new-user", (Request rqst, Response rspns) -> {
        //Obtener datos como parmetros
        String nombre = rqst.queryParams("name");
        String username = rqst.queryParams("username");
        String password = rqst.queryParams("password");

        //Validar si no hay datos vacos
        if (nombre != null && !nombre.equals("") && username != null && !username.equals("") && password != null
                && !password.equals("")) {
            //Crear objeto usuario
            Usuario usuario = new Usuario();
            usuario.setNombre(nombre);
            usuario.setPassword(password);
            usuario.setUsername(username);

            //Crear objeto en base de datos
            try {
                usuarioDao.create(usuario);

                //Crear carpeta
                File file = new File("/tmp/" + username);
                if (!file.exists()) {
                    boolean success = file.mkdir();
                    if (!success) {
                        System.out.println("La carpeta no pudo ser creada");
                    }
                }

            } catch (SQLException ex) {
                System.out.println("Error creando el usuario");
                return false;
            }

        } else {
            System.out.println("No debes dejar campos vacos");
            return false;
        }

        System.out.println("Usuario creado");
        return true;
    });

    //Autenticar usuario
    post("/auth-user", (Request rqst, Response rspns) -> {
        //Obtener datos como parmetros
        String username = rqst.queryParams("username");
        String password = rqst.queryParams("password");

        //Validar si no hay datos vacos
        if (username != null && !username.equals("") && password != null && !password.equals("")) {

            //Validar la dupla usuario-password
            try {
                Usuario usuario = usuarioDao.queryForId(username);
                if (usuario != null && usuario.getPassword().equals(password)) {
                    return true;
                }

            } catch (SQLException ex) {
            }

        }

        return false;

    });

    //Listar sistemas operativos disponibles
    get("/list-so", (Request rqst, Response rspns) -> {
        List<SistemaOperativo> sistemasOperativos = new ArrayList<>();
        try {
            sistemasOperativos = sistemaOperativoDao.queryForAll();
        } catch (SQLException ex) {
            System.out.println("Error listando los sistemas operativos");
        }

        return sistemasOperativos;
    }, new JsonTransformer());

    //Crear mquina virtual
    post("/create-machine", (Request rqst, Response rspns) -> {
        try {
            //Obtener parmetros
            String username = rqst.queryParams("username");
            String nombreMaquina = rqst.queryParams("nombreMaquina");
            String nombreSO = rqst.queryParams("nombreSO");

            Usuario user = usuarioDao.queryForId(username);
            SistemaOperativo so = sistemaOperativoDao.queryForId(nombreSO);

            if (user != null && so != null) {
                //Crear mquina virtual
                MaquinaVirtual maquinaVirtual = new MaquinaVirtual();
                maquinaVirtual.setNombre(nombreMaquina);
                maquinaVirtual.setSistemaOperativo(sistemaOperativoDao.queryForId(nombreSO));
                maquinaVirtual.setUsername(usuarioDao.queryForId(username));

                maquinaVirtualDao.create(maquinaVirtual);

                //Crear carpeta
                String path = "/tmp/" + username + "/" + nombreMaquina;
                File file = new File(path);
                if (!file.exists()) {
                    boolean success = file.mkdir();

                    if (!success) {
                        System.out.println("No se pudo crear la carpeta para la mquina");
                    } else {

                        //Crear Vagrantfile
                        try (Writer writer = new BufferedWriter(
                                new OutputStreamWriter(new FileOutputStream(path + "/Vagrantfile"), "UTF-8"))) {
                            writer.write("VAGRANTFILE_API_VERSION = \"2\"\n");
                            writer.write("Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|\n");
                            writer.write("\n");
                            writer.write("end\n");
                        }

                    }
                }

                return true;
            } else {
                return false;
            }

        } catch (SQLException ex) {
            System.out.println("Error creando la mquina virtual");
            return false;
        }
    });

    //Eliminar usuario y sus mquinas virtuales asociadas
    post("/delete-user", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("usernameLogged");
        String nombreUsuario = rqst.queryParams("usernameToDelete");

        if (userLogged != null && !userLogged.equals("") && nombreUsuario != null && !userLogged.equals("")
                && userLogged.equals("admin")) {
            try {
                Usuario user = usuarioDao.queryForId(nombreUsuario);

                if (user != null) {
                    //Eliminar mquinas virtuales del usuario
                    Collection<MaquinaVirtual> maquinasUsuario = user.getMaquinasVirtuales();
                    for (MaquinaVirtual maquina : maquinasUsuario) {
                        //Eliminar apps de las mquinas virtuales del usuario
                        QueryBuilder<MaquinaApp, String> queryBuilder = maquinaAppDao.queryBuilder();
                        queryBuilder.where().eq(MaquinaApp.MACHINE_FIELD, maquina.getId());
                        PreparedQuery<MaquinaApp> preparedQuery = queryBuilder.prepare();

                        Collection<MaquinaApp> maquinasApps = maquinaAppDao.query(preparedQuery);
                        maquinaAppDao.delete(maquinasApps);

                        //Eliminar la mquina virtual
                        maquinaVirtualDao.delete(maquina);
                    }

                    //Eliminar usuario
                    usuarioDao.delete(user);

                    //Eliminar carpeta del usuario
                    FileUtils.deleteDirectory(new File("/tmp/" + nombreUsuario));

                    return true;
                } else {
                    return false;
                }

            } catch (SQLException ex) {
                System.out.println("Error eliminando el usuario");
                return false;
            }

        } else {
            System.out.println("No tiene permisos para realizar esta accin");
            return false;
        }
    });

    //Listar mquinas virtuales de un usuario
    get("/list-machines", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("username");
        return listMachines(username);
    }, new JsonTransformer());

    //Listar usuarios
    get("/list-users", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("usernameLogged");

        if (username.equals("admin")) {
            List<Usuario> usuarios = new ArrayList<>();
            try {
                usuarios = usuarioDao.queryForAll();
            } catch (SQLException ex) {
                System.out.println("Error listando los usuarios");
            }

            return usuarios;
        } else {
            System.out.println("No tiene permisos para realizar esta accin");
            return "No tiene permisos para realizar esta accin";
        }
    }, new JsonTransformer());

    // Agregar nodo a una mquina virtual
    post("/add-node", (Request rqst, Response rspns) -> {
        String nombreNodo = rqst.queryParams("nombreNodo");
        String ipPrivada = rqst.queryParams("ipPrivada");
        String ipPublica = rqst.queryParams("ipPublica");
        String mascaraRed = rqst.queryParams("mascaraRed");
        String cantidadMemoria = rqst.queryParams("cantidadMemoria");
        String cantidadCPU = rqst.queryParams("cantidadCPU");
        String interfazPuente = rqst.queryParams("interfazPuente");
        String parametrosJSON = rqst.queryParams("parametrosJSON");
        String nombreMaquina = rqst.queryParams("nombreMaquina");
        String userLogged = rqst.queryParams("userLogged");

        Usuario user = usuarioDao.queryForId(userLogged);

        if (user != null) {
            //Buscar mquina
            QueryBuilder<MaquinaVirtual, Integer> queryBuilder = maquinaVirtualDao.queryBuilder();
            queryBuilder.where().eq(MaquinaVirtual.USERNAME_FIELD, userLogged);
            queryBuilder.where().eq(MaquinaVirtual.NOMBRE_FIELD, nombreMaquina);
            PreparedQuery<MaquinaVirtual> preparedQuery = queryBuilder.prepare();
            List<MaquinaVirtual> maquinasUser = maquinaVirtualDao.query(preparedQuery);

            //Existe la mquina
            if (maquinasUser.size() > 0 && maquinasUser.get(0).getNombre().equals(nombreMaquina)) {
                //Crear nodo
                Nodo nodo = new Nodo();
                nodo.setNombre(nombreNodo);
                nodo.setCantidadCPU(cantidadCPU);
                nodo.setCantidadMemoria(cantidadMemoria);
                nodo.setInterfazPuente(interfazPuente);
                nodo.setIpPrivada(ipPrivada);
                nodo.setIpPublica(ipPublica);
                nodo.setMascaraRed(mascaraRed);
                nodo.setParametrosJSON(parametrosJSON);
                nodo.setMaquinaVirtual(maquinasUser.get(0));
                nodoDao.create(nodo);

                //Crear nodo en Vagrantfile
                insertarNodoEnVagrantFile("/tmp/" + userLogged + "/" + nombreMaquina, nodo);

                return true;

            }
        }

        return false;

    });

    //Listar apps para un SO
    get("/list-apps", (Request rqst, Response rspns) -> {
        String nameSO = rqst.queryParams("nombreSO");

        SistemaOperativo buscado = sistemaOperativoDao.queryForId(nameSO);

        if (buscado != null) {

            QueryBuilder<App, String> queryBuilder = appDao.queryBuilder();
            queryBuilder.where().eq(App.SO_FIELD, buscado.getNombre());
            PreparedQuery<App> preparedQuery = queryBuilder.prepare();

            Collection<App> aplicaciones = appDao.query(preparedQuery);

            return aplicaciones;
        } else {
            return "El SO buscado no existe";
        }

    }, new JsonTransformer());

    //Listar apps para una maquina virtual
    get("/list-app-installed", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("userLogged");
        String machineName = rqst.queryParams("nombreMaquina");

        List<MaquinaApp> maquinaApp;
        List<App> apps = new ArrayList<>();

        //Buscar si el usuario loggeado existe
        Usuario buscado;
        MaquinaVirtual buscada = null;
        try {
            buscado = usuarioDao.queryForId(userLogged);

            if (buscado != null) {
                //Lista de maquinas virtuales del usuario
                Collection<MaquinaVirtual> maquinasVirtuales = listMachines(userLogged);

                //Revisar si la maquina virtual buscada pertenece al usuario loggeado
                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(machineName)) {
                        buscada = maquina;
                        break;
                    }
                }

                if (buscada != null) {
                    //Obtener la lista de aplicaciones de la maquina virtual
                    QueryBuilder<MaquinaApp, String> queryBuilderN = maquinaAppDao.queryBuilder();
                    queryBuilderN.where().eq(MaquinaApp.MACHINE_FIELD, buscada.getId());
                    PreparedQuery<MaquinaApp> preparedQueryN = queryBuilderN.prepare();

                    maquinaApp = maquinaAppDao.query(preparedQueryN);

                    if (maquinaApp.size() > 0) {
                        for (MaquinaApp m : maquinaApp) {
                            apps.add(m.getApp());
                        }
                    }

                } else {
                    System.out.println("La maquina no existe para el usuario buscado");
                }
            } else {
                System.out.println("El usuario loggeado no existe");
            }

        } catch (SQLException ex) {
            System.out.println("Error listando las apps instaladas");
        }
        return apps;

    }, new JsonTransformer());

    //Listar nodos de una maquina virtual
    get("/list-node", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        //Inicializar la lista de nodos que se va a retornar
        Collection<Nodo> nodos = new ArrayList<>();

        //Validar que no hayan campos vacios
        if (userLogged != null && !userLogged.equals("") && nombreMaquina != null
                && !nombreMaquina.equals("")) {
            //Buscar el usuario loggeado
            Usuario user = usuarioDao.queryForId(userLogged);

            //Verificar que el usuario existe
            if (user != null) {
                //Obtener las maquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(userLogged);

                for (MaquinaVirtual m : maquinasVirtuales) {
                    if (m.getNombre().equals(nombreMaquina)) {
                        nodos = m.getNodos();
                    }
                }

            } else {
                System.out.println("El usuario loggeado no existe");
            }
        } else {
            System.out.println("No pueden haber parametros vacios");
        }

        return nodos;
    }, new JsonTransformer());

    //Eliminar maquina virtual y aplicaciones asociadas
    post("/delete-vm", (Request rqst, Response rspns) -> {
        String usernameLogged = rqst.queryParams("usernameLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual buscada = null;
        List<MaquinaApp> maquinaApp;

        //Verificar que los parametros recibidos no son null
        if (usernameLogged != null && !usernameLogged.equals("") && nombreMaquina != null
                && !nombreMaquina.equals("")) {

            Usuario user = usuarioDao.queryForId(usernameLogged);

            if (user != null) {
                //Obtener las maquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(usernameLogged);

                //Buscar la maquina virtual a eliminar dentro de las maquinas del usuario
                for (MaquinaVirtual m : maquinasVirtuales) {
                    if (m.getNombre().equals(nombreMaquina)) {
                        buscada = m;
                        break;
                    }
                }

                //Verificar que la maquina buscada pertenece al usuario en cuestion
                if (buscada != null) {
                    //Obtener la lista de aplicaciones de la maquina virtual
                    QueryBuilder<MaquinaApp, String> queryBuilder = maquinaAppDao.queryBuilder();
                    queryBuilder.where().eq(MaquinaApp.MACHINE_FIELD, buscada.getId());
                    PreparedQuery<MaquinaApp> preparedQuery = queryBuilder.prepare();

                    maquinaApp = maquinaAppDao.query(preparedQuery);

                    if (maquinaApp.size() > 0) {
                        //Eliminar las aplicaciones 
                        for (MaquinaApp i : maquinaApp) {
                            maquinaAppDao.delete(i);
                        }

                    } else {
                        System.out.println("No existen aplicaciones para la maquina virtual en cuestion");
                    }

                    //Eliminar mquina virtual
                    maquinaVirtualDao.delete(buscada);

                    //Eliminar carpeta de la maquina virtual
                    FileUtils.deleteDirectory(new File("/tmp/" + usernameLogged + "/" + nombreMaquina));
                    return true;

                }
            } else {
                System.out.println("EL usuario loggeado no existe");
            }

        } else {
            System.out.println("No pueden haber campos vacios");
        }

        return false;
    });

    //Correr mquina virtual
    post("/run-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant up");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Destruir mquina virtual
    post("/destroy-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant destroy -f");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Reanudar mquina virtual
    post("/resume-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant resume");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Asociar app a una mquina virtual
    post("/associate-app", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("username");
        String nombreMaquina = rqst.queryParams("nombreMaquina");
        String nombreApp = rqst.queryParams("nombreApp");

        Usuario user = usuarioDao.queryForId(username);

        if (user != null) {
            //Verificar si el usuario tiene la mquina
            List<MaquinaVirtual> maquinas = listMachines(username);

            MaquinaVirtual buscada = null;

            for (MaquinaVirtual maquina : maquinas) {
                if (maquina.getNombre().equals(nombreMaquina)) {
                    buscada = maquina;
                    break;
                }
            }

            if (buscada != null) {
                App app = appDao.queryForId(nombreApp);

                //Verificar si la app existe y si est para el mismo sistema operativo que tiene la mquina
                if (app != null && app.getSistemaOperativo().getNombre()
                        .equals(buscada.getSistemaOperativo().getNombre())) {
                    //Agregar a la base de datos
                    MaquinaApp maquinaApp = new MaquinaApp(buscada, app);
                    maquinaAppDao.create(maquinaApp);

                    //Crear registro en el Vagrantfile
                    String path = "/tmp/" + username + "/" + nombreMaquina;
                    insertarCookbooksANodos(new ArrayList(buscada.getNodos()), app, path);

                    return true;
                } else {
                    System.out.println("La app no existe");
                }
            } else {
                System.out.println("No se encontr la mquina en la lista del usuario");
            }
        } else {
            System.out.println("El usuario no existe");
        }

        return false;

    });

    //Listar todas las aplicaciones
    get("/list-apps-all", (Request rqst, Response rspns) -> {
        return appDao.queryForAll();
    }, new JsonTransformer());

    // Cargar datos de prueba
    get("/add-testdata", (Request rqst, Response rspns) -> {
        try {
            if (connectionSource != null) {
                TableUtils.createTableIfNotExists(connectionSource, Usuario.class);
                TableUtils.createTableIfNotExists(connectionSource, SistemaOperativo.class);
                TableUtils.createTableIfNotExists(connectionSource, MaquinaVirtual.class);
                TableUtils.createTableIfNotExists(connectionSource, App.class);
                TableUtils.createTableIfNotExists(connectionSource, MaquinaApp.class);
                TableUtils.createTableIfNotExists(connectionSource, Cookbook.class);
                TableUtils.createTableIfNotExists(connectionSource, CookbookApp.class);
                TableUtils.createTableIfNotExists(connectionSource, Nodo.class);
            }
            testData();
        } catch (SQLException ex) {
            return "Error agregando informacin de prueba";
        }

        return "OK";
    });

    //Eliminar datos de prueba
    get("/delete-testdata", (Request rqst, Response rspns) -> {
        try {
            TableUtils.dropTable(connectionSource, Usuario.class, true);
            TableUtils.dropTable(connectionSource, MaquinaVirtual.class, true);
            TableUtils.dropTable(connectionSource, SistemaOperativo.class, true);
            TableUtils.dropTable(connectionSource, App.class, true);
            TableUtils.dropTable(connectionSource, Cookbook.class, true);
            TableUtils.dropTable(connectionSource, MaquinaApp.class, true);
            TableUtils.dropTable(connectionSource, CookbookApp.class, true);
            TableUtils.dropTable(connectionSource, Nodo.class, true);
        } catch (SQLException ex) {
            return "Error eliminando la informacin";
        }

        return "OK";
    });

}

From source file:edu.isi.karma.research.modeling.ModelLearner_LOD.java

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

    ServletContextParameterMap contextParameters = ContextParametersRegistry.getInstance().getDefault();
    contextParameters.setParameterValue(ContextParameter.USER_CONFIG_DIRECTORY, "/Users/mohsen/karma/config");

    OntologyManager ontologyManager = new OntologyManager(contextParameters.getId());
    File ff = new File(Params.ONTOLOGY_DIR);
    File[] files = ff.listFiles();
    if (files == null) {
        logger.error("no ontology to import at " + ff.getAbsolutePath());
        return;/* w w  w  .  j a  v a  2  s  .  c  om*/
    }

    for (File f : files) {
        if (f.getName().endsWith(".owl") || f.getName().endsWith(".rdf") || f.getName().endsWith(".n3")
                || f.getName().endsWith(".ttl") || f.getName().endsWith(".xml")) {
            logger.info("Loading ontology file: " + f.getAbsolutePath());
            ontologyManager.doImport(f, "UTF-8");
        }
    }
    ontologyManager.updateCache();

    String outputPath = Params.OUTPUT_DIR;
    String graphPath = Params.GRAPHS_DIR;

    FileUtils.cleanDirectory(new File(graphPath));

    List<SemanticModel> semanticModels = ModelReader.importSemanticModelsFromJsonFiles(Params.MODEL_DIR,
            Params.MODEL_MAIN_FILE_EXT);

    ModelLearner_LOD modelLearner = null;

    boolean onlyGenerateSemanticTypeStatistics = false;
    boolean onlyUseOntology = false;
    boolean useCorrectType = false;
    int numberOfCandidates = 4;
    boolean onlyEvaluateInternalLinks = false;
    int maxPatternSize = 3;

    if (onlyGenerateSemanticTypeStatistics) {
        getStatistics(semanticModels);
        return;
    }

    String filePath = Params.RESULTS_DIR + "temp/";
    String filename = "";

    filename += "lod-results";
    filename += useCorrectType ? "-correct" : "-k=" + numberOfCandidates;
    filename += onlyUseOntology ? "-ontology" : "-p" + maxPatternSize;
    filename += onlyEvaluateInternalLinks ? "-internal" : "-all";
    filename += ".csv";

    PrintWriter resultFile = new PrintWriter(new File(filePath + filename));

    resultFile.println("source \t p \t r \t t \n");

    for (int i = 0; i < semanticModels.size(); i++) {
        //      for (int i = 0; i <= 10; i++) {
        //      int i = 1; {

        int newSourceIndex = i;
        SemanticModel newSource = semanticModels.get(newSourceIndex);

        logger.info("======================================================");
        logger.info(newSource.getName() + "(#attributes:" + newSource.getColumnNodes().size() + ")");
        System.out.println(newSource.getName() + "(#attributes:" + newSource.getColumnNodes().size() + ")");
        logger.info("======================================================");

        SemanticModel correctModel = newSource;
        List<ColumnNode> columnNodes = correctModel.getColumnNodes();

        List<Node> steinerNodes = new LinkedList<Node>(columnNodes);

        String graphName = graphPath + "lod" + Params.GRAPH_FILE_EXT;

        if (onlyUseOntology) {
            modelLearner = new ModelLearner_LOD(new GraphBuilder(ontologyManager, false), steinerNodes);
        } else if (new File(graphName).exists()) {
            // read graph from file
            try {
                logger.info("loading the graph ...");
                DirectedWeightedMultigraph<Node, DefaultLink> graph = GraphUtil.importJson(graphName);
                modelLearner = new ModelLearner_LOD(new GraphBuilderTopK(ontologyManager, graph), steinerNodes);
            } catch (Exception e) {
                e.printStackTrace();
                resultFile.close();
                return;
            }
        } else {
            logger.info("building the graph ...");
            // create and save the graph to file
            //            GraphBuilder_Popularity b = new GraphBuilder_Popularity(ontologyManager, 
            //                  Params.LOD_OBJECT_PROPERIES_FILE, 
            //                  Params.LOD_DATA_PROPERIES_FILE);
            GraphBuilder_LOD_Pattern b = new GraphBuilder_LOD_Pattern(ontologyManager, Params.PATTERNS_DIR,
                    maxPatternSize);
            modelLearner = new ModelLearner_LOD(b.getGraphBuilder(), steinerNodes);
        }

        long start = System.currentTimeMillis();

        List<SortableSemanticModel> hypothesisList = modelLearner.hypothesize(useCorrectType,
                numberOfCandidates);

        long elapsedTimeMillis = System.currentTimeMillis() - start;
        float elapsedTimeSec = elapsedTimeMillis / 1000F;

        List<SortableSemanticModel> topHypotheses = null;
        if (hypothesisList != null) {

            //            for (SortableSemanticModel sss : hypothesisList) {
            //               ModelEvaluation mmm = sss.evaluate(correctModel);
            //               System.out.println(mmm.getPrecision() + ", " + mmm.getRecall());
            //            }
            topHypotheses = hypothesisList.size() > 10 ? hypothesisList.subList(0, 10) : hypothesisList;
        }

        Map<String, SemanticModel> models = new TreeMap<String, SemanticModel>();

        ModelEvaluation me;
        models.put("1-correct model", correctModel);
        if (topHypotheses != null)
            for (int k = 0; k < topHypotheses.size(); k++) {

                SortableSemanticModel m = topHypotheses.get(k);

                me = m.evaluate(correctModel, onlyEvaluateInternalLinks, false);

                String label = "candidate " + k + "\n" +
                //                     (m.getSteinerNodes() == null ? "" : m.getSteinerNodes().getScoreDetailsString()) +
                        "link coherence:"
                        + (m.getLinkCoherence() == null ? "" : m.getLinkCoherence().getCoherenceValue()) + "\n";
                label += (m.getSteinerNodes() == null || m.getSteinerNodes().getCoherence() == null) ? ""
                        : "node coherence:" + m.getSteinerNodes().getCoherence().getCoherenceValue() + "\n";
                label += "confidence:" + m.getConfidenceScore() + "\n";
                label += m.getSteinerNodes() == null ? ""
                        : "mapping score:" + m.getSteinerNodes().getScore() + "\n";
                label += "cost:" + roundDecimals(m.getCost(), 6) + "\n" +
                //                        "-distance:" + me.getDistance() + 
                        "-precision:" + me.getPrecision() + "-recall:" + me.getRecall();

                models.put(label, m);

                if (k == 0) { // first rank model
                    System.out.println("precision: " + me.getPrecision() + ", recall: " + me.getRecall()
                            + ", time: " + elapsedTimeSec);
                    logger.info("precision: " + me.getPrecision() + ", recall: " + me.getRecall() + ", time: "
                            + elapsedTimeSec);
                    String s = newSource.getName() + "\t" + me.getPrecision() + "\t" + me.getRecall() + "\t"
                            + elapsedTimeSec;
                    resultFile.println(s);

                }
            }

        String outName = outputPath + newSource.getName() + Params.GRAPHVIS_OUT_DETAILS_FILE_EXT;

        GraphVizUtil.exportSemanticModelsToGraphviz(models, newSource.getName(), outName,
                GraphVizLabelType.LocalId, GraphVizLabelType.LocalUri, true, true);

    }

    resultFile.close();

}

From source file:com.cyberway.issue.io.warc.WARCReader.java

/**
 * Command-line interface to WARCReader.
 *
 * Here is the command-line interface:/* ww w  .  j av a 2s  .c  o m*/
 * <pre>
 * usage: java com.cyberway.issue.io.arc.WARCReader [--offset=#] ARCFILE
 *  -h,--help      Prints this message and exits.
 *  -o,--offset    Outputs record at this offset into arc file.</pre>
 *
 * <p>Outputs using a pseudo-CDX format as described here:
 * <a href="http://www.archive.org/web/researcher/cdx_legend.php">CDX
 * Legent</a> and here
 * <a href="http://www.archive.org/web/researcher/example_cdx.php">Example</a>.
 * Legend used in below is: 'CDX b e a m s c V (or v if uncompressed) n g'.
 * Hash is hard-coded straight SHA-1 hash of content.
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = getOptions();
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();

    // If no args, print help.
    if (cmdlineArgs.size() <= 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    long offset = -1;
    boolean digest = false;
    boolean strict = false;
    String format = CDX;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'o':
            offset = Long.parseLong(cmdlineOptions[i].getValue());
            break;

        case 's':
            strict = true;
            break;

        case 'd':
            digest = getTrueOrFalse(cmdlineOptions[i].getValue());
            break;

        case 'f':
            format = cmdlineOptions[i].getValue().toLowerCase();
            boolean match = false;
            // List of supported formats.
            final String[] supportedFormats = { CDX, DUMP, GZIP_DUMP, CDX_FILE };
            for (int ii = 0; ii < supportedFormats.length; ii++) {
                if (supportedFormats[ii].equals(format)) {
                    match = true;
                    break;
                }
            }
            if (!match) {
                usage(formatter, options, 1);
            }
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    if (offset >= 0) {
        if (cmdlineArgs.size() != 1) {
            System.out.println("Error: Pass one arcfile only.");
            usage(formatter, options, 1);
        }
        WARCReader r = WARCReaderFactory.get(new File((String) cmdlineArgs.get(0)), offset);
        r.setStrict(strict);
        outputRecord(r, format);
    } else {
        for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) {
            String urlOrPath = (String) i.next();
            try {
                WARCReader r = WARCReaderFactory.get(urlOrPath);
                r.setStrict(strict);
                r.setDigest(digest);
                output(r, format);
            } catch (RuntimeException e) {
                // Write out name of file we failed on to help with
                // debugging.  Then print stack trace and try to keep
                // going.  We do this for case where we're being fed
                // a bunch of ARCs; just note the bad one and move
                // on to the next.
                System.err.println("Exception processing " + urlOrPath + ": " + e.getMessage());
                e.printStackTrace(System.err);
                System.exit(1);
            }
        }
    }
}

From source file:imp.lstm.main.Driver.java

public static void main(String[] args)
        throws FileNotFoundException, IOException, ConfigurationException, InvalidParametersException {
    FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(
            PropertiesConfiguration.class).configure(
                    new Parameters().properties().setFileName(args[0]).setThrowExceptionOnMissing(true)
                            .setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
                            .setIncludesAllowed(false));
    Configuration config = builder.getConfiguration();

    String inputSongPath = config.getString("input_song");
    String outputFolderPath = config.getString("output_folder");
    String autoEncoderParamsPath = config.getString("auto_encoder_params");
    String nameGeneratorParamsPath = config.getString("name_generator_params");
    String queueFolderPath = config.getString("queue_folder");
    String referenceQueuePath = config.getString("reference_queue", "nil");
    String inputCorpusFolder = config.getString("input_corpus_folder");
    boolean shouldWriteQueue = config.getBoolean("should_write_generated_queue");
    boolean frankensteinTest = config.getBoolean("queue_tests_frankenstein");
    boolean interpolateTest = config.getBoolean("queue_tests_interpolation");
    boolean iterateOverCorpus = config.getBoolean("iterate_over_corpus", false);
    boolean shouldGenerateSongTitle = config.getBoolean("generate_song_title");
    boolean shouldGenerateSong = config.getBoolean("generate_leadsheet");

    LogTimer.initStartTime(); //start our logging timer to keep track of our execution time
    LogTimer.log("Creating name generator...");

    //here is just silly code for generating name based on an LSTM lol $wag
    LSTM lstm = new LSTM();
    FullyConnectedLayer fullLayer = new FullyConnectedLayer(Operations.None);
    Loadable titleNetLoader = new Loadable() {
        @Override//  ww w  . j a va 2 s  .  co  m
        public boolean load(INDArray array, String path) {
            String car = pathCar(path);
            String cdr = pathCdr(path);
            switch (car) {
            case "full":
                return fullLayer.load(array, cdr);
            case "lstm":
                return lstm.load(array, cdr);
            default:
                return false;
            }
        }
    };

    LogTimer.log("Packing name generator from files...");
    (new NetworkConnectomeLoader()).load(nameGeneratorParamsPath, titleNetLoader);

    String characterString = " !\"'[],-.01245679:?ABCDEFGHIJKLMNOPQRSTUVWYZabcdefghijklmnopqrstuvwxyz";

    //Initialization
    LogTimer.log("Creating autoencoder...");
    int inputSize = 34;
    int outputSize = EncodingParameters.noteEncoder.getNoteLength();
    int featureVectorSize = 100;
    ProductCompressingAutoencoder autoencoder = new ProductCompressingAutoencoder(24, 48, 84 + 1, false); //create our network

    int numInterpolationDivisions = 5;

    //"pack" the network from weights and biases file directory
    LogTimer.log("Packing autoencoder from files");
    (new NetworkConnectomeLoader()).load(autoEncoderParamsPath, autoencoder);

    File[] songFiles;
    if (iterateOverCorpus) {
        songFiles = new File(inputCorpusFolder).listFiles();
    } else {
        songFiles = new File[] { new File(inputSongPath) };
    }
    for (File inputFile : songFiles) {
        (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate");
        String songTitle;
        if (shouldGenerateSong) {
            Random rand = new Random();
            AVector charOut = Vector.createLength(characterString.length());
            GroupedSoftMaxSampler sampler = new GroupedSoftMaxSampler(
                    new Group[] { new Group(0, characterString.length(), true) });
            songTitle = "";
            for (int i = 0; i < 50; i++) {
                charOut = fullLayer.forward(lstm.step(charOut));
                charOut = sampler.filter(charOut);
                int charIndex = 0;
                for (; charIndex < charOut.length(); charIndex++) {
                    if (charOut.get(charIndex) == 1.0) {
                        break;
                    }
                }
                songTitle += characterString.substring(charIndex, charIndex + 1);
            }
            songTitle = songTitle.trim();

            LogTimer.log("Generated song name: " + songTitle);
        } else {
            songTitle = "The Song We Never Name";
        }
        LogTimer.log("Reading file...");
        LeadSheetDataSequence inputSequence = LeadSheetIO.readLeadSheet(inputFile); //read our leadsheet to get a data vessel as retrieved in rbm-provisor
        LeadSheetDataSequence outputSequence = inputSequence.copy();

        outputSequence.clearMelody();
        if (interpolateTest) {
            LeadSheetDataSequence additionalOutput = outputSequence.copy();
            for (int i = 0; i < numInterpolationDivisions; i++) {
                outputSequence.concat(additionalOutput.copy());
            }
        }
        LeadSheetDataSequence decoderInputSequence = outputSequence.copy();

        LogTimer.startLog("Encoding data...");
        //TradingTimer.initStart(); //start our trading timer to keep track our our generation versus realtime play
        while (inputSequence.hasNext()) { //iterate through time steps in input data
            //TradingTimer.waitForNextTimedInput();
            autoencoder.encodeStep(inputSequence.retrieve()); //feed the resultant input vector into the network
            if (advanceDecoding) { //if we are using advance decoding (we start decoding as soon as we can)
                if (autoencoder.canDecode()) { //if queue has enough data to decode from
                    outputSequence.pushStep(null, null,
                            autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                    //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are
                }
            }
        }
        LogTimer.endLog();

        if (shouldWriteQueue) {
            String queueFilePath = queueFolderPath + java.io.File.separator
                    + inputFile.getName().replace(".ls", ".q");
            FragmentedNeuralQueue currQueue = autoencoder.getQueue();
            currQueue.writeToFile(queueFilePath);
            LogTimer.log("Wrote queue " + inputFile.getName().replace(".ls", ".q") + " to file...");
        }
        if (shouldGenerateSong) {
            if (interpolateTest) {

                FragmentedNeuralQueue refQueue = new FragmentedNeuralQueue();
                refQueue.initFromFile(referenceQueuePath);

                FragmentedNeuralQueue currQueue = autoencoder.getQueue();
                //currQueue.writeToFile(queueFilePath);

                autoencoder.setQueue(currQueue.copy());
                while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                    outputSequence.pushStep(null, null,
                            autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                    //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                }

                for (int i = 1; i <= numInterpolationDivisions; i++) {
                    System.out.println("Starting interpolation " + ((1.0 / numInterpolationDivisions) * (i)));
                    (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate");
                    FragmentedNeuralQueue currCopy = currQueue.copy();
                    currCopy.basicInterpolate(refQueue, (1.0 / numInterpolationDivisions) * (i));
                    autoencoder.setQueue(currCopy);
                    int timeStep = 0;
                    while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                        System.out.println("interpolation " + i + " step " + ++timeStep);
                        outputSequence.pushStep(null, null,
                                autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                        //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                    }
                }

            }
            if (frankensteinTest) {
                LogTimer.startLog("Loading queues");
                File queueFolder = new File(queueFolderPath);
                int numComponents = config.getInt("frankenstein_num_components", 5);
                int numCombinations = config.getInt("frankenstein_num_combinations", 6);
                double interpolationMagnitude = config.getDouble("frankenstein_magnitude", 2.0);
                if (queueFolder.isDirectory()) {
                    File[] queueFiles = queueFolder.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return name.contains(".q");
                        }
                    });

                    List<File> fileList = new ArrayList<>();
                    for (File file : queueFiles) {
                        fileList.add(file);
                    }
                    Collections.shuffle(fileList);
                    int numSelectedFiles = (numComponents > queueFiles.length) ? queueFiles.length
                            : numComponents;

                    for (int i = 0; i < queueFiles.length - numSelectedFiles; i++) {
                        fileList.remove(fileList.size() - 1);
                    }
                    List<FragmentedNeuralQueue> queuePopulation = new ArrayList<>(fileList.size());
                    songTitle += " - a mix of ";
                    for (File file : fileList) {
                        FragmentedNeuralQueue newQueue = new FragmentedNeuralQueue();
                        newQueue.initFromFile(file.getPath());
                        queuePopulation.add(newQueue);
                        songTitle += file.getName().replaceAll(".ls", "") + ", ";
                    }
                    LogTimer.endLog();

                    LeadSheetDataSequence additionalOutput = outputSequence.copy();
                    for (int i = 1; i < numCombinations; i++) {
                        outputSequence.concat(additionalOutput.copy());
                    }
                    decoderInputSequence = outputSequence.copy();

                    FragmentedNeuralQueue origQueue = autoencoder.getQueue();

                    for (int i = 0; i < numCombinations; i++) {

                        LogTimer.startLog("Performing queue interpolation...");
                        AVector combinationStrengths = Vector.createLength(queuePopulation.size());
                        Random vectorRand = new Random(i);
                        for (int j = 0; j < combinationStrengths.length(); j++) {
                            combinationStrengths.set(j, vectorRand.nextDouble());
                        }
                        combinationStrengths.divide(combinationStrengths.elementSum());
                        FragmentedNeuralQueue currQueue = origQueue.copy();
                        for (int k = 0; k < combinationStrengths.length(); k++) {
                            currQueue.basicInterpolate(queuePopulation.get(k),
                                    combinationStrengths.get(k) * interpolationMagnitude);
                        }
                        LogTimer.endLog();
                        autoencoder.setQueue(currQueue);
                        LogTimer.startLog("Refreshing autoencoder state...");
                        (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder,
                                "initialstate");
                        LogTimer.endLog();
                        LogTimer.startLog("Decoding segment...");
                        while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                            outputSequence.pushStep(null, null,
                                    autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                            //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                        }
                        LogTimer.endLog();
                    }

                }
            }

            while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
            }
            LogTimer.log("Writing file...");

            String outputFilename = outputFolderPath + java.io.File.separator
                    + inputFile.getName().replace(".ls", "_Output"); //we'll write our generated file with the same name plus "_Output"
            LeadSheetIO.writeLeadSheet(outputSequence, outputFilename, songTitle);
            System.out.println(outputFilename);
        } else {
            autoencoder.setQueue(new FragmentedNeuralQueue());
        }
    }
    LogTimer.log("Process finished"); //Done!

}

From source file:de.codesourcery.geoip.Main.java

public static void main(String[] args) throws Exception {
    final IGeoLocator<StringSubject> locator = createGeoLocator();

    final JFrame frame = new JFrame("GeoIP");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent e) {
            try {
                locator.dispose();//from w  w  w  .ja  v a 2  s  .c o m
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        };
    });

    final MapImage image = MapImage.getRobinsonWorldMap(); // MapImage.getMillerWorldMap();      
    final MapCanvas canvas = new MapCanvas(image);

    for (GeoLocation<StringSubject> loc : locator.locate(getSpammers())) {
        if (loc.hasValidCoordinates()) {
            canvas.addCoordinate(PointRenderer.createPoint(loc, Color.YELLOW));
        }
    }

    //      canvas.addCoordinate( PointRenderer.createPoint( ZERO , Color.YELLOW ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( WELLINGTON , Color.RED ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( MELBOURNE , Color.RED ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( HAMBURG , Color.RED ) );

    final double heightToWidth = image.height() / (double) image.width(); // preserve aspect ratio of map
    canvas.setPreferredSize(new Dimension(640, (int) Math.round(640 * heightToWidth)));

    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());

    panel.add(new JLabel("Scale-X"));
    final JTextField scaleX = new JTextField(Double.toString(image.getScaleX()));
    scaleX.setColumns(5);

    final JTextField scaleY = new JTextField(Double.toString(image.getScaleY()));
    scaleY.setColumns(5);

    final ActionListener listener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            double x = Double.parseDouble(scaleX.getText());
            double y = Double.parseDouble(scaleY.getText());
            image.setScale(x, y);
            canvas.repaint();
        }
    };
    scaleX.addActionListener(listener);
    scaleY.addActionListener(listener);

    panel.add(new JLabel("Scale-X"));
    panel.add(scaleX);

    panel.add(new JLabel("Scale-Y"));
    panel.add(scaleY);

    final JTextField ipAddress = new JTextField("www.kickstarter.com");
    ipAddress.setColumns(20);

    final ActionListener ipListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final String destinationIP = ipAddress.getText();
            if (StringUtils.isBlank(destinationIP)) {
                return;
            }

            /*
             * Perform traceroute.
             */
            final List<String> hops;
            try {
                if (TracePath.isPathTracingAvailable()) {
                    hops = TracePath.trace(destinationIP);
                } else {
                    System.err.println("tracepath not available.");
                    if (TracePath.isValidAddress(destinationIP)) {
                        hops = new ArrayList<>();
                        hops.add(destinationIP);
                    } else {
                        System.err.println(destinationIP + " is no valid IP");
                        return;
                    }
                }
            } catch (Exception ex) {
                System.err.println("Failed to trace " + destinationIP);
                ex.printStackTrace();
                return;
            }

            System.out.println("Trace contains " + hops.size() + " IPs");

            /*
             * Gather locations.
             */
            final List<StringSubject> subjects = new ArrayList<>();
            for (String ip : hops) {
                subjects.add(new StringSubject(ip));
            }

            final List<GeoLocation<StringSubject>> locations;
            try {
                long time = -System.currentTimeMillis();
                locations = locator.locate(subjects);
                time += System.currentTimeMillis();

                System.out.println("Locating hops for " + destinationIP + " returned " + locations.size()
                        + " valid locations ( time: " + time + " ms)");
                System.out.flush();

            } catch (Exception e2) {
                e2.printStackTrace();
                return;
            }

            /*
             * Weed-out invalid/unknown locations.
             */
            {
                GeoLocation<StringSubject> previous = null;
                for (Iterator<GeoLocation<StringSubject>> it = locations.iterator(); it.hasNext();) {
                    final GeoLocation<StringSubject> location = it.next();
                    if (!location.hasValidCoordinates()
                            || (previous != null && previous.coordinate().equals(location.coordinate()))) {
                        it.remove();
                        System.err.println("Ignoring invalid/duplicate location for " + location);
                    } else {
                        previous = location;
                    }
                }
            }

            /*
             * Populate chart.
             */

            System.out.println("Adding " + locations.size() + " hops to chart");
            System.out.flush();

            canvas.removeAllCoordinates();

            if (locations.size() == 1) {
                canvas.addCoordinate(
                        PointRenderer.createPoint(locations.get(0), getLabel(locations.get(0)), Color.BLACK));
            } else if (locations.size() > 1) {
                GeoLocation<StringSubject> previous = locations.get(0);
                MapPoint previousPoint = PointRenderer.createPoint(previous, getLabel(previous), Color.BLACK);
                final int len = locations.size();
                for (int i = 1; i < len; i++) {
                    final GeoLocation<StringSubject> current = locations.get(i);
                    //                  final MapPoint currentPoint = PointRenderer.createPoint( current , getLabel( current ) , Color.BLACK );
                    final MapPoint currentPoint = PointRenderer.createPoint(current, Color.BLACK);

                    //                  canvas.addCoordinate( LineRenderer.createLine( previousPoint , currentPoint , Color.RED ) );
                    canvas.addCoordinate(CurvedLineRenderer.createLine(previousPoint, currentPoint, Color.RED));

                    previous = locations.get(i);
                    previousPoint = currentPoint;
                }
            }
            System.out.println("Finished adding");
            System.out.flush();
            canvas.repaint();
        }
    };
    ipAddress.addActionListener(ipListener);

    panel.add(new JLabel("IP"));
    panel.add(ipAddress);

    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(panel, BorderLayout.NORTH);
    frame.getContentPane().add(canvas, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
}