public static void handleServiceRemoved(List<Cartridge> cartridgeList) { Topology topology = TopologyManager.getTopology(); for (Cartridge cartridge : cartridgeList) { Service service = topology.getService(cartridge.getType()); if (service == null) { log.warn("Cartridge does not exist [cartidge] " + cartridge); return; } if (service.getClusters().size() == 0) { if (topology.serviceExists(cartridge.getType())) { try { TopologyManager.acquireWriteLock(); topology.removeService(cartridge.getType()); TopologyManager.updateTopology(topology); } finally { TopologyManager.releaseWriteLock(); } TopologyEventPublisher.sendServiceRemovedEvent(cartridgeList); } else { log.warn(String.format("Service %s does not exist..", cartridge.getType())); } } else { log.warn( "Subscription already exists. Hence not removing the service:" + cartridge.getType() + " from the topology"); } } }
private void jMenuItem22ActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jMenuItem22ActionPerformed // TODO add your handling code here: Service s = new Service(); s.setVisible(true); setVisible(false); } // GEN-LAST:event_jMenuItem22ActionPerformed
public static List<String> getServiceNames(Device d) { ArrayList<String> services = new ArrayList<>(); for (Service s : d.getServices()) { services.add(s.getServiceId().getId()); } return services; }
public static void handleClusterRemoved(ClusterContext ctxt) { Topology topology = TopologyManager.getTopology(); Service service = topology.getService(ctxt.getCartridgeType()); String deploymentPolicy; if (service == null) { log.warn(String.format("Service %s does not exist", ctxt.getCartridgeType())); return; } if (!service.clusterExists(ctxt.getClusterId())) { log.warn( String.format( "Cluster %s does not exist for service %s", ctxt.getClusterId(), ctxt.getCartridgeType())); return; } try { TopologyManager.acquireWriteLock(); Cluster cluster = service.removeCluster(ctxt.getClusterId()); deploymentPolicy = cluster.getDeploymentPolicyName(); TopologyManager.updateTopology(topology); } finally { TopologyManager.releaseWriteLock(); } TopologyEventPublisher.sendClusterRemovedEvent(ctxt, deploymentPolicy); }
public void update(UpdateMemo memo) throws Exception { ArtifactData target = put(memo.best.urls.iterator().next()); memo.current.version = new Version(memo.best.version); target.sync(); memo.current.sha = target.sha; // memo.current.dependencies = target.dependencies; // memo.current.dependencies.add((new File(repoDir, // Hex.toHexString(target.sha))).getCanonicalPath()); // memo.current.runbundles = target.runbundles; // memo.current.description = target.description; memo.current.time = target.time; if (memo.current instanceof ServiceData) { Service service = getService((ServiceData) memo.current); service.remove(); createService((ServiceData) memo.current); IO.delete(new File(IO.getFile(serviceDir, memo.current.name), "data")); storeData(new File(IO.getFile(serviceDir, memo.current.name), "data"), memo.current); } else { platform.deleteCommand(memo.current); createCommand(memo.current, false); IO.delete(IO.getFile(commandDir, memo.current.name)); storeData(IO.getFile(commandDir, memo.current.name), memo.current); } }
/** * This is called when JPM runs in the background to start jobs * * @throws Exception */ public void daemon() throws Exception { Runtime.getRuntime() .addShutdownHook( new Thread("Daemon shutdown") { public void run() { for (Service service : startedByDaemon) { try { reporter.error("Stopping " + service); service.stop(); reporter.error("Stopped " + service); } catch (Exception e) { // Ignore } } } }); List<ServiceData> services = getServices(); Map<String, ServiceData> map = new HashMap<String, ServiceData>(); for (ServiceData d : services) { map.put(d.name, d); } List<ServiceData> start = new ArrayList<ServiceData>(); Set<ServiceData> set = new HashSet<ServiceData>(); for (ServiceData sd : services) { checkStartup(map, start, sd, set); } if (start.isEmpty()) reporter.warning("No services to start"); for (ServiceData sd : start) { try { Service service = getService(sd.name); reporter.trace("Starting " + service); String result = service.start(); if (result != null) reporter.error("Started error " + result); else startedByDaemon.add(service); reporter.trace("Started " + service); } catch (Exception e) { reporter.error("Cannot start daemon %s, due to %s", sd.name, e); } } while (true) { for (Service sd : startedByDaemon) { try { if (!sd.isRunning()) { reporter.error("Starting due to failure " + sd); String result = sd.start(); if (result != null) reporter.error("Started error " + result); } } catch (Exception e) { reporter.error("Cannot start daemon %s, due to %s", sd, e); } } Thread.sleep(10000); } }
public static void handleClusterTerminatedEvent(ClusterStatusClusterTerminatedEvent event) { TopologyManager.acquireWriteLock(); try { Topology topology = TopologyManager.getTopology(); Service service = topology.getService(event.getServiceName()); // update the status of the cluster if (service == null) { log.warn(String.format("Service %s does not exist", event.getServiceName())); return; } Cluster cluster = service.getCluster(event.getClusterId()); if (cluster == null) { log.warn(String.format("Cluster %s does not exist", event.getClusterId())); return; } ClusterInstance context = cluster.getInstanceContexts(event.getInstanceId()); if (context == null) { log.warn( "Cluster Instance Context is not found for [cluster] " + event.getClusterId() + " [instance-id] " + event.getInstanceId()); return; } ClusterStatus status = ClusterStatus.Terminated; if (context.isStateTransitionValid(status)) { context.setStatus(status); log.info( "Cluster Terminated adding status started for and removing the cluster instance" + cluster.getClusterId()); cluster.removeInstanceContext(event.getInstanceId()); TopologyManager.updateTopology(topology); // publishing data ClusterInstanceTerminatedEvent clusterTerminatedEvent = new ClusterInstanceTerminatedEvent( event.getAppId(), event.getServiceName(), event.getClusterId(), event.getInstanceId()); TopologyEventPublisher.sendClusterTerminatedEvent(clusterTerminatedEvent); } else { log.error( String.format( "Cluster state transition is not valid: [cluster-id] %s " + " [instance-id] %s [current-status] %s [status-requested] %s", event.getClusterId(), event.getInstanceId(), context.getStatus(), status)); return; } } finally { TopologyManager.releaseWriteLock(); } }
public static void handleMemberMaintenance( InstanceMaintenanceModeEvent instanceMaintenanceModeEvent) throws InvalidMemberException, InvalidCartridgeTypeException { Topology topology = TopologyManager.getTopology(); Service service = topology.getService(instanceMaintenanceModeEvent.getServiceName()); // update the status of the member if (service == null) { log.warn( String.format( "Service %s does not exist", instanceMaintenanceModeEvent.getServiceName())); return; } Cluster cluster = service.getCluster(instanceMaintenanceModeEvent.getClusterId()); if (cluster == null) { log.warn( String.format("Cluster %s does not exist", instanceMaintenanceModeEvent.getClusterId())); return; } Member member = cluster.getMember(instanceMaintenanceModeEvent.getMemberId()); if (member == null) { log.warn( String.format("Member %s does not exist", instanceMaintenanceModeEvent.getMemberId())); return; } MemberMaintenanceModeEvent memberMaintenanceModeEvent = new MemberMaintenanceModeEvent( instanceMaintenanceModeEvent.getServiceName(), instanceMaintenanceModeEvent.getClusterId(), instanceMaintenanceModeEvent.getClusterInstanceId(), instanceMaintenanceModeEvent.getMemberId(), instanceMaintenanceModeEvent.getNetworkPartitionId(), instanceMaintenanceModeEvent.getPartitionId()); try { TopologyManager.acquireWriteLock(); // try update lifecycle state if (!member.isStateTransitionValid(MemberStatus.In_Maintenance)) { log.error( "Invalid State Transition from " + member.getStatus() + " to " + MemberStatus.In_Maintenance); return; } member.setStatus(MemberStatus.In_Maintenance); log.info("member maintenance mode event adding status started"); TopologyManager.updateTopology(topology); } finally { TopologyManager.releaseWriteLock(); } // publishing data TopologyEventPublisher.sendMemberMaintenanceModeEvent(memberMaintenanceModeEvent); }
public static void handleClusterInstanceCreated( String serviceType, String clusterId, String alias, String instanceId, String partitionId, String networkPartitionId) { TopologyManager.acquireWriteLock(); try { Topology topology = TopologyManager.getTopology(); Service service = topology.getService(serviceType); if (service == null) { log.error( "Service " + serviceType + " not found in Topology, unable to update the cluster status to Created"); return; } Cluster cluster = service.getCluster(clusterId); if (cluster == null) { log.error( "Cluster " + clusterId + " not found in Topology, unable to update " + "status to Created"); return; } if (cluster.getInstanceContexts(instanceId) != null) { log.warn( "The Instance context for the cluster already exists for [cluster] " + clusterId + " [instance-id] " + instanceId); return; } ClusterInstance clusterInstance = new ClusterInstance(alias, clusterId, instanceId); clusterInstance.setNetworkPartitionId(networkPartitionId); clusterInstance.setPartitionId(partitionId); cluster.addInstanceContext(instanceId, clusterInstance); TopologyManager.updateTopology(topology); ClusterInstanceCreatedEvent clusterInstanceCreatedEvent = new ClusterInstanceCreatedEvent(serviceType, clusterId, clusterInstance); clusterInstanceCreatedEvent.setPartitionId(partitionId); TopologyEventPublisher.sendClusterInstanceCreatedEvent(clusterInstanceCreatedEvent); } finally { TopologyManager.releaseWriteLock(); } }
public static void handleApplicationClustersCreated(String appId, List<Cluster> appClusters) { TopologyManager.acquireWriteLock(); try { Topology topology = TopologyManager.getTopology(); for (Cluster cluster : appClusters) { Service service = topology.getService(cluster.getServiceName()); if (service == null) { log.error( "Service " + cluster.getServiceName() + " not found in Topology, unable to create Application cluster"); } else { service.addCluster(cluster); log.info("Application Cluster " + cluster.getClusterId() + " created in CC topology"); } } TopologyManager.updateTopology(topology); } finally { TopologyManager.releaseWriteLock(); } log.debug("Creating cluster port mappings: [appication-id] " + appId); for (Cluster cluster : appClusters) { String cartridgeType = cluster.getServiceName(); Cartridge cartridge = CloudControllerContext.getInstance().getCartridge(cartridgeType); if (cartridge == null) { throw new CloudControllerException( "Cartridge not found: [cartridge-type] " + cartridgeType); } for (PortMapping portMapping : cartridge.getPortMappings()) { ClusterPortMapping clusterPortMapping = new ClusterPortMapping( appId, cluster.getClusterId(), portMapping.getName(), portMapping.getProtocol(), portMapping.getPort(), portMapping.getProxyPort()); if (portMapping.getKubernetesPortType() != null) { clusterPortMapping.setKubernetesServiceType(portMapping.getKubernetesPortType()); } CloudControllerContext.getInstance().addClusterPortMapping(clusterPortMapping); log.debug("Cluster port mapping created: " + clusterPortMapping.toString()); } } // Persist cluster port mappings CloudControllerContext.getInstance().persist(); // Send application clusters created event TopologyEventPublisher.sendApplicationClustersCreated(appId, appClusters); }
public static void handleApplicationClustersRemoved( String appId, Set<ClusterDataHolder> clusterData) { TopologyManager.acquireWriteLock(); List<Cluster> removedClusters = new ArrayList<Cluster>(); CloudControllerContext context = CloudControllerContext.getInstance(); try { Topology topology = TopologyManager.getTopology(); if (clusterData != null) { // remove clusters from CC topology model and remove runtime information for (ClusterDataHolder aClusterData : clusterData) { Service aService = topology.getService(aClusterData.getServiceType()); if (aService != null) { removedClusters.add(aService.removeCluster(aClusterData.getClusterId())); } else { log.warn( "Service " + aClusterData.getServiceType() + " not found, " + "unable to remove Cluster " + aClusterData.getClusterId()); } // remove runtime data context.removeClusterContext(aClusterData.getClusterId()); log.info( "Removed application [ " + appId + " ]'s Cluster " + "[ " + aClusterData.getClusterId() + " ] from the topology"); } // persist runtime data changes CloudControllerContext.getInstance().persist(); } else { log.info("No cluster data found for application " + appId + " to remove"); } TopologyManager.updateTopology(topology); } finally { TopologyManager.releaseWriteLock(); } // Remove cluster port mappings of application CloudControllerContext.getInstance().removeClusterPortMappings(appId); CloudControllerContext.getInstance().persist(); TopologyEventPublisher.sendApplicationClustersRemoved(appId, clusterData); }
/** * Prepare the Service JAXB object in order to build the XML response. * * @return A Service instance */ private Service getService() { Service s = new Service(); s.setName("WMS"); s.setTitle((String) properties.getProperty(WMSProperties.TITLE)); OnlineResource oR = new OnlineResource(); oR.setHref((String) properties.getProperty(WMSProperties.RESOURCE_URL)); oR.setTitle((String) properties.getProperty(WMSProperties.RESOURCE_NAME)); s.setOnlineResource(oR); ContactInformation cI = new ContactInformation(); cI.setContactElectronicMailAddress("*****@*****.**"); s.setContactInformation(cI); return s; }
protected void subscribeAll(Device d, String uuid) { String name = getFriendlyName(d); int ctrl = 0; for (Service s : d.getServices()) { String sid = s.getServiceId().getId(); LOGGER.debug("Subscribing to " + sid + " service on " + name); if (sid.contains("AVTransport")) { ctrl |= AVT; } else if (sid.contains("RenderingControl")) { ctrl |= RC; } upnpService.getControlPoint().execute(new SubscriptionCB(s)); } rendererMap.mark(uuid, RENEW, false); rendererMap.mark(uuid, CONTROLS, ctrl); }
@Test public void shouldSearchExistingFlwsAndUpdateFlw() { Flw toBeUpdatedFlw = flw( "5ba9a0928dde95d187544babf6c0ad24", "FirstName1", flwGroupWithNameAndId("64a9a0928dde95d187544babf6c0ad38", "oldGroupName")); Flw notToBeUpdateFlw = flw("5ba9a0928dde95d187544babf6c0ad25", "FirstName2", new FlwGroup()); template.saveOrUpdateAll(Arrays.asList(toBeUpdatedFlw, notToBeUpdateFlw)); Flw newFlw = flw( "5ba9a0928dde95d187544babf6c0ad24", "FirstName3", flwGroupWithNameAndId("38a9a0928dde95d187544babf6c0ad64", "newGroupName")); ArrayList<Flw> flwsToUpdate = new ArrayList<>(); flwsToUpdate.add(newFlw); careService.saveOrUpdateAllByExternalPrimaryKey(Flw.class, flwsToUpdate); Flw updatedFlw = template.load(Flw.class, toBeUpdatedFlw.getId()); assertReflectionEqualsWithIgnore( newFlw, updatedFlw, new String[] {"id", "creationTime", "lastModifiedTime"}); assertDateIgnoringSeconds(new Date(), updatedFlw.getCreationTime()); assertDateIgnoringSeconds(new Date(), updatedFlw.getLastModifiedTime()); Flw unchangedFlw = template.load(Flw.class, notToBeUpdateFlw.getId()); assertEquals("FirstName2", unchangedFlw.getFirstName()); }
@Test public void shouldDeleteEarlierFormIfBothNewerAndOlderMotherFormWithSameInstanceIdHasNullDate() { NewForm persistedForm = new NewForm(); persistedForm.setInstanceId("e34707f8-80c8-4198-bf99-c11c90ba5c98"); persistedForm.setCaste("OldCaste"); persistedForm.setServerDateModified(null); template.save(persistedForm); final String newCaste = "NewCaste"; Map<String, String> motherFormValues = new HashMap<String, String>() { { put("caseId", "94d5374f-290e-409f-bc57-86c2e4bcc43f"); put("serverDateModified", null); put("userId", "89fda0284e008d2e0c980fb13fa0e5bb"); put("xmlns", "http://bihar.commcarehq.org/pregnancy/new"); put("instanceId", "e34707f8-80c8-4198-bf99-c11c90ba5c98"); put("caste", newCaste); } }; careService.processAndSaveForms(motherFormValues, new ArrayList<Map<String, String>>()); List<NewForm> newFormsFromDb = template.loadAll(NewForm.class); assertEquals(1, newFormsFromDb.size()); assertNull(newFormsFromDb.get(0).getDateModified()); assertEquals(newCaste, newFormsFromDb.get(0).getCaste()); }
@Test public void shouldNotDeleteEarlierFormIfNewerMotherFormWithSameInstanceIdHasOldDate() { NewForm persistedForm = new NewForm(); persistedForm.setInstanceId("e34707f8-80c8-4198-bf99-c11c90ba5c98"); final Date oldFormModifiedDate = DateTime.parse("2012-07-20T12:02:59.923+05:30").toDate(); persistedForm.setServerDateModified(oldFormModifiedDate); persistedForm.setDateModified(oldFormModifiedDate); template.save(persistedForm); final String newFormModifiedOn = "2012-07-10T12:02:59.923+05:30"; Map<String, String> motherFormValues = new HashMap<String, String>() { { put("caseId", "94d5374f-290e-409f-bc57-86c2e4bcc43f"); put("dateModified", newFormModifiedOn); put("serverDateModified", newFormModifiedOn); put("userId", "89fda0284e008d2e0c980fb13fa0e5bb"); put("xmlns", "http://bihar.commcarehq.org/pregnancy/new"); put("instanceId", "e34707f8-80c8-4198-bf99-c11c90ba5c98"); } }; careService.processAndSaveForms(motherFormValues, new ArrayList<Map<String, String>>()); List<NewForm> newFormsFromDb = template.loadAll(NewForm.class); assertEquals(1, newFormsFromDb.size()); assertEquals(oldFormModifiedDate, newFormsFromDb.get(0).getDateModified()); }
@Test public void shouldUpdateEntityByExternalPrimaryKeyWhenExists() { String caseId = "94d5374f-290e-409f-bc57-86c2e4bcc43f"; ChildCase existingChild = new ChildCase(); existingChild.setCaseId(caseId); existingChild.setName("old Child name"); template.save(existingChild); HashMap<String, String> updatedValues = new HashMap<String, String>() { { put("caseId", "94d5374f-290e-409f-bc57-86c2e4bcc43f"); put("name", "new child name"); } }; careService.saveByExternalPrimaryKey(ChildCase.class, updatedValues); List<ChildCase> childCases = template.loadAll(ChildCase.class); Assert.assertEquals(1, childCases.size()); ChildCase expectedChildCase = new ChildCase(); expectedChildCase.setCaseId(caseId); expectedChildCase.setName("new child name"); assertReflectionEqualsWithIgnore( expectedChildCase, childCases.get(0), new String[] {"id", "creationTime", "lastModifiedTime"}); }
@Test public void shouldSearchForExistingGroupBeforeUpdating() throws Exception { FlwGroup toBeUpdatedGroup = new FlwGroupBuilder() .groupId("5ba9a0928dde95d187544babf6c0ad24") .name("afrisis team 1") .domain("care-bihar") .awcCode("001") .caseSharing(true) .reporting(true) .build(); FlwGroup notToBeUpdatedGroup = flwGroupWithNameAndId("5ba9a0928dde95d187544babf6c0af36", "ashok team 1"); template.saveOrUpdateAll(Arrays.asList(toBeUpdatedGroup, notToBeUpdatedGroup)); FlwGroup updatedGroup = updatedGroup(); careService.saveOrUpdateAllByExternalPrimaryKey(FlwGroup.class, Arrays.asList(updatedGroup)); FlwGroup loadedFlwGroup = template.load(FlwGroup.class, toBeUpdatedGroup.getId()); FlwGroup unchangedFlwGroup = template.load(FlwGroup.class, notToBeUpdatedGroup.getId()); assertReflectionEqualsWithIgnore( updatedGroup(), loadedFlwGroup, new String[] {"id", "creationTime", "lastModifiedTime"}); assertDateIgnoringSeconds(new Date(), loadedFlwGroup.getCreationTime()); assertDateIgnoringSeconds(new Date(), loadedFlwGroup.getLastModifiedTime()); assertEquals("ashok team 1", unchangedFlwGroup.getName()); }
@Test public void shouldSaveChildForm() { ArrayList<Map<String, String>> childFormValues = new ArrayList<>(); HashMap<String, String> childFormValue = new HashMap<>(); childFormValue.put("caseId", "94d5374f-290e-409f-bc57-86c2e4bcc43f"); childFormValue.put("xmlns", "http://bihar.commcarehq.org/pregnancy/registration"); childFormValue.put("childName", "suraj"); childFormValue.put("birthStatus", "healthy"); childFormValue.put("instanceId", "ff2eb090-03a9-4f23-afed-cf6012784c55"); childFormValue.put("flw", "89fda0284e008d2e0c980fb13fa0e5bb"); childFormValue.put("timeStart", "2013-03-03T10:31:51.045+05:30"); childFormValue.put("timeEnd", "2013-03-03T10:38:52.804+05:30"); childFormValue.put("dateModified", "2013-03-03T10:38:52.804+05:30"); childFormValues.add(childFormValue); careService.processAndSaveForms(null, childFormValues); List<RegistrationChildForm> registrationChildForms = template.loadAll(RegistrationChildForm.class); assertEquals(1, registrationChildForms.size()); RegistrationChildForm expectedForm = getExpectedForm("94d5374f-290e-409f-bc57-86c2e4bcc43f"); assertReflectionEqualsWithIgnore( expectedForm, registrationChildForms.get(0), new String[] {"id", "flw", "childCase", "creationTime", "lastModifiedTime"}); List<Flw> flws = template.loadAll(Flw.class); assertEquals(1, flws.size()); assertEquals("89fda0284e008d2e0c980fb13fa0e5bb", flws.get(0).getFlwId()); }
/** * Remove member from topology and send member terminated event. * * @param serviceName * @param clusterId * @param networkPartitionId * @param partitionId * @param memberId */ public static void handleMemberTerminated( String serviceName, String clusterId, String networkPartitionId, String partitionId, String memberId) { Topology topology = TopologyManager.getTopology(); Service service = topology.getService(serviceName); Properties properties; if (service == null) { log.warn(String.format("Service %s does not exist", serviceName)); return; } Cluster cluster = service.getCluster(clusterId); if (cluster == null) { log.warn(String.format("Cluster %s does not exist", clusterId)); return; } Member member = cluster.getMember(memberId); if (member == null) { log.warn(String.format("Member %s does not exist", memberId)); return; } String clusterInstanceId = member.getClusterInstanceId(); try { TopologyManager.acquireWriteLock(); properties = member.getProperties(); cluster.removeMember(member); TopologyManager.updateTopology(topology); } finally { TopologyManager.releaseWriteLock(); } /* @TODO leftover from grouping_poc*/ String groupAlias = null; TopologyEventPublisher.sendMemberTerminatedEvent( serviceName, clusterId, memberId, clusterInstanceId, networkPartitionId, partitionId, properties, groupAlias); }
private List<Service> parseServices(Element el, Node parent) { if (el == null) { return Collections.EMPTY_LIST; } List<Element> nodes = el.elements(); List<Service> services = new ArrayList<Service>(nodes.size()); for (Element node : nodes) { Service service = new Service(); service.setName(node.attributeValue("name")); service.setParent(parent); parseDoc(node, service); service.setMethods(parseMethods(node.elements("method"), service)); services.add(service); } Collections.sort(services); return services; }
// Convenience functions for sending various upnp service requests public static ActionInvocation send( final Device dev, String instanceID, String service, String action, String... args) { Service svc = dev.findService(ServiceId.valueOf("urn:upnp-org:serviceId:" + service)); final String uuid = getUUID(dev); if (svc != null) { Action x = svc.getAction(action); String name = getFriendlyName(dev); boolean log = !action.equals("GetPositionInfo"); if (x != null) { ActionInvocation a = new ActionInvocation(x); a.setInput("InstanceID", instanceID); for (int i = 0; i < args.length; i += 2) { a.setInput(args[i], args[i + 1]); } if (log) { LOGGER.debug("Sending upnp {}.{} {} to {}[{}]", service, action, args, name, instanceID); } new ActionCallback(a, upnpService.getControlPoint()) { @Override public void success(ActionInvocation invocation) { rendererMap.mark(uuid, ACTIVE, true); } @Override public void failure( ActionInvocation invocation, UpnpResponse operation, String defaultMsg) { LOGGER.debug("Action failed: {}", defaultMsg); rendererMap.mark(uuid, ACTIVE, false); } }.run(); if (log) { for (ActionArgumentValue arg : a.getOutput()) { LOGGER.debug( "Received from {}[{}]: {}={}", name, instanceID, arg.getArgument().getName(), arg.toString()); } } return a; } } return null; }
/** Loads internal services */ private void loadInternalServices() { try { Iterator services; String servicename; String baseURL = System.getProperty("user.dir") + "/" + APPLICATIONS_DIRECTORY; LucaneClassLoader loader = LucaneClassLoader.getInstance(); services = store.getServiceStore().getAllServices(); while (services.hasNext()) { ServiceConcept service = (ServiceConcept) services.next(); servicename = service.getName(); try { loader.addUrl(new URL("jar:file:///" + baseURL + servicename + ".jar!/")); String className = (new JarFile(baseURL + servicename + ".jar")) .getManifest() .getMainAttributes() .getValue("Service-Class"); if (className == null) continue; Service serv = (Service) Class.forName(className, true, loader).newInstance(); this.services.add(serv); serv.init(this); if (!service.isInstalled()) { serv.install(); service.setInstalled(); store.getServiceStore().updateService(service); } Logging.getLogger().info("Service '" + servicename + "' loaded."); this.connections.add( new ConnectInfo(servicename, serverIp, serverIp, port, "nokey", "service")); } catch (Exception e) { Logging.getLogger().warning("Unable to load service '" + servicename); } } } catch (Exception e) { Logging.getLogger().warning("Unable to load internal services : " + e); e.printStackTrace(); } }
@Test public void shouldNotSaveMotherOrChildFormsIfNullAndEmpty() { careService.processAndSaveForms(null, new ArrayList<Map<String, String>>()); List<MotherCase> mothers = template.loadAll(MotherCase.class); assertTrue(mothers.isEmpty()); List<ChildCase> children = template.loadAll(ChildCase.class); assertTrue(children.isEmpty()); }
private String listFiles(final File cache, List<File> toDelete) throws Exception { boolean stopServices = false; if (toDelete == null) { toDelete = new ArrayList<File>(); } else { stopServices = true; } int count = 0; Formatter f = new Formatter(); f.format(" - Cache:%n * %s%n", cache.getCanonicalPath()); f.format(" - Commands:%n"); for (CommandData cdata : getCommands(new File(cache, COMMANDS))) { f.format(" * %s \t0 handle for \"%s\"%n", cdata.bin, cdata.name); toDelete.add(new File(cdata.bin)); count++; } f.format(" - Services:%n"); for (ServiceData sdata : getServices(new File(cache, SERVICE))) { if (sdata != null) { f.format(" * %s \t0 service directory for \"%s\"%n", sdata.sdir, sdata.name); toDelete.add(new File(sdata.sdir)); File initd = platform.getInitd(sdata); if (initd != null && initd.exists()) { f.format(" * %s \t0 init.d file for \"%s\"%n", initd.getCanonicalPath(), sdata.name); toDelete.add(initd); } if (stopServices) { Service s = getService(sdata); try { s.stop(); } catch (Exception e) { } } count++; } } f.format("%n"); String result = (count > 0) ? f.toString() : null; f.close(); return result; }
/** * Add member object to the topology and publish member created event * * @param memberContext */ public static void handleMemberCreatedEvent(MemberContext memberContext) { Topology topology = TopologyManager.getTopology(); Service service = topology.getService(memberContext.getCartridgeType()); String clusterId = memberContext.getClusterId(); Cluster cluster = service.getCluster(clusterId); String memberId = memberContext.getMemberId(); String clusterInstanceId = memberContext.getClusterInstanceId(); String networkPartitionId = memberContext.getNetworkPartitionId(); String partitionId = memberContext.getPartition().getId(); String lbClusterId = memberContext.getLbClusterId(); long initTime = memberContext.getInitTime(); if (cluster.memberExists(memberId)) { log.warn(String.format("Member %s already exists", memberId)); return; } try { TopologyManager.acquireWriteLock(); Member member = new Member( service.getServiceName(), clusterId, memberId, clusterInstanceId, networkPartitionId, partitionId, memberContext.getLoadBalancingIPType(), initTime); member.setStatus(MemberStatus.Created); member.setLbClusterId(lbClusterId); member.setProperties(CloudControllerUtil.toJavaUtilProperties(memberContext.getProperties())); cluster.addMember(member); TopologyManager.updateTopology(topology); } finally { TopologyManager.releaseWriteLock(); } TopologyEventPublisher.sendMemberCreatedEvent(memberContext); }
@Test public void shouldSaveFlwOnceForMotherAndChild() { final String flwId = "89fda0284e008d2e0c980fb13fa0e5bb"; Flw flw = new FlwBuilder().flwId(flwId).build(); final String instanceId = "e34707f8-80c8-4198-bf99-c11c90ba5c98"; HashMap<String, String> motherCase = new HashMap<String, String>() { { put("caseId", "3e8998ce-b19f-4fa7-b1a1-721b6951e3cf"); put("userId", flwId); put("flw", flwId); put("instanceId", instanceId); put("xmlns", "http://bihar.commcarehq.org/pregnancy/registration"); } }; final HashMap<String, String> child1 = new HashMap<String, String>() { { put("caseId", "3e8998ce-b19f-4fa7-b1a1-721b6951e3c1"); put("userId", flwId); put("flw", flwId); put("instanceId", instanceId); put("xmlns", "http://bihar.commcarehq.org/pregnancy/registration"); } }; final HashMap<String, String> child2 = new HashMap<String, String>() { { put("caseId", "3e8998ce-b19f-4fa7-b1a1-721b6951e3c2"); put("userId", flwId); put("flw", flwId); put("instanceId", instanceId); put("xmlns", "http://bihar.commcarehq.org/pregnancy/registration"); } }; careService.processAndSaveForms( motherCase, new ArrayList<Map<String, String>>() { { add(child1); add(child2); } }); List<Flw> actualFlws = template.loadAll(Flw.class); assertEquals(1, actualFlws.size()); assertReflectionEqualsWithIgnore( flw, actualFlws.get(0), new String[] {"id", "creationTime", "lastModifiedTime"}); }
@Test public void shouldNotThrowExceptionIfXmlnsNotRecognized() { Map<String, String> motherFormValuesWithoutXmlns = motherFormValues( "94d5374f-290e-409f-bc57-86c2e4bcc43f", "89fda0284e008d2e0c980fb13fa0e5bb"); motherFormValuesWithoutXmlns.put("xmlns", "randomurl"); try { careService.processAndSaveForms( motherFormValuesWithoutXmlns, new ArrayList<Map<String, String>>()); } catch (Exception e) { fail("The exception should not have been thrown: " + e.getMessage()); } }
@Test public void shouldCreateNewFlw() { Flw newFlw = flw( "5ba9a0928dde95d187544babf6c0ad24", "FirstName1", flwGroupWithNameAndId("64a9a0928dde95d187544babf6c0ad38", "oldGroupName")); careService.saveOrUpdateAllByExternalPrimaryKey(Flw.class, Arrays.asList(newFlw)); List<Flw> flwsFromDb = template.loadAll(Flw.class); assertEquals(1, flwsFromDb.size()); assertReflectionContains(newFlw, flwsFromDb, new String[] {"id"}); }
@Test public void shouldSaveNewGroup() throws Exception { FlwGroup newGroup = new FlwGroupBuilder() .groupId("5ba9a0928dde95d187544babf6c0ad24") .name("amir team 1") .domain("care-mp") .awcCode("007") .caseSharing(true) .reporting(true) .build(); careService.saveOrUpdateAllByExternalPrimaryKey(FlwGroup.class, Arrays.asList(newGroup)); List<FlwGroup> flwGroupsFromDb = template.loadAll(FlwGroup.class); assertEquals(1, flwGroupsFromDb.size()); assertReflectionContains(newGroup, flwGroupsFromDb, new String[] {"id"}); }