@Override JSONStreamAware processRequest(HttpServletRequest req) throws RiseException { long recipient = ParameterParser.getRecipientId(req); long amountNQT = ParameterParser.getAmountNQT(req); Account account = ParameterParser.getSenderAccount(req); return createTransaction(req, account, recipient, amountNQT); }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { final int timestamp = ParameterParser.getTimestamp(req); int firstIndex = ParameterParser.getFirstIndex(req); int lastIndex = ParameterParser.getLastIndex(req); boolean includeCurrencyInfo = !"false".equalsIgnoreCase(req.getParameter("includeCurrencyInfo")); JSONObject response = new JSONObject(); JSONArray exchanges = new JSONArray(); try (FilteringIterator<Exchange> exchangeIterator = new FilteringIterator<>( Exchange.getAllExchanges(0, -1), new Filter<Exchange>() { @Override public boolean ok(Exchange exchange) { return exchange.getTimestamp() >= timestamp; } }, firstIndex, lastIndex)) { while (exchangeIterator.hasNext()) { exchanges.add(JSONData.exchange(exchangeIterator.next(), includeCurrencyInfo)); } } response.put("exchanges", exchanges); return response; }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { long accountId = ParameterParser.getAccount(req).getId(); long assetId = 0; try { assetId = Convert.parseUnsignedLong(req.getParameter("asset")); } catch (RuntimeException e) { // ignore } int firstIndex = ParameterParser.getFirstIndex(req); int lastIndex = ParameterParser.getLastIndex(req); DbIterator<Order.Ask> askOrders; if (assetId == 0) { askOrders = Order.Ask.getAskOrdersByAccount(accountId, firstIndex, lastIndex); } else { askOrders = Order.Ask.getAskOrdersByAccountAsset(accountId, assetId, firstIndex, lastIndex); } JSONArray orderIds = new JSONArray(); try { while (askOrders.hasNext()) { orderIds.add(Convert.toUnsignedLong(askOrders.next().getId())); } } finally { askOrders.close(); } JSONObject response = new JSONObject(); response.put("askOrderIds", orderIds); return response; }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { Currency currency = ParameterParser.getCurrency(req); long units = ParameterParser.getLong(req, "units", 0, currency.getReserveSupply(), false); Account account = ParameterParser.getSenderAccount(req); Attachment attachment = new Attachment.MonetarySystemReserveClaim(currency.getId(), units); return createTransaction(req, account, attachment); }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { long assetId = ParameterParser.getUnsignedLong(req, "asset", true); int height = ParameterParser.getHeight(req); JSONObject response = new JSONObject(); response.put("numberOfAccounts", Account.getAssetAccountCount(assetId, height)); return response; }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { long orderId = ParameterParser.getUnsignedLong(req, "order", true); Account account = ParameterParser.getSenderAccount(req); Order.Ask orderData = Order.Ask.getAskOrder(orderId); if (orderData == null || orderData.getAccountId() != account.getId()) { return UNKNOWN_ORDER; } Attachment attachment = new Attachment.ColoredCoinsAskOrderCancellation(orderId); return createTransaction(req, account, attachment); }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { long recipientId = ParameterParser.getRecipientId(req); Account recipientAccount = Account.getAccount(recipientId); if (recipientAccount == null || recipientAccount.getPublicKey() == null) { return INCORRECT_RECIPIENT; } EncryptedData encryptedData = ParameterParser.getEncryptedMessage(req, recipientAccount); return JSONData.encryptedData(encryptedData); }
private void onAppend(ChannelHandlerContext ctx) throws IOException { writeContinueHeader(ctx); final String nnId = params.namenodeId(); final int bufferSize = params.bufferSize(); DFSClient dfsClient = newDfsClient(nnId, conf); OutputStream out = dfsClient.append(path, bufferSize, EnumSet.of(CreateFlag.APPEND), null, null); DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, OK); resp.headers().set(CONTENT_LENGTH, 0); ctx.pipeline() .replace(this, HdfsWriter.class.getSimpleName(), new HdfsWriter(dfsClient, out, resp)); }
private void injectToken() throws IOException { if (UserGroupInformation.isSecurityEnabled()) { Token<DelegationTokenIdentifier> token = params.delegationToken(); token.setKind(HDFS_DELEGATION_KIND); ugi.addToken(token); } }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws RiseException { String name = req.getParameter("name"); String description = req.getParameter("description"); String decimalsValue = Convert.emptyToNull(req.getParameter("decimals")); if (name == null) { return MISSING_NAME; } name = name.trim(); if (name.length() < Constants.MIN_ASSET_NAME_LENGTH || name.length() > Constants.MAX_ASSET_NAME_LENGTH) { return INCORRECT_ASSET_NAME_LENGTH; } String normalizedName = name.toLowerCase(); for (int i = 0; i < normalizedName.length(); i++) { if (Constants.ALPHABET.indexOf(normalizedName.charAt(i)) < 0) { return INCORRECT_ASSET_NAME; } } if (description != null && description.length() > Constants.MAX_ASSET_DESCRIPTION_LENGTH) { return INCORRECT_ASSET_DESCRIPTION; } byte decimals = 0; if (decimalsValue != null) { try { decimals = Byte.parseByte(decimalsValue); if (decimals < 0 || decimals > 8) { return INCORRECT_DECIMALS; } } catch (NumberFormatException e) { return INCORRECT_DECIMALS; } } long quantityQNT = ParameterParser.getQuantityQNT(req); Account account = ParameterParser.getSenderAccount(req); Attachment attachment = new Attachment.ColoredCoinsAssetIssuance(name, description, quantityQNT, decimals); return createTransaction(req, account, attachment); }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws ParameterException { String query = Convert.nullToEmpty(req.getParameter("query")); int firstIndex = ParameterParser.getFirstIndex(req); int lastIndex = ParameterParser.getLastIndex(req); boolean includeCounts = !"false".equalsIgnoreCase(req.getParameter("includeCounts")); JSONObject response = new JSONObject(); JSONArray jsonArray = new JSONArray(); try (DbIterator<Currency> currencies = Currency.searchCurrencies(query, firstIndex, lastIndex)) { while (currencies.hasNext()) { jsonArray.add(JSONData.currency(currencies.next(), includeCounts)); } } response.put("currencies", jsonArray); return response; }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { Long orderId = ParameterParser.getOrderId(req); Order.Ask askOrder = Order.Ask.getAskOrder(orderId); if (askOrder == null) { return UNKNOWN_ORDER; } return JSONData.askOrder(askOrder); }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws RiseException { Account account = ParameterParser.getAccount(req); JSONObject response = new JSONObject(); response.put("numberOfBlocks", Rise.getBlockchain().getBlockCount(account)); return response; }
@Override protected JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { DigitalGoodsStore.Goods goods = ParameterParser.getGoods(req); if (goods.isDelisted()) { return UNKNOWN_GOODS; } int quantity = ParameterParser.getGoodsQuantity(req); if (quantity > goods.getQuantity()) { return INCORRECT_PURCHASE_QUANTITY; } long priceNQT = ParameterParser.getPriceNQT(req); if (priceNQT != goods.getPriceNQT()) { return INCORRECT_PURCHASE_PRICE; } String deliveryDeadlineString = Convert.emptyToNull(req.getParameter("deliveryDeadlineTimestamp")); if (deliveryDeadlineString == null) { return MISSING_DELIVERY_DEADLINE_TIMESTAMP; } int deliveryDeadline; try { deliveryDeadline = Integer.parseInt(deliveryDeadlineString); if (deliveryDeadline <= Nxt.getEpochTime()) { return INCORRECT_DELIVERY_DEADLINE_TIMESTAMP; } } catch (NumberFormatException e) { return INCORRECT_DELIVERY_DEADLINE_TIMESTAMP; } Account buyerAccount = ParameterParser.getSenderAccount(req); Account sellerAccount = Account.getAccount(goods.getSellerId()); Attachment attachment = new Attachment.DigitalGoodsPurchase(goods.getId(), quantity, priceNQT, deliveryDeadline); try { return createTransaction(req, buyerAccount, sellerAccount.getId(), 0, attachment); } catch (NxtException.InsufficientBalanceException e) { return JSONResponses.NOT_ENOUGH_FUNDS; } }
private void onOpen(ChannelHandlerContext ctx) throws IOException { final String nnId = params.namenodeId(); final int bufferSize = params.bufferSize(); final long offset = params.offset(); final long length = params.length(); DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders headers = response.headers(); // Allow the UI to access the file headers.set(ACCESS_CONTROL_ALLOW_METHODS, GET); headers.set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); headers.set(CONTENT_TYPE, APPLICATION_OCTET_STREAM); headers.set(CONNECTION, CLOSE); final DFSClient dfsclient = newDfsClient(nnId, conf); HdfsDataInputStream in = dfsclient.createWrappedInputStream(dfsclient.open(path, bufferSize, true)); in.seek(offset); long contentLength = in.getVisibleLength() - offset; if (length >= 0) { contentLength = Math.min(contentLength, length); } final InputStream data; if (contentLength >= 0) { headers.set(CONTENT_LENGTH, contentLength); data = new LimitInputStream(in, contentLength); } else { data = in; } ctx.write(response); ctx.writeAndFlush( new ChunkedStream(data) { @Override public void close() throws Exception { super.close(); dfsclient.close(); } }) .addListener(ChannelFutureListener.CLOSE); }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { long sellerId = ParameterParser.getAccountId(req, "seller", true); int firstIndex = ParameterParser.getFirstIndex(req); int lastIndex = ParameterParser.getLastIndex(req); JSONObject response = new JSONObject(); JSONArray purchasesJSON = new JSONArray(); try (DbIterator<DigitalGoodsStore.Purchase> purchases = DigitalGoodsStore.Purchase.getExpiredSellerPurchases(sellerId, firstIndex, lastIndex)) { while (purchases.hasNext()) { purchasesJSON.add(JSONData.purchase(purchases.next())); } } response.put("purchases", purchasesJSON); return response; }
private void onCreate(ChannelHandlerContext ctx) throws IOException, URISyntaxException { writeContinueHeader(ctx); final String nnId = params.namenodeId(); final int bufferSize = params.bufferSize(); final short replication = params.replication(); final long blockSize = params.blockSize(); final FsPermission permission = params.permission(); EnumSet<CreateFlag> flags = params.overwrite() ? EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE) : EnumSet.of(CreateFlag.CREATE); final DFSClient dfsClient = newDfsClient(nnId, confForCreate); OutputStream out = dfsClient.createWrappedOutputStream( dfsClient.create( path, permission, flags, replication, blockSize, null, bufferSize, null), null); DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, CREATED); final URI uri = new URI(HDFS_URI_SCHEME, nnId, path, null, null); resp.headers().set(LOCATION, uri.toString()); resp.headers().set(CONTENT_LENGTH, 0); ctx.pipeline() .replace(this, HdfsWriter.class.getSimpleName(), new HdfsWriter(dfsClient, out, resp)); }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { long accountId = ParameterParser.getAccountId(req, "account", false); boolean includeFinished = "true".equalsIgnoreCase(req.getParameter("includeFinished")); int firstIndex = ParameterParser.getFirstIndex(req); int lastIndex = ParameterParser.getLastIndex(req); final int timestamp = ParameterParser.getTimestamp(req); JSONArray pollsJson = new JSONArray(); DbIterator<Poll> polls = null; try { if (accountId == 0) { if (includeFinished) { polls = Poll.getAllPolls(firstIndex, lastIndex); } else { polls = Poll.getActivePolls(firstIndex, lastIndex); } } else { polls = Poll.getPollsByAccount(accountId, includeFinished, firstIndex, lastIndex); } while (polls.hasNext()) { Poll poll = polls.next(); if (poll.getTimestamp() < timestamp) { break; } pollsJson.add(JSONData.poll(poll)); } } finally { DbUtils.close(polls); } JSONObject response = new JSONObject(); response.put("polls", pollsJson); return response; }
public void handle(ChannelHandlerContext ctx, HttpRequest req) throws IOException, URISyntaxException { String op = params.op(); HttpMethod method = req.method(); if (PutOpParam.Op.CREATE.name().equalsIgnoreCase(op) && method == PUT) { onCreate(ctx); } else if (PostOpParam.Op.APPEND.name().equalsIgnoreCase(op) && method == POST) { onAppend(ctx); } else if (GetOpParam.Op.OPEN.name().equalsIgnoreCase(op) && method == GET) { onOpen(ctx); } else if (GetOpParam.Op.GETFILECHECKSUM.name().equalsIgnoreCase(op) && method == GET) { onGetFileChecksum(ctx); } else { throw new IllegalArgumentException("Invalid operation " + op); } }
@Override protected JSONStreamAware processRequest(HttpServletRequest req) throws ParameterException { long[] currencyIds = ParameterParser.getUnsignedLongs(req, "currencies"); boolean includeCounts = "true".equalsIgnoreCase(req.getParameter("includeCounts")); JSONObject response = new JSONObject(); JSONArray currenciesJSONArray = new JSONArray(); response.put("currencies", currenciesJSONArray); for (long currencyId : currencyIds) { Currency currency = Currency.getCurrency(currencyId); if (currency == null) { return UNKNOWN_CURRENCY; } currenciesJSONArray.add(JSONData.currency(currency, includeCounts)); } return response; }
private void onGetFileChecksum(ChannelHandlerContext ctx) throws IOException { MD5MD5CRC32FileChecksum checksum = null; final String nnId = params.namenodeId(); DFSClient dfsclient = newDfsClient(nnId, conf); try { checksum = dfsclient.getFileChecksum(path, Long.MAX_VALUE); dfsclient.close(); dfsclient = null; } finally { IOUtils.cleanup(LOG, dfsclient); } final byte[] js = JsonUtil.toJsonString(checksum).getBytes(Charsets.UTF_8); DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(js)); resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8); resp.headers().set(CONTENT_LENGTH, js.length); resp.headers().set(CONNECTION, CLOSE); ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE); }
@Override public void channelRead0(final ChannelHandlerContext ctx, final HttpRequest req) throws Exception { Preconditions.checkArgument(req.uri().startsWith(WEBHDFS_PREFIX)); QueryStringDecoder queryString = new QueryStringDecoder(req.uri()); params = new ParameterParser(queryString, conf); DataNodeUGIProvider ugiProvider = new DataNodeUGIProvider(params); ugi = ugiProvider.ugi(); path = params.path(); injectToken(); ugi.doAs( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { handle(ctx, req); return null; } }); }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { String transactionBytes = Convert.emptyToNull(req.getParameter("transactionBytes")); String transactionJSON = Convert.emptyToNull(req.getParameter("transactionJSON")); String prunableAttachmentJSON = Convert.emptyToNull(req.getParameter("prunableAttachmentJSON")); Transaction transaction = ParameterParser.parseTransaction(transactionJSON, transactionBytes, prunableAttachmentJSON) .build(); JSONObject response = JSONData.unconfirmedTransaction(transaction); try { transaction.validate(); } catch (NxtException.ValidationException | RuntimeException e) { Logger.logDebugMessage(e.getMessage(), e); response.put("validate", false); JSONData.putException(response, e, "Invalid transaction"); } response.put("verify", transaction.verifySignature()); return response; }
@Override JSONStreamAware processRequest(HttpServletRequest req) throws RiseException { String pollValue = req.getParameter("poll"); if (pollValue == null) { return MISSING_POLL; } Poll pollData; int numberOfOptions = 0; try { pollData = Poll.getPoll(Convert.parseUnsignedLong(pollValue)); if (pollData != null) { numberOfOptions = pollData.getOptions().length; } else { return INCORRECT_POLL; } } catch (RuntimeException e) { return INCORRECT_POLL; } byte[] vote = new byte[numberOfOptions]; try { for (int i = 0; i < numberOfOptions; i++) { String voteValue = req.getParameter("vote" + i); if (voteValue != null) { vote[i] = Byte.parseByte(voteValue); } } } catch (NumberFormatException e) { return INCORRECT_VOTE; } Account account = ParameterParser.getSenderAccount(req); Attachment attachment = new Attachment.MessagingVoteCasting(pollData.getId(), vote); return createTransaction(req, account, attachment); }
private String processRequest( HttpServletRequest request, HttpServletResponse response, ConnectionPool conPool) throws Exception { // getting id parameters ParameterParser parameter = new ParameterParser(request); String bookID = parameter.getString(bookInterface.FIELD_ID, null); String sellerID = parameter.getString(bookInterface.FIELD_SELLERID, null); String message = parameter.getString(FIELD_MESSAGE, null); int codeID = parameter.getInt(bookInterface.FIELD_HIDDENID, 0); // get buyer's user object User user = (User) request.getSession().getAttribute(StringInterface.USERATTR); // security feauture: // if one of ids is missing or incorrect return false if (bookID == null || sellerID == null || codeID == 0 || bookID.length() != booksTable.ID_LENGTH || sellerID.length() != usersTable.ID_LENGTH || codeID != Math.abs(bookID.hashCode())) { return "We were unable to find the book you specified! Please make sure that the book id is correct."; } if (user.getID().equals(sellerID)) { return "You may not purchase an item from yourself!"; } // get connection Connection con = conPool.getConnection(); try { booksTable book = generalUtils.getBook(bookID, con); /*security feauture: *check seller id == passed hidden id *book != null */ if (book == null || !book.getSellerID().equals(sellerID)) { return "We were unable to find the book you specified! Please make sure that the book id is correct."; } usersTable sellerInfo = userUtils.getUserInfo(sellerID, con); usersTable buyerInfo = userUtils.getUserInfo(user.getID(), con); collegeTable college = getCollege(book.getCollegeID() + "", con); // if still here continue if (message == null) { request.setAttribute(ATTR_BOOK, book); request.setAttribute(ATTR_SELLER, sellerInfo); request.setAttribute(ATTR_BUYER, buyerInfo); request.setAttribute(ATTR_COLLEGE, college.getFull()); RequestDispatcher rd = getServletContext().getRequestDispatcher(PATH_BUY_CONFIRM); rd.include(request, response); return null; } else if (buy(book, user, con)) { // sending email to buyer request.setAttribute(mailInterface.USERATTR, buyerInfo.getUsername()); request.setAttribute(mailInterface.EMAILATTR, buyerInfo.getEmail()); request.setAttribute(mailInterface.BOOKATTR, book); request.setAttribute("book_id", bookID); request.setAttribute("seller_id", sellerID); RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHBIDCONFIRMATION); rd.include(request, response); // sending email to seller request.setAttribute(ATTR_COLLEGE, college.getFull()); request.setAttribute(mailInterface.USERATTR, sellerInfo.getUsername()); request.setAttribute(mailInterface.EMAILATTR, sellerInfo.getEmail()); request.setAttribute(mailInterface.MESSAGEATTR, message); request.setAttribute(mailInterface.BOOKATTR, book); request.setAttribute(mailInterface.MOREATTR, buyerInfo); request.setAttribute("book_id", bookID); request.setAttribute("buyer_id", user.getID()); rd = getServletContext().getRequestDispatcher(PATHBOOKUPDATE); rd.include(request, response); // showing success message rd = getServletContext().getRequestDispatcher(PATH_BUY_SUCCESS); rd.include(request, response); return null; } else { throw new Exception("failed to process with buy"); } } catch (Exception e) { throw e; } finally { // recycle conPool.free(con); con = null; } }
private static boolean parse( final String[] args, final Context context, final List<CompileParameter> parameters) { if (args.length == 1 && ("/?".equals(args[0]) || "-?".equals(args[0]) || "?".equals(args[0]))) { showHelpAndExit(context, true, parameters); return false; } final List<ParameterParser> customParsers = new ArrayList<ParameterParser>(); for (final CompileParameter cp : parameters) { if (cp instanceof ParameterParser) { customParsers.add((ParameterParser) cp); } } final List<String> errors = new ArrayList<String>(); for (String a : args) { if (a.startsWith("-") || a.startsWith("/")) a = a.substring(1); final int eq = a.indexOf('='); final String name = a.substring(0, eq != -1 ? eq : a.length()); final String value = eq == -1 ? null : a.substring(eq + 1); final CompileParameter cp = from(name, parameters); if (cp == null) { boolean matched = false; for (final ParameterParser parser : customParsers) { final Either<Boolean> tryParse = parser.tryParse(name, value, context); if (!tryParse.isSuccess()) { errors.add(tryParse.explainError()); matched = true; break; } else if (tryParse.get()) { matched = true; break; } } if (!matched) { errors.add("Unknown parameter: " + name); } } else { if (eq == -1 && cp.getUsage() != null) { if (cp instanceof ParameterParser) { Either<Boolean> tryParse = ((ParameterParser) cp).tryParse(name, null, context); if (tryParse.isSuccess() && tryParse.get()) { context.put(cp, null); } else { errors.add("Expecting " + cp.getUsage() + " after = for " + a); } } else { errors.add("Expecting " + cp.getUsage() + " after = for " + a); } } else { context.put(cp, value); } } } if (args.length == 0 || errors.size() > 0) { for (final String err : errors) { context.error(err); } showHelpAndExit(context, args.length == errors.size(), parameters); return false; } return true; }