List of usage examples for java.util.logging Level FINER
Level FINER
To view the source code for java.util.logging Level FINER.
Click Source Link
From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java
/** * Generates the module id map used by the transport to encode/decode module names * using assigned module name ids./*from w w w . j a va 2s . c om*/ * * @param deps * The dependencies object * * @throws IOException */ protected void generateModuleIdMap(IDependencies deps) throws IOException { final String methodName = "generateModuleIdMap"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractHttpTransport.class.getName(), methodName); } if (getModuleIdRegFunctionName() == null) { if (isTraceLogging) { log.finer("No module id list registration function - returning"); //$NON-NLS-1$ log.exiting(AbstractHttpTransport.class.getName(), methodName); } return; } Map<String, String> names = new TreeMap<String, String>(); // Use TreeMap to get consistent ordering for (String name : deps.getDependencyNames()) { names.put(name, isTraceLogging ? deps.getURI(name).toString() : null); } for (String name : getSyntheticModuleNames()) { names.put(name, isTraceLogging ? "transport added" : null); //$NON-NLS-1$ } if (isTraceLogging) { // Log the module name id list. This information is useful when trying to determine // why different servers in the same cluster might be generating different list hashes. StringBuffer sb = new StringBuffer("Module ID list:\r\n"); //$NON-NLS-1$ int i = 1; for (Map.Entry<String, String> entry : names.entrySet()) { sb.append(i++).append(": ").append(entry.getKey()).append(" - ").append(entry.getValue()) //$NON-NLS-1$//$NON-NLS-2$ .append("\r\n"); //$NON-NLS-1$ } log.finer(sb.toString()); } Map<String, Integer> idMap = new HashMap<String, Integer>(names.size()); List<String> idList = new ArrayList<String>(names.size() + 1); idList.add(""); // slot 0 is unused //$NON-NLS-1$ idList.addAll(names.keySet()); for (int i = 1; i < idList.size(); i++) { idMap.put(idList.get(i), i); } MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); //$NON-NLS-1$ } catch (NoSuchAlgorithmException e) { if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, e.getMessage(), e); } throw new IOException(e); } moduleIdListHash = md.digest(idList.toString().getBytes("UTF-8")); //$NON-NLS-1$ moduleIdMap = Collections.unmodifiableMap(idMap); moduleIdList = idList; if (log.isLoggable(Level.INFO)) { log.info("Module ID List hash = " + TypeUtil.byteArray2String(moduleIdListHash)); //$NON-NLS-1$ } if (isTraceLogging) { log.exiting(AbstractHttpTransport.class.getName(), methodName); } }
From source file:org.cloudifysource.rest.controllers.ServiceController.java
/** * * Invokes a custom command on all of the specified service instances. Custom parameters are passed as a map using * the POST method and contain the command name and parameter values for the specified command. * * @param applicationName// w w w. j a v a 2s . c om * The application name. * @param serviceName * The service name. * @param beanName * deprecated. * @param params * The command parameters. * @return a Map containing the result of each invocation on a service instance. * @throws RestErrorException * When lookup service not found or no processing unit instance is found for the requested service. */ @JsonRequestExample(requestBody = "{\"param1 name\":\"param1\",\"param2 name\":\"param2\"}") @JsonResponseExample(status = "success", responseBody = "{\"instance #1@127.0.0.1\":{\"Invocation_Instance_Name\":\"instance #1@127.0.0.1\"" + ",\"Invocation_Instance_ID\":\"1\"" + ",\"Invocation_Result\":\"the invocation result as specified in the service file\"" + ",\"Invocation_Success\":\"true\"," + "\"Invocation_Exception\":null,\"Invocation_Command_Name\":\"custom command name\"}}") @PossibleResponseStatuses(responseStatuses = { @PossibleResponseStatus(code = HTTP_OK, description = "success"), @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "failed_to_locate_service"), @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "no_processing_unit_instances_found_for_invocation") }) @RequestMapping(value = "applications/{applicationName}/services/{serviceName}/beans/{beanName}/invoke", method = RequestMethod.POST) @PreAuthorize("isFullyAuthenticated()") @ResponseBody public Map<String, Object> invoke(@PathVariable final String applicationName, @PathVariable final String serviceName, @PathVariable final String beanName, @RequestBody final Map<String, Object> params) throws RestErrorException { final String absolutePuName = ServiceUtils.getAbsolutePUName(applicationName, serviceName); if (logger.isLoggable(Level.FINER)) { logger.finer("received request to invoke bean " + beanName + " of service " + absolutePuName + " of application " + applicationName); } // Get the PU final ProcessingUnit pu = admin.getProcessingUnits().waitFor(absolutePuName, PU_DISCOVERY_TIMEOUT_SEC, TimeUnit.SECONDS); if (pu == null) { logger.severe("Could not find service " + absolutePuName); return unavailableServiceError(absolutePuName); } if (permissionEvaluator != null) { final String puAuthGroups = pu.getBeanLevelProperties().getContextProperties() .getProperty(CloudifyConstants.CONTEXT_PROPERTY_AUTH_GROUPS); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final CloudifyAuthorizationDetails authDetails = new CloudifyAuthorizationDetails(authentication); permissionEvaluator.verifyPermission(authDetails, puAuthGroups, "deploy"); } // result, mapping service instances to results final Map<String, Object> invocationResult = new HashMap<String, Object>(); final ProcessingUnitInstance[] instances = pu.getInstances(); if (instances.length == 0) { throw new RestErrorException(ResponseConstants.NO_PROCESSING_UNIT_INSTANCES_FOUND_FOR_INVOCATION, serviceName); } // Why a map? TODO: Use an array here instead. // map between service name and its future final Map<String, Future<Object>> futures = new HashMap<String, Future<Object>>(instances.length); for (final ProcessingUnitInstance instance : instances) { // key includes instance ID and host name final String serviceInstanceName = buildServiceInstanceName(instance); try { final Future<Object> future = ((DefaultProcessingUnitInstance) instance).invoke(beanName, params); futures.put(serviceInstanceName, future); } catch (final Exception e) { logger.severe("Error invoking service " + serviceName + ":" + instance.getInstanceId() + " on host " + instance.getVirtualMachine().getMachine().getHostName()); invocationResult.put(serviceInstanceName, "pu_instance_invocation_failure"); } } for (final Map.Entry<String, Future<Object>> entry : futures.entrySet()) { try { Object result = entry.getValue().get(); // use only tostring of collection values, to avoid // serialization problems result = postProcessInvocationResult(result, entry.getKey()); invocationResult.put(entry.getKey(), result); } catch (final Exception e) { invocationResult.put(entry.getKey(), "Invocation failure: " + e.getMessage()); } } return successStatus(invocationResult); }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
@Override public boolean logBatch(final LogMessagingTask[] packets) { if (isClosed()) return false; if (!isLoggingEnabled()) return true; if (!isJournalingEnabled()) // no need to journal and the file, offset have no meaning here return this.logBatchDB(packets); // else journaling with just indexes in DB String journalFile = this.journaler.curLogfile; PendingLogTask[] pending = null;/*from w ww .j a v a 2 s .c om*/ boolean journaled = (ENABLE_JOURNALING && (pending = this.journal(packets)) != null); assert (pending != null); if (!journaled || !DB_INDEX_JOURNAL) return journaled; String[] journalFiles = new String[packets.length]; for (int i = 0; i < packets.length; i++) journalFiles[i] = journalFile; // synchronous indexing if (LOG_INDEX_FREQUENCY == 0) return this.syncLogMessagesIndex(); // asynchronous indexing log.log(Level.FINER, "{0} has {1} pending log messages", new Object[] { this, this.pendingLogMessages.size() }); // not strictly necessary coz we index upon rolling logfile anyway if (Util.oneIn(LOG_INDEX_FREQUENCY)) SQLPaxosLogger.this.syncLogMessagesIndexBackground(); // else no indexing of journal return journaled; }
From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java
private void mapRequestToObj(HashMap<String, Object> data, Class expectedClass, Object obj) throws Exception { if (obj == null) { throw new ApplicationException("mapRequestToObj called on NULL obj", "ERR9001"); }// w w w. j a v a 2s.c o m try { Method versionMethod = expectedClass.getMethod("getVersion", (Class<?>[]) null); Long objVersion = (Long) versionMethod.invoke(obj, (Object[]) null); String clientVersion = (String) data.get("version"); if (objVersion != null && clientVersion != null) { try { long clientVersionLong = Long.parseLong(clientVersion); if (!objVersion.equals(clientVersionLong)) { throw makeApplicationException("Can't save object", "ERR9016", (Serializable[]) null); } } catch (NumberFormatException nfe) { // Version from client isn't number - ignore } } } catch (NoSuchMethodException nme) { // No version control } Method[] methods = expectedClass.getMethods(); for (Method m : methods) { Class<?>[] paramTypes = m.getParameterTypes(); Class persistentClass = null; if (paramTypes.length == 1) { if (paramTypes[0].getAnnotation(Entity.class) != null) { persistentClass = paramTypes[0]; } else if (paramTypes[0].getAnnotation(Embeddable.class) != null) { persistentClass = paramTypes[0]; } } ServiceDescription srvParam = paramTypes.length == 1 ? findServiceByClassName(paramTypes[0].getName()) : null; if ((m.getName().startsWith(SET_PREFIX) && paramTypes.length == 1 && (paramTypes[0].isAssignableFrom(String.class) || paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE) || paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE) || paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE) || paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE) || paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE) || paramTypes[0].equals(Date.class) || Enum.class.isAssignableFrom(paramTypes[0]) || (srvParam != null && srvParam.getFindById() != null) || persistentClass != null)) || (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0 && (Set.class.isAssignableFrom(m.getReturnType()) || List.class.isAssignableFrom(m.getReturnType())))) { String fldName; if (m.getName().startsWith(GET_TRANSLATE)) { fldName = m.getName().substring(GET_TRANSLATE_LENGTH, GET_TRANSLATE_LENGTH + 1).toLowerCase() + m.getName().substring(GET_TRANSLATE_LENGTH + 1); } else { fldName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); } Object value = data.get(fldName); if (value == null) { fldName = m.getName().substring(3); value = data.get(fldName); } if (value != null) { Object typedVal; String val = null; if (value instanceof String) { val = (String) value; } log.log(Level.FINER, " value = " + value); if (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0 && (Set.class.isAssignableFrom(m.getReturnType()) || List.class.isAssignableFrom(m.getReturnType()))) { log.log(Level.FINER, "GET"); String attrName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); Type[] actualTypeArguments = null; Class iterClass = expectedClass; while (iterClass != null) { try { Field field = iterClass.getDeclaredField(attrName); ParameterizedType genericType = (ParameterizedType) field.getGenericType(); actualTypeArguments = genericType.getActualTypeArguments(); break; } catch (NoSuchFieldException nsfe) { // do nothing iterate again } iterClass = iterClass.getSuperclass(); iterClass = iterClass.equals(Object.class) ? null : iterClass; } if (actualTypeArguments != null && actualTypeArguments.length == 1 && actualTypeArguments[0] instanceof Class) { Class assocClass = (Class) actualTypeArguments[0]; ServiceDescription assocService = findServiceByClassName(assocClass.getName()); Collection dbValueSet = (Collection) m.invoke(obj, (Object[]) null); if (value == null || !(value instanceof HashMap)) { log.log(Level.FINE, "No data for db property {0}", attrName); } else if (assocService != null) { HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value; ArrayList<Object> removeIt = new ArrayList<Object>(); Iterator dbIterator = dbValueSet.iterator(); while (dbIterator.hasNext()) { Object dbVal = dbIterator.next(); String dbValId = getIdFromObj(dbVal); if (dbValId != null) { boolean wasMatchingGuiVal = false; ArrayList<String> removeKeys = new ArrayList<String>(); for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object guiValue = ((HashMap<String, Object>) object).get("id"); if (guiValue.equals(dbValId)) { removeKeys.add(key); wasMatchingGuiVal = true; mapRequestToObj((HashMap<String, Object>) guiValue, assocClass, dbVal); break; } } else if (object instanceof String) { // Association if (dbValId.equals(object)) { removeKeys.add(key); wasMatchingGuiVal = true; } } else { log.log(Level.WARNING, "Wrong object type from GUI under key {0}", key); } } // Remove processed elements // Direct remove is firing concurrent modification exception for (String removeKey : removeKeys) { guiValueMap.remove(removeKey); } if (!wasMatchingGuiVal) { // Is not in list comming from GUI - delete removeIt.add(dbVal); } } else { log.log(Level.WARNING, "No ID in object {0}", dbVal); } } dbValueSet.removeAll(removeIt); // Rest are new records for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object subObj = makeNewInstance(assocClass, (HashMap<String, Object>) object); mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj); dbValueSet.add(subObj); } else if (object instanceof String) { // Association try { Long id = new Long((String) object); Object assocObj = assocService.getFindById().invoke( assocService.getInstance(), ServiceContextStore.get(), id); if (assocObj != null) { dbValueSet.add(assocObj); } else { log.log(Level.WARNING, "Object with ID {0} not availabla via service {1}", new Object[] { id, assocService.getName() }); } } catch (Exception ex) { log.log(Level.WARNING, "No ID parsable from value {0} under key {1}", new Object[] { object, key }); } } else { log.log(Level.WARNING, "Wrong sub type {0}", attrName); } } } else if (assocClass != null) { HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value; ArrayList<Object> removeIt = new ArrayList<Object>(); Iterator dbIterator = dbValueSet.iterator(); while (dbIterator.hasNext()) { Object dbVal = dbIterator.next(); String dbValId = getIdFromObj(dbVal); if (dbValId != null) { Object matchingGuiVal = null; for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { HashMap<String, Object> guiVal = (HashMap<String, Object>) object; if (dbValId.equals(guiVal.get("id"))) { guiValueMap.remove(key); matchingGuiVal = guiVal; break; } } else { log.log(Level.WARNING, "Wrong object type from GUI under key {0}", key); } } if (matchingGuiVal != null) { // Coming from GUI - update mapRequestToObj((HashMap<String, Object>) matchingGuiVal, assocClass, dbVal); } else { // Not in GUI - delete removeIt.add(dbVal); } } else { log.log(Level.WARNING, "No ID in object {0}", dbVal); } } dbValueSet.removeAll(removeIt); // Rest are new records for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object subObj = makeNewInstance(assocClass, (HashMap<String, Object>) object); mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj); dbValueSet.add(subObj); } else { log.log(Level.WARNING, "Wrong sub type {0}", attrName); } } } } else { log.log(Level.WARNING, "No DB mapping or not of collection type: {0}", attrName); } typedVal = null; } else if (paramTypes[0].isAssignableFrom(String.class)) { typedVal = val; } else if (paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE)) { typedVal = Integer.parseInt(val); } else if (paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE)) { typedVal = Long.parseLong(val); } else if (paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE)) { typedVal = Double.parseDouble(val); } else if (paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE)) { typedVal = Float.parseFloat(val); } else if (paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE)) { typedVal = "true".equalsIgnoreCase(val) || "t".equalsIgnoreCase(val) || "y".equalsIgnoreCase(val); } else if (paramTypes[0].isAssignableFrom(Date.class)) { typedVal = dateFormat.parse(val); } else if (Enum.class.isAssignableFrom(paramTypes[0])) { try { Method fromValueMethod = paramTypes[0].getMethod("fromValue", String.class); typedVal = fromValueMethod.invoke(null, val); } catch (Exception ex) { typedVal = null; } try { if (typedVal == null) { Method valueOfMethod = paramTypes[0].getMethod("valueOf", String.class); typedVal = valueOfMethod.invoke(null, val); } } catch (Exception ex) { typedVal = null; } } else if (persistentClass != null && persistentClass.equals(FileUpload.class)) { FileItem fileItem = uploadServlet.getFileItem(sessionId.get(), fldName, val); if (fileItem != null) { typedVal = fileUploadService.uploadFile(ServiceContextStore.get(), fileItem.getName(), fileItem.getContentType(), fileItem.getInputStream()); } else { typedVal = null; } } else if (srvParam != null && srvParam.getFindById() != null) { if (value instanceof HashMap) { HashMap<String, Object> embeddedObj = (HashMap<String, Object>) value; typedVal = srvParam.getFindById().invoke(srvParam.getInstance(), ServiceContextStore.get(), new Long((String) embeddedObj.get("id"))); mapRequestToObj(embeddedObj, srvParam.getExpectedClass(), typedVal); } else { try { Long parsedId = new Long(val); typedVal = srvParam.getFindById().invoke(srvParam.getInstance(), ServiceContextStore.get(), parsedId); } catch (NumberFormatException nfe) { // wrong value typedVal = null; } } } else if (persistentClass != null) { String getMethodName = "g" + m.getName().substring(1); try { Method getMethod = obj.getClass().getMethod(getMethodName, (Class[]) null); typedVal = getMethod.invoke(obj, (Object[]) null); } catch (NoSuchMethodException nsme) { typedVal = null; } if (typedVal == null) { typedVal = makeNewInstance(persistentClass, (HashMap<String, Object>) value); } mapRequestToObj((HashMap<String, Object>) value, typedVal.getClass(), typedVal); } else { log.log(Level.WARNING, "Can't convert value for: {0}.{1} ({2})", new Object[] { expectedClass.getName(), m.getName(), (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) }); typedVal = null; } if (typedVal != null) { m.invoke(obj, typedVal); } } } else if (m.getName().startsWith(SET_PREFIX)) { log.log(Level.WARNING, "Unusable setter method: {0}.{1} ({2})", new Object[] { expectedClass.getName(), m.getName(), (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) }); } } }
From source file:foodsimulationmodel.pathmapping.Route.java
/** * Returns all the coordinates that describe how to travel along a path, restricted to road coordinates. In some * cases the route wont have an associated road, this occurs if the route is part of a transport network. In this * case just the origin and destination coordinates are added to the route. * /*from w w w.j a v a 2 s .co m*/ * @param shortestPath * @param startingJunction * The junction the path starts from, this is required so that the algorithm knows which road coordinate * to add first (could be first or last depending on the order that the road coordinates are stored * internally). * @return the coordinates as a mapping between the coord and its associated speed (i.e. how fast the agent can * travel to the next coord) which is dependent on the type of edge and the agent (e.g. * driving/walking/bus). LinkedHashMap is used to guarantee the insertion order of the coords is maintained. * @throws RoutingException */ private void getRouteBetweenJunctions(List<RepastEdge<Junction>> shortestPath, Junction startingJunction) throws RoutingException { double time = System.nanoTime(); if (shortestPath.size() < 1) { // This could happen if the agent's destination is on the same road // as the origin return; } // Lock the currentAgent so that NetworkEdge obejcts know what speed to use (depends on transport available to // the specific agent). synchronized (GlobalVars.TRANSPORT_PARAMS.currentBurglarLock) { GlobalVars.TRANSPORT_PARAMS.currentAgent = this.agent; // Iterate over all edges in the route adding coords and weights as appropriate NetworkEdge<Junction> e; Road r; // Use sourceFirst to represent whether or not the edge's source does actually represent the start of the // edge (agent could be going 'forwards' or 'backwards' over edge boolean sourceFirst; for (int i = 0; i < shortestPath.size(); i++) { e = (NetworkEdge<Junction>) shortestPath.get(i); if (i == 0) { // No coords in route yet, compare the source to the starting junction sourceFirst = (e.getSource().equals(startingJunction)) ? true : false; } else { // Otherwise compare the source to the last coord added to the list sourceFirst = (e.getSource().getCoords().equals(this.routeX.get(this.routeX.size() - 1))) ? true : false; } /* * Now add the coordinates describing how to move along the road. If there is no road associated with * the edge (i.e. it is a transport route) then just add the source/dest coords. Note that the shared * coordinates between two edges will be added twice, these must be removed later */ r = e.getRoad(); /* * Get the speed that the agent will be able to travel along this edge (depends on the transport * available to the agent and the edge). Some speeds will be < 1 if the agent shouldn't be using this * edge but doesn't have any other way of getting to the destination. in these cases set speed to 1 * (equivalent to walking). */ double speed = e.getSpeed(); if (speed < 1) speed = 1; if (r == null) { // No road associated with this edge (it is a // transport link) so just add source if (sourceFirst) { this.addToRoute(e.getSource().getCoords(), r, speed, "getRouteBetweenJunctions - no road"); this.addToRoute(e.getTarget().getCoords(), r, -1, "getRouteBetweenJunctions - no road"); // (Note speed = -1 used because we don't know the weight to the next // coordinate - this can be removed later) } else { this.addToRoute(e.getTarget().getCoords(), r, speed, "getRouteBetweenJunctions - no road"); this.addToRoute(e.getSource().getCoords(), r, -1, "getRouteBetweenJunctions - no road"); } } else { // This edge is a road, add all the coords which make up its geometry Coordinate[] roadCoords = ContextManager.roadProjection.getGeometry(r).getCoordinates(); if (roadCoords.length < 2) throw new RoutingException("Route.getRouteBetweenJunctions: for some reason road " + "'" + r.toString() + "' doesn't have at least two coords as part of its geometry (" + roadCoords.length + ")"); // Make sure the coordinates of the road are added in the correct order if (!sourceFirst) { ArrayUtils.reverse(roadCoords); } // Add all the road geometry's coords for (int j = 0; j < roadCoords.length; j++) { this.addToRoute(roadCoords[j], r, speed, "getRouteBetweenJuctions - on road"); // (Note that last coord will have wrong weight) } // for roadCoords.length } // if road!=null } // Check all lists are still the same size. assert this.roadsX.size() == this.routeX.size() && this.routeDescriptionX.size() == this.routeSpeedsX.size() && this.roadsX.size() == this.routeDescriptionX.size(); // Check all lists are still the same size. assert this.roadsX.size() == this.routeX.size() && this.routeDescriptionX.size() == this.routeSpeedsX.size() && this.roadsX.size() == this.routeDescriptionX.size(); // Finished! LOGGER.log(Level.FINER, "getRouteBetweenJunctions (" + (0.000001 * (System.nanoTime() - time)) + "ms"); return; } // synchronized }
From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java
/** * Returns a mapping of resource aliases to IResources defined in the init-params. * If the IResource is null, then the alias is for the aggregator itself rather * than a resource location.// w w w. j a v a 2 s. c o m * * @param initParams * The aggregator init-params * * @return Mapping of aliases to IResources */ protected Map<String, IResource> getPathsAndAliases(InitParams initParams) { final String sourceMethod = "getPahtsAndAliases"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { initParams }); } Map<String, IResource> resourcePaths = new HashMap<String, IResource>(); List<String> aliases = initParams.getValues(InitParams.ALIAS_INITPARAM); for (String alias : aliases) { addAlias(alias, null, "alias", resourcePaths); //$NON-NLS-1$ } List<String> resourceIds = initParams.getValues(InitParams.RESOURCEID_INITPARAM); for (String resourceId : resourceIds) { aliases = initParams.getValues(resourceId + ":alias"); //$NON-NLS-1$ List<String> baseNames = initParams.getValues(resourceId + ":base-name"); //$NON-NLS-1$ if (aliases == null || aliases.size() != 1) { throw new IllegalArgumentException(resourceId + ":aliases"); //$NON-NLS-1$ } if (baseNames == null || baseNames.size() != 1) { throw new IllegalArgumentException(resourceId + ":base-name"); //$NON-NLS-1$ } String alias = aliases.get(0); String baseName = baseNames.get(0); // make sure not root path boolean isPathComp = false; for (String part : alias.split("/")) { //$NON-NLS-1$ if (part.length() > 0) { isPathComp = true; break; } } if (!isPathComp) { throw new IllegalArgumentException(resourceId + ":alias = " + alias); //$NON-NLS-1$ } IResource res = newResource(URI.create(baseName)); if (res == null) { throw new NullPointerException(); } addAlias(alias, res, resourceId + ":alias", resourcePaths); //$NON-NLS-1$ } if (isTraceLogging) { log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, resourcePaths); } return Collections.unmodifiableMap(resourcePaths); }
From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java
protected void addAlias(String alias, IResource res, String initParamName, Map<String, IResource> map) { final String sourceMethod = "addAlias"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { alias, res, initParamName, map }); }/*ww w .j av a 2 s.c o m*/ String[] parts; if (alias == null || (parts = alias.split("/")).length == 0) { //$NON-NLS-1$ throw new IllegalArgumentException(initParamName + " = " + alias); //$NON-NLS-1$ } List<String> nonEmptyParts = new ArrayList<String>(parts.length); for (String part : parts) { if (part != null && part.length() > 0) { nonEmptyParts.add(part); } } alias = "/" + StringUtils.join(nonEmptyParts, "/"); //$NON-NLS-1$ //$NON-NLS-2$ // Make sure no overlapping alias paths for (String test : map.keySet()) { if (alias.equals(test)) { throw new IllegalArgumentException("Duplicate alias path: " + alias); //$NON-NLS-1$ } else if (alias.startsWith(test + "/") || test.startsWith(alias + "/")) { //$NON-NLS-1$ //$NON-NLS-2$ throw new IllegalArgumentException("Overlapping alias paths: " + alias + ", " + test); //$NON-NLS-1$ //$NON-NLS-2$ } } map.put(alias, res); log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod); }
From source file:org.cloudifysource.rest.controllers.ServiceController.java
/** * * Invokes a custom command on a specific service instance. Custom parameters are passed as a map using POST method * and contain the command name and parameter values for the specified command. * * @param applicationName/*from www. j a va2 s. co m*/ * The application name. * @param serviceName * The service name * @param instanceId * The service instance number to be invoked. * @param beanName * depreciated * @param params * a Map containing the result of each invocation on a service instance. * @return a Map containing the invocation result on the specified instance. * @throws RestErrorException * When failed to locate service/service instance or invocation failed. */ @JsonRequestExample(requestBody = "{\"param1 name\":\"param1\",\"param2 name\":\"param2\"}") @JsonResponseExample(status = "success", responseBody = "{\"Invocation_Instance_Name\":\"instance #1@127.0.0.1\"" + ",\"Invocation_Instance_ID\":\"1\"" + ",\"Invocation_Result\":\"the invocation result as specified in the service file\"" + ",\"Invocation_Success\":\"true\"," + "\"Invocation_Exception\":null,\"Invocation_Command_Name\":\"custom command name\"}") @PossibleResponseStatuses(responseStatuses = { @PossibleResponseStatus(code = HTTP_OK, description = "success"), @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "failed_to_locate_service"), @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "service_instance_unavailable"), @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "failed_to_invoke_instance") }) @RequestMapping(value = "applications/{applicationName}/services/{serviceName}/instances" + "/{instanceId}/beans/{beanName}/invoke", method = RequestMethod.POST) @PreAuthorize("isFullyAuthenticated()") @ResponseBody public Map<String, Object> invokeInstance(@PathVariable final String applicationName, @PathVariable final String serviceName, @PathVariable final int instanceId, @PathVariable final String beanName, @RequestBody final Map<String, Object> params) throws RestErrorException { final String absolutePuName = ServiceUtils.getAbsolutePUName(applicationName, serviceName); if (logger.isLoggable(Level.FINER)) { logger.finer("received request to invoke bean " + beanName + " of service " + serviceName + " of application " + applicationName); } // Get PU final ProcessingUnit pu = admin.getProcessingUnits().waitFor(absolutePuName, PU_DISCOVERY_TIMEOUT_SEC, TimeUnit.SECONDS); if (pu == null) { logger.severe("Could not find service " + absolutePuName); return unavailableServiceError(absolutePuName); } if (permissionEvaluator != null) { final String puAuthGroups = pu.getBeanLevelProperties().getContextProperties() .getProperty(CloudifyConstants.CONTEXT_PROPERTY_AUTH_GROUPS); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final CloudifyAuthorizationDetails authDetails = new CloudifyAuthorizationDetails(authentication); permissionEvaluator.verifyPermission(authDetails, puAuthGroups, "deploy"); } // Get PUI final InternalProcessingUnitInstance pui = findInstanceById(pu, instanceId); if (pui == null) { logger.severe("Could not find service instance " + instanceId + " for service " + absolutePuName); throw new RestErrorException(ResponseConstants.SERVICE_INSTANCE_UNAVAILABLE, applicationName, absolutePuName, Integer.toString(instanceId)); } final String instanceName = buildServiceInstanceName(pui); // Invoke the remote service try { final Future<?> future = pui.invoke(beanName, params); final Object invocationResult = future.get(); final Object finalResult = postProcessInvocationResult(invocationResult, instanceName); return successStatus(finalResult); } catch (final Exception e) { logger.severe("Error invoking pu instance " + absolutePuName + ":" + instanceId + " on host " + pui.getVirtualMachine().getMachine().getHostName()); throw new RestErrorException(FAILED_TO_INVOKE_INSTANCE, absolutePuName, Integer.toString(instanceId), e.getMessage()); } }
From source file:com.cloudant.sync.datastore.DatastoreImpl.java
/** * <p>/*from w ww. j a v a 2 s .c om*/ * Inserts one or more revisions of a document into the database. For efficiency, this is * performed as one database transaction. * </p> * <p> * Each revision is inserted at a point in the tree expressed by the path described in the * {@code revisionHistory} field. If any non-leaf revisions do not exist locally, then they are * created as "stub" revisions. * </p> * <p> * This method should only be called by the replicator. It is designed * to allow revisions from remote databases to be added to this * database during the replication process: the documents in the remote database already have * revision IDs that need to be preserved for the two databases to be in sync (otherwise it * would not be possible to tell that the two represent the same revision). This is analogous to * using the _new_edits false option in CouchDB * (see <a href="https://wiki.apache.org/couchdb/HTTP_Bulk_Document_API#Posting_Existing_Revisions"> * the CouchDB wiki</a> for more detail). * <p> * If the document was successfully inserted, a * {@link com.cloudant.sync.notifications.DocumentCreated DocumentCreated}, * {@link com.cloudant.sync.notifications.DocumentModified DocumentModified}, or * {@link com.cloudant.sync.notifications.DocumentDeleted DocumentDeleted} * event is posted on the event bus. The event will depend on the nature * of the update made. * </p> * * * @param items one or more revisions to insert. Each {@code ForceInsertItem} consists of: * <ul> * <li> * <b>rev</b> A {@code DocumentRevision} containing the information for a revision * from a remote datastore. * </li> * <li> * <b>revisionHistory</b> The history of the revision being inserted, * including the rev ID of {@code rev}. This list * needs to be sorted in ascending order * </li> * <li> * <b>attachments</b> Attachments metadata and optionally data if {@code pullAttachmentsInline} true * </li> * <li> * <b>preparedAttachments</b> Non-empty if {@code pullAttachmentsInline} false. * Attachments that have already been prepared, this is a * Map of String[docId,revId] list of attachments * </li> * <li> * <b>pullAttachmentsInline</b> If true, use {@code attachments} metadata and data directly * from received JSON to add new attachments for this revision. * Else use {@code preparedAttachments} which were previously * downloaded and prepared by processOneChangesBatch in * BasicPullStrategy * </li> * </ul> * * @see Datastore#getEventBus() * @throws DocumentException if there was an error inserting the revision or its attachments * into the database */ public void forceInsert(final List<ForceInsertItem> items) throws DocumentException { Preconditions.checkState(this.isOpen(), "Database is closed"); for (ForceInsertItem item : items) { Preconditions.checkNotNull(item.rev, "Input document revision cannot be null"); Preconditions.checkNotNull(item.revisionHistory, "Input revision history must not be null"); Preconditions.checkArgument(item.revisionHistory.size() > 0, "Input revision history must not be empty"); Preconditions.checkArgument(checkCurrentRevisionIsInRevisionHistory(item.rev, item.revisionHistory), "Current revision must exist in revision history."); Preconditions.checkArgument(checkRevisionIsInCorrectOrder(item.revisionHistory), "Revision history must be in right order."); CouchUtils.validateDocumentId(item.rev.getId()); CouchUtils.validateRevisionId(item.rev.getRevision()); } // for raising events after completing database transaction final List<DocumentModified> events = new LinkedList<DocumentModified>(); try { queue.submitTransaction(new SQLQueueCallable<Object>() { @Override public Object call(SQLDatabase db) throws Exception { for (ForceInsertItem item : items) { logger.finer("forceInsert(): " + item.rev.toString()); DocumentCreated documentCreated = null; DocumentUpdated documentUpdated = null; boolean ok = true; long docNumericId = getNumericIdInQueue(db, item.rev.getId()); long seq = 0; if (docNumericId != -1) { seq = doForceInsertExistingDocumentWithHistory(db, item.rev, docNumericId, item.revisionHistory, item.attachments); item.rev.initialiseSequence(seq); // TODO fetch the parent doc? documentUpdated = new DocumentUpdated(null, item.rev); } else { seq = doForceInsertNewDocumentWithHistory(db, item.rev, item.revisionHistory); item.rev.initialiseSequence(seq); documentCreated = new DocumentCreated(item.rev); } // now deal with any attachments if (item.pullAttachmentsInline) { if (item.attachments != null) { for (String att : item.attachments.keySet()) { Map attachmentMetadata = (Map) item.attachments.get(att); Boolean stub = (Boolean) attachmentMetadata.get("stub"); if (stub != null && stub) { // stubs get copied forward at the end of // insertDocumentHistoryIntoExistingTree - nothing to do here continue; } String data = (String) attachmentMetadata.get("data"); String type = (String) attachmentMetadata.get("content_type"); InputStream is = Base64InputStreamFactory .get(new ByteArrayInputStream(data.getBytes("UTF-8"))); // inline attachments are automatically decompressed, // so we don't have to worry about that UnsavedStreamAttachment usa = new UnsavedStreamAttachment(is, att, type); try { PreparedAttachment pa = AttachmentManager.prepareAttachment(attachmentsDir, attachmentStreamFactory, usa); AttachmentManager.addAttachment(db, attachmentsDir, item.rev, pa); } catch (Exception e) { logger.log(Level.SEVERE, "There was a problem adding the " + "attachment " + usa + "to the datastore for document " + item.rev, e); throw e; } } } } else { try { if (item.preparedAttachments != null) { for (String[] key : item.preparedAttachments.keySet()) { String id = key[0]; String rev = key[1]; try { DocumentRevision doc = getDocumentInQueue(db, id, rev); if (doc != null) { AttachmentManager.addAttachmentsToRevision(db, attachmentsDir, doc, item.preparedAttachments.get(key)); } } catch (DocumentNotFoundException e) { //safe to continue, previously getDocumentInQueue could return // null and this was deemed safe and expected behaviour // DocumentNotFoundException is thrown instead of returning // null now. continue; } } } } catch (Exception e) { logger.log(Level.SEVERE, "There was a problem adding an " + "attachment to the datastore", e); throw e; } } if (ok) { logger.log(Level.FINER, "Inserted revision: %s", item.rev); if (documentCreated != null) { events.add(documentCreated); } else if (documentUpdated != null) { events.add(documentUpdated); } } } return null; } }).get(); // if we got here, everything got written to the database successfully // now raise any events we stored up for (DocumentModified event : events) { eventBus.post(event); } } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new DocumentException(e); } }
From source file:com.npower.dm.server.session.ManagementSessionHandler.java
/** * Starts a new management session, choosing the right managment processor. * * @param requestMessage the request/* www.j a v a2 s .c o m*/ * * @return the SyncML message to send back to the client containing the * management commands (if there is any) as obtained by the * management processor * * @throws ProtocolException in the case the message could not meet SyncML specs * @throws ManagementException if any other error occurs */ private SyncML startManagementSession(SyncML requestMessage, HttpServletRequest httpRequest) throws ProtocolException, ManagementException { // // If the client sent a MD5/HMAC Chal, store the server next nonce // storeServerNonce(ProtocolUtil.getStatusChal(requestMessage)); // Prameter name "sid" defined by Sync4jServlet String httpSessionId = httpRequest.getParameter("sid"); if (StringUtils.isEmpty(httpSessionId)) { httpSessionId = (String) httpRequest.getAttribute("sid"); } String dmSessionId = requestMessage.getSyncHdr().getSessionID().getSessionID(); // // Gets the processor selector and retrieve the processor to be used // for this management session // Configuration c = Configuration.getConfiguration(); // // Try to associate this session to an existing state (by session id or // device id). See the design document for details. // sessionState.dmstate = new DeviceDMState(sessionState.device.getDeviceId()); sessionState.dmstate.mssid = init.getSessionId(); if (!engine.resolveDMState(sessionState.dmstate, sessionState.device)) { // // This is new DM session for which the server has no information // sessionState.dmstate.id = null; // Fix bug#79 //sessionState.dmstate.mssid = init.getSessionId(); sessionState.dmstate.mssid = "0"; } // // If addAbsCmd is != null means that the processor already has been called. // Then cache contains the AbstractCommand to send // if (addAbsCmd == null) { ProcessorSelector selector = (ProcessorSelector) c.getBeanInstance(CFG_SERVER_DM_SELECTOR); processor = selector.getProcessor(sessionState.dmstate, init.getDevInfo(), init); if (processor == null) { throw new ManagementException("No management processor could be selected!"); } if (sessionState.dmstate.state == DeviceDMState.STATE_NOTIFIED) { // // Change the state to IN_PROGRESS // sessionState.dmstate.state = DeviceDMState.STATE_IN_PROGRESS; } } // // The alert could be issued in any of the initialization messages // Alert alert = init.getClientAlert(); if (alert != null) { sessionState.type = alert.getData(); } // // If addAbsCmd is != null means that the processor already has been called. // Then cache contains the AbstractCommand to send // if (addAbsCmd == null) { sessionState.dmstate.start = new Date(System.currentTimeMillis()); // // Perform session initialization // SessionContext context = new SessionContext(httpSessionId, dmSessionId, sessionState.loggedPrincipal, sessionState.type, init.getDevInfo(), sessionState.dmstate, sessionState.syncMLVerProto, init); processor.beginSession(context); // // Set Generic alerts // Alert[] genericAlerts = ProtocolUtil.searchGenericAlertCommands(requestMessage.getSyncBody()); if (genericAlerts != null || genericAlerts.length > 0) { if (log.isLoggable(Level.FINER)) { log.finer( "Start session calls setGenericAlert with " + genericAlerts.length + " generic alerts"); } processor.setGenericAlert(genericAlerts); } if (!init.isSessionAbortRequired()) { // // Get the next available operations // init.setManagementCommands(Util.managementOperations2commands(processor.getNextOperations(), engine.getCommandIdGenerator(), mimeType)); } } // re-set the request because the init put in the response a reference to the request (MsgRef) init.setRequest(requestMessage); if (requestMessage.getSyncBody().isFinalMsg()) { init.setFlag(Flags.FLAG_FINAL_MESSAGE); } else { init.unsetFlag(Flags.FLAG_FINAL_MESSAGE); } SyncML response = init.getResponse(msgIdGenerator.current()); // // Calculate size of response message // SyncHdr syncHdr = response.getSyncHdr(); SyncBody syncBody = response.getSyncBody(); long sizeSyncHdr = 0, sizeSyncBody = 0; /** * The test case suite currently send only ds mime type, then we must check * also MIMETYPE_SYNCMLDS_WBXML and MIMETYPE_SYNCMLDS_XML */ if (Constants.MIMETYPE_SYNCMLDM_WBXML.equals(mimeType) || Constants.MIMETYPE_SYNCMLDS_WBXML.equals(mimeType)) { sizeSyncHdr = SizeCalculator.getWBXMLSize(syncHdr); sizeSyncBody = SizeCalculator.getWBXMLSize(syncBody); } else if (Constants.MIMETYPE_SYNCMLDM_XML.equals(mimeType) || Constants.MIMETYPE_SYNCMLDS_XML.equals(mimeType)) { sizeSyncHdr = SizeCalculator.getXMLSize(syncHdr); sizeSyncBody = SizeCalculator.getXMLSize(syncBody); } if (log.isLoggable(Level.FINER)) { log.finer("maxMsgSize: " + sessionState.getMaxMsgSize()); log.finer("sizeSyncHdr: " + sizeSyncHdr); log.finer("sizeSyncBody: " + sizeSyncBody); } sessionState.setOverheadHdr(sizeSyncHdr); maxSizeAvailable = sessionState.getMaxMsgSize(); // // Check if the client MaxMsgSize is greater then the server // minmsgsize // checkMaxMsgSize(response); // // If the dimension of the response is < maxSizeAvailable or maxSizeAvailable is = 0 // and there aren't the status/alerts/cmds cached then returns the response. // Else caches the commands of the response and re-create it. // if ((maxSizeAvailable >= sizeSyncHdr + sizeSyncBody || maxSizeAvailable == 0) && sessionState.getStatusCmdOut().size() == 0 && sessionState.getAlertCmdOut().size() == 0 && sessionState.getCmdOut().size() == 0) { return response; } clearCache(); // // Cache the alert/status/commands to send in the next package // cacheCommands(response); // // The size of the answer is greater then the allowed MaxMsgSize // Calculate size of the single commands of the response. // Create one answer of the allowed dimension. // try { response = createNextMsg(response); } catch (Sync4jException e) { throw new ProtocolException(e); } return response; }