List of usage examples for java.lang StringBuilder StringBuilder
@HotSpotIntrinsicCandidate
public StringBuilder()
From source file:com.github.xbn.examples.regexutil.non_xbn.BetweenLineMarkersButSkipFirstXmpl.java
public static final void main(String[] as_1RqdTxtFilePath) { Iterator<String> lineItr = null; try {//ww w. j ava 2 s. co m lineItr = FileUtils.lineIterator(new File(as_1RqdTxtFilePath[0])); //Throws npx if null } catch (IOException iox) { throw new RuntimeException("Attempting to open \"" + as_1RqdTxtFilePath[0] + "\"", iox); } catch (RuntimeException rx) { throw new RuntimeException("One required parameter: The path to the text file.", rx); } String LINE_SEP = System.getProperty("line.separator", "\n"); ArrayList<String> alsItems = new ArrayList<String>(); boolean bStartMark = false; boolean bLine1Skipped = false; StringBuilder sdCurrentItem = new StringBuilder(); while (lineItr.hasNext()) { String sLine = lineItr.next().trim(); if (!bStartMark) { if (sLine.startsWith(".START_SEQUENCE")) { bStartMark = true; continue; } throw new IllegalStateException("Start mark not found."); } if (!bLine1Skipped) { bLine1Skipped = true; continue; } else if (!sLine.equals(".END_SEQUENCE")) { sdCurrentItem.append(sLine).append(LINE_SEP); } else { alsItems.add(sdCurrentItem.toString()); sdCurrentItem.setLength(0); bStartMark = false; bLine1Skipped = false; continue; } } for (String s : alsItems) { System.out.println("----------"); System.out.print(s); } }
From source file:me.camerongray.teamlocker.server.Server.java
public static void main(String[] args) throws PropertyVetoException, SQLException { ConnectionManager.initialise("localhost", "teamlocker", "teamlocker", "teamlocker"); before((request, response) -> {// w w w . j a v a 2 s .co m // Log request StringBuilder sb = new StringBuilder(); sb.append(request.requestMethod()); sb.append(" " + request.url()); sb.append(" " + request.body()); System.out.println(sb); if (request.headers("Authorization") == null) { response.header("WWW-Authenticate", "Basic"); halt(401); } RequestCredentials credentials = new RequestCredentials(request); if (!Auth.checkCredentials(credentials.username, credentials.password)) { ResponseBuilder.errorHalt(response, 401, "Incorrect username/password"); } }); get("/check_auth/", (request, response) -> { return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); get("/users/:userId/", (request, response) -> { DynaBean user = null; try (Database database = new Database(ConnectionManager.getConnection(request))) { if (request.params(":userId").equals("self")) { try { user = database.getUser((new RequestCredentials(request)).getUsername()); } catch (ObjectNotFoundException e) { ResponseBuilder.errorHalt(response, 404, "User not found"); } } else { Auth.enforceAdmin(request, response); try { user = database.getUser(Integer.parseInt(request.params(":userId"))); } catch (NumberFormatException e) { ResponseBuilder.errorHalt(response, 400, "User ID must be a number"); } catch (ObjectNotFoundException e) { ResponseBuilder.errorHalt(response, 404, "User not found"); } } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("user", ResponseBuilder.objectOf("id", (int) user.get("id"), "full_name", (String) user.get("full_name"), "username", (String) user.get("username"), "email", (String) user.get("email"), "auth_hash", (String) user.get("auth_hash"), "encrypted_private_key", (String) user.get("encrypted_private_key"), "public_key", (String) user.get("public_key"), "admin", (boolean) user.get("admin"), "pbkdf2_salt", (String) user.get("pbkdf2_salt"), "aes_iv", (String) user.get("aes_iv")))); }); get("/users/:userId/encrypted_aes_keys/", (request, response) -> { int userId; if (request.params(":userId").equals("self")) { userId = Auth.getCurrentUserId(request); } else { Auth.enforceAdmin(request, response); userId = Integer.parseInt(request.params(":userId")); } List<DynaBean> accountData; try (Database database = new Database(ConnectionManager.getConnection(request))) { accountData = database.getUserAccountData(userId); } ArrayList<JSONObject> aesKeyObjects = new ArrayList<>(); for (DynaBean accountDataItem : accountData) { aesKeyObjects.add(ResponseBuilder.objectOf("account_id", (int) accountDataItem.get("account_id"), "encrypted_aes_key", (String) accountDataItem.get("encrypted_aes_key"))); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("encrypted_aes_keys", ResponseBuilder.fromArrayList(aesKeyObjects))); }); get("/users/:userId/permissions/", (request, response) -> { Auth.enforceAdmin(request, response); List<DynaBean> permissions = new ArrayList<>(); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { permissions = database.getUserPermissions(Integer.parseInt(request.params(":userId"))); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "User ID must be a number"); } } ArrayList<JSONObject> responseObjects = new ArrayList<>(); for (DynaBean permission : permissions) { responseObjects.add(ResponseBuilder.objectOf("folder_id", (int) permission.get("folder_id"), "read", (boolean) permission.get("read"), "write", (boolean) permission.get("write"))); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("permissions", ResponseBuilder.fromArrayList(responseObjects))); }); delete("/users/:userId/permissions/", (request, response) -> { Auth.enforceAdmin(request, response); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.deleteUserPermissions(Integer.parseInt(request.params(":userId"))); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "User ID must be a number"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); post("/users/:userId/", (request, response) -> { Auth.enforceAdmin(request, response); int userId = -1; try { userId = Integer.parseInt(request.params(":userId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "User ID must be a number"); } JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "postUsers"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } try (Database database = new Database(ConnectionManager.getConnection(request))) { boolean usernameExists = true; try { DynaBean user = database.getUser(requestJson.getString("username")); if ((Integer) user.get("id") == userId) { usernameExists = false; } } catch (ObjectNotFoundException ex) { usernameExists = false; } if (usernameExists) { ResponseBuilder.errorHalt(response, 409, "A user with that username already exists"); } database.updateUser(userId, requestJson.getString("username"), requestJson.getString("full_name"), requestJson.getString("email"), requestJson.getBoolean("admin")); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); get("/users/", (request, response) -> { Auth.enforceAdmin(request, response); ArrayList<JSONObject> userObjects = new ArrayList<>(); try (Database database = new Database(ConnectionManager.getConnection(request))) { List<DynaBean> users = database.getAllUsers(); for (DynaBean user : users) { userObjects.add(ResponseBuilder.objectOf("id", (int) user.get("id"), "full_name", (String) user.get("full_name"), "username", (String) user.get("username"), "email", (String) user.get("email"), "auth_hash", (String) user.get("auth_hash"), "encrypted_private_key", (String) user.get("encrypted_private_key"), "public_key", (String) user.get("public_key"), "admin", (boolean) user.get("admin"), "pbkdf2_salt", (String) user.get("pbkdf2_salt"), "aes_iv", (String) user.get("aes_iv"))); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("users", ResponseBuilder.fromArrayList(userObjects))); }); put("/users/", (request, response) -> { JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "putUsers"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } int userId = -1; try (Database database = new Database(ConnectionManager.getConnection(request))) { boolean userExists = true; try { database.getUser(requestJson.getString("username")); } catch (ObjectNotFoundException ex) { userExists = false; } if (userExists) { ResponseBuilder.errorHalt(response, 409, "A user with that username already exists"); } userId = database.addUser(requestJson.getString("full_name"), requestJson.getString("username"), requestJson.getString("email"), BCrypt.hashpw(requestJson.getString("auth_key"), BCrypt.gensalt()), requestJson.getString("encrypted_private_key"), requestJson.getString("public_key"), requestJson.getBoolean("admin"), requestJson.getString("pbkdf2_salt"), requestJson.getString("aes_iv")); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("user_id", userId)); }); get("/folders/", (request, response) -> { ArrayList<JSONObject> folderObjects = new ArrayList<>(); try (Database database = new Database(ConnectionManager.getConnection(request))) { List<DynaBean> folders = database.getFolders((int) Auth.getCurrentUser(request).get("id")); for (DynaBean folder : folders) { folderObjects.add(ResponseBuilder.objectOf("id", (int) folder.get("id"), "name", (String) folder.get("name"), "read", (boolean) folder.get("read"), "write", (boolean) folder.get("write"))); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("folders", ResponseBuilder.fromArrayList(folderObjects))); }); put("/folders/", (request, response) -> { JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "putFolder"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } Auth.enforceAdmin(request, response); int folderId = -1; try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.getFolder(requestJson.getString("name")); ResponseBuilder.errorHalt(response, 409, "A folder with that name already exists"); } catch (ObjectNotFoundException ex) { // We don't care if it doesn't exist, we actually want this exception to be thrown! } folderId = database.addFolder(requestJson.getString("name")); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("folder_id", folderId)); }); post("/folders/:folderId/", (request, response) -> { int folderId = -1; try { folderId = Integer.parseInt(request.params(":folderId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_WRITE); JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "postFolders"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.updateFolder(folderId, requestJson.getString("name")); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Folder not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); // TODO - Replace with generic update user method post("/users/self/update_password/", (request, response) -> { JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "postUsersUpdatePassword"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.updateUserPassword(Auth.getCurrentUserId(request), requestJson.getString("encrypted_private_key"), requestJson.getString("aes_iv"), requestJson.getString("pbkdf2_salt"), BCrypt.hashpw(requestJson.getString("auth_key"), BCrypt.gensalt())); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "User not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); delete("/folders/:folderId/", (request, response) -> { int folderId = -1; try { folderId = Integer.parseInt(request.params(":folderId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_WRITE); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.deleteFolder(folderId); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Folder not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); get("/folders/:folderId/accounts/", (request, response) -> { int folderId = -1; try { folderId = Integer.parseInt(request.params(":folderId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_READ); ArrayList<JSONObject> accountObjects = new ArrayList<>(); try (Database database = new Database(ConnectionManager.getConnection(request))) { List<DynaBean> accounts = new ArrayList<>(); accounts = database.getFolderAccounts(folderId, Auth.getCurrentUserId(request)); for (DynaBean account : accounts) { accountObjects.add(ResponseBuilder.objectOf("id", (int) account.get("account_id"), "account_metadata", (String) account.get("account_metadata"), "encrypted_aes_key", (String) account.get("encrypted_aes_key"))); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("accounts", ResponseBuilder.fromArrayList(accountObjects))); }); get("/folders/:folderId/permissions/", (request, response) -> { Auth.enforceAdmin(request, response); List<DynaBean> permissions = new ArrayList<>(); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { permissions = database.getFolderPermissions(Integer.parseInt(request.params(":folderId"))); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } } ArrayList<JSONObject> responseObjects = new ArrayList<>(); for (DynaBean permission : permissions) { responseObjects.add(ResponseBuilder.objectOf("user_id", (int) permission.get("user_id"), "read", (boolean) permission.get("read"), "write", (boolean) permission.get("write"))); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("permissions", ResponseBuilder.fromArrayList(responseObjects))); }); post("/folders/:folderId/permissions/", (request, response) -> { Auth.enforceAdmin(request, response); int folderId = -1; try { folderId = Integer.parseInt(request.params(":folderId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } JSONObject requestJson = RequestJson.getValidated(request, "postFoldersPermissions"); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.getFolder(folderId); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Folder not found!"); } TransactionInterface transaction; try { transaction = new Transaction(database.getWrappedConnection()); } catch (ExistingOpenTransactionException ex) { transaction = new NullTransaction(); } try { database.deleteFolderPermissions(folderId); JSONArray permissions = requestJson.getJSONArray("permissions"); for (int i = 0; i < permissions.length(); i++) { JSONObject permission = permissions.getJSONObject(i); int userId = permission.getInt("user_id"); boolean read = permission.getBoolean("read"); boolean write = permission.getBoolean("write"); try { DynaBean user = database.getUser(userId); if ((boolean) user.get("admin")) { transaction.rollback(); ResponseBuilder.errorHalt(response, 400, "Trying to set permissions " + "for an administrator, administrators already have full permission."); } } catch (ObjectNotFoundException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 404, "User not found!"); } if (write && !read) { transaction.rollback(); ResponseBuilder.errorHalt(response, 400, "Users must be able " + "to read a folder if they are to write to it"); } if (!(write || read)) { database.deleteAccountDataForFolder(folderId, userId); } else { database.addPermission(folderId, userId, read, write); } } } catch (SQLException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 500, "Error updating permissions - " + ex); } transaction.commit(); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); get("/folders/:folderId/public_keys/", (request, response) -> { int folderId = -1; try { folderId = Integer.parseInt(request.params(":folderId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_WRITE); List<DynaBean> users; try (Database database = new Database(ConnectionManager.getConnection(request))) { users = database.getFolderUsers(folderId); } ArrayList<JSONObject> publicKeyObjects = new ArrayList<>(); for (DynaBean user : users) { publicKeyObjects.add(ResponseBuilder.objectOf("user_id", (int) user.get("id"), "public_key", (String) user.get("public_key"))); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("public_keys", ResponseBuilder.fromArrayList(publicKeyObjects))); }); get("/accounts/:accountId/", (request, response) -> { int accountId = -1; try { accountId = Integer.parseInt(request.params(":accountId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Account ID must be a number"); } Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_READ); DynaBean account = null; try (Database database = new Database(ConnectionManager.getConnection(request))) { try { account = database.getAccountData(accountId, Auth.getCurrentUserId(request)); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Account not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("account", ResponseBuilder.objectOf("account_metadata", (String) account.get("account_metadata"), "encrypted_aes_key", (String) account.get("encrypted_aes_key")))); }); delete("/accounts/:accountId/", (request, response) -> { int accountId = -1; try { accountId = Integer.parseInt(request.params(":accountId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Account ID must be a number"); } Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_WRITE); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.deleteAccount(accountId); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Account not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); post("/accounts/:accountId/", (request, response) -> { JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "postAccountsSingle"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, "JSON Validation Error - " + ex.getMessage()); } int accountId = -1; try { accountId = Integer.parseInt(request.params(":accountId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Account ID must be a number"); } Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_WRITE); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.getAccount(accountId); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Account not found"); } try { database.getFolder(requestJson.getInt("folder_id")); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Folder not found"); } TransactionInterface transaction; try { transaction = new Transaction(database.getWrappedConnection()); } catch (ExistingOpenTransactionException ex) { transaction = new NullTransaction(); } try { database.updateAccount(accountId, requestJson.getInt("folder_id")); JSONArray accountDataItems = requestJson.getJSONArray("encrypted_account_data"); for (int i = 0; i < accountDataItems.length(); i++) { JSONObject accountDataItem = accountDataItems.getJSONObject(i); int userId = accountDataItem.getInt("user_id"); database.deleteAccountData(accountId, userId); database.addAccountDataItem(accountId, userId, accountDataItem.getString("account_metadata"), accountDataItem.getString("password"), accountDataItem.getString("encrypted_aes_key")); } } catch (SQLException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 500, "Error saving account - " + ex); } catch (ObjectNotFoundException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 404, "Error saving account - Object Not Found"); } transaction.commit(); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); post("/accounts/", (request, response) -> { JSONObject requestJson = RequestJson.getValidated(request, "postAccountsBatch"); JSONArray accounts = requestJson.getJSONArray("accounts"); try (Database database = new Database(ConnectionManager.getConnection(request))) { TransactionInterface transaction; try { transaction = new Transaction(database.getWrappedConnection()); } catch (ExistingOpenTransactionException ex) { transaction = new NullTransaction(); } try { for (int i = 0; i < accounts.length(); i++) { JSONObject account = accounts.getJSONObject(i); int accountId = account.getInt("account_id"); try { if (!Auth.getAccountPermission(request, response, accountId, Auth.PERMISSION_WRITE)) { transaction.rollback(); ResponseBuilder.errorHalt(response, 403, "You do not have write permission for account " + accountId); } } catch (ObjectNotFoundException ex) { transaction.rollback(); ex.printStackTrace(); ResponseBuilder.errorHalt(response, 404, "Account not found"); } JSONArray accountDataItems = account.getJSONArray("encrypted_account_data"); for (int j = 0; j < accountDataItems.length(); j++) { JSONObject accountDataItem = accountDataItems.getJSONObject(j); int userId = accountDataItem.getInt("user_id"); database.deleteAccountData(accountId, userId); database.addAccountDataItem(accountId, userId, accountDataItem.getString("account_metadata"), accountDataItem.getString("password"), accountDataItem.getString("encrypted_aes_key")); } } } catch (SQLException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 500, "Error saving accounts - " + ex); } transaction.commit(); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); put("/accounts/", (request, response) -> { JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "putAccounts"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } Auth.enforceFolderPermission(request, response, requestJson.getInt("folder_id"), Auth.PERMISSION_WRITE); int accountId = -1; WrappedConnection connection = ConnectionManager.getConnection(request); try (Database database = new Database(connection)) { try { database.getFolder(requestJson.getInt("folder_id")); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Folder not found"); } TransactionInterface transaction; try { transaction = new Transaction(connection); } catch (ExistingOpenTransactionException ex) { transaction = new NullTransaction(); Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } try { accountId = database.addAccount(requestJson.getInt("folder_id")); JSONArray accountDataItems = requestJson.getJSONArray("encrypted_account_data"); for (int i = 0; i < accountDataItems.length(); i++) { JSONObject accountDataItem = accountDataItems.getJSONObject(i); database.addAccountDataItem(accountId, accountDataItem.getInt("user_id"), accountDataItem.getString("account_metadata"), accountDataItem.getString("password"), accountDataItem.getString("encrypted_aes_key")); } } catch (SQLException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 500, "Error adding account - " + ex); } transaction.commit(); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("account_id", accountId)); }); get("/accounts/:accountId/password/", (request, response) -> { int accountId = -1; try { accountId = Integer.parseInt(request.params(":accountId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Account ID must be a number"); } Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_READ); DynaBean account = null; try (Database database = new Database(ConnectionManager.getConnection(request))) { try { account = database.getAccountData(accountId, Auth.getCurrentUserId(request)); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Account not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("password", ResponseBuilder.objectOf("encrypted_password", (String) account.get("password"), "encrypted_aes_key", (String) account.get("encrypted_aes_key")))); }); put("/transaction/", (request, response) -> { Transaction transaction = TransactionStore.getTransaction(); return ResponseBuilder.build(response, ResponseBuilder.objectOf("transaction_id", transaction.getId())); }); post("/transaction/:transactionId/commit/", (request, response) -> { String transactionId = request.params(":transactionId"); try { Transaction transaction = TransactionStore.getTransaction(transactionId); transaction.commit(); transaction.getWrappedConnection().getConnection().close(); TransactionStore.forgetTransaction(transactionId); } catch (TransactionNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Transaction not found!"); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); post("/transaction/:transactionId/rollback/", (request, response) -> { String transactionId = request.params(":transactionId"); try { Transaction transaction = TransactionStore.getTransaction(transactionId); transaction.rollback(); transaction.getWrappedConnection().getConnection().close(); TransactionStore.forgetTransaction(transactionId); } catch (TransactionNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Transaction not found!"); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); exception(Exception.class, (e, request, response) -> { if (e.getClass().equals(TransactionNotFoundException.class)) { response.status(404); response.body(ResponseBuilder.objectOf("error", true, "message", "Transaction not found", "type", "transaction_not_found").toString()); } else { System.out.println("An unhandled exception occurred!"); System.out.println(e.toString()); e.printStackTrace(); response.status(500); response.type("application/json"); response.body(ResponseBuilder .objectOf("error", true, "message", "An unhandled server error occurred! - " + e.toString()) .toString()); } }); //TODO - Disable this in production! // spark.debug.DebugScreen.enableDebugScreen(); }
From source file:ProxyAdapter.java
/** * Usage example//from w w w . j ava 2 s . com */ public static void main(String[] args) throws Exception { //Create adapter for Appendable ProxyAdapter<Appendable> pa = new ProxyAdapter(Appendable.class) { private StringBuilder sb = new StringBuilder(); //Override only 2 methods: append and toString public Appendable append(char c) { System.out.println("Proxy append(char c) method. Append " + c); sb.append(c); return (Appendable) getProxy(); } public String toString() { return "Proxy toString method: " + sb; } }; final Appendable a = pa.getProxy(); a.append('1').append('2'); System.out.println("a.toString() = " + a.toString()); //this invocation fails because no method has been created a.append("Not implemented"); }
From source file:Naive.java
public static void main(String[] args) throws Exception { // Basic access authentication setup String key = "CHANGEME: YOUR_API_KEY"; String secret = "CHANGEME: YOUR_API_SECRET"; String version = "preview1"; // CHANGEME: the API version to use String practiceid = "000000"; // CHANGEME: the practice ID to use // Find the authentication path Map<String, String> auth_prefix = new HashMap<String, String>(); auth_prefix.put("v1", "oauth"); auth_prefix.put("preview1", "oauthpreview"); auth_prefix.put("openpreview1", "oauthopenpreview"); URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token"); HttpURLConnection conn = (HttpURLConnection) authurl.openConnection(); conn.setRequestMethod("POST"); // Set the Authorization request header String auth = Base64.encodeBase64String((key + ':' + secret).getBytes()); conn.setRequestProperty("Authorization", "Basic " + auth); // Since this is a POST, the parameters go in the body conn.setDoOutput(true);//from w w w.j a va 2 s.c om String contents = "grant_type=client_credentials"; DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(contents); wr.flush(); wr.close(); // Read the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); // Decode from JSON and save the token for later String response = sb.toString(); JSONObject authorization = new JSONObject(response); String token = authorization.get("access_token").toString(); // GET /departments HashMap<String, String> params = new HashMap<String, String>(); params.put("limit", "1"); // Set up the URL, method, and Authorization header URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?" + urlencode(params)); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Bearer " + token); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); JSONObject departments = new JSONObject(response); System.out.println(departments.toString()); // POST /appointments/{appointmentid}/notes params = new HashMap<String, String>(); params.put("notetext", "Hello from Java!"); url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + token); // POST parameters go in the body conn.setDoOutput(true); contents = urlencode(params); wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(contents); wr.flush(); wr.close(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); JSONObject note = new JSONObject(response); System.out.println(note.toString()); }
From source file:com.benasmussen.tools.testeditor.ExtractorCLI.java
public static void main(String[] args) throws Exception { HelpFormatter formatter = new HelpFormatter(); // cli options Options options = new Options(); options.addOption(CMD_OPT_INPUT, true, "Input file"); // options.addOption(CMD_OPT_OUTPUT, true, "Output file"); try {/* w w w .ja v a 2 s . c o m*/ // evaluate command line options CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(CMD_OPT_INPUT)) { // option value String optionValue = cmd.getOptionValue(CMD_OPT_INPUT); // input file File inputFile = new File(optionValue); // id extractor IdExtractor idExtractor = new IdExtractor(inputFile); Vector<Vector> data = idExtractor.parse(); // // TODO implement output folder // if (cmd.hasOption(CMD_OPT_OUTPUT)) // { // // file output // throw new Exception("Not implemented"); // } // else // { // console output System.out.println("Id;Value"); for (Vector vector : data) { StringBuilder sb = new StringBuilder(); if (vector.size() >= 1) { sb.append(vector.get(0)); } sb.append(";"); if (vector.size() >= 2) { sb.append(vector.get(1)); } System.out.println(sb.toString()); } // } } else { throw new IllegalArgumentException(); } } catch (ParseException e) { formatter.printHelp("ExtractorCLI", options); } catch (IllegalArgumentException e) { formatter.printHelp("ExtractorCLI", options); } }
From source file:com.asakusafw.generator.HadoopBulkLoaderDDLGenerator.java
/** * HadoopBulkLoader?????/*from w w w . j a va2s. c o m*/ * * @param args * ?? * @throws Exception * ?????? */ public static void main(String[] args) throws Exception { String outputTablesString = findVariable(ENV_BULKLOADER_TABLES, true); List<String> outputTableList = null; if (outputTablesString != null && !OUTPUT_TABLES_PROPERTY.equals(outputTablesString)) { String[] outputTables = outputTablesString.trim().split("\\s+"); outputTableList = Arrays.asList(outputTables); } String ddlTemplate; InputStream in = HadoopBulkLoaderDDLGenerator.class.getResourceAsStream(TEMPLATE_DDL_FILENAME); try { ddlTemplate = IOUtils.toString(in); } finally { in.close(); } StringBuilder sb = new StringBuilder(); for (String tableName : args) { if (outputTableList == null || outputTableList.contains(tableName)) { String tableddl = ddlTemplate.replaceAll(TABLENAME_REPLACE_STRING, tableName); sb.append(tableddl); } } String outputFilePath = findVariable(ENV_BULKLOADER_GENDDL, true); if (outputFilePath == null) { throw new RuntimeException( "ASAKUSA_BULKLOADER_TABLES???????"); } FileUtils.write(new File(outputFilePath), sb); }
From source file:baldrickv.s3streamingtool.S3StreamingTool.java
public static void main(String args[]) throws Exception { BasicParser p = new BasicParser(); Options o = getOptions();/*from w ww .j a v a 2 s .c o m*/ CommandLine cl = p.parse(o, args); if (cl.hasOption('h')) { HelpFormatter hf = new HelpFormatter(); hf.setWidth(80); StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("Upload:\n"); sb.append(" -u -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Download:\n"); sb.append(" -d -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Upload encrypted:\n"); sb.append(" -u -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Download encrypted:\n"); sb.append(" -d -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n"); sb.append("Cleanup in-progress multipart uploads\n"); sb.append(" -c -r creds -b my_bucket\n"); System.out.println(sb.toString()); hf.printHelp("See above", o); return; } int n = 0; if (cl.hasOption('d')) n++; if (cl.hasOption('u')) n++; if (cl.hasOption('c')) n++; if (cl.hasOption('m')) n++; if (n != 1) { System.err.println("Must specify at exactly one of -d, -u, -c or -m"); System.exit(-1); } if (cl.hasOption('m')) { //InputStream in = new java.io.BufferedInputStream(System.in,1024*1024*2); InputStream in = System.in; System.out.println(TreeHashGenerator.calculateTreeHash(in)); return; } require(cl, 'b'); if (cl.hasOption('d') || cl.hasOption('u')) { require(cl, 'f'); } if (cl.hasOption('z')) { require(cl, 'k'); } AWSCredentials creds = null; if (cl.hasOption('r')) { creds = Utils.loadAWSCredentails(cl.getOptionValue('r')); } else { if (cl.hasOption('i') && cl.hasOption('e')) { creds = new BasicAWSCredentials(cl.getOptionValue('i'), cl.getOptionValue('e')); } else { System.out.println("Must specify either credential file (-r) or AWS key ID and secret (-i and -e)"); System.exit(-1); } } S3StreamConfig config = new S3StreamConfig(); config.setEncryption(false); if (cl.hasOption('z')) { config.setEncryption(true); config.setSecretKey(Utils.loadSecretKey(cl.getOptionValue("k"))); } if (cl.hasOption("encryption-mode")) { config.setEncryptionMode(cl.getOptionValue("encryption-mode")); } config.setS3Bucket(cl.getOptionValue("bucket")); if (cl.hasOption("file")) { config.setS3File(cl.getOptionValue("file")); } if (cl.hasOption("threads")) { config.setIOThreads(Integer.parseInt(cl.getOptionValue("threads"))); } if (cl.hasOption("blocksize")) { String s = cl.getOptionValue("blocksize"); s = s.toUpperCase(); int multi = 1; int end = 0; while ((end < s.length()) && (s.charAt(end) >= '0') && (s.charAt(end) <= '9')) { end++; } int size = Integer.parseInt(s.substring(0, end)); if (end < s.length()) { String m = s.substring(end); if (m.equals("K")) multi = 1024; else if (m.equals("M")) multi = 1048576; else if (m.equals("G")) multi = 1024 * 1024 * 1024; else if (m.equals("KB")) multi = 1024; else if (m.equals("MB")) multi = 1048576; else if (m.equals("GB")) multi = 1024 * 1024 * 1024; else { System.out.println("Unknown suffix on block size. Only K,M and G understood."); System.exit(-1); } } size *= multi; config.setBlockSize(size); } Logger.getLogger("").setLevel(Level.FINE); S3StreamingDownload.log.setLevel(Level.FINE); S3StreamingUpload.log.setLevel(Level.FINE); config.setS3Client(new AmazonS3Client(creds)); config.setGlacierClient(new AmazonGlacierClient(creds)); config.getGlacierClient().setEndpoint("glacier.us-west-2.amazonaws.com"); if (cl.hasOption("glacier")) { config.setGlacier(true); config.setStorageInterface(new StorageGlacier(config.getGlacierClient())); } else { config.setStorageInterface(new StorageS3(config.getS3Client())); } if (cl.hasOption("bwlimit")) { config.setMaxBytesPerSecond(Double.parseDouble(cl.getOptionValue("bwlimit"))); } if (cl.hasOption('c')) { if (config.getGlacier()) { GlacierCleanupMultipart.cleanup(config); } else { S3CleanupMultipart.cleanup(config); } return; } if (cl.hasOption('d')) { config.setOutputStream(System.out); S3StreamingDownload.download(config); return; } if (cl.hasOption('u')) { config.setInputStream(System.in); S3StreamingUpload.upload(config); return; } }
From source file:com.yahoo.athenz.example.http.tls.client.HttpTLSClient.java
public static void main(String[] args) { // parse our command line to retrieve required input CommandLine cmd = parseCommandLine(args); final String url = cmd.getOptionValue("url"); final String keyPath = cmd.getOptionValue("key"); final String certPath = cmd.getOptionValue("cert"); final String trustStorePath = cmd.getOptionValue("trustStorePath"); final String trustStorePassword = cmd.getOptionValue("trustStorePassword"); // we are going to setup our service private key and // certificate into a ssl context that we can use with // our http client try {/*from w ww .ja v a 2 s.c o m*/ KeyRefresher keyRefresher = Utils.generateKeyRefresher(trustStorePath, trustStorePassword, certPath, keyPath); SSLContext sslContext = Utils.buildSSLContext(keyRefresher.getKeyManagerProxy(), keyRefresher.getTrustManagerProxy()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection(); con.setReadTimeout(15000); con.setDoOutput(true); con.connect(); try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) { StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println("Data output: " + sb.toString()); } } catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); ex.printStackTrace(); System.exit(1); } }
From source file:MainGeneratePicasaIniFile.java
public static void main(String[] args) { try {//w w w . ja v a 2 s.co m Calendar start = Calendar.getInstance(); start.set(1899, 11, 30, 0, 0); PicasawebService myService = new PicasawebService("My Application"); myService.setUserCredentials(args[0], args[1]); // Get a list of all entries URL metafeedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/" + args[0] + "?kind=album"); System.out.println("Getting Picasa Web Albums entries...\n"); UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class); // resultFeed. File root = new File(args[2]); File[] albuns = root.listFiles(); int j = 0; List<GphotoEntry> entries = resultFeed.getEntries(); for (int i = 0; i < entries.size(); i++) { GphotoEntry entry = entries.get(i); String href = entry.getHtmlLink().getHref(); String name = entry.getTitle().getPlainText(); for (File album : albuns) { if (album.getName().equals(name) && !href.contains("02?")) { File picasaini = new File(album, "Picasa.ini"); if (!picasaini.exists()) { StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append("[Picasa]\n"); builder.append("name="); builder.append(name); builder.append("\n"); builder.append("location="); Collection<Extension> extensions = entry.getExtensions(); for (Extension extension : extensions) { if (extension instanceof GphotoLocation) { GphotoLocation location = (GphotoLocation) extension; if (location.getValue() != null) { builder.append(location.getValue()); } } } builder.append("\n"); builder.append("category=Folders on Disk"); builder.append("\n"); builder.append("date="); String source = name.substring(0, 10); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); Date date = formater.parse(source); Calendar end = Calendar.getInstance(); end.setTime(date); builder.append(daysBetween(start, end)); builder.append(".000000"); builder.append("\n"); builder.append(args[0]); builder.append("_lh="); builder.append(entry.getGphotoId()); builder.append("\n"); builder.append("P2category=Folders on Disk"); builder.append("\n"); URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/" + args[0] + "/albumid/" + entry.getGphotoId()); AlbumFeed feed = myService.getFeed(feedUrl, AlbumFeed.class); for (GphotoEntry photo : feed.getEntries()) { builder.append("\n"); builder.append("["); builder.append(photo.getTitle().getPlainText()); builder.append("]"); builder.append("\n"); long id = Long.parseLong(photo.getGphotoId()); builder.append("IIDLIST_"); builder.append(args[0]); builder.append("_lh="); builder.append(Long.toHexString(id)); builder.append("\n"); } System.out.println(builder.toString()); IOUtils.write(builder.toString(), new FileOutputStream(picasaini)); j++; } } } } System.out.println(j); System.out.println("\nTotal Entries: " + entries.size()); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.github.codingtogenomic.CodingToGenomic.java
public static void main(String[] args) throws Exception { //parse commandline Options options = new Options(); CommandLineParser parser = new PosixParser(); String gene = new String(); String transcript = new String(); String species = "human"; boolean mapCdna = false; String coordinate = new String(); StringBuilder errorMsg = new StringBuilder(); try {/*from w w w . j a v a 2 s . c o m*/ options = getOptions(args); } catch (org.apache.commons.cli.ParseException ex) { System.err.println("Parsing failed. Reason: " + ex.getMessage()); System.exit(1); } CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { showHelp(options); } if (line.hasOption("gene")) { gene = line.getOptionValue("gene"); } else { if (!line.hasOption("transcript")) { errorMsg.append("Either --gene or --transcript argument is required\n"); } } if (line.hasOption("transcript")) { if (line.hasOption("gene")) { errorMsg.append("Please specify only one of " + "--gene or --transcript arguments, not both\n"); } else { transcript = line.getOptionValue("transcript"); if (line.hasOption("species")) { System.out.println("Ignoring --species option when using --transcript argument"); } } } if (line.hasOption("coordinate")) { coordinate = line.getOptionValue("coordinate"); } else { errorMsg.append("--coordinate argument is required\n"); } if (line.hasOption("species")) { species = line.getOptionValue("species").replaceAll("\\s+", "_"); } if (line.hasOption("b37")) { if (species.equalsIgnoreCase("human") || species.equalsIgnoreCase("homo sapiens")) { SERVER = GRCh37Server; } else { System.out.println("--b37 argument will be ignored - it can only be " + "used when human is the species of interest. Current species" + " is " + species + ".\n"); } } if (line.hasOption("noncoding")) { mapCdna = true; } if (errorMsg.length() > 0) { showHelp(options, errorMsg.toString(), 2); } int c = 0; boolean threePrimeUtr = false; String prefix = "c."; if (mapCdna) { prefix = "n."; try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } else if (coordinate.startsWith("*")) { threePrimeUtr = true; prefix = "c.*"; String coord = coordinate.replaceFirst("\\*", ""); try { c = Integer.parseInt(coord); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer or UTR coordinate", 2); } } else { try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } //got arguments String result; String header = "Input\tSymbol\tEnsemblGene\tEnsemblTranscript\tGenomicCoordinate"; if (!gene.isEmpty()) { IdParser idParser = new IdParser(gene); System.out.println("Interpretting " + gene + " as of type " + idParser.getIdentifierType()); if (idParser.isEnsemblId()) { if (line.hasOption("species")) { System.out.println("Ignoring --species option when searching Ensembl ID."); } if (idParser.isTranscript()) { result = codingToGenomicTranscript(gene, c, threePrimeUtr, mapCdna); } else if (idParser.isEnsp()) { result = codingToGenomicEnsp(gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicId(gene, c, threePrimeUtr, mapCdna); } } else { if (idParser.isTranscript()) { //append user input to beginning result = codingToGenomicXrefTranscript(species, gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicXref(species, gene, c, threePrimeUtr, mapCdna); } } if (idParser.isTranscript() || idParser.isEnsp()) { result = gene + ":" + prefix + c + "\t" + result; } else { result = convertGeneResult(result, gene, c, prefix); } } else { System.out.println("Searching for " + transcript + " as Ensembl transcript ID"); result = codingToGenomicTranscript(transcript, c, threePrimeUtr, mapCdna); //append user input to beginning result = transcript + ":" + prefix + c + "\t" + result; } System.out.println(header); System.out.println(result); }