在本文中,我们将为您详细介绍javax.websocket.DeploymentException的实例源码的相关知识,并且为您解答关于javasocket源码的疑问,此外,我们还会提供一些关于com
在本文中,我们将为您详细介绍javax.websocket.DeploymentException的实例源码的相关知识,并且为您解答关于java socket源码的疑问,此外,我们还会提供一些关于com.lowagie.text.DocumentException的实例源码、Error: weblogic.management.DeploymentException: Cannot set web app root system p、io.jsonwebtoken.ExpiredJwtException的实例源码、io.jsonwebtoken.JwtException的实例源码的有用信息。
本文目录一览:- javax.websocket.DeploymentException的实例源码(java socket源码)
- com.lowagie.text.DocumentException的实例源码
- Error: weblogic.management.DeploymentException: Cannot set web app root system p
- io.jsonwebtoken.ExpiredJwtException的实例源码
- io.jsonwebtoken.JwtException的实例源码
javax.websocket.DeploymentException的实例源码(java socket源码)
/** * * @param context the context to add the web socket endpoints to * @param rtEventResource The instance of the websocket endpoint to return * @throws DeploymentException */ private static void setWebSocketEndpoints(ServletContextHandler context,EventsResource rtEventResource) throws DeploymentException,servletexception { ServerContainer wsContainer = WebSocketServerContainerInitializer.configureContext(context); ServerEndpointConfig serverConfig = ServerEndpointConfig.Builder .create(EventsResource.class,EventsResource.RT_EVENT_ENDPOINT) .configurator(new Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { return endpointClass.cast(rtEventResource); } }).build(); wsContainer.addEndpoint(serverConfig); }
public void subscribe(String sparql,String alias,String jwt,NotificationHandler handler) throws IOException,URISyntaxException { this.handler = handler; this.sparql = sparql; this.alias = alias; this.jwt = jwt; if (!isConnected()) try { connect(); } catch (DeploymentException e) { throw new IOException(e.getMessage()); } else sendSubscribeRequest(); //Start watchdog if (watchDog == null) watchDog = new WebsocketWatchdog(handler,this,sparql); }
public void unsubscribe(String spuid,String jwt) throws IOException,URISyntaxException { logger.debug("unsubscribe"); if (!isConnected()) try { connect(); } catch (DeploymentException e) { throw new IOException(e.getMessage()); } JsonObject request = new JsonObject(); if (spuid != null) request.add("unsubscribe",new JsonPrimitive(spuid)); if (jwt != null) request.add("authorization",new JsonPrimitive(jwt)); wsClientSession.getBasicRemote().sendText(request.toString()); }
private synchronized boolean subscribing() throws DeploymentException,IOException,URISyntaxException { logger.debug("Subscribing..."); if (wsClient == null) { logger.warn("Websocket client is null"); return false; } while(state == SUBSCRIPTION_STATE.broKEN_SOCKET) { if (wsClient.isConnected()) wsClient.close(); wsClient.subscribe(sparql,alias,token,handler); try { wait(DEFAULT_SUBSCRIPTION_DELAY); } catch (InterruptedException e) { } } return (state == SUBSCRIPTION_STATE.SUBSCRIbed); }
public static void main(String[] args) throws FileNotFoundException,NoSuchElementException,DeploymentException,URISyntaxException { ApplicationProfile profile = new ApplicationProfile("GarbageCollector.jsap"); chatServer = new GarbageCollector(profile,"GARBAGE","REMOVE"); if (chatServer.subscribe(null) == null) return; logger.info("Up and running"); logger.info("Press any key to exit..."); try { system.in.read(); } catch (IOException e) { logger.debug(e.getMessage()); } }
public static void configureEndpoint(String endpointPath,Class endpointClass,Class handshakeHandlerClass,luceeApp app) throws ClassNotFoundException,illegalaccessexception,InstantiationException,PageException { ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(endpointClass,endpointPath).configurator( (ServerEndpointConfig.Configurator) handshakeHandlerClass.newInstance()).build(); try { ServerContainer serverContainer = (ServerContainer) app.getServletContext().getAttribute( "javax.websocket.server.ServerContainer"); serverContainer.addEndpoint(serverEndpointConfig); } catch (DeploymentException ex) { app.log(Log.LEVEL_DEBUG,"Failed to register endpoint " + endpointPath + ": " + ex.getMessage(),app.getName(),"websocket"); } // System.out.println(Configurator.class.getName() + " >>> exit configureEndpoint()"); }
private int parseStatus(String line) throws DeploymentException { // This client only understands HTTP 1. // RFC2616 is case specific String[] parts = line.trim().split(" "); // CONNECT for proxy may return a 1.0 response if (parts.length < 2 || !("HTTP/1.0".equals(parts[0]) || "HTTP/1.1".equals(parts[0]))) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.invalidStatus",line)); } try { return Integer.parseInt(parts[1]); } catch (NumberFormatException nfe) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.invalidStatus",line)); } }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); try { sc.addEndpoint(Async.class); sc.addEndpoint(Basic.class); sc.addEndpoint(BasiclimitLow.class); sc.addEndpoint(BasiclimitHigh.class); sc.addEndpoint(RootEcho.class); } catch (DeploymentException e) { throw new IllegalStateException(e); } }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( Bug58624ServerEndpoint.class,PATH).build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( TesterEchoServer.Basic.class,"/{param}").build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); List<Class<? extends Encoder>> encoders = new ArrayList<Class<? extends Encoder>>(); encoders.add(Bug58624Encoder.class); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( Bug58624Endpoint.class,PATH).encoders(encoders).build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce .getServletContext() .getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( getEndpointClass(),PATH).build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@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)); }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); try { sc.addEndpoint(ServerEndpointConfig.Builder.create( ConstantTxEndpoint.class,PATH).build()); if (TestWsWebSocketContainer.timeoutOnContainer) { sc.setAsyncSendTimeout(TIMEOUT_MS); } } catch (DeploymentException e) { throw new IllegalStateException(e); } }
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,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 int parseStatus(String line) throws DeploymentException { // This client only understands HTTP 1. // RFC2616 is case specific String[] parts = line.trim().split(" "); // CONNECT for proxy may return a 1.0 response if (parts.length < 2 || !("HTTP/1.0".equals(parts[0]) || "HTTP/1.1".equals(parts[0]))) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.invalidStatus",line)); } }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); try { sc.addEndpoint(Async.class); sc.addEndpoint(Basic.class); sc.addEndpoint(BasiclimitLow.class); sc.addEndpoint(BasiclimitHigh.class); sc.addEndpoint(RootEcho.class); } catch (DeploymentException e) { throw new IllegalStateException(e); } }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( Bug58624ServerEndpoint.class,PATH).build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( TesterEchoServer.Basic.class,"/{param}").build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); List<Class<? extends Encoder>> encoders = new ArrayList<Class<? extends Encoder>>(); encoders.add(Bug58624Encoder.class); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( Bug58624Endpoint.class,PATH).encoders(encoders).build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@Override public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce .getServletContext() .getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create( getEndpointClass(),PATH).build(); try { sc.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException(e); } }
@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 public void contextinitialized(ServletContextEvent sce) { super.contextinitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); try { sc.addEndpoint(ServerEndpointConfig.Builder.create( ConstantTxEndpoint.class,PATH).build()); if (TestWsWebSocketContainer.timeoutOnContainer) { sc.setAsyncSendTimeout(TIMEOUT_MS); } } catch (DeploymentException e) { throw new IllegalStateException(e); } }
public void connect(long timeout,TimeUnit unit) throws DeploymentException,EncodeException,InterruptedException,ExecutionException,TimeoutException { if (getState() != State.disCONNECTED) { throw new IllegalStateException("Connection open,or in progress!"); } this.session = ContainerProvider.getWebSocketContainer().connectToServer(this,this.uri); this.state = State.CONNECTING; final Frame connectFrame = Frame.connect(this.uri.getHost(),"1.2").heartbeat(5_000,5_000).build(); sendToClient(connectFrame); this.connectFuture = new CompletableFuture<>(); final Frame connectedFrame = this.connectFuture.get(timeout,unit); this.connectFuture = null; final long readDelay = Math.max(connectedFrame.heartBeat().get().x,connectFrame.heartBeat().get().y); final long writeDelay = Math.max(connectFrame.heartBeat().get().x,connectedFrame.heartBeat().get().y); this.heartBeatMonitor.start(readDelay,writeDelay); }
/** * Sends message to the WebSocket server. * * @param endpoint The server endpoint * @param msg The message * @return a return message */ private String sendMessage(String endpoint,String msg) { LOGGER.config(() -> "Sending message: " + msg); String returnValue = "-1"; try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); String uri = serviceUrl + endpoint; Session session = container.connectToServer(this,URI.create(uri)); session.getBasicRemote().sendText(msg != null ? msg : ""); returnValue = session.getId(); session.close(); } catch (DeploymentException | IOException ex) { LOGGER.warning(ex.getMessage()); } return returnValue; }
@Override public void contextinitialized(final ServletContextEvent servletContextEvent) { super.contextinitialized(servletContextEvent); final ServerContainer serverContainer = (ServerContainer) servletContextEvent.getServletContext() .getAttribute("javax.websocket.server.ServerContainer"); if (serverContainer != null) { try { serverContainer.addEndpoint(ServerEndpointConfig.Builder .create(SubscriptionEndpoint.class,"/ContextManager/{" + PATH_NAME + "}").build()); // serverContainer.addEndpoint(ServerEndpointConfig.Builder // .create(ExtendedSubscriptionEndpoint.class,// "/ContextManager/{contextParticipantId}") // .configurator(new WebSocketsConfigurator()).build()); } catch (final DeploymentException e) { throw new RuntimeException(e.getMessage(),e); } } }
protected void addEndpoint(final Class<?> cls) { final ServerContainer container = getServerContainer(); if (container == null) { LOG.warn("ServerContainer is null. Skip registration of websocket endpoint {}",cls); return; } try { LOG.debug("Register endpoint {}",cls); final ServerEndpointConfig config = createEndpointConfig(cls); container.addEndpoint(config); } catch (final DeploymentException e) { addError(e); } }
@Override public Object createdEndpoint(ServerEndpointRegistration registration,ComponentProviderService provider,WebSocketContainer container,TyrusWebSocketEngine engine) throws DeploymentException { DirectFieldAccessor accessor = new DirectFieldAccessor(engine); Object sessionListener = accessor.getPropertyValue("sessionListener"); Object clusterContext = accessor.getPropertyValue("clusterContext"); try { if (constructorWithBooleanArgument) { // Tyrus 1.11+ return constructor.newInstance(registration.getEndpoint(),registration,provider,container,"/",registration.getConfigurator(),sessionListener,clusterContext,null,Boolean.TRUE); } else { return constructor.newInstance(registration.getEndpoint(),null); } } catch (Exception ex) { throw new HandshakeFailureException("Failed to register " + registration,ex); } }
/** * Connects the current agent to a server. * * @param serverAddress * - address of the agent we want to connect to. * @param webSocketPort * - the port number,on which the Server is listening * @param agentId * - An identifier of the current agent * @throws URISyntaxException * - thrown to indicate that a string Could not be parsed as a URI reference * @throws IOException * - thrown when I/O exception of some sort has occurred * @throws DeploymentException * - failure to publish an endpoint on its server,or a failure to connect a client to its server */ public void connectToServer(String serverAddress,int webSocketPort,String agentId) throws DeploymentException,URISyntaxException { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.setDefaultMaxTextMessageBufferSize(Integer.MAX_VALUE); String uriAddress = String.format(SERVER_URI,serverAddress,webSocketPort); this.session = container.connectToServer(AgentEndpoint.class,new URI(uriAddress)); List<Deviceinformation> connectedDevicesinformation = deviceManager.getDevicesinformation(); Deviceinformation[] devicesinformationArray = connectedDevicesinformation.toArray(new Deviceinformation[0]); RequestMessage registeragentRequest = new RequestMessage(MessageAction.REGISTER_AGENT,agentId,devicesinformationArray); String registeragentJsonRequest = jsonUtil.serialize(registeragentRequest); sendText(registeragentJsonRequest,session); LOGGER.debug("Connected to server address: " + uriAddress); agentManager.registerServer(); LOGGER.info("The Server(" + serverAddress + ":" + webSocketPort + ") is registered for the device changed event notifications."); }
/** * Creates a new {@link ComputeRealtimeServer} * * @param config * The chatalytics config * @return A newly created {@link ComputeRealtimeServer} */ public ComputeRealtimeServer createComputeRealtimeServer() { Server server = new Server(config.computeConfig.rtComputePort); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setcontextpath("/"); ServletHolder jerseyServlet = context.addServlet(ServletContainer.class,"/*"); jerseyServlet.setinitParameter(PackagesResourceConfig.PROPERTY_PACKAGES,StatusResource.class.getPackage().toString()); server.setHandler(context); ServerContainer wscontainer; try { wscontainer = WebSocketServerContainerInitializer.configureContext(context); wscontainer.addEndpoint(RealtimeResource.class); } catch (servletexception | DeploymentException e) { throw new RuntimeException("Can't instantiate websocket. Reason: " + e.getMessage()); } return new ComputeRealtimeServer(server); }
/** * Starts the WebSocket server on the address and port from the config file. * * @param serverAddress * - an IP address for the WebSocket connection * @param websocketPort * - a port for the WebSocket connection */ public void startWebSocketServer(String serverAddress,int websocketPort) { server = new org.glassfish.tyrus.server.Server(serverAddress,websocketPort,ClientServerEndpoint.class,ServerAgentEndpoint.class); LOGGER.info("Websocket Server started on port " + websocketPort); try { server.start(); } catch (DeploymentException e) { LOGGER.error("Could not start WebSocket server.",e); } }
@Test(timeout = 0) public void testSessions() throws DeploymentException,InterruptedException{ Thread.sleep(500); assertTrue(WebsocketServer.isRunning()); WebsocketClient client = new WebsocketClient("ws://localhost:8787/websocket"); WebsocketClient client2 = new WebsocketClient("ws://localhost:8787/websocket"); WebsocketClient client3 = new WebsocketClient("ws://localhost:8787/websocket"); WebsocketClient client4 = new WebsocketClient("ws://localhost:8787/websocket"); int actualClients = WebsocketServer.getSessions().size(); assertSame(actualClients,4 * 2); //why *2? every client is added twice to session list (server and client connection). client.close(); client2.close(); client3.close(); client4.close(); Thread.sleep(200); actualClients = WebsocketServer.getSessions().size(); assertSame(actualClients,0); }
@Test @InSequence(2) public void testNotificationWhenBecameAWriter() throws URISyntaxException,InterruptedException { final String writer = "@mgreau"; final String JSONNotificationWhenBecameAWriter = "{\"type\":\"notification\",\"adocId\":\"" + ADOC_ID + "\",\"data\":{\"nbConnected\":0,\"nbWriters\":1,\"writers\":{\"" + writer + "\":\"" + writer + "\"}}}"; // notifOnopen - notifWhenSend Adoc - output MyBasicEndpointClient endpoint = new MyBasicEndpointClient(); Session session = connectToServer(MyBasicEndpointClient.class,ADOC_URL + ADOC_ID); assertNotNull(session); session.getBasicRemote().sendText(dataConvertToPDF); await().timeout(50000,TimeUnit.MILLISECONDS).untilCall(to(endpoint).getNotificationMessage(),is(equalTo(JSONNotificationWhenBecameAWriter))); }
public static void connect(String clientString) throws IOException { if (clientString.startsWith(NEW_CLIENT) ) { clientString = clientString.substring(NEW_CLIENT.length()); WebSocketContainer c = ContainerProvider.getWebSocketContainer(); Hello.log(AnnotatedClientEndpoint.class,"Starting the client for " + clientString); URI uriServerEP = URI.create(clientString); try { Session s = c.connectToServer(AnnotatedClientEndpoint.class,uriServerEP); // we're just going to maintain one client at a time,so reading the output // can be somewhat sane.. Set the new session,and close the old one. s = clientConnection.getAndSet(s); if ( s != null ) s.close(); } catch (DeploymentException e) { e.printstacktrace(); } } }
/** * Sends message to the WebSocket server. * * @param endpoint The server endpoint * @param msg The message * @return a return message */ private String sendMessage(String endpoint,URI.create(uri)); session.getBasicRemote().sendText(msg != null ? msg : ""); returnValue = session.getId(); } catch (DeploymentException | IOException ex) { LOGGER.warning(ex.getMessage()); } return returnValue; }
@Override public void contextinitialized(ServletContextEvent servletContextEvent) { ServletContext context = servletContextEvent.getServletContext(); final ServerContainer serverContainer = (ServerContainer) context .getAttribute("javax.websocket.server.ServerContainer"); try { context.setAttribute("protocol",new MetadataProtocol()); //attach the WebSockets Endpoint to the web container serverContainer.addEndpoint(WebSocketEndpoint.class); logger.log(Level.INFO,"HOPSWORKS DEPLOYED"); } catch (DeploymentException ex) { logger.log(Level.SEVERE,ex.getMessage(),ex); } }
@Override public void contextinitialized(ServletContextEvent sce) { // initialize DiqubeServletConfig WebApplicationContext ctx = WebApplicationContextUtils.getrequiredWebApplicationContext(sce.getServletContext()); ctx.getBean(DiqubeServletConfig.class).initialize(sce.getServletContext()); // register our Websocket Endpoint ServerContainer serverContainer = (ServerContainer) sce.getServletContext().getAttribute(ATTR_SERVER_CONTAINER); ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(WebSocketEndpoint.class,WebSocketEndpoint.ENDPOINT_URL_MAPPING).build(); sec.getUserProperties().put(WebSocketEndpoint.PROP_BEAN_CONTEXT,ctx); try { serverContainer.addEndpoint(sec); } catch (DeploymentException e) { throw new RuntimeException("DeploymentException when deploying Websocket endpoint",e); } }
@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,cec,uriServerEP); }
/** * Create session * * @param jsessionid * @param userpwd * @return */ protected Session createAndGetSession(String jsessionid,String userpwd) { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); try { StringBuilder sb = new StringBuilder("ws://localhost:"); sb.append(PORT).append(Constants.SLASH).append(CTXPATH).append(Constants.SLASH).append("ocelot-endpoint"); URI uri = new URI(sb.toString()); return container.connectToServer(new Endpoint() { @Override public void onopen(Session session,EndpointConfig config) { } },createClientEndpointConfigWithJsession(jsessionid,userpwd),uri); } catch (URISyntaxException | DeploymentException | IOException ex) { ex.getCause().printstacktrace(); fail("CONNEXION Failed " + ex.getMessage()); } return null; }
com.lowagie.text.DocumentException的实例源码
/** * Título del documento. * @param document Documento en cuestión * @throws DocumentException Excepcion generada por algún problema */ private void addTitlePage(Document document) throws DocumentException { Paragraph preface = new Paragraph(); addEmptyLine(preface,1); preface.add(new Paragraph("CitizensLoader PDF",catFont)); // addEmptyLine(preface,1); // // Will create: Report generated by: _name,_date // preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + "," + new Date(),//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // smallBold)); // addEmptyLine(preface,3); // preface.add(new Paragraph("This document describes something which is very important ",smallBold)); // // addEmptyLine(preface,8); // // preface.add(new Paragraph( // "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",// redFont)); // // document.add(preface); // // Start a new page // document.newPage(); document.add(preface); addEmptyLine(preface,2); }
@Override public void close() throws IOException { try { float width = 0; float[] w = new float[iMaxWidth.length - iHiddenColumns.size()]; int wi = 0; for (int i = 0; i < iMaxWidth.length; i++) if (!iHiddenColumns.contains(i)) { width += 15f + iMaxWidth[i]; w[wi++] = iMaxWidth[i]; } Document document = new Document(new Rectangle(60f + width,60f + width * 0.75f),30f,30f); PdfWriter writer = PdfWriter.getInstance(document,IoUtput); writer.setPageEvent(new PdfEventHandler()); document.open(); iTable.setWidths(w); document.add(iTable); document.close(); } catch (DocumentException e) { throw new IOException(e.getMessage(),e); } }
@Override protected void crearCarta(Citizen citizen) throws FileNotFoundException,DocumentException,IOException { XWPFDocument documento = new XWPFDocument(); File folder = new File("Letter/WORD"); folder.mkdir(); letter = new FileOutputStream( "Letter/WORD/" + citizen.getDni() + ".docx"); XWPFParagraph paragraph = documento.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText("Usuario: " + citizen.getDni()); run.addBreak(); run.addBreak(); run.setText("Password: " + citizen.getpassword()); documento.write(letter); documento.close(); }
@Override public void createDocument(String documentName,String content) throws CitizenException { String realPath = FILE_PATH + documentName + ".pdf"; Document doc = new Document(); try { PdfWriter.getInstance(doc,new FileOutputStream(realPath)); doc.open(); addMetaData(doc); addTitlePage(doc); addContent(doc,content); } catch (DocumentException | FileNotFoundException e) { throw new CitizenException("Error al generar documento pdf" + " ["+ FILE_PATH+documentName+".pdf] | ["+this.getClass().getName()+"]"); } finally { if (doc != null) { doc.close(); } } }
public static void convertWritetoPdf(BufferedImage bufeBufferedImage,String path) { try { //Image img = Image.getInstance("C:\\Users\\SOFTWARE1\\Desktop\\boshtwain4JImages\\testcapture1507134499431.jpg"); Image img = Image.getInstance(bufeBufferedImage,null); Document document = new Document(img); PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(path)); //-- document.open(); img.setAbsolutePosition(0,0); //-- document.add(img); //-- document.close(); } catch (DocumentException | IOException e) { System.out.println("Intern Log : " + e.getMessage()); } }
@Override public void printReport() throws DocumentException { setHeader(buildHeaderString()); List results = getAuditResults(getSubjectAreas()); Vector<String> lines = new Vector<String>(); Iterator it = results.iterator(); while(it.hasNext()) { MultipleCourseEnrollmentsAuditResult result = new MultipleCourseEnrollmentsAuditResult((Object[]) it.next()); lines.add(buildLinestring(result)); } printHeader(); for (String str : lines) { println(str); } if (!lines.isEmpty()){ lastPage(); } }
@Override public void printReport() throws DocumentException { setHeader(buildHeaderString()); List results = getAuditResults(getSubjectAreas()); Vector<String> lines = new Vector<String>(); Iterator it = results.iterator(); while(it.hasNext()) { EnrollmentsViolatingCourseStructureAuditResult result = new EnrollmentsViolatingCourseStructureAuditResult((Object[]) it.next()); lines.add(buildLinestring(result)); } printHeader(); for (String str : lines) { println(str); } if (!lines.isEmpty()){ lastPage(); } }
@Override public void printReport() throws DocumentException { setHeader(buildHeaderString()); List results = getAuditResults(getSubjectAreas()); Vector<String> lines = new Vector<String>(); Iterator it = results.iterator(); while(it.hasNext()) { MissingCourseEnrollmentsAuditResult result = new MissingCourseEnrollmentsAuditResult((Object[]) it.next()); lines.add(buildLinestring(result)); } printHeader(); for (String str : lines) { println(str); } if (!lines.isEmpty()){ lastPage(); } }
public void open(OutputStream out,int mode) throws DocumentException,IOException { IoUt = out; if (mode==sModeText) { iPrint = new PrintWriter(IoUt); } else { iNrLines = (mode==sModeLedger?116:50); iDoc = new Document(mode==sModeLedger?PageSize.LEDGER.rotate():PageSize.LETTER.rotate()); PdfWriter.getInstance(iDoc,IoUt); iDoc.addTitle(iTitle); iDoc.addAuthor("UniTime "+Constants.getVersion()+",www.unitime.org"); iDoc.addSubject(iSubject); iDoc.addCreator("UniTime "+Constants.getVersion()+",www.unitime.org"); iDoc.open(); } iEmpty = true; iPageNo = 0; iLineNo = 0; }
public static boolean print(OutputStream out,Collection<SubjectArea> subjectAreas) throws IOException,DocumentException { TreeSet courses = new TreeSet(new Comparator() { public int compare(Object o1,Object o2) { CourSEOffering co1 = (CourSEOffering)o1; CourSEOffering co2 = (CourSEOffering)o2; int cmp = co1.getCourseName().compareto(co2.getCourseName()); if (cmp != 0) return cmp; return co1.getUniqueId().compareto(co2.getUniqueId()); } }); String subjectIds = ""; for (SubjectArea sa: subjectAreas) subjectIds += (subjectIds.isEmpty() ? "" : ",") + sa.getUniqueId(); courses.addAll(SessionDAO.getInstance().getSession().createquery( "select co from CourSEOffering co where co.subjectArea.uniqueId in (" + subjectIds + ")").list()); if (courses.isEmpty()) return false; PdfWorksheet w = new PdfWorksheet(out,subjectAreas,null); for (Iterator i=courses.iterator();i.hasNext();) { w.print((CourSEOffering)i.next()); } w.lastPage(); w.close(); return true; }
public void start() throws DocumentException,IOException { //Create the font we are going to print to bf = BaseFont.createFont(BaseFont.HELVETICA,BaseFont.CP1252,BaseFont.NOT_EMbedDED); font = new Font(bf,FONTSIZE,Font.norMAL); boldFont = new Font(bf,Font.BOLD); //Create the document we are going to write to document = new Document(); writer = PdfWriterFactory.newInstance(document,os,FontSettings.HELVETICA_10PT); // writer = PdfWriter.getInstance(document,os); // writer.setPageEvent(new EndPage()); writer.setStrictimageSequence(true); document.setPageSize(PageSize.LETTER); document.open(); }
int reorderPages(int order[]) throws DocumentException { if (order == null) return pages.size(); if (parents.size() > 1) throw new DocumentException("Page reordering requires a single parent in the page tree. Call PdfWriter.setLinearMode() after open."); if (order.length != pages.size()) throw new DocumentException("Page reordering requires an array with the same size as the number of pages."); int max = pages.size(); boolean temp[] = new boolean[max]; for (int k = 0; k < max; ++k) { int p = order[k]; if (p < 1 || p > max) throw new DocumentException("Page reordering requires pages between 1 and " + max + ". Found " + p + "."); if (temp[p - 1]) throw new DocumentException("Page reordering requires no page repetition. Page " + p + " is repeated."); temp[p - 1] = true; } Object copy[] = pages.toArray(); for (int k = 0; k < max; ++k) { pages.set(k,copy[order[k] - 1]); } return max; }
void writeFont(PdfWriter writer,PdfIndirectReference ref,Object params[]) throws DocumentException,IOException { IntHashtable cjkTag = (IntHashtable)params[0]; PdfIndirectReference ind_font = null; PdfObject pobj = null; PdfIndirectObject obj = null; pobj = getFontDescriptor(); if (pobj != null){ obj = writer.addToBody(pobj); ind_font = obj.getIndirectReference(); } pobj = getCIDFont(ind_font,cjkTag); if (pobj != null){ obj = writer.addToBody(pobj); ind_font = obj.getIndirectReference(); } pobj = getFontBaseType(ind_font); writer.addToBody(pobj,ref); }
private PdfPTable createNeedHeader(String name) throws DocumentException { Font whiteFont = new Font(Font.HELVETICA,14,Font.BOLD,Color.WHITE); PdfPTable table = new PdfPTable(3); table.setWidthPercentage(100); table.setWidths(new float[]{0.10f,0.20f,0.70f}); PdfPCell emptyCell = new PdfPCell(); emptyCell.setBorder(0); table.addCell(emptyCell); PdfPCell headerCell = new PdfPCell(); headerCell.setColspan(2); headerCell.setPhrase(new Phrase(name,whiteFont)); headerCell.setHorizontalAlignment(Element.ALIGN_CENTER); headerCell.setBackgroundColor(Color.LIGHT_GRAY); table.addCell(headerCell); return table; }
private float calculateFontSize(float w,float h) throws IOException,DocumentException { BaseFont ufont = getRealFont(); float fsize = fontSize; if (fsize == 0) { float bw = ufont.getWidthPoint(text,1); if (bw == 0) fsize = 12; else fsize = w / bw; float nfsize = h / (1 - ufont.getFontDescriptor(BaseFont.DESCENT,1)); fsize = Math.min(fsize,nfsize); if (fsize < 4) fsize = 4; } return fsize; }
/** * */ protected void exportPage(JRPrintPage page) throws JRException,IOException { tagHelper.startPage(); Collection<JRPrintElement> elements = page.getElements(); exportElements(elements); tagHelper.endPage(); JRExportProgressMonitor progressMonitor = getCurrentItemConfiguration().getProgressMonitor(); if (progressMonitor != null) { progressMonitor.afterPageExport(); } }
private void setPageNumbers() throws DocumentException,IOException { int pages = getReader().getNumberOfPages(); int i = 0; PdfContentByte overContent; Rectangle pageSize = null; BaseFont font = BaseFont.createFont(BaseFont.HELVETICA,BaseFont.WINANSI,BaseFont.EMbedDED); while (i < pages) { i++; overContent = getStamper().getoverContent(i); pageSize = overContent.getPdfDocument().getPageSize(); overContent.beginText(); overContent.setFontAndSize(font,9); overContent.setTextMatrix(pageSize.getWidth() - 50,pageSize.getHeight() - 70); overContent.showtext("Page " + i + " of " + pages); overContent.endText(); } }
private void addCell_WithDropDownListField( PdfPTable table,Rectangle rect,PdfWriter writer,PdfPCell cell,String strfldName,String[] optionList,String[] valueList ) throws IOException,DocumentException { TextField textList = new TextField( writer,rect,strfldName ); textList.setChoices( optionList ); textList.setChoiceExports( valueList ); textList.setBorderWidth( 1 ); textList.setBorderColor( Color.BLACK ); textList.setBorderStyle( PdfBorderDictionary.STYLE_SOLID ); textList.setBackgroundColor( COLOR_BACKGROUDTEXTBox ); PdfFormField dropDown = textList.getComboField(); cell.setCellEvent( new PdfFieldCell( dropDown,rect.getWidth(),rect.getHeight(),writer ) ); table.addCell( cell ); }
/** * Adds an Element to the Document * * @param element The element to be added * @return <code>false</code> * @throws DocumentException */ public boolean add(Element element) throws DocumentException { if (pause) { return false; } RtfBasicElement[] rtfElements = rtfDoc.getMapper().mapElement(element); if(rtfElements.length != 0) { for(int i = 0; i < rtfElements.length; i++) { if(rtfElements[i] != null) { rtfDoc.add(rtfElements[i]); } } return true; } else { return false; } }
@Test public void testTableSpacingPercentage() throws FileNotFoundException,DocumentException { Document document = PdfTestBase .createPdf("testTableSpacingPercentage.pdf"); document.setMargins(72,72,72); document.open(); PdfPTable table = new PdfPTable(1); table.setSpacingBefore(20); table.setWidthPercentage(100); PdfPCell cell; cell = new PdfPCell(); Phrase phase = new Phrase("John Doe"); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // This has no // effect cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // This has no effect cell.addElement(phase); table.addCell(cell); document.add(table); document.close(); }
public PdfRecordPrinter(HttpServletRequest request,OutputStream os) throws DocumentException,IOException { this.request = request; this.os = os; formatter = new SimpleDateFormat("dd-MMM-yyyy"); //Create the font we are going to print to bf = BaseFont.createFont(BaseFont.HELVETICA,Font.BOLD); //Create the document we are going to write to document = new Document(); writer = PdfWriter.getInstance(document,os); writer.setPageEvent(new EndPage()); writer.setStrictimageSequence(true); document.setPageSize(PageSize.LETTER); document.open(); }
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){ if(!securityInfoManager.hasPrivilege(LoggedInInfo.getLoggedInInfoFromSession(request),"_prevention","r",null)) { throw new SecurityException("missing required security object (_prevention)"); } try { PreventionPrintPdf pdf = new PreventionPrintPdf(); pdf.printPdf(request,response); }catch(DocumentException de) { logger.error("",de); request.setAttribute("printError",new Boolean(true)); return mapping.findForward("error"); } catch(IOException ioe) { logger.error("",ioe); request.setAttribute("printError",new Boolean(true)); return mapping.findForward("error"); } return null; }
private void addPageNumbers(File file,String fileName) throws IOException,DocumentException { PdfReader reader = new PdfReader(file.getAbsolutePath()); int n = reader.getNumberOfPages(); pdfstamper stamp = new pdfstamper(reader,new FileOutputStream(fileName)); int i = 0; PdfContentByte over; BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,BaseFont.EMbedDED); float width = reader.getPageSize(1).getWidth(); while (i < n) { i++; over = stamp.getoverContent(i); over.beginText(); over.setFontAndSize(bf,PAGE_NUMBER_FONT_SIZE); over.setTextMatrix((width / 2) - (PAGE_NUMBER_WIDTH / 2),PAGE_NUMBER_HEIGHT); over.showtext(i + "/" + n); over.endText(); } stamp.close(); }
@Override protected void crearCarta(Citizen citizen) throws DocumentException,IOException { File letter = new File("Letter/TXT/" + citizen.getDni() + ".txt"); writer = new FileWriter(letter); writer.write("Usuario: " + citizen.getDni() + "\n" + "Password: " + citizen.getpassword()); }
public void printReport(ExamInstructorInfo instructor) throws DocumentException { TreeSet<ExamAssignmentInfo> exams = new TreeSet(); for (ExamAssignmentInfo exam:getExams()) { if (exam.getPeriod()==null) continue; if (exam.getInstructors().contains(instructor)); } if (exams.isEmpty()) return; printHeader(); printReport(instructor,exams); lastPage(); }
public void printReport(Long studentId) throws DocumentException { TreeSet<ExamSectionInfo> sections = new TreeSet(); for (ExamAssignmentInfo exam : getExams()) { if (exam.getPeriod()==null) continue; for (ExamSectionInfo section : exam.getSectionsIncludeCrosslistedDummies()) if (section.getStudentIds().contains(studentId)) sections.add(section); } if (sections.isEmpty()) return; Student student = new StudentDAO().get(studentId); printHeader(); printReport(student,sections); lastPage(); }
public ConflictsByCourseAndStudentReport(int mode,File file,Session session,ExamType examType,Collection<SubjectArea> subjectAreas,Collection<ExamAssignmentInfo> exams) throws IOException,DocumentException { super(mode,file,"CONFLICTS BY COURSE AND STUDENT",session,examType,exams); sLog.debug(" Loading students ..."); for (Iterator i=new StudentDAO().getSession().createquery("select s.uniqueId,s.externalUniqueId,s.lastName,s.firstName,s.middleName from Student s where s.session.uniqueId=:sessionId").setLong("sessionId",session.getUniqueId()).iterate();i.hasNext();) { Object[] o = (Object[])i.next(); if (o[2]!=null) iStudentNames.put((Long)o[0],(String)o[2]+(o[3]==null?"":" "+(String)o[3])+(o[4]==null?"":" "+(String)o[4])); else if (o[1]!=null) iStudentNames.put((Long)o[0],(String)o[1]); else iStudentNames.put((Long)o[0],"N/A"); } }
public PdfLegacyExamReport(int mode,OutputStream out,String title,Collection<ExamAssignmentInfo> exams) throws DocumentException,IOException { super(mode,out,title,ApplicationProperty.ExaminationPdfReportTitle.value(examType == null ? "all" : examType.getReference(),examType == null ? "EXAMINATIONS" : examType.getLabel().toupperCase() + " EXAMINATIONS"),title + " -- " + session.getLabel(),session.getLabel()); if (subjectAreas!=null && subjectAreas.size() == 1) setFooter(subjectAreas.iterator().next().getSubjectAreaAbbreviation()); iExams = exams; iSession = session; iExamType = examType; iSubjectAreas = subjectAreas; idispRooms = "true".equals(System.getProperty("room","true")); idispNote = "true".equals(System.getProperty("note","false")); iCompact = "true".equals(System.getProperty("compact","false")); inoroom = System.getProperty("noroom",ApplicationProperty.ExaminationsnoroomText.value()); iDirect = "true".equals(System.getProperty("direct","true")); iM2d = "true".equals(System.getProperty("m2d",(examType == null || examType.getType() == ExamType.sExamTypeFinal?"true":"false"))); iBtb = "true".equals(System.getProperty("btb","false")); iLimit = Integer.parseInt(System.getProperty("limit","-1")); iItype = "true".equals(System.getProperty("itype",ApplicationProperty.ExaminationReportsShowInstructionalType.value())); iTotals = "true".equals(System.getProperty("totals","true")); iUseClassSuffix = "true".equals(System.getProperty("suffix",ApplicationProperty.ExaminationReportsClassSufix.value())); iExternal = ApplicationProperty.ExaminationReportsExternalId.isTrue(); idispLimits = "true".equals(System.getProperty("verlimit","true")); iClassSchedule = "true".equals(System.getProperty("cschedule",ApplicationProperty.ExaminationPdfReportsIncludeClassSchedule.value())); iDispfullTermDates = "true".equals(System.getProperty("fullterm","false")); iRoomdisplayNames = "true".equals(System.getProperty("roomdispNames","true")); iFullTermCheckDatePattern = ApplicationProperty.ExaminationPdfReportsFullTermCheckDatePattern.isTrue(); iMeetingTimeUseEvents = ApplicationProperty.ExaminationPdfReportsUseEventsForMeetingTimes.isTrue(); if (System.getProperty("since")!=null) { try { iSince = new SimpleDateFormat(System.getProperty("sinceFormat","MM/dd/yy")).parse(System.getProperty("since")); } catch (Exception e) { sLog.error("Unable to parse date "+System.getProperty("since")+",reason: "+e.getMessage()); } } setRoomCode(System.getProperty("roomcode",ApplicationProperty.ExaminationRoomCode.value())); }
public PdfLegacyReport(int mode,String title2,String subject,String session) throws IOException,DocumentException{ iTitle = title; iTitle2 = title2; iSubject = subject; iSession = session; if (file!=null) open(new FileOutputStream(file),mode); }
public PdfLegacyReport(int mode,DocumentException{ iTitle = title; iTitle2 = title2; iSubject = subject; iSession = session; if (out!=null) open(out,mode); }
public void printHeader() throws DocumentException { out(renderEnd( renderMiddle("UniTime "+Constants.getVersion(),iTitle),iTitle2)); out(mpad( new SimpleDateFormat("EEE MMM dd,yyyy").format(new Date()),iSession,' ',iNrChars)); outln('='); iLineNo=0; if (iCont!=null && iCont.length()>0) println("("+iCont+" Continued)"); if (iHeader!=null) for (int i=0;i<iHeader.length;i++) println(iHeader[i]); headerPrinted(); }
protected void printFooter() throws DocumentException { iEmpty=false; out(""); out(renderEnd(renderMiddle((iFooter==null?"":iFooter),"Page "+(iPageNo+1)),(iPageId==null||iPageId.length()==0?"":iPageId)+" ")); if (iPrint!=null) { iPrint.print(iBuffer); } else { //FIXME: For some reason when a line starts with space,the line is shifted by one space in the resulting PDF (when using iText 5.0.2) Paragraph p = new Paragraph(iBuffer.toString().replace("\n ","\n "),PdfFont.getFixedFont()); p.setLeading(9.5f); //was 13.5f iDoc.add(p); } iBuffer = new StringBuffer(); iPageNo++; }
protected void newPage() throws DocumentException { while (iLineNo<iNrLines) { out(""); iLineNo++; } printFooter(); if (iPrint!=null) { iPrint.print("\f\n"); } else { iDoc.newPage(); } printHeader(); }
public void close() throws IOException,DocumentException { if (isEmpty()) { println("nothing to report."); lastPage(); } if (iPrint!=null) { iPrint.flush(); iPrint.close(); } else { iDoc.close(); IoUt.close(); } }
/** * Constructor for PdfEventHandler * */ public PdfEventHandler() throws DocumentException,IOException { super(); Font font = PdfFont.getSmallFont(); setBaseFont(font.getBaseFont()); setFontSize(font.getSize()); return; }
/** * Initialize Pdf footer * @param document * @param outputStream * @return PdfWriter */ public static PdfWriter initFooter(Document document,OutputStream outputStream) throws DocumentException,IOException { PdfWriter iWriter = PdfWriter.getInstance(document,outputStream); iWriter.setPageEvent(new PdfEventHandler()); return iWriter; }
private PdfWorksheet(OutputStream out,String courseNumber) throws IOException,DocumentException { iUseCommitedAssignments = ApplicationProperty.WorksheetPdfUseCommittedAssignments.isTrue(); iSubjectAreas = new TreeSet<SubjectArea>(new Comparator<SubjectArea>() { @Override public int compare(SubjectArea s1,SubjectArea s2) { return s1.getSubjectAreaAbbreviation().compareto(s2.getSubjectAreaAbbreviation()); } }); iSubjectAreas.addAll(subjectAreas); iCourseNumber = courseNumber; if (iCourseNumber!=null && (iCourseNumber.trim().length()==0 || "*".equals(iCourseNumber.trim().length()))) iCourseNumber = null; iDoc = new Document(PageSize.LETTER.rotate()); IoUt = out; PdfWriter.getInstance(iDoc,IoUt); String session = null; String subjects = ""; for (SubjectArea sa: iSubjectAreas) { if (subjects.isEmpty()) subjects += ","; subjects += sa.getSubjectAreaAbbreviation(); if (session == null) session += sa.getSession().getLabel(); } iDoc.addTitle(subjects + (iCourseNumber==null?"":" "+iCourseNumber) + " Worksheet"); iDoc.addAuthor(ApplicationProperty.WorksheetPdfAuthor.value().replace("%",Constants.getVersion())); iDoc.addSubject(subjects + (session == null ? "" : " -- " + session)); iDoc.addCreator("UniTime "+Constants.getVersion()+",www.unitime.org"); if (!iSubjectAreas.isEmpty()) iCurrentSubjectArea = iSubjectAreas.first(); iDoc.open(); printHeader(); }
public static boolean print(OutputStream out,DocumentException { TreeSet courses = new TreeSet(new Comparator() { public int compare(Object o1,Object o2) { CourSEOffering co1 = (CourSEOffering)o1; CourSEOffering co2 = (CourSEOffering)o2; int cmp = co1.getCourseName().compareto(co2.getCourseName()); if (cmp!=0) return cmp; return co1.getUniqueId().compareto(co2.getUniqueId()); } }); List<Long> subjectIds = new ArrayList<Long>(); for (SubjectArea sa: subjectAreas) subjectIds.add(sa.getUniqueId()); String query = "select co from CourSEOffering co where co.subjectArea.uniqueId in :subjectIds"; if (courseNumber != null && !courseNumber.trim().isEmpty()) { if (courseNumber.indexOf('*') >= 0) { query += " and co.courseNbr like :courseNbr "; } else { query += " and co.courseNbr = :courseNbr "; } } Query q = new SessionDAO().getSession().createquery(query); q.setParameterList("subjectIds",subjectIds); if (courseNumber != null && !courseNumber.trim().isEmpty()) q.setParameter("courseNbr",ApplicationProperty.CourSEOfferingNumberUpperCase.isTrue()? courseNumber.trim().replace('*','%').toupperCase() : courseNumber.trim().replace('*','%')); courses.addAll(q.list()); if (courses.isEmpty()) return false; PdfWorksheet w = new PdfWorksheet(out,courseNumber); for (Iterator i=courses.iterator();i.hasNext();) { w.print((CourSEOffering)i.next()); } w.lastPage(); w.close(); return true; }
protected void printHeader() throws DocumentException { out(renderMiddle( ApplicationProperty.WorksheetPdfAuthor.value().replace("%",Constants.getVersion()),ApplicationProperty.WorksheetPdfTitle.value() )); out(mpad( new SimpleDateFormat("EEE MMM dd,iCurrentSubjectArea.getSession().getAcademicInitiative()+" "+ iCurrentSubjectArea.getSession().getAcademicTerm()+" "+ iCurrentSubjectArea.getSession().getAcademicYear(),sNrChars)); outln('='); iLineNo=0; if (iCourSEOffering!=null) println("("+iCourSEOffering.getCourseName()+" Continued)"); }
protected void printFooter() throws DocumentException { out(""); out(renderEnd(renderMiddle("","<"+iCurrentSubjectArea.getSubjectAreaAbbreviation()+(iCourseNumber!=null?" "+iCourseNumber:"")+"> ")); //FIXME: For some reason when a line starts with space,the line is shifted by one space in the resulting PDF (when using iText 5.0.2) Paragraph p = new Paragraph(iBuffer.toString().replace("\n ",PdfFont.getFixedFont()); p.setLeading(9.5f); //was 13.5f iDoc.add(p); iBuffer = new StringBuffer(); iPageNo++; }
Error: weblogic.management.DeploymentException: Cannot set web app root system p
Error: weblogic.management.DeploymentException: Cannot set web app root system p 博客分类: java这2天要将项目以war包得形式发布到weblogic下面,在项目中用到了log4j初始化的的时候是用
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
来加载log4j的。但是发布到weblogc中报错了。
Error: weblogic.management.DeploymentException: Cannot set web app root system property when WAR file is not expanded - with nested exception.
[java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded]
意思找不到那个log4j文件吧。在往上查了下,需要自己写个类加载下log4j文件
package com.dep.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.PropertyConfigurator;
public class Log4jInit extends HttpServlet {
public void init() {
/**
* apache中的调用方法
* String prefix =getServletContext().getRealPath("/");
*
* String file = getInitParameter("log4j");
* // if the log4j-init-file is not set, then no point in trying
*
* System.out.println("................log4j start");
*
* if(file != null) {
*
* PropertyConfigurator.configure(prefix+file);
* }
*
*/
String file = getInitParameter("log4j");
System.out.println("................log4j start");
if (file != null) {
Properties ps=new Properties();
try {
InputStream log = getServletContext().getResourceAsStream(file);
ps.load(log);
} catch (IOException e) {
e.printStackTrace();
}
PropertyConfigurator.configure(ps);
}
}
}
<servlet>
<servlet-name>log4jLoader</servlet-name>
<servlet-class>com.dep.util.Log4jInit</servlet-class>
<init-param>
<param-name>log4j</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
io.jsonwebtoken.ExpiredJwtException的实例源码
@Override public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException,servletexception { try { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String jwt = resolvetoken(httpServletRequest); if (StringUtils.hasText(jwt) && this.tokenProvider.validatetoken(jwt)) { Authentication authentication = this.tokenProvider.getAuthentication(jwt); SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(servletRequest,servletResponse); } catch (ExpiredJwtException eje) { log.info("Security exception for user {} - {}",eje.getClaims().getSubject(),eje.getMessage()); log.trace("Security exception trace: {}",eje); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
public static boolean Verify(String jwt,String type) throws Exception { try{ Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY)) .parseClaimsJws(jwt).getBody(); //verifica se o issuer é igual ao type return claims.getIssuer().equals(type); } catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) { System.out.println(e.getMessage()); return false; } }
@Override public void doFilter(ServletRequest servletRequest,servletexception { try { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String jwt = resolvetoken(httpServletRequest); if (StringUtils.hasText(jwt)) { if (this.tokenProvider.validatetoken(jwt)) { Authentication authentication = this.tokenProvider.getAuthentication(jwt); SecurityContextHolder.getContext().setAuthentication(authentication); } } filterChain.doFilter(servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
private Jws<Claims> parsetokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException { try { return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() { @Override public byte[] resolveSigningKeyBytes(JwsHeader header,Claims claims) { final String identity = claims.getSubject(); // Get the key based on the key id in the claims final String keyId = claims.get(KEY_ID_CLaim,String.class); final Key key = keyService.getKey(keyId); // Ensure we were able to find a key that was prevIoUsly issued by this key service for this user if (key == null || key.getKey() == null) { throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]"); } return key.getKey().getBytes(StandardCharsets.UTF_8); } }).parseClaimsJws(base64EncodedToken); } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) { // Todo: Exercise all exceptions to ensure none leak key material to logs final String errorMessage = "Unable to validate the access token."; throw new JwtException(errorMessage,e); } }
/** * To validate the JWT token e.g Signature check,JWT claims check(expiration) etc * * @param token The JWT access tokens * @param context * @return the AuthenticationStatus to notify the container */ private AuthenticationStatus validatetoken(String token,HttpMessageContext context) { try { if (tokenProvider.validatetoken(token)) { JwtCredential credential = tokenProvider.getCredential(token); //fire an @Authenticated CDI event. authenticatedEvent.fire(new UserInfo(credential.getPrincipal(),credential.getAuthorities())); return context.notifyContainerAboutLogin(credential.getPrincipal(),credential.getAuthorities()); } // if token invalid,response with unauthorized status return context.responseUnauthorized(); } catch (ExpiredJwtException eje) { LOGGER.log(Level.INFO,"Security exception for user {0} - {1}",new String[]{eje.getClaims().getSubject(),eje.getMessage()}); return context.responseUnauthorized(); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Path("dosomething") @POST @Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") public String dosomething(@FormParam(value = "token") String token) throws IOException { String result; try { Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(SECRECT)) .parseClaimsJws(token).getBody(); result = claims.getIssuer(); } catch (ExpiredJwtException exception) { result = "expired"; } return result; }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
@Override public void doFilter(ServletRequest servletRequest,eje.getMessage()); HttpServletResponse reponse = (HttpServletResponse) servletResponse; reponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Token expired (" + eje.getMessage() + ")"); } }
@Test(expected = ExpiredJwtException.class) public void expiredTokenCannotBeRefreshed() throws Exception { when(timeProviderMock.Now()) .thenReturn(DateUtil.yesterday()); String token = createtoken(); jwtTokenUtil.canTokenBeRefreshed(token,DateUtil.tomorrow()); }
private JwtAuthenticatedUser parsetoken(String token) { JwtAuthenticatedUser user = null; try { Claims body = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); user = new JwtAuthenticatedUser(body.getSubject(),Arrays.asList(body.get(ROLE_KEY).toString().split(ROLE_DELIMITER))); } catch (ExpiredJwtException e) { LOGGER.warn("Error token expired",e); } return user; }
private Jws<Claims> parsetoken(final String token) { if (token != null) { try { return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { return null; } } return null; }
@Test(expected=ExpiredJwtException.class) public void testGeneratetokenExpired() { String token = tokenHelper.generatetoken("fanjin"); Jwts.parser() .setSigningKey("mySecret") .parseClaimsJws(token) .getBody(); }
/** * Parses and validates JWT Token signature. * * @throws BadCredentialsException * @throws JwtExpiredTokenException * */ public Jws<Claims> parseClaims(String signingKey) { try { return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token); } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) { logger.error("Invalid JWT Token",ex); throw new BadCredentialsException("Invalid JWT token: ",ex); } catch (ExpiredJwtException expiredEx) { logger.info("JWT Token is expired",expiredEx); throw new JwtExpiredTokenException(this,"JWT Token expired",expiredEx); } }
@Test(expected = ExpiredJwtException.class) public void authenticateIfTokenExpirationFinishedtest() { final User user = createuser(); String token = tokenService.generate(user.getUsername(),user.getpassword()).getToken(); token = modifyTokenExpirationTime(token); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(authHeaderName,token); final Authentication authentication = tokenService.authenticate(request); assertNull(authentication); }
/** * Parses and validates JWT Token signature. * * @throws BadCredentialsException * @throws JwtExpiredTokenException * */ public Jws<Claims> parseClaims(String signingKey) { try { return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token); } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) { logger.error("Invalid JWT Token",expiredEx); } }
@Override public CredentialValidationResult validate(RememberMeCredential rememberMeCredential) { try { if (tokenProvider.validatetoken(rememberMeCredential.getToken())) { JwtCredential credential = tokenProvider.getCredential(rememberMeCredential.getToken()); return new CredentialValidationResult(credential.getPrincipal(),response with invalid result status return INVALID_RESULT; } catch (ExpiredJwtException eje) { LOGGER.log(Level.INFO,new Object[]{eje.getClaims().getSubject(),eje.getMessage()}); return INVALID_RESULT; } }
/** * Parses and validates JWT Token signature. * * @throws BadCredentialsException * @throws JwtExpiredTokenException * */ public Jws<Claims> parseClaims(String signingKey) { try { return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token); } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) { logger.error("Invalid JWT Token",ex); throw new BadCredentialsException("Invalid JWT token: ",ex); } catch (ExpiredJwtException expiredEx) { logger.info("JWT Token is expired",expiredEx); throw new JwtExpiredTokenException(this,expiredEx); } }
@Override public Authentication authenticate(Authentication authentication) { log.debug("Authenticating: {}",authentication); try { final String token = authentication.getCredentials().toString(); final Claims claims = jwtParser.parseClaimsJws(token).getBody(); checkClaims(claims); return new JwtToken(token,claims); } catch (ExpiredJwtException | MalformedJwtException | PrematureJwtException | SignatureException | UnsupportedJwtException e) { log.warn("{}",e); throw new BadCredentialsException(e.getMessage(),e); } }
@Test public void testAuthenticateExpiredException() throws Exception { final String token = "token"; doReturn(token).when(authentication).getCredentials(); doThrow(new ExpiredJwtException(null,null,null)).when(jwtParser).parseClaimsJws(anyString()); exception.expect(BadCredentialsException.class); exception.expectCause(is(instanceOf(ExpiredJwtException.class))); jwtAuthenticationProvider.authenticate(authentication); }
io.jsonwebtoken.JwtException的实例源码
public AuthTokenDetails parseAndValidate(String token) { AuthTokenDetails authTokenDetails = null; try { Claims claims = Jwts.parser().setSigningKey(getSecretKey()) .parseClaimsJws(token) .getBody(); String userId = claims.getSubject(); String username = (String) claims.get("username"); List<String> roleNames = (List) claims.get("roleNames"); Date expirationDate = claims.getExpiration(); authTokenDetails = new AuthTokenDetails(); authTokenDetails.setId(Long.valueOf(userId)); authTokenDetails.setUsername(username); authTokenDetails.setRoleNames(roleNames); authTokenDetails.setExpirationDate(expirationDate); } catch (JwtException ex) { logger.error(ex.getMessage(),ex); } return authTokenDetails; }
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException { // The library representations of the JWT should be kept internal to this service. try { final Jws<Claims> jws = parsetokenFromBase64EncodedString(base64EncodedToken); if (jws == null) { throw new JwtException("Unable to parse token"); } // Additional validation that subject is present if (StringUtils.isEmpty(jws.getBody().getSubject())) { throw new JwtException("No subject available in token"); } // Todo: Validate issuer against active IdentityProvider? if (StringUtils.isEmpty(jws.getBody().getIssuer())) { throw new JwtException("No issuer available in token"); } return jws.getBody().getSubject(); } catch (JwtException e) { logger.debug("The Base64 encoded JWT: " + base64EncodedToken); final String errorMessage = "There was an error validating the JWT"; logger.error(errorMessage,e); throw e; } }
private Jws<Claims> parsetokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException { try { return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() { @Override public byte[] resolveSigningKeyBytes(JwsHeader header,Claims claims) { final String identity = claims.getSubject(); // Get the key based on the key id in the claims final String keyId = claims.get(KEY_ID_CLaim,String.class); final Key key = keyService.getKey(keyId); // Ensure we were able to find a key that was prevIoUsly issued by this key service for this user if (key == null || key.getKey() == null) { throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]"); } return key.getKey().getBytes(StandardCharsets.UTF_8); } }).parseClaimsJws(base64EncodedToken); } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) { // Todo: Exercise all exceptions to ensure none leak key material to logs final String errorMessage = "Unable to validate the access token."; throw new JwtException(errorMessage,e); } }
@Override public AuthenticationResponse authenticate(AuthenticationRequest authenticationRequest) throws InvalidCredentialsException,IdentityAccessException { if (authenticationRequest == null) { logger.info("Cannot authenticate null authenticationRequest,returning null."); return null; } final Object credentials = authenticationRequest.getCredentials(); String jwtAuthToken = credentials != null && credentials instanceof String ? (String) credentials : null; if (credentials == null) { logger.info("JWT not found in authenticationRequest credentials,returning null."); return null; } try { final String jwtPrincipal = jwtService.getAuthenticationFromToken(jwtAuthToken); return new AuthenticationResponse(jwtPrincipal,jwtPrincipal,expiration,issuer); } catch (JwtException e) { throw new InvalidAuthenticationException(e.getMessage(),e); } }
@Test public void Can_fail_parse_a_jwt_token() throws JwtInvalidTokenException { final String token = someString(); final JwtParser parser = mock(JwtParser.class); final JwtParser secretParser = mock(JwtParser.class); final JwtException exception = new JwtException(someString()); // Given given(parserFactory.create()).willReturn(parser); given(parser.setSigningKey(publicKey)).willReturn(secretParser); given(secretParser.parseClaimsJws(token)).willThrow(exception); expectedException.expect(JwtInvalidTokenException.class); expectedException.expectCause(is(exception)); // When decryptor.decrypt(token,Object.class); }
@Override protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain) throws IOException,servletexception { String header = request.getHeader(configurerParams.getHeader()); if (header == null || !header.startsWith(configurerParams.getPrefix())) { chain.doFilter(request,response); return; } UsernamePasswordAuthenticationToken authentication = null; try { authentication = getAuthentication(request); } catch (JwtException | IllegalArgumentException e) { e.printstacktrace(); } SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(request,response); }
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) throws JwtException,IllegalArgumentException { String token = request.getHeader(configurerParams.getHeader()); if (token != null) { String user = Jwts.parser() .setSigningKey(configurerParams.getSecret().getBytes()) .parseClaimsJws(token.replace(configurerParams.getPrefix(),"")) .getBody() .getSubject(); if (user != null) { return new UsernamePasswordAuthenticationToken(user,null,new ArrayList<>()); } return null; } return null; }
@Override public void authenticate(final JsonObject authRequest,final Handler<AsyncResult<HonoUser>> authenticationResultHandler) { final DeliveryOptions options = new DeliveryOptions().setSendTimeout(AUTH_REQUEST_TIMEOUT_MILLIS); vertx.eventBus().send(AuthenticationConstants.EVENT_BUS_ADDRESS_AUTHENTICATION_IN,authRequest,options,reply -> { if (reply.succeeded()) { JsonObject result = (JsonObject) reply.result().body(); String token = result.getString(AuthenticationConstants.FIELD_TOKEN); log.debug("received token [length: {}] in response to authentication request",token.length()); try { Jws<Claims> expandedToken = tokenValidator.expand(result.getString(AuthenticationConstants.FIELD_TOKEN)); authenticationResultHandler.handle(Future.succeededFuture(new HonoUserImpl(expandedToken,token))); } catch (JwtException e) { authenticationResultHandler.handle(Future.FailedFuture(e)); } } else { authenticationResultHandler.handle(Future.FailedFuture(reply.cause())); } }); }
@Override public boolean isValid(final String token,final String tenantId,final String deviceid) { try { Jwts.parser() .setSigningKey(key) .requireSubject(Objects.requireNonNull(deviceid)) .require("ten",Objects.requireNonNull(tenantId)) .setAllowedClockSkewSeconds(10) .parse(token); return true; } catch (JwtException e) { // token is invalid for some reason LOG.debug("Failed to validate token",e); return false; } }
@Override public void doFilter(ServletRequest request,ServletResponse response,servletexception { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; final String authHeaderVal = httpRequest.getHeader(authHeader); if (null==authHeaderVal) { httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } try { JwtUser jwtUser = jwtTokenService.getUser(authHeaderVal); httpRequest.setAttribute("jwtUser",jwtUser); } catch(JwtException e) { httpResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); return; } chain.doFilter(httpRequest,httpResponse); }
public AuthTokenDetailsDTO parseAndValidate(String token) { AuthTokenDetailsDTO authTokenDetailsDTO = null; try { Claims claims = Jwts.parser().setSigningKey(getSecretKey()).parseClaimsJws(token).getBody(); String userId = claims.getSubject(); String email = (String) claims.get("email"); List<String> roleNames = (List<String>) claims.get("roles"); Date expirationDate = claims.getExpiration(); authTokenDetailsDTO = new AuthTokenDetailsDTO(); authTokenDetailsDTO.userId = userId; authTokenDetailsDTO.email = email; authTokenDetailsDTO.roleNames = roleNames; authTokenDetailsDTO.expirationDate = expirationDate; } catch (JwtException ex) { System.out.println(ex); } return authTokenDetailsDTO; }
public static Boolean invalidate(String jwt) { if (jwt == null) return false; String subject; try { subject = getSubject(jwt); } catch(JwtException e) { return false; } if (!userToKeyMap.containsKey(subject)) return false; userToKeyMap.remove(subject); return true; }
@Override public Response refreshTokenRequest(JwtRefreshTokenVO requestTokenVO) { hiveValidator.validate(requestTokenVO); JwtPayload payload; try { payload = tokenService.getPayload(requestTokenVO.getRefreshToken()); } catch (JwtException e) { logger.error(e.getMessage()); return ResponseFactory.response(UNAUTHORIZED); } if (!payload.getTokenType().equals(TokenType.REFRESH.getId())) { logger.warn("JwtToken: refresh token is not valid"); return ResponseFactory.response(UNAUTHORIZED,new ErrorResponse(UNAUTHORIZED.getStatusCode(),INVALID_TOKEN_TYPE)); } if (payload.getExpiration().before(timestampService.getDate())) { logger.warn("JwtToken: refresh token has expired"); return ResponseFactory.response(UNAUTHORIZED,EXPIRED_TOKEN)); } return payload.isUserPayload() ? getRefreshResponse((JwtUserPayload) payload) : getRefreshResponse((JwtPluginPayload) payload); }
@Override public ResponseEntity<Object> settingsPicturetokenGet(@RequestParam(value = "token",required = false) String token) throws ApiException{ // System.out.println("token:" + token); if(token==null || token.trim().length()==0){ //throw new ApiException(403,"Invalid token"); return new ResponseEntity<>(HttpStatus.FORBIDDEN); } Long clientUserId = 0L; try{ Claims claims = JwtCodec.decode(token); clientUserId = Long.parseLong(claims.getSubject()); } catch(JwtException e){ //throw new ApiException(403,"Access denied"); return new ResponseEntity<>(HttpStatus.FORBIDDEN); } com.jrtechnologies.yum.data.entity.User userDAO = userRepo.findById(clientUserId); if(!userDAO.hasPicture()){ //throw new ApiException(404,"No picture"); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } ByteArrayInputStream inputStream = new ByteArrayInputStream(userDAO.getPicture()); return ResponseEntity .ok() .contentLength(userDAO.getPictureLength()) .contentType(MediaType.parseMediaType("image/jpeg")) .body(new InputStreamResource(inputStream)); }
@Override //@PreAuthorize("hasAuthority('admin')") public ResponseEntity<Object> usersIdPictureGet(@RequestParam(value = "token",required = true) String token,@PathVariable("id") Integer id)throws ApiException { com.jrtechnologies.yum.data.entity.User user = userRepo.findById(id); // System.out.println("token:"+token); // System.out.println("id:"+id); if(user==null){ //throw new ApiException(404,"User not found"); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } if(token==null || token.trim().length()==0){ //throw new ApiException(400,"No token") return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } Long clientUserId = 0L; try{ Claims claims = JwtCodec.decode(token); clientUserId = Long.parseLong(claims.getSubject()); } catch(JwtException e){ //throw new ApiException(403,"Access denied"); return new ResponseEntity<>(HttpStatus.FORBIDDEN); } if(!user.hasPicture()){ //throw new ApiException(404,"No picture"); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } ByteArrayInputStream inputStream = new ByteArrayInputStream(user.getPicture()); return ResponseEntity .ok() .contentLength(user.getPictureLength()) .contentType(MediaType.parseMediaType("image/jpeg")) .body(new InputStreamResource(inputStream)); }
public boolean validatetoken(String token) { try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); return true; } catch (JwtException | IllegalArgumentException e) { throw new CustomException("Expired or invalid JWT token",HttpStatus.INTERNAL_SERVER_ERROR); } }
@Override protected String[] decodeCookie(String cookieValue) throws InvalidCookieException { try { Claims claims = Jwts.parser() .setSigningKey(getKey()) .parseClaimsJws(cookieValue) .getBody(); return new String[] { claims.getId(),claims.getSubject() }; } catch (JwtException e) { LOGGER.warn(e.getMessage()); throw new InvalidCookieException(e.getMessage()); } }
@Override public String parse(String token) { try { return Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody() .getSubject(); } catch (JwtException | IllegalArgumentException e) { throw new TokenException(e); } }
/** * Generates a signed JWT token from the provided IdentityProvider AuthenticationResponse * * @param authenticationResponse an instance issued by an IdentityProvider after identity claim has been verified as authentic * @return a signed JWT containing the user identity and the identity provider,Base64-encoded * @throws JwtException if there is a problem generating the signed token */ public String generateSignedToken(final AuthenticationResponse authenticationResponse) throws JwtException { if (authenticationResponse == null) { throw new IllegalArgumentException("Cannot generate a JWT for a null authenticationResponse"); } return generateSignedToken( authenticationResponse.getIdentity(),authenticationResponse.getUsername(),authenticationResponse.getIssuer(),authenticationResponse.getExpiration()); }
private String createAccesstoken(IdentityProvider identityProvider,AuthenticationRequest authenticationRequest) throws InvalidCredentialsException,AdministrationException { final AuthenticationResponse authenticationResponse; try { authenticationResponse = identityProvider.authenticate(authenticationRequest); final String token = jwtService.generateSignedToken(authenticationResponse); return token; } catch (final IdentityAccessException | JwtException e) { throw new AdministrationException(e.getMessage()); } }
@Override public void doFilter(ServletRequest req,ServletResponse res,servletexception { try { Authentication authentication = tokenAuthenticationService.getAuthentication((HttpServletRequest) req); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(req,res); SecurityContextHolder.getContext().setAuthentication(null); } catch (AuthenticationException | JwtException e) { SecurityContextHolder.clearContext(); ((HttpServletResponse) res).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }
public Authentication getExistingAuthentication(final HttpServletRequest request) { final String jwtToken = request.getHeader(AUTH_HEADER_NAME); if (jwtToken != null) { try { final User user = tokenHandler.parseUserFromJwtToken(jwtToken); return new UserAuthentication(user); } catch (final UsernameNotFoundException | JwtException e) { return null; } } return null; }
/** * Parse token details from provided jwt. * * @param rawToken raw jwt,can contain {@value BEARER} at the start of it. * @return decoded token details optional. */ public Optional<DecodedToken> parse(String rawToken) { if (StringUtils.isBlank(rawToken)) { return Optional.empty(); } String token = rawToken .replaceFirst(BEARER,""); try { Claims claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); String version = Optional .ofNullable(claims.get(VERSION,String.class)) .orElseThrow(() -> new ChatException("Token must include version",HttpStatus.BAD_REQUEST)); return Optional.of(new DecodedToken(claims.getSubject(),UUID.fromString(version))); } catch (JwtException e) { LOGGER.error("Could not parse token: {}",token,e); return Optional.empty(); } }
/** * Gets the value of the <em>exp</em> claim of a JWT. * * @param token The token. * @return The expiration. * @throws NullPointerException if the token is {@code null}. * @throws IllegalArgumentException if the given token contains no <em>exp</em> claim. */ public static final Date getExpiration(final String token) { if (token == null) { throw new NullPointerException("token must not be null"); } final atomicreference<Date> result = new atomicreference<>(); try { Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() { @SuppressWarnings("rawtypes") @Override public Key resolveSigningKey(JwsHeader header,Claims claims) { Date exp = claims.getExpiration(); if (exp != null) { result.set(exp); } return DUMMY_KEY; } }).parse(token); } catch (JwtException e) { // expected since we do not kNow the signing key } if (result.get() == null) { throw new IllegalArgumentException("token contains no exp claim"); } else { return result.get(); } }
/** * Tries to parse specified String as a JWT token. If successful,returns User object with username,id * and role prefilled (extracted from token). * If unsuccessful (token is invalid or not containing all required user properties),throws exception. * * @param token the JWT token to parse * @return the User object extracted from specified token if a token is valid * @throws AuthenticationException if a token is invalid */ public User parsetoken(final String token) throws AuthenticationException { try { final Claims body = Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token) .getBody(); return new User((String) body.get("userId"),body.getSubject(),(Set<String>) body.get("role")); } catch (JwtException | ClassCastException e) { throw (JwtTokenMalformedException) new JwtTokenMalformedException("JWT token is not valid").initCause(e); } }
@Override protected JwtAuthToken createtoken(ServletRequest request,ServletResponse response) throws Exception { String jwt = TokenManager.extractToken(request); String subject; try { subject = TokenManager.getSubject(jwt); } catch (JwtException e) { throw new AuthenticationException(e); } return new JwtAuthToken(subject); }
/** * Returns the expected signature byte array length (R + S parts) for * the specified ECDSA algorithm. * * @param alg The ECDSA algorithm. Must be supported and not * {@code null}. * * @return The expected byte array length for the signature. * * @throws JwtException If the algorithm is not supported. */ public static int getSignatureByteArrayLength(final SignatureAlgorithm alg) throws JwtException { switch (alg) { case ES256: return 64; case ES384: return 96; case ES512: return 132; default: throw new JwtException("Unsupported Algorithm: " + alg.name()); } }
protected byte[] doSign(byte[] data) throws InvalidKeyException,java.security.SignatureException,JwtException { PrivateKey privateKey = (PrivateKey)key; Signature sig = createSignatureInstance(); sig.initSign(privateKey); sig.update(data); return transcodeSignaturetoConcat(sig.sign(),getSignatureByteArrayLength(alg)); }
@POST @PermitAll @Path("/refresh") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response refresh(RestRefreshTokenRequest refreshTokenRequest) throws InvalidKeySpecException,NoSuchAlgorithmException { RestAuthorizationResponse authorizationResponse = new RestAuthorizationResponse(); // Check if username and password are defined in request if (refreshTokenRequest == null || StringUtils.isEmpty(refreshTokenRequest.getRefreshToken())) { authorizationResponse.setMessage(RestAuthorizationResponse.getFaultLoginEmptyMsg()); return Responses.ok(authorizationResponse); } ApiSecuritySettings settings = settingsDao.getSettings(ApiSecuritySettings.class); // Decode refresh token Claims claims; try { claims = jwtGenerator.validatetoken(settings.getSecret(),refreshTokenRequest.getRefreshToken(),TokenType.REFRESH); } catch (JwtException e) { authorizationResponse.setMessage(e.getMessage()); return Responses.ok(authorizationResponse); } // Search for credentials by token subject (user display name,exact) User user = settings.getLogins().stream() .filter(apiLogin -> apiLogin.getUser().getUsername().equals(claims.getSubject())) .map(ApiLogin::getUser) .findFirst() .orElse(null); // Check if user was found within credentialsSets if (user == null) { authorizationResponse.setMessage(RestAuthorizationResponse.getFaultInvalidTokenMsg()); return Responses.ok(authorizationResponse); } String token = jwtGenerator.generateAuthorizationToken(settings.getSecret(),user); String refreshToken = jwtGenerator.generateRefreshToken(settings.getSecret(),user); authorizationResponse.setMessage(RestAuthorizationResponse.getLoginokMsg()); authorizationResponse.setAuthorizationToken(token); authorizationResponse.setRefreshToken(refreshToken); return Responses.ok(authorizationResponse); }
@ExceptionHandler(JwtException.class) @ResponseStatus(value = HttpStatus.FORBIDDEN) @ResponseBody public ApiError jwtException(JwtException exception) { String message; if (exception instanceof ExpiredJwtException) { message = "Expired token"; } else { message = "Invalid token"; } return new ApiError(message); }
public static String getSubject(String jwt) throws JwtException { return getBody(jwt).getSubject(); }
/** * Transcodes the JCA ASN.1/DER-encoded signature into the concatenated * R + S format expected by ECDSA JWS. * * @param derSignature The ASN1./DER-encoded. Must not be {@code null}. * @param outputLength The expected length of the ECDSA JWS signature. * * @return The ECDSA JWS encoded signature. * * @throws JwtException If the ASN.1/DER signature format is invalid. */ public static byte[] transcodeSignaturetoConcat(final byte[] derSignature,int outputLength) throws JwtException { if (derSignature.length < 8 || derSignature[0] != 48) { throw new JwtException("Invalid ECDSA signature format"); } int offset; if (derSignature[1] > 0) { offset = 2; } else if (derSignature[1] == (byte) 0x81) { offset = 3; } else { throw new JwtException("Invalid ECDSA signature format"); } byte rLength = derSignature[offset + 1]; int i = rLength; while ((i > 0) && (derSignature[(offset + 2 + rLength) - i] == 0)) i--; byte sLength = derSignature[offset + 2 + rLength + 1]; int j = sLength; while ((j > 0) && (derSignature[(offset + 2 + rLength + 2 + sLength) - j] == 0)) j--; int rawLen = Math.max(i,j); rawLen = Math.max(rawLen,outputLength / 2); if ((derSignature[offset - 1] & 0xff) != derSignature.length - offset || (derSignature[offset - 1] & 0xff) != 2 + rLength + 2 + sLength || derSignature[offset] != 2 || derSignature[offset + 2 + rLength] != 2) { throw new JwtException("Invalid ECDSA signature format"); } final byte[] concatSignature = new byte[2 * rawLen]; System.arraycopy(derSignature,(offset + 2 + rLength) - i,concatSignature,rawLen - i,i); System.arraycopy(derSignature,(offset + 2 + rLength + 2 + sLength) - j,2 * rawLen - j,j); return concatSignature; }
/** * Transcodes the ECDSA JWS signature into ASN.1/DER format for use by * the JCA verifier. * * @param jwsSignature The JWS signature,consisting of the * concatenated R and S values. Must not be * {@code null}. * * @return The ASN.1/DER encoded signature. * * @throws JwtException If the ECDSA JWS signature format is invalid. */ public static byte[] transcodeSignaturetoDER(byte[] jwsSignature) throws JwtException { int rawLen = jwsSignature.length / 2; int i = rawLen; while((i > 0) && (jwsSignature[rawLen - i] == 0)) i--; int j = i; if (jwsSignature[rawLen - i] < 0) { j += 1; } int k = rawLen; while ((k > 0) && (jwsSignature[2 * rawLen - k] == 0)) k--; int l = k; if (jwsSignature[2 * rawLen - k] < 0) { l += 1; } int len = 2 + j + 2 + l; if (len > 255) { throw new JwtException("Invalid ECDSA signature format"); } int offset; final byte derSignature[]; if (len < 128) { derSignature = new byte[2 + 2 + j + 2 + l]; offset = 1; } else { derSignature = new byte[3 + 2 + j + 2 + l]; derSignature[1] = (byte) 0x81; offset = 2; } derSignature[0] = 48; derSignature[offset++] = (byte) len; derSignature[offset++] = 2; derSignature[offset++] = (byte) j; System.arraycopy(jwsSignature,derSignature,(offset + j) - i,i); offset += j; derSignature[offset++] = 2; derSignature[offset++] = (byte) l; System.arraycopy(jwsSignature,2 * rawLen - k,(offset + l) - k,k); return derSignature; }
/** * 生成Token * * @param claims * @param expiration * @param secretKey * @return */ public static String generatetoken(Claims claims,Long expiration,String secretKey) throws JwtException { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate(expiration)) .signWith(SignatureAlgorithm.HS512,secretKey) .compact(); }
/** * 从Token获取信息 * * @param token * @param secretKey * @return */ public static Claims getClaims(String token,String secretKey) throws JwtException { return Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); }
/** * 从Token获取受众 * * @param token * @param secretKey * @return */ public static String getAudience(String token,String secretKey) throws JwtException { return getClaims(token,secretKey).getAudience(); }
/** * 从Token获取受众 * * @param claims * @return */ public static String getAudience(Claims claims) throws JwtException { return claims.getAudience(); }
/** * 有效期是否期满,过期为true * * @param token * @param secretKey * @return */ public static Boolean isTokenExpired(String token,String secretKey) throws JwtException { Claims claims = getClaims(token,secretKey); Date expiration = claims.getExpiration(); return expiration.before(new Date()); }
/** * 有效期是否期满,过期为true * * @param claims * @return */ public static Boolean isTokenExpired(Claims claims) throws JwtException { Date expiration = claims.getExpiration(); return expiration.before(new Date()); }
我们今天的关于javax.websocket.DeploymentException的实例源码和java socket源码的分享就到这里,谢谢您的阅读,如果想了解更多关于com.lowagie.text.DocumentException的实例源码、Error: weblogic.management.DeploymentException: Cannot set web app root system p、io.jsonwebtoken.ExpiredJwtException的实例源码、io.jsonwebtoken.JwtException的实例源码的相关信息,可以在本站进行搜索。
本文标签: