public static void main(String[] args) { String response; String filetoUpload; if (args.length == 1) filetoUpload = args[0]; else filetoUpload = "/Users/aditya/Downloads/poc.pdf"; // Load the Properties Files Configs.loadProperties(); // Create a Entity Document which stores the details of the File EntityDocument entDoc = new EntityDocument("Twitter", Configs.getFolderId(), "png"); // Prepare the Post Request to be sent PostRequestBuilder req = new PostRequestBuilder(filetoUpload, entDoc); try { HttpService.uploadDoc(req.preparePostRequest()); // Read the Response received response = HttpService.readResponse(); // Convert to SFDCResponse Instance SFDCResponse sr = SFDCResponse.convertResponse(response); } catch (ClientProtocolException e) { // TODO Auto-generated catch block System.out.println("Error while sending the Post Request : "); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Error while sending the Post Request : "); e.printStackTrace(); } }
void _serializeNumber(String key, Number value) { NodeList elements = numberElements.getElementsByTagName(ENTRY_FLAG); final int size = elements.getLength(); for (int i = 0; i < size; ++i) { Element e = (Element) elements.item(i); Attr nameAttr = e.getAttributeNode(KEY_FLAG); if (nameAttr == null) { throw newMalformedKeyAttrException(Repository.NUMBER); } if (key.equals(nameAttr.getValue())) { Attr valueAttr = e.getAttributeNode(VALUE_FLAG); if (valueAttr == null) { throw newMalformedValueAttrException(key, Repository.NUMBER); } Attr typeAttr = e.getAttributeNode(TYPE_FLAG); if (typeAttr == null) { throw newMalformedTypeAttrException(key, Repository.NUMBER); } typeAttr.setValue(Configs.resolveNumberType(value).name()); valueAttr.setValue(value.toString()); return; } } // no existing element found Element element = xmlDoc.createElement(ENTRY_FLAG); element.setAttribute(KEY_FLAG, key); element.setAttribute(VALUE_FLAG, value.toString()); element.setAttribute(TYPE_FLAG, Configs.resolveNumberType(value).name()); numberElements.appendChild(element); }
/** * add source scanner to restart server when source change * * @param web * @param webAppClassPath * @param scanIntervalSeconds */ private static void initScanner(final WebAppContext web, final Configs config) { int scanIntervalSeconds = config.getScanIntervalSeconds(); final ArrayList<File> scanList = new ArrayList<File>(); System.err.println("init scanning folders..."); if (config.getScanlist() != null) { String[] items = config.getScanlist().split(File.pathSeparator); for (String item : items) { File f = new File(item); scanList.add(f); System.err.println("add to scan list:" + item); } } // startScanner Scanner scanner = new Scanner(); scanner.setScanInterval(scanIntervalSeconds); scanner.setScanDirs(scanList); scanner.setRecursive(true); scanner.setReportExistingFilesOnStartup(true); scanner.addListener(new RJRFileChangeListener(web, config)); System.err.println("Starting scanner at interval of " + scanIntervalSeconds + " seconds."); scanner.start(); }
/** * copy so lib to specify directory(/data/data/host_pack_name/pluginlib) * * @param dexPath plugin path * @param nativeLibDir nativeLibDir */ public void copyPluginSoLib(Context context, String dexPath, String nativeLibDir) { String cpuName = getCpuName(); String cpuArchitect = getCpuArch(cpuName); sNativeLibDir = nativeLibDir; Log.d(TAG, "cpuArchitect: " + cpuArchitect); long start = System.currentTimeMillis(); try { ZipFile zipFile = new ZipFile(dexPath); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.isDirectory()) { continue; } String zipEntryName = zipEntry.getName(); if (zipEntryName.endsWith(".so") && zipEntryName.contains(cpuArchitect)) { final long lastModify = zipEntry.getTime(); if (lastModify == Configs.getSoLastModifiedTime(context, zipEntryName)) { // exist and no change Log.d(TAG, "skip copying, the so lib is exist and not change: " + zipEntryName); continue; } mSoExecutor.execute(new CopySoTask(context, zipFile, zipEntry, lastModify)); } } } catch (IOException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); Log.d(TAG, "### copy so time : " + (end - start) + " ms"); }
@Override public void run() { try { writeSoFile2LibDir(); Configs.setSoLastModifiedTime(mContext, mZipEntry.getName(), mLastModityTime); Log.d(TAG, "copy so lib success: " + mZipEntry.getName()); } catch (IOException e) { Log.e(TAG, "copy so lib failed: " + e.toString()); e.printStackTrace(); } }
private static void initEclipseListener(final Configs configs) { // init eclipse hook if (configs.getEclipseListenerPort() != -1) { Thread eclipseListener = new Thread() { public void run() { try { while (true) { Thread.sleep(5000L); Socket sock = new Socket("127.0.0.1", configs.getEclipseListenerPort()); byte[] response = new byte[4]; sock.getInputStream().read(response); // @see runjettyrun.Plugin#enableListenter // TODO applied on Jetty7 and Jetty8 if (response[0] == 1 && response[1] == 2) { // it's ok! } else { // Eclipse crashs shutdownServer(); } } } catch (UnknownHostException e) { System.err.println("lost connection with Eclipse , shutting down."); shutdownServer(); } catch (IOException e) { System.err.println("lost connection with Eclipse , shutting down."); shutdownServer(); } catch (InterruptedException e) { System.err.println("lost connection with Eclipse , shutting down."); shutdownServer(); } }; }; eclipseListener.start(); } }
/** * Main function, starts the jetty server. * * @param args */ public static void main(String[] args) throws Exception { System.err.println("Running Jetty 6.1.26"); final Configs configs = new Configs(); configs.validation(); server = new Server(); initConnnector(server, configs); initWebappContext(server, configs); if (configs.getJettyXML() != null && !"".equals(configs.getJettyXML().trim())) { System.err.println("Loading Jetty.xml:" + configs.getJettyXML()); try { XmlConfiguration configuration = new XmlConfiguration(new File(configs.getJettyXML()).toURI().toURL()); configuration.configure(server); } catch (Exception ex) { System.err.println("Exception happened when loading Jetty.xml:"); ex.printStackTrace(); } } // configureScanner if (configs.getEnablescanner()) initScanner(web, configs); initEclipseListener(configs); initCommandListener(configs); try { server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); System.exit(100); } return; }
/** * Sets up the document for use. * * @param rv the {@code XMLConfig} to set up * @param xmlDoc * @return */ static XMLConfig readAndSetupEntriesImpl(final XMLConfig rv, final Document xmlDoc) { try { xmlDoc.setXmlStandalone(true); rv.xmlDoc = xmlDoc; Element root = xmlDoc.getDocumentElement(); if (root == null) { throw new ConfigException("missing root element"); } NodeList nodeList; Element repoElement; Node repoNode; NodeList elementNodes; int len; for (Repository repository : Repository.values()) { nodeList = root.getElementsByTagName(repository.getName()); len = nodeList.getLength(); if (len == 0) { throw Configs.newMissingRepoException(repository); } else if (len > 1) { throw Configs.newDuplicateRepoException(repository); } repoNode = nodeList.item(0); if (!(repoNode instanceof Element)) { throw newInvalidNodeClassException(Element.class); } repoElement = (Element) repoNode; switch (repository) { case NUMBER: rv.numberElements = repoElement; break; case BOOLEAN: rv.booleanElements = repoElement; break; case STRING: rv.stringElements = repoElement; break; } elementNodes = repoElement.getElementsByTagName(ENTRY_FLAG); len = elementNodes.getLength(); for (int j = 0; j < len; ++j) { Node n = elementNodes.item(j); if (n instanceof Element) { Element e = (Element) n; Attr nameAttr = e.getAttributeNode(KEY_FLAG); if (nameAttr == null) { throw newMalformedKeyAttrException(repository); } String key = nameAttr.getValue(); Attr valueAttr = e.getAttributeNode(VALUE_FLAG); if (valueAttr == null) { throw newMalformedValueAttrException(key, repository); } String value = valueAttr.getValue(); // Number uses a different format if (repository == Repository.NUMBER) { Attr typeAttr = e.getAttributeNode(TYPE_FLAG); if (typeAttr == null) { throw newMalformedValueAttrException(key, repository); } rv.flushedNumberElements.put( key, Configs.parseNumberFromType( value, Configs.numberTypeValueOf(typeAttr.getValue()))); continue; } if (repository == Repository.BOOLEAN) { rv.flushedBooleanElements.put(key, Configs.parseBoolean(value)); } else { rv.flushedStringElements.put(key, value); } } } } } catch (Configs.BooleanParsingException ex) { throw new ConfigException(ex); } catch (NumberFormatException ex) { throw new ConfigException(ex); } catch (DOMException ex) { throw new ConfigException(ex); } return rv; }
private Startpage(String title) { super(title); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); int frameWidth = 800; int frameHeight = 600; setSize(frameWidth, frameHeight); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); int x = (d.width - getSize().width) / 2; int y = (d.height - getSize().height) / 2; setLocation(x, y); setResizable(false); this.setLayout(null); image = (BufferedImage) ImageManager.get("Background"); Container c = new Container() { @Override public void paint(Graphics g) { g.drawImage(image, 0, 0, null); super.paint(g); } }; c.setBackground(new Color(0, 0, 0, 0)); this.setContentPane(c); names[0] = new JTextField(); mode[0] = new JComboBox<>(); names[1] = new JTextField(); mode[1] = new JComboBox<>(); names[2] = new JTextField(); mode[2] = new JComboBox<>(); names[3] = new JTextField(); mode[3] = new JComboBox<>(); names[0].setBounds(25, 300, 150, 25); names[0].setFont(new Font("Consolas", Font.PLAIN, 12)); names[0].setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); names[0].setBackground(Color.WHITE); names[0].setToolTipText("Enter your name, program!"); names[0].addActionListener( (ActionEvent evt) -> { Configs.setPlayerName(names[0].getText(), 1); }); this.add(names[0]); mode[0].setBounds(25, 275, 150, 25); mode[0].addItem(PlayerStartConfig.MODE.TWOKEY); mode[0].addItem(PlayerStartConfig.MODE.FOURKEY); mode[0].addItem(PlayerStartConfig.MODE.BOT); this.add(mode[0]); names[1].setBounds(225, 300, 150, 25); names[1].setFont(new Font("Consolas", Font.PLAIN, 12)); names[1].setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); names[1].setBackground(Color.WHITE); names[1].setToolTipText("Enter your name, program!"); names[1].addActionListener( (ActionEvent evt) -> { Configs.setPlayerName(names[1].getText(), 2); }); this.add(names[1]); mode[1].setBounds(225, 275, 150, 25); mode[1].addItem(PlayerStartConfig.MODE.TWOKEY); mode[1].addItem(PlayerStartConfig.MODE.FOURKEY); mode[1].addItem(PlayerStartConfig.MODE.BOT); this.add(mode[1]); names[2].setBounds(425, 300, 150, 25); names[2].setFont(new Font("Consolas", Font.PLAIN, 12)); names[2].setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); names[2].setBackground(Color.WHITE); names[2].setToolTipText("Enter your name, program!"); names[2].addActionListener( (ActionEvent evt) -> { Configs.setPlayerName(names[2].getText(), 3); }); this.add(names[2]); mode[2].setBounds(425, 275, 150, 25); mode[2].addItem(PlayerStartConfig.MODE.TWOKEY); mode[2].addItem(PlayerStartConfig.MODE.FOURKEY); mode[2].addItem(PlayerStartConfig.MODE.BOT); this.add(mode[2]); names[3].setBounds(625, 300, 150, 25); names[3].setFont(new Font("Consolas", Font.PLAIN, 12)); names[3].setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); names[3].setBackground(Color.WHITE); names[3].setToolTipText("Enter your name, program!"); names[3].addActionListener( (ActionEvent evt) -> { Configs.setPlayerName(names[3].getText(), 4); }); this.add(names[3]); mode[3].setBounds(625, 275, 150, 25); mode[3].addItem(PlayerStartConfig.MODE.TWOKEY); mode[3].addItem(PlayerStartConfig.MODE.FOURKEY); mode[3].addItem(PlayerStartConfig.MODE.BOT); this.add(mode[3]); Ok.setBounds(300, 352, 75, 25); Ok.setText("Ok"); Ok.setMargin(new Insets(2, 2, 2, 2)); Ok.addActionListener( (ActionEvent evt) -> { for (int i = 0; i < 4; i++) { Configs.setPlayerName(names[i].getText(), i + 1); Configs.setControlMode((PlayerStartConfig.MODE) mode[i].getSelectedItem(), i + 1); } setVisible(false); Tron.getInstance().startGame(); }); this.add(Ok); Back.setBounds(425, 352, 75, 25); Back.setText("Back"); Back.setMargin(new Insets(2, 2, 2, 2)); Back.addActionListener( (ActionEvent evt) -> { MainMenue.getInstance().setVisible(true); setVisible(false); }); this.add(Back); TRON.setBounds(320, 50, 160, 90); TRON.setText("TRON"); TRON.setFont(new Font("Consolas", Font.BOLD, 72)); TRON.setForeground(Color.WHITE); this.add(TRON); setVisible(true); }
public void setRandomQuestion() { String[] questions = Configs.getValues(Configs.greylistQuestionsFile); question = Integer.parseInt(questions[random.nextInt(questions.length)].split(":")[0]); }
public Config copyConfig(Configs configs, Config config, String destConfigName, Logger logger) throws PropertyVetoException, TransactionFailure { final Config destCopy = (Config) config.deepCopy(configs); if (systemproperties != null) { final Properties properties = GenericCrudCommand.convertStringToProperties(systemproperties, ':'); for (final Object key : properties.keySet()) { final String propName = (String) key; // cannot update a system property so remove it first List<SystemProperty> sysprops = destCopy.getSystemProperty(); for (SystemProperty sysprop : sysprops) { if (propName.equals(sysprop.getName())) { sysprops.remove(sysprop); break; } } SystemProperty newSysProp = destCopy.createChild(SystemProperty.class); newSysProp.setName(propName); newSysProp.setValue(properties.getProperty(propName)); destCopy.getSystemProperty().add(newSysProp); } } final String configName = destConfigName; destCopy.setName(configName); configs.getConfig().add(destCopy); copyOfConfig = destCopy; String srcConfig = ""; srcConfig = config.getName(); File configConfigDir = new File(env.getConfigDirPath(), configName); for (Config c : configs.getConfig()) { File existingConfigConfigDir = new File(env.getConfigDirPath(), c.getName()); if (!c.getName().equals(configName) && configConfigDir.equals(existingConfigConfigDir)) { throw new TransactionFailure( localStrings.getLocalString( "config.duplicate.dir", "Config {0} is trying to use the same directory as config {1}", configName, c.getName())); } } try { if (!(new File(configConfigDir, "docroot").mkdirs() && new File(configConfigDir, "lib/ext").mkdirs())) { throw new IOException( localStrings.getLocalString( "config.mkdirs", "error creating config specific directories")); } String srcConfigLoggingFile = env.getInstanceRoot().getAbsolutePath() + File.separator + "config" + File.separator + srcConfig + File.separator + ServerEnvironmentImpl.kLoggingPropertiesFileName; File src = new File(srcConfigLoggingFile); if (!src.exists()) { src = new File(env.getConfigDirPath(), ServerEnvironmentImpl.kLoggingPropertiesFileName); } File dest = new File(configConfigDir, ServerEnvironmentImpl.kLoggingPropertiesFileName); FileUtils.copy(src, dest); } catch (Exception e) { logger.log(Level.WARNING, ConfigApiLoggerInfo.copyConfigError, e.getLocalizedMessage()); } return destCopy; }
private static void initConnnector(Server server, Configs configObj) { SelectChannelConnector connector = new SelectChannelConnector(); // Don't set any host , or the port detection will failed. -_-# // connector.setHost("127.0.0.1"); connector.setPort(configObj.getPort()); if (configObj.getEnablessl() && configObj.getSslport() != null) { if (!available(configObj.getSslport())) { throw new IllegalStateException("SSL port :" + configObj.getSslport() + " already in use!"); } connector.setConfidentialPort(configObj.getSslport()); } server.addConnector(connector); if (configObj.getEnablessl() && configObj.getSslport() != null) initSSL( server, configObj.getSslport(), configObj.getKeystore(), configObj.getPassword(), configObj.getKeyPassword(), configObj.getNeedClientAuth()); }
private static void initWebappContext(Server server, Configs configs) throws IOException, URISyntaxException { web = new WebAppContext(); if (configs.getParentLoaderPriority()) { System.err.println("ParentLoaderPriority enabled"); web.setParentLoaderPriority(true); } web.setContextPath(configs.getContext()); System.err.println("Context path:" + configs.getContext()); web.setWar(configs.getWebAppDir()); /** open a way to set the configuration classes */ List<String> configurationClasses = configs.getConfigurationClassesList(); if (configurationClasses.size() != 0) { web.setConfigurationClasses(configurationClasses.toArray(new String[0])); for (String conf : configurationClasses) System.err.println("Enable config class:" + conf); } // Fix issue 7, File locking on windows/Disable Jetty's locking of // static files // http://code.google.com/p/run-jetty-run/issues/detail?id=7 // by disabling the use of the file mapped buffers. The default Jetty // behavior is // intended to provide a performance boost, but run-jetty-run is focused // on // development (especially debugging) of web apps, not high-performance // production // serving of static content. Therefore, I'm not worried about the // performance // degradation of this change. My only concern is that there might be a // need to // test this feature that I'm disabling. web.setInitParams( Collections.singletonMap("org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false")); if (configs.getWebAppClassPath() != null) { ProjectClassLoader loader = new ProjectClassLoader(web, configs.getWebAppClassPath(), configs.getExcludedclasspath()); web.setClassLoader(loader); } List<Resource> resources = new ArrayList<Resource>(); URL urlWebapp = new File(configs.getWebAppDir()).toURI().toURL(); Resource webapp = new FileResource(urlWebapp); resources.add(webapp); Map<String, String> map = configs.getResourceMap(); for (String key : map.keySet()) { /* * URL url = new File(map.get(key)).toURI().toURL(); Resource resource; try { resource = new FileResource(url); final ResourceHandler handler = new ResourceHandler(); handler.setBaseResource(resource); handler.setServer(server); handler.setContextPath(key); web.addHandler(handler); } catch (URISyntaxException e) { e.printStackTrace(); } */ resources.add(new VirtualResource(webapp, "/" + key, map.get(key))); // final WebAppContext js = new WebAppContext(); // js.setContextPath(key); // js.setResourceBase(map.get(key)); // or whatever the correct path is in your case // js.setParentLoaderPriority(true); // server.addHandler(js); } ResourceCollection webAppDirResources = new ResourceCollection(); webAppDirResources.setResources(resources.toArray(new Resource[0])); web.setBaseResource(webAppDirResources); server.addHandler(web); }