List of usage examples for java.lang Object wait
public final native void wait(long timeoutMillis) throws InterruptedException;
From source file:org.apache.cxf.dosgi.systests.common.AbstractListenerHookServiceListenerTest.java
private void verifyGreeterResponse(FutureTask<Map<GreetingPhrase, String>> task, Object mutex) throws Exception { Map<GreetingPhrase, String> greetings = null; synchronized (mutex) { while (task == null) { mutex.wait(500); }//from w ww . j a va 2 s . c o m greetings = task.get(); } assertEquals("Fred", greetings.get(new GreetingPhrase("Hello"))); }
From source file:io.github.microcks.service.TestService.java
private void waitSomeRandomMS(int min, int max) { Object semaphore = new Object(); long timeout = ThreadLocalRandom.current().nextInt(min, max + 1); synchronized (semaphore) { try {/*from w ww . j av a 2 s . c o m*/ semaphore.wait(timeout); } catch (Exception e) { log.debug("waitSomeRandomMS semaphore was interrupted"); } } }
From source file:io.github.microcks.web.SoapController.java
@RequestMapping(value = "/{service}/{version}", method = RequestMethod.POST) public ResponseEntity<?> execute(@PathVariable("service") String serviceName, @PathVariable("version") String version, @RequestParam(value = "validate", required = false) Boolean validate, @RequestParam(value = "delay", required = false) Long delay, @RequestBody String body) { log.info("Servicing mock response for service [{}, {}]", serviceName, version); log.debug("Request body: " + body); long startTime = System.currentTimeMillis(); // Retrieve service and correct operation. Service service = serviceRepository.findByNameAndVersion(serviceName, version); Operation rOperation = null;/* ww w.j a va2 s . co m*/ for (Operation operation : service.getOperations()) { // Enhancement : try getting operation from soap:body directly! String openingPattern = "(.*):Body>(\\s*)<(\\w+):" + operation.getInputName() + ">(.*)"; String closingPattern = "(.*)</(\\w+):" + operation.getInputName() + ">(\\s*)</(\\w+):Body>(.*)"; Pattern op = Pattern.compile(openingPattern, Pattern.DOTALL); Pattern cp = Pattern.compile(closingPattern, Pattern.DOTALL); if (op.matcher(body).matches() && cp.matcher(body).matches()) { rOperation = operation; break; } } if (rOperation != null) { log.debug("Found a valid operation with rules: {}", rOperation.getDispatcherRules()); if (validate != null && validate) { log.debug("Soap message validation is turned on, validating..."); try { List<XmlError> errors = SoapMessageValidator.validateSoapMessage(rOperation.getInputName(), service.getXmlNS(), body, resourceUrl + service.getName() + "-" + version + ".wsdl", true); log.debug("SoapBody validation errors: " + errors.size()); // Return a 400 http code with errors. if (errors != null && errors.size() > 0) { return new ResponseEntity<Object>(errors, HttpStatus.BAD_REQUEST); } } catch (Exception e) { log.error("Error during Soap validation", e); } } Response response = null; String dispatchCriteria = null; // Depending on dispatcher, evaluate request with rules. if (DispatchStyles.QUERY_MATCH.equals(rOperation.getDispatcher())) { dispatchCriteria = getDispatchCriteriaFromXPathEval(rOperation, body); } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) { dispatchCriteria = getDispatchCriteriaFromScriptEval(rOperation, body); } log.debug("Dispatch criteria for finding response is {}", dispatchCriteria); List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria( IdBuilder.buildOperationId(service, rOperation), dispatchCriteria); if (!responses.isEmpty()) { response = responses.get(0); } // Setting delay to default one if not set. if (delay == null && rOperation.getDefaultDelay() != null) { delay = rOperation.getDefaultDelay(); } if (delay != null && delay > -1) { log.debug("Mock delay is turned on, waiting if necessary..."); long duration = System.currentTimeMillis() - startTime; if (duration < delay) { Object semaphore = new Object(); synchronized (semaphore) { try { semaphore.wait(delay - duration); } catch (Exception e) { log.debug("Delay semaphore was interrupted"); } } } log.debug("Delay now expired, releasing response !"); } // Publish an invocation event before returning. MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version, response.getName(), new Date(startTime), startTime - System.currentTimeMillis()); applicationContext.publishEvent(event); log.debug("Mock invocation event has been published"); // Set Content-Type to "text/xml". HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.valueOf("text/xml;charset=UTF-8")); return new ResponseEntity<Object>(response.getContent(), responseHeaders, HttpStatus.OK); } return new ResponseEntity<Object>(HttpStatus.NOT_FOUND); }
From source file:io.github.microcks.web.DynamicMockRestController.java
private void waitForDelay(Long since, Long delay, MockContext mockContext) { // Setting delay to default one if not set. if (delay == null && mockContext.operation.getDefaultDelay() != null) { delay = mockContext.operation.getDefaultDelay(); }//from w w w .j a va 2 s . co m if (delay != null && delay > -1) { log.debug("Mock delay is turned on, waiting if necessary..."); long duration = System.currentTimeMillis() - since; if (duration < delay) { Object semaphore = new Object(); synchronized (semaphore) { try { semaphore.wait(delay - duration); } catch (Exception e) { log.debug("Delay semaphore was interrupted"); } } } log.debug("Delay now expired, releasing response !"); } // Publish an invocation event before returning. MockInvocationEvent event = new MockInvocationEvent(this, mockContext.service.getName(), mockContext.service.getVersion(), "DynamicMockRestController", new Date(since), since - System.currentTimeMillis()); applicationContext.publishEvent(event); log.debug("Mock invocation event has been published"); }
From source file:com.zapp.library.merchant.test.TestUtils.java
/** * Change orientation of given activity and wait until the popup re-appears. * * @param activity The activity to rotate. * @param newOrientation The new orientation to change to. * @throws InterruptedException If thread synchronisation is interrupted. * @return The new activity after orientation change. *///w ww.j av a 2s. c o m @SuppressWarnings({ "SynchronizationOnLocalVariableOrMethodParameter", "UnconditionalWait", "WaitNotInLoop", "SameParameterValue" }) public static FragmentActivity changeOrientationWithPopup(@NonNull final FragmentActivity activity, final int newOrientation) throws InterruptedException { final Object monitor = new Object(); final Wrapper<FragmentActivity> wrapper = new Wrapper<>(activity); activity.setRequestedOrientation(newOrientation); //wait until the popup re-appears Espresso.onView(ViewMatchers.withId(R.id.pbba_popup_container)).perform(ViewActions.click()); activity.runOnUiThread(new Runnable() { @SuppressWarnings("NakedNotify") @Override public void run() { final Collection<Activity> activities = ActivityLifecycleMonitorRegistry.getInstance() .getActivitiesInStage(Stage.RESUMED); final int numberOfActivities = activities.size(); if (numberOfActivities != 1) { throw new IllegalStateException( String.format(Locale.ENGLISH, "activities.size() = %d", numberOfActivities)); } final TestActivity landscapeActivity = (TestActivity) activities.iterator().next(); wrapper.setObject(landscapeActivity); synchronized (monitor) { //noinspection NakedNotify monitor.notifyAll(); } } }); synchronized (monitor) { //wait for popup callback re-connect on the UI thread. monitor.wait(WAIT_TIMEOUT_MS); } return wrapper.getObject(); }
From source file:io.github.microcks.web.RestController.java
@RequestMapping(value = "/{service}/{version}/**") public ResponseEntity<?> execute(@PathVariable("service") String serviceName, @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay, @RequestBody(required = false) String body, HttpServletRequest request) { log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version, request.getRequestURI(), request.getMethod()); log.debug("Request body: " + body); long startTime = System.currentTimeMillis(); // Extract resourcePath for matching with correct operation. String requestURI = request.getRequestURI(); String serviceAndVersion = null; String resourcePath = null;/* www .j a va2 s . co m*/ try { // Build the encoded URI fragment to retrieve simple resourcePath. serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version; resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length()); } catch (UnsupportedEncodingException e1) { return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR); } log.info("Found resourcePath: " + resourcePath); Service service = serviceRepository.findByNameAndVersion(serviceName, version); Operation rOperation = null; for (Operation operation : service.getOperations()) { // Select operation based onto Http verb (GET, POST, PUT, etc ...) if (operation.getMethod().equals(request.getMethod().toUpperCase())) { // ... then check is we have a matching resource path. if (operation.getResourcePaths().contains(resourcePath)) { rOperation = operation; break; } } } if (rOperation != null) { log.debug("Found a valid operation {} with rules: {}", rOperation.getName(), rOperation.getDispatcherRules()); Response response = null; String uriPattern = getURIPattern(rOperation.getName()); String dispatchCriteria = null; // Depending on dispatcher, evaluate request with rules. if (DispatchStyles.SEQUENCE.equals(rOperation.getDispatcher())) { dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath); } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) { ScriptEngineManager sem = new ScriptEngineManager(); try { // Evaluating request with script coming from operation dispatcher rules. ScriptEngine se = sem.getEngineByExtension("groovy"); SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request); dispatchCriteria = (String) se.eval(rOperation.getDispatcherRules()); } catch (Exception e) { log.error("Error during Script evaluation", e); } } // New cases related to services/operations/messages coming from a postman collection file. else if (DispatchStyles.URI_PARAMS.equals(rOperation.getDispatcher())) { String fullURI = request.getRequestURL() + "?" + request.getQueryString(); dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(), fullURI); } else if (DispatchStyles.URI_PARTS.equals(rOperation.getDispatcher())) { dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath); } else if (DispatchStyles.URI_ELEMENTS.equals(rOperation.getDispatcher())) { dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath); String fullURI = request.getRequestURL() + "?" + request.getQueryString(); dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(), fullURI); } log.debug("Dispatch criteria for finding response is {}", dispatchCriteria); List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria( IdBuilder.buildOperationId(service, rOperation), dispatchCriteria); if (!responses.isEmpty()) { response = responses.get(0); } if (response != null) { // Setting delay to default one if not set. if (delay == null && rOperation.getDefaultDelay() != null) { delay = rOperation.getDefaultDelay(); } if (delay != null && delay > -1) { log.debug("Mock delay is turned on, waiting if necessary..."); long duration = System.currentTimeMillis() - startTime; if (duration < delay) { Object semaphore = new Object(); synchronized (semaphore) { try { semaphore.wait(delay - duration); } catch (Exception e) { log.debug("Delay semaphore was interrupted"); } } } log.debug("Delay now expired, releasing response !"); } // Publish an invocation event before returning. MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version, response.getName(), new Date(startTime), startTime - System.currentTimeMillis()); applicationContext.publishEvent(event); log.debug("Mock invocation event has been published"); HttpStatus status = (response.getStatus() != null ? HttpStatus.valueOf(Integer.parseInt(response.getStatus())) : HttpStatus.OK); // Deal with specific headers (content-type and redirect directive). HttpHeaders responseHeaders = new HttpHeaders(); if (response.getMediaType() != null) { responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8")); } // Adding other generic headers (caching directives and so on...) if (response.getHeaders() != null) { for (Header header : response.getHeaders()) { if ("Location".equals(header.getName())) { // We should process location in order to make relative URI specified an absolute one from // the client perspective. String location = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/rest" + serviceAndVersion + header.getValues().iterator().next(); responseHeaders.add(header.getName(), location); } else { if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) { responseHeaders.put(header.getName(), new ArrayList<>(header.getValues())); } } } } return new ResponseEntity<Object>(response.getContent(), responseHeaders, status); } return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<Object>(HttpStatus.NOT_FOUND); }
From source file:org.sufficientlysecure.keychain.service.PassphraseCacheService.java
/** * Gets a cached passphrase from memory by sending an intent to the service. This method is * designed to wait until the service returns the passphrase. * * @param context//from ww w . j av a2s. com * @param keyId * @return passphrase or null (if no passphrase is cached for this keyId) */ public static String getCachedPassphrase(Context context, long keyId) { Log.d(TAG, "getCachedPassphrase() get masterKeyId for " + keyId); Intent intent = new Intent(context, PassphraseCacheService.class); intent.setAction(ACTION_PASSPHRASE_CACHE_GET); final Object mutex = new Object(); final Bundle returnBundle = new Bundle(); HandlerThread handlerThread = new HandlerThread("getPassphraseThread"); handlerThread.start(); Handler returnHandler = new Handler(handlerThread.getLooper()) { @Override public void handleMessage(Message message) { if (message.obj != null) { String passphrase = ((Bundle) message.obj).getString(EXTRA_PASSPHRASE); returnBundle.putString(EXTRA_PASSPHRASE, passphrase); } synchronized (mutex) { mutex.notify(); } // quit handlerThread getLooper().quit(); } }; // Create a new Messenger for the communication back Messenger messenger = new Messenger(returnHandler); intent.putExtra(EXTRA_KEY_ID, keyId); intent.putExtra(EXTRA_MESSENGER, messenger); // send intent to this service context.startService(intent); // Wait on mutex until passphrase is returned to handlerThread synchronized (mutex) { try { mutex.wait(3000); } catch (InterruptedException e) { } } if (returnBundle.containsKey(EXTRA_PASSPHRASE)) { return returnBundle.getString(EXTRA_PASSPHRASE); } else { return null; } }
From source file:org.sonatype.nexus.testsuite.obr.ObrITSupport.java
protected void deployUsingObrIntoFelix(final String repoId) throws Exception { final File felixHome = util.resolveFile("target/org.apache.felix.main.distribution-3.2.2"); final File felixRepo = util.resolveFile("target/felix-local-repository"); final File felixConfig = testData().resolveFile("felix.properties"); // ensure we have an obr.xml final Content content = content(); final Location obrLocation = new Location(repoId, ".meta/obr.xml"); content.download(obrLocation, new File(testIndex().getDirectory("downloads"), repoId + "-obr.xml")); FileUtils.deleteDirectory(new File(felixHome, "felix-cache")); FileUtils.deleteDirectory(new File(felixRepo, ".meta")); final ProcessBuilder pb = new ProcessBuilder("java", "-Dfelix.felix.properties=" + felixConfig.toURI(), "-jar", "bin/felix.jar"); pb.directory(felixHome);//from w ww . j a va 2 s . co m pb.redirectErrorStream(true); final Process p = pb.start(); final Object lock = new Object(); final Thread t = new Thread(new Runnable() { public void run() { // just a safeguard, if felix get stuck kill everything try { synchronized (lock) { lock.wait(5 * 1000 * 60); } } catch (final InterruptedException e) { // ignore } p.destroy(); } }); t.setDaemon(true); t.start(); synchronized (lock) { final InputStream input = p.getInputStream(); final OutputStream output = p.getOutputStream(); waitFor(input, "g!"); output.write(("obr:repos add " + nexus().getUrl() + "content/" + obrLocation.toContentPath() + "\r\n") .getBytes()); output.flush(); waitFor(input, "g!"); output.write(("obr:repos remove http://felix.apache.org/obr/releases.xml\r\n").getBytes()); output.flush(); waitFor(input, "g!"); output.write(("obr:repos list\r\n").getBytes()); output.flush(); waitFor(input, "g!"); output.write("obr:deploy -s org.apache.felix.webconsole\r\n".getBytes()); output.flush(); waitFor(input, "done."); p.destroy(); lock.notifyAll(); } }
From source file:WaitSemaphore.java
protected boolean waitImpl(Object lock) throws InterruptedException { // Wait (forever) until notified. To discover deadlocks, // turn on debugging of this class long start = System.currentTimeMillis(); lock.wait(DEADLOCK_TIMEOUT); long end = System.currentTimeMillis(); if ((end - start) > (DEADLOCK_TIMEOUT - 1000)) { logDeadlock();/* w w w.j a v a 2 s .c o m*/ return false; } return true; }
From source file:com.runwaysdk.mobile.IdConversionTest.java
private void waitRandomAmount() { Object threadWait = new Object(); synchronized (threadWait) { try {//from ww w . j ava 2s.c o m threadWait.wait(new Random().nextInt(2) + 70); } catch (InterruptedException e) { throw new RuntimeException(e); } } }