conflict_resolution
stringlengths
27
16k
<<<<<<< // requestHandleWithGoodInputTest() helpers ======= /** * Creates a {@link HttpRequest} with the given parameters. * @param httpMethod the {@link HttpMethod} required. * @param uri the URI to hit. * @return a {@link HttpRequest} with the given parameters. */ private HttpRequest createRequest(HttpMethod httpMethod, String uri) { HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri); // keep-alive by default but set it for readability HttpHeaders.setKeepAlive(request, true); return request; } /** * Converts the content in {@code httpContent} to a human readable string. * @param httpContent the {@link HttpContent} whose content needs to be converted to a human readable string. * @return content that is inside {@code httpContent} as a human readable string. * @throws IOException */ private String getContentString(HttpContent httpContent) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); httpContent.content().readBytes(out, httpContent.content().readableBytes()); return out.toString("UTF-8"); } >>>>>>> <<<<<<< EmbeddedChannel channel = createChannel(); channel.writeInbound(RestTestUtils.createRequest(httpMethod, MockBlobStorageService.ECHO_REST_METHOD, null)); if (httpMethod != HttpMethod.POST) { ======= long requestId = requestIdGenerator.getAndIncrement(); String uri = MockBlobStorageService.ECHO_REST_METHOD + requestId; HttpRequest httpRequest = createRequest(httpMethod, uri); HttpHeaders.setKeepAlive(httpRequest, isKeepAlive); channel.writeInbound(httpRequest); if (!restMethod.equals(RestMethod.POST)) { >>>>>>> long requestId = requestIdGenerator.getAndIncrement(); String uri = MockBlobStorageService.ECHO_REST_METHOD + requestId; HttpRequest httpRequest = RestTestUtils.createRequest(httpMethod, uri, null); HttpHeaders.setKeepAlive(httpRequest, isKeepAlive); channel.writeInbound(httpRequest); if (!restMethod.equals(RestMethod.POST)) { <<<<<<< // MockBlobStorageService echoes the RestMethod. assertEquals("Unexpected content", restMethod.toString(), RestTestUtils.getContentString((HttpContent) channel.readOutbound())); ======= // MockBlobStorageService echoes the RestMethod + request id. String expectedResponse = restMethod.toString() + requestId; assertEquals("Unexpected content", expectedResponse, getContentString((HttpContent) channel.readOutbound())); assertTrue("End marker was expected", channel.readOutbound() instanceof LastHttpContent); } // requestHandleWithGoodInputTest() helpers /** * Does a test to see that request handling with good input succeeds when channel is not keep alive. * @param httpMethod the {@link HttpMethod} for the request. * @param restMethod the equivalent {@link RestMethod} for {@code httpMethod}. Used to check for correctness of * response. * @throws IOException */ private void doRequestHandleWithoutKeepAlive(HttpMethod httpMethod, RestMethod restMethod) throws IOException { EmbeddedChannel channel = createChannel(); sendRequestCheckResponse(channel, httpMethod, restMethod, false); >>>>>>> // MockBlobStorageService echoes the RestMethod + request id. String expectedResponse = restMethod.toString() + requestId; assertEquals("Unexpected content", expectedResponse, RestTestUtils.getContentString((HttpContent) channel.readOutbound())); assertTrue("End marker was expected", channel.readOutbound() instanceof LastHttpContent); } // requestHandleWithGoodInputTest() helpers /** * Does a test to see that request handling with good input succeeds when channel is not keep alive. * @param httpMethod the {@link HttpMethod} for the request. * @param restMethod the equivalent {@link RestMethod} for {@code httpMethod}. Used to check for correctness of * response. * @throws IOException */ private void doRequestHandleWithoutKeepAlive(HttpMethod httpMethod, RestMethod restMethod) throws IOException { EmbeddedChannel channel = createChannel(); sendRequestCheckResponse(channel, httpMethod, restMethod, false);
<<<<<<< allArgsReadOnly = Collections.unmodifiableMap(allArgs); ======= // add cookies to the args as java cookies if (nettyCookies != null) { Set<javax.servlet.http.Cookie> cookies = convertHttpToJavaCookies(nettyCookies); allArgs.put(RestUtils.Headers.COOKIE, cookies); } args = Collections.unmodifiableMap(allArgs); >>>>>>> // add cookies to the args as java cookies if (nettyCookies != null) { Set<javax.servlet.http.Cookie> cookies = convertHttpToJavaCookies(nettyCookies); allArgs.put(RestUtils.Headers.COOKIE, cookies); } allArgsReadOnly = Collections.unmodifiableMap(allArgs);
<<<<<<< import com.github.ambry.shared.PartitionRequestInfo; import com.github.ambry.shared.PartitionResponseInfo; import com.github.ambry.shared.ReplicaMetadataRequestInfo; import com.github.ambry.shared.ReplicaMetadataResponseInfo; import com.github.ambry.shared.RequestOrResponseType; ======= >>>>>>> <<<<<<< import com.github.ambry.shared.PutRequest; import com.github.ambry.shared.PutResponse; import com.github.ambry.network.Request; ======= >>>>>>>
<<<<<<< import com.codahale.metrics.MetricRegistry; import com.github.ambry.commons.BlobId; import com.github.ambry.commons.ServerErrorCode; ======= >>>>>>> import com.codahale.metrics.MetricRegistry; <<<<<<< import com.github.ambry.config.ConnectionPoolConfig; import com.github.ambry.config.SSLConfig; ======= import com.github.ambry.commons.BlobId; import com.github.ambry.commons.ServerErrorCode; >>>>>>> import com.github.ambry.commons.BlobId; import com.github.ambry.commons.ServerErrorCode; import com.github.ambry.config.ConnectionPoolConfig; import com.github.ambry.config.SSLConfig; <<<<<<< ======= import com.github.ambry.store.PersistentIndex; import com.github.ambry.store.StoreException; import com.github.ambry.store.StoreKey; >>>>>>> import com.github.ambry.store.PersistentIndex; import com.github.ambry.store.StoreKey; <<<<<<< throws IOException, InstantiationException, URISyntaxException, GeneralSecurityException { sslCluster.startServers(); ======= throws IOException, InstantiationException { // do nothing cluster = new MockCluster(notificationSystem, false, "", "", "", SystemTime.getInstance()); >>>>>>> throws IOException, InstantiationException, URISyntaxException, GeneralSecurityException { sslCluster.startServers(); <<<<<<< sslCluster = new MockCluster(notificationSystem, true, "DC1,DC2,DC3", serverSSLProps, true); sslCluster.startServers(); MockClusterMap clusterMap = sslCluster.getClusterMap(); DataNodeId dataNodeId = clusterMap.getDataNodeIds().get(0); ======= MockTime time = new MockTime(SystemTime.getInstance().milliseconds()); cluster = new MockCluster(notificationSystem, true, "", "", "", time); MockClusterMap clusterMap = cluster.getClusterMap(); >>>>>>> MockTime time = new MockTime(SystemTime.getInstance().milliseconds()); sslCluster = new MockCluster(notificationSystem, true, "DC1,DC2,DC3", serverSSLProps, true, time); sslCluster.startServers(); MockClusterMap clusterMap = sslCluster.getClusterMap(); DataNodeId dataNodeId = clusterMap.getDataNodeIds().get(0); <<<<<<< // interestedDataNodePortNumber is used to locate the datanode and hence has to be PlainText port ======= // sourceNode is used to locate the datanode and hence has to be PlainText port cluster = new MockCluster(notificationSystem, enableSSLPorts, sslEnabledDatacentersForDC1, sslEnabledDatacentersForDC2, sslEnabledDatacentersForDC3, SystemTime.getInstance()); >>>>>>> // interestedDataNodePortNumber is used to locate the datanode and hence has to be PlainText port <<<<<<< // interestedDataNodePortNumber is used to locate the datanode and hence has to be PlainTextPort ======= // sourceNode is used to locate the datanode and hence has to be PlainTextPort cluster = new MockCluster(notificationSystem, enableSSLPorts, sslEnabledDatacentersForDC1, sslEnabledDatacentersForDC2, sslEnabledDatacentersForDC3, SystemTime.getInstance()); >>>>>>> // interestedDataNodePortNumber is used to locate the datanode and hence has to be PlainTextPort <<<<<<< private void endToEndReplicationWithMultiNodeMultiPartitionMultiDCTest(String sourceDatacenter, PortType portType, MockCluster cluster) throws Exception { ======= private void endToEndReplicationWithMultiNodeMultiPartitionMultiDCTest(String sourceDatacenter, boolean enableSSLPorts, String sslEnabledDatacenter1, String sslEnabledDatacenter2, String sslEnabledDatacenter3) throws InterruptedException, IOException, InstantiationException { cluster = new MockCluster(notificationSystem, enableSSLPorts, sslEnabledDatacenter1, sslEnabledDatacenter2, sslEnabledDatacenter3, SystemTime.getInstance()); >>>>>>> private void endToEndReplicationWithMultiNodeMultiPartitionMultiDCTest(String sourceDatacenter, PortType portType, MockCluster cluster) throws Exception {
<<<<<<< import com.github.ambry.router.AsyncWritableChannel; import com.github.ambry.router.Callback; ======= import com.github.ambry.rest.RestUtilsTest; >>>>>>> import com.github.ambry.rest.RestUtilsTest; import com.github.ambry.router.AsyncWritableChannel; import com.github.ambry.router.Callback;
<<<<<<< ModEntities.initMobs(); if (Config.genJSON) { ModRecipes x = new ModRecipes(); } ======= ModSpawns.addSpawns(); >>>>>>> ModEntities.initMobs();
<<<<<<< final View view = getView(viewId); if (view!=null){ view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (adapter.getOnItemChildClickListener() != null) { adapter.getOnItemChildClickListener().onItemChildClick(adapter, view, getClickPosition()); } } }); } ======= View view = getView(viewId); if (!view.isClickable()) { view.setClickable(true); } >>>>>>> View view = getView(viewId); if (!view.isClickable()) { view.setClickable(true); } final View view = getView(viewId); if (view!=null){ view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (adapter.getOnItemChildClickListener() != null) { adapter.getOnItemChildClickListener().onItemChildClick(adapter, view, getClickPosition()); } } }); } <<<<<<< final View view = getView(viewId); if (view!=null){ view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (adapter.getmOnItemChildLongClickListener() != null) { adapter.getmOnItemChildLongClickListener().onItemChildLongClick(adapter, view, getClickPosition()); } return false; } }); } ======= View view = getView(viewId); if (!view.isLongClickable()) { view.setLongClickable(true); } >>>>>>> final View view = getView(viewId); if (view!=null){ view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (adapter.getmOnItemChildLongClickListener() != null) { adapter.getmOnItemChildLongClickListener().onItemChildLongClick(adapter, view, getClickPosition()); } return false; } }); } View view = getView(viewId); if (!view.isLongClickable()) { view.setLongClickable(true); }
<<<<<<< if (promise != null) { promise.reject("Failed to authenticate", "Data intent is null" ); } ======= promise.reject("authentication_error", "Data intent is null" ); >>>>>>> if (promise != null) { promise.reject("authentication_error", "Data intent is null" ); } <<<<<<< if (promise != null) { promise.reject("Failed to authenticate", getErrorMessage(exception)); } ======= promise.reject("authentication_error", getErrorMessage(exception)); >>>>>>> if (promise != null) { promise.reject("authentication_error", getErrorMessage(exception)); } <<<<<<< if (promise != null) { promise.reject("Failed exchange token", getErrorMessage(ex)); } ======= promise.reject("token_exchange_failed", getErrorMessage(ex)); >>>>>>> if (promise != null) { promise.reject("token_exchange_failed", getErrorMessage(ex)); }
<<<<<<< final String response = createResource("whois/geolocation?source=test&ipkey=10.0.0.0") .request(MediaType.APPLICATION_XML) ======= final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .accept(MediaType.APPLICATION_XML) >>>>>>> final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .request(MediaType.APPLICATION_XML) <<<<<<< final String response = createResource("whois/geolocation?source=test&ipkey=10.0.0.0") .request(MediaType.APPLICATION_XML) ======= final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .accept(MediaType.APPLICATION_XML) >>>>>>> final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .request(MediaType.APPLICATION_XML) <<<<<<< final String response = createResource("whois/geolocation?source=test&ipkey=10.0.0.0") .request(MediaType.APPLICATION_JSON) ======= final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .accept(MediaType.APPLICATION_JSON) >>>>>>> final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .request(MediaType.APPLICATION_JSON) <<<<<<< createResource("whois/geolocation?source=test&ipkey=10.0.0.0") .request(MediaType.APPLICATION_XML) ======= createResource("whois/geolocation?ipkey=10.0.0.0") .accept(MediaType.APPLICATION_XML) >>>>>>> createResource("whois/geolocation?ipkey=10.0.0.0") .request(MediaType.APPLICATION_XML) <<<<<<< createResource("whois/geolocation?source=test&ipkey=127.0.0.1") .request(MediaType.APPLICATION_XML) ======= createResource("whois/geolocation?ipkey=127.0.0.1") .accept(MediaType.APPLICATION_XML) >>>>>>> createResource("whois/geolocation?ipkey=127.0.0.1") .request(MediaType.APPLICATION_XML) <<<<<<< final String response = createResource("whois/geolocation?source=test&ipkey=10.0.0.0") .request(MediaType.APPLICATION_XML) ======= final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .accept(MediaType.APPLICATION_XML) >>>>>>> final String response = createResource("whois/geolocation?ipkey=10.0.0.0") .request(MediaType.APPLICATION_XML) <<<<<<< final String response = createResource("whois/geolocation?source=test&ipkey=10.1.0.0%20-%2010.1.255.255") .request(MediaType.APPLICATION_XML) ======= final String response = createResource("whois/geolocation?ipkey=10.1.0.0%20-%2010.1.255.255") .accept(MediaType.APPLICATION_XML) >>>>>>> final String response = createResource("whois/geolocation?ipkey=10.1.0.0%20-%2010.1.255.255") .request(MediaType.APPLICATION_XML) <<<<<<< final String response = createResource("whois/geolocation?source=test&ipkey=2001::/20") .request(MediaType.APPLICATION_XML) ======= final String response = createResource("whois/geolocation?ipkey=2001::/20") .accept(MediaType.APPLICATION_XML) >>>>>>> final String response = createResource("whois/geolocation?ipkey=2001::/20") .request(MediaType.APPLICATION_XML) <<<<<<< createResource("whois/geolocation?source=test&ipkey=invalid") .request(MediaType.APPLICATION_XML) ======= createResource("whois/geolocation?ipkey=invalid") .accept(MediaType.APPLICATION_XML) >>>>>>> createResource("whois/geolocation?ipkey=invalid") .request(MediaType.APPLICATION_XML) <<<<<<< protected WebTarget createResource(final String path) { return client.target(String.format("http://localhost:%s/%s", getPort(Audience.PUBLIC), path)); ======= @Test public void geolocation_without_query_params() throws Exception { try { createResource("whois/geolocation") .get(String.class); fail(); } catch (UniformInterfaceException e) { assertThat(e.getResponse().getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); assertThat(e.getResponse().getEntity(String.class), is("ipkey is required")); } } protected WebResource createResource(final String path) { return client.resource(String.format("http://localhost:%s/%s", getPort(Audience.PUBLIC), path)); >>>>>>> @Test public void geolocation_without_query_params() throws Exception { try { createResource("whois/geolocation") .request(MediaType.APPLICATION_XML) .get(String.class); fail(); } catch (BadRequestException e) { assertThat(e.getResponse().readEntity(String.class), is("ipkey is required")); } } protected WebTarget createResource(final String path) { return client.target(String.format("http://localhost:%s/%s", getPort(Audience.PUBLIC), path));
<<<<<<< import com.mp4parser.authoring.Movie; import com.mp4parser.authoring.builder.DefaultMp4Builder; import com.mp4parser.authoring.tracks.SMPTETTTrackImpl; ======= import com.googlecode.mp4parser.authoring.Movie; import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder; import com.googlecode.mp4parser.authoring.tracks.ttml.TtmlTrackImpl; import org.w3c.dom.Document; >>>>>>> import com.mp4parser.authoring.Movie; import com.mp4parser.authoring.builder.DefaultMp4Builder; import com.mp4parser.authoring.tracks.SMPTETTTrackImpl; import org.w3c.dom.Document; <<<<<<< ======= import java.net.URISyntaxException; import java.util.Collections; >>>>>>> import java.net.URISyntaxException; import java.util.Collections;
<<<<<<< return sampleEntries.get(l2i(Math.max(0, tfhd.getSampleDescriptionIndex()-1))); ======= return sampleEntries.size() == 1 ? sampleEntries.get(0) : sampleEntries.get(l2i(tfhd.getSampleDescriptionIndex() - 1)); >>>>>>> return sampleEntries.size() == 1 ? sampleEntries.get(0) : sampleEntries.get(l2i(Math.max(0, tfhd.getSampleDescriptionIndex()-1)));
<<<<<<< log.debug("Re-computing topology due " + "to HA change from SLAVE->MASTER"); newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS, TimeUnit.MILLISECONDS); ======= role = Role.MASTER; if (oldRole == Role.SLAVE) { log.debug("Re-computing topology due " + "to HA change from SLAVE->MASTER"); newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS, TimeUnit.MILLISECONDS); } >>>>>>> role = Role.MASTER; log.debug("Re-computing topology due " + "to HA change from SLAVE->MASTER"); newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS, TimeUnit.MILLISECONDS);
<<<<<<< import net.floodlightcontroller.routing.Path; ======= import net.floodlightcontroller.routing.Route; import net.floodlightcontroller.routing.RoutingDecision; >>>>>>> import net.floodlightcontroller.routing.Path; import net.floodlightcontroller.routing.RoutingDecision; <<<<<<< expect(routingEngine.getPath(DatapathId.of(1L), OFPort.of(1), DatapathId.of(2L), OFPort.of(3))).andReturn(route).atLeastOnce(); ======= reset(routingEngine); expect(routingEngine.getRoute(DatapathId.of(1L), OFPort.of(1), DatapathId.of(2L), OFPort.of(3), Forwarding.DEFAULT_FORWARDING_COOKIE)).andReturn(route).atLeastOnce(); >>>>>>> reset(routingEngine); expect(routingEngine.getPath(DatapathId.of(1L), OFPort.of(1), DatapathId.of(2L), OFPort.of(3))).andReturn(route).atLeastOnce(); <<<<<<< expect(routingEngine.getPath(DatapathId.of(1L), OFPort.of(1), DatapathId.of(1L), OFPort.of(3))).andReturn(route).atLeastOnce(); ======= >>>>>>> expect(routingEngine.getPath(DatapathId.of(1L), OFPort.of(1), DatapathId.of(1L), OFPort.of(3))).andReturn(route).atLeastOnce(); <<<<<<< expect(routingEngine.getPath(DatapathId.of(1L), OFPort.of(1), DatapathId.of(1L), OFPort.of(3))).andReturn(route).atLeastOnce(); ======= reset(routingEngine); expect(routingEngine.getRoute(DatapathId.of(1L), OFPort.of(1), DatapathId.of(1L), OFPort.of(3), Forwarding.DEFAULT_FORWARDING_COOKIE)).andReturn(route).atLeastOnce(); >>>>>>> reset(routingEngine); expect(routingEngine.getPath(DatapathId.of(1L), OFPort.of(1), DatapathId.of(1L), OFPort.of(3))).andReturn(route).atLeastOnce();
<<<<<<< import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.IHARoleListener; ======= import net.floodlightcontroller.core.IHAListener; >>>>>>> import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.IHAListener; <<<<<<< public class TopologyManager implements IFloodlightModule, ITopologyService, IRoutingService, ILinkDiscoveryListener, IOFMessageListener, IHARoleListener { ======= public class TopologyManager implements IFloodlightModule, ITopologyService, IRoutingService, ILinkDiscoveryListener, IHAListener { >>>>>>> public class TopologyManager implements IFloodlightModule, ITopologyService, IRoutingService, ILinkDiscoveryListener, IOFMessageListener, IHAListener { <<<<<<< ======= // // ILinkDiscoveryListener interface methods // public void linkDiscoveryUpdate(LDUpdate update) { boolean scheduleFlag = false; // if there's no udpates in the queue, then // we need to schedule an update. if (ldUpdates.peek() == null) scheduleFlag = true; if (log.isTraceEnabled()) { log.trace("Queuing update: {}", update); } ldUpdates.add(update); if (scheduleFlag) { newInstanceTask.reschedule(1, TimeUnit.MICROSECONDS); } } // // IFloodlightModule interfaces // @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(ITopologyService.class); l.add(IRoutingService.class); return l; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { Map<Class<? extends IFloodlightService>, IFloodlightService> m = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>(); // We are the class that implements the service m.put(ITopologyService.class, this); m.put(IRoutingService.class, this); return m; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(ILinkDiscoveryService.class); l.add(IThreadPoolService.class); l.add(IFloodlightProviderService.class); l.add(IRestApiService.class); return l; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { linkDiscovery = context.getServiceImpl(ILinkDiscoveryService.class); threadPool = context.getServiceImpl(IThreadPoolService.class); floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class); restApi = context.getServiceImpl(IRestApiService.class); switchPorts = new HashMap<Long,Set<Short>>(); switchPortLinks = new HashMap<NodePortTuple, Set<Link>>(); portBroadcastDomainLinks = new HashMap<NodePortTuple, Set<Link>>(); tunnelLinks = new HashMap<NodePortTuple, Set<Link>>(); topologyAware = new ArrayList<ITopologyListener>(); ldUpdates = new LinkedBlockingQueue<LDUpdate>(); } @Override public void startUp(FloodlightModuleContext context) { ScheduledExecutorService ses = threadPool.getScheduledExecutor(); newInstanceTask = new SingletonTask(ses, new NewInstanceWorker()); linkDiscovery.addListener(this); floodlightProvider.addHAListener(this); addWebRoutable(); newInstanceTask.reschedule(1, TimeUnit.MILLISECONDS); } protected void addWebRoutable() { restApi.addRestletRoutable(new TopologyWebRoutable()); } // // ITopologyService interface methods // @Override public boolean isInternal(long switchid, short port) { return currentInstance.isInternal(switchid, port); } @Override public long getSwitchClusterId(long switchId) { return currentInstance.getSwitchClusterId(switchId); } @Override public Set<Long> getSwitchesInCluster(long switchId) { return currentInstance.getSwitchesInCluster(switchId); } @Override public boolean inSameCluster(long switch1, long switch2) { return currentInstance.inSameCluster(switch1, switch2); } @Override public void addListener(ITopologyListener listener) { topologyAware.add(listener); } @Override public boolean isAllowed(long sw, short portId) { return currentInstance.isAllowed(sw, portId); } @Override public NodePortTuple getAllowedOutgoingBroadcastPort(long src, short srcPort, long dst, short dstPort) { return currentInstance.getAllowedOutgoingBroadcastPort(src,srcPort, dst,dstPort); } @Override public NodePortTuple getAllowedIncomingBroadcastPort(long src, short srcPort) { return currentInstance.getAllowedIncomingBroadcastPort(src,srcPort); } @Override public boolean isIncomingBroadcastAllowed(long sw, short portId) { return currentInstance.isIncomingBroadcastAllowedOnSwitchPort(sw, portId); } @Override public Set<Short> getPorts(long sw) { return currentInstance.getPorts(sw); } public Set<Short> getBroadcastPorts(long targetSw, long src, short srcPort) { return currentInstance.getBroadcastPorts(targetSw, src, srcPort); } // // IRoutingService interface methods // @Override public Route getRoute(long src, long dst) { Route r = currentInstance.getRoute(src, dst); return r; } @Override public boolean routeExists(long src, long dst) { return currentInstance.routeExists(src, dst); } @Override public BroadcastTree getBroadcastTreeForCluster(long clusterId) { return currentInstance.getBroadcastTreeForCluster(clusterId); } @Override public boolean isInSameBroadcastDomain(long s1, short p1, long s2, short p2) { return currentInstance.isInSameBroadcastDomain(s1, p1, s2, p2); } @Override public NodePortTuple getOutgoingSwitchPort(long src, short srcPort, long dst, short dstPort) { // Use this function to redirect traffic if needed. return currentInstance.getOutgoingSwitchPort(src, srcPort, dst, dstPort); } @Override public NodePortTuple getIncomingSwitchPort(long src, short srcPort, long dst, short dstPort) { return currentInstance.getIncomingSwitchPort(src, srcPort, dst, dstPort); } @Override public boolean isBroadcastDomainPort(long sw, short port) { return currentInstance.isBroadcastDomainPort(new NodePortTuple(sw, port)); } @Override public boolean isConsistent(long oldSw, short oldPort, long newSw, short newPort) { return currentInstance.isConsistent(oldSw, oldPort, newSw, newPort); } @Override public boolean inSameIsland(long switch1, long switch2) { return currentInstance.inSameIsland(switch1, switch2); } /** * Clears the current topology. Note that this does NOT * send out updates. */ public void clearCurrentTopology() { switchPorts.clear(); switchPortLinks.clear(); portBroadcastDomainLinks.clear(); tunnelLinks.clear(); createNewInstance(); } // IHAListener @Override public void roleChanged(Role oldRole, Role newRole) { switch(newRole) { case MASTER: if (oldRole == Role.SLAVE) { log.debug("Re-computing topology due " + "to HA change from SLAVE->MASTER"); newInstanceTask.reschedule(1, TimeUnit.MILLISECONDS); } break; case SLAVE: log.debug("Clearing topology due to " + "HA change to SLAVE"); clearCurrentTopology(); break; } } @Override public void controllerNodeIPsChanged( Map<String, String> curControllerNodeIPs, Map<String, String> addedControllerNodeIPs, Map<String, String> removedControllerNodeIPs) { // ignore } @Override public Set<NodePortTuple> getBroadcastDomainLinks() { return portBroadcastDomainLinks.keySet(); } @Override public Set<NodePortTuple> getTunnelLinks() { return tunnelLinks.keySet(); } >>>>>>>
<<<<<<< ======= /** * @param deviceManagerAware the deviceManagerAware to set */ public void setDeviceManagerAware(Set<IDeviceManagerAware> deviceManagerAware) { this.deviceManagerAware = deviceManagerAware; } public void setStorageSource(IStorageSource storageSource) { this.storageSource = storageSource; storageSource.createTable(DEVICE_TABLE_NAME, null); storageSource.setTablePrimaryKeyName( DEVICE_TABLE_NAME, MAC_COLUMN_NAME); storageSource.createTable(DEVICE_ATTACHMENT_POINT_TABLE_NAME, null); storageSource.setTablePrimaryKeyName( DEVICE_ATTACHMENT_POINT_TABLE_NAME, ID_COLUMN_NAME); storageSource.createTable(DEVICE_NETWORK_ADDRESS_TABLE_NAME, null); storageSource.setTablePrimaryKeyName( DEVICE_NETWORK_ADDRESS_TABLE_NAME, ID_COLUMN_NAME); storageSource.createTable(PORT_CHANNEL_TABLE_NAME, null); storageSource.setTablePrimaryKeyName( PORT_CHANNEL_TABLE_NAME, PC_ID_COLUMN_NAME); } >>>>>>> /** * @param deviceManagerAware the deviceManagerAware to set */ public void setDeviceManagerAware(Set<IDeviceManagerAware> deviceManagerAware) { this.deviceManagerAware = deviceManagerAware; } public void setStorageSource(IStorageSource storageSource) { this.storageSource = storageSource; }
<<<<<<< import net.floodlightcontroller.topology.ILinkDiscoveryService; ======= import net.floodlightcontroller.topology.ITopologyService; import net.floodlightcontroller.topology.SwitchPortTuple; >>>>>>> import net.floodlightcontroller.topology.ITopologyService; <<<<<<< expect(sw2.getSwitchClusterId()).andReturn(1L).anyTimes(); ======= expect(topology.getSwitchClusterId(2L)).andReturn(1L).anyTimes(); >>>>>>> expect(topology.getSwitchClusterId(2L)).andReturn(1L).anyTimes();
<<<<<<< import net.floodlightcontroller.packet.Ethernet; ======= import net.floodlightcontroller.restserver.IRestApiService; >>>>>>> import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.restserver.IRestApiService; <<<<<<< ======= import net.floodlightcontroller.topology.web.TopologyWebRoutable; import net.floodlightcontroller.util.StackTraceUtil; >>>>>>> import net.floodlightcontroller.topology.web.TopologyWebRoutable; <<<<<<< ======= protected IRestApiService restApi; >>>>>>> protected IRestApiService restApi;
<<<<<<< setConfigParams(configParams); ======= this.setRole(getInitialRole()); initVendorMessages(); >>>>>>> setConfigParams(configParams); this.setRole(getInitialRole()); initVendorMessages();
<<<<<<< ======= import net.floodlightcontroller.counter.ICounterStoreService; import net.floodlightcontroller.devicemanager.Device; >>>>>>> import net.floodlightcontroller.counter.ICounterStoreService;
<<<<<<< public Map<Long,IOFSwitch> getAllSwitchMap(); ======= public Map<Long, IOFSwitch> getSwitches(); public IOFSwitch getSwitchByDpid(String dpid); >>>>>>> public Map<Long,IOFSwitch> getAllSwitchMap(); public IOFSwitch getSwitchByDpid(String dpid);
<<<<<<< ======= // Comparator for sorting by SwitchCluster public Comparator<DeviceAttachmentPoint> clusterIdComparator = new Comparator<DeviceAttachmentPoint>() { @Override public int compare(DeviceAttachmentPoint d1, DeviceAttachmentPoint d2) { Long d1ClusterId = topology.getSwitchClusterId(d1.getSwitchPort().getSw().getId()); Long d2ClusterId = topology.getSwitchClusterId(d2.getSwitchPort().getSw().getId()); return d1ClusterId.compareTo(d2ClusterId); } }; // Comparator for sorting the attachment points by last seen. public Comparator<DeviceAttachmentPoint> lastSeenComparator = new Comparator<DeviceAttachmentPoint>() { @Override public int compare(DeviceAttachmentPoint d1, DeviceAttachmentPoint d2) { return d1.getLastSeen().compareTo(d2.getLastSeen()); } }; >>>>>>> <<<<<<< log.debug("pushRoute flowmod sw={} inPort={} outPort={}", new Object[] { sw, fm.getMatch().getInputPort(), ((OFActionOutput) fm.getActions().get(0)).getPort() }); log.info("Flow mod sent: Wildcard={} match={}", Integer.toHexString(fm.getMatch().getWildcards()), fm.getMatch().toString()); ======= if (log.isTraceEnabled()) { log.debug("pushRoute flowmod sw={} inPort={} outPort={}", new Object[] { sw, fm.getMatch().getInputPort(), ((OFActionOutput)fm.getActions().get(0)).getPort() }); } >>>>>>> if (log.isTraceEnabled()) { log.trace("pushRoute flowmod sw={} inPort={} outPort={}", new Object[] { sw, fm.getMatch().getInputPort(), ((OFActionOutput)fm.getActions().get(0)).getPort() }); } <<<<<<< if (log.isDebugEnabled()) { log.debug("PacketOut srcSwitch={} match={} pi={}", new Object[] { sw, match, pi }); ======= if (log.isTraceEnabled()) { log.debug("PacketOut srcSwitch={} match={} pi={}", new Object[] {sw, match, pi}); >>>>>>> if (log.isTraceEnabled()) { log.trace("PacketOut srcSwitch={} match={} pi={}", new Object[] {sw, match, pi}); <<<<<<< OFMessage fm = ((OFFlowMod) floodlightProvider.getOFMessageFactory() .getMessage(OFType.FLOW_MOD)).setCommand(OFFlowMod.OFPFC_DELETE) .setOutPort((short) OFPort.OFPP_NONE.getValue()) .setMatch(match) .setLength(U16.t(OFFlowMod.MINIMUM_LENGTH)); ======= long cookie = AppCookie.makeCookie(FORWARDING_APP_ID, 0); OFMessage fm = ((OFFlowMod) floodlightProvider.getOFMessageFactory() .getMessage(OFType.FLOW_MOD)) .setCommand(OFFlowMod.OFPFC_DELETE) .setOutPort((short) OFPort.OFPP_NONE.getValue()) .setMatch(match) .setCookie(cookie) .setLength(U16.t(OFFlowMod.MINIMUM_LENGTH)); >>>>>>> long cookie = AppCookie.makeCookie(FORWARDING_APP_ID, 0); OFMessage fm = ((OFFlowMod) floodlightProvider.getOFMessageFactory() .getMessage(OFType.FLOW_MOD)) .setCommand(OFFlowMod.OFPFC_DELETE) .setOutPort((short) OFPort.OFPP_NONE.getValue()) .setMatch(match) .setCookie(cookie) .setLength(U16.t(OFFlowMod.MINIMUM_LENGTH));
<<<<<<< expect(mockTopology.isInternal(mockSwitch, (short)1)).andReturn(false).anyTimes(); deviceManager.topology = mockTopology; ======= expect(mockTopology.isInternal(1L, (short)1)).andReturn(false); deviceManager.setTopology(mockTopology); >>>>>>> expect(mockTopology.isInternal(1L, (short)1)).andReturn(false).anyTimes(); deviceManager.topology = mockTopology; <<<<<<< expect(mockSwitch.getStringId()). andReturn("00:00:00:00:00:00:00:02").anyTimes(); expect(mockTopology.isInternal(mockSwitch, (short)2)).andReturn(false); expect(mockTopology.inSameCluster(1L, 2L)).andReturn(true); ======= expect(mockSwitch.getStringId()).andReturn("00:00:00:00:00:00:00:02").anyTimes(); expect(mockTopology.isInternal(2L, (short)2)).andReturn(false); assertEquals(1, deviceManager.getDeviceByIPv4Address(ipaddr).getAttachmentPoints().size()); deviceManager.invalidateDeviceAPsByIPv4Address(ipaddr); assertEquals(0, deviceManager.getDeviceByIPv4Address(ipaddr).getAttachmentPoints().size()); >>>>>>> expect(mockSwitch.getStringId()). andReturn("00:00:00:00:00:00:00:02").anyTimes(); expect(mockTopology.isInternal(2L, (short)2)).andReturn(false); expect(mockTopology.inSameCluster(1L, 2L)).andReturn(true); <<<<<<< rdevice = (Device) deviceManager.findDevice(Ethernet.toLong(dataLayerSource), (short)5, null, null, null); assertEquals(device, rdevice); ======= assertEquals(device, deviceManager.getDeviceByDataLayerAddress(dataLayerSource)); // Reset the device cache deviceManager.clearAllDeviceStateFromMemory(); } @Test public void testDeviceRecoverFromStorage() throws Exception { byte[] dataLayerSource = ((Ethernet)this.anotherTestPacket).getSourceMACAddress(); // Mock up our expected behavior IOFSwitch mockSwitch = createMock(IOFSwitch.class); ITopologyService mockTopology = createNiceMock(ITopologyService.class); expect(mockSwitch.getId()).andReturn(1L).anyTimes(); expect(mockSwitch.getStringId()).andReturn("00:00:00:00:00:00:00:01").anyTimes(); expect(mockTopology.isInternal(1L, (short)1)).andReturn(false); deviceManager.setTopology(mockTopology); // Start recording the replay on the mocks replay(mockSwitch, mockTopology); // Add the switch so the list isn't empty mockFloodlightProvider.getSwitches().put(mockSwitch.getId(), mockSwitch); // build our expected Device Device device = new Device(); Date currentDate = new Date(); Integer ipaddr = IPv4.toIPv4Address("192.168.1.1"); Integer ipaddr2 = IPv4.toIPv4Address("192.168.1.3"); device.setDataLayerAddress(dataLayerSource); SwitchPortTuple spt = new SwitchPortTuple(mockSwitch, (short)1); DeviceAttachmentPoint dap = new DeviceAttachmentPoint(spt, currentDate); device.addAttachmentPoint(dap); device.addNetworkAddress(ipaddr, currentDate); device.addNetworkAddress(ipaddr2, currentDate); // Get the listener and trigger the packet ins mockFloodlightProvider.dispatchMessage(mockSwitch, this.anotherPacketIn); mockFloodlightProvider.dispatchMessage(mockSwitch, this.thirdPacketIn); // Verify the device assertEquals(device, deviceManager.getDeviceByDataLayerAddress(dataLayerSource)); assertEquals(device, deviceManager.getDeviceByIPv4Address(ipaddr)); assertEquals(device, deviceManager.getDeviceByIPv4Address(ipaddr2)); assertEquals(dap, device.getAttachmentPoint(spt)); // Reset the device cache deviceManager.clearAllDeviceStateFromMemory(); // Verify the device assertNull(deviceManager.getDeviceByDataLayerAddress(dataLayerSource)); assertNull(deviceManager.getDeviceByIPv4Address(ipaddr)); assertNull(deviceManager.getDeviceByIPv4Address(ipaddr2)); // Load the device cache from storage deviceManager.readAllDeviceStateFromStorage(); // Verify the device Device device2 = deviceManager.getDeviceByDataLayerAddress(dataLayerSource); assertEquals(device, device2); assertEquals(dap, device2.getAttachmentPoint(spt)); deviceManager.clearAllDeviceStateFromMemory(); mockFloodlightProvider.setSwitches(new HashMap<Long,IOFSwitch>()); deviceManager.removedSwitch(mockSwitch); deviceManager.readAllDeviceStateFromStorage(); device2 = deviceManager.getDeviceByDataLayerAddress(dataLayerSource); assertEquals(device, device2); assertNull(device2.getAttachmentPoint(spt)); // The following two asserts seems to be incorrect, need to // replace NULL check with the correct value TODO //assertNull(deviceManager.getDeviceByIPv4Address(ipaddr)); //assertNull(deviceManager.getDeviceByIPv4Address(ipaddr2)); deviceManager.addedSwitch(mockSwitch); assertEquals(dap, device.getAttachmentPoint(spt)); assertEquals(device, deviceManager.getDeviceByIPv4Address(ipaddr)); assertEquals(device, deviceManager.getDeviceByIPv4Address(ipaddr2)); } @Test public void testDeviceUpdateLastSeenToStorage() throws Exception { deviceManager.clearAllDeviceStateFromMemory(); MockFloodlightProvider mockFloodlightProvider = getMockFloodlightProvider(); byte[] dataLayerSource = ((Ethernet)this.testPacket).getSourceMACAddress(); // Mock up our expected behavior IOFSwitch mockSwitch = createNiceMock(IOFSwitch.class); expect(mockSwitch.getId()).andReturn(1L).atLeastOnce(); ITopologyService mockTopology = createNiceMock(ITopologyService.class); //expect(mockTopology.isInternal(new SwitchPortTuple(mockSwitch, 1))).andReturn(false); deviceManager.setTopology(mockTopology); Date currentDate = new Date(); // build our expected Device Device device = new Device(); // Set Device to always update last-seen to storage Device.setStorageUpdateInterval(1); device.setDataLayerAddress(dataLayerSource); device.addAttachmentPoint(new SwitchPortTuple(mockSwitch, (short)1), currentDate); Integer ipaddr = IPv4.toIPv4Address("192.168.1.1"); device.addNetworkAddress(ipaddr, currentDate); // Start recording the replay on the mocks replay(mockSwitch, mockTopology); // Get the listener and trigger the packet in mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn); Thread.sleep(100); // Get the listener and trigger the packet in mockFloodlightProvider.dispatchMessage(mockSwitch, this.packetIn); // Clear the device cache deviceManager.clearAllDeviceStateFromMemory(); // Load the device cache from storage deviceManager.readAllDeviceStateFromStorage(); // Make sure the last seen is after our date device = deviceManager.getDeviceByDataLayerAddress(dataLayerSource); assertTrue(device.getLastSeen().after(currentDate)); >>>>>>> rdevice = (Device) deviceManager.findDevice(Ethernet.toLong(dataLayerSource), (short)5, null, null, null); assertEquals(device, rdevice);
<<<<<<< @Override public int getId() { return IOFMessageListener.FlListenerID.DEVICEMANAGERIMPL; } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { return (type == OFType.PACKET_IN && name.equals("topology")); ======= /** * Used in processPortStatus to check if the event is delete or shutdown * of a switch-port * @param ps * @return */ private boolean isPortStatusDelOrModify(OFPortStatus ps) { boolean isDelete = ((byte)OFPortReason.OFPPR_DELETE.ordinal() == ps.getReason()); boolean isModify = ((byte)OFPortReason.OFPPR_MODIFY.ordinal() == ps.getReason()); boolean isNotActive = (((OFPortConfig.OFPPC_PORT_DOWN.getValue() & ps.getDesc().getConfig()) > 0) || ((OFPortState.OFPPS_LINK_DOWN.getValue() & ps.getDesc().getState()) > 0)); return (isDelete || (isModify && isNotActive)); >>>>>>> @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { return (type == OFType.PACKET_IN && name.equals("topology")); <<<<<<< // ********************** // IStorageSourceListener // ********************** @Override public void rowsModified(String tableName, Set<Object> rowKeys) { // TODO Auto-generated method stub ======= private void handleNewDevice(byte[] mac, Date currentDate, SwitchPortTuple swPort, int nwAddr, Short vlan) { // Create the new device with attachment point and network address Device device = new Device(mac, currentDate); device.addAttachmentPoint(swPort, currentDate); evHistAttachmtPt(mac, swPort, EvAction.ADDED, "New device"); device.addNetworkAddress(nwAddr, currentDate); device.setVlanId(vlan); // Update the maps - insert the device in the maps devMgrMaps.updateMaps(device); writeDeviceToStorage(device, currentDate); updateStatus(device, true); if (log.isDebugEnabled()) { log.debug("New device learned {}", device); } >>>>>>> // ********************** // IStorageSourceListener // ********************** @Override public void rowsModified(String tableName, Set<Object> rowKeys) { // TODO Auto-generated method stub <<<<<<< @Override public void init(FloodlightModuleContext fmc) { this.perClassIndices = new HashSet<EnumSet<DeviceField>>(); addIndex(true, EnumSet.of(DeviceField.IPV4)); ======= if (newNetworkAddress) { // add the address nd.addNetworkAddress(networkAddress); log.info("Device {} added IP {}, packet {}", new Object[] {nd, IPv4.fromIPv4Address(nwSrc), eth.toString()}); } >>>>>>> @Override public void init(FloodlightModuleContext fmc) { this.perClassIndices = new HashSet<EnumSet<DeviceField>>(); addIndex(true, EnumSet.of(DeviceField.IPV4)); <<<<<<< // Extract source entity information Entity srcEntity = getSourceEntityFromPacket(eth, sw, pi.getInPort()); if (srcEntity == null) return Command.STOP; ======= // Do we have an old attachment point? DeviceAttachmentPoint attachmentPoint = device.getOldAttachmentPoint(swPort); if (attachmentPoint == null) { attachmentPoint = new DeviceAttachmentPoint(swPort, currentDate); } else { attachmentPoint.setLastSeen(currentDate); if (attachmentPoint.isBlocked()) { // Attachment point is currently in blocked state // If curAttachmentPoint exists and active, drop the packet if (curAttachmentPoint != null && currentDate.getTime() - curAttachmentPoint.getLastSeen().getTime() < 600000) { throw new APBlockedException("Attachment point is blocked"); } log.info("Unblocking {} for device {}", attachmentPoint.getSwitchPort(), device); attachmentPoint.setBlocked(false); evHistAttachmtPt(device, swPort, EvAction.UNBLOCKED, "packet-in after block timer expired"); } // Remove from old list device.removeOldAttachmentPoint(attachmentPoint); } // Update mappings devMgrMaps.addDevAttachmentPoint( device.getDataLayerAddressAsLong(), swPort, currentDate); evHistAttachmtPt(device, swPort, EvAction.ADDED, "packet-in GNAP"); // If curAttachmentPoint exists, we mark it a conflict and may block it. if (curAttachmentPoint != null) { device.removeAttachmentPoint(curAttachmentPoint); device.addOldAttachmentPoint(curAttachmentPoint); // If two ports are in the same port-channel, we don't treat it // as conflict, but will forward based on the last seen switch-port if (!devMgrMaps.inSamePortChannel(swPort, curAttachmentPoint.getSwitchPort()) && !topology.isInSameBroadcastDomain(swPort.getSw().getId(), swPort.getPort(), curAttachmentPoint.getSwitchPort().getSw().getId(), curAttachmentPoint.getSwitchPort().getPort())) { curAttachmentPoint.setConflict(currentDate); if (curAttachmentPoint.isFlapping()) { curAttachmentPoint.setBlocked(true); evHistAttachmtPt(device, curAttachmentPoint.getSwitchPort(), EvAction.BLOCKED, "Conflict"); writeAttachmentPointToStorage(device, curAttachmentPoint, currentDate); log.warn( "Device {}: flapping between {} and {}, block the latter", new Object[] {device, swPort, curAttachmentPoint.getSwitchPort()}); } else { removeAttachmentPointFromStorage(device, curAttachmentPoint); evHistAttachmtPt(device, curAttachmentPoint.getSwitchPort(), EvAction.REMOVED, "Conflict"); } } updateMoved(device, curAttachmentPoint.getSwitchPort(), attachmentPoint); >>>>>>> // Extract source entity information Entity srcEntity = getSourceEntityFromPacket(eth, sw, pi.getInPort()); if (srcEntity == null) return Command.STOP; <<<<<<< /** * Look up a {@link Device} within a particular entity class based on * the provided {@link Entity}. * @param clazz the entity class to search for the entity * @param entity the entity to search for * @return The {@link Device} object if found private Device findDeviceInClassByEntity(IEntityClass clazz, Entity entity) { // XXX - TODO throw new UnsupportedOperationException(); ======= // ******************** // Storage Read Methods // ******************** public boolean readPortChannelConfigFromStorage() { devMgrMaps.clearPortChannelMap(); try { IResultSet pcResultSet = storageSource.executeQuery( PORT_CHANNEL_TABLE_NAME, null, null, null); while (pcResultSet.next()) { String port_channel = pcResultSet.getString(PORT_CHANNEL_COLUMN_NAME); String switch_id = pcResultSet.getString(PC_SWITCH_COLUMN_NAME); String port_name = pcResultSet.getString(PC_PORT_COLUMN_NAME); devMgrMaps.addPortToPortChannel(switch_id, port_name, port_channel); } return true; } catch (StorageException e) { log.error("Error reading port-channel data from storage {}", e); return false; } >>>>>>> /** * Look up a {@link Device} within a particular entity class based on * the provided {@link Entity}. * @param clazz the entity class to search for the entity * @param entity the entity to search for * @return The {@link Device} object if found private Device findDeviceInClassByEntity(IEntityClass clazz, Entity entity) { // XXX - TODO throw new UnsupportedOperationException(); <<<<<<< protected Device allocateDevice(Long deviceKey, Collection<Entity> entities, IEntityClass[] entityClasses) { return new Device(this, deviceKey, entities, entityClasses); ======= @Override public void startUp(FloodlightModuleContext context) { // This is our 'constructor' if (linkDiscovery != null) { // Register to get updates from topology linkDiscovery.addListener(this); } else { log.error("Could not add topology listener"); } // Create our database tables storageSource.createTable(DEVICE_TABLE_NAME, null); storageSource.setTablePrimaryKeyName( DEVICE_TABLE_NAME, MAC_COLUMN_NAME); storageSource.createTable(DEVICE_ATTACHMENT_POINT_TABLE_NAME, null); storageSource.setTablePrimaryKeyName( DEVICE_ATTACHMENT_POINT_TABLE_NAME, ID_COLUMN_NAME); storageSource.createTable(DEVICE_NETWORK_ADDRESS_TABLE_NAME, null); storageSource.setTablePrimaryKeyName( DEVICE_NETWORK_ADDRESS_TABLE_NAME, ID_COLUMN_NAME); storageSource.createTable(PORT_CHANNEL_TABLE_NAME, null); storageSource.setTablePrimaryKeyName( PORT_CHANNEL_TABLE_NAME, PC_ID_COLUMN_NAME); storageSource.addListener(PORT_CHANNEL_TABLE_NAME, this); ScheduledExecutorService ses = floodlightProvider.getScheduledExecutor(); deviceUpdateTask = new SingletonTask(ses, new DeviceUpdateWorker()); // Register for the OpenFlow messages we want floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this); floodlightProvider.addOFMessageListener(OFType.PORT_STATUS, this); // Register for switch events floodlightProvider.addOFSwitchListener(this); floodlightProvider.addInfoProvider("summary", this); // Device and storage aging. enableDeviceAgingTimer(); // Read all our device state (MACs, IPs, attachment points) from storage readAllDeviceStateFromStorage(); >>>>>>> protected Device allocateDevice(Long deviceKey, Collection<Entity> entities, IEntityClass[] entityClasses) { return new Device(this, deviceKey, entities, entityClasses); <<<<<<< ======= @Override public Map<String, Object> getInfo(String type) { if (!"summary".equals(type)) return null; Map<String, Object> info = new HashMap<String, Object>(); info.put("# hosts", devMgrMaps.dataLayerAddressDeviceMap.size()); info.put("# IP Addresses", devMgrMaps.ipv4AddressDeviceMap.size()); int num_aps = 0; for (Map<Integer, Device> devAps : devMgrMaps.switchPortDeviceMap.values()) num_aps += devAps.size(); info.put("# attachment points", num_aps); return info; } >>>>>>>
<<<<<<< expect(topology.isIncomingBroadcastAllowedOnSwitchPort(1L, (short)1)).andReturn(true).anyTimes(); replay(sw1, sw2, routingEngine, topology); ======= expect(topology.isIncomingBroadcastAllowed(1L, (short)1)).andReturn(true).anyTimes(); replay(sw1, sw2, deviceManager, routingEngine, topology); >>>>>>> expect(topology.isIncomingBroadcastAllowed(1L, (short)1)).andReturn(true).anyTimes(); replay(sw1, sw2, routingEngine, topology);
<<<<<<< ======= import net.floodlightcontroller.debugcounter.IDebugCounterService.CounterType; import net.floodlightcontroller.flowcache.IFlowCacheService; >>>>>>> import net.floodlightcontroller.debugcounter.IDebugCounterService.CounterType; <<<<<<< protected IRestApiService restApi; protected ICounterStoreService counterStore = null; protected IDebugCounterService debugCounter; protected IStorageSourceService storageSource; protected IPktInProcessingTimeService pktinProcTime; protected IThreadPoolService threadPool; ======= private IRestApiService restApi; private ICounterStoreService counterStore = null; private IDebugCounterService debugCounters; private IFlowCacheService bigFlowCacheMgr; private IStorageSourceService storageSource; private IPktInProcessingTimeService pktinProcTime; private IThreadPoolService threadPool; private ScheduledExecutorService ses; private ISyncService syncService; private IStoreClient<Long, SwitchSyncRepresentation> storeClient; >>>>>>> private IRestApiService restApi; private ICounterStoreService counterStore = null; private IDebugCounterService debugCounters; private IStorageSourceService storageSource; private IPktInProcessingTimeService pktinProcTime; private IThreadPoolService threadPool; private ScheduledExecutorService ses; private ISyncService syncService; private IStoreClient<Long, SwitchSyncRepresentation> storeClient; <<<<<<< public void setPktInProcessingService(IPktInProcessingTimeService pits) { ======= void setFlowCacheMgr(IFlowCacheService flowCacheMgr) { this.bigFlowCacheMgr = flowCacheMgr; } void setPktInProcessingService(IPktInProcessingTimeService pits) { >>>>>>> void setPktInProcessingService(IPktInProcessingTimeService pits) {
<<<<<<< import net.floodlightcontroller.counter.ICounterStoreService; ======= import net.floodlightcontroller.devicemanager.IDeviceManagerAware; import net.floodlightcontroller.devicemanager.internal.DeviceManagerImpl; import net.floodlightcontroller.flowcache.FlowCache; import net.floodlightcontroller.forwarding.Forwarding; >>>>>>> import net.floodlightcontroller.counter.ICounterStoreService; import net.floodlightcontroller.devicemanager.IDeviceManagerAware; import net.floodlightcontroller.devicemanager.internal.DeviceManagerImpl; import net.floodlightcontroller.flowcache.FlowCache; import net.floodlightcontroller.forwarding.Forwarding; <<<<<<< protected IStorageSourceService storageSource; protected IOFMessageFilterManagerService messageFilterManager; protected IPktInProcessingTimeService pktinProcTime; ======= protected IStorageSource storageSource; protected TopologyImpl topology; protected DeviceManagerImpl deviceManager; protected RoutingImpl routingEngine; protected Forwarding forwarding; protected OFMessageFilterManager messageFilterManager; protected PktinProcessingTime pktinProcTime; protected FlowCache flowCacheManager; private StaticFlowEntryPusher staticFlowEntryPusher; >>>>>>> protected IStorageSourceService storageSource; protected IOFMessageFilterManagerService messageFilterManager; protected IPktInProcessingTimeService pktinProcTime; protected FlowCache flowCacheManager; // Configuration options protected int openFlowPort = 6633; <<<<<<< ======= >>>>>>> <<<<<<< final ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); ======= // Start listening for REST requests final Component component = new Component(); component.getServers().add(Protocol.HTTP, restPort); component.getDefaultHost().attach(this); component.start(); // Start listening for switch connections //int threads = // Runtime.getRuntime().availableProcessors() * 2 + 1; //int threads = 1; //long maxMem = Runtime.getRuntime().maxMemory() * 1 / 3; //long memPerChannel = 2 * 1024 * 1024; final ServerBootstrap bootstrap = createServerBootStrap(workerThreads); >>>>>>> final ServerBootstrap bootstrap = createServerBootStrap(workerThreads);
<<<<<<< ======= import net.floodlightcontroller.devicemanager.Device; import net.floodlightcontroller.devicemanager.DeviceAttachmentPoint; import net.floodlightcontroller.devicemanager.IDeviceManagerService; import net.floodlightcontroller.linkdiscovery.SwitchPortTuple; >>>>>>>
<<<<<<< // Test SeatMaps get Mockito.when(client.get("/v1/shopping/seatmaps", null)) .thenReturn(multiResponse); Mockito.when(client.get("/v1/shopping/seatmaps", params)) .thenReturn(multiResponse); SeatMaps seatmap = new SeatMaps(client); TestCase.assertNotNull(seatmap.get(params)); ======= // Test fetching a specific offer Mockito.when(client.get("/v1/booking/flight-orders/XXX", null)) .thenReturn(singleResponse); Mockito.when(client.get("/v1/booking/flight-orders/XXX", params)) .thenReturn(singleResponse); FlightOrder flightOrder = new FlightOrder(client, "XXX"); TestCase.assertNotNull(flightOrder.get()); TestCase.assertNotNull(flightOrder.get(params)); >>>>>>> // Test SeatMaps get Mockito.when(client.get("/v1/shopping/seatmaps", null)) .thenReturn(multiResponse); Mockito.when(client.get("/v1/shopping/seatmaps", params)) .thenReturn(multiResponse); SeatMaps seatmap = new SeatMaps(client); TestCase.assertNotNull(seatmap.get(params)); // Test fetching a specific offer Mockito.when(client.get("/v1/booking/flight-orders/XXX", null)) .thenReturn(singleResponse); Mockito.when(client.get("/v1/booking/flight-orders/XXX", params)) .thenReturn(singleResponse); FlightOrder flightOrder = new FlightOrder(client, "XXX"); TestCase.assertNotNull(flightOrder.get()); TestCase.assertNotNull(flightOrder.get(params));
<<<<<<< * @author Johannes Stelzer ======= * @author Johannes Edmeier * >>>>>>> * @author Johannes Edmeier <<<<<<< ResponseEntity<Map<String, String>> response = restTemplate.getForEntity( application.getHealthUrl(), (Class<Map<String, String>>) (Class<?>) Map.class); ======= ResponseEntity<Map<String, Object>> response = restTemplate.getForEntity(application.getHealthUrl(), (Class<Map<String, Object>>)(Class<?>) Map.class); >>>>>>> ResponseEntity<Map<String, Object>> response = restTemplate.getForEntity( application.getHealthUrl(), (Class<Map<String, Object>>) (Class<?>) Map.class); <<<<<<< if (response.hasBody() && response.getBody().get("status") != null) { return StatusInfo.valueOf(response.getBody().get("status")); ======= if (response.hasBody() && response.getBody().get("status") instanceof String) { return StatusInfo.valueOf((String) response.getBody().get("status")); >>>>>>> if (response.hasBody() && response.getBody().get("status") instanceof String) { return StatusInfo.valueOf((String) response.getBody().get("status")); <<<<<<< } catch (RestClientException ex) { ======= } catch (Exception ex){ >>>>>>> } catch (Exception ex) {
<<<<<<< @EnableConfigurationProperties({ClientProperties.class, InstanceProperties.class}) ======= @EnableConfigurationProperties({AdminProperties.class, AdminClientProperties.class}) @ConditionalOnWebApplication >>>>>>> @EnableConfigurationProperties({ClientProperties.class, InstanceProperties.class}) @ConditionalOnWebApplication
<<<<<<< public void close() { // TODO Auto-generated method stub } ======= public void visitFacets(FacetVisitor visitor) { if (_predefinedRangeIndexes!=null) { int[] rangeCounts = new int[_predefinedRangeIndexes.length]; for (int i=0;i<_count.length;++i){ if (_count[i] >0 ){ for (int k=0;k<_predefinedRangeIndexes.length;++k) { if (i>=_predefinedRangeIndexes[k][0] && i<=_predefinedRangeIndexes[k][1]) { rangeCounts[k]+=_count[i]; } } } } for (int i=0;i<rangeCounts.length;++i) { visitor.visit(_predefinedRanges.get(i), rangeCounts[i]); } } } >>>>>>> public void close() { // TODO Auto-generated method stub } public void visitFacets(FacetVisitor visitor) { if (_predefinedRangeIndexes!=null) { int[] rangeCounts = new int[_predefinedRangeIndexes.length]; for (int i=0;i<_count.length;++i){ if (_count[i] >0 ){ for (int k=0;k<_predefinedRangeIndexes.length;++k) { if (i>=_predefinedRangeIndexes[k][0] && i<=_predefinedRangeIndexes[k][1]) { rangeCounts[k]+=_count[i]; } } } } for (int i=0;i<rangeCounts.length;++i) { visitor.visit(_predefinedRanges.get(i), rangeCounts[i]); } } }
<<<<<<< public void close() { // TODO Auto-generated method stub } ======= public void visitFacets(FacetVisitor visitor) { for (BrowseFacet facet : _facets) { visitor.visit(facet.getValue(), facet.getHitCount()); } } >>>>>>> public void close() { // TODO Auto-generated method stub } public void visitFacets(FacetVisitor visitor) { for (BrowseFacet facet : _facets) { visitor.visit(facet.getValue(), facet.getHitCount()); } }
<<<<<<< import magic.model.choice.MagicTargetChoice; import magic.model.target.MagicTargetFilter; import magic.model.target.MagicTargetFilterFactory; ======= import magic.model.event.MagicAdditionalCost; import magic.model.event.MagicBestowActivation; import magic.model.event.MagicCardActivation; import magic.model.event.MagicCyclingActivation; import magic.model.event.MagicEquipActivation; import magic.model.event.MagicEvokeActivation; import magic.model.event.MagicFlashbackActivation; import magic.model.event.MagicKickerCost; import magic.model.event.MagicLevelUpActivation; import magic.model.event.MagicMatchedCostEvent; import magic.model.event.MagicMonstrosityActivation; import magic.model.event.MagicMultikickerCost; import magic.model.event.MagicNinjutsuActivation; import magic.model.event.MagicPainTapManaActivation; import magic.model.event.MagicPayLifeTapManaActivation; import magic.model.event.MagicPermanentActivation; import magic.model.event.MagicPlayMulticounterEvent; import magic.model.event.MagicReinforceActivation; import magic.model.event.MagicRetraceActivation; import magic.model.event.MagicRuleEventAction; import magic.model.event.MagicSacrificeManaActivation; import magic.model.event.MagicSacrificeTapManaActivation; import magic.model.event.MagicSourceEvent; import magic.model.event.MagicTapManaActivation; import magic.model.event.MagicTransmuteActivation; import magic.model.event.MagicTypeCyclingActivation; import magic.model.event.MagicVividManaActivation; >>>>>>> import magic.model.event.MagicAdditionalCost; import magic.model.event.MagicBestowActivation; import magic.model.event.MagicCardActivation; import magic.model.event.MagicCyclingActivation; import magic.model.event.MagicEvokeActivation; import magic.model.event.MagicFlashbackActivation; import magic.model.event.MagicKickerCost; import magic.model.event.MagicMatchedCostEvent; import magic.model.event.MagicMonstrosityActivation; import magic.model.event.MagicMultikickerCost; import magic.model.event.MagicNinjutsuActivation; import magic.model.event.MagicPlayMulticounterEvent; import magic.model.event.MagicRetraceActivation; import magic.model.event.MagicSacrificeManaActivation; import magic.model.event.MagicSacrificeTapManaActivation; import magic.model.event.MagicTapManaActivation; import magic.model.event.MagicTransmuteActivation; import magic.model.event.MagicTypeCyclingActivation; import magic.model.event.MagicVividManaActivation; <<<<<<< import magic.model.event.*; import magic.model.trigger.*; import magic.model.trigger.MagicThiefTrigger.Type; ======= import magic.model.target.MagicTargetFilter; import magic.model.target.MagicTargetFilterFactory; import magic.model.trigger.MagicAnnihilatorTrigger; import magic.model.trigger.MagicAtEndOfTurnTrigger; import magic.model.trigger.MagicAtUpkeepTrigger; import magic.model.trigger.MagicBattalionTrigger; import magic.model.trigger.MagicBattleCryTrigger; import magic.model.trigger.MagicBecomesBlockedPumpTrigger; import magic.model.trigger.MagicBlockedByCreaturePumpTrigger; import magic.model.trigger.MagicBloodthirstTrigger; import magic.model.trigger.MagicCascadeTrigger; import magic.model.trigger.MagicChampionTrigger; import magic.model.trigger.MagicComesIntoPlayWithCounterTrigger; import magic.model.trigger.MagicCumulativeUpkeepTrigger; import magic.model.trigger.MagicDamageGrowTrigger; import magic.model.trigger.MagicDevourTrigger; import magic.model.trigger.MagicEchoTrigger; import magic.model.trigger.MagicExaltedTrigger; import magic.model.trigger.MagicExtortTrigger; import magic.model.trigger.MagicFadeVanishCounterTrigger; import magic.model.trigger.MagicFlankingTrigger; import magic.model.trigger.MagicFromGraveyardToLibraryTrigger; import magic.model.trigger.MagicHeroicTrigger; import magic.model.trigger.MagicLeavesReturnExileTrigger; import magic.model.trigger.MagicLivingWeaponTrigger; import magic.model.trigger.MagicMiracleTrigger; import magic.model.trigger.MagicModularTrigger; import magic.model.trigger.MagicPersistTrigger; import magic.model.trigger.MagicRampageTrigger; import magic.model.trigger.MagicRavnicaLandTrigger; import magic.model.trigger.MagicReplicateTrigger; import magic.model.trigger.MagicSoulshiftTrigger; import magic.model.trigger.MagicSpecterTrigger; import magic.model.trigger.MagicStormTrigger; import magic.model.trigger.MagicTappedIntoPlayTrigger; import magic.model.trigger.MagicTappedIntoPlayUnlessTrigger; import magic.model.trigger.MagicTappedIntoPlayUnlessTwoTrigger; >>>>>>> import magic.model.target.MagicTargetFilter; import magic.model.target.MagicTargetFilterFactory; import magic.model.trigger.MagicAtEndOfTurnTrigger; import magic.model.trigger.MagicAtUpkeepTrigger; import magic.model.trigger.MagicBattalionTrigger; import magic.model.trigger.MagicCascadeTrigger; import magic.model.trigger.MagicChampionTrigger; import magic.model.trigger.MagicExtortTrigger; import magic.model.trigger.MagicHeroicTrigger; import magic.model.trigger.MagicPersistTrigger; <<<<<<< ======= import magic.model.trigger.MagicThiefTrigger.Type; import magic.model.trigger.MagicTributeTrigger; import magic.model.trigger.MagicUndyingTrigger; import magic.model.trigger.MagicUnleashTrigger; import magic.model.trigger.MagicWhenBlocksPumpTrigger; import magic.model.trigger.MagicWhenComesIntoPlayTrigger; import magic.model.trigger.MagicWhenDamageIsDealtTrigger; import magic.model.trigger.MagicWhenDiesTrigger; import magic.model.trigger.MagicWhenOtherComesIntoPlayTrigger; import magic.model.trigger.MagicWhenOtherDiesTrigger; import magic.model.trigger.MagicWhenOtherSpellIsCastTrigger; import magic.model.trigger.MagicWhenPutIntoGraveyardTrigger; import magic.model.trigger.MagicWhenSelfAttacksTrigger; import magic.model.trigger.MagicWhenSelfBecomesBlockedTrigger; import magic.model.trigger.MagicWhenSelfBecomesTappedTrigger; import magic.model.trigger.MagicWhenSelfBecomesUntappedTrigger; import magic.model.trigger.MagicWhenSelfBlocksTrigger; import magic.model.trigger.MagicWhenSelfLeavesPlayTrigger; import magic.model.trigger.MagicWhenTargetedTrigger; >>>>>>> import magic.model.trigger.MagicThiefTrigger.Type; import magic.model.trigger.MagicTributeTrigger; import magic.model.trigger.MagicUndyingTrigger; import magic.model.trigger.MagicUnleashTrigger; import magic.model.trigger.MagicWhenDamageIsDealtTrigger; import magic.model.trigger.MagicWhenOtherDiesTrigger; import magic.model.trigger.MagicWhenOtherSpellIsCastTrigger; import magic.model.trigger.MagicWhenPutIntoGraveyardTrigger; import magic.model.trigger.MagicWhenSelfBlocksTrigger; import magic.model.trigger.MagicWhenSelfLeavesPlayTrigger; import magic.model.trigger.MagicWhenTargetedTrigger;
<<<<<<< public static MagicCondition ADDENDUM = new MagicCondition() { @Override public boolean accept(final MagicSource source) { final MagicCardOnStack spell = (MagicCardOnStack)source; final MagicGame game = source.getGame(); final MagicPhaseType phaseType = game.getPhase().getType(); return spell.isCast() && spell.getController().getId() == game.getTurnPlayer().getId() && (phaseType == MagicPhaseType.FirstMain || phaseType == MagicPhaseType.SecondMain); } }; ======= public static MagicCondition SPECTACLE = new MagicCondition() { @Override public boolean accept(final MagicSource source) { final MagicPlayer opponent = source.getOpponent(); return opponent.getLifeLossThisTurn() > 0; } }; >>>>>>> public static MagicCondition ADDENDUM = new MagicCondition() { @Override public boolean accept(final MagicSource source) { final MagicCardOnStack spell = (MagicCardOnStack)source; final MagicGame game = source.getGame(); final MagicPhaseType phaseType = game.getPhase().getType(); return spell.isCast() && spell.getController().getId() == game.getTurnPlayer().getId() && (phaseType == MagicPhaseType.FirstMain || phaseType == MagicPhaseType.SecondMain); } }; public static MagicCondition SPECTACLE = new MagicCondition() { @Override public boolean accept(final MagicSource source) { final MagicPlayer opponent = source.getOpponent(); return opponent.getLifeLossThisTurn() > 0; } };
<<<<<<< ======= import com.avaje.ebean.bean.EntityBean; >>>>>>> import com.avaje.ebean.bean.EntityBean; <<<<<<< ======= >>>>>>>
<<<<<<< ======= >>>>>>> <<<<<<< ======= >>>>>>>
<<<<<<< private boolean loadedBeanChanged; ======= boolean loadedBeanChanged; >>>>>>> private boolean loadedBeanChanged; <<<<<<< public void setLoadedBean(Object bean, Object id, Object lazyLoadParentId) { ======= public void setLoadedBean(EntityBean bean, Object id) { >>>>>>> public void setLoadedBean(EntityBean bean, Object id, Object lazyLoadParentId) {
<<<<<<< import com.avaje.ebeaninternal.server.autofetch.AutoFetchManager; import com.avaje.ebeaninternal.server.autofetch.AutoFetchManagerFactory; import com.avaje.ebeaninternal.server.changelog.DefaultChangeLogListener; ======= import com.avaje.ebeaninternal.server.autofetch.AutoTuneService; import com.avaje.ebeaninternal.server.autofetch.service.AutoTuneServiceFactory; import com.avaje.ebeaninternal.server.changelog.DefaultChangeLogListener; >>>>>>> import com.avaje.ebeaninternal.server.autofetch.AutoTuneService; import com.avaje.ebeaninternal.server.autofetch.service.AutoTuneServiceFactory; import com.avaje.ebeaninternal.server.changelog.DefaultChangeLogListener; <<<<<<< import com.avaje.ebeaninternal.server.readaudit.DefaultReadAuditLogger; import com.avaje.ebeaninternal.server.readaudit.DefaultReadAuditPrepare; import com.avaje.ebeaninternal.server.resource.ResourceManager; import com.avaje.ebeaninternal.server.resource.ResourceManagerFactory; ======= >>>>>>> import com.avaje.ebeaninternal.server.readaudit.DefaultReadAuditLogger; import com.avaje.ebeaninternal.server.readaudit.DefaultReadAuditPrepare;
<<<<<<< import com.avaje.ebeaninternal.server.autofetch.AutoFetchManager; ======= import com.avaje.ebeaninternal.server.autofetch.AutoTuneService; import com.avaje.ebean.dbmigration.DdlGenerator; >>>>>>> import com.avaje.ebeaninternal.server.autofetch.AutoTuneService; <<<<<<< private final AutoFetchManager autoFetchManager; ======= private final DiffHelp diffHelp; private final AutoTuneService autoTuneService; >>>>>>> private final AutoTuneService autoTuneService; <<<<<<< this.autoFetchManager = config.createAutoFetchManager(this); this.adminAutofetch = new MAdminAutofetch(autoFetchManager); this.readAuditPrepare = config.getReadAuditPrepare(); this.readAuditLogger = config.getReadAuditLogger(); ======= this.autoTuneService = config.createAutoFetchManager(this); >>>>>>> this.autoTuneService = config.createAutoFetchManager(this); this.readAuditPrepare = config.getReadAuditPrepare(); this.readAuditLogger = config.getReadAuditLogger();
<<<<<<< public AutoFetchManager getAutoFetchManager() { return null; } @Override public ReadAuditLogger getReadAuditLogger() { return null; } @Override public ReadAuditPrepare getReadAuditPrepare() { return null; } @Override ======= >>>>>>> public ReadAuditLogger getReadAuditLogger() { return null; } @Override public ReadAuditPrepare getReadAuditPrepare() { return null; } @Override
<<<<<<< import ch.qos.logback.classic.Level; import io.netty.handler.codec.http.HttpServerKeepAliveHandler; ======= import io.nuls.base.data.NulsDigestData; >>>>>>> import ch.qos.logback.classic.Level; <<<<<<< import io.nuls.core.parse.HashUtil; import io.nuls.core.rpc.model.ModuleE; ======= >>>>>>> import io.nuls.core.parse.HashUtil; import io.nuls.core.rpc.model.ModuleE;
<<<<<<< ======= import java.util.Currency; >>>>>>> import java.util.Currency; <<<<<<< ======= import com.avaje.ebean.text.json.JsonContext; import com.avaje.ebeaninternal.api.SpiEbeanServer; import com.avaje.ebeaninternal.server.deploy.BeanDescriptor; import com.avaje.ebeaninternal.server.el.ElPropertyValue; >>>>>>> import com.avaje.ebean.text.json.JsonContext; import com.avaje.ebeaninternal.api.SpiEbeanServer; import com.avaje.ebeaninternal.server.deploy.BeanDescriptor; import com.avaje.ebeaninternal.server.el.ElPropertyValue;
<<<<<<< ======= import javax.persistence.PersistenceException; import com.avaje.ebean.bean.EntityBean; >>>>>>> import javax.persistence.PersistenceException; import com.avaje.ebean.bean.EntityBean; <<<<<<< public Object[] getIdValues(Object bean) { bean = embIdProperty.getValue(bean); ======= /** * Convert the lucene string term value into embedded id. */ public Object readTerm(String idTermValue) { String[] split = idTermValue.split("|"); if (split.length != props.length){ String msg = "Failed to split ["+idTermValue+"] using | for id."; throw new PersistenceException(msg); } EntityBean embId = idDesc.createBean(); for (int i = 0; i < props.length; i++) { Object v = props[i].getScalarType().parse(split[i]); props[i].setValue(embId, v); } return embId; } /** * Write the embedded id as a Lucene string term value. */ public String writeTerm(Object idValue) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < props.length; i++) { Object v = props[i].getValue((EntityBean)idValue); String formatValue = props[i].getScalarType().format(v); if (i > 0){ sb.append("|"); } sb.append(formatValue); } return sb.toString(); } public Object[] getIdValues(EntityBean bean) { Object val = embIdProperty.getValue(bean); >>>>>>> public Object[] getIdValues(EntityBean bean) { Object val = embIdProperty.getValue(bean);
<<<<<<< /* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.util.normalize.output; import org.encog.util.normalize.input.InputField; /** * A ranged mapped output field. This will scale the input so that it is between * the high and low value. */ public class OutputFieldRangeMapped extends BasicOutputField implements RequireTwoPass { /** * Calculate a ranged mapped value. * @param value The to map. * @param min The minimum that the value param can be. * @param max The maximum that the value param can be. * @param hi The high value to map into. * @param lo The low value to map into. * @return The mapped value. */ public static double calculate(final double value, final double min, final double max, final double hi, final double lo) { return ((value - min) / (max - min)) * (hi - lo) + lo; } /** * The input field to scale. */ private InputField field; /** * The low value of the field. */ private double low; /** * The high value of the field. */ private double high; /** * Default constructor, used mainly for reflection. */ public OutputFieldRangeMapped() { } /** * Construct a range mapped output field. * * @param field * The input field to base this on. * @param low * The low value. * @param high * The high value. */ public OutputFieldRangeMapped(final InputField field, final double low, final double high) { this.field = field; this.low = low; this.high = high; } /** * Create a range field with -1 and 1 as low/high. * @param f The input field to use. */ public OutputFieldRangeMapped(InputField f) { this(f,-1,1); } /** * Calculate this output field. * * @param subfield * Not used. * @return The calculated value. */ public double calculate(final int subfield) { if (this.field.getMax() == this.field.getMin()) { return 0; } else { return ((this.field.getCurrentValue() - this.field.getMin()) / (this.field.getMax() - this.field.getMin())) * (this.high - this.low) + this.low; } } /** * @return The field that this output is based on. */ public InputField getField() { return this.field; } /** * @return The high value of the range to map into. */ public double getHigh() { return this.high; } /** * @return The low value of the range to map into. */ public double getLow() { return this.low; } /** * @return This field only produces one value, so this will return 1. */ public int getSubfieldCount() { return 1; } /** * Not needed for this sort of output field. */ public void rowInit() { } /** * Convert a number back after its been normalized. * @param data The number to convert back. * @return The result. */ public double convertBack(final double data) { double result = ((field.getMin() - field.getMax()) * data - high * field.getMin() + field.getMax() * low) / (low - high); return result; } } ======= /* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.util.normalize.output; import org.encog.util.normalize.input.InputField; /** * A ranged mapped output field. This will scale the input so that it is between * the high and low value. */ public class OutputFieldRangeMapped extends BasicOutputField implements RequireTwoPass { /** * Calculate a ranged mapped value. * @param value The to map. * @param min The minimum that the value param can be. * @param max The maximum that the value param can be. * @param hi The high value to map into. * @param lo The low value to map into. * @return The mapped value. */ public static double calculate(final double value, final double min, final double max, final double hi, final double lo) { return ((value - min) / (max - min)) * (hi - lo) + lo; } /** * The input field to scale. */ private InputField field; /** * The low value of the field. */ private double low; /** * The high value of the field. */ private double high; /** * Default constructor, used mainly for reflection. */ public OutputFieldRangeMapped() { } /** * Construct a range mapped output field. * * @param field * The input field to base this on. * @param low * The low value. * @param high * The high value. */ public OutputFieldRangeMapped(final InputField field, final double low, final double high) { this.field = field; this.low = low; this.high = high; } /** * Create a range field with -1 and 1 as low/high. * @param f The input field to use. */ public OutputFieldRangeMapped(InputField f) { this(f,-1,1); } /** * Calculate this output field. * * @param subfield * Not used. * @return The calculated value. */ public double calculate(final int subfield) { return ((this.field.getCurrentValue() - this.field.getMin()) / (this.field .getMax() - this.field.getMin())) * (this.high - this.low) + this.low; } /** * @return The field that this output is based on. */ public InputField getField() { return this.field; } /** * @return The high value of the range to map into. */ public double getHigh() { return this.high; } /** * @return The low value of the range to map into. */ public double getLow() { return this.low; } /** * @return This field only produces one value, so this will return 1. */ public int getSubfieldCount() { return 1; } /** * Not needed for this sort of output field. */ public void rowInit() { } /** * Convert a number back after its been normalized. * @param data The number to convert back. * @return The result. */ public double convertBack(final double data) { double result = ((field.getMin() - field.getMax()) * data - high * field.getMin() + field.getMax() * low) / (low - high); return result; } } >>>>>>> /* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.util.normalize.output; import org.encog.util.normalize.input.InputField; /** * A ranged mapped output field. This will scale the input so that it is between * the high and low value. */ public class OutputFieldRangeMapped extends BasicOutputField implements RequireTwoPass { /** * Calculate a ranged mapped value. * @param value The to map. * @param min The minimum that the value param can be. * @param max The maximum that the value param can be. * @param hi The high value to map into. * @param lo The low value to map into. * @return The mapped value. */ public static double calculate(final double value, final double min, final double max, final double hi, final double lo) { return ((value - min) / (max - min)) * (hi - lo) + lo; } /** * The input field to scale. */ private InputField field; /** * The low value of the field. */ private double low; /** * The high value of the field. */ private double high; /** * Default constructor, used mainly for reflection. */ public OutputFieldRangeMapped() { } /** * Construct a range mapped output field. * * @param field * The input field to base this on. * @param low * The low value. * @param high * The high value. */ public OutputFieldRangeMapped(final InputField field, final double low, final double high) { this.field = field; this.low = low; this.high = high; } /** * Create a range field with -1 and 1 as low/high. * @param f The input field to use. */ public OutputFieldRangeMapped(InputField f) { this(f,-1,1); } /** * Calculate this output field. * * @param subfield * Not used. * @return The calculated value. */ public double calculate(final int subfield) { if (this.field.getMax() == this.field.getMin()) { return 0; } else { return ((this.field.getCurrentValue() - this.field.getMin()) / (this.field.getMax() - this.field.getMin())) * (this.high - this.low) + this.low; } } /** * @return The field that this output is based on. */ public InputField getField() { return this.field; } /** * @return The high value of the range to map into. */ public double getHigh() { return this.high; } /** * @return The low value of the range to map into. */ public double getLow() { return this.low; } /** * @return This field only produces one value, so this will return 1. */ public int getSubfieldCount() { return 1; } /** * Not needed for this sort of output field. */ public void rowInit() { } /** * Convert a number back after its been normalized. * @param data The number to convert back. * @return The result. */ public double convertBack(final double data) { double result = ((field.getMin() - field.getMax()) * data - high * field.getMin() + field.getMax() * low) / (low - high); return result; } }
<<<<<<< /* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ensemble.ml.mlp.factory; import java.util.Collection; import org.encog.engine.network.activation.ActivationFunction; import org.encog.ensemble.EnsembleMLMethodFactory; import org.encog.ml.MLMethod; import org.encog.neural.networks.BasicNetwork; import org.encog.neural.networks.layers.BasicLayer; public class MultiLayerPerceptronFactory implements EnsembleMLMethodFactory { Collection<Integer> layers; ActivationFunction activation; int sizeMultiplier = 1; public void setParameters(Collection<Integer> layers, ActivationFunction activation){ this.layers=layers; this.activation=activation; } @Override public MLMethod createML(int inputs, int outputs) { BasicNetwork network = new BasicNetwork(); network.addLayer(new BasicLayer(activation,false,inputs)); for (Integer layerSize: layers) network.addLayer(new BasicLayer(activation,true,layerSize * sizeMultiplier)); network.addLayer(new BasicLayer(activation,true,outputs)); network.getStructure().finalizeStructure(); network.reset(); return network; } @Override public String getLabel() { String ret = "mlp{"; for (int i=0; i < layers.size() - 1; i++) ret = ret + layers.toArray()[i] + ","; return ret + layers.toArray()[layers.size() - 1] + "}"; } @Override public void reInit(MLMethod ml) { ((BasicNetwork) ml).reset(); } @Override public void setSizeMultiplier(int sizeMultiplier) { this.sizeMultiplier = sizeMultiplier; } } ======= /* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ensemble.ml.mlp.factory; import java.util.Collection; import org.encog.engine.network.activation.ActivationFunction; import org.encog.ensemble.EnsembleMLMethodFactory; import org.encog.ml.MLMethod; import org.encog.neural.networks.BasicNetwork; import org.encog.neural.networks.layers.BasicLayer; public class MultiLayerPerceptronFactory implements EnsembleMLMethodFactory { Collection<Integer> layers; ActivationFunction activation; public void setParameters(Collection<Integer> layers, ActivationFunction activation){ this.layers=layers; this.activation=activation; } @Override public MLMethod createML(int inputs, int outputs) { BasicNetwork network = new BasicNetwork(); network.addLayer(new BasicLayer(activation,false,inputs)); //(inputs)); for (Integer layerSize: layers) network.addLayer(new BasicLayer(activation,true,layerSize)); network.addLayer(new BasicLayer(activation,true,outputs)); network.getStructure().finalizeStructure(); network.reset(); return network; } @Override public String getLabel() { String ret = "mlp{"; for (int i=0; i < layers.size() - 1; i++) ret = ret + layers.toArray()[i] + ","; return ret + layers.toArray()[layers.size() - 1] + "}"; } @Override public void reInit(MLMethod ml) { ((BasicNetwork) ml).reset(); } } >>>>>>> /* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ensemble.ml.mlp.factory; import java.util.Collection; import org.encog.engine.network.activation.ActivationFunction; import org.encog.ensemble.EnsembleMLMethodFactory; import org.encog.ml.MLMethod; import org.encog.neural.networks.BasicNetwork; import org.encog.neural.networks.layers.BasicLayer; public class MultiLayerPerceptronFactory implements EnsembleMLMethodFactory { Collection<Integer> layers; ActivationFunction activation; int sizeMultiplier = 1; public void setParameters(Collection<Integer> layers, ActivationFunction activation){ this.layers=layers; this.activation=activation; } @Override public MLMethod createML(int inputs, int outputs) { BasicNetwork network = new BasicNetwork(); network.addLayer(new BasicLayer(activation,false,inputs)); //(inputs)); for (Integer layerSize: layers) network.addLayer(new BasicLayer(activation,true,layerSize * sizeMultiplier)); network.addLayer(new BasicLayer(activation,true,outputs)); network.getStructure().finalizeStructure(); network.reset(); return network; } @Override public String getLabel() { String ret = "mlp{"; for (int i=0; i < layers.size() - 1; i++) ret = ret + layers.toArray()[i] + ","; return ret + layers.toArray()[layers.size() - 1] + "}"; } @Override public void reInit(MLMethod ml) { ((BasicNetwork) ml).reset(); } @Override public void setSizeMultiplier(int sizeMultiplier) { this.sizeMultiplier = sizeMultiplier; } }
<<<<<<< /* * Encog(tm) Core v3.1 - Java Version * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * Copyright 2008-2012 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.data.basic; import java.io.Serializable; import org.encog.ml.data.MLData; import org.encog.util.kmeans.Centroid; /** * Basic implementation of the MLData interface that stores the data in an * array. * * @author jheaton * */ public class BasicMLData implements MLData, Serializable, Cloneable { /** * The serial id. */ private static final long serialVersionUID = -3644304891793584603L; /** * The data held by this object. */ private double[] data; /** * Construct this object with the specified data. * * @param d * The data to construct this object with. */ public BasicMLData(final double[] d) { this(d.length); System.arraycopy(d, 0, this.data, 0, d.length); } /** * Construct this object with blank data and a specified size. * * @param size * The amount of data to store. */ public BasicMLData(final int size) { this.data = new double[size]; } /** * Construct a new BasicMLData object from an existing one. This makes a * copy of an array. * * @param d * The object to be copied. */ public BasicMLData(final MLData d) { this(d.size()); System.arraycopy(d.getData(), 0, this.data, 0, d.size()); } /** * {@inheritDoc} */ @Override public final void add(final int index, final double value) { this.data[index] += value; } /** * {@inheritDoc} */ @Override public final void clear() { for (int i = 0; i < this.data.length; i++) { this.data[i] = 0; } } /** * {@inheritDoc} */ @Override public final MLData clone() { return new BasicMLData(this); } /** * {@inheritDoc} */ @Override public final double[] getData() { return this.data; } /** * {@inheritDoc} */ @Override public final double getData(final int index) { return this.data[index]; } /** * {@inheritDoc} */ @Override public final void setData(final double[] theData) { this.data = theData; } /** * {@inheritDoc} */ @Override public final void setData(final int index, final double d) { this.data[index] = d; } /** * {@inheritDoc} */ @Override public final int size() { return this.data.length; } /** * {@inheritDoc} */ @Override public final String toString() { final StringBuilder builder = new StringBuilder("["); builder.append(this.getClass().getSimpleName()); builder.append(":"); for (int i = 0; i < this.data.length; i++) { if (i != 0) { builder.append(','); } builder.append(this.data[i]); } builder.append("]"); return builder.toString(); } /** * {@inheritDoc} */ @Override public Centroid<MLData> createCentroid() { return new BasicMLDataCentroid(this); } /** * Add one data element to another. This does not modify the object. * @param o The other data element * @return The result. */ public MLData plus(MLData o) { if (size() != o.size()) throw new IllegalArgumentException(); BasicMLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) result.setData(i, getData(i) + o.getData(i)); return result; } /** * Multiply one data element with another. This does not modify the object. * @param o The other data element * @return The result. */ public MLData times(double d) { MLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) result.setData(i, getData(i) * d); return result; } /** * Subtract one data element from another. This does not modify the object. * @param o The other data element * @return The result. */ public MLData minus(MLData o) { if (size() != o.size()) throw new IllegalArgumentException(); MLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) result.setData(i, getData(i) - o.getData(i)); return result; } public MLData threshold(double thresholdValue, double lowValue, double highValue) { MLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) if (getData(i) > thresholdValue) result.setData(i,highValue); else result.setData(i,lowValue); return result; } } ======= /* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.data.basic; import java.io.Serializable; import org.encog.ml.data.MLData; import org.encog.util.kmeans.Centroid; /** * Basic implementation of the MLData interface that stores the data in an * array. * * @author jheaton * */ public class BasicMLData implements MLData, Serializable, Cloneable { /** * The serial id. */ private static final long serialVersionUID = -3644304891793584603L; /** * The data held by this object. */ private double[] data; /** * Construct this object with the specified data. * * @param d * The data to construct this object with. */ public BasicMLData(final double[] d) { this(d.length); System.arraycopy(d, 0, this.data, 0, d.length); } /** * Construct this object with blank data and a specified size. * * @param size * The amount of data to store. */ public BasicMLData(final int size) { this.data = new double[size]; } /** * Construct a new BasicMLData object from an existing one. This makes a * copy of an array. * * @param d * The object to be copied. */ public BasicMLData(final MLData d) { this(d.size()); System.arraycopy(d.getData(), 0, this.data, 0, d.size()); } /** * {@inheritDoc} */ @Override public void add(final int index, final double value) { this.data[index] += value; } /** * {@inheritDoc} */ @Override public void clear() { for (int i = 0; i < this.data.length; i++) { this.data[i] = 0; } } /** * {@inheritDoc} */ @Override public MLData clone() { return new BasicMLData(this); } /** * {@inheritDoc} */ @Override public double[] getData() { return this.data; } /** * {@inheritDoc} */ @Override public double getData(final int index) { return this.data[index]; } /** * {@inheritDoc} */ @Override public void setData(final double[] theData) { this.data = theData; } /** * {@inheritDoc} */ @Override public void setData(final int index, final double d) { this.data[index] = d; } /** * {@inheritDoc} */ @Override public int size() { return this.data.length; } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder builder = new StringBuilder("["); builder.append(this.getClass().getSimpleName()); builder.append(":"); for (int i = 0; i < this.data.length; i++) { if (i != 0) { builder.append(','); } builder.append(this.data[i]); } builder.append("]"); return builder.toString(); } /** * {@inheritDoc} */ @Override public Centroid<MLData> createCentroid() { return new BasicMLDataCentroid(this); } /** * Add one data element to another. This does not modify the object. * @param o The other data element * @return The result. */ public MLData plus(MLData o) { if (size() != o.size()) throw new IllegalArgumentException(); BasicMLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) result.setData(i, getData(i) + o.getData(i)); return result; } /** * Multiply one data element with another. This does not modify the object. * @param d The other data element * @return The result. */ public MLData times(double d) { MLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) result.setData(i, getData(i) * d); return result; } /** * Subtract one data element from another. This does not modify the object. * @param o The other data element * @return The result. */ public MLData minus(MLData o) { if (size() != o.size()) throw new IllegalArgumentException(); MLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) result.setData(i, getData(i) - o.getData(i)); return result; } } >>>>>>> /* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.data.basic; import java.io.Serializable; import org.encog.ml.data.MLData; import org.encog.util.kmeans.Centroid; /** * Basic implementation of the MLData interface that stores the data in an * array. * * @author jheaton * */ public class BasicMLData implements MLData, Serializable, Cloneable { /** * The serial id. */ private static final long serialVersionUID = -3644304891793584603L; /** * The data held by this object. */ private double[] data; /** * Construct this object with the specified data. * * @param d * The data to construct this object with. */ public BasicMLData(final double[] d) { this(d.length); System.arraycopy(d, 0, this.data, 0, d.length); } /** * Construct this object with blank data and a specified size. * * @param size * The amount of data to store. */ public BasicMLData(final int size) { this.data = new double[size]; } /** * Construct a new BasicMLData object from an existing one. This makes a * copy of an array. * * @param d * The object to be copied. */ public BasicMLData(final MLData d) { this(d.size()); System.arraycopy(d.getData(), 0, this.data, 0, d.size()); } /** * {@inheritDoc} */ @Override public void add(final int index, final double value) { this.data[index] += value; } /** * {@inheritDoc} */ @Override public void clear() { for (int i = 0; i < this.data.length; i++) { this.data[i] = 0; } } /** * {@inheritDoc} */ @Override public MLData clone() { return new BasicMLData(this); } /** * {@inheritDoc} */ @Override public double[] getData() { return this.data; } /** * {@inheritDoc} */ @Override public double getData(final int index) { return this.data[index]; } /** * {@inheritDoc} */ @Override public void setData(final double[] theData) { this.data = theData; } /** * {@inheritDoc} */ @Override public void setData(final int index, final double d) { this.data[index] = d; } /** * {@inheritDoc} */ @Override public int size() { return this.data.length; } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder builder = new StringBuilder("["); builder.append(this.getClass().getSimpleName()); builder.append(":"); for (int i = 0; i < this.data.length; i++) { if (i != 0) { builder.append(','); } builder.append(this.data[i]); } builder.append("]"); return builder.toString(); } /** * {@inheritDoc} */ @Override public Centroid<MLData> createCentroid() { return new BasicMLDataCentroid(this); } /** * Add one data element to another. This does not modify the object. * @param o The other data element * @return The result. */ public MLData plus(MLData o) { if (size() != o.size()) throw new IllegalArgumentException(); BasicMLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) result.setData(i, getData(i) + o.getData(i)); return result; } /** * Multiply one data element with another. This does not modify the object. * @param d The other data element * @return The result. */ public MLData times(double d) { MLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) result.setData(i, getData(i) * d); return result; } /** * Subtract one data element from another. This does not modify the object. * @param o The other data element * @return The result. */ public MLData minus(MLData o) { if (size() != o.size()) throw new IllegalArgumentException(); MLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) result.setData(i, getData(i) - o.getData(i)); return result; } public MLData threshold(double thresholdValue, double lowValue, double highValue) { MLData result = new BasicMLData(size()); for (int i = 0; i < size(); i++) if (getData(i) > thresholdValue) result.setData(i,highValue); else result.setData(i,lowValue); return result; } }
<<<<<<< /* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ensemble.data.factories; import java.util.ArrayList; import org.encog.ensemble.data.EnsembleDataSet; import org.encog.ml.data.MLDataSet; public abstract class EnsembleDataSetFactory { protected MLDataSet dataSource = null; protected int dataSetSize; public EnsembleDataSetFactory(int dataSetSize) { setDataSetSize(dataSetSize); } public void setInputData(MLDataSet dataSource) { this.dataSource = dataSource; this.reload(); } abstract public EnsembleDataSet getNewDataSet(); public boolean hasSource() { return (dataSource != null); } public MLDataSet getInputData() { return this.dataSource; } public int getDataSetSize() { return dataSetSize; } public int getDataSourceSize() { return this.dataSource.size(); } public MLDataSet getDataSource() { return this.dataSource; } public void setDataSetSize(int dataSetSize) { this.dataSetSize = dataSetSize; } public int getInputCount() { return this.dataSource.getInputSize(); } public int getOutputCount() { return this.dataSource.getIdealSize(); } public void setSignificance(ArrayList<Double> D) { for (int i = 0; i < dataSource.size(); i++) dataSource.get(i).setSignificance(D.get(i)); } public ArrayList<Double> getSignificance() { ArrayList<Double> res = new ArrayList<Double>(); for (int i = 0; i < dataSource.size(); i++) res.add(dataSource.get(i).getSignificance()); return res; } public void reload() { } } ======= /* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ensemble.data.factories; import java.util.ArrayList; import org.encog.ensemble.data.EnsembleDataSet; import org.encog.ml.data.MLDataSet; public abstract class EnsembleDataSetFactory { protected MLDataSet dataSource = null; protected int dataSetSize; public EnsembleDataSetFactory(int dataSetSize) { setDataSetSize(dataSetSize); } public void setInputData(MLDataSet dataSource) { this.dataSource = dataSource; } abstract public EnsembleDataSet getNewDataSet(); public boolean hasSource() { return (dataSource != null); } public MLDataSet getInputData() { return this.dataSource; } public int getDataSetSize() { return dataSetSize; } public void setDataSetSize(int dataSetSize) { this.dataSetSize = dataSetSize; } public int getInputCount() { return this.dataSource.getInputSize(); } public int getOutputCount() { return this.dataSource.getIdealSize(); } public void setSignificance(ArrayList<Double> D) { for (int i = 0; i < dataSource.size(); i++) dataSource.get(i).setSignificance(D.get(i)); } public ArrayList<Double> getSignificance() { ArrayList<Double> res = new ArrayList<Double>(); for (int i = 0; i < dataSource.size(); i++) res.add(dataSource.get(i).getSignificance()); return res; } } >>>>>>> /* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ensemble.data.factories; import java.util.ArrayList; import org.encog.ensemble.data.EnsembleDataSet; import org.encog.ml.data.MLDataSet; public abstract class EnsembleDataSetFactory { protected MLDataSet dataSource = null; protected int dataSetSize; public EnsembleDataSetFactory(int dataSetSize) { setDataSetSize(dataSetSize); } public void setInputData(MLDataSet dataSource) { this.dataSource = dataSource; this.reload(); } abstract public EnsembleDataSet getNewDataSet(); public boolean hasSource() { return (dataSource != null); } public MLDataSet getInputData() { return this.dataSource; } public int getDataSetSize() { return dataSetSize; } public void setDataSetSize(int dataSetSize) { this.dataSetSize = dataSetSize; } public int getDataSourceSize() { return this.dataSource.size(); } public MLDataSet getDataSource() { return this.dataSource; } public int getInputCount() { return this.dataSource.getInputSize(); } public int getOutputCount() { return this.dataSource.getIdealSize(); } public void setSignificance(ArrayList<Double> D) { for (int i = 0; i < dataSource.size(); i++) dataSource.get(i).setSignificance(D.get(i)); } public ArrayList<Double> getSignificance() { ArrayList<Double> res = new ArrayList<Double>(); for (int i = 0; i < dataSource.size(); i++) res.add(dataSource.get(i).getSignificance()); return res; } public void reload() { } }
<<<<<<< /* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ensemble; import org.encog.ensemble.data.EnsembleDataSet; import org.encog.ml.MLMethod; import org.encog.ml.data.MLData; import org.encog.ml.train.MLTrain; import org.encog.neural.networks.BasicNetwork; import org.encog.util.EngineArray; public class GenericEnsembleML implements EnsembleML { private EnsembleDataSet trainingSet; private BasicNetwork ml; private MLTrain trainer; private String label; private final int DEFAULT_MAX_ITERATIONS = 2000; public GenericEnsembleML(MLMethod fromML, String description) { setMl(fromML); this.label = description; } @Override public void setTrainingSet(EnsembleDataSet dataSet) { this.trainingSet = dataSet; } @Override public EnsembleDataSet getTrainingSet() { return trainingSet; } @Override public void train(double targetError, int maxIterations, boolean verbose) { double error = 0; double previouserror = 1; double errordelta = 1; int iteration = 0; do { trainer.iteration(); iteration++; if (iteration > 1) { previouserror = error; } error = trainer.getError(); if (iteration > 1) { errordelta = previouserror - error; } if (verbose) System.out.println(iteration + " " + error); } while ((error > targetError) && trainer.canContinue() && //errordelta / previouserror < 2 && iteration < maxIterations); trainer.finishTraining(); } @Override public void setMl(MLMethod newMl) { ml = (BasicNetwork) newMl; } @Override public MLMethod getMl() { return ml; } @Override public int classify(MLData input) { return ml.classify(input); } @Override public MLData compute(MLData input) { return ml.compute(input); } @Override public int getInputCount() { return ml.getInputCount(); } @Override public int getOutputCount() { return ml.getOutputCount(); } @Override public void train(double targetError) { train(targetError, false); } public int winner(MLData output) { return EngineArray.maxIndex(output.getData()); } @Override public void setTraining(MLTrain train) { trainer = train; } @Override public MLTrain getTraining() { return trainer; } @Override public void trainStep() { trainer.iteration(); } @Override public String getLabel() { return label; } @Override public double getError(EnsembleDataSet testset) { return ml.calculateError(testset); } @Override public void train(double targetError, int maxIterations) { train(targetError, maxIterations, false); } @Override public void train(double targetError, boolean verbose) { train(targetError, DEFAULT_MAX_ITERATIONS, verbose); } } ======= /* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ensemble; import org.encog.ensemble.data.EnsembleDataSet; import org.encog.ml.MLMethod; import org.encog.ml.data.MLData; import org.encog.ml.train.MLTrain; import org.encog.neural.networks.BasicNetwork; import org.encog.util.EngineArray; public class GenericEnsembleML implements EnsembleML { private EnsembleDataSet trainingSet; private BasicNetwork ml; private MLTrain trainer; private String label; public GenericEnsembleML(MLMethod fromML, String description) { setMl(fromML); this.label = description; } @Override public void setTrainingSet(EnsembleDataSet dataSet) { this.trainingSet = dataSet; } @Override public EnsembleDataSet getTrainingSet() { return trainingSet; } @Override public void train(double targetError, boolean verbose) { double error = 0; double previouserror = 0; double errordelta = 0; int iteration = 0; do { trainer.iteration(); iteration++; if (iteration > 1) { previouserror = error; } error = trainer.getError(); if (iteration > 1) { errordelta = previouserror - error; } if (verbose) System.out.println(iteration + " " + error); } while ((error > targetError) && trainer.canContinue() && errordelta > -0.1 && //make this a parameter iteration < 2000); trainer.finishTraining(); } @Override public void setMl(MLMethod newMl) { ml = (BasicNetwork) newMl; } @Override public MLMethod getMl() { return ml; } @Override public int classify(MLData input) { return ml.classify(input); } @Override public MLData compute(MLData input) { return ml.compute(input); } @Override public int getInputCount() { return ml.getInputCount(); } @Override public int getOutputCount() { return ml.getOutputCount(); } @Override public void train(double targetError) { train(targetError, false); } public int winner(MLData output) { return EngineArray.maxIndex(output.getData()); } @Override public void setTraining(MLTrain train) { trainer = train; } @Override public MLTrain getTraining() { return trainer; } @Override public void trainStep() { trainer.iteration(); } @Override public String getLabel() { return label; } @Override public double getError(EnsembleDataSet testset) { return ml.calculateError(testset); } } >>>>>>> /* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ensemble; import org.encog.ensemble.data.EnsembleDataSet; import org.encog.ml.MLMethod; import org.encog.ml.data.MLData; import org.encog.ml.train.MLTrain; import org.encog.neural.networks.BasicNetwork; import org.encog.util.EngineArray; public class GenericEnsembleML implements EnsembleML { private EnsembleDataSet trainingSet; private BasicNetwork ml; private MLTrain trainer; private String label; private final int DEFAULT_MAX_ITERATIONS = 2000; public GenericEnsembleML(MLMethod fromML, String description) { setMl(fromML); this.label = description; } @Override public void setTrainingSet(EnsembleDataSet dataSet) { this.trainingSet = dataSet; } @Override public EnsembleDataSet getTrainingSet() { return trainingSet; } @Override public void train(double targetError, int maxIterations, boolean verbose) { double error = 0; double previouserror = 1; double errordelta = 1; int iteration = 0; do { trainer.iteration(); iteration++; if (iteration > 1) { previouserror = error; } error = trainer.getError(); if (iteration > 1) { errordelta = previouserror - error; } if (verbose) System.out.println(iteration + " " + error); } while ((error > targetError) && trainer.canContinue() && //errordelta / previouserror < 2 && iteration < maxIterations); trainer.finishTraining(); } @Override public void train(double targetError) { train(targetError, false); } @Override public void train(double targetError, int maxIterations) { train(targetError, maxIterations, false); } @Override public void train(double targetError, boolean verbose) { train(targetError, DEFAULT_MAX_ITERATIONS, verbose); } @Override public void setMl(MLMethod newMl) { ml = (BasicNetwork) newMl; } @Override public MLMethod getMl() { return ml; } @Override public int classify(MLData input) { return ml.classify(input); } @Override public MLData compute(MLData input) { return ml.compute(input); } @Override public int getInputCount() { return ml.getInputCount(); } @Override public int getOutputCount() { return ml.getOutputCount(); } public int winner(MLData output) { return EngineArray.maxIndex(output.getData()); } @Override public void setTraining(MLTrain train) { trainer = train; } @Override public MLTrain getTraining() { return trainer; } @Override public void trainStep() { trainer.iteration(); } @Override public String getLabel() { return label; } @Override public double getError(EnsembleDataSet testset) { return ml.calculateError(testset); } }
<<<<<<< import com.qaprosoft.carina.core.foundation.utils.SpecialKeywords; ======= import com.qaprosoft.carina.core.foundation.utils.SpecialKeywords; import static com.qaprosoft.carina.core.foundation.cucumber.CucumberRunner.*; import static com.qaprosoft.carina.core.foundation.report.ReportContext.isArtifactsFolderExists; >>>>>>> import com.qaprosoft.carina.core.foundation.utils.SpecialKeywords; <<<<<<< private static final int MESSAGE_LIMIT = R.EMAIL.getInt("fail_description_limit"); ======= //Cucumber section private static final String CUCUMBER_RESULTS_PLACEHOLDER = "${cucumber_results}"; private static final String CUCUMBER_JS_PLACEHOLDER ="${js_placeholder}"; private static final int MESSAGE_LIMIT = 2048; >>>>>>> private static final int MESSAGE_LIMIT = R.EMAIL.getInt("fail_description_limit"); //Cucumber section private static final String CUCUMBER_RESULTS_PLACEHOLDER = "${cucumber_results}"; private static final String CUCUMBER_JS_PLACEHOLDER ="${js_placeholder}";
<<<<<<< /* * Copyright 2013-2015 QAPROSOFT (http://qaprosoft.com/). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qaprosoft.carina.core.foundation.webdriver; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.ios.IOSDriver; import java.net.URL; import org.apache.log4j.Logger; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import com.qaprosoft.carina.core.foundation.utils.Configuration; import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter; import com.qaprosoft.carina.core.foundation.utils.SpecialKeywords; import com.qaprosoft.carina.core.foundation.webdriver.core.capability.impl.mobile.MobileCapabilies; import com.qaprosoft.carina.core.foundation.webdriver.core.factory.AbstractFactory; import com.qaprosoft.carina.core.foundation.webdriver.core.factory.impl.DesktopFactory; import com.qaprosoft.carina.core.foundation.webdriver.core.factory.impl.MobileFactory; import com.qaprosoft.carina.core.foundation.webdriver.device.Device; /** * DriverFactory produces driver instance with desired capabilities according to * configuration. * * @author Alexey Khursevich ([email protected]) */ public class DriverFactory { public static final String HTML_UNIT = "htmlunit"; protected static final Logger LOGGER = Logger.getLogger(DriverFactory.class); private static final Device nullDevice = new Device(); @SuppressWarnings("rawtypes") public static WebDriver create(String testName, DesiredCapabilities capabilities, String selenium_host) { RemoteWebDriver driver = null; try { if (capabilities.getCapability("automationName") == null) driver = new RemoteWebDriver(new URL(selenium_host), capabilities); else { String platform; if (capabilities.getCapability("platform") != null) { platform = capabilities.getCapability("platform").toString(); } else if (capabilities.getCapability("platformName") != null) { platform = capabilities.getCapability("platformName").toString(); } else { throw new RuntimeException("Unable to identify platform type using platform and platformName capabilities for test: " + testName); } if (platform.toLowerCase().equals("android")) { driver = new AndroidDriver(new URL(selenium_host), capabilities); } else if (platform.toLowerCase().equals("ios")) { driver = new IOSDriver(new URL(selenium_host), capabilities); } else { throw new RuntimeException("Undefined platform type for mobile driver test: " + testName); } } } catch (Exception e) { LOGGER.error("Unable to initialize extra driver!\r\n" + e.getMessage()); } return driver; } /** * Creates driver instance for specified test. * * @param testName in which driver will be used * @return RemoteWebDriver instance */ public static WebDriver create(String testName) { return create(testName, nullDevice); } public static WebDriver create(String testName, Device device) { AbstractFactory factory; String driverType = Configuration.get(Parameter.DRIVER_TYPE); if (driverType.equalsIgnoreCase(SpecialKeywords.DESKTOP)) { factory = new DesktopFactory(); } else if (driverType.equalsIgnoreCase(SpecialKeywords.MOBILE) || driverType.equalsIgnoreCase(SpecialKeywords.MOBILE_POOL) || driverType.equalsIgnoreCase(SpecialKeywords.MOBILE_GRID)) { factory = new MobileFactory(); } else { throw new RuntimeException("Unsupported driver_type: " + driverType + "!"); } return factory.create(testName, device); } public static String getBrowserName(WebDriver driver) { Capabilities cap = ((RemoteWebDriver) driver).getCapabilities(); return cap.getBrowserName().toString(); } public static String getBrowserVersion(WebDriver driver) { Capabilities cap = ((RemoteWebDriver) driver).getCapabilities(); return cap.getVersion().toString(); } @Deprecated public static DesiredCapabilities getMobileWebCapabilities(boolean gridMode, String testName, String platform, String platformVersion, String deviceName, String automationName, String commandTimeout, String browserName) { return MobileCapabilies.getMobileCapabilities(gridMode, platform, platformVersion, deviceName, automationName, commandTimeout, browserName, "", "", ""); } ======= /* * Copyright 2013-2015 QAPROSOFT (http://qaprosoft.com/). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qaprosoft.carina.core.foundation.webdriver; import java.net.URL; import org.apache.log4j.Logger; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import com.qaprosoft.carina.core.foundation.utils.Configuration; import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter; import com.qaprosoft.carina.core.foundation.utils.SpecialKeywords; import com.qaprosoft.carina.core.foundation.webdriver.core.factory.AbstractFactory; import com.qaprosoft.carina.core.foundation.webdriver.core.factory.impl.DesktopFactory; import com.qaprosoft.carina.core.foundation.webdriver.core.factory.impl.MobileFactory; import com.qaprosoft.carina.core.foundation.webdriver.device.Device; import com.qaprosoft.carina.core.foundation.webdriver.device.DevicePool; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.ios.IOSDriver; /** * DriverFactory produces driver instance with desired capabilities according to * configuration. * * @author Alexey Khursevich ([email protected]) */ public class DriverFactory { public static final String HTML_UNIT = "htmlunit"; protected static final Logger LOGGER = Logger.getLogger(DriverFactory.class); private static final Device nullDevice = new Device(); @SuppressWarnings("rawtypes") public static WebDriver create(String testName, DesiredCapabilities capabilities, String selenium_host) { RemoteWebDriver driver = null; try { if (capabilities.getCapability("automationName") == null) driver = new RemoteWebDriver(new URL(selenium_host), capabilities); else { String platform; if (capabilities.getCapability("platform") != null) { platform = capabilities.getCapability("platform").toString(); } else if (capabilities.getCapability("platformName") != null) { platform = capabilities.getCapability("platformName").toString(); } else { throw new RuntimeException("Unable to identify platform type using platform and platformName capabilities for test: " + testName); } if (platform.toLowerCase().equals("android")) { driver = new AndroidDriver(new URL(selenium_host), capabilities); } else if (platform.toLowerCase().equals("ios")) { driver = new IOSDriver(new URL(selenium_host), capabilities); } else { throw new RuntimeException("Undefined platform type for mobile driver test: " + testName); } } } catch (Exception e) { LOGGER.error("Unable to initialize extra driver!\r\n" + e.getMessage()); } if (driver == null) { LOGGER.error("Page isn't created. There is no any initialized driver for thread: " + Thread.currentThread().getId()); Device device = DevicePool.getDevice(); DevicePool.unregisterDevice(device); throw new RuntimeException("Page isn't created. Driver isn't initialized."); } return driver; } /** * Creates driver instance for specified test. * * @param testName in which driver will be used * @return RemoteWebDriver instance */ public static WebDriver create(String testName) { return create(testName, nullDevice); } public static WebDriver create(String testName, Device device) { AbstractFactory factory; String driverType = Configuration.get(Parameter.DRIVER_TYPE); if (driverType.equalsIgnoreCase(SpecialKeywords.DESKTOP)) { factory = new DesktopFactory(); } else if (driverType.equalsIgnoreCase(SpecialKeywords.MOBILE) || driverType.equalsIgnoreCase(SpecialKeywords.MOBILE_POOL) || driverType.equalsIgnoreCase(SpecialKeywords.MOBILE_GRID)) { factory = new MobileFactory(); } else { throw new RuntimeException("Unsupported driver_type: " + driverType + "!"); } return factory.create(testName, device); } public static String getBrowserName(WebDriver driver) { Capabilities cap = ((RemoteWebDriver) driver).getCapabilities(); return cap.getBrowserName().toString(); } public static String getBrowserVersion(WebDriver driver) { Capabilities cap = ((RemoteWebDriver) driver).getCapabilities(); return cap.getVersion().toString(); } >>>>>>> /* * Copyright 2013-2015 QAPROSOFT (http://qaprosoft.com/). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qaprosoft.carina.core.foundation.webdriver; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.ios.IOSDriver; import java.net.URL; import org.apache.log4j.Logger; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import com.qaprosoft.carina.core.foundation.utils.Configuration; import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter; import com.qaprosoft.carina.core.foundation.utils.SpecialKeywords; import com.qaprosoft.carina.core.foundation.webdriver.core.factory.AbstractFactory; import com.qaprosoft.carina.core.foundation.webdriver.core.factory.impl.DesktopFactory; import com.qaprosoft.carina.core.foundation.webdriver.core.factory.impl.MobileFactory; import com.qaprosoft.carina.core.foundation.webdriver.device.Device; import com.qaprosoft.carina.core.foundation.webdriver.device.DevicePool; /** * DriverFactory produces driver instance with desired capabilities according to * configuration. * * @author Alexey Khursevich ([email protected]) */ public class DriverFactory { public static final String HTML_UNIT = "htmlunit"; protected static final Logger LOGGER = Logger.getLogger(DriverFactory.class); private static final Device nullDevice = new Device(); @SuppressWarnings("rawtypes") public static WebDriver create(String testName, DesiredCapabilities capabilities, String selenium_host) { RemoteWebDriver driver = null; try { if (capabilities.getCapability("automationName") == null) driver = new RemoteWebDriver(new URL(selenium_host), capabilities); else { String platform; if (capabilities.getCapability("platform") != null) { platform = capabilities.getCapability("platform").toString(); } else if (capabilities.getCapability("platformName") != null) { platform = capabilities.getCapability("platformName").toString(); } else { throw new RuntimeException("Unable to identify platform type using platform and platformName capabilities for test: " + testName); } if (platform.toLowerCase().equals("android")) { driver = new AndroidDriver(new URL(selenium_host), capabilities); } else if (platform.toLowerCase().equals("ios")) { driver = new IOSDriver(new URL(selenium_host), capabilities); } else { throw new RuntimeException("Undefined platform type for mobile driver test: " + testName); } } } catch (Exception e) { LOGGER.error("Unable to initialize extra driver!\r\n" + e.getMessage()); } if (driver == null) { LOGGER.error("Page isn't created. There is no any initialized driver for thread: " + Thread.currentThread().getId()); Device device = DevicePool.getDevice(); DevicePool.unregisterDevice(device); throw new RuntimeException("Page isn't created. Driver isn't initialized."); } return driver; } /** * Creates driver instance for specified test. * * @param testName in which driver will be used * @return RemoteWebDriver instance */ public static WebDriver create(String testName) { return create(testName, nullDevice); } public static WebDriver create(String testName, Device device) { AbstractFactory factory; String driverType = Configuration.get(Parameter.DRIVER_TYPE); if (driverType.equalsIgnoreCase(SpecialKeywords.DESKTOP)) { factory = new DesktopFactory(); } else if (driverType.equalsIgnoreCase(SpecialKeywords.MOBILE) || driverType.equalsIgnoreCase(SpecialKeywords.MOBILE_POOL) || driverType.equalsIgnoreCase(SpecialKeywords.MOBILE_GRID)) { factory = new MobileFactory(); } else { throw new RuntimeException("Unsupported driver_type: " + driverType + "!"); } return factory.create(testName, device); } public static String getBrowserName(WebDriver driver) { Capabilities cap = ((RemoteWebDriver) driver).getCapabilities(); return cap.getBrowserName().toString(); } public static String getBrowserVersion(WebDriver driver) { Capabilities cap = ((RemoteWebDriver) driver).getCapabilities(); return cap.getVersion().toString(); }
<<<<<<< public static synchronized void associateCanonicTestName(String test) { threadId2CanonicTestName.put(Thread.currentThread().getId(), test); } public static String getCanonicTestNameByThread() { return getCanonicTestNameByThread(Thread.currentThread().getId()); } public static String getCanonicTestNameByThread(long threadId) { return threadId2CanonicTestName.get(threadId); } ======= public static synchronized void associateBug(String testName, String id) { testName2Bug.put(testName, id); } public static synchronized String getBug(String testName) { return testName2Bug.get(testName); } >>>>>>> public static synchronized void associateCanonicTestName(String test) { threadId2CanonicTestName.put(Thread.currentThread().getId(), test); } public static String getCanonicTestNameByThread() { return getCanonicTestNameByThread(Thread.currentThread().getId()); } public static String getCanonicTestNameByThread(long threadId) { return threadId2CanonicTestName.get(threadId); } public static synchronized void associateBug(String testName, String id) { testName2Bug.put(testName, id); } public static synchronized String getBug(String testName) { return testName2Bug.get(testName); }
<<<<<<< import java.text.SimpleDateFormat; ======= >>>>>>> <<<<<<< protected boolean isVideoEnabled() { return R.CONFIG.getBoolean(SpecialKeywords.ENABLE_VIDEO); ======= /** * Retrieves VNC URL if available. * * @param driver - {@link RemoteWebDriver} instance * @return VNC URL */ abstract public String getVncURL(WebDriver driver); /** * Returns bitrate by {@link VideoQuality} * * @param quality - video quality for recording * @return appropriate bitrate */ abstract protected int getBitrate(VideoQuality quality); /** * Initialize test artifact. * @param name - artifact name * @param url - artifact url * @return test artifact with video details */ protected TestArtifactType initArtifact(String name, String url) { TestArtifactType artifact = new TestArtifactType(); artifact.setName(name); artifact.setLink(url); return artifact; } protected boolean isEnabled(String capability) { return R.CONFIG.getBoolean(capability); >>>>>>> protected boolean isEnabled(String capability) { return R.CONFIG.getBoolean(capability);
<<<<<<< import org.openqa.selenium.Platform; import org.openqa.selenium.Proxy; ======= >>>>>>> <<<<<<< public static synchronized WebDriver create(String testName, Device device) { RemoteWebDriver driver = null; DesiredCapabilities capabilities = null; String selenium = Configuration.get(Parameter.SELENIUM_HOST); try { String browser = Configuration.get(Parameter.BROWSER); if (BrowserType.FIREFOX.equalsIgnoreCase(browser)) { capabilities = getFirefoxCapabilities(testName, Configuration.get(Parameter.BROWSER_VERSION)); } else if (BrowserType.IEXPLORE.equalsIgnoreCase(browser) || BrowserType.IE.equalsIgnoreCase(browser) || browser.equalsIgnoreCase("ie")) { capabilities = getInternetExplorerCapabilities(testName, Configuration.get(Parameter.BROWSER_VERSION)); } else if (HTML_UNIT.equalsIgnoreCase(browser)) { capabilities = getHtmlUnitCapabilities(testName); } else if (MOBILE_GRID.equalsIgnoreCase(browser)) { if (!Configuration.get(Parameter.MOBILE_BROWSER_NAME).isEmpty()) { capabilities = getMobileWebCapabilities(true, testName, Configuration.get(Parameter.MOBILE_PLATFORM_NAME), Configuration.get(Parameter.MOBILE_PLATFORM_VERSION), Configuration.get(Parameter.MOBILE_DEVICE_NAME), Configuration.get(Parameter.MOBILE_AUTOMATION_NAME), Configuration.get(Parameter.MOBILE_NEW_COMMAND_TIMEOUT), Configuration.get(Parameter.MOBILE_BROWSER_NAME)); } else { capabilities = getMobileAppCapabilities(true, testName, Configuration.get(Parameter.MOBILE_PLATFORM_NAME), Configuration.get(Parameter.MOBILE_PLATFORM_VERSION), Configuration.get(Parameter.MOBILE_DEVICE_NAME), Configuration.get(Parameter.MOBILE_AUTOMATION_NAME), Configuration.get(Parameter.MOBILE_NEW_COMMAND_TIMEOUT), Configuration.get(Parameter.MOBILE_APP), Configuration.get(Parameter.MOBILE_APP_ACTIVITY), Configuration.get(Parameter.MOBILE_APP_PACKAGE)); } } else if (MOBILE_POOL.equalsIgnoreCase(browser) || MOBILE.equalsIgnoreCase(browser)) { // 1. parse mobile_devices // 2. verify status for each selenium/appium server // 3. !adjust thread count if possible or organize delays when all devices are busy // 4. create driver using any free device if (!Configuration.get(Parameter.MOBILE_BROWSER_NAME).isEmpty()) { selenium = device.getSeleniumServer(); capabilities = getMobileWebCapabilities(false, testName, device.getOs(), device.getOsVersion(), device.getName(), Configuration.get(Parameter.MOBILE_AUTOMATION_NAME), Configuration.get(Parameter.MOBILE_NEW_COMMAND_TIMEOUT), Configuration.get(Parameter.MOBILE_BROWSER_NAME)); } else { selenium = device.getSeleniumServer(); capabilities = getMobileAppCapabilities(false, testName, device.getOs(), device.getOsVersion(), device.getName(), Configuration.get(Parameter.MOBILE_AUTOMATION_NAME), Configuration.get(Parameter.MOBILE_NEW_COMMAND_TIMEOUT), Configuration.get(Parameter.MOBILE_APP), Configuration.get(Parameter.MOBILE_APP_ACTIVITY), Configuration.get(Parameter.MOBILE_APP_PACKAGE)); } } else if (SAFARI.equalsIgnoreCase(browser)) { capabilities = getSafariCapabilities(testName, Configuration.get(Parameter.BROWSER_VERSION)); } else { capabilities = getChromeCapabilities(testName, Configuration.get(Parameter.BROWSER_VERSION)); } LOGGER.debug("-------------------------------------- Driver Factory start ----------------------------------"); if (browser.toLowerCase().contains(MOBILE.toLowerCase())) { //only in case of "mobile" or "mobile_grid" as browser and ANDROID as mobile_platform_name String mobile_platform_name = Configuration.get(Parameter.MOBILE_PLATFORM_NAME); if (mobile_platform_name.toLowerCase().equals("android")) driver = new AndroidDriver(new URL(selenium), capabilities); else if (mobile_platform_name.toLowerCase().equals("ios")) { driver = new IOSDriver(new URL(selenium), capabilities); } } else { String PROXY = Configuration.get(Parameter.PROXY_SERVER); if (!StringUtils.EMPTY.equals(PROXY)) { Proxy proxy = new Proxy(); proxy.setHttpProxy(PROXY).setFtpProxy(PROXY).setSslProxy(PROXY); capabilities.setCapability(CapabilityType.PROXY, proxy); } if (staticCapabilities != null) { capabilities.merge(staticCapabilities); } driver = new RemoteWebDriver(new URL(selenium), capabilities); } LOGGER.debug("-------------------------------------- Driver Factory finish ---------------------------------"); } catch (Exception e) { LOGGER.debug("Unable to initialize driver. Test will be SKIPPED due to the\r\n", e); throw new SkipException("Unable to initialize driver. Test will be SKIPPED due to the\r\n" + e.getMessage()); } return driver; } public static DesiredCapabilities getMobileAppCapabilities(boolean gridMode, String testName, String platform, String platformVersion, String deviceName, String automationName, String commandTimeout, String app, String appActivity, String appPackage) { return getMobileCapabilities(gridMode, testName, platform, platformVersion, deviceName, automationName, commandTimeout, null, app, appActivity, appPackage); } public static DesiredCapabilities getMobileWebCapabilities(boolean gridMode, String testName, String platform, String platformVersion, String deviceName, String automationName, String commandTimeout, String browserName) { return getMobileCapabilities(gridMode, testName, platform, platformVersion, deviceName, automationName, commandTimeout, browserName, null, null, null); } private static DesiredCapabilities getMobileCapabilities(boolean gridMode, String testName, String platform, String platformVersion, String deviceName, String automationName, String commandTimeout, String browserName, String app, String appActivity, String appPackage) { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("platformName", platform); //Parameter.MOBILE_PLATFORM_NAME capabilities.setCapability("platformVersion", platformVersion); //Parameter.MOBILE_PLATFORM_VERSION if (deviceName != null) capabilities.setCapability("deviceName", deviceName); //Parameter.MOBILE_DEVICE_NAME capabilities.setCapability("automationName", automationName); //Parameter.MOBILE_AUTOMATION_NAME capabilities.setCapability("newCommandTimeout", commandTimeout); //Parameter.MOBILE_NEW_COMMAND_TIMEOUT if (gridMode) { capabilities.setCapability("platform", platform); capabilities.setCapability("version", platformVersion); capabilities.setCapability("browserName", deviceName); } ======= public static WebDriver create(String testName, Device device) { AbstractFactory factory; String driverType = Configuration.get(Parameter.DRIVER_TYPE); if (driverType.equalsIgnoreCase(SpecialKeywords.DESKTOP)) { factory = new DesktopFactory(); } else if (driverType.equalsIgnoreCase(SpecialKeywords.MOBILE) || driverType.equalsIgnoreCase(SpecialKeywords.MOBILE_POOL) || driverType.equalsIgnoreCase(SpecialKeywords.MOBILE_GRID)) { factory = new MobileFactory(); } else { throw new RuntimeException("Unsupported driver_type: " + driverType + "!"); } return factory.create(testName, device); } >>>>>>> public static WebDriver create(String testName, Device device) { AbstractFactory factory; String driverType = Configuration.get(Parameter.DRIVER_TYPE); if (driverType.equalsIgnoreCase(SpecialKeywords.DESKTOP)) { factory = new DesktopFactory(); } else if (driverType.equalsIgnoreCase(SpecialKeywords.MOBILE) || driverType.equalsIgnoreCase(SpecialKeywords.MOBILE_POOL) || driverType.equalsIgnoreCase(SpecialKeywords.MOBILE_GRID)) { factory = new MobileFactory(); } else { throw new RuntimeException("Unsupported driver_type: " + driverType + "!"); } return factory.create(testName, device); } <<<<<<< private static DesiredCapabilities initBaseCapabilities(DesiredCapabilities capabilities, String browser, String browserVersion, String testName) { //platform should be detected and provided into capabilities automatically String platform = Configuration.get(Parameter.PLATFORM); if (!platform.equals("*")) { capabilities.setPlatform(Platform.extractFromSysProperty(platform)); } capabilities.setBrowserName(browser); capabilities.setVersion(browserVersion); capabilities.setCapability("name", testName); return capabilities; } public static void addCapability(String name, Object value) { if (staticCapabilities == null) { staticCapabilities = new DesiredCapabilities(); } staticCapabilities.setCapability(name, value); } ======= >>>>>>>
<<<<<<< import org.openqa.selenium.support.FindBys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; ======= import org.apache.log4j.Logger; >>>>>>> import org.slf4j.Logger; import org.slf4j.LoggerFactory; <<<<<<< import com.qaprosoft.carina.core.foundation.utils.mobile.IMobileUtils; ======= >>>>>>> <<<<<<< notificationList = notificationsOtherDevices; } LOGGER.info("Visible Notifications size:" + notificationList.size()); for (ExtendedWebElement notification : notificationList) { point = notification.getElement().getLocation(); dim = notification.getElement().getSize(); x1 = point.x + dim.width / 6; x2 = point.x + dim.width * 5 / 6; y1 = y2 = point.y + dim.height / 2; swipe(x1, y1, x2, y2, SWIPE_DURATION); ======= LOGGER.info("'Dismiss All Notifications' Button is present but disabled, meaning any alerts displayed are not closable. Collapsing tray..."); pressBack(); >>>>>>> LOGGER.info("'Dismiss All Notifications' Button is present but disabled, meaning any alerts displayed are not closable. Collapsing tray..."); pressBack(); <<<<<<< return isOpened(IMobileUtils.EXPLICIT_TIMEOUT); ======= return isOpened(DriverHelper.EXPLICIT_TIMEOUT); >>>>>>> return isOpened(DriverHelper.EXPLICIT_TIMEOUT);
<<<<<<< import java.lang.invoke.MethodHandles; ======= import java.io.IOException; >>>>>>> import java.io.IOException; import java.lang.invoke.MethodHandles;
<<<<<<< import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransform; import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformMember; import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformTypes; ======= import org.broadleafcommerce.common.i18n.service.DynamicTranslationProvider; >>>>>>> import org.broadleafcommerce.common.i18n.service.DynamicTranslationProvider; import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransform; import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformMember; import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformTypes;
<<<<<<< @DirectCopyTransform({ @DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.SANDBOX, skipOverlaps=true), @DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.MULTITENANT_SITE) }) public class StructuredContentImpl implements StructuredContent, AdminMainEntity { ======= @Cache(usage= CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blCMSElements") public class StructuredContentImpl implements StructuredContent { >>>>>>> @DirectCopyTransform({ @DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.SANDBOX, skipOverlaps=true), @DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.MULTITENANT_SITE) }) @Cache(usage= CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blCMSElements") public class StructuredContentImpl implements StructuredContent, AdminMainEntity {
<<<<<<< import org.broadleafcommerce.core.catalog.dao.SkuDao; import org.broadleafcommerce.core.catalog.domain.Category; import org.broadleafcommerce.core.catalog.domain.CategoryProductXref; ======= >>>>>>> import org.broadleafcommerce.core.catalog.dao.SkuDao; <<<<<<< Long numItemsToIndex = null; if (useSku) { numItemsToIndex = skuDao.readCountAllActiveSkus(); } else { numItemsToIndex = productDao.readCountAllActiveProducts(); } ======= final Long numProducts = productDao.readCountAllActiveProducts(); >>>>>>> final Long numItemsToIndex; if (useSku) { numItemsToIndex = skuDao.readCountAllActiveSkus(); } else { numItemsToIndex = productDao.readCountAllActiveProducts(); } <<<<<<< int page = 0; while ((page * pageSize) < numItemsToIndex) { buildIncrementalIndex(page, pageSize); page++; } ======= performCachedOperation(new SolrIndexCachedOperation.CacheOperation() { @Override public void execute() throws ServiceException { int page = 0; while ((page * pageSize) < numProducts) { buildIncrementalIndex(page, pageSize); page++; } } }); >>>>>>> int page = 0; while ((page * pageSize) < numItemsToIndex) { buildIncrementalIndex(page, pageSize); page++; } performCachedOperation(new SolrIndexCachedOperation.CacheOperation() { @Override public void execute() throws ServiceException { int page = 0; while ((page * pageSize) < numItemsToIndex) { buildIncrementalIndex(page, pageSize); page++; } } }); <<<<<<< Collection<SolrInputDocument> documents = new ArrayList<SolrInputDocument>(); ======= CatalogStructure cache = SolrIndexCachedOperation.getCache(); if (cache != null) { cacheOperationManaged = true; } else { cache = new CatalogStructure(); SolrIndexCachedOperation.setCache(cache); } List<Product> products = readAllActiveProducts(page, pageSize); List<Long> productIds = BLCCollectionUtils.collectList(products, new TypedTransformer<Long>() { @Override public Long transform(Object input) { return ((Product) input).getId(); } }); solrIndexDao.populateCatalogStructure(productIds, SolrIndexCachedOperation.getCache()); List<Field> fields = fieldDao.readAllProductFields(); >>>>>>> Collection<SolrInputDocument> documents = new ArrayList<SolrInputDocument>(); <<<<<<< protected void attachBasicDocumentFields(Product product, Sku sku, SolrInputDocument document) { // Add the namespace and ID fields for this product document.addField(shs.getNamespaceFieldName(), shs.getCurrentNamespace()); if (useSku) { document.addField(shs.getIdFieldName(), shs.getSolrDocumentId(document, sku)); document.addField(shs.getSkuIdFieldName(), sku.getId()); product = sku.getProduct(); } else { document.addField(shs.getIdFieldName(), shs.getSolrDocumentId(document, product)); } document.addField(shs.getProductIdFieldName(), product.getId()); extensionManager.getProxy().attachAdditionalBasicFields(product, document, shs); // The explicit categories are the ones defined by the product itself for (CategoryProductXref categoryXref : product.getAllParentCategoryXrefs()) { document.addField(shs.getExplicitCategoryFieldName(), shs.getCategoryId(categoryXref.getCategory().getId())); String categorySortFieldName = shs.getCategorySortFieldName(categoryXref.getCategory()); int index = -1; int count = 0; for (CategoryProductXref productXref : categoryXref.getCategory().getAllProductXrefs()) { if (productXref.getProduct().equals(product)) { index = count; break; } count++; ======= protected void attachBasicDocumentFields(Product product, SolrInputDocument document) { boolean cacheOperationManaged = false; try { CatalogStructure cache = SolrIndexCachedOperation.getCache(); if (cache != null) { cacheOperationManaged = true; } else { cache = new CatalogStructure(); SolrIndexCachedOperation.setCache(cache); solrIndexDao.populateCatalogStructure(Arrays.asList(product.getId()), SolrIndexCachedOperation.getCache()); >>>>>>> protected void attachBasicDocumentFields(Sku sku, SolrInputDocument document) { boolean cacheOperationManaged = false; Product product = sku.getProduct(); try { CatalogStructure cache = SolrIndexCachedOperation.getCache(); if (cache != null) { cacheOperationManaged = true; } else { cache = new CatalogStructure(); SolrIndexCachedOperation.setCache(cache); solrIndexDao.populateProductCatalogStructure(Arrays.asList(sku.getId()), SolrIndexCachedOperation.getCache()); } // Add the namespace and ID fields for this product document.addField(shs.getNamespaceFieldName(), shs.getCurrentNamespace()); document.addField(shs.getIdFieldName(), shs.getSolrDocumentId(document, sku)); document.addField(shs.getSkuIdFieldName(), sku.getId()); extensionManager.getProxy().attachAdditionalBasicFields(sku, document, shs); // The explicit categories are the ones defined by the product itself if (cache.getParentCategoriesByProduct().containsKey(product.getId())) { for (Long categoryId : cache.getParentCategoriesByProduct().get(product.getId())) { document.addField(shs.getExplicitCategoryFieldName(), shs.getCategoryId(categoryId)); String categorySortFieldName = shs.getCategorySortFieldName(shs.getCategoryId(categoryId)); String displayOrderKey = categoryId + "-" + shs.getProductId(product.getId()); BigDecimal displayOrder = cache.getDisplayOrdersByCategoryProduct().get(displayOrderKey); if (displayOrder == null) { displayOrderKey = categoryId + "-" + product.getId(); displayOrder = cache.getDisplayOrdersByCategoryProduct().get(displayOrderKey); } if (document.getField(categorySortFieldName) == null) { document.addField(categorySortFieldName, displayOrder); } // This is the entire tree of every category defined on the product buildFullCategoryHierarchy(document, cache, categoryId); } } } finally { if (!cacheOperationManaged) { SolrIndexCachedOperation.clearCache(); } } } protected void attachBasicDocumentFields(Product product, SolrInputDocument document) { boolean cacheOperationManaged = false; try { CatalogStructure cache = SolrIndexCachedOperation.getCache(); if (cache != null) { cacheOperationManaged = true; } else { cache = new CatalogStructure(); SolrIndexCachedOperation.setCache(cache); solrIndexDao.populateProductCatalogStructure(Arrays.asList(product.getId()), SolrIndexCachedOperation.getCache());
<<<<<<< setAuditCreatedBy(entity, new AdminAuditable()); ======= if (entity.getClass().isAnnotationPresent(Entity.class)) { Field field = getSingleField(entity.getClass(), getAuditableFieldName()); field.setAccessible(true); if (field.isAnnotationPresent(Embedded.class)) { Object auditable = field.get(entity); if (auditable == null) { field.set(entity, new AdminAuditable()); auditable = field.get(entity); } Field temporalCreatedField = auditable.getClass().getDeclaredField("dateCreated"); Field temporalUpdatedField = auditable.getClass().getDeclaredField("dateUpdated"); Field agentField = auditable.getClass().getDeclaredField("createdBy"); setAuditValueTemporal(temporalCreatedField, auditable); setAuditValueTemporal(temporalUpdatedField, auditable); setAuditValueAgent(agentField, auditable); } } >>>>>>> setAuditCreatedBy(entity, new AdminAuditable()); <<<<<<< setAuditUpdatedBy(entity, new AdminAuditable()); ======= if (entity.getClass().isAnnotationPresent(Entity.class)) { Field field = getSingleField(entity.getClass(), getAuditableFieldName()); field.setAccessible(true); if (field.isAnnotationPresent(Embedded.class)) { Object auditable = field.get(entity); if (auditable == null) { field.set(entity, new AdminAuditable()); auditable = field.get(entity); } Field temporalField = auditable.getClass().getDeclaredField("dateUpdated"); Field agentField = auditable.getClass().getDeclaredField("updatedBy"); setAuditValueTemporal(temporalField, auditable); setAuditValueAgent(agentField, auditable); } } } protected void setAuditValueTemporal(Field field, Object entity) throws IllegalArgumentException, IllegalAccessException { Calendar cal = SystemTime.asCalendar(); field.setAccessible(true); field.set(entity, cal.getTime()); >>>>>>> setAuditUpdatedBy(entity, new AdminAuditable()); } protected void setAuditValueTemporal(Field field, Object entity) throws IllegalArgumentException, IllegalAccessException { Calendar cal = SystemTime.asCalendar(); field.setAccessible(true); field.set(entity, cal.getTime());
<<<<<<< ======= * Returns a prefix if required for the passed in facet. */ ExtensionResultStatusType buildPrefixListForSearchableFacet(Field field, List<String> prefixList); /** >>>>>>> <<<<<<< public ExtensionResultStatusType buildPrefixListForIndexField(IndexField field, FieldType fieldType, ======= ExtensionResultStatusType buildPrefixListForSearchableField(Field field, FieldType searchableFieldType, >>>>>>> ExtensionResultStatusType buildPrefixListForIndexField(IndexField field, FieldType fieldType, <<<<<<< ======= * Given the input field, populates the values array with the fields needed for the * passed in field. * * For example, a handler might create multiple fields for the given passed in field. * @param product * @param field * @param values * @param propertyName * @param locales * @return * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ ExtensionResultStatusType addPropertyValues(Product product, Field field, FieldType fieldType, Map<String, Object> values, String propertyName, List<Locale> locales) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException; /** * Given the input field, populates the values array with the fields needed for the * passed in field. * * For example, a handler might create multiple fields for the given passed in field. * @param sku * @param field * @param values * @param propertyName * @param locales * @return * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ ExtensionResultStatusType addPropertyValues(Sku sku, Field field, FieldType fieldType, Map<String, Object> values, String propertyName, List<Locale> locales) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException; /** >>>>>>> <<<<<<< * In certain scenarios, the requested category id might not be the one that should be used in Solr. ======= * Allows the extension additional fields to the document that are not configured via the DB. */ ExtensionResultStatusType attachAdditionalBasicFields(Product product, SolrInputDocument document, SolrHelperService shs); /** * Allows the extension additional fields to the document that are not configured via the DB. */ ExtensionResultStatusType attachAdditionalBasicFields(Sku sku, SolrInputDocument document, SolrHelperService shs); /** * In certain scenarios, we may want to produce a different Solr document id than the default. >>>>>>> * In certain scenarios, the requested category id might not be the one that should be used in Solr. <<<<<<< public ExtensionResultStatusType getCategoryId(Category category, Long[] returnContainer); ======= ExtensionResultStatusType getSolrDocumentId(SolrInputDocument document, Product product, String[] returnContainer); >>>>>>> ExtensionResultStatusType getCategoryId(Category category, Long[] returnContainer); <<<<<<< public ExtensionResultStatusType getQueryField(SolrQuery query, SearchCriteria searchCriteria, IndexFieldType indexFieldType, ExtensionResultHolder<List<String>> queryFieldsResult); ======= ExtensionResultStatusType getSolrDocumentId(SolrInputDocument document, Sku sku, String[] returnContainer); >>>>>>> ExtensionResultStatusType getQueryField(SolrQuery query, SearchCriteria searchCriteria, IndexFieldType indexFieldType, ExtensionResultHolder<List<String>> queryFieldsResult); <<<<<<< public ExtensionResultStatusType modifySearchResults(List<SolrDocument> responseDocuments, List<Product> products); ======= ExtensionResultStatusType getCategoryId(Category category, Long[] returnContainer); >>>>>>> ExtensionResultStatusType modifySearchResults(List<SolrDocument> responseDocuments, List<Product> products); <<<<<<< public ExtensionResultStatusType getSearchFacets(List<SearchFacet> searchFacets); ======= ExtensionResultStatusType getCategoryId(Long category, Long[] returnContainer); >>>>>>> ExtensionResultStatusType getSearchFacets(List<SearchFacet> searchFacets); <<<<<<< public ExtensionResultStatusType attachFacet(SolrQuery query, String indexField, SearchFacetDTO dto); ======= ExtensionResultStatusType getProductId(Product product, Long[] returnContainer); >>>>>>> ExtensionResultStatusType attachFacet(SolrQuery query, String indexField, SearchFacetDTO dto); <<<<<<< public ExtensionResultStatusType getCategorySearchFacets(Category category, List<SearchFacet> searchFacets); /** * Populated the List of searchable IndexField's that will be used in building the query fields (qf) for a Solr query. * It is assumed that if the result of this call is NOT_HANDLED, then SolrSearchService will follow it's default behavior * for populating IndexFields. * * @param fields the List to be populated. * @return HANDLED_CONTINUE if it added field, NOT_HANDLED otherwise */ public ExtensionResultStatusType getSearchableIndexFields(List<IndexField> fields); ======= ExtensionResultStatusType endBatchEvent(); /** * Batch fetch important collections for the entire list of products in single batch fetch queries. In general, this is intended * to be used for search results and category landing page results. For batch fetching during solr indexing, see * {@link #startBatchEvent(List)}. * * @param products * @return */ ExtensionResultStatusType batchFetchCatalogData(List<Product> products); >>>>>>> ExtensionResultStatusType getCategorySearchFacets(Category category, List<SearchFacet> searchFacets); /** * Populated the List of searchable IndexField's that will be used in building the query fields (qf) for a Solr query. * It is assumed that if the result of this call is NOT_HANDLED, then SolrSearchService will follow it's default behavior * for populating IndexFields. * * @param fields the List to be populated. * @return HANDLED_CONTINUE if it added field, NOT_HANDLED otherwise */ ExtensionResultStatusType getSearchableIndexFields(List<IndexField> fields); /** * Perform actions at the start of a batch to improve performance of Solr search for the list of batch products. * For example we want to get, in bulk, the SkuPriceData for each product and save these in memory by default. This * is intended for usage while performing a solr index. For search results and category landing page results, * see {@link #batchFetchCatalogData(List)}. * * @param products * @return */ ExtensionResultStatusType startBatchEvent(List<Product> products); /** * Perform actions to end a batch event, such as closing any Contexts that have been previously created. * * @return */ ExtensionResultStatusType endBatchEvent(); /** * Batch fetch important collections for the entire list of products in single batch fetch queries. In general, this is intended * to be used for search results and category landing page results. For batch fetching during solr indexing, see * {@link #startBatchEvent(List)}. * * @param products * @return */ ExtensionResultStatusType batchFetchCatalogData(List<Product> products);
<<<<<<< import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; ======= >>>>>>>
<<<<<<< import org.broadleafcommerce.common.admin.domain.AdminMainEntity; ======= import org.apache.commons.collections.MapUtils; >>>>>>> import org.apache.commons.collections.MapUtils; import org.broadleafcommerce.common.admin.domain.AdminMainEntity; <<<<<<< ======= import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; >>>>>>> import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; <<<<<<< @Transactional("blTransactionManager") public PersistenceResponse updateEntity(EntityForm entityForm, String[] customCriteria) throws ServiceException { ======= @Transactional(value = "blTransactionManager", rollbackFor = {ServiceException.class}) public Entity updateEntity(EntityForm entityForm, String[] customCriteria) throws ServiceException { PersistencePackageRequest ppr = getRequestForEntityForm(entityForm, customCriteria); Entity returnEntity = update(ppr); >>>>>>> @Transactional(value = "blTransactionManager", rollbackFor = {ServiceException.class}) public PersistenceResponse updateEntity(EntityForm entityForm, String[] customCriteria) throws ServiceException { PersistencePackageRequest ppr = getRequestForEntityForm(entityForm, customCriteria); PersistenceResponse response = update(ppr); <<<<<<< PersistencePackageRequest ppr = getRequestForEntityForm(entityForm, customCriteria); ppr.setRequestingEntityName(entityForm.getMainEntityName()); // Add the validation errors from the dynamic forms prior to invoking update. This way, errors will be // caught downstream and will prevent an actual save ppr.getEntity().getValidationErrors().putAll(dynamicFormValidationErrors); // After the dynamic forms have had a chance to update (and potentially fail validation), update the main entity PersistenceResponse response = update(ppr); return response; ======= >>>>>>>
<<<<<<< for (ProductOptionValue option : allowedValues) { ======= // Check to make sure there is at least 1 Allowed Value, else prevent generation if (currentOption.getAllowedValues().isEmpty()) { return null; } for (ProductOptionValue option : currentOption.getAllowedValues()) { >>>>>>> // Check to make sure there is at least 1 Allowed Value, else prevent generation if (currentOption.getAllowedValues().isEmpty()) { return null; } for (ProductOptionValue option : allowedValues) {
<<<<<<< import javax.persistence.criteria.Path; ======= import javax.persistence.criteria.Join; >>>>>>> import javax.persistence.criteria.Path; import javax.persistence.criteria.Join; <<<<<<< @Override public List<Long> readSkuIdsForProductOptionValues(Long productId, String attributeName, String attributeValue, List<Long> possibleSkuIds) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> criteria = cb.createQuery(Long.class); Root<SkuProductOptionValueXrefImpl> root = criteria.from(SkuProductOptionValueXrefImpl.class); criteria.select(root.get("sku").get("id").as(Long.class)); List<Predicate> predicates = new ArrayList<>(); // restrict archived values predicates.add(cb.or(cb.notEqual(root.get("sku").get("archiveStatus").get("archived"), 'Y'), cb.isNull(root.get("sku").get("archiveStatus").get("archived")))); // restrict to skus that match the product predicates.add(root.get("sku").get("product").get("id").in(sandBoxHelper.mergeCloneIds(ProductImpl.class, productId))); // restrict to skus that match the attributeName predicates.add(cb.equal(root.get("productOptionValue").get("productOption").get("attributeName"), attributeName)); // restrict to skus that match the attributeValue predicates.add(cb.equal(root.get("productOptionValue").get("attributeValue"), attributeValue)); // restrict to skus that have ids within the given list of skus ids Predicate skuDomainPredicate = buildSkuDomainPredicate(cb, root.get("sku").get("id"), possibleSkuIds); if (skuDomainPredicate != null) { predicates.add(skuDomainPredicate); } criteria.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))); TypedQuery<Long> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } @SuppressWarnings("unchecked") protected Predicate buildSkuDomainPredicate(CriteriaBuilder cb, Path fieldName, List<Long> possibleSkuIds) { int listSize = possibleSkuIds.size(); Predicate predicate = null; for (int i = 0; i < listSize; i += IN_CLAUSE_LIMIT) { List subList; if (listSize > i + IN_CLAUSE_LIMIT) { subList = possibleSkuIds.subList(i, (i + IN_CLAUSE_LIMIT)); } else { subList = possibleSkuIds.subList(i, listSize); } if (predicate == null) { predicate = fieldName.in(subList); } else { predicate = cb.or(predicate, fieldName.in(subList)); } } return predicate; } ======= @Override public Long countProductsUsingProductOptionById(Long productOptionId) { TypedQuery<Long> query = getProductIdsUsingProductOptionByIdQuery(productOptionId, true); query.setHint(QueryHints.HINT_CACHEABLE, true); return query.getSingleResult(); } @Override public List<Long> findProductIdsUsingProductOptionById(Long productOptionId, int start, int pageSize) { TypedQuery<Long> query = getProductIdsUsingProductOptionByIdQuery(productOptionId, false); query.setFirstResult(start); query.setMaxResults(pageSize); query.setHint(QueryHints.HINT_CACHEABLE, true); return query.getResultList(); } private TypedQuery<Long> getProductIdsUsingProductOptionByIdQuery(Long productOptionId, boolean count) { // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); // The root of our search is ProductOptionXref Root<ProductOptionXrefImpl> productOptionXref = criteria.from(ProductOptionXrefImpl.class); Join<ProductOptionXref, Product> product = productOptionXref.join("product"); Join<ProductOptionXref, ProductOption> productOption = productOptionXref.join("productOption"); if (count) { criteria.select(builder.count(product)); } else { // Product IDs are what we want back criteria.select(product.get("id").as(Long.class)); } criteria.distinct(true); List<Predicate> restrictions = new ArrayList<Predicate>(); restrictions.add(productOption.get("id").in(sandBoxHelper.mergeCloneIds(ProductOptionImpl.class, productOptionId))); // Execute the query with the restrictions criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); return em.createQuery(criteria); } >>>>>>> @Override public List<Long> readSkuIdsForProductOptionValues(Long productId, String attributeName, String attributeValue, List<Long> possibleSkuIds) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> criteria = cb.createQuery(Long.class); Root<SkuProductOptionValueXrefImpl> root = criteria.from(SkuProductOptionValueXrefImpl.class); criteria.select(root.get("sku").get("id").as(Long.class)); List<Predicate> predicates = new ArrayList<>(); // restrict archived values predicates.add(cb.or(cb.notEqual(root.get("sku").get("archiveStatus").get("archived"), 'Y'), cb.isNull(root.get("sku").get("archiveStatus").get("archived")))); // restrict to skus that match the product predicates.add(root.get("sku").get("product").get("id").in(sandBoxHelper.mergeCloneIds(ProductImpl.class, productId))); // restrict to skus that match the attributeName predicates.add(cb.equal(root.get("productOptionValue").get("productOption").get("attributeName"), attributeName)); // restrict to skus that match the attributeValue predicates.add(cb.equal(root.get("productOptionValue").get("attributeValue"), attributeValue)); // restrict to skus that have ids within the given list of skus ids Predicate skuDomainPredicate = buildSkuDomainPredicate(cb, root.get("sku").get("id"), possibleSkuIds); if (skuDomainPredicate != null) { predicates.add(skuDomainPredicate); } criteria.where(cb.and(predicates.toArray(new Predicate[predicates.size()]))); TypedQuery<Long> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getResultList(); } @SuppressWarnings("unchecked") protected Predicate buildSkuDomainPredicate(CriteriaBuilder cb, Path fieldName, List<Long> possibleSkuIds) { int listSize = possibleSkuIds.size(); Predicate predicate = null; for (int i = 0; i < listSize; i += IN_CLAUSE_LIMIT) { List subList; if (listSize > i + IN_CLAUSE_LIMIT) { subList = possibleSkuIds.subList(i, (i + IN_CLAUSE_LIMIT)); } else { subList = possibleSkuIds.subList(i, listSize); } if (predicate == null) { predicate = fieldName.in(subList); } else { predicate = cb.or(predicate, fieldName.in(subList)); } } return predicate; } @Override public Long countProductsUsingProductOptionById(Long productOptionId) { TypedQuery<Long> query = getProductIdsUsingProductOptionByIdQuery(productOptionId, true); query.setHint(QueryHints.HINT_CACHEABLE, true); return query.getSingleResult(); } @Override public List<Long> findProductIdsUsingProductOptionById(Long productOptionId, int start, int pageSize) { TypedQuery<Long> query = getProductIdsUsingProductOptionByIdQuery(productOptionId, false); query.setFirstResult(start); query.setMaxResults(pageSize); query.setHint(QueryHints.HINT_CACHEABLE, true); return query.getResultList(); } private TypedQuery<Long> getProductIdsUsingProductOptionByIdQuery(Long productOptionId, boolean count) { // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); // The root of our search is ProductOptionXref Root<ProductOptionXrefImpl> productOptionXref = criteria.from(ProductOptionXrefImpl.class); Join<ProductOptionXref, Product> product = productOptionXref.join("product"); Join<ProductOptionXref, ProductOption> productOption = productOptionXref.join("productOption"); if (count) { criteria.select(builder.count(product)); } else { // Product IDs are what we want back criteria.select(product.get("id").as(Long.class)); } criteria.distinct(true); List<Predicate> restrictions = new ArrayList<Predicate>(); restrictions.add(productOption.get("id").in(sandBoxHelper.mergeCloneIds(ProductOptionImpl.class, productOptionId))); // Execute the query with the restrictions criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); return em.createQuery(criteria); }
<<<<<<< tx.setBlockHeight(height); ValidateResult validateResult = blockTxsValidate(chainId, tx, batchValidateTxSet, accountValidateTxMap, accountStateMap, lockedCancelNonceMap); ======= ValidateResult validateResult = blockTxsValidate(chainId, tx, batchValidateTxSet, accountValidateTxMap, accountStateMap, lockedCancelNonceMap, lockedTimeMap, lockedHeightMap); >>>>>>> tx.setBlockHeight(height); ValidateResult validateResult = blockTxsValidate(chainId, tx, batchValidateTxSet, accountValidateTxMap, accountStateMap, lockedCancelNonceMap, lockedTimeMap, lockedHeightMap); <<<<<<< Map<String, AccountState> accountStateMap, Map<String, AccountState> balanceValidateMap) { // 判断硬分叉,需要一个高度 long hardForkingHeight = 878000; boolean forked = blockHeight <= 0 || blockHeight > hardForkingHeight; ======= Map<String, AccountState> accountStateMap, Map<String, AccountState> balanceValidateMap, String txHash) { >>>>>>> Map<String, AccountState> accountStateMap, Map<String, AccountState> balanceValidateMap, String txHash) { // 判断硬分叉,需要一个高度 long hardForkingHeight = 878000; boolean forked = blockHeight <= 0 || blockHeight > hardForkingHeight; <<<<<<< ValidateResult validateResult = analysisFromCoinPerTx(chainId, tx.getType(), tx.getBlockHeight(), nonce8Bytes, coinFroms, accountValidateTxMap, accountStateMap, balanceValidateMap); ======= ValidateResult validateResult = analysisFromCoinPerTx(chainId, tx.getType(), nonce8Bytes, coinFroms, accountValidateTxMap, accountStateMap, balanceValidateMap, txHash); >>>>>>> ValidateResult validateResult = analysisFromCoinPerTx(chainId, tx.getType(), tx.getBlockHeight(), nonce8Bytes, coinFroms, accountValidateTxMap, accountStateMap, balanceValidateMap, txHash); <<<<<<< private ValidateResult analysisFromCoinBlokTx(int chainId, int txType, long blockHeight, byte[] txNonce, List<CoinFrom> coinFroms, Map<String, List<TempAccountNonce>> accountValidateTxMap, Map<String, AccountState> accountStateMap, Map<String, Object> lockedCancelNonceMap) { // 判断硬分叉,需要一个高度 long hardForkingHeight = 878000; boolean forked = blockHeight <= 0 || blockHeight > hardForkingHeight; ======= private ValidateResult analysisFromCoinBlokTx(int chainId, int txType, byte[] txNonce, List<CoinFrom> coinFroms, Map<String, List<TempAccountNonce>> accountValidateTxMap, Map<String, AccountState> accountStateMap, Map<String, Object> lockedCancelNonceMap, Map<String, List<FreezeLockTimeState>> timeLockMap, Map<String, List<FreezeHeightState>> heightLockMap, String txHash) { >>>>>>> private ValidateResult analysisFromCoinBlokTx(int chainId, int txType, long blockHeight, byte[] txNonce, List<CoinFrom> coinFroms, Map<String, List<TempAccountNonce>> accountValidateTxMap, Map<String, AccountState> accountStateMap, Map<String, Object> lockedCancelNonceMap, Map<String, List<FreezeLockTimeState>> timeLockMap, Map<String, List<FreezeHeightState>> heightLockMap, String txHash) { // 判断硬分叉,需要一个高度 long hardForkingHeight = 878000; boolean forked = blockHeight <= 0 || blockHeight > hardForkingHeight; <<<<<<< ValidateResult fromCoinsValidateResult = analysisFromCoinBlokTx(chainId, tx.getType(), tx.getBlockHeight(), txNonce, coinFroms, accountValidateTxMap, accountStateMap, lockedCancelNonceMap); ======= ValidateResult fromCoinsValidateResult = analysisFromCoinBlokTx(chainId, tx.getType(), txNonce, coinFroms, accountValidateTxMap, accountStateMap, lockedCancelNonceMap, lockedTimeMap, lockedHeightMap, txHash); >>>>>>> ValidateResult fromCoinsValidateResult = analysisFromCoinBlokTx(chainId, tx.getType(), tx.getBlockHeight(), txNonce, coinFroms, accountValidateTxMap, accountStateMap, lockedCancelNonceMap, lockedTimeMap, lockedHeightMap, txHash);
<<<<<<< import junit.framework.TestCase; ======= import org.broadleafcommerce.common.service.GenericEntityService; >>>>>>> import junit.framework.TestCase; import org.broadleafcommerce.common.service.GenericEntityService; <<<<<<< protected PromotableOfferUtility promotableOfferUtility; ======= protected GenericEntityService genericEntityServiceMock; >>>>>>> protected PromotableOfferUtility promotableOfferUtility; protected GenericEntityService genericEntityServiceMock; <<<<<<< promotableOfferUtility = new PromotableOfferUtilityImpl(); ======= genericEntityServiceMock = EasyMock.createMock(GenericEntityService.class); >>>>>>> promotableOfferUtility = new PromotableOfferUtilityImpl(); genericEntityServiceMock = EasyMock.createMock(GenericEntityService.class); <<<<<<< offerServiceUtilities.setPromotableItemFactory(new PromotableItemFactoryImpl(promotableOfferUtility)); ======= offerServiceUtilities.setPromotableItemFactory(new PromotableItemFactoryImpl()); offerServiceUtilities.setGenericEntityService(genericEntityServiceMock); >>>>>>> offerServiceUtilities.setPromotableItemFactory(new PromotableItemFactoryImpl(promotableOfferUtility)); offerServiceUtilities.setGenericEntityService(genericEntityServiceMock);
<<<<<<< pp.setRequestingEntityName(request.getRequestingEntityName()); ======= pp.setValidateUnsubmittedProperties(request.isValidateUnsubmittedProperties()); >>>>>>> pp.setRequestingEntityName(request.getRequestingEntityName()); pp.setValidateUnsubmittedProperties(request.isValidateUnsubmittedProperties());
<<<<<<< entityForm = formService.buildAdornedListForm(fmd, ppr.getAdornedList(), id); entityForm.setCeilingEntityClassname(ppr.getAdornedList().getAdornedTargetEntityClassname()); ======= entityForm = formService.buildAdornedListForm(fmd, ppr.getAdornedList(), id, false); >>>>>>> entityForm = formService.buildAdornedListForm(fmd, ppr.getAdornedList(), id, false); entityForm.setCeilingEntityClassname(ppr.getAdornedList().getAdornedTargetEntityClassname());
<<<<<<< NulsDigestData hash = message.getHash(); ======= // if (message == null) { // chain.getLoggerMap().get(TxConstant.LOG_TX_MESSAGE).debug( // "recieve [newHash], message is null from node-{}, chainId:{}", nodeId, chainId); // return failed(TxErrorCode.PARAMETER_ERROR); // } NulsDigestData hash = message.getRequestHash(); >>>>>>> NulsDigestData hash = message.getHash(); <<<<<<< ======= // if (message == null) { // chain.getLoggerMap().get(TxConstant.LOG_TX_MESSAGE).debug( // "recieve [askTx], message is null from node-{}, chainId:{}", nodeId, chainId); // return failed(TxErrorCode.PARAMETER_ERROR); // } >>>>>>> <<<<<<< ======= // if (message == null) { // chain.getLoggerMap().get(TxConstant.LOG_TX_MESSAGE).debug( // "recieve [receiveTx], message is null from node-{}, chainId:{}", nodeId, chainId); // return failed(TxErrorCode.PARAMETER_ERROR); // } >>>>>>>
<<<<<<< joinEntityClass = "org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl", targetObjectProperty = "category", parentObjectProperty = "product", ======= sortProperty = "displayOrder", targetObjectProperty = "categoryProductXref.category", parentObjectProperty = "categoryProductXref.product", >>>>>>> sortProperty = "displayOrder", targetObjectProperty = "category", parentObjectProperty = "product",
<<<<<<< public String getTooltip(); public void setTooltip(String tooltip); public String getHelpText(); public void setHelpText(String helpText); public String getHint(); public void setHint(String hint); ======= public String getAdditionalForeignKeyClass(); public void setAdditionalForeignKeyClass(String className); >>>>>>> public String getTooltip(); public void setTooltip(String tooltip); public String getHelpText(); public void setHelpText(String helpText); public String getHint(); public void setHint(String hint); public String getAdditionalForeignKeyClass(); public void setAdditionalForeignKeyClass(String className);
<<<<<<< this.discountType.wrap(model.getDiscountType(), request); this.offerId = model.getId(); ======= this.discountType.wrapDetails(model.getDiscountType(), request); >>>>>>> this.discountType.wrapDetails(model.getDiscountType(), request); this.offerId = model.getId();
<<<<<<< OrderItem updateDiscreteOrderItem(OrderItem orderItem, DiscreteOrderItemRequest itemRequest); ======= public OrderItem createOrderItem(OrderItemRequest itemRequest); >>>>>>> public OrderItem updateDiscreteOrderItem(OrderItem orderItem, DiscreteOrderItemRequest itemRequest); public OrderItem createOrderItem(OrderItemRequest itemRequest);
<<<<<<< import org.broadleafcommerce.common.extension.ExtensionResultHolder; import org.broadleafcommerce.common.extension.ExtensionResultStatusType; ======= import org.broadleafcommerce.core.catalog.dao.ProductOptionDao; >>>>>>> import org.broadleafcommerce.common.extension.ExtensionResultHolder; import org.broadleafcommerce.common.extension.ExtensionResultStatusType; import org.broadleafcommerce.core.catalog.dao.ProductOptionDao;
<<<<<<< ======= import net.sf.cglib.core.CollectionUtils; import net.sf.cglib.core.Predicate; >>>>>>> import net.sf.cglib.core.CollectionUtils; import net.sf.cglib.core.Predicate; <<<<<<< import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Transient; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; ======= import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.Type; import org.hibernate.annotations.Where; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Transient; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; >>>>>>> import org.hibernate.annotations.SQLDelete; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Transient; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; <<<<<<< @Override ======= @Embedded protected ArchiveStatus archiveStatus = new ArchiveStatus(); @Transient protected List<RelatedProduct> filteredCrossSales = null; @Transient protected List<RelatedProduct> filteredUpSales = null; /* * (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.Product#getId() */ >>>>>>> @Embedded protected ArchiveStatus archiveStatus = new ArchiveStatus(); @Transient protected List<RelatedProduct> filteredCrossSales = null; @Transient protected List<RelatedProduct> filteredUpSales = null; @Override <<<<<<< return getDefaultSku().getActiveStartDate(); ======= if ('Y'==getArchived()) { return null; } return activeStartDate; >>>>>>> return getDefaultSku().getActiveStartDate();
<<<<<<< import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransform; import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformMember; import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformTypes; ======= import org.broadleafcommerce.common.i18n.service.DynamicTranslationProvider; >>>>>>> import org.broadleafcommerce.common.i18n.service.DynamicTranslationProvider; import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransform; import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformMember; import org.broadleafcommerce.common.extensibility.jpa.copy.DirectCopyTransformTypes;
<<<<<<< import org.broadleafcommerce.core.order.service.call.ActivityMessageDTO; ======= import org.broadleafcommerce.core.order.service.call.NonDiscreteOrderItemRequestDTO; >>>>>>> import org.broadleafcommerce.core.order.service.call.ActivityMessageDTO; import org.broadleafcommerce.core.order.service.call.NonDiscreteOrderItemRequestDTO;
<<<<<<< ======= import org.apache.commons.lang3.StringUtils; import org.broadleafcommerce.openadmin.web.form.entity.Field; import org.codehaus.jettison.json.JSONObject; >>>>>>>
<<<<<<< protected PersistenceResponse add(PersistencePackageRequest request) ======= @Override public Entity add(PersistencePackageRequest request) >>>>>>> @Override public PersistenceResponse add(PersistencePackageRequest request) <<<<<<< protected PersistenceResponse update(PersistencePackageRequest request) ======= @Override public Entity update(PersistencePackageRequest request) >>>>>>> @Override public PersistenceResponse update(PersistencePackageRequest request) <<<<<<< protected PersistenceResponse inspect(PersistencePackageRequest request) ======= @Override public DynamicResultSet inspect(PersistencePackageRequest request) >>>>>>> @Override public PersistenceResponse inspect(PersistencePackageRequest request) <<<<<<< protected PersistenceResponse remove(PersistencePackageRequest request) ======= @Override public void remove(PersistencePackageRequest request) >>>>>>> @Override public PersistenceResponse remove(PersistencePackageRequest request) <<<<<<< protected PersistenceResponse fetch(PersistencePackageRequest request) ======= @Override public DynamicResultSet fetch(PersistencePackageRequest request) >>>>>>> @Override public PersistenceResponse fetch(PersistencePackageRequest request)
<<<<<<< import com.google.gwt.event.shared.HandlerRegistration; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.DSCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.DataSource; import com.smartgwt.client.data.DataSourceField; import com.smartgwt.client.data.Record; import com.smartgwt.client.data.ResultSet; import com.smartgwt.client.rpc.RPCResponse; import com.smartgwt.client.types.DSOperationType; import com.smartgwt.client.types.Visibility; import com.smartgwt.client.util.BooleanCallback; import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.events.FetchDataEvent; import com.smartgwt.client.widgets.events.FetchDataHandler; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.grid.events.CellSavedEvent; import com.smartgwt.client.widgets.grid.events.CellSavedHandler; import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler; import com.smartgwt.client.widgets.grid.events.SelectionEvent; import com.smartgwt.client.widgets.layout.Layout; import com.smartgwt.client.widgets.tree.TreeGrid; ======= >>>>>>>
<<<<<<< public class SearchFacetImpl implements SearchFacet, Serializable, AdminMainEntity, SearchFacetAdminPresentation { ======= @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE) public class SearchFacetImpl implements SearchFacet, Serializable { >>>>>>> @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE) public class SearchFacetImpl implements SearchFacet, Serializable, AdminMainEntity, SearchFacetAdminPresentation {
<<<<<<< populateValueRequest.getProperty().setIsDirty(dirty); return FieldProviderResponse.HANDLED; ======= return FieldProviderResponse.HANDLED_BREAK; >>>>>>> populateValueRequest.getProperty().setIsDirty(dirty); return FieldProviderResponse.HANDLED_BREAK;
<<<<<<< dirty = true; } else { dirty = assignableValue.getValue().equals(populateValueRequest.getProperty().getValue()); populateValueRequest.getProperty().setOriginalValue(String.valueOf(assignableValue)); populateValueRequest.getProperty().setOriginalDisplayValue(String.valueOf(assignableValue)); ======= setOnParent = true; >>>>>>> setOnParent = true; dirty = true; } else { dirty = assignableValue.getValue().equals(populateValueRequest.getProperty().getValue()); populateValueRequest.getProperty().setOriginalValue(String.valueOf(assignableValue)); populateValueRequest.getProperty().setOriginalDisplayValue(String.valueOf(assignableValue));
<<<<<<< @Override public String getFieldValue(String fieldName) { if (structuredContentFields.containsKey(fieldName)) { return getStructuredContentFields().get(fieldName).getValue(); } return null; } ======= @Override public void setFieldValues(Map<String, String> fieldValuesMap) { this.fieldValuesMap = fieldValuesMap; } @Override public Map<String, String> getFieldValues() { if (fieldValuesMap == null) { fieldValuesMap = new HashMap<String, String>(); for (Entry<String, StructuredContentField> entry : getStructuredContentFields().entrySet()) { fieldValuesMap.put(entry.getKey(), entry.getValue().getValue()); } } return fieldValuesMap; } >>>>>>> @Override public String getFieldValue(String fieldName) { if (structuredContentFields.containsKey(fieldName)) { return getStructuredContentFields().get(fieldName).getValue(); } return null; } @Override public void setFieldValues(Map<String, String> fieldValuesMap) { this.fieldValuesMap = fieldValuesMap; } @Override public Map<String, String> getFieldValues() { if (fieldValuesMap == null) { fieldValuesMap = new HashMap<String, String>(); for (Entry<String, StructuredContentField> entry : getStructuredContentFields().entrySet()) { fieldValuesMap.put(entry.getKey(), entry.getValue().getValue()); } } return fieldValuesMap; }
<<<<<<< public static final String MAX_RESULTS_PARAMETER = "maxResults"; ======= public static final String LAST_ID_PARAMETER = "lastId"; public static final String FIRST_ID_PARAMETER = "firstId"; public static final String UPPER_COUNT_PARAMETER = "upperCount"; public static final String LOWER_COUNT_PARAMETER = "lowerCount"; public static final String PAGE_SIZE_PARAMETER = "pageSize"; >>>>>>> public static final String MAX_RESULTS_PARAMETER = "maxResults"; public static final String LAST_ID_PARAMETER = "lastId"; public static final String FIRST_ID_PARAMETER = "firstId"; public static final String UPPER_COUNT_PARAMETER = "upperCount"; public static final String LOWER_COUNT_PARAMETER = "lowerCount"; public static final String PAGE_SIZE_PARAMETER = "pageSize";
<<<<<<< import org.broadleafcommerce.common.email.service.EmailService; import org.broadleafcommerce.common.email.service.info.EmailInfo; import org.broadleafcommerce.common.id.service.IdGenerationService; ======= import org.broadleafcommerce.common.event.BroadleafApplicationEventPublisher; import org.broadleafcommerce.common.id.service.IdGenerationService; >>>>>>> import org.broadleafcommerce.common.event.BroadleafApplicationEventPublisher; import org.broadleafcommerce.common.id.service.IdGenerationService; <<<<<<< import org.broadleafcommerce.profile.core.dto.CustomerRuleHolder; ======= import org.broadleafcommerce.profile.core.dto.CustomerRuleHolder; import org.broadleafcommerce.profile.core.event.ForgotPasswordEvent; import org.broadleafcommerce.profile.core.event.ForgotUsernameEvent; import org.broadleafcommerce.profile.core.event.RegisterCustomerEvent; >>>>>>> import org.broadleafcommerce.profile.core.dto.CustomerRuleHolder; import org.broadleafcommerce.profile.core.event.ForgotPasswordEvent; import org.broadleafcommerce.profile.core.event.ForgotUsernameEvent; import org.broadleafcommerce.profile.core.event.RegisterCustomerEvent; <<<<<<< ======= import javax.annotation.PostConstruct; >>>>>>> <<<<<<< HashMap<String, Object> vars = new HashMap<String, Object>(); vars.put("token", token); ======= >>>>>>> <<<<<<< public EmailInfo getForgotPasswordEmailInfo() { return forgotPasswordEmailInfo; } public void setForgotPasswordEmailInfo(EmailInfo forgotPasswordEmailInfo) { this.forgotPasswordEmailInfo = forgotPasswordEmailInfo; } public EmailInfo getForgotUsernameEmailInfo() { return forgotUsernameEmailInfo; } public void setForgotUsernameEmailInfo(EmailInfo forgotUsernameEmailInfo) { this.forgotUsernameEmailInfo = forgotUsernameEmailInfo; } public EmailInfo getRegistrationEmailInfo() { return registrationEmailInfo; } public void setRegistrationEmailInfo(EmailInfo registrationEmailInfo) { this.registrationEmailInfo = registrationEmailInfo; } public EmailInfo getChangePasswordEmailInfo() { return changePasswordEmailInfo; } public void setChangePasswordEmailInfo(EmailInfo changePasswordEmailInfo) { this.changePasswordEmailInfo = changePasswordEmailInfo; } ======= >>>>>>>
<<<<<<< @Override public Collection<SolrInputDocument> buildIncrementalIndex(List<? extends Indexable> indexables, SolrClient solrServer) throws ServiceException { return buildIncrementalIndex(null, indexables, solrServer); } @Override public void optimizeIndex(SolrClient server) throws ServiceException, IOException { optimizeIndex(null, server); } @Override public void commit(SolrClient server) throws ServiceException, IOException { commit(null, server); } @Override public void commit(SolrClient server, boolean softCommit, boolean waitSearcher, boolean waitFlush) throws ServiceException, IOException { commit(null, server, softCommit, waitSearcher, waitFlush); } @Override public void deleteAllNamespaceDocuments(SolrClient server) throws ServiceException { deleteAllNamespaceDocuments(null, server); } @Override public void deleteAllDocuments(SolrClient server) throws ServiceException { deleteAllDocuments(null, server); } ======= @Override public boolean useLegacyIndexer() { return useLegacySolrIndexer; } >>>>>>> @Override public Collection<SolrInputDocument> buildIncrementalIndex(List<? extends Indexable> indexables, SolrClient solrServer) throws ServiceException { return buildIncrementalIndex(null, indexables, solrServer); } @Override public void optimizeIndex(SolrClient server) throws ServiceException, IOException { optimizeIndex(null, server); } @Override public void commit(SolrClient server) throws ServiceException, IOException { commit(null, server); } @Override public void commit(SolrClient server, boolean softCommit, boolean waitSearcher, boolean waitFlush) throws ServiceException, IOException { commit(null, server, softCommit, waitSearcher, waitFlush); } @Override public void deleteAllNamespaceDocuments(SolrClient server) throws ServiceException { deleteAllNamespaceDocuments(null, server); } @Override public void deleteAllDocuments(SolrClient server) throws ServiceException { deleteAllDocuments(null, server); } @Override public boolean useLegacyIndexer() { return useLegacySolrIndexer; }
<<<<<<< import org.broadleafcommerce.common.dao.GenericEntityDao; ======= import org.broadleafcommerce.common.extensibility.jpa.SiteDiscriminator; >>>>>>> import org.broadleafcommerce.common.dao.GenericEntityDao; import org.broadleafcommerce.common.extensibility.jpa.SiteDiscriminator;
<<<<<<< import org.broadleafcommerce.common.copy.CreateResponse; import org.broadleafcommerce.common.copy.MultiTenantCopyContext; ======= import org.broadleafcommerce.common.i18n.service.DynamicTranslationProvider; >>>>>>> import org.broadleafcommerce.common.i18n.service.DynamicTranslationProvider; import org.broadleafcommerce.common.copy.CreateResponse; import org.broadleafcommerce.common.copy.MultiTenantCopyContext;
<<<<<<< import org.broadleafcommerce.core.checkout.service.workflow.CheckoutSeed; import org.broadleafcommerce.core.offer.dao.OfferAuditDao; import org.broadleafcommerce.core.offer.domain.Adjustment; ======= import org.broadleafcommerce.core.checkout.service.workflow.CheckoutContext; import org.broadleafcommerce.core.offer.domain.Offer; import org.broadleafcommerce.core.offer.domain.OfferCode; import org.broadleafcommerce.core.offer.service.OfferAuditService; import org.broadleafcommerce.core.offer.service.OfferService; >>>>>>> import org.broadleafcommerce.core.checkout.service.workflow.CheckoutSeed; import org.broadleafcommerce.core.offer.domain.Offer; import org.broadleafcommerce.core.offer.domain.OfferCode; import org.broadleafcommerce.core.offer.service.OfferAuditService; import org.broadleafcommerce.core.offer.service.OfferService; <<<<<<< public ProcessContext<CheckoutSeed> execute(ProcessContext<CheckoutSeed> context) throws Exception { Map<Long,Long> offerIdToAllowedUsesMap = new HashMap<Long,Long>(); CheckoutSeed seed = context.getSeedData(); Order order = seed.getOrder(); if (order != null) { addOfferIds(order.getOrderAdjustments(), offerIdToAllowedUsesMap); if (order.getOrderItems() != null) { for (OrderItem item : order.getOrderItems()) { addOfferIds(item.getOrderItemAdjustments(), offerIdToAllowedUsesMap); } } if (order.getFulfillmentGroups() != null) { for (FulfillmentGroup fg : order.getFulfillmentGroups()) { addOfferIds(fg.getFulfillmentGroupAdjustments(), offerIdToAllowedUsesMap); } } if (! checkOffers(offerIdToAllowedUsesMap, order)) { throw new OfferMaxUseExceededException("The customer has used this offer code more than the maximum allowed number of times."); } } return context; } private boolean checkOffers(Map<Long,Long> offerIdToAllowedUsesMap, Order order) { boolean orderVerified = true; if (order.getCustomer() != null && order.getCustomer().getId() != null) { Long customerId = order.getCustomer().getId(); for(Long offerId : offerIdToAllowedUsesMap.keySet()) { Long allowedUses = offerIdToAllowedUsesMap.get(offerId); Long currentUses = offerAuditDao.countUsesByCustomer(customerId, offerId); if (currentUses != null && currentUses >= allowedUses) { return false; ======= public CheckoutContext execute(CheckoutContext context) throws Exception { Order order = context.getSeedData().getOrder(); Set<Offer> appliedOffers = offerService.getUniqueOffersFromOrder(order); for (Offer offer : appliedOffers) { if (offer.isLimitedUsePerCustomer()) { Long currentUses = offerAuditService.countUsesByCustomer(order.getCustomer().getId(), offer.getId()); if (currentUses >= offer.getMaxUsesPerCustomer()) { throw new OfferMaxUseExceededException("The customer has used this offer more than the maximum allowed number of times."); >>>>>>> public ProcessContext<CheckoutSeed> execute(ProcessContext<CheckoutSeed> context) throws Exception { Order order = context.getSeedData().getOrder(); Set<Offer> appliedOffers = offerService.getUniqueOffersFromOrder(order); for (Offer offer : appliedOffers) { if (offer.isLimitedUsePerCustomer()) { Long currentUses = offerAuditService.countUsesByCustomer(order.getCustomer().getId(), offer.getId()); if (currentUses >= offer.getMaxUsesPerCustomer()) { throw new OfferMaxUseExceededException("The customer has used this offer more than the maximum allowed number of times.");
<<<<<<< import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.math.BigDecimal; import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; import javax.annotation.Resource; ======= >>>>>>>
<<<<<<< @Value("${cache.entity.dao.metadata.ttl}") protected int cacheEntityMetaDataTtl; ======= >>>>>>> <<<<<<< ======= protected String[] getPolymorphicClasses(Class<?> clazz) { DynamicDaoHelperImpl helper = new DynamicDaoHelperImpl(); Class<?>[] classes = helper.getAllPolymorphicEntitiesFromCeiling(clazz, helper.getSessionFactory((HibernateEntityManager) em), true, skuMetadataCacheService.useCache()); String[] result = new String[classes.length]; for (int i = 0; i < classes.length; i++) { result[i] = classes[i].getName(); } return result; } >>>>>>> /** * Returns a {@link Property} filled out with a delimited list of the <b>values</b> that are passed in. This should be * invoked on a fetch and the returned property should be added to the fetched {@link Entity} dto. * * @param values * @return * @see {@link #createConsolidatedOptionField(Class)}; */ public Property getConsolidatedOptionProperty(Collection<ProductOptionValue> values) { Property optionValueProperty = new Property(); optionValueProperty.setName(CONSOLIDATED_PRODUCT_OPTIONS_FIELD_NAME); //order the values by the display order of their correspond product option // Collections.sort(values, new Comparator<ProductOptionValue>() { // // @Override // public int compare(ProductOptionValue value1, ProductOptionValue value2) { // return new CompareToBuilder().append(value1.getProductOption().getDisplayOrder(), // value2.getProductOption().getDisplayOrder()).toComparison(); // } // }); ArrayList<String> stringValues = new ArrayList<>(); CollectionUtils.collect(values, new Transformer() { @Override public Object transform(Object input) { return ((ProductOptionValue) input).getAttributeValue(); } }, stringValues); optionValueProperty.setValue(StringUtils.join(stringValues, CONSOLIDATED_PRODUCT_OPTIONS_DELIMETER)); return optionValueProperty; }
<<<<<<< ======= import org.broadleafcommerce.common.persistence.Status; import org.broadleafcommerce.common.util.StreamCapableTransactionalOperationAdapter; import org.broadleafcommerce.common.util.StreamingTransactionCapableUtil; import org.broadleafcommerce.common.util.TransactionUtils; >>>>>>> import org.broadleafcommerce.common.util.StreamCapableTransactionalOperationAdapter; import org.broadleafcommerce.common.util.StreamingTransactionCapableUtil; import org.broadleafcommerce.common.util.TransactionUtils;
<<<<<<< import io.nuls.core.model.DateUtils; import io.nuls.core.rpc.model.ModuleE; ======= import io.nuls.core.rpc.util.NulsDateUtils; >>>>>>> import io.nuls.core.model.DateUtils; import io.nuls.core.rpc.model.ModuleE; import io.nuls.core.rpc.util.NulsDateUtils;
<<<<<<< @Resource(name="blMetadata") ======= protected EJB3ConfigurationDao ejb3ConfigurationDao; @Resource(name = "blMetadata") >>>>>>> @Resource(name = "blMetadata") <<<<<<< return dynamicDaoHelper.getAllPolymorphicEntitiesFromCeiling(ceilingClass, includeUnqualifiedPolymorphicEntities, useCache()); ======= return dynamicDaoHelper.getAllPolymorphicEntitiesFromCeiling(ceilingClass, getSessionFactory(), includeUnqualifiedPolymorphicEntities, useCache()); >>>>>>> return dynamicDaoHelper.getAllPolymorphicEntitiesFromCeiling(ceilingClass, includeUnqualifiedPolymorphicEntities, useCache()); <<<<<<< return new FieldManager(entityConfiguration, getStandardEntityManager()); ======= return this.getFieldManager(true); } @Override public FieldManager getFieldManager(boolean cleanFieldManager) { if (fieldManager == null) { //keep in mind that getStandardEntityManager() can return null, this is in general OK, // we re-init fieldManager in setStandardEntityManager method fieldManager = new FieldManager(entityConfiguration, getStandardEntityManager()); } else if (cleanFieldManager){ fieldManager.clearMiddleFields(); } return fieldManager; >>>>>>> return this.getFieldManager(true); } @Override public FieldManager getFieldManager(boolean cleanFieldManager) { if (fieldManager == null) { //keep in mind that getStandardEntityManager() can return null, this is in general OK, // we re-init fieldManager in setStandardEntityManager method fieldManager = new FieldManager(entityConfiguration, getStandardEntityManager()); } else if (cleanFieldManager){ fieldManager.clearMiddleFields(); } return fieldManager;
<<<<<<< ======= import org.apache.commons.collections.CollectionUtils; >>>>>>> import org.apache.commons.collections.CollectionUtils; <<<<<<< import org.broadleafcommerce.core.search.domain.SearchCriteria; ======= import org.broadleafcommerce.core.inventory.service.InventoryService; import org.broadleafcommerce.core.search.domain.ProductSearchCriteria; import org.broadleafcommerce.core.search.domain.ProductSearchResult; >>>>>>> import org.broadleafcommerce.core.inventory.service.InventoryService; import org.broadleafcommerce.core.search.domain.SearchCriteria; <<<<<<< import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; ======= import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; >>>>>>> import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response;
<<<<<<< /** * Convenience method to return the calculated meta-description. Will return description if meta-description is null, * will return name if description is null. * * @return metaDescription */ public String getCalculatedMetaDescription(); /** * Returns the type of inventory for this category * @return the {@link InventoryType} for this category */ public InventoryType getInventoryType(); /** * Sets the type of inventory for this category * @param inventoryType the {@link InventoryType} for this category */ public void setInventoryType(InventoryType inventoryType); /** * Returns the default fulfillment type for skus in this category. May be null. * @return */ public FulfillmentType getFulfillmentType(); /** * Sets the default fulfillment type for skus in this category. May return null. * @param fulfillmentType */ public void setFulfillmentType(FulfillmentType fulfillmentType); /** * * @return list of possible translations */ public Map<String, CategoryTranslation> getTranslations(); /** * * @param translations */ public void setTranslations(Map<String, CategoryTranslation> translations); ======= >>>>>>> /** * Returns the type of inventory for this category * @return the {@link InventoryType} for this category */ public InventoryType getInventoryType(); /** * Sets the type of inventory for this category * @param inventoryType the {@link InventoryType} for this category */ public void setInventoryType(InventoryType inventoryType); /** * Returns the default fulfillment type for skus in this category. May be null. * @return */ public FulfillmentType getFulfillmentType(); /** * Sets the default fulfillment type for skus in this category. May return null. * @param fulfillmentType */ public void setFulfillmentType(FulfillmentType fulfillmentType); /** * * @return list of possible translations */ public Map<String, CategoryTranslation> getTranslations(); /** * * @param translations */ public void setTranslations(Map<String, CategoryTranslation> translations);
<<<<<<< import org.broadleafcommerce.common.currency.domain.BroadleafCurrency; import org.broadleafcommerce.common.extension.AbstractExtensionHandler; import org.broadleafcommerce.common.extension.ExtensionResultHolder; import org.broadleafcommerce.common.extension.ExtensionResultStatusType; import org.broadleafcommerce.core.order.domain.DiscreteOrderItem; ======= import org.broadleafcommerce.core.extension.AbstractExtensionHandler; import org.broadleafcommerce.core.extension.ExtensionResultHolder; import org.broadleafcommerce.core.extension.ExtensionResultStatusType; >>>>>>> import org.broadleafcommerce.common.extension.AbstractExtensionHandler; import org.broadleafcommerce.common.extension.ExtensionResultHolder; import org.broadleafcommerce.common.extension.ExtensionResultStatusType;
<<<<<<< import org.broadleafcommerce.common.web.BroadleafRequestContext; import org.broadleafcommerce.core.inventory.exception.InventoryUnavailableException; ======= import org.broadleafcommerce.common.locale.domain.Locale; import org.broadleafcommerce.common.pricelist.domain.PriceList; >>>>>>> import org.broadleafcommerce.common.web.BroadleafRequestContext;
<<<<<<< public ExtensionResultStatusType attachFacet(SolrQuery query, String indexField, SearchFacetDTO dto, SearchCriteria searchCriteria); ======= ExtensionResultStatusType attachFacet(SolrQuery query, String indexField, SearchFacetDTO dto); >>>>>>> ExtensionResultStatusType attachFacet(SolrQuery query, String indexField, SearchFacetDTO dto, SearchCriteria searchCriteria);