List of usage examples for java.lang Long decode
public static Long decode(String nm) throws NumberFormatException
From source file:pl.nask.hsn2.normalizers.URLNormalizerUtils.java
public static long[] decodeIPv4(String st) throws URLHostParseException { long[] ipv4Tab = new long[4]; int i = 0;//from ww w .j a v a 2 s . c o m String[] val = Pattern.compile("\\.").split(st); for (String str : val) { try { ipv4Tab[i++] = Long.decode(str); } catch (NumberFormatException e) { throw new URLHostParseException("Cannot decode IP:" + str, e); } } if (--i < 3) { long ip = ipv4Tab[i]; int indx = 3; while (i++ < 4) { ipv4Tab[indx--] = ip % 256l; ip /= 256l; } } if (ipv4Tab[0] == 10 || (ipv4Tab[0] == 192 && ipv4Tab[1] == 168) || (ipv4Tab[0] == 172 && ipv4Tab[1] >= 16 && ipv4Tab[1] <= 31)) { LOG.warn("non routable IPv4 address: {}.{}.{}.{}", new Object[] { ipv4Tab[0], ipv4Tab[1], ipv4Tab[2], ipv4Tab[3] }); } if (ipv4Tab[0] == 0) { throw new URLHostParseException("IPv4 in format 0.x.x.x is incorrect"); } return ipv4Tab; }
From source file:org.kuali.rice.ken.web.spring.NotificationController.java
/** * This method takes an action on the message delivery - dismisses it with the action/cause that comes from the * UI layer//w ww. j av a 2 s. c o m * @param action the action or cause of the dismissal * @param message the message to display to the user * @param request the HttpServletRequest * @param response the HttpServletResponse * @return an appropriate ModelAndView */ private ModelAndView dismissMessage(String action, String message, HttpServletRequest request, HttpServletResponse response) { String view = "NotificationDetail"; String principalNm = request.getRemoteUser(); String messageDeliveryId = request .getParameter(NotificationConstants.NOTIFICATION_CONTROLLER_CONSTANTS.MSG_DELIVERY_ID); String command = request.getParameter(NotificationConstants.NOTIFICATION_CONTROLLER_CONSTANTS.COMMAND); String standaloneWindow = request .getParameter(NotificationConstants.NOTIFICATION_CONTROLLER_CONSTANTS.STANDALONE_WINDOW); if (messageDeliveryId == null) { throw new RuntimeException("A null messageDeliveryId was provided."); } LOG.debug("messageDeliveryId: " + messageDeliveryId); LOG.debug("command: " + command); /** * We can get the notification object given a workflow ID or a notification * Id. This method might be called either from a workflow action list or * as a link from a message deliverer endpoint such as an email message. */ NotificationMessageDelivery delivery = messageDeliveryService .getNotificationMessageDelivery(Long.decode(messageDeliveryId)); if (delivery == null) { throw new RuntimeException("Could not find message delivery with id " + messageDeliveryId); } NotificationBo notification = delivery.getNotification(); /* * dismiss the message delivery */ Principal principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(principalNm); notificationService.dismissNotificationMessageDelivery(delivery.getId(), principal.getPrincipalId(), action); List<NotificationSenderBo> senders = notification.getSenders(); List<NotificationRecipientBo> recipients = notification.getRecipients(); String contenthtml = Util.transformContent(notification); // first check to see if this is a standalone window, b/c if it is, we'll want to close if (standaloneWindow != null && standaloneWindow.equals("true")) { view = "NotificationActionTakenCloseWindow"; } else { // otherwise check to see if the details need to be rendered in line (no stuff around them) if (command != null && command.equals(NotificationConstants.NOTIFICATION_DETAIL_VIEWS.INLINE)) { view = "NotificationDetailInline"; } } Map<String, Object> model = new HashMap<String, Object>(); model.put("notification", notification); model.put("message", message); model.put("senders", senders); model.put("recipients", recipients); model.put("contenthtml", contenthtml); model.put("messageDeliveryId", messageDeliveryId); model.put("command", command); model.put(NotificationConstants.NOTIFICATION_CONTROLLER_CONSTANTS.STANDALONE_WINDOW, standaloneWindow); return new ModelAndView(view, model); }
From source file:org.kchine.r.server.http.frontend.CommandServlet.java
protected void doAny(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = null;//from w w w. ja va2 s. c o m Object result = null; try { final String command = request.getParameter("method"); do { if (command.equals("ping")) { result = "pong"; break; } else if (command.equals("logon")) { session = request.getSession(false); if (session != null) { result = session.getId(); break; } String login = (String) PoolUtils.hexToObject(request.getParameter("login")); String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd")); boolean namedAccessMode = login.contains("@@"); String sname = null; if (namedAccessMode) { sname = login.substring(login.indexOf("@@") + "@@".length()); login = login.substring(0, login.indexOf("@@")); } System.out.println("login :" + login); System.out.println("pwd :" + pwd); if (_rkit == null && (!login.equals(System.getProperty("login")) || !pwd.equals(System.getProperty("pwd")))) { result = new BadLoginPasswordException(); break; } HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils .hexToObject(request.getParameter("options")); if (options == null) options = new HashMap<String, Object>(); System.out.println("options:" + options); RPFSessionInfo.get().put("LOGIN", login); RPFSessionInfo.get().put("REMOTE_ADDR", request.getRemoteAddr()); RPFSessionInfo.get().put("REMOTE_HOST", request.getRemoteHost()); boolean nopool = !options.keySet().contains("nopool") || ((String) options.get("nopool")).equals("") || !((String) options.get("nopool")).equalsIgnoreCase("false"); boolean save = options.keySet().contains("save") && ((String) options.get("save")).equalsIgnoreCase("true"); boolean selfish = options.keySet().contains("selfish") && ((String) options.get("selfish")).equalsIgnoreCase("true"); String privateName = (String) options.get("privatename"); int memoryMin = DEFAULT_MEMORY_MIN; int memoryMax = DEFAULT_MEMORY_MAX; try { if (options.get("memorymin") != null) memoryMin = Integer.decode((String) options.get("memorymin")); if (options.get("memorymax") != null) memoryMax = Integer.decode((String) options.get("memorymax")); } catch (Exception e) { e.printStackTrace(); } boolean privateEngineMode = false; RServices r = null; URL[] codeUrls = null; if (_rkit == null) { if (namedAccessMode) { try { if (System.getProperty("submit.mode") != null && System.getProperty("submit.mode").equals("ssh")) { if (PoolUtils.isStubCandidate(sname)) { r = (RServices) PoolUtils.hexToStub(sname, PoolUtils.class.getClassLoader()); } else { r = (RServices) ((DBLayerInterface) SSHTunnelingProxy.getDynamicProxy( System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home"), "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}", "db", new Class<?>[] { DBLayerInterface.class })).lookup(sname); } } else { if (PoolUtils.isStubCandidate(sname)) { r = (RServices) PoolUtils.hexToStub(sname, PoolUtils.class.getClassLoader()); } else { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } r = (RServices) spFactory.getServantProvider().getRegistry().lookup(sname); } } } catch (Exception e) { e.printStackTrace(); } } else { if (nopool) { /* ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } String nodeName = options.keySet().contains("node") ? (String) options.get("node") : System .getProperty("private.servant.node.name"); Registry registry = spFactory.getServantProvider().getRegistry(); NodeManager nm = null; try { nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name") + "_" + nodeName); } catch (NotBoundException nbe) { nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name")); } catch (Exception e) { result = new NoNodeManagerFound(); break; } r = (RServices) nm.createPrivateServant(nodeName); */ if (System.getProperty("submit.mode") != null && System.getProperty("submit.mode").equals("ssh")) { DBLayerInterface dbLayer = (DBLayerInterface) SSHTunnelingProxy.getDynamicProxy( System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home"), "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}", "db", new Class<?>[] { DBLayerInterface.class }); if (privateName != null && !privateName.equals("")) { try { r = (RServices) dbLayer.lookup(privateName); } catch (Exception e) { //e.printStackTrace(); } } if (r == null) { final String uid = (privateName != null && !privateName.equals("")) ? privateName : UUID.randomUUID().toString(); final String[] jobIdHolder = new String[1]; new Thread(new Runnable() { public void run() { try { String command = "java -Dlog.file=" + System.getProperty("submit.ssh.biocep.home") + "/log/%{uid}.log" + " -Drmi.port.start=" + System.getProperty("submit.ssh.rmi.port.start") + " -Dname=%{uid}" + " -Dnaming.mode=db" + " -Ddb.host=" + System.getProperty("submit.ssh.host") + " -Dwait=true" + " -jar " + System.getProperty("submit.ssh.biocep.home") + "/biocep-core.jar"; jobIdHolder[0] = SSHUtils.execSshBatch(command, uid, System.getProperty("submit.ssh.prefix"), System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home")); System.out.println("jobId:" + jobIdHolder[0]); } catch (Exception e) { e.printStackTrace(); } } }).start(); long TIMEOUT = Long.decode(System.getProperty("submit.ssh.timeout")); long tStart = System.currentTimeMillis(); while ((System.currentTimeMillis() - tStart) < TIMEOUT) { try { r = (RServices) dbLayer.lookup(uid); } catch (Exception e) { } if (r != null) break; try { Thread.sleep(10); } catch (Exception e) { } } if (r != null) { try { r.setJobId(jobIdHolder[0]); } catch (Exception e) { r = null; } } } } else { System.out.println("LocalHttpServer.getLocalHttpServerPort():" + LocalHttpServer.getLocalHttpServerPort()); System.out.println("LocalRmiRegistry.getLocalRmiRegistryPort():" + LocalHttpServer.getLocalHttpServerPort()); if (privateName != null && !privateName.equals("")) { try { r = (RServices) LocalRmiRegistry.getInstance().lookup(privateName); } catch (Exception e) { //e.printStackTrace(); } } if (r == null) { codeUrls = (URL[]) options.get("urls"); System.out.println("CODE URL->" + Arrays.toString(codeUrls)); //String r = ServerManager.createR(System.getProperty("r.binary"), false, false, PoolUtils.getHostIp(), LocalHttpServer.getLocalHttpServerPort(), ServerManager.getRegistryNamingInfo(PoolUtils.getHostIp(), LocalRmiRegistry.getLocalRmiRegistryPort()), memoryMin, memoryMax, privateName, false, codeUrls, null, (_webAppMode ? "javaws" : "standard"), null, "127.0.0.1"); } privateEngineMode = true; } } else { if (System.getProperty("submit.mode") != null && System.getProperty("submit.mode").equals("ssh")) { ServantProvider servantProvider = (ServantProvider) SSHTunnelingProxy .getDynamicProxy(System.getProperty("submit.ssh.host"), Integer.decode(System.getProperty("submit.ssh.port")), System.getProperty("submit.ssh.user"), System.getProperty("submit.ssh.password"), System.getProperty("submit.ssh.biocep.home"), "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}", "servant.provider", new Class<?>[] { ServantProvider.class }); boolean wait = options.keySet().contains("wait") && ((String) options.get("wait")).equalsIgnoreCase("true"); String poolname = ((String) options.get("poolname")); if (wait) { r = (RServices) (poolname == null || poolname.trim().equals("") ? servantProvider.borrowServantProxy() : servantProvider.borrowServantProxy(poolname)); } else { r = (RServices) (poolname == null || poolname.trim().equals("") ? servantProvider.borrowServantProxyNoWait() : servantProvider.borrowServantProxyNoWait(poolname)); } System.out.println("---> borrowed : " + r); } else { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } boolean wait = options.keySet().contains("wait") && ((String) options.get("wait")).equalsIgnoreCase("true"); String poolname = ((String) options.get("poolname")); if (wait) { r = (RServices) (poolname == null || poolname.trim().equals("") ? spFactory.getServantProvider().borrowServantProxy() : spFactory.getServantProvider().borrowServantProxy(poolname)); } else { r = (RServices) (poolname == null || poolname.trim().equals("") ? spFactory.getServantProvider().borrowServantProxyNoWait() : spFactory.getServantProvider() .borrowServantProxyNoWait(poolname)); } } } } } else { r = _rkit.getR(); } if (r == null) { result = new NoServantAvailableException(); break; } session = request.getSession(true); Integer sessionTimeOut = null; try { if (options.get("sessiontimeout") != null) sessionTimeOut = Integer.decode((String) options.get("sessiontimeout")); } catch (Exception e) { e.printStackTrace(); } if (sessionTimeOut != null) { session.setMaxInactiveInterval(sessionTimeOut); } session.setAttribute("TYPE", "RS"); session.setAttribute("R", r); session.setAttribute("NOPOOL", nopool); session.setAttribute("SAVE", save); session.setAttribute("LOGIN", login); session.setAttribute("NAMED_ACCESS_MODE", namedAccessMode); session.setAttribute("PROCESS_ID", r.getProcessId()); session.setAttribute("JOB_ID", r.getJobId()); session.setAttribute("SELFISH", selfish); session.setAttribute("IS_RELAY", _rkit != null); if (privateName != null) session.setAttribute("PRIVATE_NAME", privateName); if (codeUrls != null && codeUrls.length > 0) { session.setAttribute("CODEURLS", codeUrls); } session.setAttribute("THREADS", new ThreadsHolder()); ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP")) .put(session.getId(), session); saveSessionAttributes(session); Vector<HttpSession> sessionVector = ((HashMap<RServices, Vector<HttpSession>>) getServletContext() .getAttribute("R_SESSIONS")).get(r); if (sessionVector == null) { sessionVector = new Vector<HttpSession>(); ((HashMap<RServices, Vector<HttpSession>>) getServletContext().getAttribute("R_SESSIONS")) .put(r, sessionVector); } sessionVector.add(session); if (_rkit == null && save) { UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), r); } System.out.println("---> Has Collaboration Listeners:" + r.hasRCollaborationListeners()); if (selfish || !r.hasRCollaborationListeners()) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); GDDevice[] devices = r.listDevices(); for (int i = 0; i < devices.length; ++i) { String deviceName = devices[i].getId(); System.out.println("??? ---- deviceName=" + deviceName); session.setAttribute(deviceName, devices[i]); } } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } if (privateEngineMode) { if (options.get("newdevice") != null) { GDDevice deviceProxy = null; GDDevice[] dlist = r.listDevices(); if (dlist == null || dlist.length == 0) { deviceProxy = r.newDevice(480, 480); } else { deviceProxy = dlist[0]; } String deviceName = deviceProxy.getId(); session.setAttribute(deviceName, deviceProxy); session.setAttribute("maindevice", deviceProxy); saveSessionAttributes(session); } if (options.get("newgenericcallbackdevice") != null) { GenericCallbackDevice genericCallBackDevice = null; GenericCallbackDevice[] clist = r.listGenericCallbackDevices(); if (clist == null || clist.length == 0) { genericCallBackDevice = r.newGenericCallbackDevice(); } else { genericCallBackDevice = clist[0]; } String genericCallBackDeviceName = genericCallBackDevice.getId(); session.setAttribute(genericCallBackDeviceName, genericCallBackDevice); session.setAttribute("maingenericcallbackdevice", genericCallBackDevice); saveSessionAttributes(session); } } result = session.getId(); break; } else if (command.equals("logondb")) { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } String login = (String) PoolUtils.hexToObject(request.getParameter("login")); String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd")); HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils .hexToObject(request.getParameter("options")); if (options == null) options = new HashMap<String, Object>(); System.out.println("options:" + options); session = request.getSession(true); Integer sessionTimeOut = null; try { if (options.get("sessiontimeout") != null) sessionTimeOut = Integer.decode((String) options.get("sessiontimeout")); } catch (Exception e) { e.printStackTrace(); } if (sessionTimeOut != null) { session.setMaxInactiveInterval(sessionTimeOut); } session.setAttribute("TYPE", "DBS"); session.setAttribute("REGISTRY", (DBLayer) spFactory.getServantProvider().getRegistry()); session.setAttribute("SUPERVISOR", new SupervisorUtils((DBLayer) spFactory.getServantProvider().getRegistry())); session.setAttribute("THREADS", new ThreadsHolder()); ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP")) .put(session.getId(), session); saveSessionAttributes(session); result = session.getId(); break; } session = request.getSession(false); if (session == null) { result = new NotLoggedInException(); break; } if (command.equals("logoff")) { if (session.getAttribute("TYPE").equals("RS")) { if (_rkit != null) { /* Enumeration<String> attributeNames = session.getAttributeNames(); while (attributeNames.hasMoreElements()) { String aname = attributeNames.nextElement(); if (session.getAttribute(aname) instanceof GDDevice) { try { _rkit.getRLock().lock(); ((GDDevice) session.getAttribute(aname)).dispose(); } catch (Exception e) { e.printStackTrace(); } finally { _rkit.getRLock().unlock(); } } } */ } } try { session.invalidate(); } catch (Exception ex) { ex.printStackTrace(); } result = null; break; } final boolean[] stop = { false }; final HttpSession currentSession = session; if (command.equals("invoke")) { String servantName = (String) PoolUtils.hexToObject(request.getParameter("servantname")); final Object servant = session.getAttribute(servantName); if (servant == null) { throw new Exception("Bad Servant Name :" + servantName); } String methodName = (String) PoolUtils.hexToObject(request.getParameter("methodname")); ClassLoader urlClassLoader = this.getClass().getClassLoader(); if (session.getAttribute("CODEURLS") != null) { urlClassLoader = new URLClassLoader((URL[]) session.getAttribute("CODEURLS"), this.getClass().getClassLoader()); } Class<?>[] methodSignature = (Class[]) PoolUtils .hexToObject(request.getParameter("methodsignature")); final Method m = servant.getClass().getMethod(methodName, methodSignature); if (m == null) { throw new Exception("Bad Method Name :" + methodName); } final Object[] methodParams = (Object[]) PoolUtils .hexToObject(request.getParameter("methodparameters"), urlClassLoader); final Object[] resultHolder = new Object[1]; Runnable rmiRunnable = new Runnable() { public void run() { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); resultHolder[0] = m.invoke(servant, methodParams); if (resultHolder[0] == null) resultHolder[0] = RMICALL_DONE; } catch (InvocationTargetException ite) { if (ite.getCause() instanceof ConnectException) { currentSession.invalidate(); resultHolder[0] = new NotLoggedInException(); } else { resultHolder[0] = ite.getCause(); } } catch (Exception e) { final boolean wasInterrupted = Thread.interrupted(); if (wasInterrupted) { resultHolder[0] = new RmiCallInterrupted(); } else { resultHolder[0] = e; } } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } }; Thread rmiThread = InterruptibleRMIThreadFactory.getInstance().newThread(rmiRunnable); ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().add(rmiThread); rmiThread.start(); long t1 = System.currentTimeMillis(); while (resultHolder[0] == null) { if ((System.currentTimeMillis() - t1) > RMICALL_TIMEOUT_MILLISEC || stop[0]) { rmiThread.interrupt(); resultHolder[0] = new RmiCallTimeout(); break; } try { Thread.sleep(10); } catch (Exception e) { } } try { ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().remove(rmiThread); } catch (IllegalStateException e) { } if (resultHolder[0] instanceof Throwable) { throw (Throwable) resultHolder[0]; } if (resultHolder[0] == RMICALL_DONE) { result = null; } else { result = resultHolder[0]; } break; } if (command.equals("interrupt")) { final Vector<Thread> tvec = (Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")) .getThreads().clone(); for (int i = 0; i < tvec.size(); ++i) { try { tvec.elementAt(i).interrupt(); } catch (Exception e) { e.printStackTrace(); } } stop[0] = true; ((Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")).getThreads()) .removeAllElements(); result = null; break; } else if (command.equals("saveimage")) { UserUtils.saveWorkspace((String) session.getAttribute("LOGIN"), (RServices) session.getAttribute("R")); result = null; break; } else if (command.equals("loadimage")) { UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), (RServices) session.getAttribute("R")); result = null; break; } else if (command.equals("newdevice")) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); boolean broadcasted = new Boolean(request.getParameter("broadcasted")); GDDevice deviceProxy = null; if (broadcasted) { deviceProxy = ((RServices) session.getAttribute("R")).newBroadcastedDevice( Integer.decode(request.getParameter("width")), Integer.decode(request.getParameter("height"))); } else { deviceProxy = ((RServices) session.getAttribute("R")).newDevice( Integer.decode(request.getParameter("width")), Integer.decode(request.getParameter("height"))); } String deviceName = deviceProxy.getId(); System.out.println("deviceName=" + deviceName); session.setAttribute(deviceName, deviceProxy); saveSessionAttributes(session); result = deviceName; break; } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } else if (command.equals("listdevices")) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); result = new Vector<String>(); for (Enumeration<String> e = session.getAttributeNames(); e.hasMoreElements();) { String attributeName = e.nextElement(); if (attributeName.startsWith("device_")) { ((Vector<String>) result).add(attributeName); } } break; } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } else if (command.equals("newgenericcallbackdevice")) { try { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawLock(); GenericCallbackDevice genericCallBackDevice = ((RServices) session.getAttribute("R")) .newGenericCallbackDevice(); String genericCallBackDeviceName = genericCallBackDevice.getId(); session.setAttribute(genericCallBackDeviceName, genericCallBackDevice); saveSessionAttributes(session); result = genericCallBackDeviceName; break; } finally { if (_rkit != null && _safeModeEnabled) ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock(); } } else if (command.equals("newspreadsheetmodeldevice")) { String spreadsheetModelDeviceId = request.getParameter("id"); SpreadsheetModelRemote model = null; if (spreadsheetModelDeviceId == null || spreadsheetModelDeviceId.equals("")) { model = ((RServices) session.getAttribute("R")).newSpreadsheetTableModelRemote( Integer.decode(request.getParameter("rowcount")), Integer.decode(request.getParameter("colcount"))); } else { model = ((RServices) session.getAttribute("R")) .getSpreadsheetTableModelRemote(spreadsheetModelDeviceId); } SpreadsheetModelDevice spreadsheetDevice = model.newSpreadsheetModelDevice(); String spreadsheetDeviceId = spreadsheetDevice.getId(); session.setAttribute(spreadsheetDeviceId, spreadsheetDevice); saveSessionAttributes(session); result = spreadsheetDeviceId; break; } else if (command.equals("list")) { ServantProviderFactory spFactory = ServantProviderFactory.getFactory(); if (spFactory == null) { result = new NoRegistryAvailableException(); break; } result = spFactory.getServantProvider().getRegistry().list(); break; } } while (true); } catch (TunnelingException te) { result = te; te.printStackTrace(); } catch (Throwable e) { result = new TunnelingException("Server Side", e); e.printStackTrace(); } response.setContentType("application/x-java-serialized-object"); new ObjectOutputStream(response.getOutputStream()).writeObject(result); response.flushBuffer(); }
From source file:com.emergya.persistenceGeo.web.RestFoldersAdminController.java
/** * Rename a folder//w ww.j av a 2 s .c om * * @param folderId * @param name * * @return JSON file with success */ @RequestMapping(value = "/persistenceGeo/renameFolder", produces = { MediaType.APPLICATION_JSON_VALUE }) public @ResponseBody Map<String, Object> renameFolder(@RequestParam("folderId") String folderId, @RequestParam("name") String name) { Map<String, Object> result = new HashMap<String, Object>(); FolderDto folder = null; try { /* * //TODO: Secure with logged user String username = ((UserDetails) * SecurityContextHolder.getContext() * .getAuthentication().getPrincipal()).getUsername(); */ Long idFolder = Long.decode(folderId); folder = (FolderDto) foldersAdminService.getById(idFolder); folder.setName(name); folder = (FolderDto) foldersAdminService.update(folder); result.put(SUCCESS, true); } catch (Exception e) { e.printStackTrace(); result.put(SUCCESS, false); } result.put(RESULTS, folder != null ? 1 : 0); result.put(ROOT, folder); return result; }
From source file:org.jboss.dashboard.ui.NavigationManager.java
public void actionNavigateToPage(CommandRequest request) throws Exception { String workspaceId = request.getParameter(WORKSPACE_ID); String pageId = request.getParameter(PAGE_ID); if (workspaceId != null && pageId != null) { WorkspaceImpl workspace = (WorkspaceImpl) UIServices.lookup().getWorkspacesManager() .getWorkspace(workspaceId); if (workspace != null) { setCurrentSection(workspace.getSection(Long.decode(pageId))); }/*w w w .j a v a 2 s. c om*/ } }
From source file:AltiConsole.AltiConsoleMainScreen.java
public boolean ConnectToAlti() { long timeOut = 10000; if (UserPref.getRetrievalTimeout() != null && UserPref.getRetrievalTimeout() != "") timeOut = Long.decode(UserPref.getRetrievalTimeout()); System.out.println("timeOut " + timeOut); if (Serial.getConnected() == true) { System.out.println("I am already connected... let's disconnect\n"); Serial.disconnect();/* ww w . j a v a2 s. c om*/ //Serial.DataReady = false; Serial.setDataReady(false); } /* Connect */ Serial.connect(); //while (Serial.getConnected() != true); if (Serial.getConnected() == true) { if (Serial.initIOStream() == true) { if (Serial.initListener() == true) { // send command to switch off the continuity test //Serial.DataReady = false; Serial.clearInput(); Serial.setDataReady(false); Serial.writeData("f;\n"); System.out.println("f;\n"); long startTime; // Serial.lastReceived = System.currentTimeMillis(); while (Serial.getDataReady() != true) { long currentTime = System.currentTimeMillis(); startTime = Serial.lastReceived; if ((currentTime - startTime) > timeOut) { // This is some sort of data retrieval timeout System.out.println("ConnectToAlti - Data retrieval timed out\n"); this.setCursor(Cursor.getDefaultCursor()); JOptionPane.showMessageDialog(null, trans.get("AltiConsoleMainScreen.dataTimeOut"), trans.get("AltiConsoleMainScreen.ConnectionError"), JOptionPane.ERROR_MESSAGE); return false; } } System.out.println("ConnectToAlti - " + Serial.commandRet); //System.out.println("Data retrieval timed out\n"); //Serial.DataReady = false; Serial.clearInput(); Serial.setDataReady(false); Serial.writeData("f;\n"); //startTime = System.currentTimeMillis(); Serial.lastReceived = System.currentTimeMillis(); System.out.println("ConnectToAlti - 2"); if (Serial.getDataReady()) System.out.println("ConnectToAlti - 2 true"); while (Serial.getDataReady() != true) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } long currentTime = System.currentTimeMillis(); startTime = Serial.lastReceived; if ((currentTime - startTime) > timeOut) { // This is some sort of data retrieval timeout System.out.println("ConnectToAlti - Data retrieval timed out1\n"); this.setCursor(Cursor.getDefaultCursor()); JOptionPane.showMessageDialog(null, trans.get("AltiConsoleMainScreen.dataTimeOut"), trans.get("AltiConsoleMainScreen.ConnectionError"), JOptionPane.ERROR_MESSAGE); return false; } } System.out.println("ConnectToAlti - 2 I am out"); //Serial.DataReady = false; Serial.setDataReady(false); } } } return true; }
From source file:com.emergya.persistenceGeo.web.RestLayersAdminController.java
/** * This method saves layer visibility, layerOpacity... * // w ww. j a v a 2s . co m * @param layerId * @param properties * * @return JSON file with layer modified */ @RequestMapping(value = "/persistenceGeo/saveLayerSimpleProperties", produces = { MediaType.APPLICATION_JSON_VALUE }) public @ResponseBody Map<String, Object> saveLayerSimpleProperties(@RequestParam("layerId") String layerId, @RequestParam(value = "name", required = false) String name, @RequestParam(value = "properties", required = false) String properties) { Map<String, Object> result = new HashMap<String, Object>(); LayerDto layer = null; try { /* //TODO: Secure with logged user String username = ((UserDetails) SecurityContextHolder.getContext() .getAuthentication().getPrincipal()).getUsername(); */ Long idLayer = Long.decode(layerId); layer = (LayerDto) layerAdminService.getById(idLayer); // override name if (name != null) { layer.setName(name); } // override properties if (properties != null) { Map<String, String> propertyMap = getMapFromString(properties); Map<String, String> layerProperties = layer.getProperties() != null ? layer.getProperties() : new HashMap<String, String>(); for (String key : propertyMap.keySet()) { layerProperties.put(key, propertyMap.get(key)); } layer.setProperties(layerProperties); } //layer update layer = (LayerDto) layerAdminService.update(layer); //Must already loaded in RestLayerAdminController if (layer.getId() != null && layer.getData() != null) { layer.setData(null); layer.setServer_resource("rest/persistenceGeo/getLayerResource/" + layer.getId()); } result.put(SUCCESS, true); } catch (Exception e) { e.printStackTrace(); result.put(SUCCESS, false); } result.put(RESULTS, layer != null ? 1 : 0); result.put(ROOT, layer); return result; }
From source file:org.ohmage.request.survey.SurveyResponseReadRequest.java
/** * Creates a survey response read request. * /*from ww w. j a v a2s. c om*/ * @param httpRequest The request to retrieve parameters from. * * @throws InvalidRequestException Thrown if the parameters cannot be * parsed. * * @throws IOException There was an error reading from the request. */ public SurveyResponseReadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException { super(httpRequest); Set<SurveyResponse.ColumnKey> tColumns = null; SurveyResponse.OutputFormat tOutputFormat = null; List<SortParameter> tSortOrder = null; Boolean tCollapse = null; Boolean tPrettyPrint = null; Boolean tReturnId = null; Boolean tSuppressMetadata = null; long tSurveyResponsesToSkip = 0; long tSurveyResponsesToProcess = -1; try { tSurveyResponsesToProcess = Long .decode(PreferenceCache.instance().lookup(PreferenceCache.KEY_MAX_SURVEY_RESPONSE_PAGE_SIZE)); if (tSurveyResponsesToProcess == -1) { tSurveyResponsesToProcess = Long.MAX_VALUE; } } catch (CacheMissException e) { LOGGER.error("The cache is missing the max page size.", e); setFailed(); } catch (NumberFormatException e) { LOGGER.error("The max page size is not a number.", e); setFailed(); } if (!isFailed()) { LOGGER.info("Creating a survey response read request."); String[] t; try { // Column List t = getParameterValues(InputKeys.COLUMN_LIST); if (t.length == 0) { throw new ValidationException(ErrorCode.SURVEY_INVALID_COLUMN_ID, "The required column list was missing: " + InputKeys.COLUMN_LIST); } else if (t.length > 1) { throw new ValidationException(ErrorCode.SURVEY_INVALID_COLUMN_ID, "Multiple column lists were given: " + InputKeys.COLUMN_LIST); } else { tColumns = SurveyResponseValidators.validateColumnList(t[0]); if (tColumns == null) { throw new ValidationException(ErrorCode.SURVEY_INVALID_COLUMN_ID, "The required column list was missing: " + InputKeys.COLUMN_LIST); } } // Output Format t = getParameterValues(InputKeys.OUTPUT_FORMAT); if (t.length == 0) { throw new ValidationException(ErrorCode.SURVEY_INVALID_OUTPUT_FORMAT, "The output format is missing: " + InputKeys.OUTPUT_FORMAT); } else if (t.length > 1) { throw new ValidationException(ErrorCode.SURVEY_INVALID_OUTPUT_FORMAT, "Multiple output formats were given: " + InputKeys.OUTPUT_FORMAT); } else { tOutputFormat = SurveyResponseValidators.validateOutputFormat(t[0]); if (tOutputFormat == null) { throw new ValidationException(ErrorCode.SURVEY_INVALID_OUTPUT_FORMAT, "The output format is missing: " + InputKeys.OUTPUT_FORMAT); } } // Sort Order t = getParameterValues(InputKeys.SORT_ORDER); if (t.length > 1) { throw new ValidationException(ErrorCode.SURVEY_INVALID_SORT_ORDER, "Multiple sort order lists were given: " + InputKeys.SORT_ORDER); } else if (t.length == 1) { tSortOrder = SurveyResponseValidators.validateSortOrder(t[0]); } // Collapse t = getParameterValues(InputKeys.COLLAPSE); if (t.length > 1) { throw new ValidationException(ErrorCode.SURVEY_INVALID_COLLAPSE_VALUE, "Multiple collapse values were given: " + InputKeys.COLLAPSE); } else if (t.length == 1) { tCollapse = SurveyResponseValidators.validateCollapse(t[0]); } // Pretty print t = getParameterValues(InputKeys.PRETTY_PRINT); if (t.length > 1) { throw new ValidationException(ErrorCode.SURVEY_INVALID_PRETTY_PRINT_VALUE, "Multiple pretty print values were given: " + InputKeys.PRETTY_PRINT); } else if (t.length == 1) { tPrettyPrint = SurveyResponseValidators.validatePrettyPrint(t[0]); } // Return ID t = getParameterValues(InputKeys.RETURN_ID); if (t.length > 1) { throw new ValidationException(ErrorCode.SURVEY_INVALID_RETURN_ID, "Multiple return ID values were given: " + InputKeys.RETURN_ID); } else if (t.length == 1) { tReturnId = SurveyResponseValidators.validateReturnId(t[0]); } // Suppress metadata t = getParameterValues(InputKeys.SUPPRESS_METADATA); if (t.length > 1) { throw new ValidationException(ErrorCode.SURVEY_INVALID_SUPPRESS_METADATA_VALUE, "Multiple suppress metadata values were given: " + InputKeys.SUPPRESS_METADATA); } else if (t.length == 1) { tSuppressMetadata = SurveyResponseValidators.validateSuppressMetadata(t[0]); } // Number of survey responses to skip. t = getParameterValues(InputKeys.NUM_TO_SKIP); if (t.length > 1) { throw new ValidationException(ErrorCode.SERVER_INVALID_NUM_TO_SKIP, "Multiple values were given for the number of survey responses to skip: " + InputKeys.NUM_TO_SKIP); } else if (t.length == 1) { tSurveyResponsesToSkip = SurveyResponseValidators.validateNumSurveyResponsesToSkip(t[0]); } // Number of survey responses to process. t = getParameterValues(InputKeys.NUM_TO_RETURN); if (t.length > 1) { throw new ValidationException(ErrorCode.SERVER_INVALID_NUM_TO_RETURN, "Multiple values were given for the number of survey responses to process: " + InputKeys.NUM_TO_RETURN); } else if (t.length == 1) { tSurveyResponsesToProcess = SurveyResponseValidators.validateNumSurveyResponsesToProcess(t[0], tSurveyResponsesToProcess); } } catch (ValidationException e) { e.failRequest(this); e.logException(LOGGER); } } columns = tColumns; outputFormat = tOutputFormat; sortOrder = tSortOrder; collapse = tCollapse; prettyPrint = tPrettyPrint; returnId = tReturnId; suppressMetadata = tSuppressMetadata; surveyResponsesToSkip = tSurveyResponsesToSkip; surveyResponsesToProcess = tSurveyResponsesToProcess; }
From source file:org.testeditor.fixture.host.screen.Field.java
/** * More information can be found under:/*from www . j a v a 2s. co m*/ * * <pre> * File : x3270\include\3270ds.h * Sources : <a href= * "https://sourceforge.net/p/x3270/code/ci/master/tree/">https://sourceforge.net/p/x3270/code/ci/master/tree/</a> * * Here are the bit definitions from the source : * * #define FA_PRINTABLE 0xc0 these make the character "printable" * #define FA_PROTECT 0x20 unprotected (0) / protected (1) * #define FA_NUMERIC 0x10 alphanumeric (0) /numeric (1) * #define FA_INTENSITY 0x0c display/selector pen detectable: * #define FA_INT_NORM_NSEL 0x00 00 normal, non-detect * #define FA_INT_NORM_SEL 0x04 01 normal, detectable * #define FA_INT_HIGH_SEL 0x08 10 intensified, detectable * #define FA_INT_ZERO_NSEL 0x0c 11 nondisplay, non-detect * #define FA_RESERVED 0x02 must be 0 * #define FA_MODIFY 0x01 modified (1) * * This translates as follows: * +--------------------+----------+---------+----------------------+---------+--------+ * Bits | 7 6 | 5 | 4 | 3 2 | 1 | 0 | * +--------------------+----------+---------+----------------------+---------+--------+ * | Ignore | Protect | Numeric | Display Mode | Ignore |Modified| * +--------------------+----------+---------+----------------------+---------+--------+ * </pre> * * @param controlCharacter * The so called field attribute defines the start of a field and * the characteristics of the field. * <p> * Field attribute defines the following field characteristics: * <ul> * <li>Protected or unprotected. A protected field cannot be * modified by the operator. The operator can enter data or * modify the contents of an unprotected field. Unprotected * fields are classified as input fields. * <p> * The Bit representation of a protected field: * <table border="1" > * <tr> * <th>Binary</td> * <th>Hexadecimal</td> * <th>Decimal</td> * </tr> * <tr> * <td>00100000</td> * <td>20</td> * <td>32</td> * </tr> * </table> * </li> * <li>Alphanumeric or numeric. Unprotected alphanumeric fields * are fields into which an operator enters data normally, using * the shift keys (uppercase/lowercase or numeric/alphabetic) as * required. Fields defined as numeric accept all uppercase * symbols and numerics from a data entry keyboard. On a * typewriter keyboard, numeric has no meaning and all entries * are accepted. * <p> * The Bit representation of a numeric field: * <table border="1" > * <tr> * <th>Binary</td> * <th>Hexadecimal</td> * <th>Decimal</td> * </tr> * <tr> * <td>00010000</td> * <td>10</td> * <td>16</td> * </tr> * </table> * </li> * <li>Nondisplay or display/intensified display. The selected * characteristics apply to the entire field. Nondisplay means * that any characters entered from the keyboard are placed in * the buffer for possible subsequent transmission to the * application program, but they are not displayed. Intensified * display means the intensified characters appear on the screen * brighter than the nonintensified characters. Some devices * cannot intensify characters on the screen and highlight * characters in a different manner. * <p> * The Bit representation of a nondisplay field: * <table border="1" > * <tr> * <th>Binary</td> * <th>Hexaddecimal</td> * <th>Decimal</td> * </tr> * <tr> * <td>00001100</td> * <td>c</td> * <td>12</td> * </tr> * </table> * </li> * </ul> * * @param hexValueForAttribute * the hexadecimal representation of a {@link Field} attribute * valie * @return true if the hex value for the attribute correlates with the * control character, false otherwise. If a control character * correlates bitwise. * */ public boolean isAttribute(String controlCharacter, int hexValueForAttribute) { boolean isAttribute = false; int intValue = Long.decode("0x" + controlCharacter).intValue(); int attributeInt = intValue & hexValueForAttribute; if (attributeInt == hexValueForAttribute) { isAttribute = true; } return isAttribute; }
From source file:eu.comsode.unifiedviews.plugins.transformer.generatedtorelational.GeneratedToRelational.java
private GenTableRow parseValues(String values) { GenTableRow gtr = new GenTableRow(); values = values.replace("(", ""); values = values.replace(")", ""); values = values.replace("'", ""); values = values.replace(" ", ""); values = values.replace("T", " "); String[] fields = values.split(","); try {//from w ww .java 2s .c om gtr.id = Long.decode(fields[1]); } catch (NumberFormatException ex) { LOG.error("Error parsing ID from response from CKAN."); } try { gtr.data = fields[2]; gtr.modificationTimestamp = fmt.parse(fields[3]); if (!fields[4].equalsIgnoreCase("null")) { gtr.deletedTimestamp = fmt.parse(fields[4]); } else { gtr.deletedTimestamp = null; } } catch (ParseException ex) { LOG.error("Error parsing dates from response from CKAN."); } LOG.debug("Parsed data: {}", gtr.toString()); return gtr; }