Search in sources :

Example 81 with LinkedList

use of java.util.LinkedList in project jersey by jersey.

the class GenerateJerseyModuleListMojo method categorizeModules.

private Map<String, List<MavenProject>> categorizeModules(List<MavenProject> projects) {
    Map<String, List<MavenProject>> categorizedProjects = new HashMap<>();
    for (MavenProject project : projects) {
        String groupId = project.getGroupId();
        if (categorizedProjects.containsKey(groupId)) {
            categorizedProjects.get(groupId).add(project);
        } else {
            List<MavenProject> actualList = new LinkedList<>();
            actualList.add(project);
            categorizedProjects.put(groupId, actualList);
        }
    }
    return categorizedProjects;
}
Also used : MavenProject(org.apache.maven.project.MavenProject) HashMap(java.util.HashMap) List(java.util.List) LinkedList(java.util.LinkedList) LinkedList(java.util.LinkedList)

Example 82 with LinkedList

use of java.util.LinkedList in project jersey by jersey.

the class DefaultConfiguredValidator method createInterceptorList.

private List<ValidationInterceptor> createInterceptorList(Iterable<ValidationInterceptor> interceptors) {
    List<ValidationInterceptor> result = new LinkedList<>();
    for (ValidationInterceptor i : interceptors) {
        result.add(i);
    }
    result.add(this);
    return result;
}
Also used : ValidationInterceptor(org.glassfish.jersey.server.spi.ValidationInterceptor) LinkedList(java.util.LinkedList)

Example 83 with LinkedList

use of java.util.LinkedList in project jersey by jersey.

the class App method getJavaFiles.

private static List<JavaFile> getJavaFiles(File configFile) throws Exception {
    final List<JavaFile> javaFiles = new LinkedList<>();
    try (BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(configFile), "UTF-8"))) {
        while (r.ready()) {
            final String className = r.readLine();
            if (!className.startsWith("#")) {
                javaFiles.add(new JavaFile(className, SRC_MAIN_JAVA));
                LOGGER.info(String.format(" + included class %s.\n", className));
            } else {
                LOGGER.info(String.format(" - ignored class %s\n", className.substring(1)));
            }
        }
    }
    return javaFiles;
}
Also used : InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JavaFile(org.glassfish.jersey.examples.reload.compiler.JavaFile) LinkedList(java.util.LinkedList) FileInputStream(java.io.FileInputStream)

Example 84 with LinkedList

use of java.util.LinkedList in project jersey by jersey.

the class ManagedAsyncResourceTest method testChatResource.

@Test
public void testChatResource() throws InterruptedException {
    final WebTarget resourceTarget = target().path("chat");
    final int MAX_MESSAGES = 100;
    final int LATCH_WAIT_TIMEOUT = 10 * getAsyncTimeoutMultiplier();
    final boolean debugMode = false;
    final boolean sequentialGet = false;
    final boolean sequentialPost = false;
    final Object sequentialGetLock = new Object();
    final Object sequentialPostLock = new Object();
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("async-resource-test-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    final Map<Integer, Integer> postResponses = new ConcurrentHashMap<Integer, Integer>();
    final Map<Integer, Message> getResponses = new ConcurrentHashMap<Integer, Message>();
    final CountDownLatch postRequestLatch = new CountDownLatch(MAX_MESSAGES);
    final CountDownLatch getRequestLatch = new CountDownLatch(MAX_MESSAGES);
    try {
        for (int i = 0; i < MAX_MESSAGES; i++) {
            final int requestId = i;
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    if (debugMode || sequentialPost) {
                        synchronized (sequentialPostLock) {
                            post();
                        }
                    } else {
                        post();
                    }
                }

                private void post() {
                    try {
                        int attemptCounter = 0;
                        while (true) {
                            attemptCounter++;
                            try {
                                final Response response = resourceTarget.request().post(Entity.json(new Message("" + requestId, "" + requestId)));
                                postResponses.put(requestId, response.getStatus());
                                break;
                            } catch (Throwable t) {
                                LOGGER.log(Level.WARNING, String.format("Error POSTING message <%s> for %d. time.", requestId, attemptCounter), t);
                            }
                            if (attemptCounter > 3) {
                                break;
                            }
                            Thread.sleep(10);
                        }
                    } catch (InterruptedException ignored) {
                        LOGGER.log(Level.WARNING, String.format("Error POSTING message <%s>: Interrupted", requestId), ignored);
                    } finally {
                        postRequestLatch.countDown();
                    }
                }
            });
            executor.submit(new Runnable() {

                @Override
                public void run() {
                    if (debugMode || sequentialGet) {
                        synchronized (sequentialGetLock) {
                            get();
                        }
                    } else {
                        get();
                    }
                }

                private void get() {
                    try {
                        int attemptCounter = 0;
                        while (true) {
                            attemptCounter++;
                            try {
                                final Message response = resourceTarget.request("application/json").get(Message.class);
                                getResponses.put(requestId, response);
                                break;
                            } catch (Throwable t) {
                                LOGGER.log(Level.SEVERE, String.format("Error sending GET request <%s> for %d. time.", requestId, attemptCounter), t);
                            }
                            if (attemptCounter > 3) {
                                break;
                            }
                            Thread.sleep(10);
                        }
                    } catch (InterruptedException ignored) {
                        LOGGER.log(Level.WARNING, String.format("Error sending GET message <%s>: Interrupted", requestId), ignored);
                    } finally {
                        getRequestLatch.countDown();
                    }
                }
            });
        }
        if (debugMode) {
            postRequestLatch.await();
            getRequestLatch.await();
        } else {
            if (!postRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS)) {
                LOGGER.log(Level.SEVERE, "Waiting for all POST requests to complete has timed out.");
            }
            if (!getRequestLatch.await(LATCH_WAIT_TIMEOUT, TimeUnit.SECONDS)) {
                LOGGER.log(Level.SEVERE, "Waiting for all GET requests to complete has timed out.");
            }
        }
    } finally {
        executor.shutdownNow();
    }
    StringBuilder messageBuilder = new StringBuilder("POST responses received: ").append(postResponses.size()).append("\n");
    for (Map.Entry<Integer, Integer> postResponseEntry : postResponses.entrySet()) {
        messageBuilder.append("POST response for message ").append(postResponseEntry.getKey()).append(": ").append(postResponseEntry.getValue()).append('\n');
    }
    messageBuilder.append('\n');
    messageBuilder.append("GET responses received: ").append(getResponses.size()).append("\n");
    for (Map.Entry<Integer, Message> getResponseEntry : getResponses.entrySet()) {
        messageBuilder.append("GET response for message ").append(getResponseEntry.getKey()).append(": ").append(getResponseEntry.getValue()).append('\n');
    }
    LOGGER.info(messageBuilder.toString());
    for (Map.Entry<Integer, Integer> postResponseEntry : postResponses.entrySet()) {
        assertEquals("Unexpected POST notification response for message " + postResponseEntry.getKey(), 200, postResponseEntry.getValue().intValue());
    }
    final List<Integer> lost = new LinkedList<Integer>();
    final Collection<Message> getResponseValues = getResponses.values();
    for (int i = 0; i < MAX_MESSAGES; i++) {
        if (!getResponseValues.contains(new Message("" + i, "" + i))) {
            lost.add(i);
        }
    }
    if (!lost.isEmpty()) {
        fail("Detected a posted message loss(es): " + lost.toString());
    }
    assertEquals(MAX_MESSAGES, postResponses.size());
    assertEquals(MAX_MESSAGES, getResponses.size());
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedList(java.util.LinkedList) Response(javax.ws.rs.core.Response) ExecutorService(java.util.concurrent.ExecutorService) WebTarget(javax.ws.rs.client.WebTarget) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 85 with LinkedList

use of java.util.LinkedList in project rest.li by linkedin.

the class DegraderLoadBalancerTest method callClients.

/**
   * simulates calling clients
   * @param milliseconds latency of the call
   * @param qps qps of traffic per client
   * @param clients list of clients being called
   * @param clock
   * @param timeInterval
   * @param withError calling client with error that we don't use for load balancing (any generic error)
   * @param withQualifiedDegraderError calling client with error that we use for load balancing
   */
private void callClients(long milliseconds, double qps, List<TrackerClient> clients, TestClock clock, long timeInterval, boolean withError, boolean withQualifiedDegraderError) {
    LinkedList<CallCompletion> callCompletions = new LinkedList<CallCompletion>();
    int callHowManyTimes = (int) ((qps * timeInterval) / 1000);
    for (int i = 0; i < callHowManyTimes; i++) {
        for (TrackerClient client : clients) {
            CallCompletion cc = client.getCallTracker().startCall();
            callCompletions.add(cc);
        }
    }
    Random random = new Random();
    clock.addMs(milliseconds);
    for (CallCompletion cc : callCompletions) {
        if (withError) {
            cc.endCallWithError();
        } else if (withQualifiedDegraderError) {
            //choose a random error type
            if (random.nextBoolean()) {
                cc.endCallWithError(ErrorType.CLOSED_CHANNEL_EXCEPTION);
            } else {
                cc.endCallWithError(ErrorType.CONNECT_EXCEPTION);
            }
        } else {
            cc.endCall();
        }
    }
    //complete a full interval cycle
    clock.addMs(timeInterval - (milliseconds % timeInterval));
}
Also used : CallCompletion(com.linkedin.util.degrader.CallCompletion) TrackerClient(com.linkedin.d2.balancer.clients.TrackerClient) Random(java.util.Random) LinkedList(java.util.LinkedList)

Aggregations

LinkedList (java.util.LinkedList)10512 Test (org.junit.Test)1487 List (java.util.List)1463 HashMap (java.util.HashMap)1371 ArrayList (java.util.ArrayList)1313 Map (java.util.Map)871 IOException (java.io.IOException)800 File (java.io.File)695 HashSet (java.util.HashSet)605 LinkedHashMap (java.util.LinkedHashMap)382 GenericValue (org.apache.ofbiz.entity.GenericValue)296 Iterator (java.util.Iterator)277 Set (java.util.Set)255 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)232 Date (java.util.Date)222 Collection (java.util.Collection)201 Delegator (org.apache.ofbiz.entity.Delegator)162 Locale (java.util.Locale)158 URL (java.net.URL)154 BufferedReader (java.io.BufferedReader)146