public <T> T sendRequest(Class<T> cls, Object request) throws WasabiNetClientException { StringWriter sw = new StringWriter(); String convertida = null; String received = null; try { marshaller.setWriter(sw); marshaller.marshal(request); convertida = new String(sw.getBuffer().toString().getBytes("UTF8"), "UTF8"); System.out.println(convertida); received = getData(serviceUrl, convertida); System.out.println("---" + received + "---"); unmarshaller.setClass(cls); return (T) unmarshaller.unmarshal(new StringReader(received)); } catch (IOException e) { throw new WasabiNetClientException("Error de lectura/escritura:" + e.getMessage()); } catch (MarshalException e) { e.printStackTrace(); throw new WasabiNetClientException( "Error al armar la respuesta:" + e.getMessage(), convertida, received); } catch (ValidationException e) { throw new WasabiNetClientException( "Error en la validacion de la respuesta:" + e.getMessage(), convertida, received); } // catch WasabiNetClientException -> Esta directamente salta al metodo que ha llamado a // sendrequest }
public synchronized Object fromXML(java.io.Reader input) throws XMLUtilityException { Object beanObject; org.exolab.castor.xml.Unmarshaller unmarshaller = null; try { log.debug("Creating unmarshaller"); unmarshaller = new org.exolab.castor.xml.Unmarshaller(this.getMapping()); } catch (MappingException e) { log.error("XML mapping file is invalid: ", e); throw new XMLUtilityException("XML mapping file invalid: ", e); } catch (Exception e) { log.error("General Exception caught trying to create unmarshaller: ", e); throw new XMLUtilityException("General Exception caught trying to create unmarshaller: ", e); } try { log.debug("About to unmarshal from input "); beanObject = unmarshaller.unmarshal(input); } catch (MarshalException e) { log.error("Error marshalling input: ", e); throw new XMLUtilityException("Error unmarshalling xml input: " + e.getMessage(), e); } catch (ValidationException e) { log.error("Error in xml validation when unmarshalling xml input: ", e); throw new XMLUtilityException("Error in xml validation when unmarshalling xml input: ", e); } return beanObject; }
private FileWriter handleLoadCastor(FileWriter writer, RulesPostImportContainer rpic) { try { // Create Mapping Mapping mapping = new Mapping(); mapping.loadMapping(SpringServletAccess.getPropertiesDir(context) + "mappingMarshaller.xml"); // Create XMLContext XMLContext xmlContext = new XMLContext(); xmlContext.addMapping(mapping); Marshaller marshaller = xmlContext.createMarshaller(); marshaller.setWriter(writer); marshaller.marshal(rpic); return writer; } catch (FileNotFoundException ex) { throw new OpenClinicaSystemException(ex.getMessage(), ex.getCause()); } catch (IOException ex) { throw new OpenClinicaSystemException(ex.getMessage(), ex.getCause()); } catch (MarshalException e) { throw new OpenClinicaSystemException(e.getMessage(), e.getCause()); } catch (ValidationException e) { throw new OpenClinicaSystemException(e.getMessage(), e.getCause()); } catch (MappingException e) { throw new OpenClinicaSystemException(e.getMessage(), e.getCause()); } catch (Exception e) { throw new OpenClinicaSystemException(e.getMessage(), e.getCause()); } }
/** * This method queries the Vmware vCenter server for sensor data. * * @param svc the monitored service * @param parameters the parameter map * @return the poll status for this system */ @Override public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) { OnmsNode onmsNode = m_nodeDao.get(svc.getNodeId()); // retrieve the assets and String vmwareManagementServer = onmsNode.getAssetRecord().getVmwareManagementServer(); String vmwareManagedEntityType = onmsNode.getAssetRecord().getVmwareManagedEntityType(); String vmwareManagedObjectId = onmsNode.getForeignId(); TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT); PollStatus serviceStatus = PollStatus.unknown(); for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) { VmwareViJavaAccess vmwareViJavaAccess = null; try { vmwareViJavaAccess = new VmwareViJavaAccess(vmwareManagementServer); } catch (MarshalException e) { logger.warn( "Error initialising VMware connection to '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error initialising VMware connection to '" + vmwareManagementServer + "'"); } catch (ValidationException e) { logger.warn( "Error initialising VMware connection to '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error initialising VMware connection to '" + vmwareManagementServer + "'"); } catch (IOException e) { logger.warn( "Error initialising VMware connection to '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error initialising VMware connection to '" + vmwareManagementServer + "'"); } try { vmwareViJavaAccess.connect(); } catch (MalformedURLException e) { logger.warn( "Error connecting VMware management server '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error connecting VMware management server '" + vmwareManagementServer + "'"); } catch (RemoteException e) { logger.warn( "Error connecting VMware management server '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error connecting VMware management server '" + vmwareManagementServer + "'"); } if (!vmwareViJavaAccess.setTimeout(tracker.getConnectionTimeout())) { logger.warn( "Error setting connection timeout for VMware management server '{}'", vmwareManagementServer); } String powerState = "unknown"; if ("HostSystem".equals(vmwareManagedEntityType)) { HostSystem hostSystem = vmwareViJavaAccess.getHostSystemByManagedObjectId(vmwareManagedObjectId); if (hostSystem == null) { return PollStatus.unknown("hostSystem=null"); } else { HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime(); if (hostRuntimeInfo == null) { return PollStatus.unknown("hostRuntimeInfo=null"); } else { HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState(); if (hostSystemPowerState == null) { return PollStatus.unknown("hostSystemPowerState=null"); } else { powerState = hostSystemPowerState.toString(); } } } } else { if ("VirtualMachine".equals(vmwareManagedEntityType)) { VirtualMachine virtualMachine = vmwareViJavaAccess.getVirtualMachineByManagedObjectId(vmwareManagedObjectId); if (virtualMachine == null) { return PollStatus.unknown("virtualMachine=null"); } else { VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime(); if (virtualMachineRuntimeInfo == null) { return PollStatus.unknown("virtualMachineRuntimeInfo=null"); } else { VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState(); if (virtualMachinePowerState == null) { return PollStatus.unknown("virtualMachinePowerState=null"); } else { powerState = virtualMachinePowerState.toString(); } } } } else { logger.warn( "Error getting '{}' for '{}'", vmwareManagedEntityType, vmwareManagedObjectId); vmwareViJavaAccess.disconnect(); return serviceStatus; } } if ("poweredOn".equals(powerState)) { serviceStatus = PollStatus.available(); } else { serviceStatus = PollStatus.unavailable("The system's state is '" + powerState + "'"); } vmwareViJavaAccess.disconnect(); } return serviceStatus; }
/** {@inheritDoc} */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // the path info will be the category name we need String pathInfo = request.getPathInfo(); // send 400 Bad Request if they did not specify a category in the path // info if (pathInfo == null) { LOG.error("Request with no path info"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No Category name given in path"); return; } // remove the preceding slash if present if (pathInfo.startsWith("/")) { pathInfo = pathInfo.substring(1, pathInfo.length()); } // since these category names can contain spaces, etc, // we have to URL encode them in the URL String categoryName = Util.decode(pathInfo); org.opennms.netmgt.xml.rtc.Category category = null; try { ServletInputStream inStream = request.getInputStream(); // note the unmarshaller closes the input stream, so don't try to // close // it again or the servlet container will complain org.opennms.netmgt.xml.rtc.EuiLevel level = CastorUtils.unmarshal(org.opennms.netmgt.xml.rtc.EuiLevel.class, inStream); // for now we only deal with the first category, they're only sent // one // at a time anyway category = level.getCategory(0); } catch (MarshalException ex) { LOG.error("Failed to load configuration", ex); response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid XML input: MarshalException: " + ex.getMessage()); return; } catch (ValidationException ex) { LOG.error("Failed to load configuration", ex); response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid XML input: ValidationException" + ex.getMessage()); return; } // make sure we got data for the category we are interested in // send 400 Bad Request if they did not supply category information // for the categoryname in the path info if (!categoryName.equals(category.getCatlabel())) { LOG.error("Request did not supply information for category specified in path info"); response.sendError( HttpServletResponse.SC_BAD_REQUEST, "No category info found for " + categoryName); return; } // update the category information in the CategoryModel this.model.updateCategory(category); // return a success message response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("Category data parsed successfully."); out.close(); LOG.info("Successfully received information for {}", categoryName); }
/** {@inheritDoc} */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { reloadFiles(); String query = request.getQueryString(); if (query != null) { java.util.List<String> checkedList = new ArrayList<String>(); java.util.List<String> deleteList = new ArrayList<String>(); props.store( new FileOutputStream( ConfigFileConstants.getFile(ConfigFileConstants.POLLER_CONF_FILE_NAME)), null); StringTokenizer strTok = new StringTokenizer(query, "&"); while (strTok.hasMoreTokens()) { String token = strTok.nextToken(); if (token != null) { StringTokenizer keyTokens = new StringTokenizer(token, "="); String name = null; if (keyTokens.hasMoreTokens()) { name = (String) keyTokens.nextToken(); } if (keyTokens.hasMoreTokens()) { String checked = (String) keyTokens.nextToken(); if (name != null) { if (name.indexOf("delete") == -1) // Not to be // deleted { modifyPollerInfo(checked, name); checkedList.add(name); } else // Deleted { String deleteService = name.substring(0, name.indexOf("delete")); deleteList.add(deleteService); } } } } } adjustNonChecked(checkedList); deleteThese(deleteList); Writer poller_fileWriter = new OutputStreamWriter( new FileOutputStream( ConfigFileConstants.getFile(ConfigFileConstants.POLLER_CONFIG_FILE_NAME)), "UTF-8"); Writer capsd_fileWriter = new OutputStreamWriter( new FileOutputStream( ConfigFileConstants.getFile(ConfigFileConstants.CAPSD_CONFIG_FILE_NAME)), "UTF-8"); try { Marshaller.marshal(pollerConfig, poller_fileWriter); Marshaller.marshal(capsdConfig, capsd_fileWriter); } catch (MarshalException e) { e.printStackTrace(); throw new ServletException(e.getMessage()); } catch (ValidationException e) { e.printStackTrace(); throw new ServletException(e.getMessage()); } } response.sendRedirect(this.redirectSuccess); }