本文的目的是介绍javax.websocket.ClientEndpointConfig的实例源码的详细情况,特别关注javawebsocketclient的相关信息。我们将通过专业的研究、有关数据的
本文的目的是介绍javax.websocket.ClientEndpointConfig的实例源码的详细情况,特别关注java websocket client的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解javax.websocket.ClientEndpointConfig的实例源码的机会,同时也不会遗漏关于ClientEndpoint - WebsocketClient、com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration的实例源码、com.amazonaws.mturk.util.ClientConfig的实例源码、com.hazelcast.config.ManagementCenterConfig的实例源码的知识。
本文目录一览:- javax.websocket.ClientEndpointConfig的实例源码(java websocket client)
- ClientEndpoint - WebsocketClient
- com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration的实例源码
- com.amazonaws.mturk.util.ClientConfig的实例源码
- com.hazelcast.config.ManagementCenterConfig的实例源码
javax.websocket.ClientEndpointConfig的实例源码(java websocket client)
public void echoTester(String path) throws Exception { WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build(); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class,clientEndpointConfig,new URI("ws://localhost:" + getPort() + path)); CountDownLatch latch = new CountDownLatch(1); BasicText handler = new BasicText(latch); wsSession.addMessageHandler(handler); wsSession.getBasicRemote().sendText("Hello"); boolean latchResult = handler.getLatch().await(10,TimeUnit.SECONDS); Assert.assertTrue(latchResult); Queue<String> messages = handler.getMessages(); Assert.assertEquals(1,messages.size()); for (String message : messages) { Assert.assertEquals("Hello",message); } wsSession.close(); }
private void connect() throws Exception { while (sessionServer != null && !sessionServer.isopen()) { break; } SSLContext context = createSSLContext(); SecureSocketClient endpoint = new SecureSocketClient(); Configurator configurator = new Configurator() { @Override public void beforeRequest(Map<String,List<String>> headers) { headers.put(SEC_WEB_SOCKET_PROTOCOL_STRING,singletonList("configured-proto")); } }; ClientEndpointConfig clientEndpointConfig = create().configurator(configurator) .preferredSubprotocols(asList(new String[] { "foo","bar","configured-proto" })).build(); clientEndpointConfig.getUserProperties().put(SSL_CONTEXT,context); final WebSocketContainer serverContainer = getWebSocketContainer(); URI uri = new URI("wss://127.0.0.1:8443/secure-test/session"); serverContainer.connectToServer(endpoint,uri); awake(); }
private StreamingLogToken streamLoggregatorLogs(String appName,ApplicationLogListener listener,boolean recent) { ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() { @Override public void beforeRequest(Map<String,List<String>> headers) { String authorizationHeader = oauthClient.getAuthorizationHeader(); if (authorizationHeader != null) { headers.put(AUTHORIZATION_HEADER_KEY,Arrays.asList(authorizationHeader)); } } }; String endpoint = getInfo().getLoggregatorEndpoint(); String mode = recent ? "dump" : "tail"; UUID appId = getAppId(appName); return loggregatorClient.connectToLoggregator(endpoint,mode,appId,listener,configurator); }
@Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointInvalidScheme() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("",null); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); wsContainer.connectToServer(TesterProgrammaticEndpoint.class,ClientEndpointConfig.Builder.create().build(),new URI("ftp://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); }
public WebsocketClient(String uri,final String sessionID,MessageHandler.Whole<String> messageHandler) throws IOException { // add session ID so the request gets through LAMS security Builder configBuilder = ClientEndpointConfig.Builder.create(); configBuilder.configurator(new Configurator() { @Override public void beforeRequest(Map<String,List<String>> headers) { headers.put("Cookie",Arrays.asList("JSESSIONID=" + sessionID)); } }); ClientEndpointConfig clientConfig = configBuilder.build(); this.websocketEndpoint = new WebsocketEndpoint(messageHandler); WebSocketContainer container = ContainerProvider.getWebSocketContainer(); try { container.connectToServer(websocketEndpoint,clientConfig,new URI(uri)); } catch (DeploymentException | URISyntaxException e) { throw new IOException("Error while connecting to websocket server",e); } }
@Test public void newJoineeGetsWelcomeMsg() throws DeploymentException,IOException,InterruptedException { controlLatch = new CountDownLatch(2); ChatClient newJoinee = new ChatClient(); String newJoineeName = "abhishek"; String endpointURL = BASE_SERVER_URL + newJoineeName + "/"; WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.connectToServer(newJoinee,URI.create(endpointURL)); assertTrue(controlLatch.await(5,TimeUnit.SECONDS)); String expectedWelcomeMessage = "Welcome " + newJoineeName; assertTrue(newJoinee.getResponse().contains(expectedWelcomeMessage)); newJoinee.closeConnection(); }
private void initWebSocketSession(String url,int wsConnectionTimeout) throws Exception { CountDownLatch wsLatch = new CountDownLatch(1); ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build(); ClientManager client = ClientManager.createClient(); client.connectToServer(new Endpoint() { @Override public void onopen(Session session,EndpointConfig endpointConfig) { wsSession = session; wsLatch.countDown(); } },cec,new URI(url)); if (!wsLatch.await(wsConnectionTimeout,TimeUnit.SECONDS)) { throw new TimeoutException("Web socket connection timeout"); } }
public void echoTester(String path) throws Exception { WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build(); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class,message); } wsSession.close(); }
@Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointInvalidScheme() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("",new URI("ftp://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); }
@Override protected void openConnection() { this.taskExecutor.execute(new Runnable() { @Override public void run() { try { logger.info("Connecting to WebSocket at " + getUri()); Endpoint endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler(); ClientEndpointConfig endpointConfig = configBuilder.build(); session = getWebSocketContainer().connectToServer(endpointToUse,endpointConfig,getUri()); logger.info("Successfully connected"); } catch (Throwable ex) { logger.error("Failed to connect",ex); } } }); }
private void createClearChannel() throws Exception { ClientEndpointConfig config = ClientEndpointConfig.Builder.create().build(); config.getUserProperties().put(WsWebSocketContainer.SSL_CONTEXT_PROPERTY,sslContext); clearChannel = ContainerProvider.getWebSocketContainer().connectToServer(endpoint,config,new URI(createClearUriString())); assertTrue(clearChannel.isopen()); CountDownLatch cdl = new CountDownLatch(1); endpoint.setResponseLatch(cdl); cdl.await(1,TimeUnit.SECONDS); assertNotNull(endpoint.getSystemId()); assertEquals(clearChannel,endpoint.getSession()); }
@Override public void connect() throws DeploymentException,IOException { ConnectionDetails details = info.getConnectionDetails(); Log.log(Level.FINE,drain,"Creating websocket to {0}",details.getTarget()); URI uriServerEP = URI.create(details.getTarget()); authConfigurator = new GameOnHeaderAuthConfigurator(details.getToken(),uriServerEP.getRawPath()); final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create() .decoders(Arrays.asList(RoutedMessageDecoder.class)).encoders(Arrays.asList(RoutedMessageEncoder.class)) .configurator(authConfigurator) .build(); WebSocketContainer c = ContainerProvider.getWebSocketContainer(); this.session = c.connectToServer(this,uriServerEP); }
/** * Establishes the connection to the given WebSocket Server Address. */ public void connect() { readyState = ReadyState.CONNECTING; try { if (webSocketHandler == null) { webSocketHandler = new WebSocketHandlerAdapter(); } container.connectToServer(new SimpleWebSocketClientEndpoint(),websocketURI); } catch (Exception e) { readyState = ReadyState.CLOSED; // throws DeploymentException,IOException throw new RuntimeException("Could not establish connection"); } }
@Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointInvalidScheme() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("",System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( TesterEchoServer.Config.class.getName(),false)); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); wsContainer.connectToServer(TesterProgrammaticEndpoint.class,new URI("ftp://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); }
@Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointNoHost() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("",new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC)); }
/** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws servletexception if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws servletexception,IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet TestServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet TestServlet at " + request.getcontextpath() + "</h1>"); WebSocketContainer container = ContainerProvider.getWebSocketContainer(); String uri = "ws://localhost:8080" + request.getcontextpath() + "/websocket"; out.println("Connecting to " + uri); container.connectToServer(MyClient.class,ClientEndpointConfig.Builder.create().configurator(new MyConfigurator()).build(),URI.create(uri)); out.println("<br><br>Look in server.log for message exchange between client/server and headers from configurator."); out.println("</body>"); out.println("</html>"); } catch (DeploymentException ex) { Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE,null,ex); } }
@Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointInvalidScheme() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("",System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); wsContainer.connectToServer(TesterProgrammaticEndpoint.class,new URI("ftp://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); }
@Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointNoHost() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("",new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC)); }
public DaemonMessagesClientEndpoint( String host,String port,boolean ssl,MessageEventService messageEventService ) throws KettleException { try { setAuthProperties(); String url = String.format( URL_TEMPLATE,( ssl ? PRFX_WS_SSL : PRFX_WS ),host,port ); URI uri = new URI( url ); this.messageEventService = messageEventService; WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.connectToServer( this,ClientEndpointConfig.Builder.create() .encoders( Collections.singletonList( MessageEncoder.class ) ) .decoders( Collections.singletonList( MessageDecoder.class ) ) .configurator( new SessionConfigurator( uri,keytab,principal ) ) .build(),uri ); } catch ( Exception e ) { throw new KettleException( e ); } }
private ClientEndpointConfig buildClientConfig(ClientEndpointConfig.Configurator configurator) { ClientEndpointConfig config = ClientEndpointConfig.Builder.create().configurator(configurator).build(); if (trustSelfSignedCerts) { SSLContext sslContext = buildSslContext(); Map<String,Object> userProperties = config.getUserProperties(); userProperties.put(WsWebSocketContainer.SSL_CONTEXT_PROPERTY,sslContext); } return config; }
@Test public void testPingPongMessages() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("",null); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); Tomcat.addServlet(ctx,"default",new DefaultServlet()); ctx.addServletMapping("/","default"); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider .getWebSocketContainer(); tomcat.start(); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class,ClientEndpointConfig.Builder .create().build(),new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(1); TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties() .get("endpoint"); tep.setLatch(latch); PongMessageHandler handler = new PongMessageHandler(latch); wsSession.addMessageHandler(handler); wsSession.getBasicRemote().sendPing(applicationData); boolean latchResult = handler.getLatch().await(10,TimeUnit.SECONDS); Assert.assertTrue(latchResult); Assert.assertArrayEquals(applicationData.array(),(handler.getMessages().peek()).getApplicationData().array()); }
@Test public void testConnectToServerEndpoint() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("",null); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); Tomcat.addServlet(ctx,"default"); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); // Set this artificially small to trigger // https://bz.apache.org/bugzilla/show_bug.cgi?id=57054 wsContainer.setDefaultMaxBinaryMessageBufferSize(64); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class,new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(1); BasicText handler = new BasicText(latch); wsSession.addMessageHandler(handler); wsSession.getBasicRemote().sendText(MESSAGE_STRING_1); boolean latchResult = handler.getLatch().await(10,TimeUnit.SECONDS); Assert.assertTrue(latchResult); Queue<String> messages = handler.getMessages(); Assert.assertEquals(1,messages.size()); Assert.assertEquals(MESSAGE_STRING_1,messages.peek()); ((WsWebSocketContainer) wsContainer).destroy(); }
@Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointNoHost() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("",new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC)); }
private void doTestPerMessageDefalteClient(String msg,int count) throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("",System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); Tomcat.addServlet(ctx,"default"); tomcat.start(); Extension perMessageDeflate = new WsExtension(PerMessageDeflate.NAME); List<Extension> extensions = new ArrayList<Extension>(1); extensions.add(perMessageDeflate); ClientEndpointConfig clientConfig = ClientEndpointConfig.Builder.create().extensions(extensions).build(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class,new URI("ws://" + getHostName() + ":" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(count); BasicText handler = new BasicText(latch,msg); wsSession.addMessageHandler(handler); for (int i = 0; i < count; i++) { wsSession.getBasicRemote().sendText(msg); } boolean latchResult = handler.getLatch().await(10,TimeUnit.SECONDS); Assert.assertTrue(latchResult); ((WsWebSocketContainer) wsContainer).destroy(); }
private ClientEndpointConfig getClientEndpointConfig() { // initializing custom client end point configurator this.configurator = new CustomClientEndPointConfigurator(WebSocketClient.this.mgrApi.getHandshakeParameters()); final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().configurator(this.configurator).build(); return cec; }
@Test public void sessionAutoClosedAfterMaxIdleTimeoutBreach() throws Exception { controlLatch = new CountDownLatch(2); WebSocketContainer container = ContainerProvider.getWebSocketContainer(); ChatClient abhi = new ChatClient(); String chatter = "abhishek"; String endpointURL = BASE_SERVER_URL + chatter + "/"; Session session = container.connectToServer(abhi,URI.create(endpointURL)); session.setMaxIdleTimeout(maxIdleTime); //set the timeout String expectedWelcomeMessageForChatter1 = "Welcome " + chatter; assertTrue(controlLatch.await(5,TimeUnit.SECONDS)); assertTrue(abhi.getResponse().contains(expectedWelcomeMessageForChatter1)); connClosedLatch = new CountDownLatch(1); assertTrue(connClosedLatch.await(maxIdleTime + 5000,TimeUnit.MILLISECONDS)); // wait 5 seconds more than the timeout String expectedSessionTimeoutCloseReasonPhrase = "\"Session closed by the container because of the idle timeout.\""; assertEquals(expectedSessionTimeoutCloseReasonPhrase,abhi.getCloseReason().getReasonPhrase()); //check the exact phrase //String expectedSessionTimeoutCloseReasonCode = "CLOSED_ABnorMALLY"; //assertEquals(expectedSessionTimeoutCloseReasonCode,abhi.getCloseReason().getCloseCode().toString()); //check the exact code }
@Test public void testPingPongMessages() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("",(handler.getMessages().peek()).getApplicationData().array()); }
@Test public void testConnectToServerEndpoint() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("",messages.peek()); ((WsWebSocketContainer) wsContainer).destroy(); }
@Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointNoHost() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("",new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC)); }
private void doTestPerMessageDefalteClient(String msg,TimeUnit.SECONDS); Assert.assertTrue(latchResult); ((WsWebSocketContainer) wsContainer).destroy(); }
@postconstruct public void init(){ try { WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); List<Class<? extends Decoder>> decoders = new ArrayList<>(); decoders.add(MeetupRSVPJSONDecoder.class); session = webSocketContainer.connectToServer(new MeetupRSVPsWebSocketClient(),ClientEndpointConfig.Builder.create().decoders(decoders).build(),URI.create("ws://stream.meetup.com/2/rsvps")); } catch (DeploymentException | IOException ex) { Logger.getLogger(MeetupRSVPsWebSocketClientSession.class.getName()).log(Level.SEVERE,ex); } }
@Override protected ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler,HttpHeaders headers,final URI uri,List<String> protocols,List<WebSocketExtension> extensions,Map<String,Object> attributes) { int port = getPort(uri); InetSocketAddress localAddress = new InetSocketAddress(getLocalHost(),port); InetSocketAddress remoteAddress = new InetSocketAddress(uri.getHost(),port); final StandardWebSocketSession session = new StandardWebSocketSession(headers,attributes,localAddress,remoteAddress); final ClientEndpointConfig endpointConfig = ClientEndpointConfig.Builder.create() .configurator(new StandardWebSocketClientConfigurator(headers)) .preferredSubprotocols(protocols) .extensions(adaptExtensions(extensions)).build(); endpointConfig.getUserProperties().putAll(getUserProperties()); final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler,session); Callable<WebSocketSession> connectTask = new Callable<WebSocketSession>() { @Override public WebSocketSession call() throws Exception { webSocketContainer.connectToServer(endpoint,uri); return session; } }; if (this.taskExecutor != null) { return this.taskExecutor.submitListenable(connectTask); } else { ListenableFutureTask<WebSocketSession> task = new ListenableFutureTask<WebSocketSession>(connectTask); task.run(); return task; } }
@Test public void clientEndpointConfig() throws Exception { URI uri = new URI("ws://localhost/abc"); List<String> protocols = Collections.singletonList("abc"); this.headers.setSecWebSocketProtocol(protocols); this.wsClient.doHandshake(this.wsHandler,this.headers,uri).get(); ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class); verify(this.wsContainer).connectToServer(any(Endpoint.class),captor.capture(),any(URI.class)); ClientEndpointConfig endpointConfig = captor.getValue(); assertEquals(protocols,endpointConfig.getPreferredSubprotocols()); }
@Test public void clientEndpointConfigWithUserProperties() throws Exception { Map<String,Object> userProperties = Collections.singletonMap("foo","bar"); URI uri = new URI("ws://localhost/abc"); this.wsClient.setUserProperties(userProperties); this.wsClient.doHandshake(this.wsHandler,any(URI.class)); ClientEndpointConfig endpointConfig = captor.getValue(); assertEquals(userProperties,endpointConfig.getUserProperties()); }
/** * Creates and starts teapot simulator. * * @param teapot teapot domain object * @param port port number of the server * * @throws URISyntaxException * @throws DeploymentException * @throws IOException */ public TeapotSimulator(Teapot teapot,int port) throws URISyntaxException,DeploymentException,IOException { /* Get websocket container */ final WebSocketContainer container = ContainerProvider .getWebSocketContainer(); /* Configuration of teapot client endpoint */ final ClientEndpointConfig teapotConfig = ClientEndpointConfig.Builder .create() .build(); /* disable websocket timeout */ container.setDefaultMaxSessionIdleTimeout(0); URI uri = new URI(String.format(REGISTER_URL,port,teapot.getId())); /* Create websocket client for the teapot */ container.connectToServer( new TeapotSimulatorEndpoint(this),teapotConfig,uri); /* Create the file system */ fs = new TeapotFs(); /* Create help.txt file */ fs.cat("help.txt",createHelpFileContent()); /* Create license file */ fs.cat("license",createLicenseFileContent()); /* Create config.json file */ fs.cat("config.json",createConfigFileContent(teapot)); }
private void createEncryptedChannel() throws Exception { ClientEndpointConfig config = ClientEndpointConfig.Builder.create().build(); config.getUserProperties().put(WsWebSocketContainer.SSL_CONTEXT_PROPERTY,sslContext); encChannel = ContainerProvider.getWebSocketContainer().connectToServer(endpoint,new URI(createEncUriString())); assertTrue(encChannel.isopen()); }
private ClientEndpointConfig createClientEndpointConfigWithJsession(final String jsession,final String userpwd) { ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() { @Override public void beforeRequest(Map<String,List<String>> headers) { if (null != jsession) { headers.put("Cookie",Arrays.asList("JSESSIONID=" + jsession)); } headers.put("Authorization",Arrays.asList("Basic " + DatatypeConverter.printBase64Binary(userpwd.getBytes()))); } }; return ClientEndpointConfig.Builder.create().configurator(configurator).build(); }
@Test public void testPingPongMessages() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("",false)); Tomcat.addServlet(ctx,(handler.getMessages().peek()).getApplicationData().array()); }
ClientEndpoint - WebsocketClient
如何解决ClientEndpoint - WebsocketClient?
我的代码:WebsocketClient
package bean;
import java.io.IOException;
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.Onopen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import org.json.JSONException;
@ClientEndpoint
public class WebsocketClient {
Session session = null;
private MessageHandler handler;
public WebsocketClient(URI endpointURI) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this,endpointURI);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Onopen
public void onopen(Session session) {
this.session = session;
try {
session.getBasicRemote().sendText("opening connection");
} catch (IOException ex) {
System.out.println(ex);
}
}
@OnError
public void onError(Session session,Throwable t) {
t.printstacktrace();
}
@OnMessage
public void processMessage(String message) throws JSONException {
//System.out.println("Received message in client: " + message);
if (this.handler != null) {
this.handler.handleMessage(message);
}
}
public void addMessageHandler(MessageHandler msgHandler) {
this.handler = msgHandler;
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static interface MessageHandler {
public void handleMessage(String message);
}
}
st.java
package bean;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.json.JSONException;
import org.json.JSONObject;
@ManagedBean(name = "st")
@ViewScoped
public class st implements Serializable {
private String unitate;
private String user;
private String an;
private String luna;
@ManagedProperty(value = "#{client}")
private client clt;
public void conectare() {
clt.con();
clt.getW().addMessageHandler(new WebsocketClient.MessageHandler() {
public void handleMessage(String message) {
try {
if (isJSONValid(message)) {
JSONObject jsonobj = new JSONObject(message);
switch (jsonobj.getString("raspuns")) {
case ("start"):
actiune1(jsonobj);
break;
case ("get"):
break;
case ("i"):
break;
default:
break;
}
}
} catch (JSONException ex) {
Logger.getLogger(st.class.getName()).log(Level.SEVERE,null,ex);
}
}
});
}
public String getUnitate() {
return unitate;
}
public void setUnitate(String unitate) {
this.unitate = unitate;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getAn() {
return an;
}
public void setAn(String an) {
this.an = an;
}
public String getLuna() {
return luna;
}
public void setLuna(String luna) {
this.luna = luna;
}
public void update() {
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("g:v");
}
public void actiune1(JSONObject jsonobj) {
try {
setAn(jsonobj.getString("an"));
setLuna(jsonobj.getString("luna"));
setUser(jsonobj.getString("utilizator"));
setUnitate(jsonobj.getString("unitate"));
this.update();
} catch (JSONException ex) {
Logger.getLogger(st.class.getName()).log(Level.SEVERE,ex);
}
}
private boolean isJSONValid(String ms) {
try {
JSONObject jsonobj = new JSONObject(ms);
} catch (JSONException ex) {
return false;
}
return true;
}
public client getClt() {
return clt;
}
public void setClt(client clt) {
this.clt = clt;
}
}
client.java:
package bean;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
@ManagedBean(name = "client")
@ApplicationScoped
public class client implements Serializable {
private WebsocketClient w;
public void con() {
try {
// open websocket
WebsocketClient clientEndPoint = new WebsocketClient(new URI("ws://localhost:8084/websoketserver/vali1"));
// send message to websocket
clientEndPoint.sendMessage("Message sent from client!");
w = clientEndPoint;
} catch (IOException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE,ex);
} catch (URISyntaxException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE,ex);
}
}
public WebsocketClient getW() {
return w;
}
public void setW(WebsocketClient w) {
this.w = w;
}
}
index.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
>
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form id="g">
<p:commandButton value="Connect" action="#{st.conectare()}" style/>
<h:panelGrid columns="1" id="v">
<h:outputText value="#{st.unitate}"></h:outputText>
<h:outputText value="#{st.user}"></h:outputText>
<h:outputText value="#{st.an}"></h:outputText>
<h:outputText value="#{st.luna}"></h:outputText>
<h:commandButton value="up" actionListener="#{st.update()}" > </h:commandButton>
</h:panelGrid>
</h:form>
</h:body>
</html>
我的问题在这里:
public void update() {
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("g:v");
}
错误:
opening connection
Message sent from client!
java.lang.NullPointerException
at bean.st.update(st.java:104)
at bean.st.actiune1(st.java:114)
at bean.st$1.handleMessage(st.java:45)
at bean.WebsocketClient.processMessage(WebsocketClient.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:80)
at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:393)
at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:494)
at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:289)
at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:130)
at org.apache.tomcat.websocket.WsFrameClient.processSocketRead(WsFrameClient.java:73)
at org.apache.tomcat.websocket.WsFrameClient.access$300(WsFrameClient.java:31)
at org.apache.tomcat.websocket.WsFrameClient$WsFrameClientCompletionHandler.completed(WsFrameClient.java:125)
at org.apache.tomcat.websocket.WsFrameClient$WsFrameClientCompletionHandler.completed(WsFrameClient.java:108)
at sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:126)
at sun.nio.ch.Invoker$2.run(Invoker.java:218)
at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
Connection closed
at java.lang.Thread.run(Thread.java:748)
想在收到服务器的日期消息后直接从bean更新xhtml页面.... 我不想使用 javascript ... . 我不明白为什么它是空的...
为什么是空的? 谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration的实例源码
@Before public void setup() { store = new InMemoryStorage(); metrics = new InMemoryCollectorMetrics(); collector = new SQSCollector.Builder() .queueUrl(sqsRule.queueUrl()) .parallelism(2) .waitTimeSeconds(1) // using short wait time to make test teardown faster .endpointConfiguration(new EndpointConfiguration(sqsRule.queueUrl(),"us-east-1")) .credentialsProvider(new AWsstaticCredentialsProvider(new BasicAWSCredentials("x","x"))) .metrics(metrics) .sampler(CollectorSampler.ALWAYS_SAMPLE) .storage(store) .build() .start(); }
/** * Returns a client instance for AWS DynamoDB. * @return a client that talks to DynamoDB */ public static AmazonDynamoDB getClient() { if (ddbClient != null) { return ddbClient; } if (Config.IN_PRODUCTION) { ddbClient = AmazonDynamoDBClientBuilder.standard().withCredentials(new AWsstaticCredentialsProvider( new BasicAWSCredentials(Config.AWS_ACCESSKEY,Config.AWS_SECRETKEY))). withRegion(Config.AWS_REGION).build(); } else { ddbClient = AmazonDynamoDBClientBuilder.standard(). withCredentials(new AWsstaticCredentialsProvider(new BasicAWSCredentials("local","null"))). withEndpointConfiguration(new EndpointConfiguration(LOCAL_ENDPOINT,"")).build(); } if (!existsTable(Config.getRootAppIdentifier())) { createTable(Config.getRootAppIdentifier()); } ddb = new DynamoDB(ddbClient); Para.addDestroyListener(new DestroyListener() { public void onDestroy() { shutdownClient(); } }); return ddbClient; }
/** * Returns a client instance for AWS SQS. * @return a client that talks to SQS */ public static AmazonSQS getClient() { if (sqsClient != null) { return sqsClient; } if (Config.IN_PRODUCTION) { sqsClient = AmazonSQSClientBuilder.standard().withCredentials(new AWsstaticCredentialsProvider( new BasicAWSCredentials(Config.AWS_ACCESSKEY,Config.AWS_SECRETKEY))). withRegion(Config.AWS_REGION).build(); } else { sqsClient = AmazonSQSClientBuilder.standard(). withCredentials(new AWsstaticCredentialsProvider(new BasicAWSCredentials("x","x"))). withEndpointConfiguration(new EndpointConfiguration(LOCAL_ENDPOINT,"")).build(); } Para.addDestroyListener(new DestroyListener() { public void onDestroy() { sqsClient.shutdown(); } }); return sqsClient; }
/** * Gets an Amazon S3 client from basic session credentials. * * @return an authenticated Amazon S3 amazonS3 */ public AmazonS3 getAmazonS3Client() { if (amazonS3 == null) { amazonS3 = AmazonS3ClientBuilder.standard() .withEndpointConfiguration(new EndpointConfiguration(endpoint,region)) .withClientConfiguration(new ClientConfiguration().withProtocol(Protocol.HTTP)) .withCredentials( new AWsstaticCredentialsProvider(new BasicAWSCredentials(accessKeyId,accessKeySecret))) .build(); } return amazonS3; }
private AmazonS3 newInstance(String region,S3S3copierOptions s3s3copierOptions) { HadoopAWSCredentialProviderChain credentialsChain = getCredentialsProviderChain(); AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard().withCredentials(credentialsChain); URI s3Endpoint = s3s3copierOptions.getS3Endpoint(region); if (s3Endpoint != null) { EndpointConfiguration endpointConfiguration = new EndpointConfiguration(s3Endpoint.toString(),region); builder.withEndpointConfiguration(endpointConfiguration); } else { builder.withRegion(region); } return builder.build(); }
private AmazonS3 newGlobalInstance(S3S3copierOptions s3s3copierOptions) { HadoopAWSCredentialProviderChain credentialsChain = getCredentialsProviderChain(); AmazonS3ClientBuilder builder = AmazonS3ClientBuilder .standard() .withForceGlobalBucketAccessEnabled(Boolean.TRUE) .withCredentials(credentialsChain); URI s3Endpoint = s3s3copierOptions.getS3Endpoint(); if (s3Endpoint != null) { EndpointConfiguration endpointConfiguration = new EndpointConfiguration(s3Endpoint.toString(),Region.US_Standard.getFirstRegionId()); builder.withEndpointConfiguration(endpointConfiguration); } return builder.build(); }
private static EndpointConfiguration getEndpointConfiguration(Configuration conf) { String endpointUrl = conf.get(ConfigurationVariable.S3_ENDPOINT_URI.getName()); if (endpointUrl == null) { return null; } return new EndpointConfiguration(endpointUrl,getRegion(conf)); }
public AmazonS3 newInstance(Configuration conf) { int maxErrorRetry = conf.getInt(ConfigurationVariable.UPLOAD_RETRY_COUNT.getName(),ConfigurationVariable.UPLOAD_RETRY_COUNT.defaultIntValue()); long errorRetryDelay = conf.getLong(ConfigurationVariable.UPLOAD_RETRY_DELAY_MS.getName(),ConfigurationVariable.UPLOAD_RETRY_DELAY_MS.defaultLongValue()); LOG.info("Creating AWS S3 client with a retry policy of {} retries and {} ms of exponential backoff delay",maxErrorRetry,errorRetryDelay); RetryPolicy retryPolicy = new RetryPolicy(new CounterBasedRetryCondition(maxErrorRetry),new ExponentialBackoffStrategy(errorRetryDelay),true); ClientConfiguration clientConfiguration = new ClientConfiguration(); clientConfiguration.setRetryPolicy(retryPolicy); clientConfiguration.setMaxErrorRetry(maxErrorRetry); AmazonS3ClientBuilder builder = AmazonS3ClientBuilder .standard() .withCredentials(new HadoopAWSCredentialProviderChain(conf)) .withClientConfiguration(clientConfiguration); EndpointConfiguration endpointConfiguration = getEndpointConfiguration(conf); if (endpointConfiguration != null) { builder.withEndpointConfiguration(endpointConfiguration); } else { builder.withRegion(getRegion(conf)); } return builder.build(); }
@Before public void setup() { EndpointConfiguration endpoint = new EndpointConfiguration(UNIT_STACK_URL + ":" + SNS_PORT,Region.EU_Frankfurt.name()); AWSCredentials credentials = new BasicAWSCredentials("key","secret"); AWSCredentialsProvider credentialsProvider = new AWsstaticCredentialsProvider(credentials); sns = AmazonSNSAsyncclientBuilder.standard().withEndpointConfiguration(endpoint) .withCredentials(credentialsProvider).build(); }
@Before public void setup() { MockParameters params = new MockParameters(); params.setMockRegion("EU"); mockS3(params); EndpointConfiguration endpoint = new EndpointConfiguration(UNIT_STACK_URL + ":" + S3_PORT,"secret"); AWSCredentialsProvider credentialsProvider = new AWsstaticCredentialsProvider(credentials); s3 = AmazonS3ClientBuilder.standard().withEndpointConfiguration(endpoint) .withCredentials(credentialsProvider).build(); }
@Before public void setup() { mockSqs(null); EndpointConfiguration endpoint = new EndpointConfiguration(UNIT_STACK_URL + ":" + SQS_PORT,"eu-central-1"); AWSCredentials credentials = new BasicAWSCredentials("key","secret"); AWSCredentialsProvider credentialsProvider = new AWsstaticCredentialsProvider(credentials); sqs = AmazonSQSAsyncclientBuilder.standard().withEndpointConfiguration(endpoint) .withCredentials(credentialsProvider).build(); }
@Test public void endpointAndSigningRegionCanBeUsedInPlaceOfSetRegion() { AmazonConcreteClient client = new ConcreteSyncBuilder() .withEndpointConfiguration(new EndpointConfiguration("https://mockprefix.ap-southeast-2.amazonaws.com","us-east-1")) .build(); assertEquals("us-east-1",client.getSignerRegionOverride()); assertEquals(URI.create("https://mockprefix.ap-southeast-2.amazonaws.com"),client.getEndpoint()); }
@Test(expected = IllegalStateException.class) public void cannotSetBothEndpointConfigurationAndRegionOnBuilder() { new ConcreteSyncBuilder() .withEndpointConfiguration(new EndpointConfiguration("http://localhost:3030","us-west-2")) .withRegion("us-east-1") .build(); }
/** * @return An {@link AmazonS3} client instance that is configured to call the started S3Mock * server using HTTPS. */ public AmazonS3 createS3Client() { final BasicAWSCredentials credentials = new BasicAWSCredentials("foo","bar"); return AmazonS3ClientBuilder.standard() .withCredentials(new AWsstaticCredentialsProvider(credentials)) .withClientConfiguration( configureClientToIgnoreInvalidSslCertificates(new ClientConfiguration())) .withEndpointConfiguration( new EndpointConfiguration("https://localhost:" + getPort(),"us-east-1")) .enablePathStyleAccess() .build(); }
/** * Configures the S3-Client to be used in the Test. Sets the SSL context to accept untrusted SSL * connections. */ @Before public void prepareS3Client() { final BasicAWSCredentials credentials = new BasicAWSCredentials("foo","bar"); s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWsstaticCredentialsProvider(credentials)) .withClientConfiguration(ignoringInvalidSslCertificates(new ClientConfiguration())) .withEndpointConfiguration( new EndpointConfiguration("https://" + getHost() + ":" + getPort(),"us-east-1")) .enablePathStyleAccess() .build(); }
@Before public void setup() throws Exception { sender = KinesisSender.builder() .streamName("test") .endpointConfiguration(new EndpointConfiguration(server.url("/").toString(),"us-east-1")) .credentialsProvider(new AWsstaticCredentialsProvider(new AnonymousAWSCredentials())) .build(); }
/** * Get or initialize the S3 client. * Note: this method must be synchronized because we're accessing the * {@link #s3Client} field and we're calling this method from a worker thread. * @return the S3 client */ private synchronized AmazonS3 getS3Client() { if (s3Client == null) { BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey,secretKey); AmazonS3ClientBuilder builder = AmazonS3ClientBuilder .standard() .withCredentials(new AWsstaticCredentialsProvider(credentials)); if (forceSignatureV2) { ClientConfigurationFactory configFactory = new ClientConfigurationFactory(); ClientConfiguration config = configFactory.getConfig(); config.setSignerOverride("S3SignerType"); builder = builder.withClientConfiguration(config); } String endpoint = "http://" + host + ":" + port; String clientRegion = null; if (!ServiceUtils.isS3UsstandardEndpoint(endpoint)) { clientRegion = AwsHostNameUtils.parseRegion(host,AmazonS3Client.S3_SERVICE_NAME); } builder = builder.withEndpointConfiguration(new EndpointConfiguration( endpoint,clientRegion)); builder = builder.withPathStyleAccessEnabled(pathStyleAccess); s3Client = builder.build(); } return s3Client; }
protected void before() throws Throwable { s3Mock = S3Mock.create(Helper.findRandomOpenPortOnAllLocalInterfaces()); localAddress = s3Mock.start().localAddress(); amazonS3 = AmazonS3ClientBuilder.standard() .withEndpointConfiguration(new EndpointConfiguration(getEndpoint(),"eu-west-1")) .build(); buckets.forEach(amazonS3::createBucket); files.forEach(fakeFile -> amazonS3.putObject(fakeFile.bucket,fakeFile.name,fakeFile.content)); }
@Test public void getterSettertest() { String randomValue = UUID.randomUUID().toString(); DynamoExample exampleClient = new DynamoExample(AmazonDynamoDBClientBuilder .standard() .withEndpointConfiguration(new EndpointConfiguration(subject.getEndpoint(),"eu-west-1")) .build()); exampleClient.createTable(); exampleClient.setValue(1L,randomValue); assertthat(exampleClient.getValue(1L),is(randomValue)); }
@Before public void setUp() throws Exception { TestUtils.S3ProxyLaunchInfo info = TestUtils.startS3Proxy( "s3proxy.conf"); awsCreds = new BasicAWSCredentials(info.getS3Identity(),info.getS3Credential()); context = info.getBlobStore().getContext(); s3Proxy = info.getS3Proxy(); s3Endpoint = info.getSecureEndpoint(); servicePath = info.getServicePath(); s3EndpointConfig = new EndpointConfiguration( s3Endpoint.toString() + servicePath,"us-east-1"); client = AmazonS3ClientBuilder.standard() .withCredentials(new AWsstaticCredentialsProvider(awsCreds)) .withEndpointConfiguration(s3EndpointConfig) .build(); containerName = createrandomContainerName(); info.getBlobStore().createContainerInLocation(null,containerName); blobStoreType = context.unwrap().getProviderMetadata().getId(); if (Quirks.OPAQUE_ETAG.contains(blobStoreType)) { System.setProperty( SkipMd5CheckStrategy .disABLE_GET_OBJECT_MD5_VALIDATION_PROPERTY,"true"); System.setProperty( SkipMd5CheckStrategy .disABLE_PUT_OBJECT_MD5_VALIDATION_PROPERTY,"true"); } }
@Before public void setUp() throws Exception { TestUtils.S3ProxyLaunchInfo info = TestUtils.startS3Proxy( "s3proxy-anonymous.conf"); awsCreds = new AnonymousAWSCredentials(); context = info.getBlobStore().getContext(); s3Proxy = info.getS3Proxy(); s3Endpoint = info.getSecureEndpoint(); servicePath = info.getServicePath(); s3EndpointConfig = new EndpointConfiguration( s3Endpoint.toString() + servicePath,"true"); } }
/** * Gets configured AmazonS3 client instance. Does not perform actual request until first remote data is needed */ private AmazonS3 getClient() { if (s3Client != null) { return s3Client; // already cached } ClientConfiguration config = new ClientConfiguration(); if (endpoint != null && endpoint.startsWith("https://")) { config.setProtocol(Protocol.HTTPS); } else { config.setProtocol(Protocol.HTTP); } BasicAWSCredentials creds = new BasicAWSCredentials(accessKey,secretKey); if (LOG.isDebugEnabled()) { LOG.debug("Creating S3 client to " + ( (endpoint == null) ? "default Amazon" : endpoint) + " endpoint with access key " + accessKey); } if (this.endpoint != null) { if (region == null || region.trim().length() == 0) { region = Regions.DEFAULT_REGION.name(); } s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWsstaticCredentialsProvider(creds)) .withEndpointConfiguration(new EndpointConfiguration(endpoint,region)) .withClientConfiguration(config) .withPathStyleAccessEnabled(true) .build(); } else { s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWsstaticCredentialsProvider(creds)) .withClientConfiguration(config) .withPathStyleAccessEnabled(true) .build(); } return s3Client; }
private static AmazonMTurk getSandBoxClient() { AmazonMTurkClientBuilder builder = AmazonMTurkClientBuilder.standard(); builder.setEndpointConfiguration(new EndpointConfiguration(SANDBox_ENDPOINT,SIGNING_REGION)); return builder.build(); }
private static AmazonMTurk getProdClient() { AmazonMTurkClientBuilder builder = AmazonMTurkClientBuilder.standard(); builder.setEndpointConfiguration(new EndpointConfiguration(PROD_ENDPOINT,SIGNING_REGION)); return builder.build(); }
private static AmazonMTurk getSandBoxClient() { AmazonMTurkClientBuilder builder = AmazonMTurkClientBuilder.standard(); builder.setEndpointConfiguration(new EndpointConfiguration(SANDBox_ENDPOINT,SIGNING_REGION)); return builder.build(); }
private static AmazonMTurk getProductionClient() { AmazonMTurkClientBuilder builder = AmazonMTurkClientBuilder.standard(); builder.setEndpointConfiguration(new EndpointConfiguration(PRODUCTION_ENDPOINT,SIGNING_REGION)); return builder.build(); }
private static AmazonMTurk getSandBoxClient() { AmazonMTurkClientBuilder builder = AmazonMTurkClientBuilder.standard(); builder.setEndpointConfiguration(new EndpointConfiguration(SANDBox_ENDPOINT,SIGNING_REGION)); return builder.build(); }
public static EndpointConfiguration getEndpointConfig(String serviceEndpoint,String signingRegion) { return new EndpointConfiguration(serviceEndpoint,signingRegion); }
@Nullable abstract EndpointConfiguration endpointConfiguration();
@Nullable abstract EndpointConfiguration endpointConfiguration();
com.amazonaws.mturk.util.ClientConfig的实例源码
protected RequesterServiceRaw( ClientConfig config ) { super(config); try { // instantiate port for main thread to fail-fast in case it is misconfigured AWSmechanicalturkRequesterLocator locator = new AWSmechanicalturkRequesterLocator(); locator.setEndpointAddress(PORT_NAME,this.config.getServiceURL()); getPort(); // Read the access keys from config this.setAccessKeyId(this.config.getAccessKeyId()); this.setSigner(this.config.getSecretAccessKey()); //add default Retry Filter to list of filters this.addFilter(new ErrorProcessingFilter()); this.addFilter(new RetryFilter(config.getRetriableErrors(),config.getRetryAttempts(),config.getRetryDelayMillis())); } catch (Exception e) { throw new RuntimeException("Invalid configuration for port",e); } }
protected RequesterServiceRaw( ClientConfig config ) { super(config); try { // instantiate port for main thread to fail-fast in case it is misconfigured AWSmechanicalturkRequesterLocator locator = new AWSmechanicalturkRequesterLocator(); locator.setEndpointAddress(PORT_NAME,e); } }
/** * Handles/logs throttling errors in the sandBox environment * @param ex */ private void handleException(Exception ex) throws InternalServiceException { if (ex instanceof InternalServiceException && service.getConfig().getServiceURL().equalsIgnoreCase(ClientConfig.SANDBox_SERVICE_URL)) { logFailure(ex); throw (InternalServiceException)ex; } }
/** * * @param filterList - List of Filters that should be executed. * Also appends the FinalFilter,which makes the wsdl call,to the List */ public FilteredAWSService(ClientConfig config,List<Filter> filterList) { super(config); this.filterList = new LinkedList<Filter>(filterList); this.filterList.addLast(new FinalFilter(this)); Filter.linkFilters(this.filterList); }
/** * Handles/logs throttling errors in the sandBox environment * @param ex */ private void handleException(Exception ex) throws InternalServiceException { if (ex instanceof InternalServiceException && service.getConfig().getServiceURL().equalsIgnoreCase(ClientConfig.SANDBox_SERVICE_URL)) { logFailure(ex); throw (InternalServiceException)ex; } }
/** * * @param filterList - List of Filters that should be executed. * Also appends the FinalFilter,List<Filter> filterList) { super(config); this.filterList = new LinkedList<Filter>(filterList); this.filterList.addLast(new FinalFilter(this)); Filter.linkFilters(this.filterList); }
public HITResults(HIT hit,Assignment[] assignments,ClientConfig config) { this.hit = hit; this.assignments = assignments; this.config = config; }
public AWSService(ClientConfig config) { this.config = config; }
public ClientConfig getConfig() { return this.config; }
public FilteredAWSService(ClientConfig config) { this(config,Collections.EMPTY_LIST); }
public void testCreateHITsAsync() { if (service.getConfig().getServiceURL().equals(ClientConfig.SANDBox_SERVICE_URL)) { // since we test that async performs better,let's wait a 20 secs // so that we can execute the requests without throttling skewing the times try { Thread.sleep(5000); } catch (InterruptedException ie) { //do nothing } } long t1 = System.currentTimeMillis(); AsyncReply[] replies = new AsyncReply[10]; // submit to work queue for (int i = 0; i < replies.length; i++) { replies[i] = service.createHITAsync( null,// HITTypeId "Async_" + String.valueOf(i) + "_" + defaultHITTitle + unique,"Async_" + String.valueOf(i) + "_" + defaultHITDescription,null,// keywords RequesterService.getBasicFreeTextQuestion(defaultQuestion),defaultReward,defaultAssignmentDurationInSeconds,defaultAutoApprovalDelayInSeconds,defaultLifetimeInSeconds,defaultMaxAssignments,// requesterannotation null,// responseGroup null,// uniqueRequestToken null,// assignmentReviewPolicy null,// hitReviewPolicy null // callback ); assertNotNull(replies[i]); assertNotNull(replies[i].getFuture()); assertFalse(replies[i].getFuture().isDone()); } // get results for (AsyncReply reply : replies) { HIT hit = ((HIT[]) reply.getResult())[0]; assertNotNull(hit); assertNotNull(hit.getHITId()); assertTrue(reply.getFuture().isDone()); } long t2 = System.currentTimeMillis(); // create same amount of HITs synchronously for (int i = 0; i < replies.length; i++) { createHIT(); } long t3 = System.currentTimeMillis(); long timeAsync = t2 - t1; long timeSync = t3 - t2; assertTrue(timeAsync < timeSync); }
public HITResults(HIT hit,ClientConfig config) { this.hit = hit; this.assignments = assignments; this.config = config; }
public AWSService(ClientConfig config) { this.config = config; }
public ClientConfig getConfig() { return this.config; }
public FilteredAWSService(ClientConfig config) { this(config,Collections.EMPTY_LIST); }
public void testCreateHITsAsync() { if (service.getConfig().getServiceURL().equals(ClientConfig.SANDBox_SERVICE_URL)) { // since we test that async performs better,// hitReviewPolicy null // callback ); assertNotNull(replies[i]); assertNotNull(replies[i].getFuture()); assertFalse(replies[i].getFuture().isDone()); } // get results for (AsyncReply reply : replies) { HIT hit = ((HIT[]) reply.getResult())[0]; assertNotNull(hit); assertNotNull(hit.getHITId()); assertTrue(reply.getFuture().isDone()); } long t2 = System.currentTimeMillis(); // create same amount of HITs synchronously for (int i = 0; i < replies.length; i++) { createHIT(); } long t3 = System.currentTimeMillis(); long timeAsync = t2 - t1; long timeSync = t3 - t2; assertTrue(timeAsync < timeSync); }
public GortRequesterService(ClientConfig config) { super(config); }
/** * Creates a new instance of this class using the configuration information * from the ClientConfig class. */ public RequesterService(ClientConfig config) { super(config); }
/** * Creates a new instance of this class using the configuration information * from the ClientConfig class. */ public RequesterService(ClientConfig config) { super(config); }
com.hazelcast.config.ManagementCenterConfig的实例源码
private static void enableManagementCenter(Config cfg) { ManagementCenterConfig mgtCenter = new ManagementCenterConfig("http://localhost:8080/mancenter",3); mgtCenter.setEnabled(true); cfg.setManagementCenterConfig(mgtCenter); }
@SuppressWarnings("CallToThreadStartDuringObjectConstruction") public ManagementCenterService(FactoryImpl factoryImpl) throws Exception { this.factory = factoryImpl; final ManagementCenterConfig config = factory.node.config.getManagementCenterConfig(); this.instanceFilterMap = new StatsInstanceFilter(factoryImpl.node.getGroupProperties().MC_MAP_EXCLUDES.getString()); this.instanceFilterQueue = new StatsInstanceFilter(factoryImpl.node.getGroupProperties().MC_QUEUE_EXCLUDES.getString()); this.instanceFilterTopic = new StatsInstanceFilter(factoryImpl.node.getGroupProperties().MC_TOPIC_EXCLUDES.getString()); this.instanceFilteratomicNumber = new StatsInstanceFilter(factoryImpl.node.getGroupProperties().MC_ATOMIC_NUMBER_EXCLUDES.getString()); this.instanceFilterCountDownLatch = new StatsInstanceFilter(factoryImpl.node.getGroupProperties().MC_COUNT_DOWN_LATCH_EXCLUDES.getString()); this.instanceFilterSemaphore = new StatsInstanceFilter(factoryImpl.node.getGroupProperties().MC_SEMAPHORE_EXCLUDES.getString()); updateMemberOrder(); logger = factory.node.getLogger(ManagementCenterService.class.getName()); maxVisibleInstanceCount = factory.node.groupProperties.MC_MAX_INSTANCE_COUNT.getInteger(); commandHandler = new ConsoleCommandHandler(factory); String tmpWebServerUrl = config != null ? config.getUrl() : null; webServerUrl = tmpWebServerUrl != null ? (!tmpWebServerUrl.endsWith("/") ? tmpWebServerUrl + '/' : tmpWebServerUrl) : tmpWebServerUrl; updateIntervalMs = (config != null && config.getUpdateInterval() > 0) ? config.getUpdateInterval() * 1000 : 3000; factory.getCluster().addMembershipListener(this); factory.getLifecycleService().addLifecycleListener(this); final MemberImpl memberLocal = (MemberImpl) factory.getCluster().getLocalMember(); thisAddress = memberLocal.getAddress(); if (factory.node.groupProperties.MANCENTER_ENABLED.getBoolean()) { int port = calculatePort(thisAddress); datagramSocket = new DatagramSocket(port); serverSocket = new SocketReadyServerSocket(port,1000,factory.node.config.isReuseAddress()); udplistener = new Udplistener(datagramSocket,factory.node.config.isReuseAddress()); udpSender = new UDPSender(datagramSocket); tcpListener = new TCPListener(serverSocket); for (int i = 0; i < 100; i++) { qClientHandlers.offer(new ClientHandler(i)); } udpSender.start(); tcpListener.start(); udplistener.start(); logger.log(Level.INFO,"Hazelcast Management Center started at port " + port + "."); } if (config != null && config.isEnabled()) { if (config.getUrl() != null) { taskPoller = new TaskPoller(); stateSender = new StateSender(); taskPoller.start(); stateSender.start(); logger.log(Level.INFO,"Hazelcast Management Center is listening from " + config.getUrl()); } else { logger.log(Level.WARNING,"Hazelcast Management Center Web server url is null!"); } } running = true; // volatile-write }
今天关于javax.websocket.ClientEndpointConfig的实例源码和java websocket client的讲解已经结束,谢谢您的阅读,如果想了解更多关于ClientEndpoint - WebsocketClient、com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration的实例源码、com.amazonaws.mturk.util.ClientConfig的实例源码、com.hazelcast.config.ManagementCenterConfig的实例源码的相关知识,请在本站搜索。
本文标签: