List of usage examples for java.security CodeSource getLocation
public final URL getLocation()
From source file:biz.dfch.j.graylog.plugin.filter.metricsValidation.java
public metricsValidation() throws IOException, URISyntaxException { try {//from w ww . ja va 2 s . c om LOG.debug(String.format("[%d] Initialising plugin ...\r\n", Thread.currentThread().getId())); // get config file CodeSource codeSource = this.getClass().getProtectionDomain().getCodeSource(); URI uri = codeSource.getLocation().toURI(); // String path = uri.getSchemeSpecificPart(); // path would contain absolute path including jar file name with extension // String path = FilenameUtils.getPath(uri.getPath()); // path would contain relative path (no leading '/' and no jar file name String path = FilenameUtils.getPath(uri.getPath()); if (!path.startsWith("/")) { path = String.format("/%s", path); } String baseName = FilenameUtils.getBaseName(uri.getSchemeSpecificPart()); if (null == baseName || baseName.isEmpty()) { baseName = this.getClass().getPackage().getName(); } // get config values configurationFileName = FilenameUtils.concat(path, baseName + ".conf"); JSONParser jsonParser = new JSONParser(); LOG.info(String.format("Loading configuration file '%s' ...", configurationFileName)); Object object = jsonParser.parse(new FileReader(configurationFileName)); JSONObject jsonObject = (JSONObject) object; String pluginPriority = (String) jsonObject.get(DF_PLUGIN_PRIORITY); Boolean pluginDropMessage = (Boolean) jsonObject.get(DF_PLUGIN_DROP_MESSAGE); Boolean pluginDisabled = (Boolean) jsonObject.get(DF_PLUGIN_DISABLED); // metrics = (HashMap) jsonObject.get("metrics"); // String fieldName = "cpu.average"; // Set<String> keys = metrics.keySet(); // for(String key : keys) // { // Map metric = (Map) metrics.get(key); // LOG.info(String.format("%s [type %s] [range %s .. %s]", key, metric.get("type").toString(), metric.get("minValue").toString(), metric.get("maxValue").toString())); // } // set configuration Map<String, Object> map = new HashMap<>(); map.put(DF_PLUGIN_PRIORITY, pluginPriority); map.put(DF_PLUGIN_DROP_MESSAGE, pluginDropMessage); map.put(DF_PLUGIN_DISABLED, pluginDisabled); //map.put(DF_PLUGIN_METRICS, metrics); initialize(new Configuration(map)); } catch (IOException ex) { LOG.error(String.format("[%d] Initialising plugin FAILED. Filter will be disabled.\r\n%s\r\n", Thread.currentThread().getId(), ex.getMessage())); LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - IOException - Filter will be disabled."); ex.printStackTrace(); } catch (Exception ex) { LOG.error(String.format("[%d] Initialising plugin FAILED. Filter will be disabled.\r\n", Thread.currentThread().getId())); LOG.error("*** " + DF_PLUGIN_NAME + "::dfchBizExecScript() - Exception - Filter will be disabled."); ex.printStackTrace(); } }
From source file:com.relicum.ipsum.io.PropertyIO.java
/** * Gets all files in jar./*ww w . j av a 2 s . c om*/ * * @param clazz the clazz * @return the list of files and paths in jar */ default List<String> getAllFilesInJar(Class<?> clazz) { List<String> list = new ArrayList<>(); CodeSource src = clazz.getProtectionDomain().getCodeSource(); if (src != null) { try { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); while (true) { ZipEntry e = zip.getNextEntry(); if (e == null) break; String name = e.getName(); if (name.contains(".properties")) { list.add(name); System.out.println(name); } } zip.close(); jar = null; } catch (IOException e) { e.printStackTrace(); } } return list; }
From source file:org.openanzo.client.cli.AnzoConsole.java
AnzoConsole() { try {/*from w ww .j av a 2s . c o m*/ dcw = CommandLineInterface.DEFAULT_CONSOLE; if (dcw.cr != null) { dcw.cr.setBellEnabled(true); dcw.cr.setPrompt("Anzo>"); dcw.cr.setHistoryEnabled(true); } dcw.writeOutput( "Anzo Command Line Client. \nCopyright (c) 2009 Cambridge Semantics Inc and others. All rights reserved."); String version = null; if (CommandLineInterface.class.getProtectionDomain() != null && CommandLineInterface.class.getProtectionDomain().getCodeSource() != null && CommandLineInterface.class.getProtectionDomain().getCodeSource().getLocation() != null) { ProtectionDomain domain = CommandLineInterface.class.getProtectionDomain(); CodeSource source = domain.getCodeSource(); URL location = source.getLocation(); if (location != null) { File file = new File(location.toURI()); if (file.exists() && file.getName().toLowerCase().endsWith(".jar")) { JarFile jar = new JarFile(file); version = jar.getManifest().getMainAttributes().getValue("Bundle-Version"); if (version == null) { version = jar.getManifest().getMainAttributes().getValue("Implementation-Build"); } } } } if (version == null) { version = CommandLineInterface.class.getPackage().getImplementationVersion(); } dcw.writeOutput("Version: " + ((version == null) ? "Unknown" : version)); dcw.writeOutput("Type help for usage"); HashMap<String, Completer> completers = new HashMap<String, Completer>(); completers.put("exit", new NullCompleter()); completers.put("quit", new NullCompleter()); completers.put("connect", new NullCompleter()); completers.put("disconnect", new NullCompleter()); completers.put("trace", new StringsCompleter("on", "off")); Options global = CommandLineInterface.getGlobalOptions(); for (SubCommand sc : CommandLineInterface.subcommands) { String command = sc.getName(); ArrayList<String> subcommands = new ArrayList<String>(); for (Object o : sc.getOptions().getOptions()) { Option options = (Option) o; subcommands.add("-" + options.getOpt()); subcommands.add("--" + options.getLongOpt()); } for (Object o : global.getOptions()) { Option options = (Option) o; subcommands.add("-" + options.getOpt()); subcommands.add("--" + options.getLongOpt()); } completers.put(command, new StringsCompleter(subcommands)); } if (dcw.cr != null) { dcw.cr.addCompleter(new CLICompleter(completers)); } boolean showStackTrace = false; while (true) { String command = dcw.readLine("Anzo>"); if (command != null) { if (EXIT.toLowerCase().equals(command.trim().toLowerCase()) || QUIT.toLowerCase().equals(command.trim().toLowerCase())) { if (context != null && context.client != null && context.client.isConnected()) { context.client.disconnect(); context.client.close(); dcw.writeOutput("Disonnected from:" + context.host); } System.exit(0); } String arguments[] = stringToArgs(command); try { if (arguments.length > 0) { String subcommand = arguments[0]; if ("connect".equals(subcommand.toLowerCase())) { Options options = new Options(); CommandLineInterface.appendGlobalOptions(options); CommandLineParser parser = new PosixParser(); String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1, arguments.length); CommandLine cl = parser.parse(options, subcommandArgs); if (context == null) { context = CommandLineInterface.createContext(dcw, cl, options, arguments); } if (!context.client.isConnected()) { context.client.connect(); dcw.writeOutput("Connected to:" + context.host); } } else if ("disconnect".equals(subcommand.toLowerCase())) { if (context != null && context.client != null && context.client.isConnected()) { context.client.disconnect(); context.client.close(); dcw.writeOutput("Disonnected from:" + context.host); } else { dcw.writeOutput("Not connected to:" + context.host); } context = null; } else if ("trace".equals(subcommand.toLowerCase())) { String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1, arguments.length); if (subcommandArgs.length == 0) { dcw.writeOutput("Show Stack Trace:" + showStackTrace); } else { String flag = subcommandArgs[0]; if (flag.equals("on")) showStackTrace = true; else if (flag.equals("off")) showStackTrace = false; else showStackTrace = Boolean.parseBoolean(flag); } if (context != null) { context.showTrace = showStackTrace; } } else if ("version".equals(subcommand.toLowerCase())) { String header = CommandLineInterface.generateVersionHeader(); dcw.writeOutput(header); } else { CommandLineInterface.processCommand(context, false, arguments); } } } catch (AnzoException e) { if (e.getErrorCode() == ExceptionConstants.COMBUS.JMS_CONNECT_FAILED) { dcw.writeError("Connection failed."); if (showStackTrace) dcw.printException(e, showStackTrace); } else { dcw.printException(e, showStackTrace); } } catch (AnzoRuntimeException e) { dcw.printException(e, showStackTrace); } } } } catch (Exception e) { e.printStackTrace(); System.exit(0); } }
From source file:net.sourceforge.fullsync.cli.Main.java
@Override public void launchGui(Injector injector) throws Exception { String arch = "x86"; //$NON-NLS-1$ String osName = System.getProperty("os.name").toLowerCase(); //$NON-NLS-1$ String os = "unknown"; //$NON-NLS-1$ if (-1 != System.getProperty("os.arch").indexOf("64")) { //$NON-NLS-1$ //$NON-NLS-2$ arch = "x86_64"; //$NON-NLS-1$ }//from ww w . j a v a 2s . com if (-1 != osName.indexOf("linux")) { //$NON-NLS-1$ os = "gtk.linux"; //$NON-NLS-1$ } else if (-1 != osName.indexOf("windows")) { //$NON-NLS-1$ os = "win32.win32"; //$NON-NLS-1$ } else if (-1 != osName.indexOf("mac")) { //$NON-NLS-1$ os = "cocoa.macosx"; //$NON-NLS-1$ } CodeSource cs = getClass().getProtectionDomain().getCodeSource(); String libDirectory = cs.getLocation().toURI().toString().replaceAll("^(.*)/[^/]+\\.jar$", "$1/"); //$NON-NLS-1$ //$NON-NLS-2$ List<URL> jars = new ArrayList<>(); jars.add(new URL(libDirectory + "net.sourceforge.fullsync-fullsync-assets.jar")); //$NON-NLS-1$ jars.add(new URL(libDirectory + "net.sourceforge.fullsync-fullsync-ui.jar")); //$NON-NLS-1$ // add correct SWT implementation to the class-loader jars.add(new URL(libDirectory + String.format("org.eclipse.platform-org.eclipse.swt.%s.%s.jar", os, arch))); //$NON-NLS-1$ // instantiate an URL class-loader with the constructed class-path and load the UI URLClassLoader cl = new URLClassLoader(jars.toArray(new URL[jars.size()]), Main.class.getClassLoader()); Thread.currentThread().setContextClassLoader(cl); Class<?> cls = cl.loadClass("net.sourceforge.fullsync.ui.GuiController"); //$NON-NLS-1$ Method launchUI = cls.getDeclaredMethod("launchUI", Injector.class); //$NON-NLS-1$ launchUI.invoke(null, injector); }
From source file:com.haulmont.cuba.uberjar.ServerRunner.java
protected String getJarName() { CodeSource codeSource = ServerRunner.class.getProtectionDomain().getCodeSource(); if (codeSource != null) { File file = new File(codeSource.getLocation().getPath()); return file.getName(); }// w ww . j a v a2 s . co m return null; }
From source file:net.minecraftforge.fml.common.asm.FMLSanityChecker.java
@Override public Void call() throws Exception { CodeSource codeSource = getClass().getProtectionDomain().getCodeSource(); boolean goodFML = false; boolean fmlIsJar = false; if (codeSource.getLocation().getProtocol().equals("jar")) { fmlIsJar = true;/*from w w w . ja va 2 s . c o m*/ Certificate[] certificates = codeSource.getCertificates(); if (certificates != null) { for (Certificate cert : certificates) { String fingerprint = CertificateHelper.getFingerprint(cert); if (fingerprint.equals(FMLFINGERPRINT)) { FMLRelaunchLog.info("Found valid fingerprint for FML. Certificate fingerprint %s", fingerprint); goodFML = true; } else if (fingerprint.equals(FORGEFINGERPRINT)) { FMLRelaunchLog.info( "Found valid fingerprint for Minecraft Forge. Certificate fingerprint %s", fingerprint); goodFML = true; } else { FMLRelaunchLog.severe("Found invalid fingerprint for FML: %s", fingerprint); } } } } else { goodFML = true; } // Server is not signed, so assume it's good - a deobf env is dev time so it's good too boolean goodMC = FMLLaunchHandler.side() == Side.SERVER || !liveEnv; int certCount = 0; try { Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever", false, cl); codeSource = cbr.getProtectionDomain().getCodeSource(); } catch (Exception e) { // Probably a development environment, or the server (the server is not signed) goodMC = true; } JarFile mcJarFile = null; if (fmlIsJar && !goodMC && codeSource.getLocation().getProtocol().equals("jar")) { try { String mcPath = codeSource.getLocation().getPath().substring(5); mcPath = mcPath.substring(0, mcPath.lastIndexOf('!')); mcPath = URLDecoder.decode(mcPath, Charsets.UTF_8.name()); mcJarFile = new JarFile(mcPath, true); mcJarFile.getManifest(); JarEntry cbrEntry = mcJarFile.getJarEntry("net/minecraft/client/ClientBrandRetriever.class"); InputStream mcJarFileInputStream = mcJarFile.getInputStream(cbrEntry); try { ByteStreams.toByteArray(mcJarFileInputStream); } finally { IOUtils.closeQuietly(mcJarFileInputStream); } Certificate[] certificates = cbrEntry.getCertificates(); certCount = certificates != null ? certificates.length : 0; if (certificates != null) { for (Certificate cert : certificates) { String fingerprint = CertificateHelper.getFingerprint(cert); if (fingerprint.equals(MCFINGERPRINT)) { FMLRelaunchLog.info("Found valid fingerprint for Minecraft. Certificate fingerprint %s", fingerprint); goodMC = true; } } } } catch (Throwable e) { FMLRelaunchLog.log(Level.ERROR, e, "A critical error occurred trying to read the minecraft jar file"); } finally { Java6Utils.closeZipQuietly(mcJarFile); } } else { goodMC = true; } if (!goodMC) { FMLRelaunchLog.severe( "The minecraft jar %s appears to be corrupt! There has been CRITICAL TAMPERING WITH MINECRAFT, it is highly unlikely minecraft will work! STOP NOW, get a clean copy and try again!", codeSource.getLocation().getFile()); if (!Boolean.parseBoolean(System.getProperty("fml.ignoreInvalidMinecraftCertificates", "false"))) { FMLRelaunchLog.severe( "For your safety, FML will not launch minecraft. You will need to fetch a clean version of the minecraft jar file"); FMLRelaunchLog.severe( "Technical information: The class net.minecraft.client.ClientBrandRetriever should have been associated with the minecraft jar file, " + "and should have returned us a valid, intact minecraft jar location. This did not work. Either you have modified the minecraft jar file (if so " + "run the forge installer again), or you are using a base editing jar that is changing this class (and likely others too). If you REALLY " + "want to run minecraft in this configuration, add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings' in your launcher profile."); FMLCommonHandler.instance().exitJava(1, false); } else { FMLRelaunchLog.severe( "FML has been ordered to ignore the invalid or missing minecraft certificate. This is very likely to cause a problem!"); FMLRelaunchLog.severe( "Technical information: ClientBrandRetriever was at %s, there were %d certificates for it", codeSource.getLocation(), certCount); } } if (!goodFML) { FMLRelaunchLog.severe("FML appears to be missing any signature data. This is not a good thing"); } return null; }
From source file:com.github.wolf480pl.mias4j.core.runtime.BMClassLoader.java
protected Package copyPackage(Package pkg, CodeSource cs) { return definePackage(pkg.getName(), pkg.getSpecificationTitle(), pkg.getSpecificationVersion(), pkg.getSpecificationVendor(), pkg.getImplementationTitle(), pkg.getImplementationVersion(), pkg.getImplementationVendor(), pkg.isSealed() ? cs.getLocation() : null); }
From source file:org.apache.apex.common.util.JarHelper.java
public String getJar(Class<?> jarClass, boolean makeJarFromFolder) { String jar = null;/* ww w .j a v a 2 s .c om*/ final CodeSource codeSource = jarClass.getProtectionDomain().getCodeSource(); if (codeSource != null) { URL location = codeSource.getLocation(); jar = sourceToJar.get(location); if (jar == null) { // don't create jar file from folders multiple times if ("jar".equals(location.getProtocol())) { try { location = ((JarURLConnection) location.openConnection()).getJarFileURL(); } catch (IOException e) { throw new AssertionError("Cannot resolve jar file for " + jarClass, e); } } if ("file".equals(location.getProtocol())) { jar = location.getFile(); final File dir = new File(jar); if (dir.isDirectory()) { if (!makeJarFromFolder) { throw new AssertionError( "Cannot resolve jar file for " + jarClass + ". URL " + location); } try { jar = createJar("apex-", dir, false); } catch (IOException e) { throw new AssertionError( "Cannot resolve jar file for " + jarClass + ". URL " + location, e); } } } else { throw new AssertionError("Cannot resolve jar file for " + jarClass + ". URL " + location); } sourceToJar.put(location, jar); logger.debug("added sourceLocation {} as {}", location, jar); } if (jar == null) { throw new AssertionError("Cannot resolve jar file for " + jarClass); } } return jar; }
From source file:org.springframework.cloud.deployer.thin.ThinJarAppWrapper.java
protected final Archive createArchive() { try {//from ww w . ja v a 2s .co m ProtectionDomain protectionDomain = getClass().getProtectionDomain(); CodeSource codeSource = protectionDomain.getCodeSource(); URI location; location = (codeSource == null ? null : codeSource.getLocation().toURI()); String path = (location == null ? null : location.getSchemeSpecificPart()); if (path == null) { throw new IllegalStateException("Unable to determine code source archive"); } File root = new File(path); if (!root.exists()) { throw new IllegalStateException("Unable to determine code source archive from " + root); } return (root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root)); } catch (Exception e) { throw new IllegalStateException("Cannt create local archive", e); } }
From source file:org.zgis.wps.swat.AnnotatedSwatRunnerAlgorithm.java
/** * Gets the URI of the jar file this class is in. * * @return URI of jar file this class is in * @throws URISyntaxException/* w w w . j av a2 s .c o m*/ */ private URI getJarURI() throws URISyntaxException { final ProtectionDomain domain; final CodeSource source; final URL url; final URI uri; domain = this.getClass().getProtectionDomain(); source = domain.getCodeSource(); url = source.getLocation(); uri = url.toURI(); return (uri); }