Example usage for java.util Vector elementAt

List of usage examples for java.util Vector elementAt

Introduction

In this page you can find the example usage for java.util Vector elementAt.

Prototype

public synchronized E elementAt(int index) 

Source Link

Document

Returns the component at the specified index.

Usage

From source file:Matrix.java

/**
 * Read a matrix from a stream. The format is the same the print method, so
 * printed matrices can be read back in (provided they were printed using US
 * Locale). Elements are separated by whitespace, all the elements for each
 * row appear on a single line, the last row is followed by a blank line.
 * //  w ww  .  j  av  a  2s  .c o  m
 * @param input
 *            the input stream.
 */

public static Matrix read(BufferedReader input) throws java.io.IOException {
    StreamTokenizer tokenizer = new StreamTokenizer(input);

    // Although StreamTokenizer will parse numbers, it doesn't recognize
    // scientific notation (E or D); however, Double.valueOf does.
    // The strategy here is to disable StreamTokenizer's number parsing.
    // We'll only get whitespace delimited words, EOL's and EOF's.
    // These words should all be numbers, for Double.valueOf to parse.

    tokenizer.resetSyntax();
    tokenizer.wordChars(0, 255);
    tokenizer.whitespaceChars(0, ' ');
    tokenizer.eolIsSignificant(true);
    java.util.Vector v = new java.util.Vector();

    // Ignore initial empty lines
    while (tokenizer.nextToken() == StreamTokenizer.TT_EOL)
        ;
    if (tokenizer.ttype == StreamTokenizer.TT_EOF)
        throw new java.io.IOException("Unexpected EOF on matrix read.");
    do {
        v.addElement(Double.valueOf(tokenizer.sval)); // Read & store 1st
        // row.
    } while (tokenizer.nextToken() == StreamTokenizer.TT_WORD);

    int n = v.size(); // Now we've got the number of columns!
    double row[] = new double[n];
    for (int j = 0; j < n; j++)
        // extract the elements of the 1st row.
        row[j] = ((Double) v.elementAt(j)).doubleValue();
    v.removeAllElements();
    v.addElement(row); // Start storing rows instead of columns.
    while (tokenizer.nextToken() == StreamTokenizer.TT_WORD) {
        // While non-empty lines
        v.addElement(row = new double[n]);
        int j = 0;
        do {
            if (j >= n)
                throw new java.io.IOException("Row " + v.size() + " is too long.");
            row[j++] = Double.valueOf(tokenizer.sval).doubleValue();
        } while (tokenizer.nextToken() == StreamTokenizer.TT_WORD);
        if (j < n)
            throw new java.io.IOException("Row " + v.size() + " is too short.");
    }
    int m = v.size(); // Now we've got the number of rows.
    double[][] A = new double[m][];
    v.copyInto(A); // copy the rows out of the vector
    return new Matrix(A);
}

From source file:org.ecoinformatics.seek.datasource.eml.eml2.Eml200DataSource.java

/**
 * Method to transform a string array to token array based on given type.
 *///from  w w  w.  j a v  a  2s .  co m
static Token[] transformStringVectorToTokenArray(Vector stringVector, Type type, Vector missingValuecode)
        throws IllegalActionException {
    if (stringVector == null) {
        return null;
    }
    int size = stringVector.size();
    Token[] columnToken = new Token[size];
    for (int j = 0; j < size; j++) {
        String eleStr = (String) stringVector.elementAt(j);
        log.debug("The column value " + eleStr);
        Token val = transformStringToToken(eleStr, type, missingValuecode, null);
        columnToken[j] = val;
    }

    return columnToken;
}

From source file:com.netscape.cms.servlet.cert.DoRevoke.java

/**
 * Process cert status change request//from   ww w .j  a  va  2 s  .c  o m
 * <P>
 *
 * (Certificate Request - either an "agent" cert status change request, or an "EE" cert status change request)
 * <P>
 *
 * (Certificate Request Processed - either an "agent" cert status change request, or an "EE" cert status change
 * request)
 * <P>
 *
 * <ul>
 * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST used when a cert status change request (e. g. -
 * "revocation") is made (before approval process)
 * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_STATUS_CHANGE_REQUEST_PROCESSED used when a certificate status is
 * changed (revoked, expired, on-hold, off-hold)
 * </ul>
 *
 * @param argSet CMS template parameters
 * @param header argument block
 * @param reason revocation reason (0 - Unspecified, 1 - Key compromised,
 *            2 - CA key compromised; should not be used, 3 - Affiliation changed,
 *            4 - Certificate superceded, 5 - Cessation of operation, or
 *            6 - Certificate is on hold)
 * @param invalidityDate certificate validity date
 * @param initiative string containing the audit format
 * @param req HTTP servlet request
 * @param resp HTTP servlet response
 * @param verifiedRecordCount number of verified records
 * @param revokeAll string containing information on all of the
 *            certificates to be revoked
 * @param totalRecordCount total number of records (verified and unverified)
 * @param eeSerialNumber BigInteger containing the end-entity certificate
 *            serial number
 * @param eeSubjectDN string containing the end-entity certificate subject
 *            distinguished name (DN)
 * @param comments string containing certificate comments
 * @param locale the system locale
 * @exception EBaseException an error has occurred
 */
private void process(CMSTemplateParams argSet, IArgBlock header, int reason, Date invalidityDate,
        String initiative, HttpServletRequest req, HttpServletResponse resp, int verifiedRecordCount,
        String revokeAll, int totalRecordCount, BigInteger eeSerialNumber, String eeSubjectDN, String comments,
        Locale locale) throws EBaseException {

    CMS.debug("DoRevoke: eeSerialNumber: " + eeSerialNumber);
    long startTime = CMS.getCurrentDate().getTime();

    RevocationProcessor processor = new RevocationProcessor(servletConfig.getServletName(), getLocale(req));

    processor.setStartTime(startTime);
    processor.setInitiative(initiative);
    processor.setSerialNumber(eeSerialNumber == null ? null : new CertId(eeSerialNumber));

    RevocationReason revReason = RevocationReason.fromInt(reason);
    processor.setRevocationReason(revReason);
    processor.setRequestType(
            processor.getRevocationReason() == RevocationReason.CERTIFICATE_HOLD ? RevocationProcessor.ON_HOLD
                    : RevocationProcessor.REVOKE);

    processor.setInvalidityDate(invalidityDate);
    processor.setComments(comments);

    Hashtable<BigInteger, Long> nonceMap = new Hashtable<BigInteger, Long>();
    X509Certificate clientCert = getSSLClientCertificate(req);

    if (mAuthority instanceof ICertificateAuthority) {
        processor.setAuthority(certAuthority);

        if (certAuthority.noncesEnabled()) {
            String nonces = req.getParameter("nonce");
            if (nonces == null) {
                throw new ForbiddenException("Missing nonce.");
            }

            // parse serial numbers and nonces
            for (String s : nonces.split(",")) {
                String[] elements = s.split(":");
                BigInteger serialNumber = new BigInteger(elements[0].trim());
                Long nonce = new Long(elements[1].trim());
                nonceMap.put(serialNumber, nonce);
            }
        }
    }

    try {
        processor.createCRLExtension();

        if (mAuthority instanceof ICertificateAuthority) {

            Enumeration<ICertRecord> e = mCertDB.searchCertificates(revokeAll, totalRecordCount, mTimeLimits);

            while (e != null && e.hasMoreElements()) {
                ICertRecord targetRecord = e.nextElement();
                X509CertImpl targetCert = targetRecord.getCertificate();

                // Verify end-entity cert is not revoked.
                // TODO: This should be checked during authentication.
                if (eeSerialNumber != null && eeSerialNumber.equals(targetCert.getSerialNumber())
                        && targetRecord.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
                    processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CA_CERTIFICATE_ALREADY_REVOKED_1",
                            targetRecord.getSerialNumber().toString(16)));

                    throw new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED"));
                }

                IArgBlock rarg = CMS.createArgBlock();
                rarg.addStringValue("serialNumber", targetCert.getSerialNumber().toString(16));

                try {
                    if (mAuthority instanceof ICertificateAuthority && certAuthority.noncesEnabled()
                            && !processor.isMemberOfSubsystemGroup(clientCert)) {
                        // validate nonce for each certificate
                        Long nonce = nonceMap.get(targetRecord.getSerialNumber());
                        processor.validateNonce(req, "cert-revoke", targetRecord.getSerialNumber(), nonce);
                    }

                    processor.validateCertificateToRevoke(eeSubjectDN, targetRecord, false);
                    processor.addCertificateToRevoke(targetCert);
                    rarg.addStringValue("error", null);

                } catch (PKIException ex) {
                    rarg.addStringValue("error", ex.getMessage());
                }

                argSet.addRepeatRecord(rarg);
            }

        } else if (mAuthority instanceof IRegistrationAuthority) {
            String reqIdStr = req.getParameter("requestId");
            Collection<CertId> certSerialNumbers = new ArrayList<CertId>();

            if (revokeAll != null && revokeAll.length() > 0) {
                for (int i = revokeAll.indexOf('='); i > -1; i = revokeAll.indexOf('=', i)) {
                    i++;
                    // skip spaces
                    while (i < revokeAll.length() && revokeAll.charAt(i) == ' ') {
                        i++;
                    }
                    // xxxx decimal serial number?
                    String legalDigits = "0123456789";
                    int j = i;

                    // find legal digits
                    while (j < revokeAll.length() && legalDigits.indexOf(revokeAll.charAt(j)) != -1) {
                        j++;
                    }
                    if (j > i) {
                        certSerialNumbers.add(new CertId(revokeAll.substring(i, j)));
                    }
                }
            }

            if (reqIdStr != null && reqIdStr.length() > 0 && certSerialNumbers.size() > 0) {
                IRequest certReq = mRequestQueue.findRequest(new RequestId(reqIdStr));
                X509CertImpl[] certs = certReq.getExtDataInCertArray(IRequest.OLD_CERTS);
                boolean authorized = false;

                for (int i = 0; i < certs.length; i++) {
                    boolean addToList = false;

                    for (CertId certSerialNumber : certSerialNumbers) {
                        //xxxxx serial number in decimal?
                        if (certs[i].getSerialNumber().equals(certSerialNumber.toBigInteger())
                                && eeSubjectDN != null
                                && eeSubjectDN.equals(certs[i].getSubjectDN().toString())) {
                            addToList = true;
                            break;
                        }
                    }

                    if (eeSerialNumber != null && eeSerialNumber.equals(certs[i].getSerialNumber())) {
                        authorized = true;
                    }

                    if (addToList) {
                        IArgBlock rarg = CMS.createArgBlock();

                        rarg.addStringValue("serialNumber", certs[i].getSerialNumber().toString(16));

                        processor.addCertificateToRevoke(certs[i]);

                        rarg.addStringValue("error", null);
                        argSet.addRepeatRecord(rarg);
                    }
                }

                if (!authorized) {
                    processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REQ_AUTH_REVOKED_CERT"));
                    throw new ECMSGWException(CMS.getLogMessage("CMSGW_UNAUTHORIZED"));
                }

            } else {
                String b64eCert = req.getParameter("b64eCertificate");

                if (b64eCert != null) {
                    //  BASE64Decoder decoder = new BASE64Decoder();
                    //  byte[] certBytes = decoder.decodeBuffer(b64eCert);
                    byte[] certBytes = Utils.base64decode(b64eCert);
                    X509CertImpl cert = new X509CertImpl(certBytes);
                    IArgBlock rarg = CMS.createArgBlock();

                    rarg.addStringValue("serialNumber", cert.getSerialNumber().toString(16));

                    processor.addCertificateToRevoke(cert);

                    rarg.addStringValue("error", null);
                    argSet.addRepeatRecord(rarg);
                }
            }
        }

        int count = processor.getCertificates().size();
        if (count == 0) {
            processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_REV_CERTS_ZERO"));
            throw new ECMSGWException(CMS.getLogMessage("CMSGW_REVOCATION_ERROR_CERT_NOT_FOUND"));
        }

        header.addIntegerValue("totalRecordCount", count);

        processor.createRevocationRequest();

        processor.auditChangeRequest(ILogger.SUCCESS);

    } catch (ForbiddenException e) {
        throw new EAuthzException(CMS.getUserMessage(locale, "CMS_AUTHORIZATION_ERROR"));

    } catch (CertificateException e) {
        processor.log(ILogger.LL_FAILURE, "Error " + e);
        processor.auditChangeRequest(ILogger.FAILURE);

        // TODO: throw exception or return?
        // throw new EBaseException(e.getMessage());
        return;

    } catch (EBaseException e) {
        processor.log(ILogger.LL_FAILURE, "Error " + e);
        processor.auditChangeRequest(ILogger.FAILURE);

        throw e;

    } catch (IOException e) {
        processor.log(ILogger.LL_FAILURE,
                CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED_1", e.toString()));
        processor.auditChangeRequest(ILogger.FAILURE);

        throw new ECMSGWException(CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED"));
    }

    // change audit processing from "REQUEST" to "REQUEST_PROCESSED"
    // to distinguish which type of signed audit log message to save
    // as a failure outcome in case an exception occurs

    try {
        processor.processRevocationRequest();
        IRequest revReq = processor.getRequest();

        // retrieve the request status
        RequestStatus status = revReq.getRequestStatus();
        processor.setRequestStatus(status);

        String type = revReq.getRequestType();

        // The SVC_PENDING check has been added for the Cloned CA request
        // that is meant for the Master CA. From Clone's point of view
        // the request is complete

        if (status == RequestStatus.COMPLETE
                || status == RequestStatus.SVC_PENDING && type.equals(IRequest.CLA_CERT4CRL_REQUEST)) {

            header.addStringValue("revoked", "yes");

            Integer updateCRLResult = revReq.getExtDataInInteger(IRequest.CRL_UPDATE_STATUS);

            if (updateCRLResult != null) {
                header.addStringValue("updateCRL", "yes");
                if (updateCRLResult.equals(IRequest.RES_SUCCESS)) {
                    header.addStringValue("updateCRLSuccess", "yes");
                } else {
                    header.addStringValue("updateCRLSuccess", "no");
                    String crlError = revReq.getExtDataInString(IRequest.CRL_UPDATE_ERROR);

                    if (crlError != null)
                        header.addStringValue("updateCRLError", crlError);
                }

                // let known crl publishing status too.
                Integer publishCRLResult = revReq.getExtDataInInteger(IRequest.CRL_PUBLISH_STATUS);

                if (publishCRLResult != null) {
                    if (publishCRLResult.equals(IRequest.RES_SUCCESS)) {
                        header.addStringValue("publishCRLSuccess", "yes");
                    } else {
                        header.addStringValue("publishCRLSuccess", "no");
                        String publError = revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);

                        if (publError != null)
                            header.addStringValue("publishCRLError", publError);
                    }
                }
            }

            if (mAuthority instanceof ICertificateAuthority) {
                // let known update and publish status of all crls.
                Enumeration<ICRLIssuingPoint> otherCRLs = ((ICertificateAuthority) mAuthority)
                        .getCRLIssuingPoints();

                while (otherCRLs.hasMoreElements()) {
                    ICRLIssuingPoint crl = otherCRLs.nextElement();
                    String crlId = crl.getId();

                    if (crlId.equals(ICertificateAuthority.PROP_MASTER_CRL))
                        continue;

                    String updateStatusStr = crl.getCrlUpdateStatusStr();
                    Integer updateResult = revReq.getExtDataInInteger(updateStatusStr);

                    if (updateResult != null) {
                        if (updateResult.equals(IRequest.RES_SUCCESS)) {
                            CMS.debug("DoRevoke: "
                                    + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER", updateStatusStr));
                            header.addStringValue(updateStatusStr, "yes");

                        } else {
                            String updateErrorStr = crl.getCrlUpdateErrorStr();

                            CMS.debug("DoRevoke: "
                                    + CMS.getLogMessage("ADMIN_SRVLT_ADDING_HEADER_NO", updateStatusStr));
                            header.addStringValue(updateStatusStr, "no");
                            String error = revReq.getExtDataInString(updateErrorStr);

                            if (error != null)
                                header.addStringValue(updateErrorStr, error);
                        }

                        String publishStatusStr = crl.getCrlPublishStatusStr();
                        Integer publishResult = revReq.getExtDataInInteger(publishStatusStr);

                        if (publishResult == null)
                            continue;

                        if (publishResult.equals(IRequest.RES_SUCCESS)) {
                            header.addStringValue(publishStatusStr, "yes");

                        } else {
                            String publishErrorStr = crl.getCrlPublishErrorStr();
                            header.addStringValue(publishStatusStr, "no");
                            String error = revReq.getExtDataInString(publishErrorStr);

                            if (error != null)
                                header.addStringValue(publishErrorStr, error);
                        }
                    }
                }
            }

            if (mPublisherProcessor != null && mPublisherProcessor.ldapEnabled()) {
                header.addStringValue("dirEnabled", "yes");
                Integer[] ldapPublishStatus = revReq.getExtDataInIntegerArray("ldapPublishStatus");
                int certsToUpdate = 0;
                int certsUpdated = 0;

                if (ldapPublishStatus != null) {
                    certsToUpdate = ldapPublishStatus.length;
                    for (int i = 0; i < certsToUpdate; i++) {
                        if (ldapPublishStatus[i] == IRequest.RES_SUCCESS) {
                            certsUpdated++;
                        }
                    }
                }

                header.addIntegerValue("certsUpdated", certsUpdated);
                header.addIntegerValue("certsToUpdate", certsToUpdate);

                // add crl publishing status.
                String publError = revReq.getExtDataInString(IRequest.CRL_PUBLISH_ERROR);

                if (publError != null) {
                    header.addStringValue("crlPublishError", publError);
                }

            } else {
                header.addStringValue("dirEnabled", "no");
            }

            header.addStringValue("error", null);

        } else {
            if (status == RequestStatus.PENDING || status == RequestStatus.REJECTED) {
                header.addStringValue("revoked", status.toString());
            } else {
                header.addStringValue("revoked", "no");
            }

            Vector<String> errors = revReq.getExtDataInStringVector(IRequest.ERRORS);
            if (errors != null) {
                StringBuilder errInfo = new StringBuilder();
                for (int i = 0; i < errors.size(); i++) {
                    errInfo.append(errors.elementAt(i));
                    errInfo.append("\n");
                }
                header.addStringValue("error", errInfo.toString());

            } else if (status == RequestStatus.PENDING) {
                header.addStringValue("error", "Request Pending");

            } else {
                header.addStringValue("error", null);
            }
        }

        processor.auditChangeRequestProcessed(ILogger.SUCCESS);

    } catch (EBaseException e) {
        processor.log(ILogger.LL_FAILURE, "Error " + e);
        processor.auditChangeRequestProcessed(ILogger.FAILURE);

        throw e;
    }
}

From source file:com.github.maven_nar.cpptasks.compiler.CommandLineCompiler.java

@Override
protected CompilerConfiguration createConfiguration(final CCTask task, final LinkType linkType,
        final ProcessorDef[] baseDefs, final CompilerDef specificDef, final TargetDef targetPlatform,
        final VersionInfo versionInfo) {

    this.prefix = specificDef.getCompilerPrefix();
    this.objDir = task.getObjdir();
    final Vector<String> args = new Vector<>();
    final CompilerDef[] defaultProviders = new CompilerDef[baseDefs.length + 1];
    for (int i = 0; i < baseDefs.length; i++) {
        defaultProviders[i + 1] = (CompilerDef) baseDefs[i];
    }/*w  w  w. ja  v a  2s  .c om*/
    defaultProviders[0] = specificDef;
    final Vector<CommandLineArgument> cmdArgs = new Vector<>();

    //
    // add command line arguments inherited from <cc> element
    // any "extends" and finally the specific CompilerDef
    CommandLineArgument[] commandArgs;
    for (int i = defaultProviders.length - 1; i >= 0; i--) {
        commandArgs = defaultProviders[i].getActiveProcessorArgs();
        for (final CommandLineArgument commandArg : commandArgs) {
            if (commandArg.getLocation() == 0) {
                String arg = commandArg.getValue();
                if (isWindows() && arg.matches(".*[ \"].*")) {
                    // Work around inconsistent quoting by Ant
                    arg = "\"" + arg.replaceAll("[\\\\\"]", "\\\\$0") + "\"";
                }
                args.addElement(arg);
            } else {
                cmdArgs.addElement(commandArg);
            }
        }
    }
    final Vector<ProcessorParam> params = new Vector<>();
    //
    // add command line arguments inherited from <cc> element
    // any "extends" and finally the specific CompilerDef
    ProcessorParam[] paramArray;
    for (int i = defaultProviders.length - 1; i >= 0; i--) {
        paramArray = defaultProviders[i].getActiveProcessorParams();
        Collections.addAll(params, paramArray);
    }
    paramArray = params.toArray(new ProcessorParam[params.size()]);

    if (specificDef.isClearDefaultOptions() == false) {
        final boolean multithreaded = specificDef.getMultithreaded(defaultProviders, 1);
        final boolean debug = specificDef.getDebug(baseDefs, 0);
        final boolean exceptions = specificDef.getExceptions(defaultProviders, 1);
        final Boolean rtti = specificDef.getRtti(defaultProviders, 1);
        final OptimizationEnum optimization = specificDef.getOptimization(defaultProviders, 1);
        this.addImpliedArgs(args, debug, multithreaded, exceptions, linkType, rtti, optimization);
    }

    //
    // add all appropriate defines and undefines
    //
    buildDefineArguments(defaultProviders, args);
    final int warnings = specificDef.getWarnings(defaultProviders, 0);
    addWarningSwitch(args, warnings);
    Enumeration<CommandLineArgument> argEnum = cmdArgs.elements();
    int endCount = 0;
    while (argEnum.hasMoreElements()) {
        final CommandLineArgument arg = argEnum.nextElement();
        switch (arg.getLocation()) {
        case 1:
            args.addElement(arg.getValue());
            break;
        case 2:
            endCount++;
            break;
        }
    }
    final String[] endArgs = new String[endCount];
    argEnum = cmdArgs.elements();
    int index = 0;
    while (argEnum.hasMoreElements()) {
        final CommandLineArgument arg = argEnum.nextElement();
        if (arg.getLocation() == 2) {
            endArgs[index++] = arg.getValue();
        }
    }
    //
    // Want to have distinct set of arguments with relative
    // path names for includes that are used to build
    // the configuration identifier
    //
    final Vector<String> relativeArgs = (Vector) args.clone();
    //
    // add all active include and sysincludes
    //
    final StringBuffer includePathIdentifier = new StringBuffer();
    final File baseDir = specificDef.getProject().getBaseDir();
    String baseDirPath;
    try {
        baseDirPath = baseDir.getCanonicalPath();
    } catch (final IOException ex) {
        baseDirPath = baseDir.toString();
    }
    final Vector<String> includePath = new Vector<>();
    final Vector<String> sysIncludePath = new Vector<>();
    for (int i = defaultProviders.length - 1; i >= 0; i--) {
        String[] incPath = defaultProviders[i].getActiveIncludePaths();
        for (final String element : incPath) {
            includePath.addElement(element);
        }
        incPath = defaultProviders[i].getActiveSysIncludePaths();
        for (final String element : incPath) {
            sysIncludePath.addElement(element);
        }
    }
    final File[] incPath = new File[includePath.size()];
    for (int i = 0; i < includePath.size(); i++) {
        incPath[i] = new File(includePath.elementAt(i));
    }
    final File[] sysIncPath = new File[sysIncludePath.size()];
    for (int i = 0; i < sysIncludePath.size(); i++) {
        sysIncPath[i] = new File(sysIncludePath.elementAt(i));
    }
    addIncludes(baseDirPath, incPath, args, relativeArgs, includePathIdentifier, false);
    addIncludes(baseDirPath, sysIncPath, args, null, null, true);
    final StringBuffer buf = new StringBuffer(getIdentifier());
    for (int i = 0; i < relativeArgs.size(); i++) {
        buf.append(' ');
        buf.append(relativeArgs.elementAt(i));
    }
    for (final String endArg : endArgs) {
        buf.append(' ');
        buf.append(endArg);
    }
    final String configId = buf.toString();
    final String[] argArray = new String[args.size()];
    args.copyInto(argArray);
    final boolean rebuild = specificDef.getRebuild(baseDefs, 0);
    final File[] envIncludePath = getEnvironmentIncludePath();
    final String path = specificDef.getToolPath();

    CommandLineCompiler compiler = this;
    Environment environment = specificDef.getEnv();
    if (environment == null) {
        for (final ProcessorDef baseDef : baseDefs) {
            environment = baseDef.getEnv();
            if (environment != null) {
                compiler = (CommandLineCompiler) compiler.changeEnvironment(baseDef.isNewEnvironment(),
                        environment);
            }
        }
    } else {
        compiler = (CommandLineCompiler) compiler.changeEnvironment(specificDef.isNewEnvironment(),
                environment);
    }
    return new CommandLineCompilerConfiguration(compiler, configId, incPath, sysIncPath, envIncludePath,
            includePathIdentifier.toString(), argArray, paramArray, rebuild, endArgs, path,
            specificDef.getCcache());
}

From source file:com.zd.vpn.fragments.AboutFragment.java

private void createPlayBuyOptions(ArrayList<String> ownedSkus, ArrayList<String> responseList) {
    try {/*from   w  w w  .j  av a2  s .  c o m*/
        Vector<Pair<String, String>> gdonation = new Vector<Pair<String, String>>();

        gdonation.add(new Pair<String, String>(getString(R.string.donatePlayStore), null));
        HashMap<String, SkuResponse> responseMap = new HashMap<String, SkuResponse>();
        for (String thisResponse : responseList) {
            JSONObject object = new JSONObject(thisResponse);
            responseMap.put(object.getString("productId"),
                    new SkuResponse(object.getString("price"), object.getString("title")));

        }
        for (String sku : donationSkus)
            if (responseMap.containsKey(sku))
                gdonation.add(
                        getSkuTitle(sku, responseMap.get(sku).title, responseMap.get(sku).price, ownedSkus));

        String gmsTextString = "";
        for (int i = 0; i < gdonation.size(); i++) {
            if (i == 1)
                gmsTextString += "  ";
            else if (i > 1)
                gmsTextString += ", ";
            gmsTextString += gdonation.elementAt(i).first;
        }
        SpannableString gmsText = new SpannableString(gmsTextString);

        int lStart = 0;
        int lEnd = 0;
        for (Pair<String, String> item : gdonation) {
            lEnd = lStart + item.first.length();
            if (item.second != null) {
                final String mSku = item.second;
                ClickableSpan cspan = new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        triggerBuy(mSku);
                    }
                };
                gmsText.setSpan(cspan, lStart, lEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            lStart = lEnd + 2; // Account for ", " between items
        }

        if (gmsTextView != null) {
            gmsTextView.setText(gmsText);
            gmsTextView.setMovementMethod(LinkMovementMethod.getInstance());
            gmsTextView.setVisibility(View.VISIBLE);
        }

    } catch (JSONException e) {
        VpnStatus.logException("Parsing Play Store IAP", e);
    }

}

From source file:GraficasForm.java

private void graficarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_graficarButtonActionPerformed
    Vector<String> keys = new Vector<String>();
    Vector<Integer> indexes = new Vector<Integer>();
    Boolean candSelected = false;
    if (candidatosRadio.isSelected()) {
        candSelected = true;//w  ww  .  ja v  a2  s  .  c  o m
        indexes = getCandidatosSelected();
    } else {
        indexes = getPartidosSelected();
    }
    if (indexes.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Escoja al menos un dato para graficar.");
        return;
    } else {
        if (candSelected) {
            for (int j = 0; j < indexes.size(); ++j) {
                keys.add(candidatosKeys[indexes.elementAt(j)]);
            }
        } else {
            for (int j = 0; j < indexes.size(); ++j) {
                keys.add(partidosKeys[indexes.elementAt(j)]);
            }
        }
    }

    panelGrafica.removeAll();
    XYLineChartExample chart = new XYLineChartExample();
    panelGrafica.add(chart.createChartPanel(keys), BorderLayout.CENTER);
    panelGrafica.revalidate();
    panelGrafica.repaint();

}

From source file:com.fluidops.iwb.server.SparqlServlet.java

/**
 * Handle legacy aggregation of tuple queries. Prints the aggregated result as CSV!
 * /*from www  .j a  va2 s  .c o m*/
 * Condition: tuple query + parameter "input" and "output" are set
 * 
 * Also deals with (optional) parameter "datasets"
 * 
 * This method MUST return true, if SPARQL processing shall continue. If legacy code
 * is applied, results may be written to the outputstream directly (and false is returned)
 *  
 * @param res
 * @param req
 * @return
 *          true if the standard SPARQL processing should continue, false otherwise
 * @throws QueryEvaluationException 
 * @throws IOException 
 */
private boolean handleAggregationLegacy(TupleQueryResult res, HttpServletRequest req, ReadDataManager queryDM,
        OutputStream outputStream) throws QueryEvaluationException, IOException {

    String input = req.getParameter("input");
    String output = req.getParameter("output");

    // check the condition
    if (StringUtil.isNullOrEmpty(input) || StringUtil.isNullOrEmpty(output))
        return true;

    String datasets = req.getParameter("datasets");
    String aggregation = req.getParameter("aggregation");

    String[] outputs = output.split(",");

    AggregationType aggType = AggregationType.NONE; // DEFAULT
    if (aggregation != null) {
        if (aggregation.equals("COUNT"))
            aggType = AggregationType.COUNT;
        else if (aggregation.equals("SUM"))
            aggType = AggregationType.SUM;
        else if (aggregation.equals("NONE"))
            aggType = AggregationType.NONE;
        else if (aggregation.equals("AVG"))
            aggType = AggregationType.AVG;
    }

    Map<Value, Vector<Number>> valueMap;
    if (datasets == null) {
        valueMap = queryDM.aggregateQueryResult(res, aggType, input, outputs);
    } else {
        // special handling: we must first group by the values
        // of the datasets parameter before aggregating; this
        // processing scheme supports only a single output variable
        String[] splittedDatasets = datasets.split(",");
        valueMap = queryDM.aggregateQueryResultWrtDatasets(res, aggType, input, outputs[0], splittedDatasets);
    }

    // We need to sort the input again, as the order gets lost when accessing the valueMap
    Set<Value> keySet = valueMap.keySet();
    SortedSet<Value> sortedSet = new TreeSet<Value>(new ValueComparator());
    sortedSet.addAll(keySet);

    // need to write at least one space, as empty results cause errors in charts
    if (sortedSet.isEmpty())
        outputStream.write(" ".getBytes("UTF-8"));

    for (Value val : sortedSet) {
        Vector<Number> vals = valueMap.get(val);
        outputStream.write(val.stringValue().getBytes("UTF-8"));
        for (int i = 0; i < vals.size(); i++) {
            Number n = vals.elementAt(i);
            if (n == null || n.toString() == null)
                outputStream.write(";".getBytes("UTF-8"));
            else
                outputStream.write((";" + n.toString()).getBytes("UTF-8"));
        }
        outputStream.write("\n".getBytes("UTF-8"));
    }

    return false;
}

From source file:keel.GraphInterKeel.datacf.visualizeData.VisualizePanelAttribute.java

private void infoAttribute() {
    this.enabledTable(true);
    // Extended info about selected attribute
    if (((VisualizePanel) this.getParent().getParent()).getData()
            .getAttributeTypeIndex(this.tableInfojTable.getSelectedRow()).equals("nominal")) {
        this.valuesjScrollPane.setEnabled(true);
        this.valuesjScrollPane.setVisible(true);
        this.valuesjTextPane.setEnabled(true);
        this.valuesjTextPane.setVisible(true);

        Vector r = ((VisualizePanel) this.getParent().getParent()).getData()
                .getRangesVar(((VisualizePanel) this.getParent().getParent()).getData()
                        .getAttributeIndex(this.tableInfojTable.getSelectedRow()));

        this.valuesjTextPane.setText("");
        this.valueAveragejLabel.setText("");
        this.valueVariancejLabel.setText("");
        this.valueRankjLabelIzdo.setText("  ");
        this.valueRankjLabelDcho.setText("  ");

        String cadena = new String();
        for (int i = 0; i < r.size(); i++) {
            if (i == 0) {
                cadena = r.elementAt(i).toString() + "";
                this.valuesjTextPane.setText(cadena);
            } else {
                cadena = this.valuesjTextPane.getText() + "\n" + r.elementAt(i).toString();
            }//from  w ww.  ja  v a  2s .  co m
            this.valuesjTextPane.setText(cadena);
        }
        boolean legend = false;
        // Draw bar chart
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        try {
            for (int i = 0; i < ((VisualizePanel) this.getParent().getParent()).getData().getNData(); i++) {
                String column = ((VisualizePanel) this.getParent().getParent()).getData().getDataIndex(i,
                        this.tableInfojTable.getSelectedRow());
                String row = "";
                if (((VisualizePanel) this.getParent().getParent()).getOutAttribute() != -1
                        && this.tableInfojTable
                                .getSelectedRow() != ((VisualizePanel) this.getParent().getParent())
                                        .getOutAttribute()) {
                    row = "Class " + ((VisualizePanel) this.getParent().getParent()).getData().getDataIndex(i,
                            ((VisualizePanel) this.getParent().getParent()).getOutAttribute());
                    legend = true;
                }

                if (column != null) {
                    if (dataset.getRowIndex(row) == -1 || ((dataset.getColumnIndex(column) == -1))) {
                        dataset.addValue(1.0, row, column);
                    } else {
                        dataset.incrementValue(1.0, row, column);
                    }
                }
            }
        } catch (ArrayIndexOutOfBoundsException exp) {
            JOptionPane.showMessageDialog(this,
                    "The data set contains some errors. This attribute can not be visualized", "Error", 2);
        }

        this.chart = ChartFactory.createBarChart3D("", "", "", dataset, PlotOrientation.VERTICAL, legend, false,
                false);

        this.chart.setBackgroundPaint(new Color(0xFFFFFF));
        //BufferedImage image = this.chart.createBufferedImage(210, 140);
        BufferedImage image = this.chart.createBufferedImage(400, 240);
        this.imagejLabel.setIcon(new ImageIcon(image));
        this.clickToExpandjLabel.setVisible(true);
    } else {
        this.valuesjScrollPane.setEnabled(false);
        this.valuesjScrollPane.setVisible(false);
        this.valuesjTextPane.setEnabled(false);
        this.valuesjTextPane.setVisible(false);
        Vector r = ((VisualizePanel) this.getParent().getParent()).getData()
                .getRangesVar(((VisualizePanel) this.getParent().getParent()).getData()
                        .getAttributeIndex(this.tableInfojTable.getSelectedRow()));
        this.valueRankjLabelIzdo.setText(r.elementAt(0).toString());
        this.valueRankjLabelDcho.setText(r.elementAt(1).toString());

        // Average
        double m = 0.0;
        for (int i = 0; i < ((VisualizePanel) this.getParent().getParent()).getData().getNData(); i++) {
            String valor = ((VisualizePanel) this.getParent().getParent()).getData().getDataIndex(i,
                    this.tableInfojTable.getSelectedRow());
            if (valor != null) {
                m += Double.valueOf(valor).doubleValue();
            }
        }
        m = m / ((VisualizePanel) this.getParent().getParent()).getData().getNData();
        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(3);
        this.valueAveragejLabel.setText(df.format(m));
        // Variance
        double v = 0.0;
        for (int i = 0; i < ((VisualizePanel) this.getParent().getParent()).getData().getNData(); i++) {
            String valor = ((VisualizePanel) this.getParent().getParent()).getData().getDataIndex(i,
                    this.tableInfojTable.getSelectedRow());
            if (valor != null) {
                v += Math.pow(Double.valueOf(valor).doubleValue() - m, 2);
            }
        }
        v = v / (((VisualizePanel) this.getParent().getParent()).getData().getNData() - 1);
        this.valueVariancejLabel.setText(df.format(v));

        // Draw scatter plot
        XYSeriesCollection juegoDatos = new XYSeriesCollection();
        boolean legend = false;
        if (((VisualizePanel) this.getParent().getParent()).getOutAttribute() != -1) {
            Vector outputRang = ((VisualizePanel) this.getParent().getParent()).getData()
                    .getRange(((VisualizePanel) this.getParent().getParent()).getOutAttribute());
            XYSeries series[] = new XYSeries[outputRang.size()];
            for (int i = 0; i < outputRang.size(); i++) {
                series[i] = new XYSeries("Class " + outputRang.elementAt(i));
                juegoDatos.addSeries(series[i]);
            }
            for (int i = 0; i < ((VisualizePanel) this.getParent().getParent()).getData().getNData(); i++) {
                int clase = outputRang.indexOf(((VisualizePanel) this.getParent().getParent()).getData()
                        .getDataIndex(i, ((VisualizePanel) this.getParent().getParent()).getOutAttribute()));
                String valor = ((VisualizePanel) this.getParent().getParent()).getData().getDataIndex(i,
                        this.tableInfojTable.getSelectedRow());
                if (valor != null) {
                    series[clase].add(Double.parseDouble(Integer.toString(i)),
                            Double.valueOf(valor).doubleValue());
                }
            }
            legend = true;
        } else {
            XYSeries series = new XYSeries("Regresin");
            juegoDatos.addSeries(series);
            for (int i = 0; i < ((VisualizePanel) this.getParent().getParent()).getData().getNData(); i++) {
                String valor = ((VisualizePanel) this.getParent().getParent()).getData().getDataIndex(i,
                        this.tableInfojTable.getSelectedRow());
                if (valor != null) {
                    series.add(Double.parseDouble(Integer.toString(i)), Double.valueOf(valor).doubleValue());
                }
            }

        }

        chart = ChartFactory.createScatterPlot("", "", "", juegoDatos, PlotOrientation.VERTICAL, legend, false,
                false);
        chart.setBackgroundPaint(new Color(0xFFFFFF));
        //BufferedImage image = chart.createBufferedImage(210, 140);
        BufferedImage image = chart.createBufferedImage(400, 240);
        this.imagejLabel.setIcon(new ImageIcon(image));
        this.clickToExpandjLabel.setVisible(true);
    }
}

From source file:je3.rmi.MudClient.java

 /** 
  * This convenience method is used in several places in the
  * runMud() method above.  It displays the name and description of
  * the current place (including the name of the mud the place is in), 
  * and also displays the list of things, people, and exits in
  * the current place.//w  ww .  j  a  va2 s.c o  m
  **/
 public static void look(RemoteMudPlace p) 
throws RemoteException, MudException
 {
     String mudname = p.getServer().getMudName(); // Mud name
     String placename = p.getPlaceName();         // Place name
     String description = p.getDescription();     // Place description
     Vector things = p.getThings();               // List of things here
     Vector names = p.getNames();                 // List of people here
     Vector exits = p.getExits();                 // List of exits from here

     // Print it all out
     System.out.println("You are in: " + placename +
         " of the Mud: " + mudname);
     System.out.println(description);
     System.out.print("Things here: ");
     for(int i = 0; i < things.size(); i++) {      // Display list of things
         if (i > 0) System.out.print(", ");
         System.out.print(things.elementAt(i));
     }
     System.out.print("\nPeople here: ");
     for(int i = 0; i < names.size(); i++) {       // Display list of people
         if (i > 0) System.out.print(", ");
         System.out.print(names.elementAt(i));
     }
     System.out.print("\nExits are: ");
     for(int i = 0; i < exits.size(); i++) {       // Display list of exits
         if (i > 0) System.out.print(", ");
         System.out.print(exits.elementAt(i));
     }
     System.out.println();                         // Blank line
     System.out.flush();                           // Make it appear now!
 }

From source file:Maze.java

/**
 * This method randomly generates the maze.
 *///www . ja v a2  s . co m
private void createMaze() {
    // create an initial framework of black squares.
    for (int i = 1; i < mySquares.length - 1; i++) {
        for (int j = 1; j < mySquares[i].length - 1; j++) {
            if ((i + j) % 2 == 1) {
                mySquares[i][j] = 0;
            }
        }
    }
    // initialize the squares that can be either black or white 
    // depending on the maze.
    // first we set the value to 3 which means undecided.
    for (int i = 1; i < mySquares.length - 1; i += 2) {
        for (int j = 1; j < mySquares[i].length - 1; j += 2) {
            mySquares[i][j] = 3;
        }
    }
    // Then those squares that can be selected to be open 
    // (white) paths are given the value of 2.  
    // We randomly select the square where the tree of maze 
    // paths will begin.  The maze is generated starting from 
    // this initial square and branches out from here in all 
    // directions to fill the maze grid.  
    Vector possibleSquares = new Vector(mySquares.length * mySquares[0].length);
    int[] startSquare = new int[2];
    startSquare[0] = getRandomInt(mySquares.length / 2) * 2 + 1;
    startSquare[1] = getRandomInt(mySquares[0].length / 2) * 2 + 1;
    mySquares[startSquare[0]][startSquare[1]] = 2;
    possibleSquares.addElement(startSquare);
    // Here we loop to select squares one by one to append to 
    // the maze pathway tree.
    while (possibleSquares.size() > 0) {
        // the next square to be joined on is selected randomly.
        int chosenIndex = getRandomInt(possibleSquares.size());
        int[] chosenSquare = (int[]) possibleSquares.elementAt(chosenIndex);
        // we set the chosen square to white and then 
        // remove it from the list of possibleSquares (i.e. squares 
        // that can possibly be added to the maze), and we link 
        // the new square to the maze.
        mySquares[chosenSquare[0]][chosenSquare[1]] = 1;
        possibleSquares.removeElementAt(chosenIndex);
        link(chosenSquare, possibleSquares);
    }
    // now that the maze has been completely generated, we 
    // throw away the objects that were created during the 
    // maze creation algorithm and reclaim the memory.
    possibleSquares = null;
    System.gc();
}