private void checkAndSend( boolean send, final String address, Object body, final SockJSSocket sock, final String replyAddress) { final Handler<Message> replyHandler; if (replyAddress != null) { replyHandler = new Handler<Message>() { public void handle(Message message) { // Note we don't check outbound matches for replies // Replies are always let through if the original message // was approved checkAddAccceptedReplyAddress(message.replyAddress); deliverMessage(sock, replyAddress, message); } }; } else { replyHandler = null; } if (log.isDebugEnabled()) { log.debug("Forwarding message to address " + address + " on event bus"); } if (send) { eb.send(address, body, replyHandler); } else { eb.publish(address, body); } }
public boolean pullInDependencies(String moduleName) { log.info("Attempting to pull in dependencies for module: " + moduleName); ModuleIdentifier modID = new ModuleIdentifier(moduleName); try { return doPullInDependencies(modRoot, modID); } catch (Exception e) { log.error("Failed to pull in dependencies", e); return false; } }
@Test public void testPutsNullObjectWithoutException() { log.debug( new JsonObject() .putObject("null", null) // this shouldn't cause a NullPointerException .encode()); log.debug( new JsonObject().putObject("null", new JsonObject().putString("foo", "bar")).encode()); }
@Test public void testJsonElementConversionWithoutException() { JsonElement objElement = new JsonObject().putString("foo", "bar"); JsonElement arrayElement = new JsonArray().addString("foo"); JsonObject retrievedObject = objElement.asObject(); JsonArray retrievedArray = arrayElement.asArray(); log.debug(retrievedObject.encode()); log.debug(retrievedArray.encode()); }
@Test public void testInsertJsonElementIntoJsonArrayWithouException() { JsonObject objElement = new JsonObject().putString("foo", "bar"); JsonArray arrayElement = new JsonArray().addString("foo"); /* Insert an Object */ log.debug(new JsonArray().addElement(objElement).encode()); /* Insert an Array */ log.debug(new JsonArray().addElement(arrayElement).encode()); }
public synchronized void uninstallModule(String moduleName) { log.info("Uninstalling module " + moduleName + " from directory " + modRoot); File modDir = new File(modRoot, moduleName); if (!modDir.exists()) { log.error("Cannot find module to uninstall"); } else { try { vertx.fileSystem().deleteSync(modDir.getAbsolutePath(), true); log.info("Module " + moduleName + " successfully uninstalled"); } catch (Exception e) { log.error("Failed to delete directory: " + e.getMessage()); } } }
private boolean checkModDirs() { if (!modRoot.exists()) { if (!modRoot.mkdir()) { log.error("Failed to create mods dir " + modRoot); return false; } } if (!systemModRoot.exists()) { if (!systemModRoot.mkdir()) { log.error("Failed to create sys mods dir " + modRoot); return false; } } return true; }
private boolean basicAuth(HttpServerRequest request, String encodedAuth) { byte[] authBytes = Base64.decodeBase64(encodedAuth); String decodedString = new String(authBytes); String[] splitAuth = StringUtils.split(StringUtils.trim(decodedString), ":"); // $NON-NLS-1$ if (splitAuth.length != 2) return false; if (fileBasicAuthData.containsKey(splitAuth[0])) { String storedHash = new String(Base64.decodeBase64(fileBasicAuthData.get(splitAuth[0]))); MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-256"); // $NON-NLS-1$ digest.update(splitAuth[1].getBytes()); String receivedHash = new String(digest.digest()); if (storedHash.equals(receivedHash)) { return true; } } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e.getCause()); } } request .response() .headers() .add( "WWW-Authenticate", "Basic realm=\"" + config.getRealm() + "\""); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return false; }
/** Called when a node leaves the cluster. */ private synchronized void doNodeLeft(final String nodeID) { log.info(String.format("%s - %s left the cluster", this, nodeID)); context.run( new Runnable() { @Override public void run() { // Redeploy any failed deployments. synchronized (deployments) { Collection<String> sdeploymentsInfo = deployments.get(group); for (final String sdeploymentInfo : sdeploymentsInfo) { final JsonObject deploymentInfo = new JsonObject(sdeploymentInfo); // If the deployment node is equal to the node that left the cluster then // remove the deployment from the deployments list and attempt to redeploy it. if (deploymentInfo.getString("node").equals(nodeID)) { // If the deployment is an HA deployment then attempt to redeploy it on this node. if (deployments.remove(group, sdeploymentInfo) && deploymentInfo.getBoolean("ha", false)) { doRedeploy(deploymentInfo); } } } } } }); }
private boolean doInstallMod(final ModuleIdentifier modID) { checkWorkerContext(); if (repos.isEmpty()) { log.warn("No repositories configured!"); return false; } if (locateModule(null, modID) != null) { log.error("Module is already installed"); return false; } ModuleZipInfo info = getModule(modID); if (info != null) { return unzipModule(modID, info, true); } return false; }
private boolean unzipModule( final ModuleIdentifier modID, final ModuleZipInfo zipInfo, boolean deleteZip) { // We synchronize to prevent a race whereby it tries to unzip the same module at the // same time (e.g. deployModule for the same module name has been called in parallel) String modName = modID.toString(); synchronized (modName.intern()) { if (!checkModDirs()) { return false; } File fdest = new File(modRoot, modName); File sdest = new File(systemModRoot, modName); if (fdest.exists() || sdest.exists()) { // This can happen if the same module is requested to be installed // at around the same time // It's ok if this happens log.warn("Module " + modID + " is already installed"); return true; } // Unzip into temp dir first File tdest = unzipIntoTmpDir(zipInfo, deleteZip); if (tdest == null) { return false; } // Check if it's a system module JsonObject conf = loadModuleConfig(modID, tdest); ModuleFields fields = new ModuleFields(conf); boolean system = fields.isSystem(); // Now copy it to the proper directory String moveFrom = tdest.getAbsolutePath(); try { vertx .fileSystem() .moveSync(moveFrom, system ? sdest.getAbsolutePath() : fdest.getAbsolutePath()); } catch (Exception e) { log.error("Failed to move module", e); return false; } log.info("Module " + modID + " successfully installed"); return true; } }
private void sendMessage(JsonObject msg) { EventLog.addEvent("Sending message: " + msg.encode()); try { vertx.eventBus().publish(TestBase.EVENTS_ADDRESS, msg); } catch (Exception e) { log.error("Failed to send message", e); } }
public void reportException(Throwable t) { Context ctx = getContext(); if (ctx != null) { ctx.reportException(t); } else { log.error(" default vertx Unhandled exception ", t); } }
void handleException(Exception e) { checkThread(); if (exceptionHandler != null) { exceptionHandler.handle(e); } else { log.error("Unhandled exception", e); } }
public void reportException(Throwable t) { if (deploymentContext != null) { deploymentContext.reportException(t); } else { t.printStackTrace(); log.error("context Unhandled exception", t); } }
private void doSendOrPub( final boolean send, final SockJSSocket sock, final String address, final JsonObject message) { final Object body = getMandatoryValue(message, "body"); final String replyAddress = message.getString("replyAddress"); if (log.isDebugEnabled()) { log.debug("Received msg from client in bridge. address:" + address + " message:" + body); } Match curMatch = checkMatches(true, address, body); if (curMatch.doesMatch) { if (curMatch.requiresAuth) { final String sessionID = message.getString("sessionID"); if (sessionID != null) { authorise( message, sessionID, new AsyncResultHandler<Boolean>() { public void handle(AsyncResult<Boolean> res) { if (res.succeeded()) { if (res.result) { cacheAuthorisation(sessionID, sock); checkAndSend(send, address, body, sock, replyAddress); } else { log.debug( "Inbound message for address " + address + " rejected because sessionID is not authorised"); } } else { log.error("Error in performing authorisation", res.exception); } } }); } else { log.debug( "Inbound message for address " + address + " rejected because it requires auth and sessionID is missing"); } } else { checkAndSend(send, address, body, sock, replyAddress); } } else { log.debug("Inbound message for address " + address + " rejected because there is no match"); } }
protected String escapeForJavaScript(String str) { try { str = StringEscapeUtils.escapeJavaScript(str); } catch (Exception e) { log.error("Failed to escape", e); str = null; } return str; }
private boolean doPullInDependencies(File modRoot, ModuleIdentifier modID) { File modDir = new File(modRoot, modID.toString()); if (!modDir.exists()) { log.error("Cannot find module to uninstall"); } JsonObject conf = loadModuleConfig(modID, modDir); if (conf == null) { log.error("Module " + modID + " does not contain a mod.json"); } ModuleFields fields = new ModuleFields(conf); List<String> mods = new ArrayList<>(); String includes = fields.getIncludes(); if (includes != null) { mods.addAll(Arrays.asList(parseIncludeString(includes))); } String deploys = fields.getDeploys(); if (deploys != null) { mods.addAll(Arrays.asList(parseIncludeString(deploys))); } if (!mods.isEmpty()) { File internalModsDir = new File(modDir, "mods"); if (!internalModsDir.exists()) { internalModsDir.mkdir(); } for (String modName : mods) { File internalModDir = new File(internalModsDir, modName); if (!internalModDir.exists()) { ModuleIdentifier theModID = new ModuleIdentifier(modName); ModuleZipInfo zipInfo = getModule(theModID); if (zipInfo.filename != null) { internalModDir.mkdir(); if (!unzipModuleData(internalModDir, zipInfo, true)) { return false; } else { log.info("Module " + modName + " successfully installed in mods dir of " + modName); // Now recurse so we bring in all of the deps doPullInDependencies(internalModsDir, theModID); } } } } } return true; }
private ModuleZipInfo getModule(ModuleIdentifier modID) { String fileName = generateTmpFileName() + ".zip"; for (RepoResolver resolver : repos) { if (resolver.getModule(fileName, modID)) { return new ModuleZipInfo(resolver.isOldStyle(), fileName); } } log.error("Module " + modID + " not found in any repositories"); return null; }
@Override public void handle(Message<JsonObject> message) { if (log.isDebugEnabled()) { log.debug( String.format( "%s - Received message %s", DefaultGroupManager.this, message.body().encode())); } String action = message.body().getString("action"); if (action != null) { switch (action) { case "ping": doPing(message); break; case "find": doFind(message); break; case "list": doList(message); break; case "select": doSelect(message); break; case "deploy": doDeploy(message); break; case "undeploy": doUndeploy(message); break; default: message.reply( new JsonObject() .putString("status", "error") .putString("message", "Invalid action " + action)); break; } } else { message.reply( new JsonObject() .putString("status", "error") .putString("message", "Must specify an action")); } }
/** Redeploys a deployment. */ private void doRedeploy(final JsonObject deploymentInfo) { if (deploymentInfo.getString("type").equals("module")) { log.info( String.format( "%s - redeploying module %s", DefaultGroupManager.this, deploymentInfo.getString("module"))); final CountDownLatch latch = new CountDownLatch(1); platform.deployModule( deploymentInfo.getString("module"), deploymentInfo.getObject("config", new JsonObject()), deploymentInfo.getInteger("instances", 1), createRedeployHandler(deploymentInfo, latch)); try { latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { } } else if (deploymentInfo.getString("type").equals("verticle")) { log.info( String.format( "%s - redeploying verticle %s", DefaultGroupManager.this, deploymentInfo.getString("main"))); final CountDownLatch latch = new CountDownLatch(1); if (deploymentInfo.getBoolean("worker", false)) { platform.deployWorkerVerticle( deploymentInfo.getString("main"), deploymentInfo.getObject("config", new JsonObject()), deploymentInfo.getInteger("instances", 1), deploymentInfo.getBoolean("multi-threaded"), createRedeployHandler(deploymentInfo, latch)); } else { platform.deployVerticle( deploymentInfo.getString("main"), deploymentInfo.getObject("config", new JsonObject()), deploymentInfo.getInteger("instances", 1), createRedeployHandler(deploymentInfo, latch)); } try { latch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { } } }
@Override public void handle(HttpServerRequest request) { request.response().setStatusCode(200); request.response().putHeader(WebStrings.CONTENT_TYPE, WebStrings.APP_JSON); log.info("Put Object Request"); String reqId = UUID.randomUUID().toString(); UploadEncObjectReplyHandler replyHandler = new UploadEncObjectReplyHandler(reqId, request); UploadEncObjectBodyHandler bodyHanlder = new UploadEncObjectBodyHandler(reqId, replyHandler); replyHandlers.put(reqId, replyHandler); bodyHandlers.put(reqId, bodyHanlder); request.bodyHandler(bodyHanlder); }
private String getMD5String(final String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = md.digest(str.getBytes("UTF-8")); StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(Integer.toHexString(b + 127)); } return sb.toString(); } catch (Exception e) { log.error("Failed to generate MD5 for iframe, If-None-Match headers will be ignored"); return null; } }
private String[] parseIncludeString(String sincludes) { sincludes = sincludes.trim(); if ("".equals(sincludes)) { log.error("Empty include string"); return null; } String[] arr = sincludes.split(","); if (arr != null) { for (int i = 0; i < arr.length; i++) { arr[i] = arr[i].trim(); } } return arr; }
@Override protected void prepareUser(User user, String userId, JsonObject data) { user.setUser(data.getString(principalAttributeName)); user.setAttributes(new HashMap<String, String>()); try { if (data.getString("lastName") != null && data.getString("firstName") != null) { user.getAttributes().put("nom", data.getString("lastName")); user.getAttributes().put("prenom", data.getString("firstName")); } if (data.getString("birthDate") != null) { user.getAttributes() .put( "dateNaissance", data.getString("birthDate").replaceAll("([0-9]+)-([0-9]+)-([0-9]+)", "$3/$2/$1")); } if (data.getString("postalCode") != null) { user.getAttributes().put("codePostal", data.getString("postalCode")); } String category = null; JsonArray types = data.getArray("type"); for (Object type : types.toList()) { switch (type.toString()) { case "Student": category = checkProfile(category, "National_1"); break; case "Teacher": category = checkProfile(category, "National_3"); break; case "Relative": category = checkProfile(category, "National_2"); break; case "Personnel": category = checkProfile(category, "National_4"); break; } } if (category != null) { user.getAttributes().put("categories", category); } } catch (Exception e) { log.error("Failed to transform User for Pronote"); } }
void handleResponse(HttpClientResponse resp) { try { if (resp.statusCode == 100) { if (continueHandler != null) { continueHandler.handle(null); } } else { respHandler.handle(resp); } } catch (Throwable t) { if (t instanceof Exception) { handleException((Exception) t); } else { log.error("Unhandled exception", t); } } }
private void loadRepos() { try (InputStream is = getClass().getClassLoader().getResourceAsStream(REPOS_FILE_NAME)) { if (is != null) { BufferedReader rdr = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rdr.readLine()) != null) { line = line.trim(); if (line.isEmpty() || line.startsWith("#")) { // blank line or comment continue; } int colonPos = line.indexOf(':'); if (colonPos == -1 || colonPos == line.length() - 1) { throw new IllegalArgumentException("Invalid repo: " + line); } String type = line.substring(0, colonPos); String repoID = line.substring(colonPos + 1); RepoResolver resolver; switch (type) { case "mavenLocal": resolver = new MavenLocalRepoResolver(repoID); type = "maven"; break; case "maven": resolver = new MavenRepoResolver(vertx, repoID); break; case "bintray": resolver = new BintrayRepoResolver(vertx, repoID); break; case "old": resolver = new OldRepoResolver(vertx, repoID); break; default: throw new IllegalArgumentException("Unknown repo type: " + type); } repos.add(resolver); } } } catch (IOException e) { log.error("Failed to load " + LANG_PROPS_FILE_NAME + " " + e.getMessage()); } }
private List<URL> getModuleClasspath(File modDir) { List<URL> urls = new ArrayList<>(); // Add the urls for this module try { urls.add(modDir.toURI().toURL()); File libDir = new File(modDir, "lib"); if (libDir.exists()) { File[] jars = libDir.listFiles(); for (File jar : jars) { URL jarURL = jar.toURI().toURL(); urls.add(jarURL); } } return urls; } catch (MalformedURLException e) { // Won't happen log.error("malformed url", e); return null; } }
private boolean unzipModuleData( final File directory, final ModuleZipInfo zipinfo, boolean deleteZip) { try (InputStream is = new BufferedInputStream(new FileInputStream(zipinfo.filename)); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is))) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String entryName = zipinfo.oldStyle ? removeTopDir(entry.getName()) : entry.getName(); if (!entryName.isEmpty()) { if (entry.isDirectory()) { new File(directory, entryName).mkdir(); } else { int count; byte[] buff = new byte[BUFFER_SIZE]; BufferedOutputStream dest = null; try { OutputStream fos = new FileOutputStream(new File(directory, entryName)); dest = new BufferedOutputStream(fos, BUFFER_SIZE); while ((count = zis.read(buff, 0, BUFFER_SIZE)) != -1) { dest.write(buff, 0, count); } dest.flush(); } finally { if (dest != null) { dest.close(); } } } } } } catch (Exception e) { log.error("Failed to unzip module", e); return false; } finally { directory.delete(); if (deleteZip) { new File(zipinfo.filename).delete(); } } return true; }
/* If you don't specify a trust store, and you haven't set system properties, the system will try to use either a file called jsssecacerts or cacerts in the JDK/JRE security directory. You can override this by specifying the javax.echo.ssl.trustStore system property If you don't specify a key store, and don't specify a system property no key store will be used You can override this by specifying the javax.echo.ssl.keyStore system property */ public SSLContext createContext( final String ksPath, final String ksPassword, final String tsPath, final String tsPassword, final boolean trustAll) { try { SSLContext context = SSLContext.getInstance("TLS"); KeyManager[] keyMgrs = ksPath == null ? null : getKeyMgrs(ksPath, ksPassword); TrustManager[] trustMgrs; if (trustAll) { trustMgrs = new TrustManager[] {createTrustAllTrustManager()}; } else { trustMgrs = tsPath == null ? null : getTrustMgrs(tsPath, tsPassword); } context.init(keyMgrs, trustMgrs, new SecureRandom()); return context; } catch (Exception e) { // TODO better logging log.error("Failed to create conext", e); throw new RuntimeException(e.getMessage()); } }