List of usage examples for java.lang InterruptedException toString
public String toString()
From source file:com.iiordanov.runsoft.bVNC.RemoteCanvas.java
/** * Create a view showing a remote desktop connection * @param context Containing context (activity) * @param bean Connection settings/*from ww w . j av a 2s. c o m*/ * @param setModes Callback to run on UI thread after connection is set up */ void initializeCanvas(ConnectionBean bean, Database db, final Runnable setModes) { this.setModes = setModes; connection = bean; database = db; decoder.setColorModel(COLORMODEL.valueOf(bean.getColorModel())); // Startup the connection thread with a progress dialog pd = ProgressDialog.show(getContext(), getContext().getString(R.string.info_progress_dialog_connecting), getContext().getString(R.string.info_progress_dialog_establishing), true, true, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { closeConnection(); handler.post(new Runnable() { public void run() { Utils.showFatalErrorMessage(getContext(), getContext().getString(R.string.info_progress_dialog_aborted)); } }); } }); // Make this dialog cancellable only upon hitting the Back button and not touching outside. pd.setCanceledOnTouchOutside(false); Thread t = new Thread() { public void run() { try { // Initialize SSH key if necessary if (connection.getConnectionType() == Constants.CONN_TYPE_SSH && connection.getSshHostKey().equals("") && Utils.isNullOrEmptry(connection.getIdHash())) { handler.sendEmptyMessage(Constants.DIALOG_SSH_CERT); // Block while user decides whether to accept certificate or not. // The activity ends if the user taps "No", so we block indefinitely here. synchronized (RemoteCanvas.this) { while (connection.getSshHostKey().equals("")) { try { RemoteCanvas.this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } if (isSpice) { startSpiceConnection(); } else if (isRdp) { startRdpConnection(); } else { startVncConnection(); } } catch (Throwable e) { if (maintainConnection) { Log.e(TAG, e.toString()); e.printStackTrace(); // Ensure we dismiss the progress dialog before we finish if (pd.isShowing()) pd.dismiss(); if (e instanceof OutOfMemoryError) { disposeDrawable(); showFatalMessageAndQuit(getContext().getString(R.string.error_out_of_memory)); } else { String error = getContext().getString(R.string.error_connection_failed); if (e.getMessage() != null) { if (e.getMessage().indexOf("SSH") < 0 && (e.getMessage().indexOf("authentication") > -1 || e.getMessage().indexOf("Unknown security result") > -1 || e.getMessage().indexOf("password check failed") > -1)) { error = getContext().getString(R.string.error_vnc_authentication); } error = error + "<br>" + e.getLocalizedMessage(); } showFatalMessageAndQuit(error); } } } } }; t.start(); clipboardMonitor = new ClipboardMonitor(getContext(), this); if (clipboardMonitor != null) { clipboardMonitorTimer = new Timer(); if (clipboardMonitorTimer != null) { try { clipboardMonitorTimer.schedule(clipboardMonitor, 0, 500); } catch (NullPointerException e) { } } } }
From source file:com.android.volley.NetworkDispatcher.java
@Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (true) { long startTimeMs = SystemClock.elapsedRealtime(); Request<?> request; try {//from w w w. j av a 2s .co m // Take a request from the queue. request = mQueue.take(); } catch (InterruptedException e) { // We may have been interrupted because it was time to quit. if (mQuit) { return; } continue; } try { request.addMarker("network-queue-take"); // If the request was cancelled already, do not perform the // network request. if (request.isCanceled()) { request.finish("network-discard-cancelled"); continue; } addTrafficStatsTag(request); // Perform the network request. NetworkResponse networkResponse = mNetwork.performRequest(request); request.addMarker("network-http-complete"); // If the server returned 304 AND we delivered a response already, // we're done -- don't deliver a second identical response. if (networkResponse.notModified && request.hasHadResponseDelivered()) { request.finish("not-modified"); continue; } // Parse the response here on the worker thread. Response<?> response = request.parseNetworkResponse(networkResponse); request.addMarker("network-parse-complete"); // Write to cache if applicable. // TODO: Only update cache metadata instead of entire record for 304s. if (request.shouldCache() && response.cacheEntry != null) { mCache.put(request.getCacheKey(), response.cacheEntry); request.addMarker("network-cache-written"); } // Post the response back. request.markDelivered(); mDelivery.postResponse(request, response); } catch (VolleyError volleyError) { volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); parseAndDeliverNetworkError(request, volleyError); } catch (Exception e) { VolleyLog.e(e, "Unhandled exception %s", e.toString()); VolleyError volleyError = new VolleyError(e); volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); mDelivery.postError(request, volleyError); } } }
From source file:org.apache.sqoop.manager.DirectPostgresqlManager.java
@Override /**/*from ww w . jav a 2 s.c o m*/ * Import the table into HDFS by using psql to pull the data out of the db * via COPY FILE TO STDOUT. */ public void importTable(com.cloudera.sqoop.manager.ImportJobContext context) throws IOException, ImportException { String tableName = context.getTableName(); SqoopOptions options = context.getOptions(); LOG.info("Beginning psql fast path import"); if (options.getFileLayout() != SqoopOptions.FileLayout.TextFile) { // TODO(aaron): Support SequenceFile-based load-in LOG.warn("File import layout" + options.getFileLayout() + " is not supported by"); LOG.warn("Postgresql direct import; import will proceed as text files."); } String commandFilename = null; String passwordFilename = null; Process p = null; AsyncSink sink = null; AsyncSink errSink = null; PerfCounters counters = new PerfCounters(); try { // Get the COPY TABLE command to issue, write this to a file, and pass // it in to psql with -f filename. Then make sure we delete this file // in our finally block. String copyCmd = getCopyCommand(tableName); commandFilename = writeCopyCommand(copyCmd); // Arguments to pass to psql on the command line. ArrayList<String> args = new ArrayList<String>(); // Environment to pass to psql. List<String> envp = Executor.getCurEnvpStrings(); // We need to parse the connect string URI to determine the database // name and the host and port. If the host is localhost and the port is // not specified, we don't want to pass this to psql, because we want to // force the use of a UNIX domain socket, not a TCP/IP socket. String connectString = options.getConnectString(); String databaseName = JdbcUrl.getDatabaseName(connectString); String hostname = JdbcUrl.getHostName(connectString); int port = JdbcUrl.getPort(connectString); if (null == databaseName) { throw new ImportException("Could not determine database name"); } LOG.info("Performing import of table " + tableName + " from database " + databaseName); args.add(PSQL_CMD); // requires that this is on the path. args.add("--tuples-only"); args.add("--quiet"); String username = options.getUsername(); if (username != null) { args.add("--username"); args.add(username); String password = options.getPassword(); if (null != password) { passwordFilename = writePasswordFile(password); // Need to send PGPASSFILE environment variable specifying // location of our postgres file. envp.add("PGPASSFILE=" + passwordFilename); } } args.add("--host"); args.add(hostname); if (port != -1) { args.add("--port"); args.add(Integer.toString(port)); } if (null != databaseName && databaseName.length() > 0) { args.add(databaseName); } // The COPY command is in a script file. args.add("-f"); args.add(commandFilename); // begin the import in an external process. LOG.debug("Starting psql with arguments:"); for (String arg : args) { LOG.debug(" " + arg); } // This writer will be closed by AsyncSink. SplittableBufferedWriter w = DirectImportUtils.createHdfsSink(options.getConf(), options, context); // Actually start the psql dump. p = Runtime.getRuntime().exec(args.toArray(new String[0]), envp.toArray(new String[0])); // read from the stdout pipe into the HDFS writer. InputStream is = p.getInputStream(); sink = new PostgresqlAsyncSink(w, options, counters); LOG.debug("Starting stream sink"); counters.startClock(); sink.processStream(is); errSink = new LoggingAsyncSink(LOG); errSink.processStream(p.getErrorStream()); } finally { // block until the process is done. LOG.debug("Waiting for process completion"); int result = 0; if (null != p) { while (true) { try { result = p.waitFor(); } catch (InterruptedException ie) { // interrupted; loop around. continue; } break; } } // Remove any password file we wrote if (null != passwordFilename) { if (!new File(passwordFilename).delete()) { LOG.error("Could not remove postgresql password file " + passwordFilename); LOG.error("You should remove this file to protect your credentials."); } } if (null != commandFilename) { // We wrote the COPY comand to a tmpfile. Remove it. if (!new File(commandFilename).delete()) { LOG.info("Could not remove temp file: " + commandFilename); } } // block until the stream sink is done too. int streamResult = 0; if (null != sink) { while (true) { try { streamResult = sink.join(); } catch (InterruptedException ie) { // interrupted; loop around. continue; } break; } } // Attempt to block for stderr stream sink; errors are advisory. if (null != errSink) { try { if (0 != errSink.join()) { LOG.info("Encountered exception reading stderr stream"); } } catch (InterruptedException ie) { LOG.info("Thread interrupted waiting for stderr to complete: " + ie.toString()); } } LOG.info("Transfer loop complete."); if (0 != result) { throw new IOException("psql terminated with status " + Integer.toString(result)); } if (0 != streamResult) { throw new IOException("Encountered exception in stream sink"); } counters.stopClock(); LOG.info("Transferred " + counters.toString()); } }
From source file:com.cloud.hypervisor.xenserver.resource.XenServerStorageProcessor.java
@Override public Answer copyTemplateToPrimaryStorage(final CopyCommand cmd) { final DataTO srcDataTo = cmd.getSrcTO(); final DataTO destDataTo = cmd.getDestTO(); final int wait = cmd.getWait(); final DataStoreTO srcDataStoreTo = srcDataTo.getDataStore(); final Connection conn = hypervisorResource.getConnection(); SR sr = null;// www . j a v a 2 s .co m boolean removeSrAfterCopy = false; try { if (srcDataStoreTo instanceof NfsTO && srcDataTo.getObjectType() == DataObjectType.TEMPLATE) { final NfsTO srcImageStore = (NfsTO) srcDataStoreTo; final TemplateObjectTO srcTemplateObjectTo = (TemplateObjectTO) srcDataTo; final String storeUrl = srcImageStore.getUrl(); final URI uri = new URI(storeUrl); final String tmplPath = uri.getHost() + ":" + uri.getPath() + "/" + srcDataTo.getPath(); final DataStoreTO destDataStoreTo = destDataTo.getDataStore(); boolean managed = false; String storageHost = null; String managedStoragePoolName = null; String managedStoragePoolRootVolumeName = null; String managedStoragePoolRootVolumeSize = null; String chapInitiatorUsername = null; String chapInitiatorSecret = null; if (destDataStoreTo instanceof PrimaryDataStoreTO) { final PrimaryDataStoreTO destPrimaryDataStoreTo = (PrimaryDataStoreTO) destDataStoreTo; final Map<String, String> details = destPrimaryDataStoreTo.getDetails(); if (details != null) { managed = Boolean.parseBoolean(details.get(PrimaryDataStoreTO.MANAGED)); if (managed) { storageHost = details.get(PrimaryDataStoreTO.STORAGE_HOST); managedStoragePoolName = details.get(PrimaryDataStoreTO.MANAGED_STORE_TARGET); managedStoragePoolRootVolumeName = details .get(PrimaryDataStoreTO.MANAGED_STORE_TARGET_ROOT_VOLUME); managedStoragePoolRootVolumeSize = details.get(PrimaryDataStoreTO.VOLUME_SIZE); chapInitiatorUsername = details.get(PrimaryDataStoreTO.CHAP_INITIATOR_USERNAME); chapInitiatorSecret = details.get(PrimaryDataStoreTO.CHAP_INITIATOR_SECRET); removeSrAfterCopy = Boolean .parseBoolean(details.get(PrimaryDataStoreTO.REMOVE_AFTER_COPY)); } } } if (managed) { final Map<String, String> details = new HashMap<String, String>(); details.put(DiskTO.STORAGE_HOST, storageHost); details.put(DiskTO.IQN, managedStoragePoolName); details.put(DiskTO.VOLUME_SIZE, managedStoragePoolRootVolumeSize); details.put(DiskTO.CHAP_INITIATOR_USERNAME, chapInitiatorUsername); details.put(DiskTO.CHAP_INITIATOR_SECRET, chapInitiatorSecret); sr = hypervisorResource.prepareManagedSr(conn, details); } else { final String srName = destDataStoreTo.getUuid(); final Set<SR> srs = SR.getByNameLabel(conn, srName); if (srs.size() != 1) { final String msg = "There are " + srs.size() + " SRs with same name: " + srName; s_logger.warn(msg); return new CopyCmdAnswer(msg); } else { sr = srs.iterator().next(); } } final String srUuid = sr.getUuid(conn); final String tmplUuid = copy_vhd_from_secondarystorage(conn, tmplPath, srUuid, wait); final VDI tmplVdi = getVDIbyUuid(conn, tmplUuid); final String uuidToReturn; final Long physicalSize = tmplVdi.getPhysicalUtilisation(conn); if (managed) { uuidToReturn = tmplUuid; tmplVdi.setNameLabel(conn, managedStoragePoolRootVolumeName); } else { final VDI snapshotVdi = tmplVdi.snapshot(conn, new HashMap<String, String>()); uuidToReturn = snapshotVdi.getUuid(conn); snapshotVdi.setNameLabel(conn, "Template " + srcTemplateObjectTo.getName()); tmplVdi.destroy(conn); } sr.scan(conn); try { Thread.sleep(5000); } catch (final InterruptedException e) { } final TemplateObjectTO newVol = new TemplateObjectTO(); newVol.setUuid(uuidToReturn); newVol.setPath(uuidToReturn); if (physicalSize != null) { newVol.setSize(physicalSize); } newVol.setFormat(ImageFormat.VHD); return new CopyCmdAnswer(newVol); } } catch (final Exception e) { final String msg = "Catch Exception " + e.getClass().getName() + " for template + " + " due to " + e.toString(); s_logger.warn(msg, e); return new CopyCmdAnswer(msg); } finally { if (removeSrAfterCopy && sr != null) { hypervisorResource.removeSR(conn, sr); } } return new CopyCmdAnswer("not implemented yet"); }
From source file:org.lockss.crawler.CrawlManagerImpl.java
void handReqToPool(CrawlReq req) { ArchivalUnit au = req.au;/*from ww w. j a va 2 s.c o m*/ CrawlManager.Callback cb = req.cb; Object cookie = req.cookie; ActivityRegulator.Lock lock = req.lock; if ((lock == null) || (lock.isExpired())) { lock = getNewContentLock(au); } else { lock.setNewActivity(ActivityRegulator.NEW_CONTENT_CRAWL, contentCrawlExpiration); } if (lock == null) { logger.debug("Not starting new content crawl due to activity lock: " + au); callCallback(cb, cookie, false, null); return; } Crawler crawler = null; CrawlRunner runner = null; try { crawler = makeFollowLinkCrawler(au); crawler.setCrawlReq(req); runner = new CrawlRunner(crawler, cb, cookie, SetUtil.set(lock), getNewContentRateLimiter(au), newContentStartRateLimiter); // To avoid race, must add to running crawls before starting // execution addToRunningCrawls(au, crawler); if (paramOdc) { // Add status first. execute might not return for a long time, and // we're expecting this crawl to be accepted. cmStatus.addCrawlStatus(crawler.getCrawlerStatus()); execute(runner); return; } else { // Add to status only if successfully queued or started. (No // race here; appearance in status might be delayed.) execute(runner); cmStatus.addCrawlStatus(crawler.getCrawlerStatus()); return; } } catch (InterruptedException e) { if (!isShuttingDown()) { // thrown by pool if can't execute (pool & queue full, or pool full // and no queue. In on-demand mode should throw only on shutdown.) String crawlerRunner = (crawler == null ? "no crawler" : crawler.toString()) + " " + (runner == null ? "no runner" : runner.toString()); if (e.getMessage() != null && e.getMessage().endsWith("Pool is blocked")) { logger.warning( "Couldn't start/schedule " + au + " crawl: " + e.toString() + " " + crawlerRunner); } else { logger.warning("Couldn't start/schedule " + au + " crawl" + " " + crawlerRunner, e); } } logger.debug2("Freeing crawl lock"); lock.expire(); removeFromRunningCrawls(crawler); callCallback(cb, cookie, false, null); return; } catch (RuntimeException e) { String crawlerRunner = (crawler == null ? "no crawler" : crawler.toString()) + " " + (runner == null ? "no runner" : runner.toString()); logger.error("Unexpected error attempting to start/schedule " + au + " crawl" + " " + crawlerRunner, e); logger.debug2("Freeing crawl lock"); lock.expire(); removeFromRunningCrawls(crawler); callCallback(cb, cookie, false, null); return; } }
From source file:com.streamsets.pipeline.stage.origin.salesforce.ForceStreamConsumer.java
public void start() throws StageException { LOG.info("Running streaming client"); try {/*from ww w .j a v a 2s . c o m*/ client = makeClient(); client.getChannel(Channel.META_HANDSHAKE).addListener(new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { LOG.info("[CHANNEL:META_HANDSHAKE]: " + message); // Pass these back to the source as we need to resubscribe or propagate the error try { messageQueue.put(message); } catch (InterruptedException e) { LOG.error(Errors.FORCE_10.getMessage(), e); Thread.currentThread().interrupt(); } } }); client.getChannel(Channel.META_CONNECT).addListener(new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { // Just log for troubleshooting - Bayeux client will rehandshake LOG.info("[CHANNEL:META_CONNECT]: " + message); } }); client.getChannel(Channel.META_SUBSCRIBE).addListener(new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { LOG.info("[CHANNEL:META_SUBSCRIBE]: " + message); if (!message.isSuccessful()) { String error = (String) message.get("error"); if (error != null) { try { if (isReplayIdExpired(error)) { // Retry subscription for all available events LOG.info("Event ID was not available. Subscribing for available events."); subscribeForNotifications(ForceSource.READ_EVENTS_FROM_START); return; } else { messageQueue.put(message); } } catch (InterruptedException e) { LOG.error(Errors.FORCE_10.getMessage(), e); Thread.currentThread().interrupt(); } } } subscribed.set(true); } }); client.handshake(); LOG.info("Waiting for handshake"); boolean handshaken = client.waitFor(10 * 1000, BayeuxClient.State.CONNECTED); if (!handshaken) { LOG.error("Failed to handshake: " + client); throw new StageException(Errors.FORCE_09, "Timed out waiting for handshake"); } } catch (Exception e) { LOG.error("Exception making client", e.toString(), e); throw new StageException(Errors.FORCE_09, e); } }
From source file:org.apache.accumulo.tserver.tablet.Tablet.java
void initiateClose(boolean saveState, boolean queueMinC, boolean disableWrites) { if (!saveState && queueMinC) { throw new IllegalArgumentException( "Not saving state on close and requesting minor compactions queue does not make sense"); }/* w w w . j av a 2 s.co m*/ log.debug("initiateClose(saveState=" + saveState + " queueMinC=" + queueMinC + " disableWrites=" + disableWrites + ") " + getExtent()); MinorCompactionTask mct = null; synchronized (this) { if (isClosed() || isClosing()) { String msg = "Tablet " + getExtent() + " already " + closeState; throw new IllegalStateException(msg); } // enter the closing state, no splits, minor, or major compactions can start // should cause running major compactions to stop closeState = CloseState.CLOSING; this.notifyAll(); // determines if inserts and queries can still continue while minor compacting if (disableWrites) { closeState = CloseState.CLOSED; } // wait for major compactions to finish, setting closing to // true should cause any running major compactions to abort while (isMajorCompactionRunning()) { try { this.wait(50); } catch (InterruptedException e) { log.error(e.toString()); } } while (updatingFlushID) { try { this.wait(50); } catch (InterruptedException e) { log.error(e.toString()); } } if (!saveState || getTabletMemory().getMemTable().getNumEntries() == 0) { return; } getTabletMemory().waitForMinC(); try { mct = prepareForMinC(getFlushID(), MinorCompactionReason.CLOSE); } catch (NoNodeException e) { throw new RuntimeException(e); } if (queueMinC) { getTabletResources().executeMinorCompaction(mct); return; } } // do minor compaction outside of synch block so that tablet can be read and written to while // compaction runs mct.run(); }
From source file:org.apache.accumulo.tserver.tablet.Tablet.java
synchronized void completeClose(boolean saveState, boolean completeClose) throws IOException { if (!isClosing() || isCloseComplete() || closeCompleting) { throw new IllegalStateException("closeState = " + closeState); }//from ww w. j av a2s. c o m log.debug("completeClose(saveState=" + saveState + " completeClose=" + completeClose + ") " + getExtent()); // ensure this method is only called once, also guards against multiple // threads entering the method at the same time closeCompleting = true; closeState = CloseState.CLOSED; // modify dataSourceDeletions so scans will try to switch data sources and fail because the tablet is closed dataSourceDeletions.incrementAndGet(); for (ScanDataSource activeScan : activeScans) { activeScan.interrupt(); } // wait for reads and writes to complete while (writesInProgress > 0 || activeScans.size() > 0) { try { this.wait(50); } catch (InterruptedException e) { log.error(e.toString()); } } getTabletMemory().waitForMinC(); if (saveState && getTabletMemory().getMemTable().getNumEntries() > 0) { try { prepareForMinC(getFlushID(), MinorCompactionReason.CLOSE).run(); } catch (NoNodeException e) { throw new RuntimeException(e); } } if (saveState) { // at this point all tablet data is flushed, so do a consistency check RuntimeException err = null; for (int i = 0; i < 5; i++) { try { closeConsistencyCheck(); err = null; } catch (RuntimeException t) { err = t; log.error("Consistency check fails, retrying " + t); sleepUninterruptibly(500, TimeUnit.MILLISECONDS); } } if (err != null) { ProblemReports.getInstance(tabletServer).report(new ProblemReport(extent.getTableId(), ProblemType.TABLET_LOAD, this.extent.toString(), err)); log.error( "Tablet closed consistency check has failed for " + this.extent + " giving up and closing"); } } try { getTabletMemory().getMemTable().delete(0); } catch (Throwable t) { log.error("Failed to delete mem table : " + t.getMessage(), t); } getTabletMemory().close(); // close map files getTabletResources().close(); log.log(TLevel.TABLET_HIST, extent + " closed"); tableConfiguration.getNamespaceConfiguration().removeObserver(configObserver); tableConfiguration.removeObserver(configObserver); if (completeClose) closeState = CloseState.COMPLETE; }
From source file:org.kuali.test.runner.execution.HttpRequestOperationExecution.java
/** * //from w w w .j a v a2 s .co m * @param configuration * @param platform * @param testWrapper * @throws TestException */ @Override public void execute(KualiTestConfigurationDocument.KualiTestConfiguration configuration, Platform platform, KualiTestWrapper testWrapper) throws TestException { HtmlRequestOperation reqop = getOperation().getHtmlRequestOperation(); try { try { int delay = configuration.getDefaultTestWaitInterval(); if (testWrapper.getUseTestEntryTimes()) { delay = reqop.getDelay(); } Thread.sleep(delay); } catch (InterruptedException ex) { } ; TestExecutionContext tec = getTestExecutionContext(); tec.setCurrentOperationIndex(Integer.valueOf(getOperation().getIndex())); tec.setCurrentTest(testWrapper); WebRequest request = new WebRequest(new URL(reqop.getUrl()), HttpMethod.valueOf(reqop.getMethod())); request.setAdditionalHeader(Constants.TEST_OPERATION_INDEX, "" + getOperation().getIndex()); boolean multiPart = Utils.isMultipart(reqop); boolean urlFormEncoded = Utils.isUrlFormEncoded(reqop); if (reqop.getRequestHeaders() != null) { for (RequestHeader hdr : reqop.getRequestHeaders().getHeaderArray()) { if (HttpHeaders.CONTENT_TYPE.equals(hdr.getName())) { if (!multiPart) { request.setAdditionalHeader(hdr.getName(), hdr.getValue()); } } else { request.setAdditionalHeader(hdr.getName(), hdr.getValue()); } } } boolean requestSubmitted = false; if (request.getHttpMethod().equals(HttpMethod.POST)) { String params = Utils.getContentParameterFromRequestOperation(reqop); List<NameValuePair> nvplist = new ArrayList<NameValuePair>(); if (StringUtils.isNotBlank(params)) { if (urlFormEncoded) { nvplist = tec.getWebClient() .getUpdatedParameterList(Utils.getNameValuePairsFromUrlEncodedParams(params)); } else if (multiPart) { nvplist = tec.getWebClient() .getUpdatedParameterList(Utils.getNameValuePairsFromMultipartParams(params)); } } tec.setLastHttpSubmitElementName(null); HtmlElement submit = null; // this is a hack to handle KC backdoor login - no submit is available // so the logic attempts to wait for a specified time to find the submit // which really slows down the test if (!isBackdoorLogin(request)) { submit = tec.getWebClient().findFormSubmitElement(nvplist); } // see if we can find a submit element, if we can then // use click() call to submit if (submit != null) { tec.getWebClient().populateFormElements(tec, nvplist); tec.setLastHttpSubmitElementName(getSubmitElementName(submit)); submit.click(); requestSubmitted = true; } else { request.setRequestParameters(nvplist); } } // if we have not loaded web request to this point - load now if (!requestSubmitted) { tec.getWebClient().getPage(request); } } catch (IOException ex) { Throwable t = ex.getCause(); LOG.error(ex.toString(), ex); if ((t != null) && (t instanceof TestException)) { throw (TestException) t; } else { String uri = Constants.UNKNOWN; if (reqop != null) { uri = reqop.getUrl(); } throw new TestException("An IOException occured while processing http request: " + uri + ", error: " + ex.toString(), getOperation(), ex); } } }
From source file:com.sssemil.advancedsettings.MainService.java
@Override public void onCreate() { super.onCreate(); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mDisplayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE); mDisplayManager.registerDisplayListener(this, null); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(mReceiver, filter); filter = new IntentFilter(); filter.addAction("android.intent.action.ACTION_SHUTDOWN"); registerReceiver(mReceiverOnPowerOff, filter); int timeout = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(this) .getString("screen_timeout_settings", String.valueOf( Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 0)))); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, timeout); }/*from w w w. j av a 2 s. c o m*/ String app = mSharedPreferences.getString("on_theatre_mode_launch_app", "null"); if (!app.equals("null") && !Utils.isPackageInstalled(app, this, 0)) { mSharedPreferences.edit().putString("on_theatre_mode_launch_app", "null").apply(); } new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); } try { Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(MainService.this) .getString("screen_timeout_settings", String.valueOf(Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 0))))); } catch (SecurityException e) { e.printStackTrace(); } } }).start(); //language settings provider installer new Thread(new Runnable() { @Override public void run() { try { if (!Utils.isPackageInstalled("sssemil.com.languagesettingsprovider", MainService.this, LANG_PROVIDER_VERSION_CODE)) { File apk = new File(Environment.getExternalStorageDirectory(), "wear_languagesettingsprovider-release.apk"); if (apk.exists()) { Log.i(TAG, "apk exists"); apk.delete(); } InputStream inputStream = getAssets().open("wear_languagesettingsprovider-release.apk"); FileOutputStream file = new FileOutputStream(apk); byte buf[] = new byte[4096]; int len = inputStream.read(buf); while (len > 0) { file.write(buf, 0, len); len = inputStream.read(buf); } file.close(); if (apk.exists()) { Log.i(TAG, "installing...."); ShellUtils.CommandResult result = ShellUtils .execCommand("su -c pm install -r " + apk.getPath(), true); if (result.errorMsg == null) { Log.i(TAG, "done"); } else { Log.e(TAG, "failed?"); } } } } catch (IOException e) { e.printStackTrace(); } } }).start(); //vibration intensity stuff try { int amp = Integer.parseInt(mSharedPreferences.getString("vibration_intensity", String.valueOf(Utils.getDeviceCfg(MainService.this).vibroIntensetyDefault))); ProcessBuilder pb = new ProcessBuilder("su", "-c", "echo", amp + ">", Utils.getDeviceCfg(MainService.this).vibroIntensetyPath); pb.start().waitFor(); } catch (InterruptedException | IOException | NullPointerException e) { Log.d(TAG, "catch " + e.toString() + " hit in run", e); } /*new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000); int i = Settings.Global.getInt(getContentResolver(), "theater_mode_on"); Log.i("theater_mode_on", String.valueOf(i)); } catch (Settings.SettingNotFoundException | InterruptedException e) { e.printStackTrace(); } } } }).start();*/ GlobalContentObserver contentObserver = new GlobalContentObserver(new Handler()); this.getApplicationContext().getContentResolver() .registerContentObserver(android.provider.Settings.Global.CONTENT_URI, true, contentObserver); }