Example usage for java.lang Long toHexString

List of usage examples for java.lang Long toHexString

Introduction

In this page you can find the example usage for java.lang Long toHexString.

Prototype

public static String toHexString(long i) 

Source Link

Document

Returns a string representation of the long argument as an unsigned integer in base 16.

Usage

From source file:biz.wolschon.fileformats.gnucash.jwsdpimpl.GnucashFileWritingImpl.java

/**
 * create a GUID for a new element./* w w  w .  ja  v a  2s .  c o m*/
 * (guids are globally unique and not tied
 *  to a specific kind of entity)
 * @return the new gnucash-guid
 */
protected String createGUID() {

    int len = "74e492edf60d6a28b6c1d01cc410c058".length();

    StringBuffer sb = new StringBuffer(Long.toHexString(System.currentTimeMillis()));

    while (sb.length() < len) {
        sb.append(Integer.toHexString((int) (Math.random() * HEX)).charAt(0));
    }

    return sb.toString();
}

From source file:org.apache.flink.table.runtime.functions.SqlFunctionUtils.java

/**
 * Returns the hex string of a long argument.
 *//*from   ww w  .j a v a2 s  . c o  m*/
public static String hex(long x) {
    return Long.toHexString(x).toUpperCase();
}

From source file:org.apache.hadoop.gateway.GatewayServer.java

private String calculateDeploymentName(Topology topology) {
    String name = topology.getName() + ".war." + Long.toHexString(topology.getTimestamp());
    return name;
}

From source file:org.apache.hyracks.storage.am.btree.OrderedIndexTestUtils.java

public static String getRandomString(int length, Random rnd) {
    String s = Long.toHexString(Double.doubleToLongBits(rnd.nextDouble()));
    StringBuilder strBuilder = new StringBuilder();
    for (int i = 0; i < s.length() && i < length; i++) {
        strBuilder.append(s.charAt(Math.abs(rnd.nextInt()) % s.length()));
    }//ww  w .j  a  va  2  s  .  c o  m
    return strBuilder.toString();
}

From source file:com.gst.organisation.teller.service.TellerWritePlatformServiceJpaImpl.java

private CommandProcessingResult doTransactionForCashier(final Long cashierId, final CashierTxnType txnType,
        JsonCommand command) {//from w w w  .  j  a va2 s .c o m
    try {
        final AppUser currentUser = this.context.authenticatedUser();

        final Cashier cashier = this.cashierRepository.findOne(cashierId);
        if (cashier == null) {
            throw new CashierNotFoundException(cashierId);
        }

        this.fromApiJsonDeserializer.validateForCashTxnForCashier(command.json());

        final String entityType = command.stringValueOfParameterNamed("entityType");
        final Long entityId = command.longValueOfParameterNamed("entityId");
        if (entityType != null) {
            if (entityType.equals("loan account")) {
                // TODO : Check if loan account exists
                // LoanAccount loan = null;
                // if (loan == null) { throw new
                // LoanAccountFoundException(entityId); }
            } else if (entityType.equals("savings account")) {
                // TODO : Check if loan account exists
                // SavingsAccount savingsaccount = null;
                // if (savingsaccount == null) { throw new
                // SavingsAccountNotFoundException(entityId); }

            }
            if (entityType.equals("client")) {
                // TODO: Check if client exists
                // Client client = null;
                // if (client == null) { throw new
                // ClientNotFoundException(entityId); }
            } else {
                // TODO : Invalid type handling
            }
        }

        final CashierTransaction cashierTxn = CashierTransaction.fromJson(cashier, command);
        cashierTxn.setTxnType(txnType.getId());

        this.cashierTxnRepository.save(cashierTxn);

        // Pass the journal entries
        FinancialActivityAccount mainVaultFinancialActivityAccount = this.financialActivityAccountRepositoryWrapper
                .findByFinancialActivityTypeWithNotFoundDetection(
                        FINANCIAL_ACTIVITY.CASH_AT_MAINVAULT.getValue());
        FinancialActivityAccount tellerCashFinancialActivityAccount = this.financialActivityAccountRepositoryWrapper
                .findByFinancialActivityTypeWithNotFoundDetection(FINANCIAL_ACTIVITY.CASH_AT_TELLER.getValue());
        GLAccount creditAccount = null;
        GLAccount debitAccount = null;
        if (txnType.equals(CashierTxnType.ALLOCATE)) {
            debitAccount = tellerCashFinancialActivityAccount.getGlAccount();
            creditAccount = mainVaultFinancialActivityAccount.getGlAccount();
        } else if (txnType.equals(CashierTxnType.SETTLE)) {
            debitAccount = mainVaultFinancialActivityAccount.getGlAccount();
            creditAccount = tellerCashFinancialActivityAccount.getGlAccount();
        }

        final Office cashierOffice = cashier.getTeller().getOffice();

        final Long time = System.currentTimeMillis();
        final String uniqueVal = String.valueOf(time) + currentUser.getId() + cashierOffice.getId();
        final String transactionId = Long.toHexString(Long.parseLong(uniqueVal));
        ClientTransaction clientTransaction = null;
        final Long shareTransactionId = null;

        final JournalEntry debitJournalEntry = JournalEntry.createNew(cashierOffice, null, // payment
                // detail
                debitAccount, "USD", // FIXME: Take currency code from the
                // transaction
                transactionId, false, // manual entry
                cashierTxn.getTxnDate(), JournalEntryType.DEBIT, cashierTxn.getTxnAmount(),
                cashierTxn.getTxnNote(), // Description
                null, null, null, // entity Type, entityId, reference number
                null, null, clientTransaction, shareTransactionId); // Loan and Savings Txn

        final JournalEntry creditJournalEntry = JournalEntry.createNew(cashierOffice, null, // payment
                // detail
                creditAccount, "USD", // FIXME: Take currency code from the
                // transaction
                transactionId, false, // manual entry
                cashierTxn.getTxnDate(), JournalEntryType.CREDIT, cashierTxn.getTxnAmount(),
                cashierTxn.getTxnNote(), // Description
                null, null, null, // entity Type, entityId, reference number
                null, null, clientTransaction, shareTransactionId); // Loan and Savings Txn

        this.glJournalEntryRepository.saveAndFlush(debitJournalEntry);
        this.glJournalEntryRepository.saveAndFlush(creditJournalEntry);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(cashier.getId()) //
                .withSubEntityId(cashierTxn.getId()) //
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleTellerDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleTellerDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:bookkeepr.jettyhandlers.CandidateHandler.java

public void handle(String path, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException {

    if (path.startsWith("/cand/")) {
        ((Request) request).setHandled(true);

        if (path.startsWith("/cand/lists")) {
            if (request.getMethod().equals("GET")) {
                if (path.startsWith("/cand/lists/from/")) {
                    long targetId = Long.parseLong(path.substring(17), 16);
                    if (dbMan.getType(new DummyIdAble(targetId)) == TypeIdManager
                            .getTypeFromClass(Psrxml.class)) {
                        CandListSelectionRequest req = new CandListSelectionRequest();
                        req.setAcceptPsrxmlIds(new long[] { targetId });
                        XMLWriter.write(response.getOutputStream(), candMan.getCandidateLists(req));

                    } else if (dbMan.getType(new DummyIdAble(targetId)) == TypeIdManager
                            .getTypeFromClass(Processing.class)) {
                        CandListSelectionRequest req = new CandListSelectionRequest();
                        req.setAcceptProcessingIds(new long[] { targetId });
                        XMLWriter.write(response.getOutputStream(), candMan.getCandidateLists(req));

                    } else {
                        response.sendError(400, "Bad GET request for /cand/lists/from/...");
                        return;
                    }/*from   w  w  w . ja v a2 s  . c  o m*/
                } else {
                    CandidateListIndex idx = new CandidateListIndex();
                    List<IdAble> list = dbMan
                            .getAllOfType(TypeIdManager.getTypeFromClass(CandidateListStub.class));
                    for (IdAble stub : list) {
                        idx.addCandidateListStub((CandidateListStub) stub);
                    }
                    OutputStream out = response.getOutputStream();
                    String hdr = request.getHeader("Accept-Encoding");
                    if (hdr != null && hdr.contains("gzip")) {
                        // if the host supports gzip encoding, gzip the output for quick transfer speed.
                        out = new GZIPOutputStream(out);
                        response.setHeader("Content-Encoding", "gzip");
                    }
                    XMLWriter.write(out, idx);
                    out.close();
                    return;
                }
            } else if (request.getMethod().equals("POST")) {
                try {
                    XMLAble xmlable = XMLReader.read(request.getInputStream());
                    if (xmlable instanceof CandListSelectionRequest) {
                        CandListSelectionRequest req = (CandListSelectionRequest) xmlable;
                        OutputStream out = response.getOutputStream();
                        String hdr = request.getHeader("Accept-Encoding");
                        if (hdr != null && hdr.contains("gzip")) {
                            // if the host supports gzip encoding, gzip the output for quick transfer speed.
                            out = new GZIPOutputStream(out);
                            response.setHeader("Content-Encoding", "gzip");
                        }
                        XMLWriter.write(out, candMan.getCandidateLists(req));
                        out.close();
                    } else {
                        response.sendError(400, "Bad POST request for /cand/lists");
                        return;
                    }
                } catch (SAXException ex) {
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, null, ex);
                }

            } else if (request.getMethod().equals("DELETE")) {
                String[] elems = path.substring(1).split("/");
                if (elems.length < 3) {
                    response.sendError(400, "Bad DELETE request for /cand/lists/{clistId}");
                    return;
                }
                final long clistId = Long.parseLong(elems[2], 16);
                CandidateListStub cls = (CandidateListStub) dbMan.getById(clistId);
                if (cls == null) {
                    response.sendError(404, "Bad ClistID requested for deletion (no such candlist)");
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                            "Bad ClistID requested for deletion (no such candlist)");
                    return;
                }
                try {
                    this.candMan.deleteCandidateListAndCands(cls);
                    response.setStatus(202);
                } catch (BookKeeprException ex) {
                    response.sendError(500, "Could not delete candidate list as requested");
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                            "Could not delete candidate list as requested", ex);
                    return;
                }

            } else {
                response.sendError(400, "Bad non-GET/non-POST/non-DELETE request for /cand/lists");
                return;
            }
        } else if (path.startsWith("/cand/viewed")) {
            if (request.getMethod().equals("GET")) {
                ViewedCandidatesIndex idx = new ViewedCandidatesIndex();
                List<IdAble> list = dbMan.getAllOfType(TypeIdManager.getTypeFromClass(ViewedCandidates.class));
                for (IdAble stub : list) {
                    idx.addViewedCandidates((ViewedCandidates) stub);
                }
                OutputStream out = response.getOutputStream();
                String hdr = request.getHeader("Accept-Encoding");
                if (hdr != null && hdr.contains("gzip")) {
                    // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    out = new GZIPOutputStream(out);
                    response.setHeader("Content-Encoding", "gzip");
                }
                XMLWriter.write(out, idx);
                out.close();

                return;
            } else if (request.getMethod().equals("POST")) {
                ViewedCandidates newViewed = null;
                try {
                    XMLAble xmlable = XMLReader.read(request.getInputStream());
                    if (xmlable instanceof ViewedCandidates) {
                        newViewed = (ViewedCandidates) xmlable;
                    } else {
                        response.sendError(400, "Bad Content type in request /cand/viewed");
                        return;
                    }
                } catch (SAXException ex) {
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO,
                            "Bad XML in client request to POST new viewed cands");
                    response.sendError(400, "Bad XML in request /cand/viewed");
                    return;
                }

                IdAble idable = this.dbMan.getById(newViewed.getId());
                if (idable instanceof ViewedCandidates) {
                    newViewed.append(((ViewedCandidates) idable));
                } else {
                    newViewed.setId(0);
                }

                Session session = new Session();
                this.dbMan.add(newViewed, session);
                try {
                    this.dbMan.save(session);
                } catch (BookKeeprException ex) {
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE,
                            "Error saving viewed cands to database", ex);
                    response.sendError(500, "Error saving viewed cands to database");
                    return;
                }
                OutputStream out = response.getOutputStream();
                String hdr = request.getHeader("Accept-Encoding");
                if (hdr != null && hdr.contains("gzip")) {
                    // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    out = new GZIPOutputStream(out);
                    response.setHeader("Content-Encoding", "gzip");
                }
                XMLWriter.write(out, newViewed);
                out.close();

                return;
            } else {
                response.sendError(400, "Bad non-GET/POST request /cand/viewed");
                return;
            }
        } else if (path.startsWith("/cand/psrcat")) {
            if (request.getMethod().equals("GET")) {
                String[] elems = path.substring(1).split("/");
                if (elems.length > 2) {
                    try {
                        long id = Long.parseLong(elems[2], 16);
                        ClassifiedCandidate cand = (ClassifiedCandidate) dbMan.getById(id);
                        String str = cand.getPsrcatEntry().toString();
                        response.setContentType("text/plain");
                        OutputStream out = response.getOutputStream();
                        String hdr = request.getHeader("Accept-Encoding");
                        if (hdr != null && hdr.contains("gzip")) {
                            // if the host supports gzip encoding, gzip the output for quick transfer speed.
                            out = new GZIPOutputStream(out);
                            response.setHeader("Content-Encoding", "gzip");
                        }
                        PrintWriter wr = new PrintWriter(out);
                        wr.write(str);
                        wr.close();
                        out.close();

                    } catch (ClassCastException ex) {
                        Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                "Invalid candidate id passed to /cand/psrcat", ex);
                        response.sendError(400, "Bad id in request for /cand/psrcat");
                    }
                } else {
                    response.sendError(400, "Bad request for /cand/psrcat");
                }
            } else {
                response.sendError(400, "Bad non-GET request for /cand/psrcat");

            }
        } else if (path.startsWith("/cand/classified")) {
            if (request.getMethod().equals("GET")) {
                String[] elems = path.substring(1).split("/");
                ClassifiedCandidateIndex idx = new ClassifiedCandidateIndex();
                List<IdAble> list = dbMan
                        .getAllOfType(TypeIdManager.getTypeFromClass(ClassifiedCandidate.class));
                if (elems.length > 2) {

                    int cl = Integer.parseInt(elems[2]);
                    for (IdAble stub : list) {
                        if (((ClassifiedCandidate) stub).getCandClassInt() == cl) {
                            idx.addClassifiedCandidate((ClassifiedCandidate) stub);
                        }
                    }
                } else {

                    for (IdAble stub : list) {
                        idx.addClassifiedCandidate((ClassifiedCandidate) stub);
                    }
                }
                OutputStream out = response.getOutputStream();
                String hdr = request.getHeader("Accept-Encoding");
                if (hdr != null && hdr.contains("gzip")) {
                    // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    out = new GZIPOutputStream(out);
                    response.setHeader("Content-Encoding", "gzip");
                }
                XMLWriter.write(out, idx);
                out.close();

                return;
            } else if (request.getMethod().equals("POST")) {
                // post a CandidateSelectRequest
                ClassifiedCandidateSelectRequest ccsreq = null;
                try {
                    XMLAble xmlable = XMLReader.read(request.getInputStream());
                    if (xmlable instanceof ClassifiedCandidateSelectRequest) {
                        ccsreq = (ClassifiedCandidateSelectRequest) xmlable;
                    } else {
                        response.sendError(400, "Bad item posted to /cand/classified for Searching");
                        return;
                    }
                } catch (SAXException ex) {
                    response.sendError(400, "Bad item posted to /cand/classified for Searching");
                    return;
                }

                // reply with the searched index
                ClassifiedCandidateIndex idx = candMan.searchCandidates(ccsreq);
                OutputStream out = response.getOutputStream();
                String hdr = request.getHeader("Accept-Encoding");
                if (hdr != null && hdr.contains("gzip")) {
                    // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    out = new GZIPOutputStream(out);
                    response.setHeader("Content-Encoding", "gzip");
                }
                XMLWriter.write(out, idx);
                out.close();

            } else {
                response.sendError(400, "Bad non-POST/GET request /cand/classified");
                return;
            }
        } else if (path.startsWith("/cand/newclassified")) {
            if (request.getMethod().equals("POST")) {

                ClassifiedCandidate cand = null;
                try {
                    XMLAble xmlable = XMLReader.read(request.getInputStream());
                    if (xmlable instanceof ClassifiedCandidate) {
                        cand = (ClassifiedCandidate) xmlable;
                    } else {
                        response.sendError(400, "Bad item posted to /cand/newclassified for Classifying");
                        return;
                    }
                } catch (SAXException ex) {
                    response.sendError(400, "Bad item posted to /cand/newclassified for Classifying");
                    return;
                }

                cand.setId(0);

                Session session = new Session();
                dbMan.add(cand, session);
                try {
                    dbMan.save(session);
                } catch (BookKeeprException ex) {
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE,
                            "error saving database when adding new classified cand", ex);
                    response.sendError(500, "error saving database when adding new classified cand");
                }
                OutputStream out = response.getOutputStream();
                String hdr = request.getHeader("Accept-Encoding");
                if (hdr != null && hdr.contains("gzip")) {
                    // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    out = new GZIPOutputStream(out);
                    response.setHeader("Content-Encoding", "gzip");
                }
                XMLWriter.write(out, cand);
                out.close();

                return;
            } else {
                response.sendError(400, "Bad non-POST request /cand/newclassified");
                return;
            }
        } else if (path.startsWith("/cand/add/")) {
            // assume that 'add' is not an ID, since it would have server and type = 0, which is invalid.
            if (request.getMethod().equals("POST")) {
                String[] elems = path.substring(1).split("/");
                if (elems.length < 4) {
                    response.sendError(400, "Bad URL for /cand/add/{psrxmlId}/{procId}");
                    return;
                }

                final long psrxmlId = Long.parseLong(elems[2], 16);
                final long procId = Long.parseLong(elems[3], 16);

                if (dbMan.getById(procId) == null) {
                    response.sendError(400, "Bad URL for /cand/add/{psrxmlId}/{procId}. ProcId "
                            + Long.toHexString(procId) + " does not exist!");
                    return;
                }
                if (dbMan.getById(psrxmlId) == null) {
                    response.sendError(400, "Bad URL for /cand/add/{psrxmlId}/{procId}. PsrxmlId "
                            + Long.toHexString(psrxmlId) + " does not exist!");
                    return;
                }

                synchronized (this) {
                    if (nAddSubmitted > 2) {
                        // too many jobs on. to prevent memory overload, end the session!
                        response.setHeader("Retry-After", "60");
                        response.sendError(503);
                        return;
                    } else {
                        //increment the workload counter
                        nAddSubmitted++;
                    }
                }

                final ArrayList<RawCandidate> rawCands = new ArrayList<RawCandidate>();
                if (request.getContentType().equals("application/x-tar")) {
                    TarInputStream tarin = new TarInputStream(request.getInputStream());
                    while (true) {
                        // loop over all entries in the tar file.
                        TarEntry tarEntry = tarin.getNextEntry();
                        if (tarEntry == null) {
                            break;
                        } else {
                        }
                        InputStream inStream;

                        /*
                         * There is some complication as the XML reader
                         * closes the input stream when it is done, but we
                         * don't want to do that as it closes the entire tar
                         * 
                         * So we define a 'UnclosableInputStream' that ignores
                         * the close() command. 
                         * 
                         * If we have a gzipped xml file, we should pass
                         * through a gzip input stream too.
                         */
                        if (tarEntry.getName().endsWith(".gz")) {
                            inStream = new UncloseableInputStream(new GZIPInputStream(tarin));
                        } else {
                            inStream = new UncloseableInputStream(tarin);
                        }
                        try {
                            // parse the xml document.
                            XMLAble xmlable = (XMLAble) XMLReader.read(inStream);
                            if (xmlable instanceof RawCandidate) {
                                rawCands.add((RawCandidate) xmlable);
                            } else {
                                response.sendError(400, "POSTed tar file MUST only contain raw candidates.");
                                return;
                            }

                        } catch (SAXException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, null, ex);
                            response.sendError(400, "POSTed tar file MUST only contain vaild xml candidates.");
                            return;
                        }

                    }
                    // finaly, we can close the tar stream.
                    tarin.close();
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO,
                            "Received " + rawCands.size() + " raw candidates for processing from "
                                    + request.getRemoteAddr());

                    final BackgroundedTask bgtask = new BackgroundedTask("AddRawCandidates");

                    bgtask.setTarget(new Runnable() {

                        public void run() {
                            candMan.addRawCandidates(rawCands, psrxmlId, procId);
                            synchronized (CandidateHandler.this) {
                                // decriment the counter for how many workloads are left to do.
                                CandidateHandler.this.nAddSubmitted--;
                            }
                        }
                    });
                    bookkeepr.getBackgroundTaskRunner().offer(bgtask);
                    StringBuffer buf = new StringBuffer();
                    Formatter formatter = new Formatter(buf);
                    formatter.format("%s/%s/%d", bookkeepr.getConfig().getExternalUrl(), "tasks",
                            bgtask.getId());
                    response.setStatus(303);
                    response.addHeader("Location", buf.toString());
                    return;
                } else {
                    response.sendError(400, "Must POST application/x-tar type documents to this URL");
                }
            } else {
                response.sendError(400, "Bad non-POST request /cand/add");
                return;
            }
        } else {
            // see if we are requesting and ID.
            long targetId = 0;
            String[] elems = path.substring(1).split("/");

            // try and make an int from the passed value.
            try {
                if (elems.length < 2) {
                    response.sendError(400, "Bad URL for /cand/{id}");
                    return;
                }
                targetId = Long.parseLong(elems[1], 16);
            } catch (NumberFormatException ex) {
                Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO,
                        "Recieved request for bad id " + elems[1]);
                response.sendError(400, "Submitted URI was malformed\nMessage was '" + ex.getMessage() + "'");
                return;
            }

            IdAble idable = dbMan.getById(targetId);
            if (idable == null) {
                Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO,
                        "Recieved request for non-existing ID " + Long.toHexString(targetId));
                response.sendError(400,
                        "Submitted request was for non-existing ID " + Long.toHexString(targetId));
                return;
            }

            if (idable instanceof CandidateListStub) {
                if (request.getMethod().equals("GET")) {
                    int origin = dbMan.getOrigin(idable);
                    if (dbMan.getOriginId() == origin) {
                        // request for a local item...
                        response.setHeader("Content-Encoding", "gzip");
                        outputToInput(
                                new FileInputStream(candMan.getCandidateListFile((CandidateListStub) idable)),
                                response.getOutputStream());

                    } else {
                        HttpClient httpclient = bookkeepr.checkoutHttpClient();

                        try {
                            // request for a remote item...
                            BookkeeprHost host = bookkeepr.getConfig().getBookkeeprHost(origin);
                            String targetpath = host.getUrl() + path;
                            HttpGet httpreq = new HttpGet(targetpath);
                            HttpResponse httpresp = httpclient.execute(httpreq);
                            for (Header head : httpresp.getAllHeaders()) {
                                if (head.getName().equalsIgnoreCase("transfer-encoding")) {
                                    continue;
                                }
                                response.setHeader(head.getName(), head.getValue());
                            }
                            response.setStatus(httpresp.getStatusLine().getStatusCode());
                            httpresp.getEntity().writeTo(response.getOutputStream());

                        } catch (URISyntaxException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Bad uri specified for remote candidate", ex);
                            response.sendError(500, "Bad uri specified for remote candidate");
                        } catch (HttpException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Could not make a httpreqest for remote Candidate", ex);
                            response.sendError(500, "Could not make a httpreqest for remote Candidate");
                        } catch (IOException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Could not make a httpreqest for remote Candidate", ex);
                            response.sendError(500, "Could not make a httpreqest for remote Candidate");
                        }
                        bookkeepr.returnHttpClient(httpclient);

                        //                            if (host != null) {
                        //                                response.setStatus(301);
                        //                                response.addHeader("Location", host.getUrl() + path);
                        //                            } else {
                        //                                response.sendError(500, "Cannot find a bookkeepr server for origin id " + origin);
                        //                            }
                    }
                } else {
                    response.sendError(400, "Bad non-GET request for a candidate list");
                    return;
                }
            } else if (idable instanceof ClassifiedCandidate) {

                // /cand/{id}

                if (request.getMethod().equals("POST")) {
                    //                        int origin = dbMan.getOrigin(idable);
                    //                        if (dbMan.getOriginId() == origin) {
                    RawCandidateMatched stub = null;
                    try {
                        XMLAble xmlable = XMLReader.read(request.getInputStream());
                        if (xmlable instanceof RawCandidateMatched) {
                            stub = (RawCandidateMatched) xmlable;
                        } else {
                            response.sendError(400, "Bad item posted to /cand/... for Classifying");
                            return;
                        }
                    } catch (SAXException ex) {
                        response.sendError(400, "Bad item posted to /cand/... for Classifying");
                        return;
                    }
                    ClassifiedCandidate c = null;
                    try {
                        c = (ClassifiedCandidate) ((ClassifiedCandidate) idable).clone();
                    } catch (CloneNotSupportedException ex) {
                        Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, null, ex);
                        response.sendError(500,
                                "Server error that cannot happen happened! Classified Candidates are Cloneable!");
                        return;
                    }

                    c.addRawCandidateMatched(stub);

                    Session session = new Session();
                    dbMan.add(c, session);
                    try {
                        dbMan.save(session);
                    } catch (BookKeeprException ex) {
                        Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                "Error when saving database adding raw to classified cand", ex);
                        response.sendError(500, "Error when saving database adding raw to classified cand");

                    }

                    OutputStream out = response.getOutputStream();
                    String hdr = request.getHeader("Accept-Encoding");
                    if (hdr != null && hdr.contains("gzip")) {
                        // if the host supports gzip encoding, gzip the output for quick transfer speed.
                        out = new GZIPOutputStream(out);
                        response.setHeader("Content-Encoding", "gzip");
                    }
                    XMLWriter.write(out, c);
                    out.close();

                    //                            OutputStream out = response.getOutputStream();
                    //                            String hdr = request.getHeader("Accept-Encoding");
                    //                            if (hdr != null && hdr.contains("gzip")) {
                    //                                // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    //                                out = new GZIPOutputStream(out);
                    //                                response.setHeader("Content-Encoding", "gzip");
                    //                            }
                    //                            XMLWriter.write(out, idx);
                    //                            out.close();
                    //                        } else {
                    //                            // request for a remote item...
                    //                            // currently re-direct to the remote server.. perhaps we should pass through?
                    //                            BookkeeprHost host = bookkeepr.getConfig().getBookkeeprHost(origin);
                    //                            if (host != null) {
                    //                                response.setStatus(301);
                    //                                response.addHeader("Location", host.getUrl() + path);
                    //                            } else {
                    //                                response.sendError(500, "Cannot find a bookkeepr server for origin id " + origin);
                    //                            }
                    //                        }
                } else {
                    response.sendError(400, "Bad non-POST request for a classified candidate");
                    return;
                }
            } else if (idable instanceof RawCandidateStub) {
                if (request.getMethod().equals("GET")) {
                    int origin = dbMan.getOrigin(idable);
                    if (dbMan.getOriginId() == origin) {

                        if (elems.length > 2) {
                            try {
                                int h = 600;
                                int w = 800;
                                String[] parts = elems[2].split("x|\\.png");
                                if (parts.length > 1) {
                                    try {
                                        h = Integer.parseInt(parts[1]);
                                        w = Integer.parseInt(parts[0]);
                                    } catch (NumberFormatException e) {
                                        h = 600;
                                        w = 800;
                                    }
                                }
                                RawCandidate cand = (RawCandidate) XMLReader
                                        .read(new GZIPInputStream(new FileInputStream(
                                                candMan.getRawCandidateFile((RawCandidateStub) idable))));

                                response.setContentType("image/png");
                                BufferedImage img = candMan.makeImageOf(cand, w, h);
                                ImageIO.write(img, "png", response.getOutputStream());
                                return;
                            } catch (SAXException ex) {
                                Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }

                        // request for a local item...
                        response.setHeader("Content-Encoding", "gzip");
                        outputToInput(
                                new FileInputStream(candMan.getRawCandidateFile((RawCandidateStub) idable)),
                                response.getOutputStream());

                    } else {
                        HttpClient httpclient = bookkeepr.checkoutHttpClient();

                        try {
                            // request for a remote item...
                            BookkeeprHost host = bookkeepr.getConfig().getBookkeeprHost(origin);
                            String targetpath = host.getUrl() + path;
                            HttpGet httpreq = new HttpGet(targetpath);
                            HttpResponse httpresp = httpclient.execute(httpreq);
                            for (Header head : httpresp.getAllHeaders()) {
                                if (head.getName().equalsIgnoreCase("transfer-encoding")) {
                                    continue;
                                }
                                response.setHeader(head.getName(), head.getValue());
                            }
                            response.setStatus(httpresp.getStatusLine().getStatusCode());
                            httpresp.getEntity().writeTo(response.getOutputStream());

                        } catch (URISyntaxException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Bad uri specified for remote candidate", ex);
                            response.sendError(500, "Bad uri specified for remote candidate");
                        } catch (HttpException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Could not make a httpreqest for remote Candidate", ex);
                            response.sendError(500, "Could not make a httpreqest for remote Candidate");
                        } catch (IOException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Could not make a httpreqest for remote Candidate", ex);
                            response.sendError(500, "Could not make a httpreqest for remote Candidate");
                        }
                        bookkeepr.returnHttpClient(httpclient);
                    }

                } else {
                    response.sendError(400, "Bad non-GET request for a raw candidate");
                    return;
                }
            } else {
                Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO,
                        "Recieved request for non-candidate ID " + targetId);
                response.sendError(400, "Submitted request was for non-candidate ID " + targetId);
                return;
            }
        }

    }
}

From source file:org.voltdb.regressionsuites.TestInsertIntoSelectSuite.java

private static void initializeTables(Client client) throws Exception {

    ClientResponse resp = null;//from  www.j av a 2  s  .co  m

    clearTables(client);

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

        resp = client.callProcedure("SOURCE_P1.insert", i, Long.toHexString(i), i, i);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_P1.insert", i, Long.toHexString(-i), -i, -i);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_P1.insert", i, Long.toHexString(i * 11), i * 11, i * 11);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_P1.insert", i, Long.toHexString(i * -11), i * -11, i * -11);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_R1.insert", i, Long.toHexString(i), i, i);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_R1.insert", i, Long.toHexString(-i), -i, -i);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_R1.insert", i, Long.toHexString(i * 11), i * 11, i * 11);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_R1.insert", i, Long.toHexString(i * -11), i * -11, i * -11);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        int j = i + 5;

        resp = client.callProcedure("SOURCE_P2.insert", j, Long.toHexString(j), j, j);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_P2.insert", j, Long.toHexString(-j), -j, -j);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_P2.insert", j, Long.toHexString(j * 11), j * 11, (j * 11) % 128);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_P2.insert", j, Long.toHexString(j * -11), j * -11,
                -((j * 11) % 128));
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_R2.insert", j, Long.toHexString(j), j, j);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_R2.insert", j, Long.toHexString(-j).substring(0, 3), -j, -j);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_R2.insert", j, Long.toHexString(j * 11), j * 11, (j * 11) % 128);
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());

        resp = client.callProcedure("SOURCE_R2.insert", j, Long.toHexString(j * -11).substring(0, 3), j * -11,
                -((j * 11) % 128));
        assertEquals(ClientResponse.SUCCESS, resp.getStatus());
    }
}

From source file:com.goodhustle.ouyaunitybridge.OuyaUnityActivity.java

public void requestPurchase(final String productId)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());
    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", productId);
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();
    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);//from w ww .  j a v a  2 s.  com
    SecretKey key = new SecretKeySpec(keyBytes, "AES");
    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));
    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);
    Purchasable purchasable = new Purchasable(productId, Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));
    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, productId);
    }
    ouyaFacade.requestPurchase(purchasable, new PurchaseListener(productId));
}

From source file:org.b3log.xiaov.service.QQService.java

public void onQQDiscussMessage(final DiscussMessage message) {
    final long discussId = message.getDiscussId();

    final String content = message.getContent();
    final String userName = Long.toHexString(message.getUserId());
    // Push to forum
    String qqMsg = content.replaceAll("\\[\"face\",[0-9]+\\]", "");
    if (StringUtils.isNotBlank(qqMsg)) {
        qqMsg = "<p>" + qqMsg + "</p>";
        sendToForum(qqMsg, userName);/*from   w w  w .ja va 2 s. c  om*/
    }

    String msg = "";
    if (StringUtils.contains(content, XiaoVs.QQ_BOT_NAME)
            || (StringUtils.length(content) > 6
            && (StringUtils.contains(content, "?") || StringUtils.contains(content, "") || StringUtils.contains(content, "")))) {
        msg = answer(content, userName);
    }

    if (StringUtils.isBlank(msg)) {
        return;
    }

    if (RandomUtils.nextFloat() >= 0.9) {
        Long latestAdTime = DISCUSS_AD_TIME.get(discussId);
        if (null == latestAdTime) {
            latestAdTime = 0L;
        }

        final long now = System.currentTimeMillis();

        if (now - latestAdTime > 1000 * 60 * 30) {
            msg = msg + "\n\n" + ADS.get(RandomUtils.nextInt(ADS.size())) + "";

            DISCUSS_AD_TIME.put(discussId, now);
        }
    }

    sendMessageToDiscuss(discussId, msg);
}