gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.component.ehcache; import java.io.IOException; import java.net.URL; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.spi.ClassResolver; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.annotations.Component; import org.apache.camel.support.DefaultComponent; import org.apache.camel.support.ResourceHelper; import org.apache.camel.util.ObjectHelper; import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.Configuration; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.xml.XmlConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents the component that manages {@link DefaultComponent}. */ @Component("ehcache") public class EhcacheComponent extends DefaultComponent { private static final Logger LOGGER = LoggerFactory.getLogger(EhcacheComponent.class); private final ConcurrentMap<Object, EhcacheManager> managers = new ConcurrentHashMap<>(); @Metadata(label = "advanced") private EhcacheConfiguration configuration = new EhcacheConfiguration(); public EhcacheComponent() { } public EhcacheComponent(CamelContext context) { super(context); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { EhcacheConfiguration configuration = this.configuration.copy(); setProperties(configuration, parameters); return new EhcacheEndpoint(uri, this, remaining, createCacheManager(configuration), configuration); } // **************************** // Helpers // **************************** private EhcacheManager createCacheManager(EhcacheConfiguration configuration) throws IOException { ObjectHelper.notNull(configuration, "Camel Ehcache configuration"); // Check if a cache manager has been configured if (configuration.hasCacheManager()) { LOGGER.info("EhcacheManager configured with supplied CacheManager"); return managers.computeIfAbsent( configuration.getCacheManager(), m -> new EhcacheManager( CacheManager.class.cast(m), false, configuration) ); } // Check if a cache manager configuration has been provided if (configuration.hasCacheManagerConfiguration()) { LOGGER.info("EhcacheManager configured with supplied CacheManagerConfiguration"); return managers.computeIfAbsent( configuration.getCacheManagerConfiguration(), c -> new EhcacheManager( CacheManagerBuilder.newCacheManager(Configuration.class.cast(c)), true, configuration ) ); } // Check if a configuration file has been provided if (configuration.hasConfigurationUri()) { String configurationUri = configuration.getConfigurationUri(); ClassResolver classResolver = getCamelContext().getClassResolver(); URL url = ResourceHelper.resolveMandatoryResourceAsUrl(classResolver, configurationUri); LOGGER.info("EhcacheManager configured with supplied URI {}", url); return managers.computeIfAbsent( url, u -> new EhcacheManager( CacheManagerBuilder.newCacheManager(new XmlConfiguration(URL.class.cast(u))), true, configuration ) ); } LOGGER.info("EhcacheManager configured with default builder"); return new EhcacheManager(CacheManagerBuilder.newCacheManagerBuilder().build(), true, configuration); } // **************************** // Properties // **************************** public EhcacheConfiguration getConfiguration() { return configuration; } /** * Sets the global component configuration */ public void setConfiguration(EhcacheConfiguration configuration) { // The component configuration can't be null ObjectHelper.notNull(configuration, "EhcacheConfiguration"); this.configuration = configuration; } public CacheManager getCacheManager() { return configuration.getCacheManager(); } /** * The cache manager */ public void setCacheManager(CacheManager cacheManager) { this.configuration.setCacheManager(cacheManager); } public Configuration getCacheManagerConfiguration() { return configuration.getCacheManagerConfiguration(); } /** * The cache manager configuration */ public void setCacheManagerConfiguration(Configuration cacheManagerConfiguration) { this.configuration.setCacheManagerConfiguration(cacheManagerConfiguration); } /** * The default cache configuration to be used to create caches. */ public void setCacheConfiguration(CacheConfiguration cacheConfiguration) { this.configuration.setConfiguration(cacheConfiguration); } public CacheConfiguration getCacheConfiguration() { return this.configuration.getConfiguration(); } public Map<String, CacheConfiguration> getCachesConfigurations() { return configuration.getConfigurations(); } /** * A map of caches configurations to be used to create caches. */ public void setCachesConfigurations(Map<String, CacheConfiguration> configurations) { configuration.setConfigurations(configurations); } public void addCachesConfigurations(Map<String, CacheConfiguration> configurations) { configuration.addConfigurations(configurations); } public String getCacheConfigurationUri() { return this.configuration.getConfigurationUri(); } /** * URI pointing to the Ehcache XML configuration file's location */ public void setCacheConfigurationUri(String configurationUri) { this.configuration.setConfigurationUri(configurationUri); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.sun.jini.test.impl.mercury; import java.util.logging.Level; import java.rmi.RemoteException; import java.rmi.NoSuchObjectException; import java.rmi.ServerException; import java.util.Date; import java.util.ArrayList; import java.util.logging.Logger; import net.jini.event.InvalidIteratorException; import net.jini.event.MailboxPullRegistration; import net.jini.event.PullEventMailbox; import net.jini.event.RemoteEventIterator; import net.jini.core.lease.Lease; import net.jini.core.event.EventRegistration; import net.jini.core.event.RemoteEvent; import net.jini.core.event.RemoteEventListener; import net.jini.core.event.UnknownEventException; import com.sun.jini.constants.TimeConstants; import com.sun.jini.admin.DestroyAdmin; import com.sun.jini.test.impl.mercury.EMSTestBase; import com.sun.jini.test.impl.mercury.TestUtils; import com.sun.jini.test.impl.mercury.TestListener; import com.sun.jini.test.impl.mercury.TestGenerator; import com.sun.jini.qa.harness.QAConfig; import com.sun.jini.qa.harness.TestException; /* * Test blocks multiple threads on getNext() with a timeout of 1 minute * (on an empty registration). * The test then tries to call the service's destroy() method * before the minute is up. The implementation attempts to notify blocking * calls at the start of the destroy process, so we should return early (i.e. * after the destroy call but before the requested timeout period). */ public class PullTimeoutTest6B extends EMSTestBase implements TimeConstants { // // This should be long enough to sensibly run the test. // If the service doesn't grant long enough leases, then // we might have to resort to using something like the // LeaseRenewalManager to keep our leases current. // private final long DURATION1 = 3*HOURS; private final int NUM_WORKERS = 5; private final long EVENT_ID = 1234; private final long EVENT_ID2 = 5678; /* Note: Service has a 2 minute unexport timeout */ private final long MAX_WAIT_GET_EVENT = 60 * 1000; private final long MAX_WAIT_SEND_DESTROY = MAX_WAIT_GET_EVENT / 5; class MyDestroyerRunnable implements Runnable { final DestroyAdmin admin; final Logger logger; final long delay; MyDestroyerRunnable(DestroyAdmin admin, Logger logger, long delay) { this.admin = admin; this.logger = logger; this.delay = delay; } public void run() { try { logger.log(Level.FINEST, "MyDestroyerRunnable sleeping @ {0} for {1} ms", new Object[] { new Date(), new Long(delay)}); Thread.sleep(delay); logger.log(Level.FINEST, "MyDestroyerRunnable awoken @ {0}", new Date()); } catch (InterruptedException ie) { // ignore logger.log(Level.FINEST, "Sleep interrupted", ie); } try { admin.destroy(); logger.log(Level.FINEST, "Called destroy @ {0}", new Date()); } catch (RemoteException re) { logger.log(Level.FINEST, "Ignoring RemoteException from calling destroy", re); } } } class MyWorker extends Thread { final MailboxPullRegistration reg; final Logger logger; final long delay; boolean failed = false; MyWorker(MailboxPullRegistration reg, Logger logger, long delay) { this.reg = reg; this.logger = logger; this.delay = delay; } public void run() { try { // Get events and verify logger.log(Level.INFO, "Getting events from empty mailbox."); RemoteEventIterator rei = reg.getRemoteEvents(); RemoteEvent rei_event = null; Date before = new Date(); logger.log(Level.INFO, "Calling next() on empty set @ {0}", before); try { rei_event = rei.next(MAX_WAIT_GET_EVENT); throw new TestException("Did not receive expected exception"); } catch (NoSuchObjectException nsoe) { logger.log(Level.INFO, "Caught expected exception", nsoe); } Date after = new Date(); //Verify that we returned before the timeout long delta = after.getTime() - before.getTime(); logger.log(Level.INFO, "Returned from next() @ {0}, delta = {1}", new Object[] {after, new Long(delta)}); if (delta >= MAX_WAIT_GET_EVENT) { throw new TestException("Returned from next() after expected: " + delta); } if (rei_event != null) { throw new TestException( "Received unexpected event from mailbox: " + rei_event); } logger.log(Level.INFO, "Worker done."); } catch (Exception e) { logger.log(Level.INFO, "Got unexpected exception.", e); failed = true; } } public boolean failed() { return failed; } } public void run() throws Exception { logger.log(Level.INFO, "Starting up " + this.getClass().toString()); PullEventMailbox mb = getPullMailbox(); Object admin = getMailboxAdmin(mb); DestroyAdmin dAdmin = (DestroyAdmin)admin; int i = 0; // Register and check lease long[] durations = new long[] {DURATION1, DURATION1, DURATION1, DURATION1, DURATION1}; MailboxPullRegistration[] mrs = getPullRegistrations(mb, durations); Lease mrl = null; for (i=0; i < durations.length; i++) { mrl = getPullMailboxLease(mrs[i]); checkLease(mrl, DURATION1); } // Start destroyer thread with a delay of MAX_WAIT_SEND_EVENT Thread t = new Thread( new MyDestroyerRunnable( dAdmin, logger, MAX_WAIT_SEND_DESTROY )); t.start(); // Start worker threads MyWorker[] workers = new MyWorker[mrs.length]; for (i=0; i < mrs.length; i++) { workers[i] = new MyWorker(mrs[i], logger, MAX_WAIT_GET_EVENT); workers[i].start(); } for (i=0; i < mrs.length; i++) { workers[i].join(); if (workers[i].failed()) { throw new TestException( "Worker failed"); } } } /** * Invoke parent's setup and parser * @exception TestException will usually indicate an "unresolved" * condition because at this point the test has not yet begun. */ public void setup(QAConfig sysConfig) throws Exception { super.setup(sysConfig); parse(); } }
package hut.hotbaby; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.hardware.Camera; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.wifi.WifiManager; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; import java.lang.Void; import java.util.regex.Pattern; public class MainActivity extends Activity { public static Camera camera = null;// has to be static, otherwise onDestroy() destroys it private RegexThread[] regexThreads; private CPUTask cpuTask; private NetworkTask networkTask; private BroadcastReceiver wifiReceiver; private LocationListener locationListener; public static final String TAG = "Hot Baby"; private boolean running = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wifiReceiver = new BroadcastReceiver() { @Override public void onReceive(Context c, Intent intent) { WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); wifiManager.getScanResults(); wifiManager.startScan(); } }; final Button play = (Button) findViewById(R.id.start_button); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(running) { running = false; play.setText(R.string.start); stop(); } else { running = true; play.setText(R.string.stop); start(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void start(){ fullBrightness(); startLocation(); startWifiScanning(); flashLightOn(); burnCPU(); startNetwork();; } private void stop() { restBrightness(); stopLocation(); stopWifiScanning(); flashLightOff(); stopCPU(); stopNetwork(); } private void fullBrightness() { WindowManager.LayoutParams layout = getWindow().getAttributes(); layout.screenBrightness = 1F; getWindow().setAttributes(layout); } private void startLocation() { // Acquire a reference to the system Location Manager final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Retrieve information about current GPS status locationManager.getGpsStatus(null); } public void onStatusChanged(String provider, int status, Bundle extras) { // Retrieve information about current GPS status locationManager.getGpsStatus(null); } public void onProviderEnabled(String provider) { // Retrieve information about current GPS status locationManager.getGpsStatus(null); } public void onProviderDisabled(String provider) { // Retrieve information about current GPS status locationManager.getGpsStatus(null); } }; // Register the listener with the Location Manager to receive location updates for (String provider : locationManager.getAllProviders()) { locationManager.requestLocationUpdates(provider, 0, 0, locationListener); } } private void startWifiScanning() { WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifiManager.startScan(); registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); } // deprecated from lollipop private void flashLightOn() { try { if (getPackageManager().hasSystemFeature( PackageManager.FEATURE_CAMERA_FLASH)) { camera = Camera.open(); Camera.Parameters p = camera.getParameters(); p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); camera.setParameters(p); camera.startPreview(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(getBaseContext(), "Exception flashLightOn()", Toast.LENGTH_SHORT).show(); } } // http://stackoverflow.com/questions/7396766/how-can-i-stress-my-phones-cpu-programatically private void burnCPU() { /* int NUM_THREADS = 10; // run 10 threads regexThreads = new RegexThread [NUM_THREADS]; for(int i = 0; i < NUM_THREADS; ++i) { regexThreads[i] = new RegexThread(); // create a new thread } */ cpuTask = new CPUTask(); cpuTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private void startNetwork () { networkTask = new NetworkTask(); networkTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } //------------------------------------------------- // turn off private void restBrightness() { WindowManager.LayoutParams layout = getWindow().getAttributes(); layout.screenBrightness = -1; getWindow().setAttributes(layout); } private void flashLightOff() { try { if (getPackageManager().hasSystemFeature( PackageManager.FEATURE_CAMERA_FLASH)) { camera.stopPreview(); camera.release(); camera = null; } } catch (Exception e) { e.printStackTrace(); Toast.makeText(getBaseContext(), "Exception flashLightOff", Toast.LENGTH_SHORT).show(); } } private void stopLocation() { LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); locationManager.removeUpdates(locationListener); } private void stopWifiScanning() { unregisterReceiver(wifiReceiver); } private void stopCPU() { /* for (int i = 0; i < regexThreads.length; i++) { regexThreads[i].terminate(); } */ cpuTask.cancel(true); } private void stopNetwork() { networkTask.cancel(true); } //-----helper class----------------------------------- class RegexThread extends Thread { private volatile boolean running = true; RegexThread() { // Create a new, second thread super("Regex Thread"); start(); // Start the thread } // This is the entry point for the second thread. public void run() { while(running) { Pattern p = Pattern.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b"); } } public void terminate() { running = false; } } // try cpu task from another approach private static class CPUTask extends AsyncTask<Void, Void, Double> { @Override protected Void doInBackground(Void... params) { while (true) { if (isCancelled()) { break; } Pattern p = Pattern.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)\b"); } } } // network task private static class NetworkTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { while (true) { if (isCancelled()) { break; } try { HttpURLConnection httpConnection = (HttpURLConnection) new URL("http://www.google.com").openConnection(); BufferedInputStream is = new BufferedInputStream(httpConnection.getInputStream()); int read; byte[] response = new byte[0]; final byte[] buffer = new byte[2048]; while ((read = is.read(buffer)) > -1) { byte[] tmp = new byte[response.length + read]; System.arraycopy(response, 0, tmp, 0, response.length); System.arraycopy(buffer, 0, tmp, response.length, read); response = tmp; } System.out.println("--> " + new String(response)); } catch (IOException e) { e.printStackTrace(); } } return null; } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.hadoop.hdfs.server.namenode.web.resources; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Options; import org.apache.hadoop.fs.XAttr; import org.apache.hadoop.fs.permission.AclStatus; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.hdfs.StorageType; import org.apache.hadoop.hdfs.XAttrHelper; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.DirectoryListing; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager; import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager; import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor; import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeStorageInfo; import org.apache.hadoop.hdfs.server.common.JspHelper; import org.apache.hadoop.hdfs.server.namenode.NameNode; import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols; import org.apache.hadoop.hdfs.web.JsonUtil; import org.apache.hadoop.hdfs.web.ParamFilter; import org.apache.hadoop.hdfs.web.SWebHdfsFileSystem; import org.apache.hadoop.hdfs.web.WebHdfsFileSystem; import org.apache.hadoop.hdfs.web.resources.AccessTimeParam; import org.apache.hadoop.hdfs.web.resources.AclPermissionParam; import org.apache.hadoop.hdfs.web.resources.BlockSizeParam; import org.apache.hadoop.hdfs.web.resources.BufferSizeParam; import org.apache.hadoop.hdfs.web.resources.ConcatSourcesParam; import org.apache.hadoop.hdfs.web.resources.CreateParentParam; import org.apache.hadoop.hdfs.web.resources.DelegationParam; import org.apache.hadoop.hdfs.web.resources.DeleteOpParam; import org.apache.hadoop.hdfs.web.resources.DestinationParam; import org.apache.hadoop.hdfs.web.resources.DoAsParam; import org.apache.hadoop.hdfs.web.resources.ExcludeDatanodesParam; import org.apache.hadoop.hdfs.web.resources.GetOpParam; import org.apache.hadoop.hdfs.web.resources.GroupParam; import org.apache.hadoop.hdfs.web.resources.HttpOpParam; import org.apache.hadoop.hdfs.web.resources.LengthParam; import org.apache.hadoop.hdfs.web.resources.ModificationTimeParam; import org.apache.hadoop.hdfs.web.resources.NamenodeAddressParam; import org.apache.hadoop.hdfs.web.resources.OffsetParam; import org.apache.hadoop.hdfs.web.resources.OldSnapshotNameParam; import org.apache.hadoop.hdfs.web.resources.OverwriteParam; import org.apache.hadoop.hdfs.web.resources.OwnerParam; import org.apache.hadoop.hdfs.web.resources.Param; import org.apache.hadoop.hdfs.web.resources.PermissionParam; import org.apache.hadoop.hdfs.web.resources.PostOpParam; import org.apache.hadoop.hdfs.web.resources.PutOpParam; import org.apache.hadoop.hdfs.web.resources.RecursiveParam; import org.apache.hadoop.hdfs.web.resources.RenameOptionSetParam; import org.apache.hadoop.hdfs.web.resources.RenewerParam; import org.apache.hadoop.hdfs.web.resources.ReplicationParam; import org.apache.hadoop.hdfs.web.resources.SnapshotNameParam; import org.apache.hadoop.hdfs.web.resources.TokenArgumentParam; import org.apache.hadoop.hdfs.web.resources.UriFsPathParam; import org.apache.hadoop.hdfs.web.resources.UserParam; import org.apache.hadoop.hdfs.web.resources.XAttrEncodingParam; import org.apache.hadoop.hdfs.web.resources.XAttrNameParam; import org.apache.hadoop.hdfs.web.resources.XAttrSetFlagParam; import org.apache.hadoop.hdfs.web.resources.XAttrValueParam; import org.apache.hadoop.hdfs.web.resources.FsActionParam; import org.apache.hadoop.io.Text; import org.apache.hadoop.ipc.RetriableException; import org.apache.hadoop.ipc.Server; import org.apache.hadoop.net.NetworkTopology.InvalidTopologyException; import org.apache.hadoop.net.Node; import org.apache.hadoop.net.NodeBase; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.util.StringUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import com.sun.jersey.spi.container.ResourceFilters; /** Web-hdfs NameNode implementation. */ @Path("") @ResourceFilters(ParamFilter.class) public class NamenodeWebHdfsMethods { public static final Log LOG = LogFactory.getLog(NamenodeWebHdfsMethods.class); private static final UriFsPathParam ROOT = new UriFsPathParam(""); private static final ThreadLocal<String> REMOTE_ADDRESS = new ThreadLocal<String>(); /** @return the remote client address. */ public static String getRemoteAddress() { return REMOTE_ADDRESS.get(); } public static InetAddress getRemoteIp() { try { return InetAddress.getByName(getRemoteAddress()); } catch (Exception e) { return null; } } /** * Returns true if a WebHdfs request is in progress. Akin to * {@link Server#isRpcInvocation()}. */ public static boolean isWebHdfsInvocation() { return getRemoteAddress() != null; } private @Context ServletContext context; private @Context HttpServletRequest request; private @Context HttpServletResponse response; private void init(final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final UriFsPathParam path, final HttpOpParam<?> op, final Param<?, ?>... parameters) { if (LOG.isTraceEnabled()) { LOG.trace("HTTP " + op.getValue().getType() + ": " + op + ", " + path + ", ugi=" + ugi + ", " + username + ", " + doAsUser + Param.toSortedString(", ", parameters)); } //clear content type response.setContentType(null); // set the remote address, if coming in via a trust proxy server then // the address with be that of the proxied client REMOTE_ADDRESS.set(JspHelper.getRemoteAddr(request)); } private void reset() { REMOTE_ADDRESS.set(null); } private static NamenodeProtocols getRPCServer(NameNode namenode) throws IOException { final NamenodeProtocols np = namenode.getRpcServer(); if (np == null) { throw new RetriableException("Namenode is in startup mode"); } return np; } @VisibleForTesting static DatanodeInfo chooseDatanode(final NameNode namenode, final String path, final HttpOpParam.Op op, final long openOffset, final long blocksize, final String excludeDatanodes) throws IOException { final BlockManager bm = namenode.getNamesystem().getBlockManager(); HashSet<Node> excludes = new HashSet<Node>(); if (excludeDatanodes != null) { for (String host : StringUtils .getTrimmedStringCollection(excludeDatanodes)) { int idx = host.indexOf(":"); if (idx != -1) { excludes.add(bm.getDatanodeManager().getDatanodeByXferAddr( host.substring(0, idx), Integer.parseInt(host.substring(idx + 1)))); } else { excludes.add(bm.getDatanodeManager().getDatanodeByHost(host)); } } } if (op == PutOpParam.Op.CREATE) { //choose a datanode near to client final DatanodeDescriptor clientNode = bm.getDatanodeManager( ).getDatanodeByHost(getRemoteAddress()); if (clientNode != null) { final DatanodeStorageInfo[] storages = bm.getBlockPlacementPolicy() .chooseTarget(path, 1, clientNode, new ArrayList<DatanodeStorageInfo>(), false, excludes, blocksize, // TODO: get storage type from the file StorageType.DEFAULT); if (storages.length > 0) { return storages[0].getDatanodeDescriptor(); } } } else if (op == GetOpParam.Op.OPEN || op == GetOpParam.Op.GETFILECHECKSUM || op == PostOpParam.Op.APPEND) { //choose a datanode containing a replica final NamenodeProtocols np = getRPCServer(namenode); final HdfsFileStatus status = np.getFileInfo(path); if (status == null) { throw new FileNotFoundException("File " + path + " not found."); } final long len = status.getLen(); if (op == GetOpParam.Op.OPEN) { if (openOffset < 0L || (openOffset >= len && len > 0)) { throw new IOException("Offset=" + openOffset + " out of the range [0, " + len + "); " + op + ", path=" + path); } } if (len > 0) { final long offset = op == GetOpParam.Op.OPEN? openOffset: len - 1; final LocatedBlocks locations = np.getBlockLocations(path, offset, 1); final int count = locations.locatedBlockCount(); if (count > 0) { return bestNode(locations.get(0).getLocations(), excludes); } } } return (DatanodeDescriptor)bm.getDatanodeManager().getNetworkTopology( ).chooseRandom(NodeBase.ROOT); } /** * Choose the datanode to redirect the request. Note that the nodes have been * sorted based on availability and network distances, thus it is sufficient * to return the first element of the node here. */ private static DatanodeInfo bestNode(DatanodeInfo[] nodes, HashSet<Node> excludes) throws IOException { for (DatanodeInfo dn: nodes) { if (false == dn.isDecommissioned() && false == excludes.contains(dn)) { return dn; } } throw new IOException("No active nodes contain this block"); } private Token<? extends TokenIdentifier> generateDelegationToken( final NameNode namenode, final UserGroupInformation ugi, final String renewer) throws IOException { final Credentials c = DelegationTokenSecretManager.createCredentials( namenode, ugi, renewer != null? renewer: ugi.getShortUserName()); final Token<? extends TokenIdentifier> t = c.getAllTokens().iterator().next(); Text kind = request.getScheme().equals("http") ? WebHdfsFileSystem.TOKEN_KIND : SWebHdfsFileSystem.TOKEN_KIND; t.setKind(kind); return t; } private URI redirectURI(final NameNode namenode, final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String path, final HttpOpParam.Op op, final long openOffset, final long blocksize, final String excludeDatanodes, final Param<?, ?>... parameters) throws URISyntaxException, IOException { final DatanodeInfo dn; try { dn = chooseDatanode(namenode, path, op, openOffset, blocksize, excludeDatanodes); } catch (InvalidTopologyException ite) { throw new IOException("Failed to find datanode, suggest to check cluster health.", ite); } final String delegationQuery; if (!UserGroupInformation.isSecurityEnabled()) { //security disabled delegationQuery = Param.toSortedString("&", doAsUser, username); } else if (delegation.getValue() != null) { //client has provided a token delegationQuery = "&" + delegation; } else { //generate a token final Token<? extends TokenIdentifier> t = generateDelegationToken( namenode, ugi, request.getUserPrincipal().getName()); delegationQuery = "&" + new DelegationParam(t.encodeToUrlString()); } final String query = op.toQueryString() + delegationQuery + "&" + new NamenodeAddressParam(namenode) + Param.toSortedString("&", parameters); final String uripath = WebHdfsFileSystem.PATH_PREFIX + path; final String scheme = request.getScheme(); int port = "http".equals(scheme) ? dn.getInfoPort() : dn .getInfoSecurePort(); final URI uri = new URI(scheme, null, dn.getHostName(), port, uripath, query, null); if (LOG.isTraceEnabled()) { LOG.trace("redirectURI=" + uri); } return uri; } /** Handle HTTP PUT request for the root. */ @PUT @Path("/") @Consumes({"*/*"}) @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) public Response putRoot( @Context final UserGroupInformation ugi, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @QueryParam(PutOpParam.NAME) @DefaultValue(PutOpParam.DEFAULT) final PutOpParam op, @QueryParam(DestinationParam.NAME) @DefaultValue(DestinationParam.DEFAULT) final DestinationParam destination, @QueryParam(OwnerParam.NAME) @DefaultValue(OwnerParam.DEFAULT) final OwnerParam owner, @QueryParam(GroupParam.NAME) @DefaultValue(GroupParam.DEFAULT) final GroupParam group, @QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT) final PermissionParam permission, @QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT) final OverwriteParam overwrite, @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT) final BufferSizeParam bufferSize, @QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT) final ReplicationParam replication, @QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT) final BlockSizeParam blockSize, @QueryParam(ModificationTimeParam.NAME) @DefaultValue(ModificationTimeParam.DEFAULT) final ModificationTimeParam modificationTime, @QueryParam(AccessTimeParam.NAME) @DefaultValue(AccessTimeParam.DEFAULT) final AccessTimeParam accessTime, @QueryParam(RenameOptionSetParam.NAME) @DefaultValue(RenameOptionSetParam.DEFAULT) final RenameOptionSetParam renameOptions, @QueryParam(CreateParentParam.NAME) @DefaultValue(CreateParentParam.DEFAULT) final CreateParentParam createParent, @QueryParam(TokenArgumentParam.NAME) @DefaultValue(TokenArgumentParam.DEFAULT) final TokenArgumentParam delegationTokenArgument, @QueryParam(AclPermissionParam.NAME) @DefaultValue(AclPermissionParam.DEFAULT) final AclPermissionParam aclPermission, @QueryParam(XAttrNameParam.NAME) @DefaultValue(XAttrNameParam.DEFAULT) final XAttrNameParam xattrName, @QueryParam(XAttrValueParam.NAME) @DefaultValue(XAttrValueParam.DEFAULT) final XAttrValueParam xattrValue, @QueryParam(XAttrSetFlagParam.NAME) @DefaultValue(XAttrSetFlagParam.DEFAULT) final XAttrSetFlagParam xattrSetFlag, @QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT) final SnapshotNameParam snapshotName, @QueryParam(OldSnapshotNameParam.NAME) @DefaultValue(OldSnapshotNameParam.DEFAULT) final OldSnapshotNameParam oldSnapshotName, @QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT) final ExcludeDatanodesParam excludeDatanodes ) throws IOException, InterruptedException { return put(ugi, delegation, username, doAsUser, ROOT, op, destination, owner, group, permission, overwrite, bufferSize, replication, blockSize, modificationTime, accessTime, renameOptions, createParent, delegationTokenArgument, aclPermission, xattrName, xattrValue, xattrSetFlag, snapshotName, oldSnapshotName, excludeDatanodes); } /** Handle HTTP PUT request. */ @PUT @Path("{" + UriFsPathParam.NAME + ":.*}") @Consumes({"*/*"}) @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) public Response put( @Context final UserGroupInformation ugi, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @PathParam(UriFsPathParam.NAME) final UriFsPathParam path, @QueryParam(PutOpParam.NAME) @DefaultValue(PutOpParam.DEFAULT) final PutOpParam op, @QueryParam(DestinationParam.NAME) @DefaultValue(DestinationParam.DEFAULT) final DestinationParam destination, @QueryParam(OwnerParam.NAME) @DefaultValue(OwnerParam.DEFAULT) final OwnerParam owner, @QueryParam(GroupParam.NAME) @DefaultValue(GroupParam.DEFAULT) final GroupParam group, @QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT) final PermissionParam permission, @QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT) final OverwriteParam overwrite, @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT) final BufferSizeParam bufferSize, @QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT) final ReplicationParam replication, @QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT) final BlockSizeParam blockSize, @QueryParam(ModificationTimeParam.NAME) @DefaultValue(ModificationTimeParam.DEFAULT) final ModificationTimeParam modificationTime, @QueryParam(AccessTimeParam.NAME) @DefaultValue(AccessTimeParam.DEFAULT) final AccessTimeParam accessTime, @QueryParam(RenameOptionSetParam.NAME) @DefaultValue(RenameOptionSetParam.DEFAULT) final RenameOptionSetParam renameOptions, @QueryParam(CreateParentParam.NAME) @DefaultValue(CreateParentParam.DEFAULT) final CreateParentParam createParent, @QueryParam(TokenArgumentParam.NAME) @DefaultValue(TokenArgumentParam.DEFAULT) final TokenArgumentParam delegationTokenArgument, @QueryParam(AclPermissionParam.NAME) @DefaultValue(AclPermissionParam.DEFAULT) final AclPermissionParam aclPermission, @QueryParam(XAttrNameParam.NAME) @DefaultValue(XAttrNameParam.DEFAULT) final XAttrNameParam xattrName, @QueryParam(XAttrValueParam.NAME) @DefaultValue(XAttrValueParam.DEFAULT) final XAttrValueParam xattrValue, @QueryParam(XAttrSetFlagParam.NAME) @DefaultValue(XAttrSetFlagParam.DEFAULT) final XAttrSetFlagParam xattrSetFlag, @QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT) final SnapshotNameParam snapshotName, @QueryParam(OldSnapshotNameParam.NAME) @DefaultValue(OldSnapshotNameParam.DEFAULT) final OldSnapshotNameParam oldSnapshotName, @QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT) final ExcludeDatanodesParam excludeDatanodes ) throws IOException, InterruptedException { init(ugi, delegation, username, doAsUser, path, op, destination, owner, group, permission, overwrite, bufferSize, replication, blockSize, modificationTime, accessTime, renameOptions, delegationTokenArgument, aclPermission, xattrName, xattrValue, xattrSetFlag, snapshotName, oldSnapshotName, excludeDatanodes); return ugi.doAs(new PrivilegedExceptionAction<Response>() { @Override public Response run() throws IOException, URISyntaxException { try { return put(ugi, delegation, username, doAsUser, path.getAbsolutePath(), op, destination, owner, group, permission, overwrite, bufferSize, replication, blockSize, modificationTime, accessTime, renameOptions, createParent, delegationTokenArgument, aclPermission, xattrName, xattrValue, xattrSetFlag, snapshotName, oldSnapshotName, excludeDatanodes); } finally { reset(); } } }); } private Response put( final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String fullpath, final PutOpParam op, final DestinationParam destination, final OwnerParam owner, final GroupParam group, final PermissionParam permission, final OverwriteParam overwrite, final BufferSizeParam bufferSize, final ReplicationParam replication, final BlockSizeParam blockSize, final ModificationTimeParam modificationTime, final AccessTimeParam accessTime, final RenameOptionSetParam renameOptions, final CreateParentParam createParent, final TokenArgumentParam delegationTokenArgument, final AclPermissionParam aclPermission, final XAttrNameParam xattrName, final XAttrValueParam xattrValue, final XAttrSetFlagParam xattrSetFlag, final SnapshotNameParam snapshotName, final OldSnapshotNameParam oldSnapshotName, final ExcludeDatanodesParam exclDatanodes ) throws IOException, URISyntaxException { final Configuration conf = (Configuration)context.getAttribute(JspHelper.CURRENT_CONF); final NameNode namenode = (NameNode)context.getAttribute("name.node"); final NamenodeProtocols np = getRPCServer(namenode); switch(op.getValue()) { case CREATE: { final URI uri = redirectURI(namenode, ugi, delegation, username, doAsUser, fullpath, op.getValue(), -1L, blockSize.getValue(conf), exclDatanodes.getValue(), permission, overwrite, bufferSize, replication, blockSize); return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build(); } case MKDIRS: { final boolean b = np.mkdirs(fullpath, permission.getFsPermission(), true); final String js = JsonUtil.toJsonString("boolean", b); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case CREATESYMLINK: { np.createSymlink(destination.getValue(), fullpath, PermissionParam.getDefaultFsPermission(), createParent.getValue()); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case RENAME: { final EnumSet<Options.Rename> s = renameOptions.getValue(); if (s.isEmpty()) { final boolean b = np.rename(fullpath, destination.getValue()); final String js = JsonUtil.toJsonString("boolean", b); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } else { np.rename2(fullpath, destination.getValue(), s.toArray(new Options.Rename[s.size()])); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } } case SETREPLICATION: { final boolean b = np.setReplication(fullpath, replication.getValue(conf)); final String js = JsonUtil.toJsonString("boolean", b); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case SETOWNER: { if (owner.getValue() == null && group.getValue() == null) { throw new IllegalArgumentException("Both owner and group are empty."); } np.setOwner(fullpath, owner.getValue(), group.getValue()); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case SETPERMISSION: { np.setPermission(fullpath, permission.getFsPermission()); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case SETTIMES: { np.setTimes(fullpath, modificationTime.getValue(), accessTime.getValue()); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case RENEWDELEGATIONTOKEN: { final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>(); token.decodeFromUrlString(delegationTokenArgument.getValue()); final long expiryTime = np.renewDelegationToken(token); final String js = JsonUtil.toJsonString("long", expiryTime); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case CANCELDELEGATIONTOKEN: { final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>(); token.decodeFromUrlString(delegationTokenArgument.getValue()); np.cancelDelegationToken(token); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case MODIFYACLENTRIES: { np.modifyAclEntries(fullpath, aclPermission.getAclPermission(true)); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case REMOVEACLENTRIES: { np.removeAclEntries(fullpath, aclPermission.getAclPermission(false)); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case REMOVEDEFAULTACL: { np.removeDefaultAcl(fullpath); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case REMOVEACL: { np.removeAcl(fullpath); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case SETACL: { np.setAcl(fullpath, aclPermission.getAclPermission(true)); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case SETXATTR: { np.setXAttr( fullpath, XAttrHelper.buildXAttr(xattrName.getXAttrName(), xattrValue.getXAttrValue()), xattrSetFlag.getFlag()); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case REMOVEXATTR: { np.removeXAttr(fullpath, XAttrHelper.buildXAttr(xattrName.getXAttrName())); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } case CREATESNAPSHOT: { String snapshotPath = np.createSnapshot(fullpath, snapshotName.getValue()); final String js = JsonUtil.toJsonString( org.apache.hadoop.fs.Path.class.getSimpleName(), snapshotPath); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case RENAMESNAPSHOT: { np.renameSnapshot(fullpath, oldSnapshotName.getValue(), snapshotName.getValue()); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } default: throw new UnsupportedOperationException(op + " is not supported"); } } /** Handle HTTP POST request for the root. */ @POST @Path("/") @Consumes({"*/*"}) @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) public Response postRoot( @Context final UserGroupInformation ugi, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @QueryParam(PostOpParam.NAME) @DefaultValue(PostOpParam.DEFAULT) final PostOpParam op, @QueryParam(ConcatSourcesParam.NAME) @DefaultValue(ConcatSourcesParam.DEFAULT) final ConcatSourcesParam concatSrcs, @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT) final BufferSizeParam bufferSize, @QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT) final ExcludeDatanodesParam excludeDatanodes ) throws IOException, InterruptedException { return post(ugi, delegation, username, doAsUser, ROOT, op, concatSrcs, bufferSize, excludeDatanodes); } /** Handle HTTP POST request. */ @POST @Path("{" + UriFsPathParam.NAME + ":.*}") @Consumes({"*/*"}) @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) public Response post( @Context final UserGroupInformation ugi, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @PathParam(UriFsPathParam.NAME) final UriFsPathParam path, @QueryParam(PostOpParam.NAME) @DefaultValue(PostOpParam.DEFAULT) final PostOpParam op, @QueryParam(ConcatSourcesParam.NAME) @DefaultValue(ConcatSourcesParam.DEFAULT) final ConcatSourcesParam concatSrcs, @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT) final BufferSizeParam bufferSize, @QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT) final ExcludeDatanodesParam excludeDatanodes ) throws IOException, InterruptedException { init(ugi, delegation, username, doAsUser, path, op, concatSrcs, bufferSize, excludeDatanodes); return ugi.doAs(new PrivilegedExceptionAction<Response>() { @Override public Response run() throws IOException, URISyntaxException { try { return post(ugi, delegation, username, doAsUser, path.getAbsolutePath(), op, concatSrcs, bufferSize, excludeDatanodes); } finally { reset(); } } }); } private Response post( final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String fullpath, final PostOpParam op, final ConcatSourcesParam concatSrcs, final BufferSizeParam bufferSize, final ExcludeDatanodesParam excludeDatanodes ) throws IOException, URISyntaxException { final NameNode namenode = (NameNode)context.getAttribute("name.node"); switch(op.getValue()) { case APPEND: { final URI uri = redirectURI(namenode, ugi, delegation, username, doAsUser, fullpath, op.getValue(), -1L, -1L, excludeDatanodes.getValue(), bufferSize); return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build(); } case CONCAT: { getRPCServer(namenode).concat(fullpath, concatSrcs.getAbsolutePaths()); return Response.ok().build(); } default: throw new UnsupportedOperationException(op + " is not supported"); } } /** Handle HTTP GET request for the root. */ @GET @Path("/") @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) public Response getRoot( @Context final UserGroupInformation ugi, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @QueryParam(GetOpParam.NAME) @DefaultValue(GetOpParam.DEFAULT) final GetOpParam op, @QueryParam(OffsetParam.NAME) @DefaultValue(OffsetParam.DEFAULT) final OffsetParam offset, @QueryParam(LengthParam.NAME) @DefaultValue(LengthParam.DEFAULT) final LengthParam length, @QueryParam(RenewerParam.NAME) @DefaultValue(RenewerParam.DEFAULT) final RenewerParam renewer, @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT) final BufferSizeParam bufferSize, @QueryParam(XAttrNameParam.NAME) @DefaultValue(XAttrNameParam.DEFAULT) final List<XAttrNameParam> xattrNames, @QueryParam(XAttrEncodingParam.NAME) @DefaultValue(XAttrEncodingParam.DEFAULT) final XAttrEncodingParam xattrEncoding, @QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT) final ExcludeDatanodesParam excludeDatanodes, @QueryParam(FsActionParam.NAME) @DefaultValue(FsActionParam.DEFAULT) final FsActionParam fsAction ) throws IOException, InterruptedException { return get(ugi, delegation, username, doAsUser, ROOT, op, offset, length, renewer, bufferSize, xattrNames, xattrEncoding, excludeDatanodes, fsAction); } /** Handle HTTP GET request. */ @GET @Path("{" + UriFsPathParam.NAME + ":.*}") @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) public Response get( @Context final UserGroupInformation ugi, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @PathParam(UriFsPathParam.NAME) final UriFsPathParam path, @QueryParam(GetOpParam.NAME) @DefaultValue(GetOpParam.DEFAULT) final GetOpParam op, @QueryParam(OffsetParam.NAME) @DefaultValue(OffsetParam.DEFAULT) final OffsetParam offset, @QueryParam(LengthParam.NAME) @DefaultValue(LengthParam.DEFAULT) final LengthParam length, @QueryParam(RenewerParam.NAME) @DefaultValue(RenewerParam.DEFAULT) final RenewerParam renewer, @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT) final BufferSizeParam bufferSize, @QueryParam(XAttrNameParam.NAME) @DefaultValue(XAttrNameParam.DEFAULT) final List<XAttrNameParam> xattrNames, @QueryParam(XAttrEncodingParam.NAME) @DefaultValue(XAttrEncodingParam.DEFAULT) final XAttrEncodingParam xattrEncoding, @QueryParam(ExcludeDatanodesParam.NAME) @DefaultValue(ExcludeDatanodesParam.DEFAULT) final ExcludeDatanodesParam excludeDatanodes, @QueryParam(FsActionParam.NAME) @DefaultValue(FsActionParam.DEFAULT) final FsActionParam fsAction ) throws IOException, InterruptedException { init(ugi, delegation, username, doAsUser, path, op, offset, length, renewer, bufferSize, xattrEncoding, excludeDatanodes, fsAction); return ugi.doAs(new PrivilegedExceptionAction<Response>() { @Override public Response run() throws IOException, URISyntaxException { try { return get(ugi, delegation, username, doAsUser, path.getAbsolutePath(), op, offset, length, renewer, bufferSize, xattrNames, xattrEncoding, excludeDatanodes, fsAction); } finally { reset(); } } }); } private Response get( final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String fullpath, final GetOpParam op, final OffsetParam offset, final LengthParam length, final RenewerParam renewer, final BufferSizeParam bufferSize, final List<XAttrNameParam> xattrNames, final XAttrEncodingParam xattrEncoding, final ExcludeDatanodesParam excludeDatanodes, final FsActionParam fsAction ) throws IOException, URISyntaxException { final NameNode namenode = (NameNode)context.getAttribute("name.node"); final NamenodeProtocols np = getRPCServer(namenode); switch(op.getValue()) { case OPEN: { final URI uri = redirectURI(namenode, ugi, delegation, username, doAsUser, fullpath, op.getValue(), offset.getValue(), -1L, excludeDatanodes.getValue(), offset, length, bufferSize); return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build(); } case GET_BLOCK_LOCATIONS: { final long offsetValue = offset.getValue(); final Long lengthValue = length.getValue(); final LocatedBlocks locatedblocks = np.getBlockLocations(fullpath, offsetValue, lengthValue != null? lengthValue: Long.MAX_VALUE); final String js = JsonUtil.toJsonString(locatedblocks); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETFILESTATUS: { final HdfsFileStatus status = np.getFileInfo(fullpath); if (status == null) { throw new FileNotFoundException("File does not exist: " + fullpath); } final String js = JsonUtil.toJsonString(status, true); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case LISTSTATUS: { final StreamingOutput streaming = getListingStream(np, fullpath); return Response.ok(streaming).type(MediaType.APPLICATION_JSON).build(); } case GETCONTENTSUMMARY: { final ContentSummary contentsummary = np.getContentSummary(fullpath); final String js = JsonUtil.toJsonString(contentsummary); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETFILECHECKSUM: { final URI uri = redirectURI(namenode, ugi, delegation, username, doAsUser, fullpath, op.getValue(), -1L, -1L, null); return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build(); } case GETDELEGATIONTOKEN: { if (delegation.getValue() != null) { throw new IllegalArgumentException(delegation.getName() + " parameter is not null."); } final Token<? extends TokenIdentifier> token = generateDelegationToken( namenode, ugi, renewer.getValue()); final String js = JsonUtil.toJsonString(token); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETHOMEDIRECTORY: { final String js = JsonUtil.toJsonString( org.apache.hadoop.fs.Path.class.getSimpleName(), WebHdfsFileSystem.getHomeDirectoryString(ugi)); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETACLSTATUS: { AclStatus status = np.getAclStatus(fullpath); if (status == null) { throw new FileNotFoundException("File does not exist: " + fullpath); } final String js = JsonUtil.toJsonString(status); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case GETXATTRS: { List<String> names = null; if (xattrNames != null) { names = Lists.newArrayListWithCapacity(xattrNames.size()); for (XAttrNameParam xattrName : xattrNames) { if (xattrName.getXAttrName() != null) { names.add(xattrName.getXAttrName()); } } } List<XAttr> xAttrs = np.getXAttrs(fullpath, (names != null && !names.isEmpty()) ? XAttrHelper.buildXAttrs(names) : null); final String js = JsonUtil.toJsonString(xAttrs, xattrEncoding.getEncoding()); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case LISTXATTRS: { final List<XAttr> xAttrs = np.listXAttrs(fullpath); final String js = JsonUtil.toJsonString(xAttrs); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case CHECKACCESS: { np.checkAccess(fullpath, FsAction.getFsAction(fsAction.getValue())); return Response.ok().build(); } default: throw new UnsupportedOperationException(op + " is not supported"); } } private static DirectoryListing getDirectoryListing(final NamenodeProtocols np, final String p, byte[] startAfter) throws IOException { final DirectoryListing listing = np.getListing(p, startAfter, false); if (listing == null) { // the directory does not exist throw new FileNotFoundException("File " + p + " does not exist."); } return listing; } private static StreamingOutput getListingStream(final NamenodeProtocols np, final String p) throws IOException { // allows exceptions like FNF or ACE to prevent http response of 200 for // a failure since we can't (currently) return error responses in the // middle of a streaming operation final DirectoryListing firstDirList = getDirectoryListing(np, p, HdfsFileStatus.EMPTY_NAME); // must save ugi because the streaming object will be executed outside // the remote user's ugi final UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); return new StreamingOutput() { @Override public void write(final OutputStream outstream) throws IOException { final PrintWriter out = new PrintWriter(new OutputStreamWriter( outstream, Charsets.UTF_8)); out.println("{\"" + FileStatus.class.getSimpleName() + "es\":{\"" + FileStatus.class.getSimpleName() + "\":["); try { // restore remote user's ugi ugi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws IOException { long n = 0; for (DirectoryListing dirList = firstDirList; ; dirList = getDirectoryListing(np, p, dirList.getLastName()) ) { // send each segment of the directory listing for (HdfsFileStatus s : dirList.getPartialListing()) { if (n++ > 0) { out.println(','); } out.print(JsonUtil.toJsonString(s, false)); } // stop if last segment if (!dirList.hasMore()) { break; } } return null; } }); } catch (InterruptedException e) { throw new IOException(e); } out.println(); out.println("]}}"); out.flush(); } }; } /** Handle HTTP DELETE request for the root. */ @DELETE @Path("/") @Produces(MediaType.APPLICATION_JSON) public Response deleteRoot( @Context final UserGroupInformation ugi, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT) final DeleteOpParam op, @QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT) final RecursiveParam recursive, @QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT) final SnapshotNameParam snapshotName ) throws IOException, InterruptedException { return delete(ugi, delegation, username, doAsUser, ROOT, op, recursive, snapshotName); } /** Handle HTTP DELETE request. */ @DELETE @Path("{" + UriFsPathParam.NAME + ":.*}") @Produces(MediaType.APPLICATION_JSON) public Response delete( @Context final UserGroupInformation ugi, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @PathParam(UriFsPathParam.NAME) final UriFsPathParam path, @QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT) final DeleteOpParam op, @QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT) final RecursiveParam recursive, @QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT) final SnapshotNameParam snapshotName ) throws IOException, InterruptedException { init(ugi, delegation, username, doAsUser, path, op, recursive, snapshotName); return ugi.doAs(new PrivilegedExceptionAction<Response>() { @Override public Response run() throws IOException { try { return delete(ugi, delegation, username, doAsUser, path.getAbsolutePath(), op, recursive, snapshotName); } finally { reset(); } } }); } private Response delete( final UserGroupInformation ugi, final DelegationParam delegation, final UserParam username, final DoAsParam doAsUser, final String fullpath, final DeleteOpParam op, final RecursiveParam recursive, final SnapshotNameParam snapshotName ) throws IOException { final NameNode namenode = (NameNode)context.getAttribute("name.node"); final NamenodeProtocols np = getRPCServer(namenode); switch(op.getValue()) { case DELETE: { final boolean b = np.delete(fullpath, recursive.getValue()); final String js = JsonUtil.toJsonString("boolean", b); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); } case DELETESNAPSHOT: { np.deleteSnapshot(fullpath, snapshotName.getValue()); return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build(); } default: throw new UnsupportedOperationException(op + " is not supported"); } } }
/* * Copyright 2002-2006,2009 The Apache Software Foundation. * * 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.opensymphony.xwork2.validator.validators; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.CompositeTextProvider; import com.opensymphony.xwork2.TextProvider; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.util.ValueStack; import com.opensymphony.xwork2.validator.ActionValidatorManager; import com.opensymphony.xwork2.validator.DelegatingValidatorContext; import com.opensymphony.xwork2.validator.ValidationException; import com.opensymphony.xwork2.validator.ValidatorContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * <!-- START SNIPPET: javadoc --> * * <p> * The VisitorFieldValidator allows you to forward validation to object * properties of your action using the object's own validation files. This * allows you to use the ModelDriven development pattern and manage your * validations for your models in one place, where they belong, next to your * model classes. The VisitorFieldValidator can handle either simple Object * properties, Collections of Objects, or Arrays. * </p> * * <!-- END SNIPPET: javadoc --> * * <!-- START SNIPPET: parameters --> * <ul> * <li>fieldName - field name if plain-validator syntax is used, not needed if field-validator syntax is used</li> * <li>context - the context of which validation should take place. Optional</li> * <li>appendPrefix - the prefix to be added to field. Optional </li> * </ul> * <!-- END SNIPPET: parameters --> * * <pre> * <!-- START SNIPPET: example --> * &lt;validators&gt; * &lt;!-- Plain Validator Syntax --&gt; * &lt;validator type="visitor"&gt; * &lt;param name="fieldName"&gt;user&lt;/param&gt; * &lt;param name="context"&gt;myContext&lt;/param&gt; * &lt;param name="appendPrefix"&gt;true&lt;/param&gt; * &lt;/validator&gt; * * &lt;!-- Field Validator Syntax --&gt; * &lt;field name="user"&gt; * &lt;field-validator type="visitor"&gt; * &lt;param name="context"&gt;myContext&lt;/param&gt; * &lt;param name="appendPrefix"&gt;true&lt;/param&gt; * &lt;/field-validator&gt; * &lt;/field&gt; * &lt;/validators&gt; * <!-- END SNIPPET: example --> * </pre> * * <!-- START SNIPPET: explanation --> * <p>In the example above, if the action's getUser() method return User object, XWork * will look for User-myContext-validation.xml for the validators. Since appednPrefix is true, * every field name will be prefixed with 'user' such that if the actual field name for 'name' is * 'user.name' </p> * <!-- END SNIPPET: explanation --> * * @author Jason Carreira * @author Rainer Hermanns */ public class VisitorFieldValidator extends FieldValidatorSupport { private static final Logger LOG = LogManager.getLogger(VisitorFieldValidator.class); private String context; private boolean appendPrefix = true; private ActionValidatorManager actionValidatorManager; @Inject public void setActionValidatorManager(ActionValidatorManager mgr) { this.actionValidatorManager = mgr; } /** * @param appendPrefix whether the field name of this field validator should be prepended to the field name of * the visited field to determine the full field name when an error occurs. The default is * true. */ public void setAppendPrefix(boolean appendPrefix) { this.appendPrefix = appendPrefix; } /** * @return whether the field name of this field validator should be prepended to the field name of * the visited field to determine the full field name when an error occurs. The default is * true. */ public boolean isAppendPrefix() { return appendPrefix; } public void setContext(String context) { this.context = context; } public String getContext() { return context; } public void validate(Object object) throws ValidationException { String fieldName = getFieldName(); Object value = this.getFieldValue(fieldName, object); if (value == null) { LOG.warn("The visited object is null, VisitorValidator will not be able to handle validation properly. Please make sure the visited object is not null for VisitorValidator to function properly"); return; } ValueStack stack = ActionContext.getContext().getValueStack(); stack.push(object); String visitorContext = (context == null) ? ActionContext.getContext().getName() : context; if (value instanceof Collection) { Collection coll = (Collection) value; Object[] array = coll.toArray(); validateArrayElements(array, fieldName, visitorContext); } else if (value instanceof Object[]) { Object[] array = (Object[]) value; validateArrayElements(array, fieldName, visitorContext); } else { validateObject(fieldName, value, visitorContext); } stack.pop(); } private void validateArrayElements(Object[] array, String fieldName, String visitorContext) throws ValidationException { if (array == null) { return; } for (int i = 0; i < array.length; i++) { Object o = array[i]; if (o != null) { validateObject(fieldName + "[" + i + "]", o, visitorContext); } } } private void validateObject(String fieldName, Object o, String visitorContext) throws ValidationException { ValueStack stack = ActionContext.getContext().getValueStack(); stack.push(o); ValidatorContext validatorContext; if (appendPrefix) { ValidatorContext parent = getValidatorContext(); validatorContext = new AppendingValidatorContext(parent, createTextProvider(o, parent), fieldName, getMessage(o)); } else { ValidatorContext parent = getValidatorContext(); CompositeTextProvider textProvider = createTextProvider(o, parent); validatorContext = new DelegatingValidatorContext(parent, textProvider, parent); } actionValidatorManager.validate(o, visitorContext, validatorContext); stack.pop(); } private CompositeTextProvider createTextProvider(Object o, ValidatorContext parent) { List<TextProvider> textProviders = new LinkedList<>(); if (o instanceof TextProvider) { textProviders.add((TextProvider) o); } else { textProviders.add(textProviderFactory.createInstance(o.getClass())); } textProviders.add(parent); return new CompositeTextProvider(textProviders); } public static class AppendingValidatorContext extends DelegatingValidatorContext { private String field; private String message; private ValidatorContext parent; public AppendingValidatorContext(ValidatorContext parent, TextProvider textProvider, String field, String message) { super(parent, textProvider, parent); this.field = field; this.message = message; this.parent = parent; } /** * Translates a simple field name into a full field name in Ognl syntax * * @param fieldName field name in OGNL syntax * @return full field name in OGNL syntax */ @Override public String getFullFieldName(String fieldName) { if (parent instanceof VisitorFieldValidator.AppendingValidatorContext) { return parent.getFullFieldName(field + "." + fieldName); } return field + "." + fieldName; } public String getFieldNameWithField(String fieldName) { return field + "." + fieldName; } @Override public void addActionError(String anErrorMessage) { super.addFieldError(getFieldNameWithField(field), message + anErrorMessage); } @Override public void addFieldError(String fieldName, String errorMessage) { super.addFieldError(getFieldNameWithField(fieldName), message + errorMessage); } } }
package uk.co.transputersystems.transputer.simulator; import uk.co.transputersystems.transputer.simulator.debugger.CommandExecutor; import uk.co.transputersystems.transputer.simulator.debugger.CommandResult; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ConsoleErrorListener; import org.antlr.v4.runtime.tree.ParseTree; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; import static java.io.File.pathSeparatorChar; public class Simulator { private static CommandResult executeCommand(String command, Transputer[] transputers, PrintWriter output, PrintWriter errOutput) { DebuggerCommandLexer commandLexer = new DebuggerCommandLexer(new ANTLRInputStream(command)); commandLexer.removeErrorListener(ConsoleErrorListener.INSTANCE); CommonTokenStream tokenStream = new CommonTokenStream(commandLexer); ErrorListener errorListener = new ErrorListener(); DebuggerCommandParser commandParser = new DebuggerCommandParser(tokenStream); commandParser.addErrorListener(errorListener); commandParser.removeErrorListener(ConsoleErrorListener.INSTANCE); ParseTree commandTree = commandParser.command(); if (errorListener.errors != 0) { output.println("Command not recognised."); output.flush(); return CommandResult.NOT_RECOGNISED; } CommandExecutor executor = new CommandExecutor(transputers, output, errOutput); return executor.visit(commandTree); } private static boolean interact(Transputer[] transputers, Scanner input, PrintWriter output, PrintWriter errOutput) { String command; CommandResult result; while (true) { System.out.printf("> "); command = input.nextLine(); output.printf("\n"); switch (executeCommand(command, transputers, output, errOutput)) { case CONTINUE: return false; case STEP: return true; default: } } } public static SimulatorConfig parseOptions(String[] args) { OptionParser optionParser = new OptionParser(); OptionSpec interactiveArg = optionParser.accepts("interactive"); OptionSpec printWorkspaceMemArg = optionParser.accepts("print-workspace-mem"); OptionSpec<File> verilogTestbenchArg = optionParser .accepts("verilog-testbench-gen") .withRequiredArg() .ofType(File.class) .describedAs("generate test checking files for verilog testbench"); OptionSpec<File> schedulerArg = optionParser .accepts("scheduler-test") .withRequiredArg() .ofType(File.class) .describedAs("generate test checking including scheduler registers"); OptionSpec<File> timerArg = optionParser .accepts("timer-test") .withRequiredArg() .ofType(File.class) .describedAs("generate test checking including timer registers"); OptionSpec<File> binariesArg = optionParser .accepts("binaries") .withRequiredArg() .required() .ofType(File.class) .withValuesSeparatedBy(pathSeparatorChar); OptionSet options = optionParser.parse(args); SimulatorConfig config = new SimulatorConfig(options.has(interactiveArg), options.valueOf(verilogTestbenchArg), options.valueOf(schedulerArg), options.valueOf(timerArg), options.valuesOf(binariesArg), options.has(printWorkspaceMemArg)); if (config.binaries.size() == 0) { throw new IllegalArgumentException("At least one binary must be supplied."); } else if (config.binaries.size() > 4) { // TODO: lift this restriction? throw new IllegalArgumentException("At most four binaries can be supplied."); } return config; } public static void run(String[] args) throws Exception { SimulatorConfig config = parseOptions(args); Transputer[] transputers; HashSet<Transputer> activeTransputers; boolean anyTransputerActive = true; boolean hitBreak; boolean currentlyInteractive = config.interactive; long loopCount = 0; PrintWriter stdout = new PrintWriter(System.out); PrintWriter stderr = new PrintWriter(System.err); Scanner stdin = new Scanner(System.in); FileWriter testCheckerFileWriter = null; PrintWriter testCheckerPrintWriter = null; FileWriter schedCheckerFileWriter = null; PrintWriter schedCheckerPrintWriter = null; FileWriter timerCheckerFileWriter = null; PrintWriter timerCheckerPrintWriter = null; //int i, j; boolean worked; if (config.testChecker != null) { // Open output file and write initial state testCheckerFileWriter = new FileWriter(config.testChecker, false); testCheckerPrintWriter = new PrintWriter(testCheckerFileWriter); } if (config.schedChecker != null) { // Open output file and write initial state schedCheckerFileWriter = new FileWriter(config.schedChecker, false); schedCheckerPrintWriter = new PrintWriter(schedCheckerFileWriter); } if (config.timerChecker != null) { timerCheckerFileWriter = new FileWriter(config.timerChecker, false); timerCheckerPrintWriter = new PrintWriter(timerCheckerFileWriter); } stdout.printf("# Loading\n"); transputers = new Transputer[config.binaries.size()]; activeTransputers = new HashSet<>(); for (int i = 0; i < config.binaries.size(); i++) { transputers[i] = new Transputer((byte) i, stdout, stderr); transputers[i].loadProgram(config.binaries.get(i)); transputers[i].printRecentMemory(stdout); transputers[i].printRegisters(stdout); if (config.testChecker != null) { transputers[i].logState(0, testCheckerPrintWriter); } if (config.schedChecker != null) { transputers[i].logSched(0, schedCheckerPrintWriter); } if (config.timerChecker != null) { transputers[i].logTimer(0, timerCheckerPrintWriter); } activeTransputers.add(transputers[i]); } stdout.printf("# Starting\n"); stdout.flush(); stderr.flush(); while (anyTransputerActive) { // Check if we hit any breakpoint hitBreak = false; for (Transputer transputer : transputers) { if (activeTransputers.contains(transputer)) { hitBreak = hitBreak || transputer.debuggerState.breakpoints.contains(transputer.registers.Iptr); } } if (currentlyInteractive || hitBreak) { currentlyInteractive = interact(transputers, stdin, stdout, stderr); } anyTransputerActive = false; loopCount += 1; for (Transputer transputer : transputers) { if (activeTransputers.contains(transputer)) { worked = transputer.performStep(); transputer.printRegisters(stdout); transputer.incrementClock(loopCount); if (transputer.programEndPtr < transputer.registers.Iptr || transputer.registers.Iptr < TransputerConstants.CODESTART) { activeTransputers.remove(transputer); } else { anyTransputerActive = true; // Check LinkIn for (int j = 0; j < TransputerConstants.IN_PORTS; j++) { transputer.processInputLink(transputer.inputLinks[j]); } // Check LinkOut transputer.processOutputLink(); } if (config.testChecker != null) { transputer.logState(loopCount - 1, testCheckerPrintWriter); } if (config.schedChecker != null) { transputer.logSched(loopCount - 1, schedCheckerPrintWriter); } if (worked && config.timerChecker != null) { transputer.logTimer(loopCount - 1, timerCheckerPrintWriter); } if (!worked) { activeTransputers.remove(transputer); } } } Transputer.switchStep(transputers, stdout); stdout.flush(); stderr.flush(); } for (Transputer transputer : transputers) { transputer.printRegisters(stdout); transputer.printRecentMemory(stdout); } if (config.testChecker != null) { testCheckerFileWriter.close(); stdout.printf("# Closed log file for testing\n"); } if (config.schedChecker != null) { schedCheckerFileWriter.close(); stdout.printf("# Closed log file for scheduler checking\n"); } if (config.timerChecker != null) { timerCheckerFileWriter.close(); stdout.printf("# Closed log file for timer checking\n"); } if (config.printWorkspaceMemory) { stdout.printf("# Workspace memory usage\n"); for (Transputer transputer : transputers) { transputer.printWorkspaceMemory(stdout); } } stdout.println(); stdout.printf("# Total steps: %d\n", loopCount); stdout.printf("\n==DONE==\n"); stdout.flush(); stderr.flush(); } }
/* * 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.facebook.presto.cli.sparql2sql; import com.facebook.presto.sql.tree.*; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; /** * Created by deke on 5/24/14. */ public class QueryRewrite { private class AttributeRecord{ private String origin; private String target; private int param; public AttributeRecord(String s1, String s2, int param){ origin = s1; target = s2; this.param = param; } public String getOrigin(){ return origin; } public String getTarget(){ return target; } public int getParam(){ return param; } } class Pair{ private Integer key; private String value; public Pair(Integer key, String value){ this.key = key; this.value = value; } public Integer getKey(){ return key; } public String getValue(){ return value; } } String sql; String rewriteSql; Map<String, Pair> tablepair; QueryPrinter printer; MySQLConnection connection; private static String getTargetTable = "select ID, ORIGIN, TARGET from TBL_TRANSFORM"; public QueryRewrite(String sql){ setSql(sql); init(); } private void init(){ rewriteSql = getSql().toLowerCase(); printer = new QueryPrinter(); connection = new MySQLConnection(); tablepair = new HashMap<>(); } public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } private boolean checkFrom(){ boolean isTransform = false; printer.parseQuery(getSql()); List<Table> tables = printer.getFroms(); Map<String, Pair> targets = getTableFromMysql(); for(int i = 0 ; i < tables.size() ; i ++){ String str = tables.get(i).getName().toString(); if(targets.keySet().contains(str)){ System.out.println(tables.get(i).getName() + " has been transformed!"); tablepair.put(str, targets.get(str)); isTransform = true; } } return isTransform; } /* // Usage: parse table from string like "a.b.c.d", returns "a" private String parseTable(String str){ int loc = str.indexOf('.'); if(loc != -1) return str.substring(0, loc); else return str; } */ private Map<Integer, List<AttributeRecord>> getAttribute(){ if(tablepair == null || tablepair.size() == 0){ System.err.println("No table involved, check from should return false!"); return null; } if(!connection.open()){ System.err.println("DB Connection is closed after fetch table!"); connection.openConnection(); } String query = "select TBL_ID, ORIGIN_ATTR, TARGET_ATTR, FLOOR_PARAM from PARTITION_INFO where TBL_ID in (" ; Iterator iterator = tablepair.keySet().iterator(); while(iterator.hasNext()){ query += tablepair.get(iterator.next()).getKey(); if(iterator.hasNext()) query += ", "; else query += ") order by TBL_ID"; } Map<Integer, List<AttributeRecord>> attributes = new HashMap<>(); try{ connection.executeQuery(query); ResultSet rs = connection.getResultSet(); while(rs.next()){ int id = rs.getInt("TBL_ID"); List<AttributeRecord> records; if(attributes.containsKey(id)){ records = attributes.get(id); }else{ records = new ArrayList<>(); } records.add(new AttributeRecord(rs.getString("ORIGIN_ATTR"), rs.getString("TARGET_ATTR"), rs.getInt("FLOOR_PARAM"))); attributes.put(id, records); } }catch(SQLException e){ e.printStackTrace(); } return attributes; } private boolean checkWhere(){ // TODO: check where clause to see if the transformed table appears here, whether with it's attributes and conditions. boolean isTransform = false; List<ComparisonExpression> whereExp = printer.getWheres(); Map<Integer, List<AttributeRecord>> attributes = getAttribute(); // Traverse each where clause for(ComparisonExpression e : whereExp){ if(!(e.getLeft() instanceof QualifiedNameReference)){ System.err.println("do not support " + e.getLeft().getClass().getName() + " in where clause!"); return false; } QualifiedNameReference left = (QualifiedNameReference)(e.getLeft()); String table = left.getPrefix().toString(); if(tablepair.keySet().contains(table)){ String attr = left.getSuffix().toString(); int id = tablepair.get(table).getKey(); // TODO: check if this attr appears in database for(AttributeRecord ar : attributes.get(id)){ if(ar.getOrigin().equals(attr)){ // TODO: get one attribute here, going to check the parameter! System.out.println("catch one attribute! " + left.toString()); addConstraint(e, tablepair.get(table).getValue(), ar); isTransform = true; } } rewriteSql = rewriteSql.replaceAll(table, tablepair.get(table).getValue()); } } return isTransform; } private void addConstraint(ComparisonExpression expression, String replaceTable, AttributeRecord record ){ String constraints = ""; Expression exp = expression.getRight(); double value; if(exp instanceof LongLiteral){ value = ((LongLiteral) exp).getValue(); }else if(exp instanceof DoubleLiteral){ value = ((DoubleLiteral) exp).getValue(); }else{ System.err.println("Do not support partition of type " + exp.getClass().getName()); return; } ComparisonExpression.Type type = expression.getType(); switch (type){ case EQUAL: constraints += replaceTable + "." + record.getTarget() + " = " + (int)(value/record.getParam()); break; case LESS_THAN: for(int i = 0 ; i < value/record.getParam(); i ++) { if(i != 0) constraints += " or "; constraints += replaceTable + "." + record.getTarget() + " = " + i; } break; case LESS_THAN_OR_EQUAL: for(int i = 0 ; i <= value/record.getParam(); i ++) { if(i != 0) constraints += " or "; constraints += replaceTable + "." + record.getTarget() + " = " + i; } break; default: System.err.println("No upper bound with comparison " + type.getValue() + ", cannot using partition information!"); return; } rewriteSql += " and (" + constraints + ")"; } private Map<String, Pair> getTableFromMysql(){ if(!connection.open()) connection.openConnection(); Map<String, Pair> tables = new HashMap<>(); try{ connection.executeQuery(getTargetTable); ResultSet rs = connection.getResultSet(); while(rs.next()){ tables.put(rs.getString("ORIGIN"), new Pair(rs.getInt("ID"), rs.getString("TARGET"))); } }catch(SQLException e){ e.printStackTrace(); return null; } return tables; } public String rewrite(){ if(checkFrom() && checkWhere()) // System.out.println(rewriteSql); connection.close(); return rewriteSql; } }
/* * Copyright 2012 Hai Bison * * 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 org.xdty.authenticator.androidlockpattern; import android.app.Activity; import android.app.Fragment; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.os.ResultReceiver; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.TextView; import org.xdty.authenticator.BuildConfig; import org.xdty.authenticator.R; import org.xdty.authenticator.androidlockpattern.util.IEncrypter; import org.xdty.authenticator.androidlockpattern.util.InvalidEncrypterException; import org.xdty.authenticator.androidlockpattern.util.LoadingView; import org.xdty.authenticator.androidlockpattern.util.Settings; import org.xdty.authenticator.androidlockpattern.util.UI; import org.xdty.authenticator.androidlockpattern.widget.LockPatternUtils; import org.xdty.authenticator.androidlockpattern.widget.LockPatternView; import org.xdty.authenticator.androidlockpattern.widget.LockPatternView.Cell; import org.xdty.authenticator.androidlockpattern.widget.LockPatternView.DisplayMode; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static android.text.format.DateUtils.SECOND_IN_MILLIS; import static org.xdty.authenticator.BuildConfig.DEBUG; import static org.xdty.authenticator.androidlockpattern.util.Settings.Display.METADATA_CAPTCHA_WIRED_DOTS; import static org.xdty.authenticator.androidlockpattern.util.Settings.Display.METADATA_MAX_RETRIES; import static org.xdty.authenticator.androidlockpattern.util.Settings.Display.METADATA_MIN_WIRED_DOTS; import static org.xdty.authenticator.androidlockpattern.util.Settings.Display.METADATA_STEALTH_MODE; import static org.xdty.authenticator.androidlockpattern.util.Settings.Security.METADATA_AUTO_SAVE_PATTERN; import static org.xdty.authenticator.androidlockpattern.util.Settings.Security.METADATA_ENCRYPTER_CLASS; /** * Main activity for this library. * <p> * You can deliver result to {@link PendingIntent}'s and/ or * {@link ResultReceiver} too. See {@link #EXTRA_PENDING_INTENT_OK}, * {@link #EXTRA_PENDING_INTENT_CANCELLED} and {@link #EXTRA_RESULT_RECEIVER} * for more details. * </p> * <p/> * <h1>NOTES</h1> * <ul> * <li> * You must use one of built-in actions when calling this activity. They start * with {@code ACTION_*}. Otherwise the library might behave strangely (we don't * cover those cases).</li> * <li>You must use one of the themes that this library supports. They start * with {@code R.style.Theme_*}. The reason is the themes contain * resources that the library needs.</li> * <li>With {@link #ACTION_COMPARE_PATTERN}, there are <b><i>4 possible result * codes</i></b>: {@link Activity#RESULT_OK}, {@link Activity#RESULT_CANCELED}, * {@link #RESULT_FAILED} and {@link #RESULT_FORGOT_PATTERN}.</li> * <li>With {@link #ACTION_VERIFY_CAPTCHA}, there are <b><i>3 possible result * codes</i></b>: {@link Activity#RESULT_OK}, {@link Activity#RESULT_CANCELED}, * and {@link #RESULT_FAILED}.</li> * </ul> * * @author Hai Bison * @since v1.0 */ public class LockPatternActivity extends Activity { /** * If you use {@link #ACTION_COMPARE_PATTERN} and the user fails to "login" * after a number of tries, this activity will finish with this result code. * * @see #ACTION_COMPARE_PATTERN * @see #EXTRA_RETRY_COUNT */ public static final int RESULT_FAILED = RESULT_FIRST_USER + 1; /** * If you use {@link #ACTION_COMPARE_PATTERN} and the user forgot his/ her * pattern and decided to ask for your help with recovering the pattern ( * {@link #EXTRA_PENDING_INTENT_FORGOT_PATTERN}), this activity will finish * with this result code. * * @see #ACTION_COMPARE_PATTERN * @see #EXTRA_RETRY_COUNT * @see #EXTRA_PENDING_INTENT_FORGOT_PATTERN * @since v2.8 beta */ public static final int RESULT_FORGOT_PATTERN = RESULT_FIRST_USER + 2; private static final String CLASSNAME = LockPatternActivity.class.getName(); /** * Use this action to create new pattern. You can provide an * {@link IEncrypter} with * {@link Settings.Security#setEncrypterClass(Context, Class)} to * improve security. * <p/> * If the user created a pattern, {@link Activity#RESULT_OK} returns with * the pattern ({@link #EXTRA_PATTERN}). Otherwise * {@link Activity#RESULT_CANCELED} returns. * * @see #EXTRA_PENDING_INTENT_OK * @see #EXTRA_PENDING_INTENT_CANCELLED * @since v2.4 beta */ public static final String ACTION_CREATE_PATTERN = CLASSNAME + ".create_pattern"; /** * Use this action to compare pattern. You provide the pattern to be * compared with {@link #EXTRA_PATTERN}. * <p/> * If you enabled feature auto-save pattern before (with * {@link Settings.Security#setAutoSavePattern(Context, boolean)} ), * then you don't need {@link #EXTRA_PATTERN} at this time. But if you use * this extra, its priority is higher than the one stored in shared * preferences. * <p/> * You can use {@link #EXTRA_PENDING_INTENT_FORGOT_PATTERN} to help your * users in case they forgot the patterns. * <p/> * If the user passes, {@link Activity#RESULT_OK} returns. If not, * {@link #RESULT_FAILED} returns. * <p/> * If the user cancels the task, {@link Activity#RESULT_CANCELED} returns. * <p/> * In any case, there will have extra {@link #EXTRA_RETRY_COUNT} available * in the intent result. * * @see #EXTRA_PATTERN * @see #EXTRA_PENDING_INTENT_OK * @see #EXTRA_PENDING_INTENT_CANCELLED * @see #RESULT_FAILED * @see #EXTRA_RETRY_COUNT * @since v2.4 beta */ public static final String ACTION_COMPARE_PATTERN = CLASSNAME + ".compare_pattern"; /** * Use this action to let the activity generate a random pattern and ask the * user to re-draw it to verify. * <p/> * The default length of the auto-generated pattern is {@code 4}. You can * change it with * {@link Settings.Display#setCaptchaWiredDots(Context, int)}. * * @since v2.7 beta */ public static final String ACTION_VERIFY_CAPTCHA = CLASSNAME + ".verify_captcha"; /** * For actions {@link #ACTION_COMPARE_PATTERN} and * {@link #ACTION_VERIFY_CAPTCHA}, this key holds the number of tries that * the user attempted to verify the input pattern. */ public static final String EXTRA_RETRY_COUNT = CLASSNAME + ".retry_count"; /** * Sets value of this key to a theme in {@code R.style.Theme_*} * . Default is the one you set in your {@code AndroidManifest.xml}. Note * that theme {@link R.style#Theme_Light_DarkActionBar} is * available in API 4+, but it only works in API 14+. * * @since v1.5.3 beta */ public static final String EXTRA_THEME = CLASSNAME + ".theme"; /** * Key to hold the pattern. It must be a {@code char[]} array. * <p/> * <ul> * <li>If you use encrypter, it should be an encrypted array.</li> * <li>If you don't use encrypter, it should be the SHA-1 value of the * actual pattern. You can generate the value by * {@link LockPatternUtils#patternToSha1(List)}.</li> * </ul> * * @since v2 beta */ public static final String EXTRA_PATTERN = CLASSNAME + ".pattern"; /** * You can provide an {@link ResultReceiver} with this key. The activity * will notify your receiver the same result code and intent data as you * will receive them in {@link #onActivityResult(int, int, Intent)}. * * @since v2.4 beta */ public static final String EXTRA_RESULT_RECEIVER = CLASSNAME + ".result_receiver"; /** * Put a {@link PendingIntent} into this key. It will be sent before * {@link Activity#RESULT_OK} will be returning. If you were calling this * activity with {@link #ACTION_CREATE_PATTERN}, key {@link #EXTRA_PATTERN} * will be attached to the original intent which the pending intent holds. * <p/> * <h1>Notes</h1> * <ul> * <li>If you're going to use an activity, you don't need * {@link Intent#FLAG_ACTIVITY_NEW_TASK} for the intent, since the library * will call it inside {@link LockPatternActivity} .</li> * </ul> */ public static final String EXTRA_PENDING_INTENT_OK = CLASSNAME + ".pending_intent_ok"; /** * Put a {@link PendingIntent} into this key. It will be sent before * {@link Activity#RESULT_CANCELED} will be returning. * <p/> * <h1>Notes</h1> * <ul> * <li>If you're going to use an activity, you don't need * {@link Intent#FLAG_ACTIVITY_NEW_TASK} for the intent, since the library * will call it inside {@link LockPatternActivity} .</li> * </ul> */ public static final String EXTRA_PENDING_INTENT_CANCELLED = CLASSNAME + ".pending_intent_cancelled"; /** * You put a {@link PendingIntent} into this extra. The library will show a * button <i>"Forgot pattern?"</i> and call your intent later when the user * taps it. * <p/> * <h1>Notes</h1> * <ul> * <li>If you use an activity, you don't need * {@link Intent#FLAG_ACTIVITY_NEW_TASK} for the intent, since the library * will call it inside {@link LockPatternActivity} .</li> * <li>{@link LockPatternActivity} will finish with * {@link #RESULT_FORGOT_PATTERN} <i><b>after</b> making a call</i> to start * your pending intent.</li> * <li>It is your responsibility to make sure the Intent is good. The * library doesn't cover any errors when calling your intent.</li> * </ul> * * @author Thanks to Yan Cheng Cheok for his idea. * @see #ACTION_COMPARE_PATTERN * @since v2.8 beta */ public static final String EXTRA_PENDING_INTENT_FORGOT_PATTERN = CLASSNAME + ".pending_intent_forgot_pattern"; /** * Delay time to reload the lock pattern view after a wrong pattern. */ private static final long DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW = SECOND_IN_MILLIS; /** * Click listener for view group progress bar. */ private final View.OnClickListener mViewGroupProgressBarOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { /* * Do nothing. We just don't want the user to interact with controls * behind this view. */ }// onClick() };// mViewGroupProgressBarOnClickListener /* * FIELDS */ private int mMaxRetries, mMinWiredDots, mRetryCount = 0, mCaptchaWiredDots; private boolean mAutoSave, mStealthMode; private IEncrypter mEncrypter; private ButtonOkCommand mBtnOkCmd; private Intent mIntentResult; /** * Click listener for button Cancel. */ private final View.OnClickListener mBtnCancelOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { finishWithNegativeResult(RESULT_CANCELED); }// onClick() };// mBtnCancelOnClickListener private LoadingView<Void, Void, Object> mLoadingView; /* * CONTROLS */ private TextView mTextInfo; private LockPatternView mLockPatternView; private View mFooter; private Button mBtnCancel; private Button mBtnConfirm; /** * Click listener for button Confirm. */ private final View.OnClickListener mBtnConfirmOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) { if (mBtnOkCmd == ButtonOkCommand.CONTINUE) { mBtnOkCmd = ButtonOkCommand.DONE; mLockPatternView.clearPattern(); mTextInfo .setText(R.string.msg_redraw_pattern_to_confirm); mBtnConfirm.setText(R.string.cmd_confirm); mBtnConfirm.setEnabled(false); } else { final char[] pattern = getIntent().getCharArrayExtra( EXTRA_PATTERN); if (mAutoSave) Settings.Security.setPattern(LockPatternActivity.this, pattern); finishWithResultOk(pattern); } }// ACTION_CREATE_PATTERN else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { /* * We don't need to verify the extra. First, this button is only * visible if there is this extra in the intent. Second, it is * the responsibility of the caller to make sure the extra is * good. */ PendingIntent pi = null; try { pi = getIntent().getParcelableExtra( EXTRA_PENDING_INTENT_FORGOT_PATTERN); pi.send(); } catch (Throwable t) { Log.e(CLASSNAME, "Error sending pending intent: " + pi, t); } finishWithNegativeResult(RESULT_FORGOT_PATTERN); }// ACTION_COMPARE_PATTERN }// onClick() };// mBtnConfirmOnClickListener private View mViewGroupProgressBar; /** * Pattern listener for LockPatternView. */ private final LockPatternView.OnPatternListener mLockPatternViewListener = new LockPatternView.OnPatternListener() { @Override public void onPatternStart() { mLockPatternView.removeCallbacks(mLockPatternViewReloader); mLockPatternView.setDisplayMode(DisplayMode.Correct); if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) { mTextInfo .setText(R.string.msg_release_finger_when_done); mBtnConfirm.setEnabled(false); if (mBtnOkCmd == ButtonOkCommand.CONTINUE) getIntent().removeExtra(EXTRA_PATTERN); }// ACTION_CREATE_PATTERN else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { mTextInfo .setText(R.string.msg_draw_pattern_to_unlock); }// ACTION_COMPARE_PATTERN else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) { mTextInfo .setText(R.string.msg_redraw_pattern_to_confirm); }// ACTION_VERIFY_CAPTCHA }// onPatternStart() @Override public void onPatternCleared() { mLockPatternView.removeCallbacks(mLockPatternViewReloader); if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) { mLockPatternView.setDisplayMode(DisplayMode.Correct); mBtnConfirm.setEnabled(false); if (mBtnOkCmd == ButtonOkCommand.CONTINUE) { getIntent().removeExtra(EXTRA_PATTERN); mTextInfo .setText(R.string.msg_draw_an_unlock_pattern); } else mTextInfo .setText(R.string.msg_redraw_pattern_to_confirm); }// ACTION_CREATE_PATTERN else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { mLockPatternView.setDisplayMode(DisplayMode.Correct); mTextInfo .setText(R.string.msg_draw_pattern_to_unlock); }// ACTION_COMPARE_PATTERN else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) { mTextInfo .setText(R.string.msg_redraw_pattern_to_confirm); List<Cell> pattern = getIntent().getParcelableArrayListExtra( EXTRA_PATTERN); mLockPatternView.setPattern(DisplayMode.Animate, pattern); }// ACTION_VERIFY_CAPTCHA }// onPatternCleared() @Override public void onPatternCellAdded(List<Cell> pattern) { // TODO Auto-generated method stub }// onPatternCellAdded() @Override public void onPatternDetected(List<Cell> pattern) { if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) { doCheckAndCreatePattern(pattern); }// ACTION_CREATE_PATTERN else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { doComparePattern(pattern); }// ACTION_COMPARE_PATTERN else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) { if (!DisplayMode.Animate.equals(mLockPatternView .getDisplayMode())) doComparePattern(pattern); }// ACTION_VERIFY_CAPTCHA }// onPatternDetected() };// mLockPatternViewListener /** * This reloads the {@link #mLockPatternView} after a wrong pattern. */ private final Runnable mLockPatternViewReloader = new Runnable() { @Override public void run() { mLockPatternView.clearPattern(); mLockPatternViewListener.onPatternCleared(); }// run() };// mLockPatternViewReloader /** * Creates new intent with {@link #ACTION_CREATE_PATTERN}. You must call * this intent from a UI thread. * * @param context the context. * @return new intent. */ public static Intent newIntentToCreatePattern(Context context) { Intent result = new Intent(ACTION_CREATE_PATTERN, null, context, LockPatternActivity.class); return result; }// newIntentToCreatePattern() /** * This method is a shortcut to call * {@link #newIntentToCreatePattern(Context)} from a UI thread. * * @param caller must be an instance of {@link Activity}, or {@link Fragment} * or support library's {@code Fragment}. Other values will be * ignored. * @param context the context. * @param requestCode request code for * {@link Activity#startActivityForResult(Intent, int)} or * counterpart methods of fragments. * @return {@code true} if the call has been made successfully, * {@code false} if any exception occurred. * @throws NullPointerException if caller or context is {@code null}. */ public static boolean startToCreatePattern(Object caller, Context context, int requestCode) { return callStartActivityForResult(caller, newIntentToCreatePattern(context), requestCode); }// startToCreatePattern() /** * Calls {@code startActivityForResult(Intent, int)} from given caller, * ignores any exception. * * @param caller the caller. * @param intent the intent. * @param requestCode request code. * @return {@code true} if the call has been made successfully, * {@code false} if any exception occurred. * @throws NullPointerException if caller or intent is {@code null}. */ public static boolean callStartActivityForResult(Object caller, Intent intent, int requestCode) { try { Method method = caller.getClass().getMethod( "startActivityForResult", Intent.class, int.class); method.setAccessible(true); method.invoke(caller, intent, requestCode); return true; } catch (Exception e) { /* * Just log it. We don't need to go to details here, as it's * responsibility of user to take care of caller. */ if (DEBUG) Log.d(CLASSNAME, e.getMessage(), e); } return false; }// callStartActivityForResult() /** * Creates new intent with {@link #ACTION_COMPARE_PATTERN}. You must call * this intent from a UI thread. * * @param context the context. * @param pattern optional, see {@link #EXTRA_PATTERN}. * @return new intent. */ public static Intent newIntentToComparePattern(Context context, char[] pattern) { Intent result = new Intent(ACTION_COMPARE_PATTERN, null, context, LockPatternActivity.class); if (pattern != null) result.putExtra(EXTRA_PATTERN, pattern); return result; }// newIntentToComparePattern() /** * This method is a shortcut to call * {@link #newIntentToComparePattern(Context, char[])} from a UI thread. * * @param caller must be an instance of {@link Activity}, or {@link Fragment} * or support library's {@code Fragment}. Other values will be * ignored. * @param context the context. * @param requestCode request code for * {@link Activity#startActivityForResult(Intent, int)} or * counterpart methods of fragments. * @param pattern optional, see {@link #EXTRA_PATTERN}. * @return {@code true} if the call has been made successfully, * {@code false} if any exception occurred. * @throws NullPointerException if caller or context is {@code null}. */ public static boolean startToComparePattern(Object caller, Context context, int requestCode, char[] pattern) { return callStartActivityForResult(caller, newIntentToComparePattern(context, pattern), requestCode); }// startToComparePattern() /** * Creates new intent with {@link #ACTION_VERIFY_CAPTCHA}. You must call * this intent from a UI thread. * * @param context the context. * @return new intent. */ public static Intent newIntentToVerifyCaptcha(Context context) { Intent result = new Intent(ACTION_VERIFY_CAPTCHA, null, context, LockPatternActivity.class); return result; }// newIntentToVerifyCaptcha() /** * This method is a shortcut to call * {@link #newIntentToVerifyCaptcha(Context)} from a UI thread. * * @param caller must be an instance of {@link Activity}, or {@link Fragment} * or support library's {@code Fragment}. Other values will be * ignored. * @param context the context. * @param requestCode request code for * {@link Activity#startActivityForResult(Intent, int)} or * counterpart methods of fragments. * @return {@code true} if the call has been made successfully, * {@code false} if any exception occurred. * @throws NullPointerException if caller or context is {@code null}. */ public static boolean startToVerifyCaptcha(Object caller, Context context, int requestCode) { return callStartActivityForResult(caller, newIntentToVerifyCaptcha(context), requestCode); }// startToVerifyCaptcha() /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { if (BuildConfig.DEBUG) Log.d(CLASSNAME, "ClassName = " + CLASSNAME); /* * EXTRA_THEME */ if (getIntent().hasExtra(EXTRA_THEME)) setTheme(getIntent().getIntExtra(EXTRA_THEME, R.style.Theme_Dark)); super.onCreate(savedInstanceState); loadSettings(); mIntentResult = new Intent(); setResult(RESULT_CANCELED, mIntentResult); initContentView(); }// onCreate() @Override protected void onDestroy() { if (mLoadingView != null) mLoadingView.cancel(true); super.onDestroy(); }// onDestroy() @Override public void onConfigurationChanged(Configuration newConfig) { if (BuildConfig.DEBUG) Log.d(CLASSNAME, "onConfigurationChanged()"); super.onConfigurationChanged(newConfig); initContentView(); }// onConfigurationChanged() @Override public boolean onKeyDown(int keyCode, KeyEvent event) { /* * Use this hook instead of onBackPressed(), because onBackPressed() is * not available in API 4. */ if (keyCode == KeyEvent.KEYCODE_BACK && ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { if (mLoadingView != null) mLoadingView.cancel(true); finishWithNegativeResult(RESULT_CANCELED); return true; }// if return super.onKeyDown(keyCode, event); }// onKeyDown() @Override public boolean onTouchEvent(MotionEvent event) { /* * Support canceling dialog on touching outside in APIs < 11. * * This piece of code is copied from android.view.Window. You can find * it by searching for methods shouldCloseOnTouch() and isOutOfBounds(). */ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB && event.getAction() == MotionEvent.ACTION_DOWN && getWindow().peekDecorView() != null) { final int x = (int) event.getX(); final int y = (int) event.getY(); final int slop = ViewConfiguration.get(this) .getScaledWindowTouchSlop(); final View decorView = getWindow().getDecorView(); boolean isOutOfBounds = (x < -slop) || (y < -slop) || (x > (decorView.getWidth() + slop)) || (y > (decorView.getHeight() + slop)); if (isOutOfBounds) { finishWithNegativeResult(RESULT_CANCELED); return true; } }// if return super.onTouchEvent(event); }// onTouchEvent() /** * Loads settings, either from manifest or {@link Settings}. */ private void loadSettings() { Bundle metaData = null; try { metaData = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA).metaData; } catch (NameNotFoundException e) { /* * Never catch this. */ e.printStackTrace(); } if (metaData != null && metaData.containsKey(METADATA_MIN_WIRED_DOTS)) mMinWiredDots = Settings.Display.validateMinWiredDots(this, metaData.getInt(METADATA_MIN_WIRED_DOTS)); else mMinWiredDots = Settings.Display.getMinWiredDots(this); if (metaData != null && metaData.containsKey(METADATA_MAX_RETRIES)) mMaxRetries = Settings.Display.validateMaxRetries(this, metaData.getInt(METADATA_MAX_RETRIES)); else mMaxRetries = Settings.Display.getMaxRetries(this); if (metaData != null && metaData.containsKey(METADATA_AUTO_SAVE_PATTERN)) mAutoSave = metaData.getBoolean(METADATA_AUTO_SAVE_PATTERN); else mAutoSave = Settings.Security.isAutoSavePattern(this); if (metaData != null && metaData.containsKey(METADATA_CAPTCHA_WIRED_DOTS)) mCaptchaWiredDots = Settings.Display.validateCaptchaWiredDots(this, metaData.getInt(METADATA_CAPTCHA_WIRED_DOTS)); else mCaptchaWiredDots = Settings.Display.getCaptchaWiredDots(this); if (metaData != null && metaData.containsKey(METADATA_STEALTH_MODE)) mStealthMode = metaData.getBoolean(METADATA_STEALTH_MODE); else mStealthMode = Settings.Display.isStealthMode(this); /* * Encrypter. */ char[] encrypterClass; if (metaData != null && metaData.containsKey(METADATA_ENCRYPTER_CLASS)) encrypterClass = metaData.getString(METADATA_ENCRYPTER_CLASS) .toCharArray(); else encrypterClass = Settings.Security.getEncrypterClass(this); if (encrypterClass != null) { try { mEncrypter = (IEncrypter) Class.forName( new String(encrypterClass), false, getClassLoader()) .newInstance(); } catch (Throwable t) { throw new InvalidEncrypterException(); } } }// loadSettings() /** * Initializes UI... */ private void initContentView() { /* * Save all controls' state to restore later. */ CharSequence infoText = mTextInfo != null ? mTextInfo.getText() : null; Boolean btnOkEnabled = mBtnConfirm != null ? mBtnConfirm.isEnabled() : null; LockPatternView.DisplayMode lastDisplayMode = mLockPatternView != null ? mLockPatternView .getDisplayMode() : null; List<Cell> lastPattern = mLockPatternView != null ? mLockPatternView .getPattern() : null; setContentView(R.layout.lock_pattern_activity); UI.adjustDialogSizeForLargeScreens(getWindow()); /* * MAP CONTROLS */ mTextInfo = (TextView) findViewById(R.id.textview_info); mLockPatternView = (LockPatternView) findViewById(R.id.view_lock_pattern); mFooter = findViewById(R.id.viewgroup_footer); mBtnCancel = (Button) findViewById(R.id.button_cancel); mBtnConfirm = (Button) findViewById(R.id.button_confirm); mViewGroupProgressBar = findViewById(R.id.view_group_progress_bar); /* * SETUP CONTROLS */ mViewGroupProgressBar .setOnClickListener(mViewGroupProgressBarOnClickListener); /* * LOCK PATTERN VIEW */ switch (getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) { case Configuration.SCREENLAYOUT_SIZE_LARGE: case Configuration.SCREENLAYOUT_SIZE_XLARGE: { final int size = getResources().getDimensionPixelSize( R.dimen.lockpatternview_size); LayoutParams lp = mLockPatternView.getLayoutParams(); lp.width = size; lp.height = size; mLockPatternView.setLayoutParams(lp); break; }// LARGE / XLARGE } /* * Haptic feedback. */ boolean hapticFeedbackEnabled = false; try { hapticFeedbackEnabled = android.provider.Settings.System .getInt(getContentResolver(), android.provider.Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) != 0; } catch (Throwable t) { /* * Ignore it. */ } mLockPatternView.setTactileFeedbackEnabled(hapticFeedbackEnabled); mLockPatternView.setInStealthMode(mStealthMode && !ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())); mLockPatternView.setOnPatternListener(mLockPatternViewListener); if (lastPattern != null && lastDisplayMode != null && !ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) mLockPatternView.setPattern(lastDisplayMode, lastPattern); /* * COMMAND BUTTONS */ if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) { mBtnCancel.setOnClickListener(mBtnCancelOnClickListener); mBtnConfirm.setOnClickListener(mBtnConfirmOnClickListener); mBtnCancel.setVisibility(View.VISIBLE); mFooter.setVisibility(View.VISIBLE); if (infoText != null) mTextInfo.setText(infoText); else mTextInfo .setText(R.string.msg_draw_an_unlock_pattern); /* * BUTTON OK */ if (mBtnOkCmd == null) mBtnOkCmd = ButtonOkCommand.CONTINUE; switch (mBtnOkCmd) { case CONTINUE: mBtnConfirm.setText(R.string.cmd_continue); break; case DONE: mBtnConfirm.setText(R.string.cmd_confirm); break; default: /* * Do nothing. */ break; } if (btnOkEnabled != null) mBtnConfirm.setEnabled(btnOkEnabled); }// ACTION_CREATE_PATTERN else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { if (TextUtils.isEmpty(infoText)) mTextInfo .setText(R.string.msg_draw_pattern_to_unlock); else mTextInfo.setText(infoText); if (getIntent().hasExtra(EXTRA_PENDING_INTENT_FORGOT_PATTERN)) { mBtnConfirm.setOnClickListener(mBtnConfirmOnClickListener); mBtnConfirm.setText(R.string.cmd_forgot_pattern); mBtnConfirm.setEnabled(true); mFooter.setVisibility(View.VISIBLE); } }// ACTION_COMPARE_PATTERN else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) { mTextInfo .setText(R.string.msg_redraw_pattern_to_confirm); /* * NOTE: EXTRA_PATTERN should hold a char[] array. In this case we * use it as a temporary variable to hold a list of Cell. */ final ArrayList<Cell> pattern; if (getIntent().hasExtra(EXTRA_PATTERN)) pattern = getIntent() .getParcelableArrayListExtra(EXTRA_PATTERN); else getIntent().putParcelableArrayListExtra( EXTRA_PATTERN, pattern = LockPatternUtils .genCaptchaPattern(mCaptchaWiredDots)); mLockPatternView.setPattern(DisplayMode.Animate, pattern); }// ACTION_VERIFY_CAPTCHA }// initContentView() /* * LISTENERS */ /** * Compares {@code pattern} to the given pattern ( * {@link #ACTION_COMPARE_PATTERN}) or to the generated "CAPTCHA" pattern ( * {@link #ACTION_VERIFY_CAPTCHA}). Then finishes the activity if they * match. * * @param pattern the pattern to be compared. */ private void doComparePattern(final List<Cell> pattern) { if (pattern == null) return; /* * Use a LoadingView because decrypting pattern might take time... */ mLoadingView = new LoadingView<Void, Void, Object>(this, mViewGroupProgressBar) { @Override protected Object doInBackground(Void... params) { if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { char[] currentPattern = getIntent().getCharArrayExtra( EXTRA_PATTERN); if (currentPattern == null) currentPattern = Settings.Security .getPattern(LockPatternActivity.this); if (currentPattern != null) { if (mEncrypter != null) return pattern.equals(mEncrypter.decrypt( LockPatternActivity.this, currentPattern)); else return Arrays.equals(currentPattern, LockPatternUtils.patternToSha1(pattern) .toCharArray()); } }// ACTION_COMPARE_PATTERN else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) { return pattern.equals(getIntent() .getParcelableArrayListExtra(EXTRA_PATTERN)); }// ACTION_VERIFY_CAPTCHA return false; }// doInBackground() @Override protected void onPostExecute(Object result) { super.onPostExecute(result); if ((Boolean) result) finishWithResultOk(null); else { mRetryCount++; mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount); if (mRetryCount >= mMaxRetries) finishWithNegativeResult(RESULT_FAILED); else { mLockPatternView.setDisplayMode(DisplayMode.Wrong); mTextInfo.setText(R.string.msg_try_again); mLockPatternView.postDelayed(mLockPatternViewReloader, DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW); } } }// onPostExecute() }; mLoadingView.execute(); }// doComparePattern() /** * Checks and creates the pattern. * * @param pattern the current pattern of lock pattern view. */ private void doCheckAndCreatePattern(final List<Cell> pattern) { if (pattern.size() < mMinWiredDots) { mLockPatternView.setDisplayMode(DisplayMode.Wrong); mTextInfo.setText(getResources().getQuantityString( R.plurals.pmsg_connect_x_dots, mMinWiredDots, mMinWiredDots)); mLockPatternView.postDelayed(mLockPatternViewReloader, DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW); return; }// if if (getIntent().hasExtra(EXTRA_PATTERN)) { /* * Use a LoadingView because decrypting pattern might take time... */ mLoadingView = new LoadingView<Void, Void, Object>(this, mViewGroupProgressBar) { @Override protected Object doInBackground(Void... params) { if (mEncrypter != null) return pattern.equals(mEncrypter.decrypt( LockPatternActivity.this, getIntent() .getCharArrayExtra(EXTRA_PATTERN))); else return Arrays.equals( getIntent().getCharArrayExtra(EXTRA_PATTERN), LockPatternUtils.patternToSha1(pattern) .toCharArray()); }// doInBackground() @Override protected void onPostExecute(Object result) { super.onPostExecute(result); if ((Boolean) result) { mTextInfo .setText(R.string.msg_your_new_unlock_pattern); mBtnConfirm.setEnabled(true); } else { mTextInfo .setText(R.string.msg_redraw_pattern_to_confirm); mBtnConfirm.setEnabled(false); mLockPatternView.setDisplayMode(DisplayMode.Wrong); mLockPatternView.postDelayed(mLockPatternViewReloader, DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW); } }// onPostExecute() }; mLoadingView.execute(); } else { /* * Use a LoadingView because encrypting pattern might take time... */ mLoadingView = new LoadingView<Void, Void, Object>(this, mViewGroupProgressBar) { @Override protected Object doInBackground(Void... params) { return mEncrypter != null ? mEncrypter.encrypt( LockPatternActivity.this, pattern) : LockPatternUtils.patternToSha1(pattern) .toCharArray(); }// onCancel() @Override protected void onPostExecute(Object result) { super.onPostExecute(result); getIntent().putExtra(EXTRA_PATTERN, (char[]) result); mTextInfo .setText(R.string.msg_pattern_recorded); mBtnConfirm.setEnabled(true); }// onPostExecute() }; mLoadingView.execute(); } }// doCheckAndCreatePattern() /** * Finishes activity with {@link Activity#RESULT_OK}. * * @param pattern the pattern, if this is in mode creating pattern. In any * cases, it can be set to {@code null}. */ private void finishWithResultOk(char[] pattern) { if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) mIntentResult.putExtra(EXTRA_PATTERN, pattern); else { /* * If the user was "logging in", minimum try count can not be zero. */ mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount + 1); } setResult(RESULT_OK, mIntentResult); /* * ResultReceiver */ ResultReceiver receiver = getIntent().getParcelableExtra( EXTRA_RESULT_RECEIVER); if (receiver != null) { Bundle bundle = new Bundle(); if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) bundle.putCharArray(EXTRA_PATTERN, pattern); else { /* * If the user was "logging in", minimum try count can not be * zero. */ bundle.putInt(EXTRA_RETRY_COUNT, mRetryCount + 1); } receiver.send(RESULT_OK, bundle); } /* * PendingIntent */ PendingIntent pi = getIntent().getParcelableExtra( EXTRA_PENDING_INTENT_OK); if (pi != null) { try { pi.send(this, RESULT_OK, mIntentResult); } catch (Throwable t) { Log.e(CLASSNAME, "Error sending PendingIntent: " + pi, t); } } finish(); }// finishWithResultOk() /** * Finishes the activity with negative result ( * {@link Activity#RESULT_CANCELED}, {@link #RESULT_FAILED} or * {@link #RESULT_FORGOT_PATTERN}). */ private void finishWithNegativeResult(int resultCode) { if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount); setResult(resultCode, mIntentResult); /* * ResultReceiver */ ResultReceiver receiver = getIntent().getParcelableExtra( EXTRA_RESULT_RECEIVER); if (receiver != null) { Bundle resultBundle = null; if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) { resultBundle = new Bundle(); resultBundle.putInt(EXTRA_RETRY_COUNT, mRetryCount); } receiver.send(resultCode, resultBundle); } /* * PendingIntent */ PendingIntent pi = getIntent().getParcelableExtra( EXTRA_PENDING_INTENT_CANCELLED); if (pi != null) { try { pi.send(this, resultCode, mIntentResult); } catch (Throwable t) { Log.e(CLASSNAME, "Error sending PendingIntent: " + pi, t); } } finish(); }// finishWithNegativeResult() /** * Helper enum for button OK commands. (Because we use only one "OK" button * for different commands). * * @author Hai Bison */ private static enum ButtonOkCommand { CONTINUE, FORGOT_PATTERN, DONE }// ButtonOkCommand }
/* * Copyright 2013-2014 Richard M. Hightower * 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. * * __________ _____ __ .__ * \______ \ ____ ____ ____ /\ / \ _____ | | _|__| ____ ____ * | | _// _ \ / _ \ / \ \/ / \ / \\__ \ | |/ / |/ \ / ___\ * | | ( <_> | <_> ) | \ /\ / Y \/ __ \| <| | | \/ /_/ > * |______ /\____/ \____/|___| / \/ \____|__ (____ /__|_ \__|___| /\___ / * \/ \/ \/ \/ \/ \//_____/ * ____. ___________ _____ ______________.___. * | |____ ___ _______ \_ _____/ / _ \ / _____/\__ | | * | \__ \\ \/ /\__ \ | __)_ / /_\ \ \_____ \ / | | * /\__| |/ __ \\ / / __ \_ | \/ | \/ \ \____ | * \________(____ /\_/ (____ / /_______ /\____|__ /_______ / / ______| * \/ \/ \/ \/ \/ \/ */ package org.boon.core; import org.boon.Lists; import org.boon.Maps; import org.junit.Test; import java.util.List; import java.util.Map; import static org.boon.Exceptions.die; /** * Created by Richard on 2/25/14. */ public class ConversionsTest { static class Age { int i; Age(int i) { this.i = i; } } @Test public void convertAgeFromInt() { Age age = Conversions.coerce(Age.class, 11); boolean ok = age.i == 11 || die(); } @Test public void convertAgeFromMap() { Map<String,Object> map = Maps.map("i", (Object)11); Age age = Conversions.coerce(Age.class, map); boolean ok = age.i == 11 || die(); } @Test public void convertAgeFromList() { List list = Lists.list( 11); Age age = Conversions.coerce(Age.class, list); boolean ok = age.i == 11 || die(); } static class Employee { String name; Age age; Employee(String name, Age age) { this.name = name; this.age = age; } Employee( Age age) { this.name = name; this.age = age; } } @Test public void convertEmployeeFromInt() { Employee e = Conversions.coerce(Employee.class, 11); boolean ok = e.age.i == 11 || die(); } @Test public void convertEmployeeFromList() { Employee e = Conversions.coerce(Employee.class, Lists.list("Rick", 11)); boolean ok = e.name.equals("Rick") || die(); ok &= e.age.i == 11 || die(); } @Test public void convertEmployeeFromListStringString() { Employee e = Conversions.coerce(Employee.class, Lists.list("Rick", "11")); boolean ok = e.name.equals("Rick") || die(); ok &= e.age.i == 11 || die(); } @Test public void convertEmployeeFromListList() { Employee e = Conversions.coerce(Employee.class, Lists.list("Rick", Lists.list(11))); boolean ok = e.name.equals("Rick") || die(); ok &= e.age.i == 11 || die(); } @Test public void convertEmployeeFromListStringNull() { Employee e = Conversions.coerce(Employee.class, Lists.list("Rick", null)); boolean ok = e.name.equals("Rick") || die(); ok &= e.age == null || die(); } @Test public void convertEmployeeFromListNullNull() { Employee e = Conversions.coerce(Employee.class, Lists.list(null, null)); boolean ok = e.name == null || die(); ok &= e.age == null || die(); } @Test public void convertEmployeeFromNull() { Employee e = Conversions.coerce(Employee.class, null); boolean ok = e == null || die(); } @Test public void coerceInt() { int i = Conversions.coerce(int.class, 1); boolean ok = i == 1 || die(); } @Test public void coerceNullToInt() { int i = Conversions.coerce(int.class, null); boolean ok = i == 0 || die(); } @Test public void coerceNullBoolean() { boolean i = Conversions.coerce(boolean.class, null); boolean ok = !i || die(); } }
/* * ============================================================================= * * Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org) * * 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 org.thymeleaf.engine; import java.io.IOException; import java.io.Writer; import org.thymeleaf.IEngineConfiguration; import org.thymeleaf.model.IXMLDeclaration; import org.thymeleaf.text.ITextRepository; import org.thymeleaf.util.TextUtils; import org.thymeleaf.util.Validate; /** * * @author Daniel Fern&aacute;ndez * @since 3.0.0 * */ final class XMLDeclaration implements IXMLDeclaration, IEngineTemplateHandlerEvent { // XML Declaration nodes do not exist in text parsing, so we are safe expliciting markup structures here public static final String DEFAULT_KEYWORD = "xml"; public static final String ATTRIBUTE_NAME_VERSION = "version"; public static final String ATTRIBUTE_NAME_ENCODING = "encoding"; public static final String ATTRIBUTE_NAME_STANDALONE = "standalone"; private final ITextRepository textRepository; private String xmlDeclaration; private String keyword; private String version; private String encoding; private String standalone; private String templateName; private int line; private int col; /* * Objects of this class are meant to both be reused by the engine and also created fresh by the processors. This * should allow reducing the number of instances of this class to the minimum. * * The 'xmlDeclaration' property, which is computed from the other properties, should be computed lazily in order to avoid * unnecessary creation of Strings which would use more memory than needed. */ // Meant to be called only from the template handler adapter XMLDeclaration(final ITextRepository textRepository) { super(); this.textRepository = textRepository; } // Meant to be called only from the model factory XMLDeclaration( final ITextRepository textRepository, final String version, final String encoding, final String standalone) { super(); this.textRepository = textRepository; initializeFromXmlDeclaration(DEFAULT_KEYWORD, version, encoding, standalone); } public String getKeyword() { return this.keyword; } public String getVersion() { return this.version; } public String getEncoding() { return this.encoding; } public String getStandalone() { return this.standalone; } public String getXmlDeclaration() { if (this.xmlDeclaration == null) { final StringBuilder strBuilder = new StringBuilder(); strBuilder.append("<?"); strBuilder.append(this.keyword); if (this.version != null) { strBuilder.append(' '); strBuilder.append(XMLDeclaration.ATTRIBUTE_NAME_VERSION); strBuilder.append("=\""); strBuilder.append(this.version); strBuilder.append('"'); } if (this.encoding != null) { strBuilder.append(' '); strBuilder.append(XMLDeclaration.ATTRIBUTE_NAME_ENCODING); strBuilder.append("=\""); strBuilder.append(this.encoding); strBuilder.append('"'); } if (this.standalone != null) { strBuilder.append(' '); strBuilder.append(XMLDeclaration.ATTRIBUTE_NAME_STANDALONE); strBuilder.append("=\""); strBuilder.append(this.standalone); strBuilder.append('"'); } strBuilder.append("?>"); this.xmlDeclaration = this.textRepository.getText(strBuilder); } return this.xmlDeclaration; } public void setVersion(final String version) { initializeFromXmlDeclaration(this.keyword, version, this.encoding, this.standalone); } public void setEncoding(final String encoding) { initializeFromXmlDeclaration(this.keyword, this.version, encoding, this.standalone); } public void setStandalone(final String standalone) { initializeFromXmlDeclaration(this.keyword, this.version, this.encoding, standalone); } // Meant to be called only from within the engine - removes the need to validate compute the 'xmlDeclaration' field void reset(final String xmlDeclaration, final String keyword, final String version, final String encoding, final String standalone, final String templateName, final int line, final int col) { this.keyword = keyword; this.version = version; this.encoding = encoding; this.standalone = standalone; this.xmlDeclaration = xmlDeclaration; this.templateName = templateName; this.line = line; this.col = col; } private void initializeFromXmlDeclaration( final String keyword, final String version, final String encoding, final String standalone) { if (keyword == null || !TextUtils.equals(true, DEFAULT_KEYWORD, keyword)) { throw new IllegalArgumentException("XML Declaration keyword must be non-null and equal to '" + DEFAULT_KEYWORD + "'"); } this.keyword = keyword; this.version = version; this.encoding = encoding; this.standalone = standalone; this.xmlDeclaration = null; this.templateName = null; this.line = -1; this.col = -1; } public boolean hasLocation() { return (this.templateName != null && this.line != -1 && this.col != -1); } public String getTemplateName() { return this.templateName; } public int getLine() { return this.line; } public int getCol() { return this.col; } public void write(final Writer writer) throws IOException { Validate.notNull(writer, "Writer cannot be null"); writer.write(getXmlDeclaration()); } public String toString() { return getXmlDeclaration(); } public XMLDeclaration cloneNode() { final XMLDeclaration clone = new XMLDeclaration(this.textRepository); clone.resetAsCloneOf(this); return clone; } // Meant to be called only from within the engine void resetAsCloneOf(final XMLDeclaration original) { this.xmlDeclaration = original.xmlDeclaration; this.keyword = original.keyword; this.version = original.version; this.encoding = original.encoding; this.standalone = original.standalone; this.templateName = original.templateName; this.line = original.line; this.col = original.col; } // Meant to be called only from within the engine static XMLDeclaration asEngineXMLDeclaration( final IEngineConfiguration configuration, final IXMLDeclaration xmlDeclaration, final boolean cloneAlways) { if (xmlDeclaration instanceof XMLDeclaration) { if (cloneAlways) { return ((XMLDeclaration) xmlDeclaration).cloneNode(); } return (XMLDeclaration) xmlDeclaration; } final XMLDeclaration newInstance = new XMLDeclaration(configuration.getTextRepository()); newInstance.xmlDeclaration = xmlDeclaration.getXmlDeclaration(); newInstance.keyword = xmlDeclaration.getKeyword(); newInstance.version = xmlDeclaration.getVersion(); newInstance.encoding = xmlDeclaration.getEncoding(); newInstance.standalone = xmlDeclaration.getStandalone(); newInstance.templateName = xmlDeclaration.getTemplateName(); newInstance.line = xmlDeclaration.getLine(); newInstance.col = xmlDeclaration.getCol(); return newInstance; } }
package org.apache.flex.forks.velocity.test; /* * Copyright 2001,2004 The Apache Software Foundation. * * 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. */ import java.lang.ClassLoader; import java.io.File; import java.io.FileInputStream; import java.io.StringWriter; import org.apache.flex.forks.velocity.app.VelocityEngine; import org.apache.flex.forks.velocity.runtime.RuntimeServices; import org.apache.flex.forks.velocity.VelocityContext; import org.apache.flex.forks.velocity.runtime.log.LogSystem; import org.apache.flex.forks.velocity.util.introspection.Introspector; import junit.framework.TestCase; /** * Tests if we can hand Velocity an arbitrary class for logging. * * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @version $Id: ClassloaderChangeTest.java,v 1.1.10.1 2004/03/03 23:23:04 geirm Exp $ */ public class ClassloaderChangeTest extends TestCase implements LogSystem { private VelocityEngine ve = null; private boolean sawCacheDump = false; private static String OUTPUT = "Hello From Foo"; /** * Default constructor. */ public ClassloaderChangeTest() { super("ClassloaderChangeTest"); try { /* * use an alternative logger. Set it up here and pass it in. */ ve = new VelocityEngine(); ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this ); ve.init(); } catch (Exception e) { System.err.println("Cannot setup ClassloaderChnageTest : " + e); System.exit(1); } } public void init( RuntimeServices rs ) { // do nothing with it } public static junit.framework.Test suite () { return new ClassloaderChangeTest(); } /** * Runs the test. */ public void runTest () { sawCacheDump = false; try { VelocityContext vc = new VelocityContext(); Object foo = null; /* * first, we need a classloader to make our foo object */ TestClassloader cl = new TestClassloader(); Class fooclass = cl.loadClass("Foo"); foo = fooclass.newInstance(); /* * put it into the context */ vc.put("foo", foo); /* * and render something that would use it * that will get it into the introspector cache */ StringWriter writer = new StringWriter(); ve.evaluate( vc, writer, "test", "$foo.doIt()"); /* * Check to make sure ok. note the obvious * dependency on the Foo class... */ if ( !writer.toString().equals( OUTPUT )) { fail("Output from doIt() incorrect"); } /* * and do it again :) */ cl = new TestClassloader(); fooclass = cl.loadClass("Foo"); foo = fooclass.newInstance(); vc.put("foo", foo); writer = new StringWriter(); ve.evaluate( vc, writer, "test", "$foo.doIt()"); if ( !writer.toString().equals( OUTPUT )) { fail("Output from doIt() incorrect"); } } catch( Exception ee ) { System.out.println("ClassloaderChangeTest : " + ee ); } if (!sawCacheDump) { fail("Didn't see introspector cache dump."); } } /** * method to catch Velocity log messages. When we * see the introspector dump message, then set the flag */ public void logVelocityMessage(int level, String message) { if (message.equals( Introspector.CACHEDUMP_MSG) ) { sawCacheDump = true; } } } /** * Simple (real simple...) classloader that depends * on a Foo.class being located in the classloader * directory under test */ class TestClassloader extends ClassLoader { private final static String testclass = "../test/classloader/Foo.class"; private Class fooClass = null; public TestClassloader() { try { File f = new File( testclass ); byte[] barr = new byte[ (int) f.length() ]; FileInputStream fis = new FileInputStream( f ); fis.read( barr ); fis.close(); fooClass = defineClass("Foo", barr, 0, barr.length); } catch( Exception e ) { System.out.println("TestClassloader : exception : " + e ); } } public Class findClass(String name) { return fooClass; } }
package com.codepath.apps.mysimpletweets.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.codepath.apps.mysimpletweets.R; import com.codepath.apps.mysimpletweets.Dialog.ReplyDialog; import com.codepath.apps.mysimpletweets.models.Tweet; import com.codepath.apps.mysimpletweets.models.TwitterApplication; import com.codepath.apps.mysimpletweets.models.TwitterClient; import com.codepath.apps.mysimpletweets.models.User; import com.google.gson.Gson; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; public class DetailTweetActivity extends AppCompatActivity { private ImageView ivProfileImage; private TextView tvUserName; private TextView tvTimeStamp; private TextView tvBody; private TextView tvRetweet; private TextView tvLike; private ImageButton btnReply; private ImageButton btnRetweet; private ImageButton btnLike; private TwitterClient mClient; private ImageView ivMedia; private long id; boolean isFavourited, isRetweeted; Tweet tweet; Gson mGson; boolean btnRetweetClicked = false; boolean btnLikeClicked = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_tweet2); setUp(); setData(); mGson = new Gson(); mClient = TwitterApplication.getRestClient(); btnReply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getBaseContext(),"ok",Toast.LENGTH_SHORT).show(); ReplyDialog replyDialog = new ReplyDialog(tweet); replyDialog.shoDialog(DetailTweetActivity.this); } }); btnRetweet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!isRetweeted) { mClient.retweetStatus(id,new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); Tweet tweet1 = mGson.fromJson(response.toString(),Tweet.class); tvRetweet.setText(String.valueOf(tweet1.getRetweetCount())); btnRetweet.setImageResource(R.drawable.ic_retweeted); isRetweeted = true; } }); } else { mClient.unRetweetStatus(id,new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); Tweet tweet1 = mGson.fromJson(response.toString(),Tweet.class); tvRetweet.setText(String.valueOf(tweet1.getRetweetCount())); btnRetweet.setImageResource(R.drawable.ic_retweet); isRetweeted = false; } }); } } }); btnLike.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!isFavourited){ mClient.favouriteStatus(id,new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); Tweet tweet1 = mGson.fromJson(response.toString(),Tweet.class); tvLike.setText(String.valueOf(tweet1.getFavouritesCount())); btnLike.setImageResource(R.drawable.ic_liked); isFavourited=true; } }); } else { mClient.unFavouriteStatus(id,new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); Tweet tweet1 = mGson.fromJson(response.toString(),Tweet.class); tvLike.setText(String.valueOf(tweet1.getFavouritesCount())); btnLike.setImageResource(R.drawable.ic_like); isFavourited= false; } }); } } }); } public void setUp(){ ivProfileImage = (ImageView) findViewById(R.id.ivProfileImage); tvUserName = (TextView) findViewById(R.id.tvUserName); tvTimeStamp = (TextView) findViewById(R.id.tvRelativeTimestamp); tvBody = (TextView) findViewById(R.id.tvBody); tvRetweet = (TextView) findViewById(R.id.tvDetailReTweet); tvLike = (TextView) findViewById(R.id.tvDetailNumberOfLike); btnRetweet = (ImageButton) findViewById(R.id.btnDetailRetweet); btnLike = (ImageButton) findViewById(R.id.btnDetailLike); btnReply = (ImageButton) findViewById(R.id.btnDetailLike); ivMedia = (ImageView) findViewById(R.id.ivMedi); } public void setData() { Intent intent = getIntent(); final String imageUrl, username, timeStamp, body, media; int like, retweet; id = intent.getLongExtra("id",0); imageUrl = intent.getStringExtra("profileImage"); username = intent.getStringExtra("userName"); timeStamp = intent.getStringExtra("timeStamp"); body = intent.getStringExtra("body"); like = intent.getIntExtra("like",0); retweet = intent.getIntExtra("retweet",0); isFavourited = intent.getBooleanExtra("liked",false); isRetweeted = intent.getBooleanExtra("retweeted",false); media = intent.getStringExtra("media"); if (media != ""){ Glide.with(ivMedia.getContext()) .load(media) .into(ivMedia); } else ivMedia.setVisibility(View.GONE); Glide.with(getApplicationContext()) .load(imageUrl) .into(ivProfileImage); tvUserName.setText(username); tvTimeStamp.setText(timeStamp); tvBody.setText(body); tvRetweet.setText(String.valueOf(retweet)); tvLike.setText(String.valueOf(like)); if (isFavourited){ btnLike.setImageResource(R.drawable.ic_liked); } else { btnLike.setImageResource(R.drawable.ic_like); } if (isRetweeted){ btnRetweet.setImageResource(R.drawable.ic_retweeted); } else { btnRetweet.setImageResource(R.drawable.ic_retweet); } ivProfileImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mClient.getAccount(id,username,new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { super.onSuccess(statusCode, headers, response); Gson gson = new Gson(); User user = gson.fromJson(response.toString(), User.class); Intent intent = new Intent(getApplicationContext(), ProfileActivity.class); intent.putExtra("id",user.getUid()); intent.putExtra("name",user.getScreenName()); startActivity(intent); } }); } }); } }
package org.apache.maven.artifact.ant; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.manager.WagonManager; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.DefaultArtifactRepository; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.profiles.DefaultProfileManager; import org.apache.maven.profiles.ProfileManager; import org.apache.maven.project.DefaultProjectBuilderConfiguration; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.settings.Mirror; import org.apache.maven.settings.RuntimeInfo; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.settings.SettingsUtils; import org.apache.maven.settings.TrackableBase; import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader; import org.apache.maven.usability.diagnostics.ErrorDiagnostics; import org.apache.maven.wagon.Wagon; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.Execute; import org.codehaus.classworlds.ClassWorld; import org.codehaus.classworlds.DuplicateRealmException; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.embed.Embedder; import org.codehaus.plexus.interpolation.EnvarBasedValueSource; import org.codehaus.plexus.interpolation.RegexBasedInterpolator; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; /** * Base class for artifact tasks. * * @author <a href="mailto:brett@apache.org">Brett Porter</a> * @version $Id: AbstractArtifactTask.java 1085345 2011-03-25 12:13:31Z stephenc $ */ public abstract class AbstractArtifactTask extends Task { private static final String WILDCARD = "*"; private static final String EXTERNAL_WILDCARD = "external:*"; private static ClassLoader plexusClassLoader; private File userSettingsFile; private File globalSettingsFile; private Settings settings; private ProfileManager profileManager; private PlexusContainer container; private Pom pom; private String pomRefId; private LocalRepository localRepository; protected ArtifactRepository createLocalArtifactRepository() { ArtifactRepositoryLayout repositoryLayout = (ArtifactRepositoryLayout) lookup( ArtifactRepositoryLayout.ROLE, getLocalRepository().getLayout() ); return new DefaultArtifactRepository( "local", "file://" + getLocalRepository().getPath(), repositoryLayout ); } /** * Create a core-Maven ArtifactRepositoryFactory from a Maven Ant Tasks's RemoteRepository definition, * eventually configured with authentication and proxy information. * @param repository the remote repository as defined in Ant * @return the corresponding ArtifactRepositoryFactory */ protected ArtifactRepositoryFactory getArtifactRepositoryFactory( RemoteRepository repository ) { WagonManager manager = (WagonManager) lookup( WagonManager.ROLE ); Authentication authentication = repository.getAuthentication(); if ( authentication != null ) { manager.addAuthenticationInfo( repository.getId(), authentication.getUserName(), authentication.getPassword(), authentication.getPrivateKey(), authentication.getPassphrase() ); } Proxy proxy = repository.getProxy(); if ( proxy != null ) { manager.addProxy( proxy.getType(), proxy.getHost(), proxy.getPort(), proxy.getUserName(), proxy.getPassword(), proxy.getNonProxyHosts() ); } return (ArtifactRepositoryFactory) lookup( ArtifactRepositoryFactory.ROLE ); } protected void releaseArtifactRepositoryFactory( ArtifactRepositoryFactory repositoryFactory ) { try { getContainer().release( repositoryFactory ); } catch ( ComponentLifecycleException e ) { // TODO: Warn the user, or not? } } /** * Create a core-Maven ArtifactRepository from a Maven Ant Tasks's RemoteRepository definition. * @param repository the remote repository as defined in Ant * @return the corresponding ArtifactRepository */ protected ArtifactRepository createRemoteArtifactRepository( RemoteRepository repository ) { ArtifactRepositoryLayout repositoryLayout = (ArtifactRepositoryLayout) lookup( ArtifactRepositoryLayout.ROLE, repository.getLayout() ); ArtifactRepositoryFactory repositoryFactory = null; ArtifactRepository artifactRepository; try { repositoryFactory = getArtifactRepositoryFactory( repository ); ArtifactRepositoryPolicy snapshots = buildArtifactRepositoryPolicy( repository.getSnapshots() ); ArtifactRepositoryPolicy releases = buildArtifactRepositoryPolicy( repository.getReleases() ); artifactRepository = repositoryFactory.createArtifactRepository( repository.getId(), repository.getUrl(), repositoryLayout, snapshots, releases ); } finally { releaseArtifactRepositoryFactory( repositoryFactory ); } return artifactRepository; } private static ArtifactRepositoryPolicy buildArtifactRepositoryPolicy( RepositoryPolicy policy ) { boolean enabled = true; String updatePolicy = null; String checksumPolicy = null; if ( policy != null ) { enabled = policy.isEnabled(); if ( policy.getUpdatePolicy() != null ) { updatePolicy = policy.getUpdatePolicy(); } if ( policy.getChecksumPolicy() != null ) { checksumPolicy = policy.getChecksumPolicy(); } } return new ArtifactRepositoryPolicy( enabled, updatePolicy, checksumPolicy ); } protected LocalRepository getDefaultLocalRepository() { Settings settings = getSettings(); LocalRepository localRepository = new LocalRepository(); localRepository.setId( "local" ); localRepository.setPath( new File( settings.getLocalRepository() ) ); return localRepository; } protected synchronized Settings getSettings() { if ( settings == null ) { initSettings(); } return settings; } private File newFile( String parent, String subdir, String filename ) { return new File( new File( parent, subdir ), filename ); } private void initSettings() { if ( userSettingsFile == null ) { File tempSettingsFile = newFile( System.getProperty( "user.home" ), ".ant", "settings.xml" ); if ( tempSettingsFile.exists() ) { userSettingsFile = tempSettingsFile; } else { tempSettingsFile = newFile( System.getProperty( "user.home" ), ".m2", "settings.xml" ); if ( tempSettingsFile.exists() ) { userSettingsFile = tempSettingsFile; } } } if ( globalSettingsFile == null ) { File tempSettingsFile = newFile( System.getProperty( "ant.home" ), "etc", "settings.xml" ); if ( tempSettingsFile.exists() ) { globalSettingsFile = tempSettingsFile; } else { // look in ${M2_HOME}/conf List<String> env = Execute.getProcEnvironment(); for ( String var: env ) { if ( var.startsWith( "M2_HOME=" ) ) { String m2Home = var.substring( "M2_HOME=".length() ); tempSettingsFile = newFile( m2Home, "conf", "settings.xml" ); if ( tempSettingsFile.exists() ) { globalSettingsFile = tempSettingsFile; } break; } } } } Settings userSettings = loadSettings( userSettingsFile ); Settings globalSettings = loadSettings( globalSettingsFile ); SettingsUtils.merge( userSettings, globalSettings, TrackableBase.GLOBAL_LEVEL ); settings = userSettings; if ( StringUtils.isEmpty( settings.getLocalRepository() ) ) { String location = newFile( System.getProperty( "user.home" ), ".m2", "repository" ).getAbsolutePath(); settings.setLocalRepository( location ); } WagonManager wagonManager = (WagonManager) lookup( WagonManager.ROLE ); wagonManager.setDownloadMonitor( new AntDownloadMonitor() ); if ( settings.isOffline() ) { log( "You are working in offline mode.", Project.MSG_INFO ); wagonManager.setOnline( false ); } else { wagonManager.setOnline( true ); } for(Mirror mirror: settings.getMirrors()) { wagonManager.addMirror(mirror.getId(), mirror.getMirrorOf(), mirror.getUrl()); } } private Settings loadSettings( File settingsFile ) { Settings settings = null; try { if ( settingsFile != null ) { log( "Loading Maven settings file: " + settingsFile.getPath(), Project.MSG_VERBOSE ); settings = readSettings( settingsFile ); } } catch ( IOException e ) { log( "Error reading settings file '" + settingsFile + "' - ignoring. Error was: " + e.getMessage(), Project.MSG_WARN ); } catch ( XmlPullParserException e ) { log( "Error parsing settings file '" + settingsFile + "' - ignoring. Error was: " + e.getMessage(), Project.MSG_WARN ); } if ( settings == null ) { settings = new Settings(); RuntimeInfo rtInfo = new RuntimeInfo( settings ); settings.setRuntimeInfo( rtInfo ); } return settings; } public void setSettingsFile( File settingsFile ) { if ( !settingsFile.exists() ) { throw new BuildException( "settingsFile does not exist: " + settingsFile.getAbsolutePath() ); } userSettingsFile = settingsFile; settings = null; } /** * @see org.apache.maven.settings.DefaultMavenSettingsBuilder#readSettings */ private Settings readSettings( File settingsFile ) throws IOException, XmlPullParserException { Settings settings = null; Reader reader = null; try { reader = ReaderFactory.newXmlReader( settingsFile ); StringWriter sWriter = new StringWriter(); IOUtil.copy( reader, sWriter ); String rawInput = sWriter.toString(); try { RegexBasedInterpolator interpolator = new RegexBasedInterpolator(); interpolator.addValueSource( new EnvarBasedValueSource() ); rawInput = interpolator.interpolate( rawInput, "settings" ); } catch ( Exception e ) { log( "Failed to initialize environment variable resolver. Skipping environment substitution in " + "settings." ); } StringReader sReader = new StringReader( rawInput ); SettingsXpp3Reader modelReader = new SettingsXpp3Reader(); settings = modelReader.read( sReader ); RuntimeInfo rtInfo = new RuntimeInfo( settings ); rtInfo.setFile( settingsFile ); settings.setRuntimeInfo( rtInfo ); } finally { IOUtil.close( reader ); } return settings; } protected RemoteRepository createAntRemoteRepository( org.apache.maven.model.Repository pomRepository ) { RemoteRepository r = createAntRemoteRepositoryBase( pomRepository ); if ( pomRepository.getSnapshots() != null ) { r.addSnapshots( convertRepositoryPolicy( pomRepository.getSnapshots() ) ); } if ( pomRepository.getReleases() != null ) { r.addReleases( convertRepositoryPolicy( pomRepository.getReleases() ) ); } return r; } protected RemoteRepository createAntRemoteRepositoryBase( org.apache.maven.model.RepositoryBase pomRepository ) { RemoteRepository r = new RemoteRepository(); r.setId( pomRepository.getId() ); r.setUrl( pomRepository.getUrl() ); r.setLayout( pomRepository.getLayout() ); return r; } protected void updateRepositoryWithSettings( RemoteRepository repository ) { // TODO: actually, we need to not funnel this through the ant repository - we should pump settings into wagon // manager at the start like m2 does, and then match up by repository id // As is, this could potentially cause a problem with 2 remote repositories with different authentication info Mirror mirror = getMirror( getSettings().getMirrors(), repository ); if ( mirror != null ) { repository.setUrl( mirror.getUrl() ); repository.setId( mirror.getId() ); } if ( repository.getAuthentication() == null ) { Server server = getSettings().getServer( repository.getId() ); if ( server != null ) { repository.addAuthentication( new Authentication( server ) ); WagonManager wagonManager = (WagonManager) lookup(WagonManager.ROLE ); wagonManager.addAuthenticationInfo(repository.getId(), server.getUsername(), server.getPassword(), server.getPrivateKey(), server.getPassphrase()); } } if ( repository.getProxy() == null ) { org.apache.maven.settings.Proxy proxy = getSettings().getActiveProxy(); if ( proxy != null ) { repository.addProxy( new Proxy( proxy ) ); } } } protected Object lookup( String role ) { try { return getContainer().lookup( role ); } catch ( ComponentLookupException e ) { throw new BuildException( "Unable to find component: " + role, e ); } } protected Object lookup( String role, String roleHint ) { try { return getContainer().lookup( role, roleHint ); } catch ( ComponentLookupException e ) { throw new BuildException( "Unable to find component: " + role + "[" + roleHint + "]", e ); } } protected synchronized PlexusContainer getContainer() { if ( container == null ) { container = (PlexusContainer) getProject().getReference( PlexusContainer.class.getName() ); if ( container == null ) { try { ClassWorld classWorld = new ClassWorld(); classWorld.newRealm( "plexus.core", getClass().getClassLoader() ); Embedder embedder = new Embedder(); embedder.start( classWorld ); container = embedder.getContainer(); } catch ( PlexusContainerException e ) { throw new BuildException( "Unable to start embedder", e ); } catch ( DuplicateRealmException e ) { throw new BuildException( "Unable to create embedder ClassRealm", e ); } getProject().addReference( PlexusContainer.class.getName(), container ); } } return container; } /** * Tries to initialize the pom. If no pom has been configured, returns null. * * @param localArtifactRepository * @return An initialized pom or null. */ public Pom initializePom( ArtifactRepository localArtifactRepository ) { Pom pom = getPom(); if ( pom != null ) { MavenProjectBuilder projectBuilder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE ); pom.initialiseMavenProject( projectBuilder, localArtifactRepository ); } return pom; } protected Pom createDummyPom( ArtifactRepository localRepository ) { Pom pom = new Pom(); MavenProject minimalProject = createMinimalProject( localRepository ); // we nulled out these fields to allow inheritance when creating poms, but the dummy // needs to be a valid pom, so set them back to something that's OK to resolve minimalProject.setGroupId( "org.apache.maven" ); minimalProject.setArtifactId( "super-pom" ); minimalProject.setVersion( "2.0" ); minimalProject.setPackaging( "pom" ); pom.setMavenProject( minimalProject ); return pom; } /** * Create a minimal project when no POM is available. * * @param localRepository * @return */ protected MavenProject createMinimalProject( ArtifactRepository localRepository ) { MavenProjectBuilder projectBuilder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE ); DefaultProjectBuilderConfiguration builderConfig = new DefaultProjectBuilderConfiguration( ); builderConfig.setLocalRepository( localRepository ); builderConfig.setGlobalProfileManager( getProfileManager() ); try { MavenProject mavenProject = projectBuilder.buildStandaloneSuperProject(builderConfig); // if we don't null out these fields then the pom that will be created is at the super-pom's // GAV coordinates and we will not be able to inherit partial GAV coordinates from a parent GAV. mavenProject.setGroupId(null); mavenProject.setArtifactId(null); mavenProject.setVersion(null); return mavenProject; } catch ( ProjectBuildingException e ) { throw new BuildException( "Unable to create dummy Pom", e ); } } protected Artifact createDummyArtifact() { ArtifactFactory factory = (ArtifactFactory) lookup( ArtifactFactory.ROLE ); // TODO: maybe not strictly correct, while we should enforce that packaging has a type handler of the same id, we don't return factory.createBuildArtifact( "unspecified", "unspecified", "0.0", "jar" ); } public String[] getSupportedProtocols() { try { Map<String,Wagon> wagonMap = getContainer().lookupMap( Wagon.ROLE ); List<String> protocols = new ArrayList<String>(); for ( Map.Entry<String,Wagon> entry : wagonMap.entrySet() ) { protocols.add( entry.getKey() ); } return (String[]) protocols.toArray( new String[protocols.size()] ); } catch ( ComponentLookupException e ) { throw new BuildException( "Unable to lookup Wagon providers", e ); } } public String getSupportedProtocolsAsString() { return StringUtils.join( getSupportedProtocols(), ", " ); } public void diagnoseError( Throwable error ) { try { ErrorDiagnostics diagnostics = (ErrorDiagnostics) container.lookup( ErrorDiagnostics.ROLE ); StringBuffer message = new StringBuffer(); message.append( "An error has occurred while processing the Maven artifact tasks.\n" ); message.append( " Diagnosis:\n\n" ); message.append( diagnostics.diagnose( error ) ); message.append( "\n\n" ); log( message.toString(), Project.MSG_INFO ); } catch ( ComponentLookupException e ) { log( "Failed to retrieve error diagnoser.", Project.MSG_DEBUG ); } } public void addPom( Pom pom ) { this.pom = pom; } /** * Try to get the POM from the nested pom element or a pomRefId * * @return The pom object */ public Pom getPom() { Pom thePom = this.pom; if ( thePom != null && getPomRefId() != null ) { throw new BuildException( "You cannot specify both a nested \"pom\" element and a \"pomrefid\" attribute" ); } if ( getPomRefId() != null ) { Object pomRefObj = getProject().getReference( getPomRefId() ); if ( pomRefObj instanceof Pom ) { thePom = (Pom) pomRefObj; } else { throw new BuildException( "Reference '" + pomRefId + "' was not found." ); } } return thePom; } public String getPomRefId() { return pomRefId; } /** * Try to get all the poms with id's which have been added to the ANT project * @return */ public List/*<Pom>*/ getAntReactorPoms() { List result = new ArrayList(); Iterator i = getProject().getReferences().values().iterator(); while ( i.hasNext() ) { Object ref = i.next(); if ( ref instanceof Pom ) { result.add( (Pom)ref ); } } return result; } public void setPomRefId( String pomRefId ) { this.pomRefId = pomRefId; } public LocalRepository getLocalRepository() { if ( localRepository == null ) { localRepository = getDefaultLocalRepository(); } return localRepository; } protected ProfileManager getProfileManager() { if ( profileManager == null ) { profileManager = new DefaultProfileManager( getContainer(), getSettings(), System.getProperties() ); } return profileManager; } public void addLocalRepository( LocalRepository localRepository ) { this.localRepository = localRepository; } public void setProfiles( String profiles ) { if ( profiles != null ) { // TODO: not sure this is the best way to do this... log( "Profiles not yet supported, ignoring profiles '" + profiles + "'", Project.MSG_WARN ); // System.setProperty( ProfileActivationUtils.ACTIVE_PROFILE_IDS, profiles ); } } private static RepositoryPolicy convertRepositoryPolicy( org.apache.maven.model.RepositoryPolicy pomRepoPolicy ) { RepositoryPolicy policy = new RepositoryPolicy(); policy.setEnabled( pomRepoPolicy.isEnabled() ); policy.setUpdatePolicy( pomRepoPolicy.getUpdatePolicy() ); return policy; } /** @noinspection RefusedBequest */ public void execute() { // Display the version if the log level is verbose showVersion(); ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); try { if ( plexusClassLoader != null ) { Thread.currentThread().setContextClassLoader( plexusClassLoader ); } initSettings(); doExecute(); } catch ( BuildException e ) { diagnoseError( e ); throw e; } finally { plexusClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( originalClassLoader ); } } /** * The main entry point for the task. */ protected abstract void doExecute(); /** * This method finds a matching mirror for the selected repository. If there is an exact match, * this will be used. If there is no exact match, then the list of mirrors is examined to see if * a pattern applies. * * @param mirrors The available mirrors. * @param repository See if there is a mirror for this repository. * @return the selected mirror or null if none is found. */ private Mirror getMirror( List<Mirror> mirrors, RemoteRepository repository ) { String repositoryId = repository.getId(); if ( repositoryId != null ) { for ( Mirror mirror : mirrors ) { if ( repositoryId.equals( mirror.getMirrorOf() ) ) { return mirror; } } for ( Mirror mirror : mirrors ) { if ( matchPattern( repository, mirror.getMirrorOf() ) ) { return mirror; } } } return null; } /** * This method checks if the pattern matches the originalRepository. Valid patterns: * = * everything external:* = everything not on the localhost and not file based. repo,repo1 = repo * or repo1 *,!repo1 = everything except repo1 * * @param originalRepository to compare for a match. * @param pattern used for match. Currently only '*' is supported. * @return true if the repository is a match to this pattern. */ boolean matchPattern( RemoteRepository originalRepository, String pattern ) { boolean result = false; String originalId = originalRepository.getId(); // simple checks first to short circuit processing below. if ( WILDCARD.equals( pattern ) || pattern.equals( originalId ) ) { result = true; } else { // process the list String[] repos = pattern.split( "," ); for ( int i = 0; i < repos.length; i++ ) { String repo = repos[i]; // see if this is a negative match if ( repo.length() > 1 && repo.startsWith( "!" ) ) { if ( originalId.equals( repo.substring( 1 ) ) ) { // explicitly exclude. Set result and stop processing. result = false; break; } } // check for exact match else if ( originalId.equals( repo ) ) { result = true; break; } // check for external:* else if ( EXTERNAL_WILDCARD.equals( repo ) && isExternalRepo( originalRepository ) ) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } else if ( WILDCARD.equals( repo ) ) { result = true; // don't stop processing in case a future segment explicitly excludes this repo } } } return result; } /** * Checks the URL to see if this repository refers to an external repository * * @param originalRepository * @return true if external. */ boolean isExternalRepo( RemoteRepository originalRepository ) { try { URL url = new URL( originalRepository.getUrl() ); return !( url.getHost().equals( "localhost" ) || url.getHost().equals( "127.0.0.1" ) || url.getProtocol().equals( "file" ) ); } catch ( MalformedURLException e ) { // bad url just skip it here. It should have been validated already, but the wagon lookup will deal with it return false; } } /** * Log the current version of the ant-tasks to the verbose output. */ protected void showVersion() { Properties properties = new Properties(); final String antTasksPropertiesPath = "META-INF/maven/org.apache.maven/maven-ant-tasks/pom.properties"; InputStream resourceAsStream = AbstractArtifactTask.class.getClassLoader().getResourceAsStream( antTasksPropertiesPath ); try { if ( resourceAsStream != null ) { properties.load( resourceAsStream ); } String version = properties.getProperty( "version", "unknown" ); String builtOn = properties.getProperty( "builtOn" ); if ( builtOn != null ) { log( "Maven Ant Tasks version: " + version + " built on " + builtOn, Project.MSG_VERBOSE ); } else { log( "Maven Ant Tasks version: " + version, Project.MSG_VERBOSE ); } } catch ( IOException e ) { log( "Unable to determine version from Maven Ant Tasks JAR file: " + e.getMessage(), Project.MSG_WARN ); } } }
package com.intellij.jps.cache.loader; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import com.intellij.jps.cache.JpsCacheBundle; import com.intellij.jps.cache.client.JpsServerClient; import com.intellij.jps.cache.model.AffectedModule; import com.intellij.jps.cache.model.BuildTargetState; import com.intellij.jps.cache.model.JpsLoaderContext; import com.intellij.jps.cache.model.OutputLoadResult; import com.intellij.jps.cache.ui.SegmentedProgressIndicatorManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.ZipUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.stream.Collectors; import static com.intellij.jps.cache.JpsCachesPluginUtil.EXECUTOR_SERVICE; class JpsCompilationOutputLoader implements JpsOutputLoader<List<OutputLoadResult>> { private static final Logger LOG = Logger.getInstance(JpsCompilationOutputLoader.class); private static final String RESOURCES_PRODUCTION = "resources-production"; private static final String JAVA_PRODUCTION = "java-production"; private static final String RESOURCES_TEST = "resources-test"; private static final String JAVA_TEST = "java-test"; private static final String PRODUCTION = "production"; private static final String TEST = "test"; private final JpsServerClient myClient; private final String myBuildDirPath; private List<File> myOldModulesPaths; private Map<File, String> myTmpFolderToModuleName; JpsCompilationOutputLoader(@NotNull JpsServerClient client, @NotNull String buildDirPath) { myClient = client; myBuildDirPath = buildDirPath; } @Override public int calculateDownloads(@NotNull Map<String, Map<String, BuildTargetState>> commitSourcesState, @Nullable Map<String, Map<String, BuildTargetState>> currentSourcesState) { return calculateAffectedModules(currentSourcesState, commitSourcesState, true).size(); } @Override public List<OutputLoadResult> load(@NotNull JpsLoaderContext context) { myOldModulesPaths = null; myTmpFolderToModuleName = null; SegmentedProgressIndicatorManager downloadProgressManager = context.getDownloadIndicatorManager(); downloadProgressManager.setText(this, JpsCacheBundle.message("progress.text.calculating.affected.modules")); List<AffectedModule> affectedModules = calculateAffectedModules(context.getCurrentSourcesState(), context.getCommitSourcesState(), true); downloadProgressManager.finished(this); downloadProgressManager.getProgressIndicator().checkCanceled(); if (affectedModules.size() > 0) { long start = System.currentTimeMillis(); List<OutputLoadResult> loadResults = myClient.downloadCompiledModules(downloadProgressManager, affectedModules); LOG.info("Download of compilation outputs took: " + (System.currentTimeMillis() - start)); return loadResults; } return Collections.emptyList(); } @Override public LoaderStatus extract(@Nullable Object loadResults, @NotNull SegmentedProgressIndicatorManager extractIndicatorManager) { if (!(loadResults instanceof List)) return LoaderStatus.FAILED; //noinspection unchecked List<OutputLoadResult> outputLoadResults = (List<OutputLoadResult>)loadResults; Map<File, String> result = new ConcurrentHashMap<>(); try { // Extracting results long start = System.currentTimeMillis(); extractIndicatorManager.setText(this, JpsCacheBundle.message("progress.text.extracting.downloaded.results")); List<Future<?>> futureList = ContainerUtil.map(outputLoadResults, loadResult -> EXECUTOR_SERVICE.submit(new UnzipOutputTask(result, loadResult, extractIndicatorManager))); for (Future<?> future : futureList) { future.get(); } extractIndicatorManager.finished(this); myTmpFolderToModuleName = result; LOG.info("Unzip compilation output took: " + (System.currentTimeMillis() - start)); return LoaderStatus.COMPLETE; } catch (ProcessCanceledException | InterruptedException | ExecutionException e) { if (!(e.getCause() instanceof ProcessCanceledException)) LOG.warn("Failed unzip downloaded compilation outputs", e); outputLoadResults.forEach(loadResult -> FileUtil.delete(loadResult.getZipFile())); result.forEach((key, value) -> FileUtil.delete(key)); } return LoaderStatus.FAILED; } @Override public void rollback() { if (myTmpFolderToModuleName == null) return; myTmpFolderToModuleName.forEach((tmpFolder, __) -> { if (tmpFolder.isDirectory() && tmpFolder.exists()) FileUtil.delete(tmpFolder); }); LOG.info("JPS cache loader rolled back"); } @Override public void apply(@NotNull SegmentedProgressIndicatorManager indicatorManager) { long start = System.currentTimeMillis(); if (myOldModulesPaths != null) { LOG.info("Removing old compilation outputs " + myOldModulesPaths.size() + " counts"); myOldModulesPaths.forEach(file -> { if (file.exists()) FileUtil.delete(file); }); } if (myTmpFolderToModuleName == null) { LOG.debug("Nothing to apply, download results are empty"); return; } indicatorManager.setText(this, JpsCacheBundle.message("progress.text.applying.jps.caches")); ContainerUtil.map(myTmpFolderToModuleName.entrySet(), entry -> EXECUTOR_SERVICE.submit(() -> { String moduleName = entry.getValue(); File tmpModuleFolder = entry.getKey(); SegmentedProgressIndicatorManager.SubTaskProgressIndicator subTaskIndicator = indicatorManager.createSubTaskIndicator(); subTaskIndicator.setText2(JpsCacheBundle.message("progress.details.applying.changes.for.module", moduleName)); File currentModuleBuildDir = new File(tmpModuleFolder.getParentFile(), moduleName); FileUtil.delete(currentModuleBuildDir); try { FileUtil.rename(tmpModuleFolder, currentModuleBuildDir); LOG.debug("Module: " + moduleName + " was replaced successfully"); } catch (IOException e) { LOG.warn("Couldn't replace compilation output for module: " + moduleName, e); } subTaskIndicator.finished(); })) .forEach(future -> { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOG.info("Couldn't apply compilation output", e); } }); indicatorManager.finished(this); LOG.info("Applying compilation output took: " + (System.currentTimeMillis() - start)); } @NotNull private List<AffectedModule> calculateAffectedModules(@Nullable Map<String, Map<String, BuildTargetState>> currentModulesState, @NotNull Map<String, Map<String, BuildTargetState>> commitModulesState, boolean checkExistance) { long start = System.currentTimeMillis(); List<AffectedModule> affectedModules = new ArrayList<>(); Map<String, String> oldModulesMap = new HashMap<>(); myOldModulesPaths = new ArrayList<>(); if (currentModulesState == null) { commitModulesState.forEach((type, map) -> { map.forEach((name, state) -> { affectedModules.add(new AffectedModule(type, name, state.getHash(), getBuildDirRelativeFile(state.getRelativePath()))); }); }); LOG.warn("Project doesn't contain metadata, force to download " + affectedModules.size() + " modules."); List<AffectedModule> result = mergeAffectedModules(affectedModules, commitModulesState); long total = System.currentTimeMillis() - start; LOG.info("Compilation output affected for the " + result.size() + " modules. Computation took " + total + "ms"); return result; } // Add new build types Set<String> newBuildTypes = new HashSet<>(commitModulesState.keySet()); newBuildTypes.removeAll(currentModulesState.keySet()); newBuildTypes.forEach(type -> { commitModulesState.get(type).forEach((name, state) -> { affectedModules.add(new AffectedModule(type, name, state.getHash(), getBuildDirRelativeFile(state.getRelativePath()))); }); }); // Calculate old paths for remove Set<String> oldBuildTypes = new HashSet<>(currentModulesState.keySet()); oldBuildTypes.removeAll(commitModulesState.keySet()); oldBuildTypes.forEach(type -> { currentModulesState.get(type).forEach((name, state) -> { oldModulesMap.put(name, state.getRelativePath()); }); }); commitModulesState.forEach((type, map) -> { Map<String, BuildTargetState> currentTypeState = currentModulesState.get(type); // New build type already added above if (currentTypeState == null) return; // Add new build modules Set<String> newBuildModules = new HashSet<>(map.keySet()); newBuildModules.removeAll(currentTypeState.keySet()); newBuildModules.forEach(name -> { BuildTargetState state = map.get(name); affectedModules.add(new AffectedModule(type, name, state.getHash(), getBuildDirRelativeFile(state.getRelativePath()))); }); // Calculate old modules paths for remove Set<String> oldBuildModules = new HashSet<>(currentTypeState.keySet()); oldBuildModules.removeAll(map.keySet()); oldBuildModules.forEach(name -> { BuildTargetState state = currentTypeState.get(name); oldModulesMap.put(name, state.getRelativePath()); }); // In another case compare modules inside the same build type map.forEach((name, state) -> { BuildTargetState currentTargetState = currentTypeState.get(name); if (currentTargetState == null || !state.equals(currentTargetState)) { affectedModules.add(new AffectedModule(type, name, state.getHash(), getBuildDirRelativeFile(state.getRelativePath()))); return; } File outFile = getBuildDirRelativeFile(state.getRelativePath()); if (checkExistance && (!outFile.exists() || ArrayUtil.isEmpty(outFile.listFiles()))) { affectedModules.add(new AffectedModule(type, name, state.getHash(), outFile)); } }); }); // Check that old modules not exist in other build types myOldModulesPaths = oldModulesMap.entrySet().stream().filter(entry -> { for (Map.Entry<String, Map<String, BuildTargetState>> commitEntry : commitModulesState.entrySet()) { BuildTargetState targetState = commitEntry.getValue().get(entry.getKey()); if (targetState != null && targetState.getRelativePath().equals(entry.getValue())) return false; } return true; }).map(entry -> getBuildDirRelativeFile(entry.getValue())) .collect(Collectors.toList()); List<AffectedModule> result = mergeAffectedModules(affectedModules, commitModulesState); long total = System.currentTimeMillis() - start; LOG.info("Compilation output affected for the " + result.size() + " modules. Computation took " + total + "ms"); return result; } @NotNull private static List<AffectedModule> mergeAffectedModules(List<AffectedModule> affectedModules, @NotNull Map<String, Map<String, BuildTargetState>> commitModulesState) { Set<AffectedModule> result = new HashSet<>(); affectedModules.forEach(affectedModule -> { if (affectedModule.getType().equals(JAVA_PRODUCTION)) { BuildTargetState targetState = commitModulesState.get(RESOURCES_PRODUCTION).get(affectedModule.getName()); if (targetState == null) { result.add(affectedModule); return; } String hash = calculateStringHash(affectedModule.getHash() + targetState.getHash()); result.add(new AffectedModule(PRODUCTION, affectedModule.getName(), hash, affectedModule.getOutPath())); } else if (affectedModule.getType().equals(RESOURCES_PRODUCTION)) { BuildTargetState targetState = commitModulesState.get(JAVA_PRODUCTION).get(affectedModule.getName()); if (targetState == null) { result.add(affectedModule); return; } String hash = calculateStringHash(targetState.getHash() + affectedModule.getHash()); result.add(new AffectedModule(PRODUCTION, affectedModule.getName(), hash, affectedModule.getOutPath())); } else if (affectedModule.getType().equals(JAVA_TEST)) { BuildTargetState targetState = commitModulesState.get(RESOURCES_TEST).get(affectedModule.getName()); if (targetState == null) { result.add(affectedModule); return; } String hash = calculateStringHash(affectedModule.getHash() + targetState.getHash()); result.add(new AffectedModule(TEST, affectedModule.getName(), hash, affectedModule.getOutPath())); } else if (affectedModule.getType().equals(RESOURCES_TEST)) { BuildTargetState targetState = commitModulesState.get(JAVA_TEST).get(affectedModule.getName()); if (targetState == null) { result.add(affectedModule); return; } String hash = calculateStringHash(targetState.getHash() + affectedModule.getHash()); result.add(new AffectedModule(TEST, affectedModule.getName(), hash, affectedModule.getOutPath())); } else { result.add(affectedModule); } }); return new ArrayList<>(result); } private File getBuildDirRelativeFile(String buildDirRelativePath) { return new File(buildDirRelativePath.replace("$BUILD_DIR$", myBuildDirPath)); } private static String calculateStringHash(String content) { Hasher hasher = Hashing.murmur3_128().newHasher(); return hasher.putString(content, StandardCharsets.UTF_8).hash().toString(); } @TestOnly List<File> getOldModulesPaths() { return myOldModulesPaths; } @TestOnly List<AffectedModule> getAffectedModules(@Nullable Map<String, Map<String, BuildTargetState>> currentModulesState, @NotNull Map<String, Map<String, BuildTargetState>> commitModulesState, boolean checkExistence) { return calculateAffectedModules(currentModulesState, commitModulesState, checkExistence); } private static final class UnzipOutputTask implements Runnable { private final OutputLoadResult loadResult; private final Map<File, String> result; private final SegmentedProgressIndicatorManager extractIndicatorManager; private UnzipOutputTask(Map<File, String> result, OutputLoadResult loadResult, SegmentedProgressIndicatorManager extractIndicatorManager) { this.result = result; this.loadResult = loadResult; this.extractIndicatorManager = extractIndicatorManager; } @Override public void run() { AffectedModule affectedModule = loadResult.getModule(); File outPath = affectedModule.getOutPath(); try { SegmentedProgressIndicatorManager.SubTaskProgressIndicator subTaskIndicator = extractIndicatorManager.createSubTaskIndicator(); extractIndicatorManager.getProgressIndicator().checkCanceled(); subTaskIndicator.setText2( JpsCacheBundle.message("progress.details.extracting.compilation.outputs.for.module", affectedModule.getName())); LOG.debug("Downloaded JPS compiled module from: " + loadResult.getDownloadUrl()); File tmpFolder = new File(outPath.getParent(), outPath.getName() + "_tmp"); File zipFile = loadResult.getZipFile(); ZipUtil.extract(zipFile, tmpFolder, null); FileUtil.delete(zipFile); result.put(tmpFolder, affectedModule.getName()); subTaskIndicator.finished(); } catch (IOException e) { LOG.warn("Couldn't extract download result for module: " + affectedModule.getName(), e); } } } }
/*************************GO-LICENSE-START********************************* * Copyright 2014 ThoughtWorks, 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. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.domain; import com.thoughtworks.go.config.*; import com.thoughtworks.go.helper.JobConfigMother; import com.thoughtworks.go.helper.PipelineConfigMother; import com.thoughtworks.go.service.TaskFactory; import com.thoughtworks.go.util.DataStructureUtils; import com.thoughtworks.go.util.ReflectionUtil; import com.thoughtworks.go.util.SystemEnvironment; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import java.util.HashMap; import static com.thoughtworks.go.util.DataStructureUtils.a; import static com.thoughtworks.go.util.DataStructureUtils.m; import static com.thoughtworks.go.util.TestUtils.sizeIs; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class JobConfigTest { JobConfig config; @Before public void setup(){ config = new JobConfig(); Tasks tasks = mock(Tasks.class); config.injectTasksForTest(tasks); doNothing().when(tasks).setConfigAttributes(Matchers.<Object>anyObject(), Matchers.<TaskFactory>any()); } @Test public void shouldCopyAttributeValuesFromAttributeMap() throws Exception { config = new JobConfig();//override the setup mock TaskFactory taskFactory = mock(TaskFactory.class); ExecTask emptyExecTask = new ExecTask(); when(taskFactory.taskInstanceFor(emptyExecTask.getTaskType())).thenReturn(emptyExecTask); config.setConfigAttributes(DataStructureUtils.m(JobConfig.NAME, "foo-job", JobConfig.TASKS, DataStructureUtils.m(Tasks.TASK_OPTIONS, "exec", "exec", DataStructureUtils.m(Task.TASK_TYPE, "exec", ExecTask.COMMAND, "ls", ExecTask.ARGS, "-la", ExecTask.WORKING_DIR, "/tmp"))), taskFactory); assertThat(config.name(), is(new CaseInsensitiveString("foo-job"))); assertThat(config.getTasks().get(0), is((Task) new ExecTask("ls", "-la", "/tmp"))); assertThat(config.getTasks().size(), is(1)); } @Test public void shouldSetTimeoutIfSpecified() throws Exception { config.setConfigAttributes( m(JobConfig.NAME, "foo-job", "timeoutType", JobConfig.OVERRIDE_TIMEOUT, JobConfig.TIMEOUT, "100", JobConfig.TASKS, m(Tasks.TASK_OPTIONS, "exec", "exec", m(Task.TASK_TYPE, "exec", ExecTask.COMMAND, "ls", ExecTask.ARGS, "-la", ExecTask.WORKING_DIR, "/tmp")))); assertThat(config.getTimeout(), is("100")); } @Test public void shouldClearTimeoutIfSubmittedWithEmptyValue() throws Exception { config.setConfigAttributes( m(JobConfig.NAME, "foo-job", "timeoutType", JobConfig.OVERRIDE_TIMEOUT, JobConfig.TIMEOUT, "", JobConfig.TASKS, m(Tasks.TASK_OPTIONS, "exec", "exec", m(Task.TASK_TYPE, "exec", ExecTask.COMMAND, "ls", ExecTask.ARGS, "-la", ExecTask.WORKING_DIR, "/tmp")))); assertThat(config.getTimeout(), is(nullValue())); } @Test public void shouldSetTimeoutToZeroIfSubmittedWithNever() throws Exception { config.setConfigAttributes(m(JobConfig.NAME, "foo-job", "timeoutType", JobConfig.NEVER_TIMEOUT, JobConfig.TIMEOUT, "100", JobConfig.TASKS, m(Tasks.TASK_OPTIONS, "exec", "exec", m(Task.TASK_TYPE, "exec", ExecTask.COMMAND, "ls", ExecTask.ARGS, "-la", ExecTask.WORKING_DIR, "/tmp")))); assertThat(config.getTimeout(), is("0")); } @Test public void shouldSetTimeoutToNullIfSubmittedWithDefault() throws Exception { config.setConfigAttributes(m(JobConfig.NAME, "foo-job", "timeoutType", JobConfig.DEFAULT_TIMEOUT, JobConfig.TIMEOUT, "", JobConfig.TASKS, m(Tasks.TASK_OPTIONS, "exec", "exec", m(Task.TASK_TYPE, "exec", ExecTask.COMMAND, "ls", ExecTask.ARGS, "-la", ExecTask.WORKING_DIR, "/tmp")))); assertThat(config.getTimeout(), is(nullValue())); } @Test public void shouldNotSetJobNameIfNotGiven() throws Exception { JobConfig config = new JobConfig("some-job-name"); config.setConfigAttributes(m()); assertThat(config.name(), is(new CaseInsensitiveString("some-job-name"))); config.setConfigAttributes(m(JobConfig.NAME, null)); assertThat(config.name(), is(nullValue())); } @Test public void shouldReturnAntTaskAsDefaultIfNoTasksSpecified() { JobConfig jobConfig = new JobConfig(); assertThat(jobConfig.tasks(), sizeIs(1)); Task task = jobConfig.tasks().first(); assertThat(task, instanceOf(NullTask.class)); } @Test public void shouldNotSetTasksIfNoTasksGiven() throws Exception { config = new JobConfig(); AntTask task = new AntTask(); task.setTarget("hello"); config.addTask(task); config.setConfigAttributes(m()); AntTask taskAfterUpdate = (AntTask) config.getTasks().get(0); assertThat(taskAfterUpdate.getTarget(), is("hello")); assertThat(config.getTasks().size(), is(1)); config.setConfigAttributes(m(JobConfig.TASKS, null)); assertThat(config.getTasks().size(), is(0)); } @Test public void shouldValidateTheJobName() { assertThat(createJobAndValidate(".name").errors().isEmpty(), is(true)); ConfigErrors configErrors = createJobAndValidate("name pavan").errors(); assertThat(configErrors.isEmpty(), is(false)); assertThat(configErrors.on(JobConfig.NAME), is("Invalid job name 'name pavan'. This must be alphanumeric and can contain underscores and periods. The maximum allowed length is 255 characters.")); } @Test public void shouldValidateAgainstSettingRunInstanceCountToIncorrectValue() { JobConfig jobConfig1 = new JobConfig(new CaseInsensitiveString("test")); jobConfig1.setRunInstanceCount(-1); jobConfig1.validate(ValidationContext.forChain(new CruiseConfig())); ConfigErrors configErrors1 = jobConfig1.errors(); assertThat(configErrors1.isEmpty(), is(false)); assertThat(configErrors1.on(JobConfig.RUN_TYPE), is("'Run Instance Count' cannot be a negative number as it represents number of instances Go needs to spawn during runtime.")); JobConfig jobConfig2 = new JobConfig(new CaseInsensitiveString("test")); ReflectionUtil.setField(jobConfig2, "runInstanceCount", "abcd"); jobConfig2.validate(ValidationContext.forChain(new CruiseConfig())); ConfigErrors configErrors2 = jobConfig2.errors(); assertThat(configErrors2.isEmpty(), is(false)); assertThat(configErrors2.on(JobConfig.RUN_TYPE), is("'Run Instance Count' should be a valid positive integer as it represents number of instances Go needs to spawn during runtime.")); } @Test public void shouldValidateAgainstSettingRunOnAllAgentsAndRunInstanceCountSetTogether() { JobConfig jobConfig = new JobConfig(new CaseInsensitiveString("test")); jobConfig.setRunOnAllAgents(true); jobConfig.setRunInstanceCount(10); jobConfig.validate(ValidationContext.forChain(new CruiseConfig())); ConfigErrors configErrors = jobConfig.errors(); assertThat(configErrors.isEmpty(), is(false)); assertThat(configErrors.on(JobConfig.RUN_TYPE), is("Job cannot be 'run on all agents' type and 'run multiple instance' type together.")); } @Test public void shouldValidateEmptyAndNullResources() { PipelineConfig pipelineConfig=PipelineConfigMother.CreatePipelineConfigWithJobConfigs("pipeline1"); JobConfig jobConfig = JobConfigMother.createJobConfigWithJobNameAndEmptyResources(); ValidationContext validationContext=mock(ValidationContext.class); when(validationContext.getPipeline()).thenReturn(pipelineConfig); when(validationContext.getStage()).thenReturn(pipelineConfig.getFirstStageConfig()); jobConfig.validate(validationContext); assertThat(jobConfig.errors().isEmpty(), is(false)); assertThat(jobConfig.errors().getAll().get(0),is("Empty resource name in job \"defaultJob\" of stage \"mingle\" of pipeline \"pipeline1\". If a template is used, please ensure that the resource parameters are defined for this pipeline.")); } @Test public void shouldErrorOutIfTwoJobsHaveSameName() { HashMap<String, JobConfig> visitedConfigs = new HashMap<String, JobConfig>(); visitedConfigs.put("defaultJob".toLowerCase(), new JobConfig("defaultJob")); JobConfig defaultJob = new JobConfig("defaultJob"); defaultJob.validateNameUniqueness(visitedConfigs); assertThat(defaultJob.errors().isEmpty(), is(false)); assertThat(defaultJob.errors().on(JobConfig.NAME), is("You have defined multiple jobs called 'defaultJob'. Job names are case-insensitive and must be unique.")); JobConfig defaultJobAllLowerCase = new JobConfig("defaultjob"); defaultJobAllLowerCase.validateNameUniqueness(visitedConfigs); assertThat(defaultJobAllLowerCase.errors().isEmpty(), is(false)); assertThat(defaultJobAllLowerCase.errors().on(JobConfig.NAME), is("You have defined multiple jobs called 'defaultjob'. Job names are case-insensitive and must be unique.")); } @Test public void shouldPopulateEnvironmentVariablesFromAttributeMap() { JobConfig jobConfig = new JobConfig(); HashMap map = new HashMap(); HashMap valueHashMap = new HashMap(); valueHashMap.put("name", "FOO"); valueHashMap.put("value", "BAR"); map.put(JobConfig.ENVIRONMENT_VARIABLES, valueHashMap); EnvironmentVariablesConfig mockEnvironmentVariablesConfig = mock(EnvironmentVariablesConfig.class); jobConfig.setVariables(mockEnvironmentVariablesConfig); jobConfig.setConfigAttributes(map); verify(mockEnvironmentVariablesConfig).setConfigAttributes(valueHashMap); } @Test public void shouldPopulateResourcesFromAttributeMap() { HashMap map = new HashMap(); String value = "a, b,c ,d,e"; map.put(JobConfig.RESOURCES, value); Resources resources = new Resources(); resources.add(new Resource("z")); JobConfig jobConfig = new JobConfig(new CaseInsensitiveString("job-name"), resources, null); jobConfig.setConfigAttributes(map); assertThat(jobConfig.resources().size(), is(5)); } @Test public void shouldPopulateTabsFromAttributeMap() { JobConfig jobConfig = new JobConfig("job-name"); jobConfig.setConfigAttributes(m(JobConfig.TABS, a(m(Tab.NAME, "tab1", Tab.PATH, "path1"), m(Tab.NAME, "tab2", Tab.PATH, "path2")))); assertThat(jobConfig.getTabs().size(), is(2)); assertThat(jobConfig.getTabs().get(0).getName(), is("tab1")); assertThat(jobConfig.getTabs().get(1).getName(), is("tab2")); assertThat(jobConfig.getTabs().get(0).getPath(), is("path1")); assertThat(jobConfig.getTabs().get(1).getPath(), is("path2")); } @Test public void shouldSetJobRunTypeCorrectly_forRails4() { // single instance HashMap map1 = new HashMap(); map1.put(JobConfig.RUN_TYPE, JobConfig.RUN_SINGLE_INSTANCE); map1.put(JobConfig.RUN_INSTANCE_COUNT, "10"); // should be ignored JobConfig jobConfig1 = new JobConfig(); jobConfig1.setConfigAttributes(map1); assertThat(jobConfig1.isRunOnAllAgents(), is(false)); assertThat(jobConfig1.isRunMultipleInstanceType(), is(false)); assertThat(jobConfig1.getRunInstanceCount(), is(nullValue())); // run on all agents HashMap map2 = new HashMap(); map2.put(JobConfig.RUN_TYPE, JobConfig.RUN_ON_ALL_AGENTS); JobConfig jobConfig2 = new JobConfig(); jobConfig2.setConfigAttributes(map2); assertThat(jobConfig2.isRunOnAllAgents(), is(true)); assertThat(jobConfig2.isRunMultipleInstanceType(), is(false)); assertThat(jobConfig2.getRunInstanceCount(), is(nullValue())); // run multiple instance HashMap map3 = new HashMap(); map3.put(JobConfig.RUN_TYPE, JobConfig.RUN_MULTIPLE_INSTANCE); map3.put(JobConfig.RUN_INSTANCE_COUNT, "10"); JobConfig jobConfig3 = new JobConfig(); jobConfig3.setConfigAttributes(map3); assertThat(jobConfig3.isRunMultipleInstanceType(), is(true)); assertThat(jobConfig3.getRunInstanceCountValue(), is(10)); assertThat(jobConfig3.isRunOnAllAgents(), is(false)); HashMap map4 = new HashMap(); map4.put(JobConfig.RUN_TYPE, JobConfig.RUN_MULTIPLE_INSTANCE); map4.put(JobConfig.RUN_INSTANCE_COUNT, ""); JobConfig jobConfig4 = new JobConfig(); jobConfig4.setConfigAttributes(map4); assertThat(jobConfig4.isRunMultipleInstanceType(), is(false)); assertThat(jobConfig4.getRunInstanceCount(), is(nullValue())); assertThat(jobConfig4.isRunOnAllAgents(), is(false)); } @Test public void shouldResetJobRunTypeCorrectly() { HashMap map1 = new HashMap(); map1.put(JobConfig.RUN_TYPE, JobConfig.RUN_MULTIPLE_INSTANCE); map1.put(JobConfig.RUN_INSTANCE_COUNT, "10"); JobConfig jobConfig = new JobConfig(); jobConfig.setConfigAttributes(map1); assertThat(jobConfig.getRunInstanceCountValue(), is(10)); assertThat(jobConfig.isRunMultipleInstanceType(), is(true)); assertThat(jobConfig.isRunOnAllAgents(), is(false)); // should not reset value when correct key not present HashMap map2 = new HashMap(); jobConfig.setConfigAttributes(map2); assertThat(jobConfig.getRunInstanceCountValue(), is(10)); assertThat(jobConfig.isRunMultipleInstanceType(), is(true)); assertThat(jobConfig.isRunOnAllAgents(), is(false)); // reset value for same job config HashMap map3 = new HashMap(); map3.put(JobConfig.RUN_TYPE, JobConfig.RUN_SINGLE_INSTANCE); jobConfig.setConfigAttributes(map3); assertThat(jobConfig.isRunMultipleInstanceType(), is(false)); assertThat(jobConfig.getRunInstanceCount(), is(nullValue())); assertThat(jobConfig.isRunOnAllAgents(), is(false)); } @Test public void shouldPopulateArtifactPlansFromAttributeMap() { HashMap map = new HashMap(); HashMap valueHashMap = new HashMap(); valueHashMap.put("src", "dest"); valueHashMap.put("src1", "dest1"); map.put(JobConfig.ARTIFACT_PLANS, valueHashMap); ArtifactPlans mockArtifactPlans = mock(ArtifactPlans.class); JobConfig jobConfig = new JobConfig(new CaseInsensitiveString("job-name"), new Resources(), mockArtifactPlans); jobConfig.setConfigAttributes(map); verify(mockArtifactPlans).setConfigAttributes(valueHashMap); } @Test public void shouldValidateThatTheTimeoutIsAValidNumber() { JobConfig job = new JobConfig("job"); job.setTimeout("5.5"); job.validate(ValidationContext.forChain(new CruiseConfig())); assertThat(job.errors().isEmpty(), is(true)); } @Test public void shouldMarkJobInvalidIfTimeoutIsNotAValidNumber() { JobConfig job = new JobConfig("job"); job.setTimeout("5.5MN"); job.validate(ValidationContext.forChain(new CruiseConfig())); assertThat(job.errors().isEmpty(), is(false)); assertThat(job.errors().on(JobConfig.TIMEOUT), is("Timeout should be a valid number as it represents number of minutes")); } @Test public void shouldReturnTimeoutType() { JobConfig job = new JobConfig("job"); assertThat(job.getTimeoutType(), is(JobConfig.DEFAULT_TIMEOUT)); job.setTimeout("0"); assertThat(job.getTimeoutType(), is(JobConfig.NEVER_TIMEOUT)); job.setTimeout("10"); assertThat(job.getTimeoutType(), is(JobConfig.OVERRIDE_TIMEOUT)); } @Test public void shouldReturnRunTypeCorrectly() { JobConfig job = new JobConfig("job"); assertThat(job.getRunType(), is(JobConfig.RUN_SINGLE_INSTANCE)); job.setRunOnAllAgents(true); assertThat(job.getRunType(), is(JobConfig.RUN_ON_ALL_AGENTS)); job.setRunOnAllAgents(false); job.setRunInstanceCount(10); assertThat(job.getRunType(), is(JobConfig.RUN_MULTIPLE_INSTANCE)); } @Test public void shouldErrorOutWhenTimeoutIsANegativeNumber() { JobConfig jobConfig = new JobConfig("job"); jobConfig.setTimeout("-1"); jobConfig.validate(ValidationContext.forChain(new CruiseConfig())); assertThat(jobConfig.errors().isEmpty(), is(false)); assertThat(jobConfig.errors().on(JobConfig.TIMEOUT), is("Timeout cannot be a negative number as it represents number of minutes")); } private JobConfig createJobAndValidate(final String name) { JobConfig jobConfig = new JobConfig(name); jobConfig.validate(ValidationContext.forChain(new CruiseConfig())); return jobConfig; } }
/*L * Copyright Moxie Informatics. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/calims/LICENSE.txt for details. */ /** * */ package gov.nih.nci.calims2.ui.inventory.wholeorganism; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import gov.nih.nci.calims2.business.common.type.TypeEnumeration; import gov.nih.nci.calims2.business.generic.GenericService; import gov.nih.nci.calims2.business.inventory.specimen.SpecimenService; import gov.nih.nci.calims2.business.util.validation.ValidationException; import gov.nih.nci.calims2.business.util.validation.ValidationMessageHelper; import gov.nih.nci.calims2.domain.administration.Location; import gov.nih.nci.calims2.domain.administration.Organization; import gov.nih.nci.calims2.domain.administration.Person; import gov.nih.nci.calims2.domain.administration.Quantity; import gov.nih.nci.calims2.domain.administration.StandardUnit; import gov.nih.nci.calims2.domain.common.Type; import gov.nih.nci.calims2.domain.interfaces.EntityWithIdHelper; import gov.nih.nci.calims2.domain.inventory.AdditionalOrganismName; import gov.nih.nci.calims2.domain.inventory.Container; import gov.nih.nci.calims2.domain.inventory.ContainerSubcategory; import gov.nih.nci.calims2.domain.inventory.ContainerType; import gov.nih.nci.calims2.domain.inventory.FillPattern; import gov.nih.nci.calims2.domain.inventory.Specimen; import gov.nih.nci.calims2.domain.inventory.Taxon; import gov.nih.nci.calims2.domain.inventory.WholeOrganism; import gov.nih.nci.calims2.domain.inventory.enumeration.ContainerComposition; import gov.nih.nci.calims2.ui.generic.crud.CRUDController; import gov.nih.nci.calims2.ui.generic.crud.CRUDControllerConfig; import gov.nih.nci.calims2.ui.generic.crud.CRUDFormDecorator; import gov.nih.nci.calims2.ui.generic.crud.CRUDTableDecorator; import gov.nih.nci.calims2.ui.inventory.quantity.QuantityHelper; import gov.nih.nci.calims2.ui.inventory.specimen.SpecimenTableDecorator; import gov.nih.nci.calims2.ui.util.interceptor.FlowContextInterceptor; import gov.nih.nci.calims2.uic.descriptor.table.Table; import gov.nih.nci.calims2.uic.flow.FlowContextHolder; /** * @author connollym * */ @Controller @RequestMapping(WholeOrganismController.URL_PREFIX) public class WholeOrganismController extends CRUDController<WholeOrganism> { /** Prefix of urls of this module. */ static final String URL_PREFIX = "/inventory/wholeorganism"; /** Create type subflow id.*/ static final int TYPE_SUBFLOW_ID = 0; /** Create taxon subflow id.*/ static final int TAXON_SUBFLOW_ID = 1; /** Create organization subflow id.*/ static final int ORGANIZATION_SUBFLOW_ID = 2; /** Create location subflow id.*/ static final int LOCATION_SUBFLOW_ID = 3; /** Create specimen subflow id.*/ static final int SPECIMEN_SUBFLOW_ID = 4; /** Create specimen subflow id.*/ static final int CONTAINER_SUBFLOW_ID = 5; /** Create standard unit subflow id.*/ static final int STANDARD_UNIT_SUBFLOW_ID = 6; /** Create standard unit subflow id.*/ static final int ADDITIONALORGANISMNAME_SUBFLOW_ID = 7; /** Create person subflow id. */ static final int PERSON_SUBFLOW_ID = 9; private static final String TYPE_QUERY = Type.class.getName() + ".findByDataElementCollection"; private static final String CONTAINER_FOR_CREATION_QUERY = Container.class.getName() + ".findContainersForSpecimenCreation"; private static final String CONTAINER_FOR_UPDATE_QUERY = Container.class.getName() + ".findContainersForSpecimenUpdate"; private GenericService<Container> containerService; private GenericService<Location> locationService; private GenericService<Organization> organizationService; private GenericService<Person> personService; private QuantityHelper quantityHelper; private GenericService<Taxon> taxonService; private GenericService<Type> typeService; private GenericService<StandardUnit> unitService; private GenericService<AdditionalOrganismName> additionalOrganismNameService; private GenericService<ContainerSubcategory> containerSubcategoryService; private GenericService<ContainerType> containerTypeService; private GenericService<FillPattern> fillPatternService; /** * Default constructor. */ public WholeOrganismController() { super(URL_PREFIX, "name"); CRUDControllerConfig config = getConfig(); config.setSubFlowUrls(new String[] {"/common/type/create.do?dataElementCollection=" + TypeEnumeration.WHOLEORGANISM, "/inventory/taxon/create.do", "/administration/organization/create.do", "/administration/location/create.do", "/inventory/wholeorganism/create.do", "/inventory/container/create.do", "/administration/standardunit/create.do", "/inventory/additionalorganismname/create.do", "/common/externalidentifier/enterList.do", "/administration/person/create.do", "/inventory/specimen/transferForSpecimen.do", "/common/document/enterList.do"}); config.setAdvancedSearch(true); } /** * Adds the category and subcategory to the model. * * @param model The model to which the categories must be added. */ void addCategories(ModelAndView model) { WholeOrganism specimen = ((WholeOrganismForm) model.getModel().get("form")).getEntity(); if (specimen.getContainer() != null) { Container container = containerService.findById(Container.class, specimen.getContainer().getId()); model.addObject("containerType", container.getContainerType()); model.addObject("subCategory", container.getContainerType().getContainerSubcategory()); model.addObject("category", container.getContainerType().getContainerSubcategory().getType()); } } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public ModelAndView completeEditModel(ModelAndView model, Locale locale) { List<AdditionalOrganismName> additionalOrganismNames = additionalOrganismNameService.findAll(AdditionalOrganismName.class, "name"); model.addObject("additionalOrganismNames", additionalOrganismNames); WholeOrganismForm form = (WholeOrganismForm) model.getModel().get("form"); List<Container> containers = null; Map<String, Object> params = new HashMap<String, Object>(); if (form.isEditMode()) { params.put("containerId", form.getEntity().getContainer().getId()); containers = containerService.findByNamedQuery(CONTAINER_FOR_UPDATE_QUERY, params); } else { containers = containerService.findByNamedQuery(CONTAINER_FOR_CREATION_QUERY, params); } model.addObject("containers", containers); params = new HashMap<String, Object>(); params.put("dataElementCollection", TypeEnumeration.CONTAINER.name()); List<Type> containerCategories = typeService.findByNamedQuery(TYPE_QUERY, params); model.addObject("containerCategories", containerCategories); List<ContainerSubcategory> containerSubcategories = containerSubcategoryService.findAll(ContainerSubcategory.class, "name"); model.addObject("containerSubcategories", containerSubcategories); List<ContainerType> containerTypes = containerTypeService.findAll(ContainerType.class, "name"); model.addObject("containerTypes", containerTypes); List<FillPattern> fillPatterns = fillPatternService.findAll(FillPattern.class, "name"); model.addObject("fillPatterns", fillPatterns); List<Location> locations = locationService.findAll(Location.class, "name"); model.addObject("locations", locations); List<Organization> organizations = organizationService.findAll(Organization.class, "name"); model.addObject("organizations", organizations); List<Person> persons = personService.findAll(Person.class, "familyName"); model.addObject("persons", persons); List<Specimen> parentSpecimens = ((GenericService) super.getMainService()).findAll(Specimen.class, "name"); Specimen specimen = ((WholeOrganismForm) model.getModel().get("form")).getEntity(); model.addObject("specimens", filterDescendents(parentSpecimens, specimen)); List<Taxon> taxons = taxonService.findAll(Taxon.class, "name"); model.addObject("taxons", taxons); params = new HashMap<String, Object>(); params.put("dataElementCollection", TypeEnumeration.WHOLEORGANISM.name()); List<Type> types = typeService.findByNamedQuery(TYPE_QUERY, params); model.addObject("types", types); List<StandardUnit> units = unitService.findAll(StandardUnit.class, "name"); model.addObject("standardUnits", units); addCategories(model); addQuantities(model, true); return model; } /** * * @param model The model to which the quantities must be added. * @param createMissing True if quantities missing in the container class must be added. */ void addQuantities(ModelAndView model, boolean createMissing) { Set<Quantity> quantities = ((WholeOrganismForm) model.getModel().get("form")).getEntity().getQuantityCollection(); model.addObject("quantities", quantityHelper.getQuantities(TypeEnumeration.SPECIMEN_QUANTITY, quantities, createMissing)); } /** * filters the descendants of the given location from the list of locations. * * @param specimens The list of specimens to filter * @param specimen The specimen to filter from the list (with all its descendants) * @return The filtered list. */ List<Specimen> filterDescendents(List<Specimen> specimens, Specimen specimen) { if (specimen.getId() == null) { return specimens; } List<Specimen> result = new ArrayList<Specimen>(); for (Specimen candidate : specimens) { Specimen currentSpecimen = candidate; while (currentSpecimen != null && !currentSpecimen.getId().equals(specimen.getId())) { currentSpecimen = currentSpecimen.getParentSpecimen(); } if (currentSpecimen == null) { result.add(candidate); } } return result; } /** * Calls a subflow. * * @param form The object containing the values of the entity to be saved. * @param subFlowId The id of the flow to call in the subFlowUrls array. * @return The next view to go to. It is a forward to the entry action of the subflow. */ @RequestMapping(CRUDControllerConfig.STD_CALL_COMMAND) public ModelAndView call(@ModelAttribute("form") WholeOrganismForm form, @RequestParam("subFlowId") int subFlowId) { return super.doCall(form, subFlowId); } /** * {@inheritDoc} */ public void doReturnFromFlow(ModelAndView model, int subFlowId, Long entityId) { if (entityId != null) { WholeOrganism wholeOrganism = ((WholeOrganismForm) model.getModel().get("form")).getEntity(); switch (subFlowId) { case TAXON_SUBFLOW_ID: { wholeOrganism.setTaxon(EntityWithIdHelper.createEntity(Taxon.class, entityId)); break; } case ORGANIZATION_SUBFLOW_ID: { wholeOrganism.getOrganizationCollection().add(EntityWithIdHelper.createEntity(Organization.class, entityId)); break; } case LOCATION_SUBFLOW_ID: { wholeOrganism.getSamplingLocationCollection().add(EntityWithIdHelper.createEntity(Location.class, entityId)); break; } case TYPE_SUBFLOW_ID: { wholeOrganism.setType(EntityWithIdHelper.createEntity(Type.class, entityId)); break; } case SPECIMEN_SUBFLOW_ID: { wholeOrganism.setParentSpecimen(EntityWithIdHelper.createEntity(Specimen.class, entityId)); break; } case CONTAINER_SUBFLOW_ID: { wholeOrganism.setContainer(EntityWithIdHelper.createEntity(Container.class, entityId)); break; } case STANDARD_UNIT_SUBFLOW_ID: { break; } case ADDITIONALORGANISMNAME_SUBFLOW_ID : { wholeOrganism.getAdditionalOrganismNameCollection().add(EntityWithIdHelper.createEntity(AdditionalOrganismName.class, entityId)); break; } case PERSON_SUBFLOW_ID: { wholeOrganism.setContactPerson(EntityWithIdHelper.createEntity(Person.class, entityId)); break; } default: { throw new IllegalArgumentException("Wrong subFlowId"); } } } } /** * {@inheritDoc} */ public ModelAndView completeDetailsModel(ModelAndView model, Locale locale) { addQuantities(model, false); addCategories(model); return model; } /** * Saves an entity and returns a refreshed list type page. * * @param form The object containing the values of the entity to be saved. * @param locale The current locale. * @return The list view. */ @SuppressWarnings("unchecked") @RequestMapping(CRUDControllerConfig.STD_SAVE_COMMAND) public ModelAndView save(@ModelAttribute("form") WholeOrganismForm form, Locale locale) { Container container = containerService.findById(Container.class, form.getContainerId()); if (container.getContainerType().getComposition() == ContainerComposition.COMPOSITE) { CRUDControllerConfig config = getConfig(); ModelAndView model = new ModelAndView(); WholeOrganism input = form.getSubmittedEntity(); try { completeExtraction(form); GenericService specimenService = super.getMainService(); ((SpecimenService) specimenService).createForCompositeContainer(input, form.getFillPatternId()); model.setViewName(config.getRedirectUrl(config.getListCommand())); model.addObject(FlowContextInterceptor.CONTEXT_PARAM, FlowContextHolder.setPersistAttributeForClient(this)); } catch (ValidationException e) { model = createEditModel(input, form.getReturnView(), locale); model.addObject("messagekey", ValidationMessageHelper.getErrors(e)); model.addObject("form", form); model.setViewName(config.getFullViewName(config.getEditView())); model.addObject(FlowContextInterceptor.CONTEXT_PARAM, FlowContextHolder.getSerializedContext()); } return model; } return doSave(form, locale); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") protected Class<? extends CRUDTableDecorator> getDefaultTableDecoratorClass() { return SpecimenTableDecorator.class; } /** * @param container the containerService to set */ @Resource(name = "containerService") public void setContainerService(GenericService<Container> container) { containerService = container; } /** * @param containerSubcategoryService the containerSubcategoryService to set */ @Resource(name = "containerSubcategoryService") public void setContainerSubcategoryService(GenericService<ContainerSubcategory> containerSubcategoryService) { this.containerSubcategoryService = containerSubcategoryService; } /** * @param containerTypeService the containerTypeService to set */ @Resource(name = "containerTypeService") public void setContainerTypeService(GenericService<ContainerType> containerTypeService) { this.containerTypeService = containerTypeService; } /** * @param fillPattern the fillPatternService to set */ @Resource(name = "fillPatternService") public void setFillPatternService(GenericService<FillPattern> fillPattern) { fillPatternService = fillPattern; } /** * @param location the locationService to set */ @Resource(name = "locationService") public void setLocationService(GenericService<Location> location) { locationService = location; } /** * @param organization the organizationService to set */ @Resource(name = "organizationService") public void setOrganizationService(GenericService<Organization> organization) { organizationService = organization; } /** * @param person the personService to set */ @Resource(name = "personService") public void setPersonService(GenericService<Person> person) { personService = person; } /** * @param quantityHelper the quantityHelper to set */ @Resource(name = "quantityHelper") public void setQuantityHelper(QuantityHelper quantityHelper) { this.quantityHelper = quantityHelper; } /** * @param specimenService the specimenService to set */ @Resource(name = "specimenService") public void setSpecimenService(GenericService<WholeOrganism> specimenService) { super.setMainService(specimenService); } /** * @param taxon the taxonService to set */ @Resource(name = "taxonService") public void setTaxonService(GenericService<Taxon> taxon) { taxonService = taxon; } /** * @param additionalOrganismName the additionalOrganismNameService to set */ @Resource(name = "additionalOrganismNameService") public void setAdditionalOrganismNameService(GenericService<AdditionalOrganismName> additionalOrganismName) { additionalOrganismNameService = additionalOrganismName; } /** * @param type the typeService to set */ @Resource(name = "typeService") public void setTypeService(GenericService<Type> type) { typeService = type; } /** * @param unitService the unitService to set */ @Resource(name = "unitService") public void setUnitService(GenericService<StandardUnit> unitService) { this.unitService = unitService; } /** * @param formDecorator the formDecorator to set */ @Resource(name = "wholeOrganismFormDecorator") public void setFormDecorator(CRUDFormDecorator formDecorator) { super.setFormDecorator(formDecorator); } /** * @param listTable the listTable to set */ @Resource(name = "wholeOrganismTable") public void setListTable(Table listTable) { super.setListTable(listTable); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.activemq.transport.amqp.client; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.InvalidDestinationException; import org.apache.activemq.transport.amqp.client.util.AsyncResult; import org.apache.activemq.transport.amqp.client.util.ClientFuture; import org.apache.activemq.transport.amqp.client.util.UnmodifiableProxy; import org.apache.qpid.proton.amqp.Binary; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.messaging.Accepted; import org.apache.qpid.proton.amqp.messaging.Modified; import org.apache.qpid.proton.amqp.messaging.Outcome; import org.apache.qpid.proton.amqp.messaging.Rejected; import org.apache.qpid.proton.amqp.messaging.Released; import org.apache.qpid.proton.amqp.messaging.Source; import org.apache.qpid.proton.amqp.messaging.Target; import org.apache.qpid.proton.amqp.transaction.TransactionalState; import org.apache.qpid.proton.amqp.transport.DeliveryState; import org.apache.qpid.proton.amqp.transport.ErrorCondition; import org.apache.qpid.proton.amqp.transport.ReceiverSettleMode; import org.apache.qpid.proton.amqp.transport.SenderSettleMode; import org.apache.qpid.proton.engine.Delivery; import org.apache.qpid.proton.engine.Sender; import org.apache.qpid.proton.message.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Sender class that manages a Proton sender endpoint. */ public class AmqpSender extends AmqpAbstractResource<Sender> { private static final Logger LOG = LoggerFactory.getLogger(AmqpSender.class); private static final byte[] EMPTY_BYTE_ARRAY = new byte[] {}; public static final long DEFAULT_SEND_TIMEOUT = 15000; private final AmqpTransferTagGenerator tagGenerator = new AmqpTransferTagGenerator(true); private final AtomicBoolean closed = new AtomicBoolean(); private final AmqpSession session; private final String address; private final String senderId; private final Target userSpecifiedTarget; private final SenderSettleMode userSpecifiedSenderSettlementMode; private final ReceiverSettleMode userSpecifiedReceiverSettlementMode; private boolean presettle; private long sendTimeout = DEFAULT_SEND_TIMEOUT; private final Set<Delivery> pending = new LinkedHashSet<>(); private byte[] encodeBuffer = new byte[1024 * 8]; private Symbol[] desiredCapabilities; private Symbol[] offeredCapabilities; private Map<Symbol, Object> properties; /** * Create a new sender instance. * * @param session * The parent session that created the session. * @param address * The address that this sender produces to. * @param senderId * The unique ID assigned to this sender. */ public AmqpSender(AmqpSession session, String address, String senderId) { this(session, address, senderId, null, null); } /** * Create a new sender instance. * * @param session * The parent session that created the session. * @param address * The address that this sender produces to. * @param senderId * The unique ID assigned to this sender. * @param senderMode * The {@link SenderSettleMode} to use on open. * @param receiverMode * The {@link ReceiverSettleMode} to use on open. */ public AmqpSender(AmqpSession session, String address, String senderId, SenderSettleMode senderMode, ReceiverSettleMode receiverMode) { if (address != null && address.isEmpty()) { throw new IllegalArgumentException("Address cannot be empty."); } this.session = session; this.address = address; this.senderId = senderId; this.userSpecifiedTarget = null; this.userSpecifiedSenderSettlementMode = senderMode; this.userSpecifiedReceiverSettlementMode = receiverMode; } /** * Create a new sender instance using the given Target when creating the link. * * @param session * The parent session that created the session. * @param target * The target that this sender produces to. * @param senderId * The unique ID assigned to this sender. */ public AmqpSender(AmqpSession session, Target target, String senderId) { if (target == null) { throw new IllegalArgumentException("User specified Target cannot be null"); } this.session = session; this.address = target.getAddress(); this.senderId = senderId; this.userSpecifiedTarget = target; this.userSpecifiedSenderSettlementMode = null; this.userSpecifiedReceiverSettlementMode = null; } /** * Sends the given message to this senders assigned address. * * @param message * the message to send. * @throws IOException * if an error occurs during the send. */ public void send(final AmqpMessage message) throws IOException { checkClosed(); send(message, null); } /** * Sends the given message to this senders assigned address using the supplied transaction * ID. * * @param message * the message to send. * @param txId * the transaction ID to assign the outgoing send. * @throws IOException * if an error occurs during the send. */ public void send(final AmqpMessage message, final AmqpTransactionId txId) throws IOException { checkClosed(); final ClientFuture sendRequest = new ClientFuture(); session.getScheduler().execute(new Runnable() { @Override public void run() { try { doSend(message, sendRequest, txId); session.pumpToProtonTransport(sendRequest); } catch (Exception e) { sendRequest.onFailure(e); session.getConnection().fireClientException(e); } } }); if (sendTimeout <= 0) { sendRequest.sync(); } else { sendRequest.sync(sendTimeout, TimeUnit.MILLISECONDS); } } /** * Close the sender, a closed sender will throw exceptions if any further send calls are * made. * * @throws IOException * if an error occurs while closing the sender. */ public void close() throws IOException { if (closed.compareAndSet(false, true)) { final ClientFuture request = new ClientFuture(); session.getScheduler().execute(new Runnable() { @Override public void run() { checkClosed(); close(request); session.pumpToProtonTransport(request); } }); request.sync(); } } /** * @return this session's parent AmqpSession. */ public AmqpSession getSession() { return session; } /** * @return an unmodifiable view of the underlying Sender instance. */ public Sender getSender() { return UnmodifiableProxy.senderProxy(getEndpoint()); } /** * @return the assigned address of this sender. */ public String getAddress() { return address; } // ----- Sender configuration ---------------------------------------------// /** * @return will messages be settle on send. */ public boolean isPresettle() { return presettle; } /** * Configure is sent messages are marked as settled on send, defaults to false. * * @param presettle * configure if this sender will presettle all sent messages. */ public void setPresettle(boolean presettle) { this.presettle = presettle; } /** * @return the currently configured send timeout. */ public long getSendTimeout() { return sendTimeout; } /** * Sets the amount of time the sender will block on a send before failing. * * @param sendTimeout * time in milliseconds to wait. */ public void setSendTimeout(long sendTimeout) { this.sendTimeout = sendTimeout; } public void setDesiredCapabilities(Symbol[] desiredCapabilities) { if (getEndpoint() != null) { throw new IllegalStateException("Endpoint already established"); } this.desiredCapabilities = desiredCapabilities; } public void setOfferedCapabilities(Symbol[] offeredCapabilities) { if (getEndpoint() != null) { throw new IllegalStateException("Endpoint already established"); } this.offeredCapabilities = offeredCapabilities; } public void setProperties(Map<Symbol, Object> properties) { if (getEndpoint() != null) { throw new IllegalStateException("Endpoint already established"); } this.properties = properties; } // ----- Private Sender implementation ------------------------------------// private void checkClosed() { if (isClosed()) { throw new IllegalStateException("Sender is already closed"); } } @Override protected void doOpen() { Symbol[] outcomes = new Symbol[] {Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL}; Source source = new Source(); source.setAddress(senderId); source.setOutcomes(outcomes); Target target = userSpecifiedTarget; if (target == null) { target = new Target(); target.setAddress(address); } String senderName = senderId + ":" + address; Sender sender = session.getEndpoint().sender(senderName); sender.setSource(source); sender.setTarget(target); if (userSpecifiedSenderSettlementMode != null) { sender.setSenderSettleMode(userSpecifiedSenderSettlementMode); if (SenderSettleMode.SETTLED.equals(userSpecifiedSenderSettlementMode)) { presettle = true; } } else { if (presettle) { sender.setSenderSettleMode(SenderSettleMode.SETTLED); } else { sender.setSenderSettleMode(SenderSettleMode.UNSETTLED); } } if (userSpecifiedReceiverSettlementMode != null) { sender.setReceiverSettleMode(userSpecifiedReceiverSettlementMode); } else { sender.setReceiverSettleMode(ReceiverSettleMode.FIRST); } sender.setDesiredCapabilities(desiredCapabilities); sender.setOfferedCapabilities(offeredCapabilities); sender.setProperties(properties); setEndpoint(sender); super.doOpen(); } @Override protected void doOpenCompletion() { // Verify the attach response contained a non-null target org.apache.qpid.proton.amqp.transport.Target t = getEndpoint().getRemoteTarget(); if (t != null) { super.doOpenCompletion(); } else { // No link terminus was created, the peer will now detach/close us. } } @Override protected void doOpenInspection() { try { getStateInspector().inspectOpenedResource(getSender()); } catch (Throwable error) { getStateInspector().markAsInvalid(error.getMessage()); } } @Override protected void doClosedInspection() { try { getStateInspector().inspectClosedResource(getSender()); } catch (Throwable error) { getStateInspector().markAsInvalid(error.getMessage()); } } @Override protected void doDetachedInspection() { try { getStateInspector().inspectDetachedResource(getSender()); } catch (Throwable error) { getStateInspector().markAsInvalid(error.getMessage()); } } protected void doDeliveryUpdateInspection(Delivery delivery) { try { getStateInspector().inspectDeliveryUpdate(getSender(), delivery); } catch (Throwable error) { getStateInspector().markAsInvalid(error.getMessage()); } } @Override protected Exception getOpenAbortException() { // Verify the attach response contained a non-null target org.apache.qpid.proton.amqp.transport.Target t = getEndpoint().getRemoteTarget(); if (t != null) { return super.getOpenAbortException(); } else { // No link terminus was created, the peer has detach/closed us, create IDE. return new InvalidDestinationException("Link creation was refused"); } } private void doSend(AmqpMessage message, AsyncResult request, AmqpTransactionId txId) throws Exception { LOG.trace("Producer sending message: {}", message); Delivery delivery = null; if (presettle) { delivery = getEndpoint().delivery(EMPTY_BYTE_ARRAY, 0, 0); } else { byte[] tag = tagGenerator.getNextTag(); delivery = getEndpoint().delivery(tag, 0, tag.length); } delivery.setContext(request); Binary amqpTxId = null; if (txId != null) { amqpTxId = txId.getRemoteTxId(); } else if (session.isInTransaction()) { amqpTxId = session.getTransactionId().getRemoteTxId(); } if (amqpTxId != null) { TransactionalState state = new TransactionalState(); state.setTxnId(amqpTxId); delivery.disposition(state); } encodeAndSend(message.getWrappedMessage(), delivery); if (presettle) { delivery.settle(); request.onSuccess(); } else { pending.add(delivery); getEndpoint().advance(); } } private void encodeAndSend(Message message, Delivery delivery) throws IOException { int encodedSize; while (true) { try { encodedSize = message.encode(encodeBuffer, 0, encodeBuffer.length); break; } catch (java.nio.BufferOverflowException e) { encodeBuffer = new byte[encodeBuffer.length * 2]; } } int sentSoFar = 0; while (true) { int sent = getEndpoint().send(encodeBuffer, sentSoFar, encodedSize - sentSoFar); if (sent > 0) { sentSoFar += sent; if ((encodedSize - sentSoFar) == 0) { break; } } else { LOG.warn("{} failed to send any data from current Message.", this); } } } @Override public void processDeliveryUpdates(AmqpConnection connection, Delivery updated) throws IOException { List<Delivery> toRemove = new ArrayList<>(); for (Delivery delivery : pending) { DeliveryState state = delivery.getRemoteState(); if (state == null) { continue; } doDeliveryUpdateInspection(delivery); Outcome outcome = null; if (state instanceof TransactionalState) { LOG.trace("State of delivery is Transactional, retrieving outcome: {}", state); outcome = ((TransactionalState) state).getOutcome(); } else if (state instanceof Outcome) { outcome = (Outcome) state; } else { LOG.warn("Message send updated with unsupported state: {}", state); outcome = null; } AsyncResult request = (AsyncResult) delivery.getContext(); Exception deliveryError = null; if (outcome instanceof Accepted) { LOG.trace("Outcome of delivery was accepted: {}", delivery); if (request != null && !request.isComplete()) { request.onSuccess(); } } else if (outcome instanceof Rejected) { LOG.trace("Outcome of delivery was rejected: {}", delivery); ErrorCondition remoteError = ((Rejected) outcome).getError(); if (remoteError == null) { remoteError = getEndpoint().getRemoteCondition(); } deliveryError = AmqpSupport.convertToException(remoteError); } else if (outcome instanceof Released) { LOG.trace("Outcome of delivery was released: {}", delivery); deliveryError = new IOException("Delivery failed: released by receiver"); } else if (outcome instanceof Modified) { LOG.trace("Outcome of delivery was modified: {}", delivery); deliveryError = new IOException("Delivery failed: failure at remote"); } if (deliveryError != null) { if (request != null && !request.isComplete()) { request.onFailure(deliveryError); } else { connection.fireClientException(deliveryError); } } tagGenerator.returnTag(delivery.getTag()); delivery.settle(); toRemove.add(delivery); } pending.removeAll(toRemove); } @Override public String toString() { return getClass().getSimpleName() + "{ address = " + address + "}"; } }
// Copyright (c) 2015 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.xwalk.core; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import java.io.File; import java.util.List; import org.xwalk.core.XWalkLibraryLoader.DownloadListener; /** * <p><code>XWalkUpdater</code> is a follow-up solution for {@link XWalkInitializer} in case the * initialization failed. The users of {@link XWalkActivity} don't need to use this class.</p> * * <p><code>XWalkUpdater</code> helps to download Crosswalk Project runtime and displays dialogs * to interact with the user. By default, it will navigate to the page of Crosswalk Project on the * application store of the device, subsequent process will be up to the user. Otherwise, if the * developer specified the download URL, it will launch the download manager to fetch the APK. * </p> * * <p>After proper Crosswalk Project runtime is downloaded and installed, the user will return to * current activity from the application store or the installer. The developer should check this * point and invoke {@link XWalkInitializer#initAsync()} again to repeat the initialization process. * Please note that from now on, the application will be running in shared mode.</p> * * <p>Besides shared mode, there is another way to update Crosswalk Project runtime that all of * download process are executed in background silently without interrupting the user.</p> * * <p>In download mode, we support two kinds of APKs of Crosswalk Project runtime, one is the * original XWalkRuntimeLib.apk, another one is XWalkRuntimeLibLzma.apk which contains compressed * libraries and resources. It has smaller size but will take a little more time at the first * launch.</p> * * <h3>Edit Activity</h3> * * <p>Here is the sample code for embedded mode and shared mode:</p> * * <pre> * import android.app.Activity; * import android.os.Bundle; * * import org.xwalk.core.XWalkInitializer; * import org.xwalk.core.XWalkUpdater; * import org.xwalk.core.XWalkView; * * public class MainActivity extends Activity implements * XWalkInitializer.XWalkInitListener, * XWalkUpdater.XWalkUpdateListener { * * private XWalkView mXWalkView; * private XWalkInitializer mXWalkInitializer; * private XWalkUpdater mXWalkUpdater; * * &#64;Override * protected void onCreate(Bundle savedInstanceState) { * super.onCreate(savedInstanceState); * * // Must call initAsync() before anything that involves the embedding * // API, including invoking setContentView() with the layout which * // holds the XWalkView object. * * mXWalkInitializer = new XWalkInitializer(this, this); * mXWalkInitializer.initAsync(); * * // Until onXWalkInitCompleted() is invoked, you should do nothing with the * // embedding API except the following: * // 1. Instantiate the XWalkView object * // 2. Call XWalkPreferences.setValue() * // 3. Call mXWalkView.setXXClient(), e.g., setUIClient * // 4. Call mXWalkView.setXXListener(), e.g., setDownloadListener * // 5. Call mXWalkView.addJavascriptInterface() * * setContentView(R.layout.activity_main); * mXWalkView = (XWalkView) findViewById(R.id.xwalkview); * } * * &#64;Override * protected void onResume() { * super.onResume(); * * // Try to initialize again when the user completed updating and * // returned to current activity. The initAsync() will do nothing if * // the initialization is proceeding or has already been completed. * * mXWalkInitializer.initAsync(); * } * * &#64;Override * public void onXWalkInitStarted() { * } * * &#64;Override * public void onXWalkInitCancelled() { * // Perform error handling here * * finish(); * } * * &#64;Override * public void onXWalkInitFailed() { * if (mXWalkUpdater == null) { * mXWalkUpdater = new XWalkUpdater(this, this); * } * mXWalkUpdater.updateXWalkRuntime(); * } * * &#64;Override * public void onXWalkInitCompleted() { * // Do anyting with the embedding API * * mXWalkView.load("https://crosswalk-project.org/", null); * } * * &#64;Override * public void onXWalkUpdateCancelled() { * // Perform error handling here * * finish(); * } * } * </pre> * * <p>For download mode, the code is almost the same except you should use * {@link XWalkBackgroundUpdateListener} instead of {@link XWalkUpdateListener}. </p> * * <pre> * public class MyActivity extends Activity implements * XWalkInitializer.XWalkInitListener, * XWalkUpdater.XWalkBackgroundUpdateListener { * * ...... * * &#64;Override * public void onXWalkUpdateStarted() { * } * * &#64;Override * public void onXWalkUpdateProgress(int percentage) { * // Update the progress to UI or do nothing * } * * &#64;Override * public void onXWalkUpdateCancelled() { * // Perform error handling here * * finish(); * } * * &#64;Override * public void onXWalkUpdateFailed() { * // Perform error handling here * * finish(); * } * * &#64;Override * public void onXWalkUpdateCompleted() { * // Start to initialize again once update finished * * mXWalkInitializer.initAsync(); * } * } * </pre> * * <h3>Edit App Manifest</h3> * * <p>For shared mode and download mode, you might need to edit the Android manifest to set some * properties. </p> * * <h4>Shared Mode</h4> * * <p>If you want the end-user to download Crosswalk Project runtime from specified URL instead of * switching to the application store, add following &lt;meta-data&gt; element inside the * &lt;application&gt; element:</p> * * <pre> * &lt;application&gt; * &lt;meta-data android:name="xwalk_apk_url" android:value="http://host/XWalkRuntimeLib.apk" /&gt; * </pre> * * <p>Please note that when the HTTP request is sent to server, the URL will be appended with * "?arch=CPU_API" to indicate that on which CPU architecture it's currently running. The CPU_API * is the same as the value returned from "adb shell getprop ro.product.cpu_abi", e.g. x86 for * IA 32bit, x86_64 for IA 64bit, armeabi-v7a for ARM 32bit and arm64-v8a for ARM 64bit. * * <p>The specified APK will be downloaded to SD card, so you have to grant following permission: </p> * * <pre> * &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; * </pre> * * <h4>Download Mode</h4> * * <p>Firstly, you need to add following &lt;meta-data&gt; element to enable download mode:</p> * * <pre> * &lt;application&gt; * &lt;meta-data android:name="xwalk_download_mode" android:value="enable"/&gt; * </pre> * * <p>In download mode, the value of <code>xwalk_apk_url</code> is mandatory. However, the * downloaded Apk will be saved into application's private storage, so the permission of writing to * SD card is not needed anymore.</p> * * <p>By default, the application will verify the signature of downloaded Crosswalk Project runtime, * which is required to be the same as your application. But you can disable it by adding following * &lt;meta-data&gt; element: * * <pre> * &lt;application&gt; * &lt;meta-data android:name="xwalk_verify" android:value="disable"/&gt; * </pre> * * <p> If your application has already downloaded Crosswalk Project runtime but the application got * an update after that, the build version of shared library you used to bundle with your * new application may be newer than the build version of downloaded Crosswalk Project runtime. * In this case, it will download new version of Crosswalk Project runtime from the server again. * If you want to continue using old version of Crosswalk Project runtime, you could add following * &lt;meta-data&gt; element: * * <pre> * &lt;application&gt; * &lt;meta-data android:name="xwalk_download_mode_update" android:value="disable"/&gt; * </pre> * */ public class XWalkUpdater { /** * Interface used to update the Crosswalk runtime */ public interface XWalkUpdateListener { /** * Run on the UI thread to notify the update is cancelled. It could be the user refused to * update or the download (from the specified URL) is cancelled */ public void onXWalkUpdateCancelled(); } /** * Interface used to update the Crosswalk runtime silently */ public interface XWalkBackgroundUpdateListener { /** * Run on the UI thread to notify the update is started. */ public void onXWalkUpdateStarted(); /** * Run on the UI thread to notify the update progress. * @param percentage Shows the update progress in percentage. */ public void onXWalkUpdateProgress(int percentage); /** * Run on the UI thread to notify the update is cancelled. */ public void onXWalkUpdateCancelled(); /** * Run on the UI thread to notify the update failed. */ public void onXWalkUpdateFailed(); /** * Run on the UI thread to notify the update is completed. */ public void onXWalkUpdateCompleted(); } private static final String ANDROID_MARKET_DETAILS = "market://details?id="; private static final String GOOGLE_PLAY_PACKAGE = "com.android.vending"; private static final String TAG = "XWalkLib"; private XWalkUpdateListener mUpdateListener; private XWalkBackgroundUpdateListener mBackgroundUpdateListener; private Context mContext; private XWalkDialogManager mDialogManager; private Runnable mDownloadCommand; private Runnable mCancelCommand; /** * Create XWalkUpdater * * @param listener The {@link XWalkUpdateListener} to use * @param context The context which initiate the update */ public XWalkUpdater(XWalkUpdateListener listener, Context context) { mUpdateListener = listener; mContext = context; mDialogManager = new XWalkDialogManager(context); } /** * Create XWalkUpdater * * @param listener The {@link XWalkUpdateListener} to use * @param context The context which initiate the update * @param dialogManager The {@link XWalkDialogManager} to use */ public XWalkUpdater(XWalkUpdateListener listener, Context context, XWalkDialogManager dialogManager) { mUpdateListener = listener; mContext = context; mDialogManager = dialogManager; } /** * Create XWalkUpdater. This updater will download silently. * * @param listener The {@link XWalkBackgroundUpdateListener} to use * @param context The context which initiate the update */ public XWalkUpdater(XWalkBackgroundUpdateListener listener, Context context) { mBackgroundUpdateListener = listener; mContext = context; } /** * Update the Crosswalk runtime. There are 2 ways to download the Crosswalk runtime: from the * play store or the specified URL. It will download from the play store if the download URL is * not specified. To specify the download URL, insert a meta-data element with the name * "xwalk_apk_url" inside the application tag in the Android manifest. * * <p>Please try to initialize by {@link XWalkInitializer} first and only invoke this method * when the initialization failed. This method must be invoked on the UI thread. * * @return true if the updater is launched, false if current or another updater is already * in updating, or the Crosswalk runtime doesn't need to be updated */ public boolean updateXWalkRuntime() { if (XWalkLibraryLoader.isInitializing() || XWalkLibraryLoader.isDownloading()) { Log.d(TAG, "Other initialization or download is proceeding"); return false; } if (XWalkLibraryLoader.isLibraryReady()) { Log.d(TAG, "Initialization has been completed. Do not need to update"); return false; } int status = XWalkLibraryLoader.getLibraryStatus(); if (status == XWalkLibraryInterface.STATUS_PENDING) { throw new RuntimeException("Must invoke XWalkInitializer.initAsync() first"); } if (mUpdateListener != null) { mDownloadCommand = new Runnable() { @Override public void run() { downloadXWalkApk(); } }; mCancelCommand = new Runnable() { @Override public void run() { Log.d(TAG, "XWalkUpdater cancelled"); mUpdateListener.onXWalkUpdateCancelled(); } }; mDialogManager.showInitializationError(status, mCancelCommand, mDownloadCommand); } else if (mBackgroundUpdateListener != null) { String url = XWalkEnvironment.getXWalkApkUrl(); XWalkLibraryLoader.startHttpDownload(new BackgroundListener(), mContext, url); } else { throw new IllegalArgumentException("Update listener is null"); } return true; } /** * Dismiss the dialog showing and waiting for user's input. * * @return Return false if no dialog is being displayed, true if dismissed the showing dialog. */ public boolean dismissDialog() { if (mDialogManager == null || !mDialogManager.isShowingDialog()) { return false; } mDialogManager.dismissDialog(); return true; } /** * Set the download URL of the Crosswalk runtime. By default, the updater will get the URL from * the Android manifest. * * @param url The download URL. */ public void setXWalkApkUrl(String url) { XWalkEnvironment.setXWalkApkUrl(url); } /** * Cancel the background download * * @return false if it is not a background updater or is not downloading, true otherwise. */ public boolean cancelBackgroundDownload() { return XWalkLibraryLoader.cancelHttpDownload(); } private void downloadXWalkApk() { String url = XWalkEnvironment.getXWalkApkUrl(); if (!url.isEmpty()) { XWalkLibraryLoader.startDownloadManager(new ForegroundListener(), mContext, url); return; } String packageName = XWalkLibraryInterface.XWALK_CORE_PACKAGE; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(ANDROID_MARKET_DETAILS + packageName)); List<ResolveInfo> infos = mContext.getPackageManager().queryIntentActivities( intent, PackageManager.MATCH_ALL); StringBuilder supportedStores = new StringBuilder(); boolean hasGooglePlay = false; Log.d(TAG, "Available Stores:"); for (ResolveInfo info : infos) { Log.d(TAG, info.activityInfo.packageName); hasGooglePlay |= info.activityInfo.packageName.equals(GOOGLE_PLAY_PACKAGE); String storeName = getStoreName(info.activityInfo.packageName); if (storeName != null) { if (supportedStores.length() > 0) { supportedStores.append("/"); } supportedStores.append(storeName); } } if (supportedStores.length() == 0) { mDialogManager.showUnsupportedStore(mCancelCommand); return; } if (hasGooglePlay || !XWalkEnvironment.isIaDevice()) { if (XWalkEnvironment.is64bitApp()) { packageName = XWalkLibraryInterface.XWALK_CORE64_PACKAGE; } else { packageName = XWalkLibraryInterface.XWALK_CORE_PACKAGE; } } else { if (XWalkEnvironment.is64bitApp()) { packageName = XWalkLibraryInterface.XWALK_CORE64_IA_PACKAGE; } else { packageName = XWalkLibraryInterface.XWALK_CORE_IA_PACKAGE; } } Log.d(TAG, "Package name of Crosswalk to download: " + packageName); intent.setData(Uri.parse(ANDROID_MARKET_DETAILS + packageName)); final Intent storeIntent = intent; String storeName = hasGooglePlay ? getStoreName(GOOGLE_PLAY_PACKAGE) : supportedStores.toString(); Log.d(TAG, "Supported Stores: " + storeName); mDialogManager.showSelectStore(new Runnable() { @Override public void run() { try { mContext.startActivity(storeIntent); } catch (ActivityNotFoundException e) { mDialogManager.showUnsupportedStore(mCancelCommand); } } }, storeName); } private class ForegroundListener implements DownloadListener { @Override public void onDownloadStarted() { mDialogManager.showDownloadProgress(new Runnable() { @Override public void run() { XWalkLibraryLoader.cancelDownloadManager(); } }); } @Override public void onDownloadUpdated(int percentage) { mDialogManager.setProgress(percentage, 100); } @Override public void onDownloadCancelled() { mUpdateListener.onXWalkUpdateCancelled(); } @Override public void onDownloadFailed(int status, int error) { mDialogManager.dismissDialog(); mDialogManager.showDownloadError(mCancelCommand, mDownloadCommand); } @Override public void onDownloadCompleted(Uri uri) { mDialogManager.dismissDialog(); Log.d(TAG, "Install the Crosswalk runtime: " + uri.toString()); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(uri, "application/vnd.android.package-archive"); mContext.startActivity(intent); } } private class BackgroundListener implements DownloadListener { @Override public void onDownloadStarted() { mBackgroundUpdateListener.onXWalkUpdateStarted(); } @Override public void onDownloadUpdated(int percentage) { mBackgroundUpdateListener.onXWalkUpdateProgress(percentage); } @Override public void onDownloadCancelled() { mBackgroundUpdateListener.onXWalkUpdateCancelled(); } @Override public void onDownloadFailed(int status, int error) { mBackgroundUpdateListener.onXWalkUpdateFailed(); } @Override public void onDownloadCompleted(Uri uri) { final String libFile = uri.getPath(); final String destDir = XWalkEnvironment.getExtractedCoreDir(); Log.d(TAG, "Download mode extract dir: " + destDir); new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { if (XWalkEnvironment.isXWalkVerify()) { if (!verifyDownloadedXWalkRuntime(libFile)) { return false; } } if (XWalkDecompressor.isResourceCompressed(libFile)) { if (!XWalkDecompressor.decompressResource(libFile, destDir)) { return false; } } else { if (!XWalkDecompressor.extractResource(libFile, destDir)) { return false; } } return true; } @Override protected void onPostExecute(Boolean result) { new File(libFile).delete(); if (!result) { mBackgroundUpdateListener.onXWalkUpdateFailed(); } else { mBackgroundUpdateListener.onXWalkUpdateCompleted(); } } }.execute(); } } private boolean verifyDownloadedXWalkRuntime(String libFile) { // getPackageArchiveInfo also check the integrity of the downloaded runtime APK // besides returning the PackageInfo with signatures. PackageInfo runtimePkgInfo = mContext.getPackageManager().getPackageArchiveInfo( libFile, PackageManager.GET_SIGNATURES); if (runtimePkgInfo == null) { Log.e(TAG, "The downloaded XWalkRuntimeLib.apk is invalid!"); return false; } PackageInfo appPkgInfo = null; try { appPkgInfo = mContext.getPackageManager().getPackageInfo( mContext.getPackageName(), PackageManager.GET_SIGNATURES); } catch (NameNotFoundException e) { return false; } if (runtimePkgInfo.signatures == null || appPkgInfo.signatures == null) { Log.e(TAG, "No signature in package info"); return false; } if (runtimePkgInfo.signatures.length != appPkgInfo.signatures.length) { Log.e(TAG, "signatures length not equal"); return false; } for (int i = 0; i < runtimePkgInfo.signatures.length; ++i) { Log.d(TAG, "Checking signature " + i); if (!appPkgInfo.signatures[i].equals(runtimePkgInfo.signatures[i])) { Log.e(TAG, "signatures do not match"); return false; } } Log.d(TAG, "Signature check passed"); return true; } private String getStoreName(String storePackage) { if (storePackage.equals(GOOGLE_PLAY_PACKAGE)) { return mContext.getString(R.string.google_play_store); } return null; } }
/* * Copyright (C) 2014 The Android Open Source Project * * 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 android.media; import android.annotation.NonNull; import android.content.ContentResolver; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.browse.MediaBrowser; import android.media.session.MediaController; import android.net.Uri; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.ArrayMap; import android.util.Log; import android.util.SparseArray; import java.util.Set; /** * Contains metadata about an item, such as the title, artist, etc. */ public final class MediaMetadata implements Parcelable { private static final String TAG = "MediaMetadata"; /** * The title of the media. */ public static final String METADATA_KEY_TITLE = "android.media.metadata.TITLE"; /** * The artist of the media. */ public static final String METADATA_KEY_ARTIST = "android.media.metadata.ARTIST"; /** * The duration of the media in ms. A negative duration indicates that the * duration is unknown (or infinite). */ public static final String METADATA_KEY_DURATION = "android.media.metadata.DURATION"; /** * The album title for the media. */ public static final String METADATA_KEY_ALBUM = "android.media.metadata.ALBUM"; /** * The author of the media. */ public static final String METADATA_KEY_AUTHOR = "android.media.metadata.AUTHOR"; /** * The writer of the media. */ public static final String METADATA_KEY_WRITER = "android.media.metadata.WRITER"; /** * The composer of the media. */ public static final String METADATA_KEY_COMPOSER = "android.media.metadata.COMPOSER"; /** * The compilation status of the media. */ public static final String METADATA_KEY_COMPILATION = "android.media.metadata.COMPILATION"; /** * The date the media was created or published. The format is unspecified * but RFC 3339 is recommended. */ public static final String METADATA_KEY_DATE = "android.media.metadata.DATE"; /** * The year the media was created or published as a long. */ public static final String METADATA_KEY_YEAR = "android.media.metadata.YEAR"; /** * The genre of the media. */ public static final String METADATA_KEY_GENRE = "android.media.metadata.GENRE"; /** * The track number for the media. */ public static final String METADATA_KEY_TRACK_NUMBER = "android.media.metadata.TRACK_NUMBER"; /** * The number of tracks in the media's original source. */ public static final String METADATA_KEY_NUM_TRACKS = "android.media.metadata.NUM_TRACKS"; /** * The disc number for the media's original source. */ public static final String METADATA_KEY_DISC_NUMBER = "android.media.metadata.DISC_NUMBER"; /** * The artist for the album of the media's original source. */ public static final String METADATA_KEY_ALBUM_ARTIST = "android.media.metadata.ALBUM_ARTIST"; /** * The artwork for the media as a {@link Bitmap}. * <p> * The artwork should be relatively small and may be scaled down by the * system if it is too large. For higher resolution artwork * {@link #METADATA_KEY_ART_URI} should be used instead. */ public static final String METADATA_KEY_ART = "android.media.metadata.ART"; /** * The artwork for the media as a Uri formatted String. The artwork can be * loaded using a combination of {@link ContentResolver#openInputStream} and * {@link BitmapFactory#decodeStream}. * <p> * For the best results, Uris should use the content:// style and support * {@link ContentResolver#EXTRA_SIZE} for retrieving scaled artwork through * {@link ContentResolver#openTypedAssetFileDescriptor(Uri, String, Bundle)}. */ public static final String METADATA_KEY_ART_URI = "android.media.metadata.ART_URI"; /** * The artwork for the album of the media's original source as a * {@link Bitmap}. * <p> * The artwork should be relatively small and may be scaled down by the * system if it is too large. For higher resolution artwork * {@link #METADATA_KEY_ALBUM_ART_URI} should be used instead. */ public static final String METADATA_KEY_ALBUM_ART = "android.media.metadata.ALBUM_ART"; /** * The artwork for the album of the media's original source as a Uri * formatted String. The artwork can be loaded using a combination of * {@link ContentResolver#openInputStream} and * {@link BitmapFactory#decodeStream}. * <p> * For the best results, Uris should use the content:// style and support * {@link ContentResolver#EXTRA_SIZE} for retrieving scaled artwork through * {@link ContentResolver#openTypedAssetFileDescriptor(Uri, String, Bundle)}. */ public static final String METADATA_KEY_ALBUM_ART_URI = "android.media.metadata.ALBUM_ART_URI"; /** * The user's rating for the media. * * @see Rating */ public static final String METADATA_KEY_USER_RATING = "android.media.metadata.USER_RATING"; /** * The overall rating for the media. * * @see Rating */ public static final String METADATA_KEY_RATING = "android.media.metadata.RATING"; /** * A title that is suitable for display to the user. This will generally be * the same as {@link #METADATA_KEY_TITLE} but may differ for some formats. * When displaying media described by this metadata this should be preferred * if present. */ public static final String METADATA_KEY_DISPLAY_TITLE = "android.media.metadata.DISPLAY_TITLE"; /** * A subtitle that is suitable for display to the user. When displaying a * second line for media described by this metadata this should be preferred * to other fields if present. */ public static final String METADATA_KEY_DISPLAY_SUBTITLE = "android.media.metadata.DISPLAY_SUBTITLE"; /** * A description that is suitable for display to the user. When displaying * more information for media described by this metadata this should be * preferred to other fields if present. */ public static final String METADATA_KEY_DISPLAY_DESCRIPTION = "android.media.metadata.DISPLAY_DESCRIPTION"; /** * An icon or thumbnail that is suitable for display to the user. When * displaying an icon for media described by this metadata this should be * preferred to other fields if present. This must be a {@link Bitmap}. * <p> * The icon should be relatively small and may be scaled down by the system * if it is too large. For higher resolution artwork * {@link #METADATA_KEY_DISPLAY_ICON_URI} should be used instead. */ public static final String METADATA_KEY_DISPLAY_ICON = "android.media.metadata.DISPLAY_ICON"; /** * A Uri formatted String for an icon or thumbnail that is suitable for * display to the user. When displaying more information for media described * by this metadata the display description should be preferred to other * fields when present. The icon can be loaded using a combination of * {@link ContentResolver#openInputStream} and * {@link BitmapFactory#decodeStream}. * <p> * For the best results, Uris should use the content:// style and support * {@link ContentResolver#EXTRA_SIZE} for retrieving scaled artwork through * {@link ContentResolver#openTypedAssetFileDescriptor(Uri, String, Bundle)}. */ public static final String METADATA_KEY_DISPLAY_ICON_URI = "android.media.metadata.DISPLAY_ICON_URI"; /** * A String key for identifying the content. This value is specific to the * service providing the content. If used, this should be a persistent * unique key for the underlying content. It may be used with * {@link MediaController.TransportControls#playFromMediaId(String, Bundle)} * to initiate playback when provided by a {@link MediaBrowser} connected to * the same app. */ public static final String METADATA_KEY_MEDIA_ID = "android.media.metadata.MEDIA_ID"; private static final String[] PREFERRED_DESCRIPTION_ORDER = { METADATA_KEY_TITLE, METADATA_KEY_ARTIST, METADATA_KEY_ALBUM, METADATA_KEY_ALBUM_ARTIST, METADATA_KEY_WRITER, METADATA_KEY_AUTHOR, METADATA_KEY_COMPOSER }; private static final String[] PREFERRED_BITMAP_ORDER = { METADATA_KEY_DISPLAY_ICON, METADATA_KEY_ART, METADATA_KEY_ALBUM_ART }; private static final String[] PREFERRED_URI_ORDER = { METADATA_KEY_DISPLAY_ICON_URI, METADATA_KEY_ART_URI, METADATA_KEY_ALBUM_ART_URI }; private static final int METADATA_TYPE_INVALID = -1; private static final int METADATA_TYPE_LONG = 0; private static final int METADATA_TYPE_TEXT = 1; private static final int METADATA_TYPE_BITMAP = 2; private static final int METADATA_TYPE_RATING = 3; private static final ArrayMap<String, Integer> METADATA_KEYS_TYPE; static { METADATA_KEYS_TYPE = new ArrayMap<String, Integer>(); METADATA_KEYS_TYPE.put(METADATA_KEY_TITLE, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_ARTIST, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_DURATION, METADATA_TYPE_LONG); METADATA_KEYS_TYPE.put(METADATA_KEY_ALBUM, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_AUTHOR, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_WRITER, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_COMPOSER, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_COMPILATION, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_DATE, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_YEAR, METADATA_TYPE_LONG); METADATA_KEYS_TYPE.put(METADATA_KEY_GENRE, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_TRACK_NUMBER, METADATA_TYPE_LONG); METADATA_KEYS_TYPE.put(METADATA_KEY_NUM_TRACKS, METADATA_TYPE_LONG); METADATA_KEYS_TYPE.put(METADATA_KEY_DISC_NUMBER, METADATA_TYPE_LONG); METADATA_KEYS_TYPE.put(METADATA_KEY_ALBUM_ARTIST, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_ART, METADATA_TYPE_BITMAP); METADATA_KEYS_TYPE.put(METADATA_KEY_ART_URI, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_ALBUM_ART, METADATA_TYPE_BITMAP); METADATA_KEYS_TYPE.put(METADATA_KEY_ALBUM_ART_URI, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_USER_RATING, METADATA_TYPE_RATING); METADATA_KEYS_TYPE.put(METADATA_KEY_RATING, METADATA_TYPE_RATING); METADATA_KEYS_TYPE.put(METADATA_KEY_DISPLAY_TITLE, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_DISPLAY_SUBTITLE, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_DISPLAY_DESCRIPTION, METADATA_TYPE_TEXT); METADATA_KEYS_TYPE.put(METADATA_KEY_DISPLAY_ICON, METADATA_TYPE_BITMAP); METADATA_KEYS_TYPE.put(METADATA_KEY_DISPLAY_ICON_URI, METADATA_TYPE_TEXT); } private static final SparseArray<String> EDITOR_KEY_MAPPING; static { EDITOR_KEY_MAPPING = new SparseArray<String>(); EDITOR_KEY_MAPPING.put(MediaMetadataEditor.BITMAP_KEY_ARTWORK, METADATA_KEY_ART); EDITOR_KEY_MAPPING.put(MediaMetadataEditor.RATING_KEY_BY_OTHERS, METADATA_KEY_RATING); EDITOR_KEY_MAPPING.put(MediaMetadataEditor.RATING_KEY_BY_USER, METADATA_KEY_USER_RATING); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_ALBUM, METADATA_KEY_ALBUM); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST, METADATA_KEY_ALBUM_ARTIST); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_ARTIST, METADATA_KEY_ARTIST); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_AUTHOR, METADATA_KEY_AUTHOR); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER, METADATA_KEY_TRACK_NUMBER); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_COMPOSER, METADATA_KEY_COMPOSER); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_COMPILATION, METADATA_KEY_COMPILATION); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_DATE, METADATA_KEY_DATE); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER, METADATA_KEY_DISC_NUMBER); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_DURATION, METADATA_KEY_DURATION); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_GENRE, METADATA_KEY_GENRE); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS, METADATA_KEY_NUM_TRACKS); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_TITLE, METADATA_KEY_TITLE); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_WRITER, METADATA_KEY_WRITER); EDITOR_KEY_MAPPING.put(MediaMetadataRetriever.METADATA_KEY_YEAR, METADATA_KEY_YEAR); } private final Bundle mBundle; private MediaDescription mDescription; private MediaMetadata(Bundle bundle) { mBundle = new Bundle(bundle); } private MediaMetadata(Parcel in) { mBundle = in.readBundle(); } /** * Returns true if the given key is contained in the metadata * * @param key a String key * @return true if the key exists in this metadata, false otherwise */ public boolean containsKey(String key) { return mBundle.containsKey(key); } /** * Returns the value associated with the given key, or null if no mapping of * the desired type exists for the given key or a null value is explicitly * associated with the key. * * @param key The key the value is stored under * @return a CharSequence value, or null */ public CharSequence getText(String key) { return mBundle.getCharSequence(key); } /** * Returns the text value associated with the given key as a String, or null * if no mapping of the desired type exists for the given key or a null * value is explicitly associated with the key. This is equivalent to * calling {@link #getText getText().toString()} if the value is not null. * * @param key The key the value is stored under * @return a String value, or null */ public String getString(String key) { CharSequence text = getText(key); if (text != null) { return text.toString(); } return null; } /** * Returns the value associated with the given key, or 0L if no long exists * for the given key. * * @param key The key the value is stored under * @return a long value */ public long getLong(String key) { return mBundle.getLong(key, 0); } /** * Returns a {@link Rating} for the given key or null if no rating exists * for the given key. * * @param key The key the value is stored under * @return A {@link Rating} or null */ public Rating getRating(String key) { Rating rating = null; try { rating = mBundle.getParcelable(key); } catch (Exception e) { // ignore, value was not a bitmap Log.w(TAG, "Failed to retrieve a key as Rating.", e); } return rating; } /** * Returns a {@link Bitmap} for the given key or null if no bitmap exists * for the given key. * * @param key The key the value is stored under * @return A {@link Bitmap} or null */ public Bitmap getBitmap(String key) { Bitmap bmp = null; try { bmp = mBundle.getParcelable(key); } catch (Exception e) { // ignore, value was not a bitmap Log.w(TAG, "Failed to retrieve a key as Bitmap.", e); } return bmp; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeBundle(mBundle); } /** * Returns the number of fields in this metadata. * * @return The number of fields in the metadata. */ public int size() { return mBundle.size(); } /** * Returns a Set containing the Strings used as keys in this metadata. * * @return a Set of String keys */ public Set<String> keySet() { return mBundle.keySet(); } /** * Returns a simple description of this metadata for display purposes. * * @return A simple description of this metadata. */ public @NonNull MediaDescription getDescription() { if (mDescription != null) { return mDescription; } String mediaId = getString(METADATA_KEY_MEDIA_ID); CharSequence[] text = new CharSequence[3]; Bitmap icon = null; Uri iconUri = null; // First handle the case where display data is set already CharSequence displayText = getText(METADATA_KEY_DISPLAY_TITLE); if (!TextUtils.isEmpty(displayText)) { // If they have a display title use only display data, otherwise use // our best bets text[0] = displayText; text[1] = getText(METADATA_KEY_DISPLAY_SUBTITLE); text[2] = getText(METADATA_KEY_DISPLAY_DESCRIPTION); } else { // Use whatever fields we can int textIndex = 0; int keyIndex = 0; while (textIndex < text.length && keyIndex < PREFERRED_DESCRIPTION_ORDER.length) { CharSequence next = getText(PREFERRED_DESCRIPTION_ORDER[keyIndex++]); if (!TextUtils.isEmpty(next)) { // Fill in the next empty bit of text text[textIndex++] = next; } } } // Get the best art bitmap we can find for (int i = 0; i < PREFERRED_BITMAP_ORDER.length; i++) { Bitmap next = getBitmap(PREFERRED_BITMAP_ORDER[i]); if (next != null) { icon = next; break; } } // Get the best Uri we can find for (int i = 0; i < PREFERRED_URI_ORDER.length; i++) { String next = getString(PREFERRED_URI_ORDER[i]); if (!TextUtils.isEmpty(next)) { iconUri = Uri.parse(next); break; } } MediaDescription.Builder bob = new MediaDescription.Builder(); bob.setMediaId(mediaId); bob.setTitle(text[0]); bob.setSubtitle(text[1]); bob.setDescription(text[2]); bob.setIconBitmap(icon); bob.setIconUri(iconUri); mDescription = bob.build(); return mDescription; } /** * Helper for getting the String key used by {@link MediaMetadata} from the * integer key that {@link MediaMetadataEditor} uses. * * @param editorKey The key used by the editor * @return The key used by this class or null if no mapping exists * @hide */ public static String getKeyFromMetadataEditorKey(int editorKey) { return EDITOR_KEY_MAPPING.get(editorKey, null); } public static final Parcelable.Creator<MediaMetadata> CREATOR = new Parcelable.Creator<MediaMetadata>() { @Override public MediaMetadata createFromParcel(Parcel in) { return new MediaMetadata(in); } @Override public MediaMetadata[] newArray(int size) { return new MediaMetadata[size]; } }; /** * Use to build MediaMetadata objects. The system defined metadata keys must * use the appropriate data type. */ public static final class Builder { private final Bundle mBundle; /** * Create an empty Builder. Any field that should be included in the * {@link MediaMetadata} must be added. */ public Builder() { mBundle = new Bundle(); } /** * Create a Builder using a {@link MediaMetadata} instance to set the * initial values. All fields in the source metadata will be included in * the new metadata. Fields can be overwritten by adding the same key. * * @param source */ public Builder(MediaMetadata source) { mBundle = new Bundle(source.mBundle); } /** * Create a Builder using a {@link MediaMetadata} instance to set * initial values, but replace bitmaps with a scaled down copy if they * are larger than maxBitmapSize. * * @param source The original metadata to copy. * @param maxBitmapSize The maximum height/width for bitmaps contained * in the metadata. * @hide */ public Builder(MediaMetadata source, int maxBitmapSize) { this(source); for (String key : mBundle.keySet()) { Object value = mBundle.get(key); if (value != null && value instanceof Bitmap) { Bitmap bmp = (Bitmap) value; if (bmp.getHeight() > maxBitmapSize || bmp.getWidth() > maxBitmapSize) { putBitmap(key, scaleBitmap(bmp, maxBitmapSize)); } } } } /** * Put a CharSequence value into the metadata. Custom keys may be used, * but if the METADATA_KEYs defined in this class are used they may only * be one of the following: * <ul> * <li>{@link #METADATA_KEY_TITLE}</li> * <li>{@link #METADATA_KEY_ARTIST}</li> * <li>{@link #METADATA_KEY_ALBUM}</li> * <li>{@link #METADATA_KEY_AUTHOR}</li> * <li>{@link #METADATA_KEY_WRITER}</li> * <li>{@link #METADATA_KEY_COMPOSER}</li> * <li>{@link #METADATA_KEY_DATE}</li> * <li>{@link #METADATA_KEY_GENRE}</li> * <li>{@link #METADATA_KEY_ALBUM_ARTIST}</li> * <li>{@link #METADATA_KEY_ART_URI}</li> * <li>{@link #METADATA_KEY_ALBUM_ART_URI}</li> * <li>{@link #METADATA_KEY_DISPLAY_TITLE}</li> * <li>{@link #METADATA_KEY_DISPLAY_SUBTITLE}</li> * <li>{@link #METADATA_KEY_DISPLAY_DESCRIPTION}</li> * <li>{@link #METADATA_KEY_DISPLAY_ICON_URI}</li> * </ul> * * @param key The key for referencing this value * @param value The CharSequence value to store * @return The Builder to allow chaining */ public Builder putText(String key, CharSequence value) { if (METADATA_KEYS_TYPE.containsKey(key)) { if (METADATA_KEYS_TYPE.get(key) != METADATA_TYPE_TEXT) { throw new IllegalArgumentException("The " + key + " key cannot be used to put a CharSequence"); } } mBundle.putCharSequence(key, value); return this; } /** * Put a String value into the metadata. Custom keys may be used, but if * the METADATA_KEYs defined in this class are used they may only be one * of the following: * <ul> * <li>{@link #METADATA_KEY_TITLE}</li> * <li>{@link #METADATA_KEY_ARTIST}</li> * <li>{@link #METADATA_KEY_ALBUM}</li> * <li>{@link #METADATA_KEY_AUTHOR}</li> * <li>{@link #METADATA_KEY_WRITER}</li> * <li>{@link #METADATA_KEY_COMPOSER}</li> * <li>{@link #METADATA_KEY_DATE}</li> * <li>{@link #METADATA_KEY_GENRE}</li> * <li>{@link #METADATA_KEY_ALBUM_ARTIST}</li> * <li>{@link #METADATA_KEY_ART_URI}</li> * <li>{@link #METADATA_KEY_ALBUM_ART_URI}</li> * <li>{@link #METADATA_KEY_DISPLAY_TITLE}</li> * <li>{@link #METADATA_KEY_DISPLAY_SUBTITLE}</li> * <li>{@link #METADATA_KEY_DISPLAY_DESCRIPTION}</li> * <li>{@link #METADATA_KEY_DISPLAY_ICON_URI}</li> * </ul> * <p> * Uris for artwork should use the content:// style and support * {@link ContentResolver#EXTRA_SIZE} for retrieving scaled artwork * through {@link ContentResolver#openTypedAssetFileDescriptor(Uri, * String, Bundle)}. * * @param key The key for referencing this value * @param value The String value to store * @return The Builder to allow chaining */ public Builder putString(String key, String value) { if (METADATA_KEYS_TYPE.containsKey(key)) { if (METADATA_KEYS_TYPE.get(key) != METADATA_TYPE_TEXT) { throw new IllegalArgumentException("The " + key + " key cannot be used to put a String"); } } mBundle.putCharSequence(key, value); return this; } /** * Put a long value into the metadata. Custom keys may be used, but if * the METADATA_KEYs defined in this class are used they may only be one * of the following: * <ul> * <li>{@link #METADATA_KEY_DURATION}</li> * <li>{@link #METADATA_KEY_TRACK_NUMBER}</li> * <li>{@link #METADATA_KEY_NUM_TRACKS}</li> * <li>{@link #METADATA_KEY_DISC_NUMBER}</li> * <li>{@link #METADATA_KEY_YEAR}</li> * </ul> * * @param key The key for referencing this value * @param value The long value to store * @return The Builder to allow chaining */ public Builder putLong(String key, long value) { if (METADATA_KEYS_TYPE.containsKey(key)) { if (METADATA_KEYS_TYPE.get(key) != METADATA_TYPE_LONG) { throw new IllegalArgumentException("The " + key + " key cannot be used to put a long"); } } mBundle.putLong(key, value); return this; } /** * Put a {@link Rating} into the metadata. Custom keys may be used, but * if the METADATA_KEYs defined in this class are used they may only be * one of the following: * <ul> * <li>{@link #METADATA_KEY_RATING}</li> * <li>{@link #METADATA_KEY_USER_RATING}</li> * </ul> * * @param key The key for referencing this value * @param value The Rating value to store * @return The Builder to allow chaining */ public Builder putRating(String key, Rating value) { if (METADATA_KEYS_TYPE.containsKey(key)) { if (METADATA_KEYS_TYPE.get(key) != METADATA_TYPE_RATING) { throw new IllegalArgumentException("The " + key + " key cannot be used to put a Rating"); } } mBundle.putParcelable(key, value); return this; } /** * Put a {@link Bitmap} into the metadata. Custom keys may be used, but * if the METADATA_KEYs defined in this class are used they may only be * one of the following: * <ul> * <li>{@link #METADATA_KEY_ART}</li> * <li>{@link #METADATA_KEY_ALBUM_ART}</li> * <li>{@link #METADATA_KEY_DISPLAY_ICON}</li> * </ul> * <p> * Large bitmaps may be scaled down by the system. To pass full * resolution images {@link Uri Uris} should be used with * {@link #putString}. * * @param key The key for referencing this value * @param value The Bitmap to store * @return The Builder to allow chaining */ public Builder putBitmap(String key, Bitmap value) { if (METADATA_KEYS_TYPE.containsKey(key)) { if (METADATA_KEYS_TYPE.get(key) != METADATA_TYPE_BITMAP) { throw new IllegalArgumentException("The " + key + " key cannot be used to put a Bitmap"); } } mBundle.putParcelable(key, value); return this; } /** * Creates a {@link MediaMetadata} instance with the specified fields. * * @return The new MediaMetadata instance */ public MediaMetadata build() { return new MediaMetadata(mBundle); } private Bitmap scaleBitmap(Bitmap bmp, int maxSize) { float maxSizeF = maxSize; float widthScale = maxSizeF / bmp.getWidth(); float heightScale = maxSizeF / bmp.getHeight(); float scale = Math.min(widthScale, heightScale); int height = (int) (bmp.getHeight() * scale); int width = (int) (bmp.getWidth() * scale); return Bitmap.createScaledBitmap(bmp, width, height, true); } } }
package com.fasterxml.jackson.databind.introspect; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.AnnotationIntrospector.ReferenceProperty; import com.fasterxml.jackson.databind.PropertyName; public class POJOPropertyBuilder extends BeanPropertyDefinition implements Comparable<POJOPropertyBuilder> { protected final AnnotationIntrospector _annotationIntrospector; protected Linked<AnnotatedParameter> _ctorParameters; protected Linked<AnnotatedField> _fields; protected final boolean _forSerialization; protected Linked<AnnotatedMethod> _getters; protected final String _internalName; protected final String _name; protected Linked<AnnotatedMethod> _setters; public POJOPropertyBuilder(POJOPropertyBuilder paramPOJOPropertyBuilder, String paramString) { this._internalName = paramPOJOPropertyBuilder._internalName; this._name = paramString; this._annotationIntrospector = paramPOJOPropertyBuilder._annotationIntrospector; this._fields = paramPOJOPropertyBuilder._fields; this._ctorParameters = paramPOJOPropertyBuilder._ctorParameters; this._getters = paramPOJOPropertyBuilder._getters; this._setters = paramPOJOPropertyBuilder._setters; this._forSerialization = paramPOJOPropertyBuilder._forSerialization; } public POJOPropertyBuilder(String paramString, AnnotationIntrospector paramAnnotationIntrospector, boolean paramBoolean) { this._internalName = paramString; this._name = paramString; this._annotationIntrospector = paramAnnotationIntrospector; this._forSerialization = paramBoolean; } private <T> boolean _anyExplicitNames(Linked<T> paramLinked) { while (paramLinked != null) { if ((paramLinked.explicitName != null) && (paramLinked.explicitName.length() > 0)) return true; paramLinked = paramLinked.next; } return false; } private <T> boolean _anyIgnorals(Linked<T> paramLinked) { while (paramLinked != null) { if (paramLinked.isMarkedIgnored) return true; paramLinked = paramLinked.next; } return false; } private <T> boolean _anyVisible(Linked<T> paramLinked) { while (paramLinked != null) { if (paramLinked.isVisible) return true; paramLinked = paramLinked.next; } return false; } private AnnotationMap _mergeAnnotations(int paramInt, Linked<? extends AnnotatedMember>[] paramArrayOfLinked) { AnnotationMap localAnnotationMap = ((AnnotatedMember)paramArrayOfLinked[paramInt].value).getAllAnnotations(); for (int i = paramInt + 1; i < paramArrayOfLinked.length; i++) if (paramArrayOfLinked[i] != null) return AnnotationMap.merge(localAnnotationMap, _mergeAnnotations(i, paramArrayOfLinked)); return localAnnotationMap; } private <T> Linked<T> _removeIgnored(Linked<T> paramLinked) { if (paramLinked == null) return paramLinked; return paramLinked.withoutIgnored(); } private <T> Linked<T> _removeNonVisible(Linked<T> paramLinked) { if (paramLinked == null) return paramLinked; return paramLinked.withoutNonVisible(); } private <T> Linked<T> _trimByVisibility(Linked<T> paramLinked) { if (paramLinked == null) return paramLinked; return paramLinked.trimByVisibility(); } private Linked<? extends AnnotatedMember> findRenamed(Linked<? extends AnnotatedMember> paramLinked1, Linked<? extends AnnotatedMember> paramLinked2) { while (paramLinked1 != null) { String str = paramLinked1.explicitName; if ((str != null) && (!str.equals(this._name))) if (paramLinked2 == null) paramLinked2 = paramLinked1; else if (!str.equals(paramLinked2.explicitName)) throw new IllegalStateException("Conflicting property name definitions: '" + paramLinked2.explicitName + "' (for " + paramLinked2.value + ") vs '" + paramLinked1.explicitName + "' (for " + paramLinked1.value + ")"); paramLinked1 = paramLinked1.next; } return paramLinked2; } private static <T> Linked<T> merge(Linked<T> paramLinked1, Linked<T> paramLinked2) { if (paramLinked1 == null) return paramLinked2; if (paramLinked2 == null) return paramLinked1; return paramLinked1.append(paramLinked2); } public void addAll(POJOPropertyBuilder paramPOJOPropertyBuilder) { this._fields = merge(this._fields, paramPOJOPropertyBuilder._fields); this._ctorParameters = merge(this._ctorParameters, paramPOJOPropertyBuilder._ctorParameters); this._getters = merge(this._getters, paramPOJOPropertyBuilder._getters); this._setters = merge(this._setters, paramPOJOPropertyBuilder._setters); } public void addCtor(AnnotatedParameter paramAnnotatedParameter, String paramString, boolean paramBoolean1, boolean paramBoolean2) { this._ctorParameters = new Linked(paramAnnotatedParameter, this._ctorParameters, paramString, paramBoolean1, paramBoolean2); } public void addField(AnnotatedField paramAnnotatedField, String paramString, boolean paramBoolean1, boolean paramBoolean2) { this._fields = new Linked(paramAnnotatedField, this._fields, paramString, paramBoolean1, paramBoolean2); } public void addGetter(AnnotatedMethod paramAnnotatedMethod, String paramString, boolean paramBoolean1, boolean paramBoolean2) { this._getters = new Linked(paramAnnotatedMethod, this._getters, paramString, paramBoolean1, paramBoolean2); } public void addSetter(AnnotatedMethod paramAnnotatedMethod, String paramString, boolean paramBoolean1, boolean paramBoolean2) { this._setters = new Linked(paramAnnotatedMethod, this._setters, paramString, paramBoolean1, paramBoolean2); } public boolean anyIgnorals() { return (_anyIgnorals(this._fields)) || (_anyIgnorals(this._getters)) || (_anyIgnorals(this._setters)) || (_anyIgnorals(this._ctorParameters)); } public boolean anyVisible() { return (_anyVisible(this._fields)) || (_anyVisible(this._getters)) || (_anyVisible(this._setters)) || (_anyVisible(this._ctorParameters)); } public int compareTo(POJOPropertyBuilder paramPOJOPropertyBuilder) { if (this._ctorParameters != null) { if (paramPOJOPropertyBuilder._ctorParameters == null) return -1; } else if (paramPOJOPropertyBuilder._ctorParameters != null) return 1; return getName().compareTo(paramPOJOPropertyBuilder.getName()); } public boolean couldSerialize() { return (this._getters != null) || (this._fields != null); } public String findNewName() { Linked localLinked1 = findRenamed(this._fields, null); Linked localLinked2 = findRenamed(this._getters, localLinked1); Linked localLinked3 = findRenamed(this._setters, localLinked2); Linked localLinked4 = findRenamed(this._ctorParameters, localLinked3); if (localLinked4 == null) return null; return localLinked4.explicitName; } public ObjectIdInfo findObjectIdInfo() { return (ObjectIdInfo)fromMemberAnnotations(new WithMember() { public ObjectIdInfo withMember(AnnotatedMember paramAnonymousAnnotatedMember) { ObjectIdInfo localObjectIdInfo1 = POJOPropertyBuilder.this._annotationIntrospector.findObjectIdInfo(paramAnonymousAnnotatedMember); ObjectIdInfo localObjectIdInfo2 = localObjectIdInfo1; if (localObjectIdInfo1 != null) localObjectIdInfo2 = POJOPropertyBuilder.this._annotationIntrospector.findObjectReferenceInfo(paramAnonymousAnnotatedMember, localObjectIdInfo2); return localObjectIdInfo2; } }); } public AnnotationIntrospector.ReferenceProperty findReferenceType() { return (AnnotationIntrospector.ReferenceProperty)fromMemberAnnotations(new WithMember() { public AnnotationIntrospector.ReferenceProperty withMember(AnnotatedMember paramAnonymousAnnotatedMember) { return POJOPropertyBuilder.this._annotationIntrospector.findReferenceType(paramAnonymousAnnotatedMember); } }); } public Class<?>[] findViews() { return (Class[])fromMemberAnnotations(new WithMember() { public Class<?>[] withMember(AnnotatedMember paramAnonymousAnnotatedMember) { return POJOPropertyBuilder.this._annotationIntrospector.findViews(paramAnonymousAnnotatedMember); } }); } protected <T> T fromMemberAnnotations(WithMember<T> paramWithMember) { AnnotationIntrospector localAnnotationIntrospector = this._annotationIntrospector; Object localObject = null; if (localAnnotationIntrospector != null) { if (this._forSerialization) { Linked localLinked2 = this._getters; localObject = null; if (localLinked2 != null) localObject = paramWithMember.withMember((AnnotatedMember)this._getters.value); } else { Linked localLinked1 = this._ctorParameters; localObject = null; if (localLinked1 != null) localObject = paramWithMember.withMember((AnnotatedMember)this._ctorParameters.value); if ((localObject == null) && (this._setters != null)) localObject = paramWithMember.withMember((AnnotatedMember)this._setters.value); } if ((localObject == null) && (this._fields != null)) localObject = paramWithMember.withMember((AnnotatedMember)this._fields.value); } return localObject; } public AnnotatedMember getAccessor() { AnnotatedMethod localAnnotatedMethod = getGetter(); Object localObject = localAnnotatedMethod; if (localAnnotatedMethod == null) localObject = getField(); return localObject; } public AnnotatedParameter getConstructorParameter() { if (this._ctorParameters == null) return null; Object localObject = this._ctorParameters; Linked localLinked; do { if ((((AnnotatedParameter)((Linked)localObject).value).getOwner() instanceof AnnotatedConstructor)) return (AnnotatedParameter)((Linked)localObject).value; localLinked = ((Linked)localObject).next; localObject = localLinked; } while (localLinked != null); return (AnnotatedParameter)this._ctorParameters.value; } public AnnotatedField getField() { if (this._fields == null) return null; Object localObject = (AnnotatedField)this._fields.value; for (Linked localLinked = this._fields.next; localLinked != null; localLinked = localLinked.next) { AnnotatedField localAnnotatedField = (AnnotatedField)localLinked.value; Class localClass1 = ((AnnotatedField)localObject).getDeclaringClass(); Class localClass2 = localAnnotatedField.getDeclaringClass(); if (localClass1 != localClass2) { if (localClass1.isAssignableFrom(localClass2)) localObject = localAnnotatedField; else if (localClass2.isAssignableFrom(localClass1)); } else throw new IllegalArgumentException("Multiple fields representing property \"" + getName() + "\": " + ((AnnotatedField)localObject).getFullName() + " vs " + localAnnotatedField.getFullName()); } return localObject; } public AnnotatedMethod getGetter() { if (this._getters == null) return null; Object localObject = (AnnotatedMethod)this._getters.value; for (Linked localLinked = this._getters.next; localLinked != null; localLinked = localLinked.next) { AnnotatedMethod localAnnotatedMethod = (AnnotatedMethod)localLinked.value; Class localClass1 = ((AnnotatedMethod)localObject).getDeclaringClass(); Class localClass2 = localAnnotatedMethod.getDeclaringClass(); if (localClass1 != localClass2) { if (localClass1.isAssignableFrom(localClass2)) localObject = localAnnotatedMethod; else if (localClass2.isAssignableFrom(localClass1)); } else throw new IllegalArgumentException("Conflicting getter definitions for property \"" + getName() + "\": " + ((AnnotatedMethod)localObject).getFullName() + " vs " + localAnnotatedMethod.getFullName()); } return localObject; } public String getInternalName() { return this._internalName; } public AnnotatedMember getMutator() { AnnotatedParameter localAnnotatedParameter = getConstructorParameter(); Object localObject = localAnnotatedParameter; if (localAnnotatedParameter == null) { AnnotatedMethod localAnnotatedMethod = getSetter(); localObject = localAnnotatedMethod; if (localAnnotatedMethod == null) localObject = getField(); } return localObject; } public String getName() { return this._name; } public AnnotatedMember getPrimaryMember() { if (this._forSerialization) return getAccessor(); return getMutator(); } public AnnotatedMethod getSetter() { if (this._setters == null) return null; Object localObject = (AnnotatedMethod)this._setters.value; for (Linked localLinked = this._setters.next; localLinked != null; localLinked = localLinked.next) { AnnotatedMethod localAnnotatedMethod = (AnnotatedMethod)localLinked.value; Class localClass1 = ((AnnotatedMethod)localObject).getDeclaringClass(); Class localClass2 = localAnnotatedMethod.getDeclaringClass(); if (localClass1 != localClass2) { if (localClass1.isAssignableFrom(localClass2)) localObject = localAnnotatedMethod; else if (localClass2.isAssignableFrom(localClass1)); } else throw new IllegalArgumentException("Conflicting setter definitions for property \"" + getName() + "\": " + ((AnnotatedMethod)localObject).getFullName() + " vs " + localAnnotatedMethod.getFullName()); } return localObject; } public PropertyName getWrapperName() { AnnotatedMember localAnnotatedMember = getPrimaryMember(); if ((localAnnotatedMember == null) || (this._annotationIntrospector == null)) return null; return this._annotationIntrospector.findWrapperName(localAnnotatedMember); } public boolean hasConstructorParameter() { return this._ctorParameters != null; } public boolean hasField() { return this._fields != null; } public boolean hasGetter() { return this._getters != null; } public boolean hasSetter() { return this._setters != null; } public boolean isExplicitlyIncluded() { return (_anyExplicitNames(this._fields)) || (_anyExplicitNames(this._getters)) || (_anyExplicitNames(this._setters)) || (_anyExplicitNames(this._ctorParameters)); } public boolean isRequired() { Boolean localBoolean = (Boolean)fromMemberAnnotations(new WithMember() { public Boolean withMember(AnnotatedMember paramAnonymousAnnotatedMember) { return POJOPropertyBuilder.this._annotationIntrospector.hasRequiredMarker(paramAnonymousAnnotatedMember); } }); return (localBoolean != null) && (localBoolean.booleanValue()); } public boolean isTypeId() { Boolean localBoolean = (Boolean)fromMemberAnnotations(new WithMember() { public Boolean withMember(AnnotatedMember paramAnonymousAnnotatedMember) { return POJOPropertyBuilder.this._annotationIntrospector.isTypeId(paramAnonymousAnnotatedMember); } }); return (localBoolean != null) && (localBoolean.booleanValue()); } public void mergeAnnotations(boolean paramBoolean) { if (paramBoolean) { if (this._getters != null) { Linked[] arrayOfLinked5 = new Linked[4]; arrayOfLinked5[0] = this._getters; arrayOfLinked5[1] = this._fields; arrayOfLinked5[2] = this._ctorParameters; arrayOfLinked5[3] = this._setters; AnnotationMap localAnnotationMap5 = _mergeAnnotations(0, arrayOfLinked5); this._getters = this._getters.withValue(((AnnotatedMethod)this._getters.value).withAnnotations(localAnnotationMap5)); return; } if (this._fields != null) { Linked[] arrayOfLinked4 = new Linked[3]; arrayOfLinked4[0] = this._fields; arrayOfLinked4[1] = this._ctorParameters; arrayOfLinked4[2] = this._setters; AnnotationMap localAnnotationMap4 = _mergeAnnotations(0, arrayOfLinked4); this._fields = this._fields.withValue(((AnnotatedField)this._fields.value).withAnnotations(localAnnotationMap4)); } } else { if (this._ctorParameters != null) { Linked[] arrayOfLinked3 = new Linked[4]; arrayOfLinked3[0] = this._ctorParameters; arrayOfLinked3[1] = this._setters; arrayOfLinked3[2] = this._fields; arrayOfLinked3[3] = this._getters; AnnotationMap localAnnotationMap3 = _mergeAnnotations(0, arrayOfLinked3); this._ctorParameters = this._ctorParameters.withValue(((AnnotatedParameter)this._ctorParameters.value).withAnnotations(localAnnotationMap3)); return; } if (this._setters != null) { Linked[] arrayOfLinked2 = new Linked[3]; arrayOfLinked2[0] = this._setters; arrayOfLinked2[1] = this._fields; arrayOfLinked2[2] = this._getters; AnnotationMap localAnnotationMap2 = _mergeAnnotations(0, arrayOfLinked2); this._setters = this._setters.withValue(((AnnotatedMethod)this._setters.value).withAnnotations(localAnnotationMap2)); return; } if (this._fields != null) { Linked[] arrayOfLinked1 = new Linked[2]; arrayOfLinked1[0] = this._fields; arrayOfLinked1[1] = this._getters; AnnotationMap localAnnotationMap1 = _mergeAnnotations(0, arrayOfLinked1); this._fields = this._fields.withValue(((AnnotatedField)this._fields.value).withAnnotations(localAnnotationMap1)); } } } public void removeIgnored() { this._fields = _removeIgnored(this._fields); this._getters = _removeIgnored(this._getters); this._setters = _removeIgnored(this._setters); this._ctorParameters = _removeIgnored(this._ctorParameters); } @Deprecated public void removeNonVisible() { removeNonVisible(false); } public void removeNonVisible(boolean paramBoolean) { this._getters = _removeNonVisible(this._getters); this._ctorParameters = _removeNonVisible(this._ctorParameters); if ((paramBoolean) || (this._getters == null)) { this._fields = _removeNonVisible(this._fields); this._setters = _removeNonVisible(this._setters); } } public String toString() { StringBuilder localStringBuilder = new StringBuilder(); localStringBuilder.append("[Property '").append(this._name).append("'; ctors: ").append(this._ctorParameters).append(", field(s): ").append(this._fields).append(", getter(s): ").append(this._getters).append(", setter(s): ").append(this._setters); localStringBuilder.append("]"); return localStringBuilder.toString(); } public void trimByVisibility() { this._fields = _trimByVisibility(this._fields); this._getters = _trimByVisibility(this._getters); this._setters = _trimByVisibility(this._setters); this._ctorParameters = _trimByVisibility(this._ctorParameters); } public POJOPropertyBuilder withName(String paramString) { return new POJOPropertyBuilder(this, paramString); } static final class Linked<T> { public final String explicitName; public final boolean isMarkedIgnored; public final boolean isVisible; public final Linked<T> next; public final T value; public Linked(T paramT, Linked<T> paramLinked, String paramString, boolean paramBoolean1, boolean paramBoolean2) { this.value = paramT; this.next = paramLinked; Linked localLinked; String str; if (paramString == null) { localLinked = this; str = null; } else { localLinked = this; if (paramString.length() == 0) str = null; else str = paramString; } localLinked.explicitName = str; this.isVisible = paramBoolean1; this.isMarkedIgnored = paramBoolean2; } private Linked<T> append(Linked<T> paramLinked) { if (this.next == null) return withNext(paramLinked); return withNext(this.next.append(paramLinked)); } public final String toString() { String str = this.value.toString() + "[visible=" + this.isVisible + "]"; if (this.next != null) str = str + ", " + this.next.toString(); return str; } public final Linked<T> trimByVisibility() { if (this.next == null) return this; Linked localLinked = this.next.trimByVisibility(); if (this.explicitName != null) { if (localLinked.explicitName == null) return withNext(null); return withNext(localLinked); } if (localLinked.explicitName != null) return localLinked; if (this.isVisible == localLinked.isVisible) return withNext(localLinked); if (this.isVisible) return withNext(null); return localLinked; } public final Linked<T> withNext(Linked<T> paramLinked) { if (paramLinked == this.next) return this; return new Linked(this.value, paramLinked, this.explicitName, this.isVisible, this.isMarkedIgnored); } public final Linked<T> withValue(T paramT) { if (paramT == this.value) return this; return new Linked(paramT, this.next, this.explicitName, this.isVisible, this.isMarkedIgnored); } public final Linked<T> withoutIgnored() { while (this.isMarkedIgnored) { if (this.next == null) return null; this = this.next; } if (this.next != null) { Linked localLinked = this.next.withoutIgnored(); if (localLinked != this.next) return withNext(localLinked); } return this; } public final Linked<T> withoutNonVisible() { Linked localLinked; if (this.next == null) localLinked = null; else localLinked = this.next.withoutNonVisible(); if (this.isVisible) return withNext(localLinked); return localLinked; } } static abstract interface WithMember<T> { public abstract T withMember(AnnotatedMember paramAnnotatedMember); } } /* Location: /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar * Qualified Name: com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder * JD-Core Version: 0.6.2 */
package edu.umass.cs.pig.test; import static org.junit.Assert.assertTrue; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import java.util.Properties; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import org.apache.pig.ExecType; import org.apache.pig.PigServer; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.DataBag; import org.apache.pig.impl.PigContext; import org.apache.pig.newplan.Operator; import org.junit.BeforeClass; import org.junit.Test; import edu.umass.cs.pig.test.util.RFile; import edu.umass.cs.pig.test.util.StreamGobbler; public class TestExGen4PigMixReal3 { static PigContext pigContext = new PigContext(ExecType.LOCAL, new Properties()); static int MAX = 100; static int MIN = 10; static String widerow, widerowX, page_viewsX, power_usersX, usersX, data12X, users_sortedX, power_users_sampleX, widegroupbydataX; // static File fileWiderowX; // page_views, , power_users static String pScalability; // pPage_Views, , pPower_Users public static Logger logger = Logger.getLogger("MyLog"); public static FileHandler fh; { try { pigContext.connect(); } catch (ExecException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @BeforeClass public static void oneTimeSetup() throws Exception { try { RFile.deleteIfExists("MyLogFile.log"); fh = new FileHandler("MyLogFile.log", true); logger.addHandler(fh); logger.setLevel(Level.FINE); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); fh.setLevel(Level.FINE); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } widerow = "'" + "/home/kaituo/code/pig3/trunk/pigmixdata/widerow" + "'"; // page_views = "'" + "/home/kaituo/code/pig3/trunk/pigmixdata/page_views" + "'"; // power_users = "'" + "/home/kaituo/code/pig3/trunk/pigmixdata/power_users100m" + "'"; // fileWiderowX = File.createTempFile("dataWiderowX", ".dat"); pScalability = "/home/kaituo/code/pig3/trunk/scripts/pScalability.pig"; // pPage_Views = "/home/kaituo/code/pig3/trunk/scripts/pPage_Views.pig"; // pPower_Users = "/home/kaituo/code/pig3/trunk/scripts/pPower_Users.pig"; RFile.createRFile(pScalability); // RFile.createRFile(pPage_Views); // RFile.createRFile(pPower_Users); // widerowX = "'" + fileWiderowX.getPath() + "'"; widerowX = "/home/kaituo/code/pig3/trunk/pigmixExtData/scalabilityData"; page_viewsX = "/home/kaituo/code/pig3/trunk/pigmixExtData/pages625m"; power_usersX = "/home/kaituo/code/pig3/trunk/pigmixExtData/power_users100m"; usersX = "/home/kaituo/code/pig3/trunk/pigmixExtData/users100m"; data12X = "/home/kaituo/code/pig3/trunk/pigmixExtData/data12"; users_sortedX = "/home/kaituo/code/pig3/trunk/pigmixExtData/data14"; power_users_sampleX = "/home/kaituo/code/pig3/trunk/pigmixExtData/power_users_sample"; widegroupbydataX = "/home/kaituo/code/pig3/trunk/pigmixExtData/widegroupbydata"; RFile.deleteIfExists(widerowX); // RFile.deleteIfExists(page_viewsX); // RFile.deleteIfExists(power_usersX); writeScalabilityData(widerow, widerowX, pScalability); // writePage_ViewsData(page_views, page_viewsX, pPage_Views); System.out.println("widerowX : " + widerowX + "\n" + "page_viewsX : " + page_viewsX + "\n" + "power_usersX : " + power_usersX + "\n" + "usersX: " + usersX + "\n" + "data12X: " + data12X + "\n" + "users_sortedX: " + users_sortedX + "\n"); System.out.println("Test data created."); } private static void writeScalabilityData(String dataOrig, String dataOut, String PIG_FILE) { int n = 501; String abody = ""; for (int i = 0; i < n; i++) { if (i > 0) abody = abody + ", "; abody = abody + "c" + i + ": int"; } // String cbody = ""; // for (int j = 0; j < n; j++) { // if (j > 0) // cbody = cbody + ", "; // cbody = cbody + "SUM(A.c" + j + ") as c" + j; // } // // String dbody = ""; // for (int k = 0; k < n; k++) { // if (k > 0) // dbody = dbody + " and "; // dbody = dbody + "c" + k + " > 100"; // } try { PrintWriter w = new PrintWriter(new FileWriter(PIG_FILE)); w.println("A = load " + dataOrig.toString() + " using PigStorage('\u0001') as (name: chararray, " + abody + ");"); w.println("B = foreach A generate name, c0, c1;"); w.println("C = limit B " + MIN + ";"); w.println("store C into '" + dataOut + "';"); w.close(); Process pp = Runtime.getRuntime().exec("java -Xmx256m -cp /home/kaituo/Downloads/pig-0.9.2/pig-0.9.2.jar org.apache.pig.Main -x local " + PIG_FILE.toString()); logErrororOutput(pp); } catch(IOException io) { io.printStackTrace(); } } // private static void writePage_ViewsData(String dataOrig, String dataOut, String PIG_FILE) { // try { // PrintWriter w = new PrintWriter(new FileWriter(PIG_FILE)); // w.println("register pigperf.jar;"); // w.println("A = load " + dataOrig.toString() // + " using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user, action, timespent, query_term, ip_addr, timestamp, estimated_revenue, page_info, page_links);"); // //as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long, estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])} );"); // w.println("B = limit A " + MIN + ";"); // w.println("store B into '" + dataOut + "' using PigStorage('\u0001');"); // w.close(); // // Process pp = Runtime.getRuntime().exec("java -Xmx256m -cp /home/kaituo/Downloads/pig-0.9.2/pig-0.9.2.jar:/home/kaituo/code/pig3/trunk/pigperf.jar org.apache.pig.Main -x local " + PIG_FILE.toString()); // logErrororOutput(pp); // } catch(IOException io) { // io.printStackTrace(); // } // // } // private static void writePower_UsersData(String dataOrig, String dataOut, String PIG_FILE) { // try { // PrintWriter w = new PrintWriter(new FileWriter(PIG_FILE)); // w.println("register pigperf.jar;"); // w.println("A = load " + dataOrig.toString() // + " using PigStorage('\u0001') as (user, action, timespent, query_term, ip_addr, timestamp, estimated_revenue, page_info, page_links);"); // //as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long, estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])} );"); // w.println("B = limit A " + MIN + ";"); // w.println("store B into '" + dataOut + "' using PigStorage('\u0001');"); // w.close(); // // Process pp = Runtime.getRuntime().exec("java -Xmx256m -cp /home/kaituo/Downloads/pig-0.9.2/pig-0.9.2.jar:/home/kaituo/code/pig3/trunk/pigperf.jar org.apache.pig.Main -x local " + PIG_FILE.toString()); // logErrororOutput(pp); // } catch(IOException io) { // io.printStackTrace(); // } // } private static void logErrororOutput(Process proc) { // any error message? StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "OUTPUT", logger); // any output? StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", logger); // kick them off errorGobbler.start(); outputGobbler.start(); // any error??? int exitVal; try { exitVal = proc.waitFor(); logger.log(Level.FINE, "ExitValue: " + exitVal); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testScalability() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer.registerQuery("A = load '" + widerowX.toString() + "/part-r-00000' using PigStorage() as (name: chararray, x : int, y : int);"); pigServer.registerQuery("B = group A by name;"); pigServer.registerQuery("C = foreach B generate group, SUM(A.x) as xx, SUM(A.y) as yy;"); pigServer.registerQuery("D = filter C by xx > 100 and yy > 100;"); //pigServer.registerQuery("store D into '" + out.getAbsolutePath() + "';"); Map<Operator, DataBag> derivedData = pigServer.getExamples("D"); assertTrue(derivedData != null); } @Test public void testScriptL1() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); //pigServer.registerJar("/home/kaituo/code/pig3/trunk/pigperf.jar"); pigServer.registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); //as (user, action, timespent, query_term, ip_addr, timestamp, estimated_revenue, page_info, page_links);"); pigServer.registerQuery("B = foreach A generate user, action, page_info, flatten(page_links) as page_links;"); //user, (int)action as action, (map[])page_info as page_info, flatten((bag{tuple(map[])})page_links) as page_links;"); pigServer.registerQuery("C = foreach B generate user, (action == 1 ? page_info#'a' : page_links#'b') as header;"); pigServer.registerQuery("D = group C by user parallel 40;"); pigServer.registerQuery("E = foreach D generate group, COUNT(C) as cnt;"); Map<Operator, DataBag> derivedData = pigServer.getExamples("E"); assertTrue(derivedData != null); } @Test public void testScriptL2() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer.registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer.registerQuery("B = foreach A generate user, estimated_revenue;"); pigServer.registerQuery("alpha = load '" + power_usersX.toString() + "' using PigStorage('\u0001') as (name: chararray, phone: chararray, address: chararray, city: chararray, state: chararray, zip: int);"); pigServer.registerQuery("beta = foreach alpha generate name;"); pigServer.registerQuery("C = join B by user, beta by name using 'replicated' parallel 40;"); Map<Operator, DataBag> derivedData = pigServer.getExamples("C"); assertTrue(derivedData != null); } @Test public void testScript3() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer.registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer.registerQuery("B = foreach A generate user, estimated_revenue;"); pigServer.registerQuery("alpha = load '" + usersX.toString() + "'using PigStorage('\u0001') as (name: chararray, phone: chararray, address: chararray, city: chararray, state: chararray, zip: int);"); pigServer.registerQuery("beta = foreach alpha generate name;"); pigServer.registerQuery("C = join beta by name, B by user parallel 40;"); pigServer.registerQuery("D = group C by $0 parallel 40;"); pigServer.registerQuery("E = foreach D generate group, SUM(C.estimated_revenue);"); Map<Operator, DataBag> derivedData = pigServer.getExamples("E"); assertTrue(derivedData != null); } @Test public void testScript4() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer.registerQuery("B = foreach A generate user, action;"); pigServer.registerQuery("C = group B by user parallel 40;"); pigServer .registerQuery("D = foreach C { aleph = B.action; beth = distinct aleph; generate group, COUNT(beth);}"); Map<Operator, DataBag> derivedData = pigServer.getExamples("D"); assertTrue(derivedData != null); } @Test public void testScript5() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer.registerQuery("B = foreach A generate user;"); pigServer .registerQuery("alpha = load '" + usersX.toString() + "'using PigStorage('\u0001') as (name: chararray, phone: chararray, address: chararray, city: chararray, state: chararray, zip: int);"); pigServer.registerQuery("beta = foreach alpha generate name;"); pigServer .registerQuery("C = cogroup beta by name, B by user parallel 40;"); pigServer.registerQuery("D = filter C by COUNT(beta) == 0;"); pigServer.registerQuery("E = foreach D generate group;"); Map<Operator, DataBag> derivedData = pigServer.getExamples("E"); assertTrue(derivedData != null); } @Test public void testScript6() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer .registerQuery("B = foreach A generate user, action, timespent, query_term, ip_addr, timestamp;"); pigServer .registerQuery("C = group B by (user, query_term, ip_addr, timestamp) parallel 40;"); pigServer .registerQuery("D = foreach C generate flatten(group), SUM(B.timespent);"); Map<Operator, DataBag> derivedData = pigServer.getExamples("D"); assertTrue(derivedData != null); } @Test public void testScript7() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer.registerQuery("B = foreach A generate user, timestamp;"); pigServer.registerQuery("C = group B by user parallel 40;"); pigServer.registerQuery("D = foreach C { morning = filter B by timestamp < 43200; afternoon = filter B by timestamp >= 43200; generate group, COUNT(morning), COUNT(afternoon);}"); Map<Operator, DataBag> derivedData = pigServer.getExamples("D"); assertTrue(derivedData != null); } @Test public void testScript8() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer .registerQuery("B = foreach A generate user, timespent, estimated_revenue;"); pigServer.registerQuery("C = group B all;"); pigServer .registerQuery("D = foreach C generate SUM(B.timespent), AVG(B.estimated_revenue);"); Map<Operator, DataBag> derivedData = pigServer.getExamples("D"); assertTrue(derivedData != null); } @Test public void testScript9() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer.registerQuery("B = order A by query_term parallel 40;"); Map<Operator, DataBag> derivedData = pigServer.getExamples("B"); assertTrue(derivedData != null); } @Test public void testScript10() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer .registerQuery("B = order A by query_term, estimated_revenue desc, timespent parallel 40;"); Map<Operator, DataBag> derivedData = pigServer.getExamples("B"); assertTrue(derivedData != null); } @Test public void testScript11() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer.registerQuery("B = foreach A generate user;"); pigServer.registerQuery("C = distinct B parallel 40;"); pigServer.registerQuery("alpha = load '" + widerowX.toString() + "/part-r-00000' using PigStorage() as (name: chararray, x : int, y : int);"); pigServer.registerQuery("beta = foreach alpha generate name;"); pigServer.registerQuery("gamma = distinct beta parallel 40;"); pigServer.registerQuery("D = union C, gamma;"); pigServer.registerQuery("E = distinct D parallel 40;"); Map<Operator, DataBag> derivedData = pigServer.getExamples("E"); assertTrue(derivedData != null); } @Test public void testScriptL12() throws Exception { PigServer pigserver = new PigServer(pigContext); pigserver.setBatchOn(); // String query = "S = load '" // + page_viewsX.toString() // + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"; // pigserver.registerQuery(query); // query = "A = foreach S generate user, action, timespent, query_term, estimated_revenue;"; String query = "A = load '" + data12X + "/part-m-00000' using PigStorage() as (user : chararray, action : chararray, timespent : int, query_term : chararray, estimated_revenue : double);"; pigserver.registerQuery(query); query = "split A into B if user is not null, alpha if user is null;"; pigserver.registerQuery(query); query = "split B into C if query_term is not null, aleph if query_term is null;"; pigserver.registerQuery(query); query = "D = group C by user;"; pigserver.registerQuery(query); query = "E = foreach D generate group, MAX(C.estimated_revenue);"; pigserver.registerQuery(query); query = "beta = group alpha by query_term;"; pigserver.registerQuery(query); query = "gamma = foreach beta generate group, SUM(alpha.timespent);"; pigserver.registerQuery(query); query = "beth = group aleph by action;"; pigserver.registerQuery(query); query = "gimel = foreach beth generate group, COUNT(aleph);"; pigserver.registerQuery(query); Map<Operator, DataBag> derivedData = pigserver.getExamples("E"); Map<Operator, DataBag> derivedData2 = pigserver.getExamples("gamma"); Map<Operator, DataBag> derivedData3 = pigserver.getExamples("gimel"); assertTrue(derivedData != null); assertTrue(derivedData2 != null); assertTrue(derivedData3 != null); } @Test public void testScriptL13() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer.registerQuery("B = foreach A generate user, estimated_revenue;"); pigServer.registerQuery("alpha = load '" + power_users_sampleX.toString() + "' using PigStorage('\u0001') as (name: chararray, phone: chararray, address: chararray, city: chararray, state: chararray, zip: int);"); pigServer.registerQuery("beta = foreach alpha generate name, phone;"); pigServer.registerQuery("C = join B by user left outer, beta by name parallel 40;"); Map<Operator, DataBag> derivedData = pigServer.getExamples("C"); assertTrue(derivedData != null); } @Test public void testScriptL14() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer.registerQuery("B = foreach A generate user, estimated_revenue;"); pigServer.registerQuery("alpha = load '" + users_sortedX.toString() + "/part-r-00000' using PigStorage() as (name: chararray, phone: chararray, address: chararray, city: chararray, state: chararray, zip: int);"); pigServer.registerQuery("beta = foreach alpha generate name;"); pigServer.registerQuery("C = join B by user, beta by name using 'merge';"); Map<Operator, DataBag> derivedData = pigServer.getExamples("C"); assertTrue(derivedData != null); } @Test public void testScriptL15() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer.registerQuery("B = foreach A generate user, action, estimated_revenue, timespent;"); pigServer.registerQuery("C = group B by user parallel 40;"); pigServer.registerQuery("D = foreach C {beth = distinct B.action; rev = distinct B.estimated_revenue; ts = distinct B.timespent; generate group, COUNT(beth), SUM(rev), (int)AVG(ts);}"); Map<Operator, DataBag> derivedData = pigServer.getExamples("D"); assertTrue(derivedData != null); } @Test public void testScriptL16() throws Exception { PigServer pigServer = new PigServer(pigContext); pigServer.setBatchOn(); pigServer .registerQuery("A = load '" + page_viewsX.toString() + "' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user: chararray, action:int, timespent:int, query_term:chararray, ip_addr:long, timestamp:long,estimated_revenue:double, page_info:map[], page_links:bag{t:(p:map[])});"); pigServer .registerQuery("B = foreach A generate user, estimated_revenue;"); pigServer.registerQuery("C = group B by user parallel 40;"); pigServer .registerQuery("D = foreach C {E = order B by estimated_revenue; F = E.estimated_revenue; generate group, SUM(F);}"); Map<Operator, DataBag> derivedData = pigServer.getExamples("D"); assertTrue(derivedData != null); } @Test public void testScriptL17() throws Exception { PigServer pigserver = new PigServer(pigContext); String query = "A = load '" + widegroupbydataX + "/part-m-00000' using org.apache.pig.test.udf.storefunc.PigPerformanceLoader() as (user : chararray, action : int, timespent : int, query_term : chararray, ip_addr : long, timestamp : long," + "estimated_revenue : double, page_info : map[], page_links : bag{t:(p:map[])}, user_1 : chararray, action_1 : int, timespent_1 : int, query_term_1 : chararray, ip_addr_1 : long, timestamp_1 : long," + "estimated_revenue_1 : double, page_info_1 : map[], page_links_1 : bag{t:(p:map[])}, user_2 : chararray, action_2 : int, timespent_2 : int, query_term_2 : chararray, ip_addr_2 : long, timestamp_2 : long," + "estimated_revenue_2 : double, page_info_2 : map[], page_links_2 : bag{t:(p:map[])});\n"; pigserver.registerQuery(query); System.out.print(query); query = "B = group A by (user, action, timespent, query_term, ip_addr, timestamp," + "estimated_revenue, user_1, action_1, timespent_1, query_term_1, ip_addr_1, timestamp_1," + "estimated_revenue_1, user_2, action_2, timespent_2, query_term_2, ip_addr_2, timestamp_2," + "estimated_revenue_2);\n"; pigserver.registerQuery(query); System.out.print(query); query = "C = foreach B generate SUM(A.timespent), SUM(A.timespent_1), SUM(A.timespent_2), AVG(A.estimated_revenue), AVG(A.estimated_revenue_1), AVG(A.estimated_revenue_2);"; pigserver.registerQuery(query); System.out.print(query); Map<Operator, DataBag> derivedData = pigserver.getExamples("C"); assertTrue(derivedData != null); } }
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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 org.sakaiproject.tool.assessment.qti.helper.item; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.sakaiproject.tool.assessment.data.ifc.assessment.AnswerIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.AttachmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemTextIfc; import org.sakaiproject.tool.assessment.qti.asi.Item; import org.sakaiproject.tool.assessment.qti.constants.AuthoringConstantStrings; import org.sakaiproject.tool.assessment.qti.constants.QTIConstantStrings; import org.sakaiproject.tool.assessment.qti.constants.QTIVersion; import org.sakaiproject.tool.assessment.qti.helper.AuthoringXml; /** * <p>Copyright: Copyright (c) 2004</p> * <p>Organization: Sakai Project</p> * <p>Version for QTI 2.0 item XML, significant differences between 1.2 and 2.0</p> * @author Ed Smiley esmiley@stanford.edu * @version $Id$ */ public class ItemHelper20Impl extends ItemHelperBase implements ItemHelperIfc { private static Logger log = LoggerFactory.getLogger(ItemHelper20Impl.class); private AuthoringXml authoringXml; public ItemHelper20Impl() { super(); authoringXml = new AuthoringXml(getQtiVersion()); log.debug("ItemHelper20Impl"); } protected AuthoringXml getAuthoringXml() { return authoringXml; } /** * Add maximum score to item XML. * @param score * @param itemXml */ public void addMaxScore(Double score, Item itemXml) { // normalize if null if (score == null) { score = Double.valueOf(0); } // set the responseElse baseValue, if it exists String xPath = "assessmentItem/responseCondition/responseIf/" + "setOutcomeValue/baseValue"; // test if this is a type that has this baseValue List list = itemXml.selectNodes(xPath); if (list == null || list.size() == 0) { return; } updateItemXml(itemXml, xPath, score.toString()); } /** * Add minimum score to item XML * @param score * @param itemXml */ public void addMinScore(Double score, Item itemXml) { // normalize if null if (score == null) { score = Double.valueOf(0); } // first, set the outcomeDeclaration defaultValue, if it exists String xPath = "assessmentItem/responseDeclaration/outcomeDeclaration/defaultValue"; // test if this is a type that has a defaultValue List list = itemXml.selectNodes(xPath); if (list == null || list.size() == 0) { return; } updateItemXml(itemXml, xPath, score.toString()); // next, set the responseElse baseValue, if it exists xPath = "assessmentItem/responseCondition/responseElse/" + "setOutcomeValue/baseValue"; // test if this is a type that has this baseValue list = itemXml.selectNodes(xPath); if (list == null || list.size() == 0) { return; } updateItemXml(itemXml, xPath, score.toString()); } /** * Flags an answer as correct. * @param correctAnswerLabel */ public void addCorrectAnswer(String correctAnswerLabel, Item itemXml) { String xPath = "assessmentItem/responseDeclaration/correctResponse/value"; updateItemXml(itemXml, xPath, correctAnswerLabel); } /** * assessmentItem/qtiMetadata not be permissible in QTI 2.0 * this this should be used by manifest * Get the metadata field entry XPath * @return the XPath */ public String getMetaXPath() { String xpath = "assessmentItem/qtiMetadata"; return xpath; } /** * assessmentItem/qtiMetadata not be permissible in QTI 2.0 * this this should be used by manifest * Get the metadata field entry XPath for a given label * @param fieldlabel * @return the XPath */ public String getMetaLabelXPath(String fieldlabel) { String xpath = "assessmentItem/qtiMetadata/qtimetadatafield/fieldlabel[text()='" + fieldlabel + "']/following-sibling::fieldentry"; return xpath; } /** * Get the text for the item * @param itemXml * @return the text */ public String getText(Item itemXml) { String xpath = "assessmentItem/itemBody"; String itemType = itemXml.getItemType(); if (itemType.equals(AuthoringConstantStrings.MATCHING)) { xpath = "assessmentItem/itemBody/matchInteraction/simpleMatchSet/simpleAssociableChoice"; } return makeItemNodeText(itemXml, xpath); } /** * Set the (one or more) item texts. * Valid for single and multiple texts. * @todo FIB, MATCHING TEXT * @param itemXml * @param itemText text to be updated */ public void setItemTexts(List<ItemTextIfc> itemTextList, Item itemXml) { String xPath = "assessmentItem/itemBody"; if (itemTextList.size() < 1) { return; } String text = ( (ItemTextIfc) itemTextList.get(0)).getText(); log.debug("item text: " + text); if (itemXml.isFIB()) { // process fib // return; } if (itemXml.isFIN()) { // process fin // return; } try { itemXml.update(xPath, text); } catch (Exception ex) { throw new RuntimeException(ex); } } // } /** * get item type string * we use title for this for now * @param itemXml * @return type as string */ public String getItemType(Item itemXml) { String type = ""; String xpath = "assessmentItem"; List list = itemXml.selectNodes(xpath); if (list.size() > 0) { Element element = (Element) list.get(0); element.getAttribute(QTIConstantStrings.TITLE); } return type; } /** * Set the answer texts for item. * @param itemTextList the text(s) for item */ public void setAnswers(List<ItemTextIfc> itemTextList, Item itemXml) { // other types either have no answer or include them in their template if (!itemXml.isMatching() && !itemXml.isFIB() && !itemXml.isFIN() && !itemXml.isMCSC() && !itemXml.isMCMC() && !itemXml.isMCMCSS() &&!itemXml.isMXSURVEY()) { return; } // OK, so now we are in business. String xpath = "assessmentItem/itemBody/choiceInteraction/<simpleChoice"; List list = itemXml.selectNodes(xpath); log.debug("xpath size:" + list.size()); Iterator nodeIter = list.iterator(); Iterator iter = itemTextList.iterator(); Set answerSet = new HashSet(); char label = 'A'; int xpathIndex = 1; while (iter.hasNext()) { answerSet = ( (ItemTextIfc) iter.next()).getAnswerSet(); Iterator aiter = answerSet.iterator(); while (aiter.hasNext()) { AnswerIfc answer = (AnswerIfc) aiter.next(); if (Boolean.TRUE.equals(answer.getIsCorrect())) { this.addCorrectAnswer("" + label, itemXml); } String value = answer.getText(); log.debug("answer: " + answer.getText()); // process into XML // we assume that we have equal to or more than the requisite elements // if we have more than the existing elements we manufacture more // with labels 'A', 'B'....etc. Node node = null; try { boolean isInsert = true; if (nodeIter.hasNext()) { isInsert = false; } this.addIndexedEntry(itemXml, xpath, value, isInsert, xpathIndex, "" + label); } catch (Exception ex) { log.error("Cannot process source document.", ex); } label++; xpathIndex++; } } } /** * @todo NEED TO SET CORRECT, INCORRECT, GENERAL FEEDBACK * Set the feedback texts for item. * @param itemTextList the text(s) for item */ public void setFeedback(List<ItemTextIfc> itemTextList, Item itemXml) { String xpath = "assessmentItem/itemBody/choiceInteraction/<simpleChoice/feedbackInline"; // for any answers that are now in the template, create a feedback int xpathIndex = 1; List list = itemXml.selectNodes(xpath); if (list == null) { return; } Iterator nodeIter = list.iterator(); Iterator iter = itemTextList.iterator(); Set answerSet = new HashSet(); char label = 'A'; boolean first = true; while (iter.hasNext()) { ItemTextIfc itemTextIfc = (ItemTextIfc) iter.next(); if (first) // then do once { // add in Correct and InCorrect Feedback String correctFeedback = itemTextIfc.getItem().getCorrectItemFeedback(); String incorrectFeedback = itemTextIfc.getItem(). getInCorrectItemFeedback(); String generalFeedback = itemTextIfc.getItem().getGeneralItemFeedback(); log.debug("NEED TO SET CORRECT FEEDBACK: " + correctFeedback); log.debug("NEED TO SET INCORRECT FEEDBACK: " + incorrectFeedback); log.debug("NEED TO SET GENERAL FEEDBACK: " + incorrectFeedback); first = false; } // answer feedback answerSet = itemTextIfc.getAnswerSet(); Iterator aiter = answerSet.iterator(); while (aiter.hasNext()) { AnswerIfc answer = (AnswerIfc) aiter.next(); String value = answer.getGeneralAnswerFeedback(); log.debug("answer feedback: " + answer.getText()); Node node = null; try { boolean isInsert = true; if (nodeIter.hasNext()) { isInsert = false; } addIndexedEntry(itemXml, xpath, value, isInsert, xpathIndex, null); } catch (Exception ex) { log.error("Cannot process source document.", ex); } label++; xpathIndex++; } } } /** * Add/insert the index-th value. * @param itemXml the item xml * @param xpath * @param value * @param isInsert * @param index the numnber * @param identifier set this attribute if not null) */ private void addIndexedEntry(Item itemXml, String xpath, String value, boolean isInsert, int index, String identifier) { String indexBrackets = "[" + index + "]"; String thisNode = xpath + indexBrackets; String thisNodeIdentity = thisNode + "/@identity"; if (isInsert) { log.debug("Adding entry: " + thisNode); itemXml.insertElement(thisNode, xpath, "itemfeedback"); } else { log.debug("Updating entry: " + thisNode); } try { if (value == null) { value = ""; } itemXml.update(thisNode, value); log.debug("updated value in addIndexedEntry()"); } catch (Exception ex) { log.error("Cannot update value in addIndexedEntry(): " + ex); } } /** * get QTI version * @return */ protected int getQtiVersion() { return QTIVersion.VERSION_2_0; } /** * @todo implement this method for 2.0 release * @param incorrectAnswerLabel * @param itemXml */ public void addIncorrectAnswer(String incorrectAnswerLabel, Item itemXml) { } public void setItemLabel(String itemLabel, Item itemXml){ //todo } public void setItemText(String itemText, Item itemXml) { //todo } public void setItemText(String itemText, String flowClass, Item itemXml){ //todo } public void setPresentationLabel(String presentationLabel, Item itemXml){ //todo } public void setPresentationFlowResponseIdent(String presentationFlowResponseIdent, Item itemXml){ //todo } public void setAttachments(Set<? extends AttachmentIfc> attachmentSet, Item item) { // todo } }
/* * Copyright (c) 2013, Intel Corporation. * All rights reserved. * * The contents of this file are released under the BSD license, you may not use this file except in compliance with the License. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.intel.mtwilson.as.controller; import com.intel.mtwilson.as.controller.exceptions.ASDataException; import com.intel.mtwilson.as.controller.exceptions.IllegalOrphanException; import com.intel.mtwilson.as.controller.exceptions.NonexistentEntityException; import com.intel.mtwilson.as.data.TblHosts; import java.io.Serializable; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import com.intel.mtwilson.as.data.TblMle; import com.intel.mtwilson.crypto.CryptographyException; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author dsmagadX */ public class TblHostsJpaController implements Serializable { private Logger log = LoggerFactory.getLogger(getClass()); private EntityManagerFactory emf = null; public TblHostsJpaController(EntityManagerFactory emf) throws CryptographyException { this.emf = emf; } public TblHostsJpaController(EntityManagerFactory emf, boolean isTest) { this.emf = emf; } public EntityManager getEntityManager() { return emf.createEntityManager(); } public void create(TblHosts tblHosts) throws CryptographyException { log.debug("create tblHosts with policy {} and keystore length {}", tblHosts.getTlsPolicyName(), tblHosts.getTlsKeystore() == null ? "null" : tblHosts.getTlsKeystore().length); EntityManager em = getEntityManager(); try { em.getTransaction().begin(); TblMle vmmMleId = tblHosts.getVmmMleId(); if (vmmMleId != null) { vmmMleId = em.getReference(vmmMleId.getClass(), vmmMleId.getId()); tblHosts.setVmmMleId(vmmMleId); } TblMle biosMleId = tblHosts.getBiosMleId(); if (biosMleId != null) { biosMleId = em.getReference(biosMleId.getClass(), biosMleId.getId()); tblHosts.setBiosMleId(biosMleId); } // encrypt addon connection string, persist, then restore the plaintext String addOnConnectionString = tblHosts.getAddOnConnectionInfo(); if( addOnConnectionString != null ) { em.persist(tblHosts); } else { log.debug("saving without encrypting connection string"); em.persist(tblHosts); } if (vmmMleId != null) { vmmMleId.getTblHostsCollection().add(tblHosts); em.merge(vmmMleId); } if (biosMleId != null) { biosMleId.getTblHostsCollection().add(tblHosts); em.merge(biosMleId); } em.getTransaction().commit(); } finally { em.close(); } } public void edit(TblHosts tblHosts) throws IllegalOrphanException, NonexistentEntityException, ASDataException { EntityManager em = getEntityManager(); try { em.getTransaction().begin(); TblHosts persistentTblHosts = em.find(TblHosts.class, tblHosts.getId()); TblMle vmmMleIdOld = persistentTblHosts.getVmmMleId(); TblMle vmmMleIdNew = tblHosts.getVmmMleId(); TblMle biosMleIdOld = persistentTblHosts.getBiosMleId(); TblMle biosMleIdNew = tblHosts.getBiosMleId(); if (vmmMleIdNew != null) { vmmMleIdNew = em.getReference(vmmMleIdNew.getClass(), vmmMleIdNew.getId()); tblHosts.setVmmMleId(vmmMleIdNew); } if (biosMleIdNew != null) { biosMleIdNew = em.getReference(biosMleIdNew.getClass(), biosMleIdNew.getId()); tblHosts.setBiosMleId(biosMleIdNew); } // encrypt addon connection string, persist, then restore the plaintext String addOnConnectionString = tblHosts.getAddOnConnectionInfo(); if( addOnConnectionString != null ) { tblHosts = em.merge(tblHosts); } else { tblHosts = em.merge(tblHosts); } if (vmmMleIdOld != null && !vmmMleIdOld.equals(vmmMleIdNew)) { vmmMleIdOld.getTblHostsCollection().remove(tblHosts); vmmMleIdOld = em.merge(vmmMleIdOld); } if (vmmMleIdNew != null && !vmmMleIdNew.equals(vmmMleIdOld)) { vmmMleIdNew.getTblHostsCollection().add(tblHosts); em.merge(vmmMleIdNew); } if (biosMleIdOld != null && !biosMleIdOld.equals(biosMleIdNew)) { biosMleIdOld.getTblHostsCollection().remove(tblHosts); biosMleIdOld = em.merge(biosMleIdOld); } if (biosMleIdNew != null && !biosMleIdNew.equals(biosMleIdOld)) { biosMleIdNew.getTblHostsCollection().add(tblHosts); em.merge(biosMleIdNew); } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Integer id = tblHosts.getId(); if (findTblHosts(id) == null) { throw new NonexistentEntityException("The tblHosts with id " + id + " no longer exists."); } } throw new ASDataException(ex); } finally { em.close(); } } public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException { EntityManager em = getEntityManager(); try { em.getTransaction().begin(); TblHosts tblHosts; try { tblHosts = em.getReference(TblHosts.class, id); tblHosts.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The tblHosts with id " + id + " no longer exists.", enfe); } TblMle vmmMleId = tblHosts.getVmmMleId(); if (vmmMleId != null) { vmmMleId.getTblHostsCollection().remove(tblHosts); em.merge(vmmMleId); } TblMle biosMleId = tblHosts.getBiosMleId(); if (biosMleId != null) { biosMleId.getTblHostsCollection().remove(tblHosts); em.merge(biosMleId); } em.remove(tblHosts); em.getTransaction().commit(); } finally { em.close(); } } public List<TblHosts> findTblHostsEntities() { return findTblHostsEntities(true, -1, -1); } public List<TblHosts> findTblHostsEntities(int maxResults, int firstResult) { return findTblHostsEntities(false, maxResults, firstResult); } private List<TblHosts> findTblHostsEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(TblHosts.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } List<TblHosts> results = q.getResultList(); return results; } finally { em.close(); } } public TblHosts findTblHosts(Integer id) { EntityManager em = getEntityManager(); try { TblHosts result = em.find(TblHosts.class, id); return result; } finally { em.close(); } } public int getTblHostsCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<TblHosts> rt = cq.from(TblHosts.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } public TblHosts findByName(String name) { TblHosts host = null; EntityManager em = getEntityManager(); try { Query query = em.createNamedQuery("TblHosts.findByName"); query.setParameter("name", name); List<TblHosts> list = query.getResultList(); if (list != null && list.size() > 0) { host = list.get(0); } } finally { em.close(); } return host; } public TblHosts findByIPAddress(String ipAddress) { TblHosts host = null; EntityManager em = getEntityManager(); try { Query query = em.createNamedQuery("TblHosts.findByIPAddress"); query.setParameter("iPAddress", ipAddress); List<TblHosts> list = query.getResultList(); if (list != null && list.size() > 0) { host = list.get(0); } } finally { em.close(); } return host; } public List<TblHosts> findHostsByNameSearchCriteria(String searchCriteria) { List<TblHosts> hostList = null; EntityManager em = getEntityManager(); try { Query query = em.createNamedQuery("TblHosts.findByNameSearchCriteria"); query.setParameter("search", "%"+searchCriteria+"%"); if (query.getResultList() != null && !query.getResultList().isEmpty()) { hostList = query.getResultList(); } } finally { em.close(); } return hostList; } }
package com.example.glasswareXE12.main; import java.io.File; import java.io.IOException; import com.google.android.glass.app.Card; import com.google.android.glass.media.CameraManager; import com.google.android.glass.touchpad.*; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.gesture.Gesture; import android.hardware.*; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.Menu; import android.net.Uri; import android.view.WindowManager; import android.os.Bundle; import android.util.*; import android.hardware.Camera.PictureCallback; import android.content.Intent; import android.os.FileObserver; import android.provider.MediaStore; public class MainActivity extends Activity { // create variable instances private static final String TAG = MainActivity.class.getSimpleName(); private GestureDetector mGestureDetector; private Camera mCamera; private CameraPreview mPreview; PictureCallback mPicture = null; protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); //keeps the camera on getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Card card1 = new Card(this); card1.setText("Nice Picture!"); card1.setFootnote("Cool! ..."); View card1View = card1.getView(); //Calling the intent setContentView(card1View); takePicture(); // Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); // cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, false); // startActivityForResult(cameraIntent, 1); setContentView(card1View); takePicture(); } /** * Boiler plate google code */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_CAMERA) { // Stop the preview and release the camera. // Execute your logic as quickly as possible // so the capture happens quickly. return false; } else { return super.onKeyDown(keyCode, event); } } /*** boiler plate google code * https://developers.google.com/glass/develop/gdk/media-camera/camera */ @Override protected void onResume() { super.onResume(); // Re-acquire the camera and start the preview. } private static final int TAKE_PICTURE_REQUEST = 1; public void takePicture() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, TAKE_PICTURE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_OK) { String picturePath = data.getStringExtra( CameraManager.EXTRA_PICTURE_FILE_PATH); processPictureWhenReady(picturePath); } super.onActivityResult(requestCode, resultCode, data); } private void processPictureWhenReady(final String picturePath) { final File pictureFile = new File(picturePath); if (pictureFile.exists()) { // The picture is ready; process it. } else { // The file does not exist yet. Before starting the file observer, you // can update your UI to let the user know that the application is // waiting for the picture (for example, by displaying the thumbnail // image and a progress indicator). final File parentDirectory = pictureFile.getParentFile(); FileObserver observer = new FileObserver(parentDirectory.getPath()) { // Protect against additional pending events after CLOSE_WRITE is // handled. private boolean isFileWritten; @Override public void onEvent(int event, String path) { if (!isFileWritten) { // For safety, make sure that the file that was created in // the directory is actually the one that we're expecting. File affectedFile = new File(parentDirectory, path); isFileWritten = (event == FileObserver.CLOSE_WRITE && affectedFile.equals(pictureFile)); if (isFileWritten) { stopWatching(); // Now that the file is ready, recursively call // processPictureWhenReady again (on the UI thread). runOnUiThread(new Runnable() { @Override public void run() { processPictureWhenReady(picturePath); } }); } } } }; observer.startWatching(); } } /** * end of boiler plate */ private class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mHolder; private Camera mCamera; public CameraPreview(Context context, Camera camera) { super(context); mCamera = camera; Log.v(TAG,"In CameraPreview"); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); Log.v(TAG,"Got holder"); mHolder.addCallback(this); Log.v(TAG,"Added callback"); // deprecated setting, but required on Android versions prior to 3.0 //mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, now tell the camera where to draw the preview. try { Log.v(TAG,"in surface created"); mCamera.setPreviewDisplay(holder); Log.v(TAG,"set preview display"); mCamera.startPreview(); Log.v(TAG,"preview started"); } catch (IOException e) { Log.d(TAG, "Error setting camera preview: " + e.getMessage()); } } public void surfaceDestroyed(SurfaceHolder holder) { // empty. Take care of releasing the Camera preview in your activity. mCamera.stopPreview(); mCamera.release(); mCamera = null; } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. Log.v(TAG,"in surface changted"); if (mHolder.getSurface() == null){ // preview surface does not exist Log.v(TAG,"surface don't exist"); return; } // stop preview before making changes try { mCamera.stopPreview(); Log.v(TAG,"stopped preview"); } catch (Exception e){ // ignore: tried to stop a non-existent preview Log.v(TAG,"preview e"); } // start preview with new settings try { Log.v(TAG,"startpreview"); mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e){ Log.d(TAG, "Error starting camera preview: " + e.getMessage()); } } } public void takePic() { // get an image from the camera mCamera.takePicture(null, null, mPicture); } /* * end of boiler plate */ }
// Copyright 2018 Google LLC // // 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.google.location.suplclient.asn1.supl2.ulp_version_2_parameter_extensions; // Copyright 2008 Google Inc. All Rights Reserved. /* * This class is AUTOMATICALLY GENERATED. Do NOT EDIT. */ // // import com.google.location.suplclient.asn1.base.Asn1Integer; import com.google.location.suplclient.asn1.base.Asn1Object; import com.google.location.suplclient.asn1.base.Asn1Sequence; import com.google.location.suplclient.asn1.base.Asn1Tag; import com.google.location.suplclient.asn1.base.BitStream; import com.google.location.suplclient.asn1.base.BitStreamReader; import com.google.location.suplclient.asn1.base.SequenceComponent; import com.google.common.collect.ImmutableList; import java.util.Collection; import javax.annotation.Nullable; /** * */ public class SatellitesListRelatedData extends Asn1Sequence { // private static final Asn1Tag TAG_SatellitesListRelatedData = Asn1Tag.fromClassAndNumber(-1, -1); public SatellitesListRelatedData() { super(); } @Override @Nullable protected Asn1Tag getTag() { return TAG_SatellitesListRelatedData; } @Override protected boolean isTagImplicit() { return true; } public static Collection<Asn1Tag> getPossibleFirstTags() { if (TAG_SatellitesListRelatedData != null) { return ImmutableList.of(TAG_SatellitesListRelatedData); } else { return Asn1Sequence.getPossibleFirstTags(); } } /** * Creates a new SatellitesListRelatedData from encoded stream. */ public static SatellitesListRelatedData fromPerUnaligned(byte[] encodedBytes) { SatellitesListRelatedData result = new SatellitesListRelatedData(); result.decodePerUnaligned(new BitStreamReader(encodedBytes)); return result; } /** * Creates a new SatellitesListRelatedData from encoded stream. */ public static SatellitesListRelatedData fromPerAligned(byte[] encodedBytes) { SatellitesListRelatedData result = new SatellitesListRelatedData(); result.decodePerAligned(new BitStreamReader(encodedBytes)); return result; } @Override protected boolean isExtensible() { return true; } @Override public boolean containsExtensionValues() { for (SequenceComponent extensionComponent : getExtensionComponents()) { if (extensionComponent.isExplicitlySet()) return true; } return false; } private SatellitesListRelatedData.satIdType satId_; public SatellitesListRelatedData.satIdType getSatId() { return satId_; } /** * @throws ClassCastException if value is not a SatellitesListRelatedData.satIdType */ public void setSatId(Asn1Object value) { this.satId_ = (SatellitesListRelatedData.satIdType) value; } public SatellitesListRelatedData.satIdType setSatIdToNewInstance() { satId_ = new SatellitesListRelatedData.satIdType(); return satId_; } private SatellitesListRelatedData.iodType iod_; public SatellitesListRelatedData.iodType getIod() { return iod_; } /** * @throws ClassCastException if value is not a SatellitesListRelatedData.iodType */ public void setIod(Asn1Object value) { this.iod_ = (SatellitesListRelatedData.iodType) value; } public SatellitesListRelatedData.iodType setIodToNewInstance() { iod_ = new SatellitesListRelatedData.iodType(); return iod_; } @Override public Iterable<? extends SequenceComponent> getComponents() { ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder(); builder.add(new SequenceComponent() { Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 0); @Override public boolean isExplicitlySet() { return getSatId() != null; } @Override public boolean hasDefaultValue() { return false; } @Override public boolean isOptional() { return false; } @Override public Asn1Object getComponentValue() { return getSatId(); } @Override public void setToNewInstance() { setSatIdToNewInstance(); } @Override public Collection<Asn1Tag> getPossibleFirstTags() { return tag == null ? SatellitesListRelatedData.satIdType.getPossibleFirstTags() : ImmutableList.of(tag); } @Override public Asn1Tag getTag() { return tag; } @Override public boolean isImplicitTagging() { return true; } @Override public String toIndentedString(String indent) { return "satId : " + getSatId().toIndentedString(indent); } }); builder.add(new SequenceComponent() { Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 1); @Override public boolean isExplicitlySet() { return getIod() != null; } @Override public boolean hasDefaultValue() { return false; } @Override public boolean isOptional() { return false; } @Override public Asn1Object getComponentValue() { return getIod(); } @Override public void setToNewInstance() { setIodToNewInstance(); } @Override public Collection<Asn1Tag> getPossibleFirstTags() { return tag == null ? SatellitesListRelatedData.iodType.getPossibleFirstTags() : ImmutableList.of(tag); } @Override public Asn1Tag getTag() { return tag; } @Override public boolean isImplicitTagging() { return true; } @Override public String toIndentedString(String indent) { return "iod : " + getIod().toIndentedString(indent); } }); return builder.build(); } @Override public Iterable<? extends SequenceComponent> getExtensionComponents() { ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder(); return builder.build(); } // Copyright 2008 Google Inc. All Rights Reserved. /* * This class is AUTOMATICALLY GENERATED. Do NOT EDIT. */ // /** * */ public static class satIdType extends Asn1Integer { // private static final Asn1Tag TAG_satIdType = Asn1Tag.fromClassAndNumber(-1, -1); public satIdType() { super(); setValueRange(new java.math.BigInteger("0"), new java.math.BigInteger("63")); } @Override @Nullable protected Asn1Tag getTag() { return TAG_satIdType; } @Override protected boolean isTagImplicit() { return true; } public static Collection<Asn1Tag> getPossibleFirstTags() { if (TAG_satIdType != null) { return ImmutableList.of(TAG_satIdType); } else { return Asn1Integer.getPossibleFirstTags(); } } /** * Creates a new satIdType from encoded stream. */ public static satIdType fromPerUnaligned(byte[] encodedBytes) { satIdType result = new satIdType(); result.decodePerUnaligned(new BitStreamReader(encodedBytes)); return result; } /** * Creates a new satIdType from encoded stream. */ public static satIdType fromPerAligned(byte[] encodedBytes) { satIdType result = new satIdType(); result.decodePerAligned(new BitStreamReader(encodedBytes)); return result; } @Override public Iterable<BitStream> encodePerUnaligned() { return super.encodePerUnaligned(); } @Override public Iterable<BitStream> encodePerAligned() { return super.encodePerAligned(); } @Override public void decodePerUnaligned(BitStreamReader reader) { super.decodePerUnaligned(reader); } @Override public void decodePerAligned(BitStreamReader reader) { super.decodePerAligned(reader); } @Override public String toString() { return toIndentedString(""); } public String toIndentedString(String indent) { return "satIdType = " + getInteger() + ";\n"; } } // Copyright 2008 Google Inc. All Rights Reserved. /* * This class is AUTOMATICALLY GENERATED. Do NOT EDIT. */ // /** * */ public static class iodType extends Asn1Integer { // private static final Asn1Tag TAG_iodType = Asn1Tag.fromClassAndNumber(-1, -1); public iodType() { super(); setValueRange(new java.math.BigInteger("0"), new java.math.BigInteger("1023")); } @Override @Nullable protected Asn1Tag getTag() { return TAG_iodType; } @Override protected boolean isTagImplicit() { return true; } public static Collection<Asn1Tag> getPossibleFirstTags() { if (TAG_iodType != null) { return ImmutableList.of(TAG_iodType); } else { return Asn1Integer.getPossibleFirstTags(); } } /** * Creates a new iodType from encoded stream. */ public static iodType fromPerUnaligned(byte[] encodedBytes) { iodType result = new iodType(); result.decodePerUnaligned(new BitStreamReader(encodedBytes)); return result; } /** * Creates a new iodType from encoded stream. */ public static iodType fromPerAligned(byte[] encodedBytes) { iodType result = new iodType(); result.decodePerAligned(new BitStreamReader(encodedBytes)); return result; } @Override public Iterable<BitStream> encodePerUnaligned() { return super.encodePerUnaligned(); } @Override public Iterable<BitStream> encodePerAligned() { return super.encodePerAligned(); } @Override public void decodePerUnaligned(BitStreamReader reader) { super.decodePerUnaligned(reader); } @Override public void decodePerAligned(BitStreamReader reader) { super.decodePerAligned(reader); } @Override public String toString() { return toIndentedString(""); } public String toIndentedString(String indent) { return "iodType = " + getInteger() + ";\n"; } } @Override public Iterable<BitStream> encodePerUnaligned() { return super.encodePerUnaligned(); } @Override public Iterable<BitStream> encodePerAligned() { return super.encodePerAligned(); } @Override public void decodePerUnaligned(BitStreamReader reader) { super.decodePerUnaligned(reader); } @Override public void decodePerAligned(BitStreamReader reader) { super.decodePerAligned(reader); } @Override public String toString() { return toIndentedString(""); } public String toIndentedString(String indent) { StringBuilder builder = new StringBuilder(); builder.append("SatellitesListRelatedData = {\n"); final String internalIndent = indent + " "; for (SequenceComponent component : getComponents()) { if (component.isExplicitlySet()) { builder.append(internalIndent) .append(component.toIndentedString(internalIndent)); } } if (isExtensible()) { builder.append(internalIndent).append("...\n"); for (SequenceComponent component : getExtensionComponents()) { if (component.isExplicitlySet()) { builder.append(internalIndent) .append(component.toIndentedString(internalIndent)); } } } builder.append(indent).append("};\n"); return builder.toString(); } }
package org.sagebionetworks.repo.model.dbo.wikiV2; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_FILES_ID; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_FILES; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_ID; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_ATTACHMENT_ID_LIST; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_FILE_HANDLE_ID; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_ID; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_MODIFIED_BY; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_MODIFIED_ON; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_TITLE; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_COL_WIKI_MARKDOWN_VERSION_NUM; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_TABLE_WIKI_MARKDOWN; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.V2_TABLE_WIKI_PAGE; import java.util.List; import org.sagebionetworks.repo.model.dbo.AutoTableMapping; import org.sagebionetworks.repo.model.dbo.Field; import org.sagebionetworks.repo.model.dbo.ForeignKey; import org.sagebionetworks.repo.model.dbo.MigratableDatabaseObject; import org.sagebionetworks.repo.model.dbo.Table; import org.sagebionetworks.repo.model.dbo.TableMapping; import org.sagebionetworks.repo.model.dbo.migration.BasicMigratableTableTranslation; import org.sagebionetworks.repo.model.dbo.migration.MigratableTableTranslation; import org.sagebionetworks.repo.model.migration.MigrationType; /** * Keeps track of markdown information of wikis * * @author hso * */ @Table(name = V2_TABLE_WIKI_MARKDOWN, constraints = {"UNIQUE KEY `V2_WIKI_UNIQUE_MARKDOWN_VERSION` (`" + V2_COL_WIKI_MARKDOWN_ID + "`,`" + V2_COL_WIKI_MARKDOWN_VERSION_NUM + "`)"}) public class V2DBOWikiMarkdown implements MigratableDatabaseObject<V2DBOWikiMarkdown, V2DBOWikiMarkdown> { @Field(name = V2_COL_WIKI_MARKDOWN_ID, backupId = true, primary = true, nullable = false) @ForeignKey(name = "V2_WIKI_MARKDOWN_FK", table = V2_TABLE_WIKI_PAGE, field = V2_COL_WIKI_ID, cascadeDelete = true) private Long wikiId; @Field(name = V2_COL_WIKI_MARKDOWN_FILE_HANDLE_ID, nullable = false, hasFileHandleRef = true) @ForeignKey(name = "V2_WIKI_MARKDOWN_FILE_HAND_FK", table = TABLE_FILES, field = COL_FILES_ID, cascadeDelete = false) private Long fileHandleId; @Field(name = V2_COL_WIKI_MARKDOWN_VERSION_NUM, primary = true, nullable = false) private Long markdownVersion; @Field(name = V2_COL_WIKI_MARKDOWN_MODIFIED_ON, nullable = false) private Long modifiedOn; @Field(name = V2_COL_WIKI_MARKDOWN_MODIFIED_BY, nullable = false) private Long modifiedBy; @Field(name = V2_COL_WIKI_MARKDOWN_TITLE, varchar = 256) private String title; @Field(name = V2_COL_WIKI_MARKDOWN_ATTACHMENT_ID_LIST, type = "mediumblob", defaultNull = true) private byte[] attachmentIdList; private static TableMapping<V2DBOWikiMarkdown> tableMapping = AutoTableMapping.create(V2DBOWikiMarkdown.class); @Override public TableMapping<V2DBOWikiMarkdown> getTableMapping() { return tableMapping; } @Override public MigrationType getMigratableTableType() { return MigrationType.V2_WIKI_MARKDOWN; } @Override public MigratableTableTranslation<V2DBOWikiMarkdown, V2DBOWikiMarkdown> getTranslator() { return new BasicMigratableTableTranslation<V2DBOWikiMarkdown>(); } @Override public Class<? extends V2DBOWikiMarkdown> getBackupClass() { return V2DBOWikiMarkdown.class; } @Override public Class<? extends V2DBOWikiMarkdown> getDatabaseObjectClass() { return V2DBOWikiMarkdown.class; } @Override public List<MigratableDatabaseObject<?,?>> getSecondaryTypes() { return null; } public Long getWikiId() { return wikiId; } public void setWikiId(Long wikiId) { this.wikiId = wikiId; } public Long getFileHandleId() { return fileHandleId; } public void setFileHandleId(Long fileHandleId) { this.fileHandleId = fileHandleId; } public Long getMarkdownVersion() { return markdownVersion; } public void setMarkdownVersion(Long markdownVersion) { this.markdownVersion = markdownVersion; } public Long getModifiedOn() { return modifiedOn; } public void setModifiedOn(Long modifiedOn) { this.modifiedOn = modifiedOn; } public Long getModifiedBy() { return modifiedBy; } public void setModifiedBy(Long modifiedBy) { this.modifiedBy = modifiedBy; } public byte[] getAttachmentIdList() { return attachmentIdList; } public void setAttachmentIdList(byte[] attachmentIdList) { this.attachmentIdList = attachmentIdList; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fileHandleId == null) ? 0 : fileHandleId.hashCode()); result = prime * result + ((markdownVersion == null) ? 0 : markdownVersion.hashCode()); result = prime * result + ((modifiedOn == null) ? 0 : modifiedOn.hashCode()); result = prime * result + ((modifiedBy == null) ? 0 : modifiedBy.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); result = prime * result + ((attachmentIdList == null) ? 0 : attachmentIdList.hashCode()); result = prime * result + ((wikiId == null) ? 0 : wikiId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; V2DBOWikiMarkdown other = (V2DBOWikiMarkdown) obj; if (fileHandleId == null) { if (other.fileHandleId != null) return false; } else if (!fileHandleId.equals(other.fileHandleId)) return false; if (markdownVersion == null) { if (other.markdownVersion != null) return false; } else if (!markdownVersion.equals(other.markdownVersion)) return false; if (modifiedOn == null) { if (other.modifiedOn != null) return false; } else if (!modifiedOn.equals(other.modifiedOn)) return false; if (modifiedBy == null) { if (other.modifiedBy != null) return false; } else if (!modifiedBy.equals(other.modifiedBy)) return false; if (attachmentIdList == null) { if (other.attachmentIdList != null) return false; } else if (!attachmentIdList.equals(other.attachmentIdList)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; if (wikiId == null) { if (other.wikiId != null) return false; } else if (!wikiId.equals(other.wikiId)) return false; return true; } @Override public String toString() { return "DBOWikiMarkdown [wikiId=" + wikiId + ", fileHandleId=" + fileHandleId + ", markdownVersion=" + markdownVersion + ", modifiedOn=" + modifiedOn + ", markdownBy=" + modifiedBy + ", title=" + title + ", attachmentIdList=" + attachmentIdList + "]"; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.drill.exec.client; import java.io.File; import java.io.FileInputStream; import java.util.List; import org.apache.drill.exec.cache.VectorAccessibleSerializable; import org.apache.drill.exec.memory.BufferAllocator; import org.apache.drill.exec.memory.TopLevelAllocator; import org.apache.drill.exec.record.BatchSchema; import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode; import org.apache.drill.exec.record.MaterializedField; import org.apache.drill.exec.record.VectorAccessible; import org.apache.drill.exec.record.VectorContainer; import org.apache.drill.exec.record.VectorWrapper; import org.apache.drill.exec.util.VectorUtil; import com.beust.jcommander.IParameterValidator; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.collect.Lists; public class DumpCat { private final static BufferAllocator allocator = new TopLevelAllocator(); public static void main(String args[]) throws Exception { DumpCat dumpCat = new DumpCat(); Options o = new Options(); JCommander jc = null; try { jc = new JCommander(o, args); jc.setProgramName("./drill_dumpcat"); } catch (ParameterException e) { System.out.println(e.getMessage()); String[] valid = {"-f", "file"}; new JCommander(o, valid).usage(); System.exit(-1); } if (o.help) { jc.usage(); System.exit(0); } /*Check if dump file exists*/ File file = new File(o.location); if (!file.exists()) { System.out.println(String.format("Trace file %s not created", o.location)); System.exit(-1); } FileInputStream input = new FileInputStream(file.getAbsoluteFile()); if (o.batch < 0) { dumpCat.doQuery(input); } else { dumpCat.doBatch(input, o.batch, o.include_headers); } input.close(); } /** * Used to ensure the param "batch" is a non-negative number. */ public static class BatchNumValidator implements IParameterValidator { @Override public void validate(String name, String value) throws ParameterException { try { int batch = Integer.parseInt(value); if (batch < 0) { throw new ParameterException("Parameter " + name + " should be non-negative number."); } } catch (NumberFormatException e) { throw new ParameterException("Parameter " + name + " should be non-negative number."); } } } /** * Options as input to JCommander. */ static class Options { @Parameter(names = {"-f"}, description = "file containing dump", required=true) public String location = null; @Parameter(names = {"-batch"}, description = "id of batch to show", required=false, validateWith = BatchNumValidator.class) public int batch = -1; @Parameter(names = {"-include-headers"}, description = "whether include header of batch", required=false) public boolean include_headers = false; @Parameter(names = {"-h", "-help", "--help"}, description = "show usage", help=true) public boolean help = false; } /** * Contains : # of rows, # of selected rows, data size (byte #). */ private class BatchMetaInfo { private long rows = 0; private long selectedRows = 0; private long dataSize = 0; public BatchMetaInfo () { } public BatchMetaInfo (long rows, long selectedRows, long dataSize) { this.rows = rows; this.selectedRows = selectedRows; this.dataSize = dataSize; } public void add(BatchMetaInfo info2) { this.rows += info2.rows; this.selectedRows += info2.selectedRows; this.dataSize += info2.dataSize; } @Override public String toString() { String avgRecSizeStr = null; if (this.rows>0) { avgRecSizeStr = String.format("Average Record Size : %d ", this.dataSize/this.rows); } else { avgRecSizeStr = "Average Record Size : 0"; } return String.format("Records : %d / %d \n", this.selectedRows, this.rows) + avgRecSizeStr + String.format("\n Total Data Size : %d", this.dataSize); } } /** * Querymode: * $drill-dumpcat --file=local:///tmp/drilltrace/[queryid]_[tag]_[majorid]_[minor]_[operator] * Batches: 135 * Records: 53,214/53,214 // the first one is the selected records. The second number is the total number of records. * Selected Records: 53,214 * Average Record Size: 74 bytes * Total Data Size: 12,345 bytes * Number of Empty Batches: 1 * Schema changes: 1 * Schema change batch indices: 0 * @throws Exception */ protected void doQuery(FileInputStream input) throws Exception{ int batchNum = 0; int emptyBatchNum = 0; BatchSchema prevSchema = null; List<Integer> schemaChangeIdx = Lists.newArrayList(); BatchMetaInfo aggBatchMetaInfo = new BatchMetaInfo(); while (input.available() > 0) { VectorAccessibleSerializable vcSerializable = new VectorAccessibleSerializable(DumpCat.allocator); vcSerializable.readFromStream(input); VectorContainer vectorContainer = (VectorContainer) vcSerializable.get(); aggBatchMetaInfo.add(getBatchMetaInfo(vcSerializable)); if (vectorContainer.getRecordCount() == 0) { emptyBatchNum ++; } if (prevSchema != null && !vectorContainer.getSchema().equals(prevSchema)) { schemaChangeIdx.add(batchNum); } prevSchema = vectorContainer.getSchema(); batchNum ++; vectorContainer.zeroVectors(); } /* output the summary stat */ System.out.println(String.format("Total # of batches: %d", batchNum)); //output: rows, selectedRows, avg rec size, total data size. System.out.println(aggBatchMetaInfo.toString()); System.out.println(String.format("Empty batch : %d", emptyBatchNum)); System.out.println(String.format("Schema changes : %d", schemaChangeIdx.size())); System.out.println(String.format("Schema change batch index : %s", schemaChangeIdx.toString())); } /** * Batch mode: * $drill-dumpcat --file=local:///tmp/drilltrace/[queryid]_[tag]_[majorid]_[minor]_[operator] --batch=123 --include-headers=true * Records: 1/1 * Average Record Size: 8 bytes * Total Data Size: 8 bytes * Schema Information * name: col1, minor_type: int4, data_mode: nullable * name: col2, minor_type: int4, data_mode: non-nullable * @param targetBatchNum * @throws Exception */ protected void doBatch(FileInputStream input, int targetBatchNum, boolean showHeader) throws Exception { int batchNum = -1; VectorAccessibleSerializable vcSerializable = null; while (input.available() > 0 && batchNum ++ < targetBatchNum) { vcSerializable = new VectorAccessibleSerializable(DumpCat.allocator); vcSerializable.readFromStream(input); if (batchNum != targetBatchNum) { VectorContainer vectorContainer = (VectorContainer) vcSerializable.get(); vectorContainer.zeroVectors(); } } if (batchNum < targetBatchNum) { System.out.println(String.format("Wrong input of batch # ! Total # of batch in the file is %d. Please input a number 0..%d as batch #", batchNum+1, batchNum)); input.close(); System.exit(-1); } if (vcSerializable != null) { showSingleBatch(vcSerializable, showHeader); VectorContainer vectorContainer = (VectorContainer) vcSerializable.get(); vectorContainer.zeroVectors(); } } private void showSingleBatch (VectorAccessibleSerializable vcSerializable, boolean showHeader) { VectorContainer vectorContainer = (VectorContainer)vcSerializable.get(); /* show the header of the batch */ if (showHeader) { System.out.println(getBatchMetaInfo(vcSerializable).toString()); System.out.println("Schema Information"); for (VectorWrapper w : vectorContainer) { MaterializedField field = w.getValueVector().getField(); System.out.println (String.format("name : %s, minor_type : %s, data_mode : %s", field.toExpr(), field.getType().getMinorType().toString(), field.isNullable() ? "nullable":"non-nullable" )); } } /* show the contents in the batch */ VectorUtil.showVectorAccessibleContent(vectorContainer); } /* Get batch meta info : rows, selectedRows, dataSize */ private BatchMetaInfo getBatchMetaInfo(VectorAccessibleSerializable vcSerializable) { VectorAccessible vectorContainer = vcSerializable.get(); int rows =0; int selectedRows = 0; int totalDataSize = 0; rows = vectorContainer.getRecordCount(); selectedRows = rows; if (vectorContainer.getSchema().getSelectionVectorMode() == SelectionVectorMode.TWO_BYTE) { selectedRows = vcSerializable.getSv2().getCount(); } for (VectorWrapper w : vectorContainer) { totalDataSize += w.getValueVector().getBufferSize(); } return new BatchMetaInfo(rows, selectedRows, totalDataSize); } }
/******************************************************************************* * Copyright (c) Intel Corporation * Copyright (c) 2017 * * 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 org.osc.core.broker.service; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.Callable; import javax.persistence.EntityManager; import org.hibernate.StaleObjectStateException; import org.hibernate.exception.ConstraintViolationException; import org.osc.core.broker.service.api.ServiceDispatcherApi; import org.osc.core.broker.service.api.server.UserContextApi; import org.osc.core.broker.service.exceptions.VmidcDbConcurrencyException; import org.osc.core.broker.service.exceptions.VmidcDbConstraintViolationException; import org.osc.core.broker.service.exceptions.VmidcException; import org.osc.core.broker.service.request.Request; import org.osc.core.broker.service.response.Response; import org.osc.core.broker.service.ssl.SslCertificatesExtendedException; import org.osc.core.broker.util.ServerUtil; import org.osc.core.broker.util.TransactionalBroadcastUtil; import org.osc.core.broker.util.db.DBConnectionManager; import org.slf4j.LoggerFactory; import org.osc.core.server.Server; import org.osgi.service.component.annotations.Reference; import org.osgi.service.transaction.control.ScopedWorkException; import org.osgi.service.transaction.control.TransactionControl; import org.slf4j.Logger; import com.google.common.annotations.VisibleForTesting; public abstract class ServiceDispatcher<I extends Request, O extends Response> implements ServiceDispatcherApi<I, O> { private static final Logger log = LoggerFactory.getLogger(ServiceDispatcher.class); private EntityManager em = null; /** * This field is why we have: <p><code> * * -dsannotations-options: inherit * * </code><p> in the bnd file. This is a non-default * option, but it is much neater than forcing every service * to implement a getUserConext() method. */ @Reference protected UserContextApi userContext; @Reference protected DBConnectionManager dbConnectionManager; @Reference protected TransactionalBroadcastUtil txBroadcastUtil; private final Queue<ChainedDispatch<O>> chainedDispatches = new LinkedList<>(); // generalized method to dispatch incoming requests to the appropriate // service handler @Override public O dispatch(I request) throws Exception { log.info("Service dispatch " + this.getClass().getSimpleName() + ". User: " + this.userContext.getCurrentUser() + ", Request: " + request); if (Server.isInMaintenance()) { log.warn("Incoming request (pid:" + ServerUtil.getCurrentPid() + ") while server is in maintenance mode."); throw new VmidcException(Server.PRODUCT_NAME + " server is in maintenance mode."); } if (this.em == null) { this.em = getEntityManager(); } TransactionControl txControl = getTransactionControl(); O response = null; try { // calling service in a transaction response = txControl.required(() -> exec(request, this.em)); } catch (ScopedWorkException e) { handleException(e.getCause()); } ChainedDispatch<O> nextDispatch; while ((nextDispatch = popChain()) != null) { try { final O previousResponse = response; final ChainedDispatch<O> tempNext = nextDispatch; response = txControl.required(() -> tempNext.dispatch(previousResponse, this.em)); } catch (ScopedWorkException e) { handleException(e.getCause()); } } log.info("Service response: " + response); return response; } private ChainedDispatch<O> popChain() { synchronized (this.chainedDispatches) { return this.chainedDispatches.poll(); } } /** * <p> * Chain an additional transaction step that will be executed in its own * transaction, after the successful completion of the main transaction and * all previously chained transaction steps. It is legal to add a chained * step during the execution of the main transaction and/or during a * previously added step. * </p> * * <p> * This variation of the method is convenient for chaining method * references, for example: * </p> * * <pre> * &#64;Override * protected B exec(A a, EntityManager em) throws Exception { * B interimResult = ...; * chain(this::doNextPart); * return interimResult; * } * private B doNextPart(B input, EntityManager em) { * // input comes from 'interimResult' above * em.merge(input); * return new B(...); * } * </pre> * * @param dispatch * A function that shall be executed in its own transaction. The * input to the function shall be the result from the previous * step or, if this is the first step, the result from the main * transaction. If this is the last step then the return value of * the provided function is used as the result for the entire * dispatch. */ protected void chain(ChainedDispatch<O> dispatch) { synchronized (this.chainedDispatches) { this.chainedDispatches.add(dispatch); } } /** * <p>See {@link #chain(ChainedDispatch)}.</p> * * <p>This variation of the method is useful for chaining lambdas, which can * have visibility of the outer scope. For example:</p> * * <pre> * &#64;Override * protected B exec(A a, EntityManager em) throws Exception { * B interimResult = ...; * chain(() -> { * em.merge(interimResult); * return new B(...); * }); * return interimResult; * } * * </pre> * * @param call * @see #chain(ChainedDispatch) */ protected void chain(Callable<O> call) { ChainedDispatch<O> dispatch = (em, o) -> call.call(); synchronized (this.chainedDispatches) { this.chainedDispatches.add(dispatch); } } /** * Created for the testing the class. Which helps to create the mock object of SessionFactory. * * @return * @throws VmidcException * @throws InterruptedException */ @VisibleForTesting protected EntityManager getEntityManager() throws InterruptedException, VmidcException { return this.dbConnectionManager.getTransactionalEntityManager(); } /** * Created for the testing the class. Which helps to create the mock object of SessionFactory. * * @return * @throws VmidcException * @throws InterruptedException */ @VisibleForTesting protected TransactionControl getTransactionControl() throws InterruptedException, VmidcException { return this.dbConnectionManager.getTransactionControl(); } protected abstract O exec(I request, EntityManager em) throws Exception; private void handleException(Throwable e) throws VmidcDbConstraintViolationException, VmidcDbConcurrencyException, Exception { if (e instanceof SslCertificatesExtendedException) { throw (SslCertificatesExtendedException) e; } else if (e instanceof VmidcException) { log.warn("Service request failed (logically): " + e.getMessage()); } else { log.error("Service request failed (unexpectedly): " + e.getMessage(), e); } if (e instanceof ConstraintViolationException) { log.error("Got database constraint violation exception", e); throw new VmidcDbConstraintViolationException("Database Constraint Violation Exception."); } else if (e instanceof StaleObjectStateException) { log.error("Got database concurrency exception", e); throw new VmidcDbConcurrencyException("Database Concurrency Exception."); } else if (e instanceof Exception) { throw (Exception) e; } throw new Exception("Exception or error executing service call: " + e.getMessage(), e); } }
package de.uni_passau.facultyinfo.server.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.uni_passau.facultyinfo.server.dao.connection.AttributeContainer; import de.uni_passau.facultyinfo.server.dao.connection.JDBCConnection; import de.uni_passau.facultyinfo.server.dto.ContactGroup; import de.uni_passau.facultyinfo.server.dto.ContactPerson; import de.uni_passau.facultyinfo.server.dto.ContactSearchResponse; public class ContactPersonDAO { public List<ContactGroup> getContactGroups() { ResultSet resultSet = JDBCConnection .getInstance() .executeSelect( "SELECT id, title, description FROM contactgroups ORDER BY title"); if (resultSet == null) { return null; } try { ArrayList<ContactGroup> contactGroups = mapResultSetToContactGroups(resultSet); return contactGroups; } catch (SQLException e) { e.printStackTrace(); return null; } } public ContactGroup getContactGroup(String id) { AttributeContainer attributes = new AttributeContainer(); attributes.add(1, id); ResultSet resultSet = JDBCConnection .getInstance() .executeSelect( "SELECT id, title, description FROM contactgroups WHERE id = ?", attributes); if (resultSet == null) { return null; } try { ContactGroup contactGroup = mapResultSetToContactGroup(resultSet); ResultSet contactPersonResultSet = JDBCConnection .getInstance() .executeSelect( "SELECT id, name, office, phone, email, description FROM contactpersons WHERE contactgroup = ?", attributes); contactGroup.setContactPersons(mapResultSetToContactPersons( contactPersonResultSet, contactGroup)); return contactGroup; } catch (SQLException e) { e.printStackTrace(); return null; } } public ContactPerson getContactPerson(String id) { AttributeContainer attributes = new AttributeContainer(); attributes.add(1, id); ResultSet resultSet = JDBCConnection .getInstance() .executeSelect( "SELECT contactpersons.id, contactpersons.name, contactpersons.office, contactpersons.phone, contactpersons.email, contactpersons.description, contactgroups.title FROM contactpersons JOIN contactgroups ON contactpersons.contactgroup = contactgroups.id WHERE contactpersons.id = ?", attributes); if (resultSet == null) { return null; } try { return mapResultSetToContactPerson(resultSet); } catch (SQLException e) { e.printStackTrace(); return null; } } public ContactSearchResponse find(String searchString) { ContactSearchResponse response = new ContactSearchResponse(); if (searchString != null && !searchString.isEmpty()) { List<ContactGroup> groups = getFullContactGroups(); Pattern pattern = Pattern.compile(searchString, Pattern.CASE_INSENSITIVE + Pattern.LITERAL); for (ContactGroup group : groups) { List<ContactPerson> persons = group.getContactPersons(); group.setContactPersons(null); boolean found = false; if (group.getTitle() != null && pattern.matcher(group.getTitle()).find()) { found = true; } if (group.getDescription() != null) { Matcher descriptionMatcher = pattern.matcher(group .getDescription()); if (descriptionMatcher.find()) { group.setDescription(crop(group.getDescription(), descriptionMatcher.start(), descriptionMatcher.end())); found = true; } else { group.setDescription(null); } } if (found) { response.add(group); } for (ContactPerson person : persons) { person.setContactGroup(null); found = false; if (person.getName() != null && pattern.matcher(person.getName()).find()) { found = true; } if (person.getOffice() != null && pattern.matcher(person.getOffice()).find()) { found = true; } else { person.setOffice(null); } if (person.getPhone() != null && pattern.matcher(person.getPhone()).find()) { found = true; } else { person.setPhone(null); } if (person.getEmail() != null && pattern.matcher(person.getEmail()).find()) { found = true; } else { person.setEmail(null); } if (person.getDescription() != null) { Matcher descriptionMatcher = pattern.matcher(person .getDescription()); if (descriptionMatcher.find()) { person.setDescription(crop(person.getDescription(), descriptionMatcher.start(), descriptionMatcher.end())); found = true; } else { person.setDescription(null); } } if (found) { person.setGroupTitle(group.getTitle()); response.add(person); } } } } return response; } private List<ContactGroup> getFullContactGroups() { ResultSet resultSet = JDBCConnection .getInstance() .executeSelect( "SELECT id, title, description FROM contactgroups ORDER BY title"); if (resultSet == null) { return null; } try { ArrayList<ContactGroup> contactGroups = mapResultSetToContactGroups(resultSet); for (ContactGroup contactGroup : contactGroups) { AttributeContainer attributes = new AttributeContainer(); attributes.add(1, contactGroup.getId()); ResultSet contactPersonResultSet = JDBCConnection .getInstance() .executeSelect( "SELECT id, name, office, phone, email, description FROM contactpersons WHERE contactgroup = ?", attributes); if (contactPersonResultSet == null) { continue; } contactGroup.setContactPersons(mapResultSetToContactPersons( contactPersonResultSet, contactGroup)); } return contactGroups; } catch (SQLException e) { e.printStackTrace(); return null; } } private ArrayList<ContactGroup> mapResultSetToContactGroups( ResultSet resultSet) throws SQLException { ArrayList<ContactGroup> contactGroups = new ArrayList<ContactGroup>(); while (resultSet.next()) { ContactGroup contactGroup = new ContactGroup( resultSet.getString("id"), resultSet.getString("title"), resultSet.getString("description")); contactGroups.add(contactGroup); } return contactGroups; } private ContactGroup mapResultSetToContactGroup(ResultSet resultSet) throws SQLException { if (resultSet.next()) { ContactGroup contactGroup = new ContactGroup( resultSet.getString("id"), resultSet.getString("title"), resultSet.getString("description")); return contactGroup; } return null; } private ArrayList<ContactPerson> mapResultSetToContactPersons( ResultSet resultSet, ContactGroup contactGroup) throws SQLException { ArrayList<ContactPerson> contactPersons = new ArrayList<ContactPerson>(); while (resultSet.next()) { ContactPerson contactPerson = new ContactPerson( resultSet.getString("id"), resultSet.getString("name"), resultSet.getString("office"), resultSet.getString("phone"), resultSet.getString("email"), resultSet.getString("description"), contactGroup); contactPersons.add(contactPerson); } return contactPersons; } private ContactPerson mapResultSetToContactPerson(ResultSet resultSet) throws SQLException { if (resultSet.next()) { ContactPerson contactPerson = new ContactPerson( resultSet.getString("id"), resultSet.getString("name"), resultSet.getString("office"), resultSet.getString("phone"), resultSet.getString("email"), resultSet.getString("description"), resultSet.getString("title")); return contactPerson; } return null; } private String crop(String input, int start, int offset) { boolean cropStart = start - 50 >= 0; boolean cropEnd = start + offset + 50 < input.length(); String croppedInput = input.substring(cropStart ? start - 50 : 0, cropEnd ? start + offset + 50 : input.length()); croppedInput = (cropStart ? "..." : "") + croppedInput + (cropEnd ? "..." : ""); return croppedInput; } }
package de.lessvoid.nifty.sound.openal; import java.net.URL; import java.util.ArrayList; import java.util.logging.Logger; import de.lessvoid.nifty.sound.openal.slick.Audio; import de.lessvoid.nifty.sound.openal.slick.AudioImpl; import de.lessvoid.nifty.sound.openal.slick.SoundStore; import de.lessvoid.nifty.tools.resourceloader.NiftyResourceLoader; /** * A piece of music loaded and playable within the game. Only one piece of music can * play at any given time and a channel is reserved so music will always play. * * @author kevin * @author Nathan Sweet <misc@n4te.com> */ public class Music { private Logger log = Logger.getLogger(Music.class.getName()); /** The music currently being played or null if none */ private static Music currentMusic; /** * Poll the state of the current music. This causes streaming music * to stream and checks listeners. Note that if you're using a game container * this will be auto-magically called for you. * * @param delta The amount of time since last poll */ public static void poll(int delta) { if (currentMusic != null) { SoundStore.get().poll(delta); if (!SoundStore.get().isMusicPlaying()) { if (!currentMusic.positioning) { Music oldMusic = currentMusic; currentMusic = null; oldMusic.fireMusicEnded(); } } else { currentMusic.update(delta); } } } /** The sound from FECK representing this music */ private Audio sound; /** True if the music is playing */ private boolean playing; /** The list of listeners waiting for notification that the music ended */ private ArrayList<MusicListener> listeners = new ArrayList<MusicListener>(); /** The volume of this music */ private float volume = 1.0f; /** Start gain for fading in/out */ private float fadeStartGain; /** End gain for fading in/out */ private float fadeEndGain; /** Countdown for fading in/out */ private int fadeTime; /** Duration for fading in/out */ private int fadeDuration; /** True if music should be stopped after fading in/out */ private boolean stopAfterFade; /** True if the music is being repositioned and it is therefore normal that it's not playing */ private boolean positioning; /** The position that was requested */ private float requiredPosition = -1; /** * Create and load a piece of music (either OGG or MOD/XM) * * @param ref The location of the music * @throws SlickException */ public Music(String ref, final NiftyResourceLoader resourceLoader) throws Exception { this(ref, false, resourceLoader); } /** * Create and load a piece of music (either OGG or MOD/XM) * * @param ref The location of the music * @throws SlickException */ public Music(URL ref, final NiftyResourceLoader resourceLoader) throws Exception { this(ref, false, resourceLoader); } /** * Create and load a piece of music (either OGG or MOD/XM) * * @param url The location of the music * @param streamingHint A hint to indicate whether streaming should be used if possible * @throws SlickException */ public Music(URL url, boolean streamingHint, final NiftyResourceLoader resourceLoader) throws Exception { SoundStore.get().init(); String ref = url.getFile(); try { if (ref.toLowerCase().endsWith(".ogg")) { if (streamingHint) { sound = SoundStore.get().getOggStream(url, resourceLoader); } else { sound = SoundStore.get().getOgg(url.openStream()); } } else if (ref.toLowerCase().endsWith(".wav")) { sound = SoundStore.get().getWAV(url.openStream()); } else if (ref.toLowerCase().endsWith(".xm") || ref.toLowerCase().endsWith(".mod")) { sound = SoundStore.get().getMOD(url.openStream()); } else if (ref.toLowerCase().endsWith(".aif") || ref.toLowerCase().endsWith(".aiff")) { sound = SoundStore.get().getAIF(url.openStream()); } else { throw new Exception("Only .xm, .mod, .ogg, and .aif/f are currently supported."); } } catch (Exception e) { log.warning(e.toString()); throw new Exception("Failed to load sound: "+url); } } /** * Create and load a piece of music (either OGG or MOD/XM) * * @param ref The location of the music * @param streamingHint A hint to indicate whether streaming should be used if possible * @throws SlickException */ public Music(String ref, boolean streamingHint, final NiftyResourceLoader resourceLoader) throws Exception { SoundStore.get().init(); try { if (ref.toLowerCase().endsWith(".ogg")) { if (streamingHint) { sound = SoundStore.get().getOggStream(ref, resourceLoader); } else { sound = SoundStore.get().getOgg(ref, resourceLoader); } } else if (ref.toLowerCase().endsWith(".wav")) { sound = SoundStore.get().getWAV(ref, resourceLoader); } else if (ref.toLowerCase().endsWith(".xm") || ref.toLowerCase().endsWith(".mod")) { sound = SoundStore.get().getMOD(ref, resourceLoader); } else if (ref.toLowerCase().endsWith(".aif") || ref.toLowerCase().endsWith(".aiff")) { sound = SoundStore.get().getAIF(ref, resourceLoader); } else { throw new Exception("Only .xm, .mod, .ogg, and .aif/f are currently supported."); } } catch (Exception e) { log.warning(e.toString()); throw new Exception("Failed to load sound: "+ref); } } /** * Add a listener to this music * * @param listener The listener to add */ public void addListener(MusicListener listener) { listeners.add(listener); } /** * Remove a listener from this music * * @param listener The listener to remove */ public void removeListener(MusicListener listener) { listeners.remove(listener); } /** * Fire notifications that this music ended */ private void fireMusicEnded() { playing = false; for (int i=0;i<listeners.size();i++) { listeners.get(i).musicEnded(this); } } /** * Fire notifications that this music was swapped out * * @param newMusic The new music that will be played */ private void fireMusicSwapped(Music newMusic) { playing = false; for (int i=0;i<listeners.size();i++) { listeners.get(i).musicSwapped(this, newMusic); } } /** * Loop the music */ public void loop() { loop(1.0f, 1.0f); } /** * Play the music */ public void play() { play(1.0f, 1.0f); } /** * Play the music at a given pitch and volume * * @param pitch The pitch to play the music at (1.0 = default) * @param volume The volume to play the music at (1.0 = default) */ public void play(float pitch, float volume) { startMusic(pitch, volume, false); } /** * Loop the music at a given pitch and volume * * @param pitch The pitch to play the music at (1.0 = default) * @param volume The volume to play the music at (1.0 = default) */ public void loop(float pitch, float volume) { startMusic(pitch, volume, true); } /** * play or loop the music at a given pitch and volume * @param pitch The pitch to play the music at (1.0 = default) * @param volume The volume to play the music at (1.0 = default) * @param loop if false the music is played once, the music is looped otherwise */ private void startMusic(float pitch, float volume, boolean loop) { if (currentMusic != null) { currentMusic.stop(); currentMusic.fireMusicSwapped(this); } currentMusic = this; if (volume < 0.0f) volume = 0.0f; if (volume > 1.0f) volume = 1.0f; sound.playAsMusic(pitch, volume, loop); playing = true; setVolume(volume); if (requiredPosition != -1) { setPosition(requiredPosition); } } /** * Pause the music playback */ public void pause() { playing = false; AudioImpl.pauseMusic(); } /** * Stop the music playing */ public void stop() { sound.stop(); } /** * Resume the music playback */ public void resume() { playing = true; AudioImpl.restartMusic(); } /** * Check if the music is being played * * @return True if the music is being played */ public boolean playing() { return (currentMusic == this) && (playing); } /** * Set the volume of the music as a factor of the global volume setting * * @param volume The volume to play music at. 0 - 1, 1 is Max */ public void setVolume(float volume) { // Bounds check if(volume > 1) { volume = 1; } else if(volume < 0) { volume = 0; } this.volume = volume; // This sound is being played as music if (currentMusic == this) { SoundStore.get().setCurrentMusicVolume(volume); } } /** * Get the individual volume of the music * @return The volume of this music, still effected by global SoundStore volume. 0 - 1, 1 is Max */ public float getVolume() { return volume; } /** * Fade this music to the volume specified * * @param duration Fade time in milliseconds. * @param endVolume The target volume * @param stopAfterFade True if music should be stopped after fading in/out */ public void fade (int duration, float endVolume, boolean stopAfterFade) { this.stopAfterFade = stopAfterFade; fadeStartGain = volume; fadeEndGain = endVolume; fadeDuration = duration; fadeTime = duration; } /** * Update the current music applying any effects that need to updated per * tick. * * @param delta The amount of time in milliseconds thats passed since last update */ void update(int delta) { if (!playing) { return; } if (fadeTime > 0) { fadeTime -= delta; if (fadeTime < 0) { fadeTime = 0; if (stopAfterFade) { stop(); return; } } float offset = (fadeEndGain - fadeStartGain) * (1 - (fadeTime / (float)fadeDuration)); setVolume(fadeStartGain + offset); } } /** * Seeks to a position in the music. For streaming music, seeking before the current position causes * the stream to be reloaded. * * @param position Position in seconds. * @return True if the seek was successful */ public boolean setPosition(float position) { if (playing) { requiredPosition = -1; positioning = true; playing = false; boolean result = sound.setPosition(position); playing = true; positioning = false; return result; } else { requiredPosition = position; return false; } } /** * The position into the sound thats being played * * @return The current position in seconds. */ public float getPosition () { return sound.getPosition(); } }
/* * Copyright (c) 2005-2013 Jyoti Parwatikar * and Washington University in St. Louis * * 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. * */ /* * File: Axis.java * Author: Jyoti Parwatikar * Email: jp@arl.wustl.edu * Organization: Washington University * * Derived from: none * * Date Created: 10/23/2003 * * Description: * * Modification History: * */ import java.awt.*; import javax.swing.*; //inner class for Axis public abstract class Axis extends JPanel { protected float spaceBetweenDivs; protected boolean isXAxis; protected Graph graph; protected int numberOfDivs; protected int left; protected int right; protected int top; protected int bottom; protected int units = Units.UNKNOWN; protected Arrow arrow = null; protected boolean hasArrow = false; protected FontMetrics fontMetrics = null; private boolean needsUpdate = false; //inner Division class draws the division and the label public class Division { public final int LEFT = 0; public final int CENTER = 1; public final int RIGHT = 2; private String label = null; private int justification = RIGHT; private int markerWidth = 5; private int position = 0; private int length = 8; private int half_length = 4; public Division(String lbl, int p) { setDimensions(lbl, p); } public void setLabel(String lbl) { label = lbl; if (fontMetrics != null) { length = fontMetrics.stringWidth(label); half_length = (int)(length/2); } } public void setDimensions(int p) { position = p; } public void setDimensions(String lbl, int p) { setLabel(lbl); position = p; } public void drawDivision(Graphics g) { if (isXAxis) { if ((position <= getMaxCoordinate()) || (position >= getMinCoordinate())) { g.drawLine(position, top, position, top + markerWidth); //add text: number += divunit g.drawString(label, (position - half_length), top + 25); } } else { if ((position >= getMaxCoordinate()) || (position <= getMinCoordinate())) //this is because origin is in top left { g.drawLine(right, position, right - markerWidth, position); //add text: number += divunit g.drawString(label, (right - length - 5), position + 3); } } } public void setMarkerWidth(int w) { markerWidth = w;} public int getLength() { return length;} public int compareTo(String id) { return (label.compareTo(id));} } //inner Arrow class public static class Arrow extends Polygon { public Arrow(int h, int w, Point c, boolean isVert) // height, width, center, points up or right { super(); double w_2 = w/2; if (isVert) { addPoint((int)(c.getX() - w_2), (int)c.getY()); addPoint((int)(c.getX() + w_2), (int)c.getY()); addPoint((int)c.getX(), (int)(c.getY() - h)); } else { addPoint((int)c.getX(), (int)(c.getY() - w_2)); addPoint((int)c.getX(), (int)(c.getY() + w_2)); addPoint((int)(c.getX() + h), (int)c.getY()); } } } //end inner Arrow class //start inner Label class public static class Label extends JPanel { private String lbl_text; private boolean isHorizontal = true; private FontMetrics fm = null; public Label(String txt, boolean isX) { this(txt,isX,12);} public Label(String txt, boolean isX, int fsize) { super(); setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); this.setFont(new Font("Dialog", Font.BOLD, fsize)); setForeground(new Color(102, 102, 153)); lbl_text = txt; isHorizontal = isX; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; //if (fm == null) // { // fm = g.getFontMetrics(); // if (!isHorizontal) setPreferredSize(new Dimension((fm.getAscent() + fm.getDescent() + 5), (fm.getStringWidth(lbl_text) + 5))); // } //g2.setFont(new Font("Dialog", Font.PLAIN, 14)); if (!isHorizontal) g2.rotate(Math.toRadians(90)); g2.drawString(lbl_text, 0,0); } public String getText() { return lbl_text;} public void setText(String txt) { lbl_text = txt;} } //end inner Label class //start Axis class public Axis(Graph g, boolean xory) { graph = g; isXAxis = xory; setFont(new Font("Dialog", Font.BOLD, g.monitorManager.getAxisNFontSize()));//9)); if (isXAxis) { setBorder(BorderFactory.createEmptyBorder(2,5,2,11)); } else { setPreferredSize(new Dimension(40,50)); setBorder(BorderFactory.createEmptyBorder(11,2,5,2)); } } public int length() { if (isXAxis) return (right - left); else return (bottom - top); } protected void updateBounds() { Insets insets = getInsets(); left = insets.left; right = getWidth() - insets.right; top = insets.top; bottom = getHeight() - insets.bottom; } protected void drawMainLine(Graphics g) { if (isXAxis) { g.drawLine(left, top, right, top); if (hasArrow) { arrow = new Arrow(8, 8, new Point(right,top), false); g.drawPolygon(arrow); } } else { g.drawLine(right, top, right, bottom); if (hasArrow) { arrow = new Arrow(8, 8, new Point(right,top), true); g.drawPolygon(arrow); } } } public int getNumberOfDivs() { return numberOfDivs; } public float getSpaceBetweenDivs() { return spaceBetweenDivs; } public int getMinCoordinate()//returns the smallest coordinate for this axis { if (isXAxis) return left; else return bottom; } public int getMaxCoordinate()//returns the largest coordinate for this axis { if (isXAxis) return right; else return top; } public abstract int getCoordinate(double value); //translates a value into a coordinate on the axis public abstract void updateDimensions(); //should set the numberOfDivs and spaceBetweenDivs atleast //and call updateBounds to set left,right,top,bottom public abstract double getValue(int coord); public int getUnits() { return units;} public void setUnits(int u) { units = u;} public void setArrow(boolean b) { hasArrow = b; if (b) { if (isXAxis) setBorder(BorderFactory.createEmptyBorder(5,5,5,11)); else setBorder(BorderFactory.createEmptyBorder(11,5,5,5)); } else { if (isXAxis) setBorder(BorderFactory.createEmptyBorder(2,5,2,11)); else setBorder(BorderFactory.createEmptyBorder(11,2,5,2)); } } public void setFont(Font f) { super.setFont(f); fontMetrics = null; } public void paintComponent(Graphics g) { if (needsUpdate) { updateDimensions(); needsUpdate = false; } super.paintComponent(g); drawMainLine(g); if (fontMetrics == null) fontMetrics = g.getFontMetrics(); } public void setUpdateDimensions(boolean b) { needsUpdate = b;} //should set to true instead of calling updateDimensions public boolean getUpdateDimensions() { return needsUpdate;} }
/* * RandomGUID * @version 1.2.1 11/05/02 * @author Marc A. Mnich * * From www.JavaExchange.com, Open Software licensing * * 11/05/02 -- Performance enhancement from Mike Dubman. * Moved InetAddr.getLocal to static block. Mike has measured * a 10 fold improvement in run time. * 01/29/02 -- Bug fix: Improper seeding of nonsecure Random object * caused duplicate GUIDs to be produced. Random object * is now only created once per JVM. * 01/19/02 -- Modified random seeding and added new constructor * to allow secure random feature. * 01/14/02 -- Added random function seeding with JVM run time * */ package edu.isi.karma.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; /* * In the multitude of java GUID generators, I found none that * guaranteed randomness. GUIDs are guaranteed to be globally unique * by using ethernet MACs, IP addresses, time elements, and sequential * numbers. GUIDs are not expected to be random and most often are * easy/possible to guess given a sample from a given generator. * SQL Server, for example generates GUID that are unique but * sequencial within a given instance. * * GUIDs can be used as security devices to hide things such as * files within a filesystem where listings are unavailable (e.g. files * that are served up from a Web server with indexing turned off). * This may be desireable in cases where standard authentication is not * appropriate. In this scenario, the RandomGUIDs are used as directories. * Another example is the use of GUIDs for primary keys in a database * where you want to ensure that the keys are secret. Random GUIDs can * then be used in a URL to prevent hackers (or users) from accessing * records by guessing or simply by incrementing sequential numbers. * * There are many other possiblities of using GUIDs in the realm of * security and encryption where the element of randomness is important. * This class was written for these purposes but can also be used as a * general purpose GUID generator as well. * * RandomGUID generates truly random GUIDs by using the system's * IP address (name/IP), system time in milliseconds (as an integer), * and a very large random number joined together in a single String * that is passed through an MD5 hash. The IP address and system time * make the MD5 seed globally unique and the random number guarantees * that the generated GUIDs will have no discernable pattern and * cannot be guessed given any number of previously generated GUIDs. * It is generally not possible to access the seed information (IP, time, * random number) from the resulting GUIDs as the MD5 hash algorithm * provides one way encryption. * * ----> Security of RandomGUID: <----- * RandomGUID can be called one of two ways -- with the basic java Random * number generator or a cryptographically strong random generator * (SecureRandom). The choice is offered because the secure random * generator takes about 3.5 times longer to generate its random numbers * and this performance hit may not be worth the added security * especially considering the basic generator is seeded with a * cryptographically strong random seed. * * Seeding the basic generator in this way effectively decouples * the random numbers from the time component making it virtually impossible * to predict the random number component even if one had absolute knowledge * of the System time. Thanks to Ashutosh Narhari for the suggestion * of using the static method to prime the basic random generator. * * Using the secure random option, this class compies with the statistical * random number generator tests specified in FIPS 140-2, Security * Requirements for Cryptographic Modules, secition 4.9.1. * * I converted all the pieces of the seed to a String before handing * it over to the MD5 hash so that you could print it out to make * sure it contains the data you expect to see and to give a nice * warm fuzzy. If you need better performance, you may want to stick * to byte[] arrays. * * I believe that it is important that the algorithm for * generating random GUIDs be open for inspection and modification. * This class is free for all uses. * * * - Marc */ public class RandomGUID extends Object { public String valueBeforeMD5 = ""; public String valueAfterMD5 = ""; private static Random myRand; private static SecureRandom mySecureRand; private static Logger logger = LoggerFactory.getLogger(RandomGUID.class); private static String s_id; /* * Static block to take care of one time secureRandom seed. * It takes a few seconds to initialize SecureRandom. You might * want to consider removing this static block or replacing * it with a "time since first loaded" seed to reduce this time. * This block will run only once per JVM instance. */ static { mySecureRand = new SecureRandom(); long secureInitializer = mySecureRand.nextLong(); myRand = new Random(secureInitializer); try { s_id = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { logger.warn(e.getMessage()); new LogStackTrace(e, logger); } } /* * Default constructor. With no specification of security option, * this constructor defaults to lower security, high performance. */ public RandomGUID() { getRandomGUID(false); } /* * Constructor with security option. Setting secure true * enables each random number generated to be cryptographically * strong. Secure false defaults to the standard Random function seeded * with a single cryptographically strong random number. */ public RandomGUID(boolean secure) { getRandomGUID(secure); } /* * Method to generate the random GUID */ private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Error: " + e); logger.warn(e.getMessage()); new LogStackTrace(e, logger); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } // This StringBuffer can be a long as you need; the MD5 // hash will always return 128 bits. You can change // the seed to include anything you want here. // You could even stream a file through the MD5 making // the odds of guessing it at least as great as that // of guessing the contents of the file! sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { logger.error("Error:" + e); logger.warn(e.getMessage()); new LogStackTrace(e, logger); } } /* * Convert to the standard format for GUID * (Useful for SQL Server UniqueIdentifiers, etc.) * Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6 */ public String toString() { String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); } /* * Demonstration and self test of class */ public static void main(String args[]) { for (int i=0; i< 100; i++) { RandomGUID myGUID = new RandomGUID(); logger.info("Seeding String=" + myGUID.valueBeforeMD5); logger.info("rawGUID=" + myGUID.valueAfterMD5); logger.info("RandomGUID=" + myGUID.toString()); } } }
package org.geoserver.shell; import it.geosolutions.geoserver.rest.GeoServerRESTPublisher; import it.geosolutions.geoserver.rest.HTTPUtils; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliAvailabilityIndicator; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.stereotype.Component; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.net.URL; @Component public class GeoserverCommands implements CommandMarker { @Autowired private Geoserver geoserver; public void setGeoserver(Geoserver gs) { this.geoserver = gs; } @CliAvailabilityIndicator({"geoserver reset", "geoserver reload", "geoserver backup", "geoserver restore", "geoserver verbose set", "geoserver show", "geoserver getmap", "geoserver getfeature", "geoserver getlegend" }) public boolean isCommandAvailable() { return geoserver.isSet(); } @CliCommand(value = "geoserver set", help = "Set the url, user, and password for Geoserver.") public boolean set( @CliOption(key = "url", mandatory = true, help = "The url") String url, @CliOption(key = "user", mandatory = false, help = "The user name", unspecifiedDefaultValue = "admin") String user, @CliOption(key = "password", mandatory = false, help = "The password", unspecifiedDefaultValue = "geoserver") String password ) { geoserver.setUrl(url); geoserver.setUser(user); geoserver.setPassword(password); // Ping URL with username and password String response = HTTPUtils.get(geoserver.getUrl() + "/rest/about/versions.xml", geoserver.getUser(), geoserver.getPassword()); return response != null; } @CliCommand(value = "geoserver verbose set", help = "Show the url, user, and password for Geoserver.") public boolean verbose(@CliOption(key = "value", mandatory = true, help = "The verbosity value") boolean verbose) { geoserver.setVerbose(verbose); return true; } @CliCommand(value = "geoserver show", help = "Show the url, user, and password for Geoserver.") public String show() { return geoserver.getUrl() + " " + geoserver.getUser() + " " + geoserver.getPassword(); } @CliCommand(value = "geoserver reset", help = "Reset Geoserver's configuration.") public boolean reset() { GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword()); return publisher.reset(); } @CliCommand(value = "geoserver reload", help = "Reload Geoserver's configuration.") public boolean reload() { GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword()); return publisher.reload(); } @CliCommand(value = "geoserver backup", help = "Backup Geoserver's configuration.") public boolean backup( @CliOption(key = "directory", mandatory = true, help = "The backup ") String backupDir, @CliOption(key = "includedata", mandatory = false, unspecifiedDefaultValue = "false", help = "The include data flag") boolean includeData, @CliOption(key = "includegwc", mandatory = false, unspecifiedDefaultValue = "false", help = "The include GWC flag") boolean includeGwc, @CliOption(key = "includelog", mandatory = false, unspecifiedDefaultValue = "false", help = "The include log files flag") boolean includeLog ) { GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword()); String result = publisher.backup(backupDir, includeData, includeGwc, includeLog); return result != null; } @CliCommand(value = "geoserver restore", help = "Restore Geoserver's configuration from a backup directory.") public boolean restore( @CliOption(key = "directory", mandatory = true, help = "The backup ") String backupDir ) { GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(geoserver.getUrl(), geoserver.getUser(), geoserver.getPassword()); String result = publisher.restore(backupDir); return result != null; } @CliCommand(value = "geoserver getmap", help = "Get a map from the WMS service.") public String getMap( @CliOption(key = "layers", mandatory = true, help = "The layers to display") String layers, @CliOption(key = "file", mandatory = false, unspecifiedDefaultValue = "map.png", help = "The file name") String fileName, @CliOption(key = "width", mandatory = false, help = "The width") String width, @CliOption(key = "height", mandatory = false, help = "The height") String height, @CliOption(key = "format", mandatory = false, help = "The format") String format, @CliOption(key = "srs", mandatory = false, help = "The srs") String srs, @CliOption(key = "bbox", mandatory = false, help = "The bbox") String bbox ) throws Exception { String url = geoserver.getUrl() + "/wms/reflect?layers=" + URLUtil.encode(layers); if (width != null) { url += "&width=" + width; } if (height != null) { url += "&height=" + height; } if (srs != null) { url += "&srs=" + srs; } if (bbox != null) { url += "&bbox=" + bbox; } String formatMimeType = "image/png"; String formatImageIO = "png"; if (format != null) { if (format.equalsIgnoreCase("jpeg") || format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("image/jpeg") || format.equalsIgnoreCase("image/jpg")) { formatMimeType = "image/jpeg"; formatImageIO = "jpeg"; } url += "&format=" + formatMimeType; } String message = fileName; BufferedImage image = ImageIO.read(new URL(url)); if (image != null) { ImageIO.write(image, formatImageIO, new File(fileName)); } else { message = "Unable to read URL (" + url + ")"; } return message; } @CliCommand(value = "geoserver getfeature", help = "Get features from the WMF service.") public String getFeature( @CliOption(key = "typeName", mandatory = true, help = "The type name to query") String typeName, @CliOption(key = "version", unspecifiedDefaultValue = "1.0.0", mandatory = false, help = "The version") String version, @CliOption(key = "maxfeatures", mandatory = false, help = "The version") String maxFeatures, @CliOption(key = "sortby", mandatory = false, help = "The version") String sortBy, @CliOption(key = "propertyname", mandatory = false, help = "The version") String propertyName, @CliOption(key = "featureid", mandatory = false, help = "The version") String featureID, @CliOption(key = "bbox", mandatory = false, help = "The version") String bbox, @CliOption(key = "srs", mandatory = false, help = "The version") String srsName, @CliOption(key = "format", unspecifiedDefaultValue = "csv", mandatory = false, help = "The version") String outputFormat, @CliOption(key = "cql", mandatory = false, help = "The CQL query") String cql ) throws Exception { String url = geoserver.getUrl() + "/wfs?service=wfs&version=" + version + "&request=GetFeature&typeName=" + URLUtil.encode(typeName); url += "&outputFormat=" + outputFormat; if (maxFeatures != null) { url += "&maxFeatures=" + maxFeatures; } if (sortBy != null) { url += "&sortBy=" + sortBy; } if (propertyName != null) { url += "&propertyName=" + propertyName; } if (featureID != null) { url += "&featureID=" + featureID; } if (bbox != null) { url += "&bbox=" + bbox; } if (srsName != null) { url += "&srsName=" + srsName; } if (cql != null) { url += "&cql_filter=" + cql; } return IOUtils.toString(new URL(url)); } @CliCommand(value = "geoserver getlegend", help = "Get a legend from the WMS service.") public String getLegend( @CliOption(key = "layer", mandatory = true, help = "The layer") String layer, @CliOption(key = "style", mandatory = false, help = "The style") String style, @CliOption(key = "featuretype", mandatory = false, help = "The feature type") String featureType, @CliOption(key = "rule", mandatory = false, help = "The rule") String rule, @CliOption(key = "scale", mandatory = false, help = "The scale") String scale, @CliOption(key = "file", mandatory = false, unspecifiedDefaultValue = "legend.png", help = "The file name") String fileName, @CliOption(key = "width", mandatory = false, help = "The width") String width, @CliOption(key = "height", mandatory = false, help = "The height") String height, @CliOption(key = "format", mandatory = false, unspecifiedDefaultValue = "png", help = "The format") String format ) throws Exception { String url = geoserver.getUrl() + "/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0"; url += "&LAYER=" + URLUtil.encode(layer); if (width != null) { url += "&WIDTH=" + width; } if (height != null) { url += "&HEIGHT=" + height; } if (style != null) { url += "&STYLE=" + style; } if (featureType != null) { url += "&FEATURETYPE=" + featureType; } if (rule != null) { url += "&RULE=" + rule; } if (scale != null) { url += "&SCALE=" + scale; } String formatMimeType = "image/png"; String formatImageIO = "png"; if (format.equalsIgnoreCase("jpeg") || format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("image/jpeg") || format.equalsIgnoreCase("image/jpg")) { formatMimeType = "image/jpeg"; formatImageIO = "jpeg"; } url += "&FORMAT=" + formatMimeType; String message = fileName; BufferedImage image = ImageIO.read(new URL(url)); if (image != null) { ImageIO.write(image, formatImageIO, new File(fileName)); } else { message = "Unable to read URL (" + url + ")"; } return message; } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.bodycomplex.implementation; import retrofit2.Retrofit; import fixtures.bodycomplex.Polymorphicrecursives; import com.google.common.reflect.TypeToken; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.ServiceResponseBuilder; import com.microsoft.rest.ServiceResponseCallback; import com.microsoft.rest.Validator; import fixtures.bodycomplex.models.ErrorException; import fixtures.bodycomplex.models.Fish; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.PUT; import retrofit2.Response; /** * An instance of this class provides access to all the operations defined * in Polymorphicrecursives. */ public final class PolymorphicrecursivesImpl implements Polymorphicrecursives { /** The Retrofit service to perform REST calls. */ private PolymorphicrecursivesService service; /** The service client containing this operation class. */ private AutoRestComplexTestServiceImpl client; /** * Initializes an instance of Polymorphicrecursives. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public PolymorphicrecursivesImpl(Retrofit retrofit, AutoRestComplexTestServiceImpl client) { this.service = retrofit.create(PolymorphicrecursivesService.class); this.client = client; } /** * The interface defining all the services for Polymorphicrecursives to be * used by Retrofit to perform actually REST calls. */ interface PolymorphicrecursivesService { @Headers("Content-Type: application/json; charset=utf-8") @GET("complex/polymorphicrecursive/valid") Call<ResponseBody> getValid(); @Headers("Content-Type: application/json; charset=utf-8") @PUT("complex/polymorphicrecursive/valid") Call<ResponseBody> putValid(@Body Fish complexBody); } /** * Get complex types that are polymorphic and have recursive references. * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @return the Fish object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse<Fish> getValid() throws ErrorException, IOException { Call<ResponseBody> call = service.getValid(); return getValidDelegate(call.execute()); } /** * Get complex types that are polymorphic and have recursive references. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ public ServiceCall getValidAsync(final ServiceCallback<Fish> serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Call<ResponseBody> call = service.getValid(); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback<Fish>(serviceCallback) { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { serviceCallback.success(getValidDelegate(response)); } catch (ErrorException | IOException exception) { serviceCallback.failure(exception); } } }); return serviceCall; } private ServiceResponse<Fish> getValidDelegate(Response<ResponseBody> response) throws ErrorException, IOException { return new ServiceResponseBuilder<Fish, ErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken<Fish>() { }.getType()) .registerError(ErrorException.class) .build(response); } /** * Put complex types that are polymorphic and have recursive references. * * @param complexBody Please put a salmon that looks like this: { "fishtype": "salmon", "species": "king", "length": 1, "age": 1, "location": "alaska", "iswild": true, "siblings": [ { "fishtype": "shark", "species": "predator", "length": 20, "age": 6, "siblings": [ { "fishtype": "salmon", "species": "coho", "length": 2, "age": 2, "location": "atlantic", "iswild": true, "siblings": [ { "fishtype": "shark", "species": "predator", "length": 20, "age": 6 }, { "fishtype": "sawshark", "species": "dangerous", "length": 10, "age": 105 } ] }, { "fishtype": "sawshark", "species": "dangerous", "length": 10, "age": 105 } ] }, { "fishtype": "sawshark", "species": "dangerous", "length": 10, "age": 105 } ] } * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse<Void> putValid(Fish complexBody) throws ErrorException, IOException, IllegalArgumentException { if (complexBody == null) { throw new IllegalArgumentException("Parameter complexBody is required and cannot be null."); } Validator.validate(complexBody); Call<ResponseBody> call = service.putValid(complexBody); return putValidDelegate(call.execute()); } /** * Put complex types that are polymorphic and have recursive references. * * @param complexBody Please put a salmon that looks like this: { "fishtype": "salmon", "species": "king", "length": 1, "age": 1, "location": "alaska", "iswild": true, "siblings": [ { "fishtype": "shark", "species": "predator", "length": 20, "age": 6, "siblings": [ { "fishtype": "salmon", "species": "coho", "length": 2, "age": 2, "location": "atlantic", "iswild": true, "siblings": [ { "fishtype": "shark", "species": "predator", "length": 20, "age": 6 }, { "fishtype": "sawshark", "species": "dangerous", "length": 10, "age": 105 } ] }, { "fishtype": "sawshark", "species": "dangerous", "length": 10, "age": 105 } ] }, { "fishtype": "sawshark", "species": "dangerous", "length": 10, "age": 105 } ] } * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ public ServiceCall putValidAsync(Fish complexBody, final ServiceCallback<Void> serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } if (complexBody == null) { serviceCallback.failure(new IllegalArgumentException("Parameter complexBody is required and cannot be null.")); return null; } Validator.validate(complexBody, serviceCallback); Call<ResponseBody> call = service.putValid(complexBody); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback<Void>(serviceCallback) { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { serviceCallback.success(putValidDelegate(response)); } catch (ErrorException | IOException exception) { serviceCallback.failure(exception); } } }); return serviceCall; } private ServiceResponse<Void> putValidDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException { return new ServiceResponseBuilder<Void, ErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .registerError(ErrorException.class) .build(response); } }
/************************************************************************** Exchange Web Services Java API Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************/ package microsoft.exchange.webservices.data; import java.util.EnumSet; /** * Represents the schema for meeting requests. */ @Schema public class MeetingRequestSchema extends MeetingMessageSchema { /** * Field URIs for MeetingRequest. */ private static interface FieldUris { /** * The Meeting request type. */ String MeetingRequestType = "meetingRequest:MeetingRequestType"; /** * The Intended free busy status. */ String IntendedFreeBusyStatus = "meetingRequest:IntendedFreeBusyStatus"; } /** * Defines the MeetingRequestType property. */ public static final PropertyDefinition MeetingRequestType = new GenericPropertyDefinition<MeetingRequestType>( MeetingRequestType.class, XmlElementNames.MeetingRequestType, FieldUris.MeetingRequestType, ExchangeVersion.Exchange2007_SP1); /** * Defines the IntendedFreeBusyStatus property. */ public static final PropertyDefinition IntendedFreeBusyStatus = new GenericPropertyDefinition<LegacyFreeBusyStatus>( LegacyFreeBusyStatus.class, XmlElementNames.IntendedFreeBusyStatus, FieldUris.IntendedFreeBusyStatus, EnumSet .of(PropertyDefinitionFlags.CanFind), ExchangeVersion.Exchange2007_SP1); /** * Defines the Start property. */ public static final PropertyDefinition Start = AppointmentSchema.Start; /** * Defines the End property. */ public static final PropertyDefinition End = AppointmentSchema.End; /** * Defines the OriginalStart property. */ public static final PropertyDefinition OriginalStart = AppointmentSchema.OriginalStart; /** * Defines the IsAllDayEvent property. */ public static final PropertyDefinition IsAllDayEvent = AppointmentSchema.IsAllDayEvent; /** * Defines the LegacyFreeBusyStatus property. */ public static final PropertyDefinition LegacyFreeBusyStatus = AppointmentSchema.LegacyFreeBusyStatus; /** * Defines the Location property. */ public static final PropertyDefinition Location = AppointmentSchema.Location; /** * Defines the When property. */ public static final PropertyDefinition When = AppointmentSchema.When; /** * Defines the IsMeeting property. */ public static final PropertyDefinition IsMeeting = AppointmentSchema.IsMeeting; /** * Defines the IsCancelled property. */ public static final PropertyDefinition IsCancelled = AppointmentSchema.IsCancelled; /** * Defines the IsRecurring property. */ public static final PropertyDefinition IsRecurring = AppointmentSchema.IsRecurring; /** * Defines the MeetingRequestWasSent property. */ public static final PropertyDefinition MeetingRequestWasSent = AppointmentSchema.MeetingRequestWasSent; /** * Defines the AppointmentType property. */ public static final PropertyDefinition AppointmentType = AppointmentSchema.AppointmentType; /** * Defines the MyResponseType property. */ public static final PropertyDefinition MyResponseType = AppointmentSchema.MyResponseType; /** * Defines the Organizer property. */ public static final PropertyDefinition Organizer = AppointmentSchema.Organizer; /** * Defines the RequiredAttendees property. */ public static final PropertyDefinition RequiredAttendees = AppointmentSchema.RequiredAttendees; /** * Defines the OptionalAttendees property. */ public static final PropertyDefinition OptionalAttendees = AppointmentSchema.OptionalAttendees; /** * Defines the Resources property. */ public static final PropertyDefinition Resources = AppointmentSchema.Resources; /** * Defines the ConflictingMeetingCount property. */ public static final PropertyDefinition ConflictingMeetingCount = AppointmentSchema.ConflictingMeetingCount; /** * Defines the AdjacentMeetingCount property. */ public static final PropertyDefinition AdjacentMeetingCount = AppointmentSchema.AdjacentMeetingCount; /** * Defines the ConflictingMeetings property. */ public static final PropertyDefinition ConflictingMeetings = AppointmentSchema.ConflictingMeetings; /** * Defines the AdjacentMeetings property. */ public static final PropertyDefinition AdjacentMeetings = AppointmentSchema.AdjacentMeetings; /** * Defines the Duration property. */ public static final PropertyDefinition Duration = AppointmentSchema.Duration; /** * Defines the TimeZone property. */ public static final PropertyDefinition TimeZone = AppointmentSchema.TimeZone; /** * Defines the AppointmentReplyTime property. */ public static final PropertyDefinition AppointmentReplyTime = AppointmentSchema.AppointmentReplyTime; /** * Defines the AppointmentSequenceNumber property. */ public static final PropertyDefinition AppointmentSequenceNumber = AppointmentSchema.AppointmentSequenceNumber; /** * Defines the AppointmentState property. */ public static final PropertyDefinition AppointmentState = AppointmentSchema.AppointmentState; /** * Defines the Recurrence property. */ public static final PropertyDefinition Recurrence = AppointmentSchema.Recurrence; /** * Defines the FirstOccurrence property. */ public static final PropertyDefinition FirstOccurrence = AppointmentSchema.FirstOccurrence; /** * Defines the LastOccurrence property. */ public static final PropertyDefinition LastOccurrence = AppointmentSchema.LastOccurrence; /** * Defines the ModifiedOccurrences property. */ public static final PropertyDefinition ModifiedOccurrences = AppointmentSchema.ModifiedOccurrences; /** * Defines the Duration property. */ public static final PropertyDefinition DeletedOccurrences = AppointmentSchema.DeletedOccurrences; /** * Defines the MeetingTimeZone property. */ static final PropertyDefinition MeetingTimeZone = AppointmentSchema.MeetingTimeZone; /** * Defines the StartTimeZone property. */ public static final PropertyDefinition StartTimeZone = AppointmentSchema.StartTimeZone; /** * Defines the EndTimeZone property. */ public static final PropertyDefinition EndTimeZone = AppointmentSchema.EndTimeZone; /** * Defines the ConferenceType property. */ public static final PropertyDefinition ConferenceType = AppointmentSchema.ConferenceType; /** * Defines the AllowNewTimeProposal property. */ public static final PropertyDefinition AllowNewTimeProposal = AppointmentSchema.AllowNewTimeProposal; /** * Defines the IsOnlineMeeting property. */ public static final PropertyDefinition IsOnlineMeeting = AppointmentSchema.IsOnlineMeeting; /** * Defines the MeetingWorkspaceUrl property. */ public static final PropertyDefinition MeetingWorkspaceUrl = AppointmentSchema.MeetingWorkspaceUrl; /** * Defines the NetShowUrl property. */ public static final PropertyDefinition NetShowUrl = AppointmentSchema.NetShowUrl; /** * This must be after the declaration of property definitions. */ protected static final MeetingRequestSchema Instance = new MeetingRequestSchema(); /** * Registers properties. * <p/> * IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the * same order as they are defined in types.xsd) */ @Override protected void registerProperties() { super.registerProperties(); this.registerProperty(MeetingRequestType); this.registerProperty(IntendedFreeBusyStatus); this.registerProperty(Start); this.registerProperty(End); this.registerProperty(OriginalStart); this.registerProperty(IsAllDayEvent); this.registerProperty(LegacyFreeBusyStatus); this.registerProperty(Location); this.registerProperty(When); this.registerProperty(IsMeeting); this.registerProperty(IsCancelled); this.registerProperty(IsRecurring); this.registerProperty(MeetingRequestWasSent); this.registerProperty(AppointmentType); this.registerProperty(MyResponseType); this.registerProperty(Organizer); this.registerProperty(RequiredAttendees); this.registerProperty(OptionalAttendees); this.registerProperty(Resources); this.registerProperty(ConflictingMeetingCount); this.registerProperty(AdjacentMeetingCount); this.registerProperty(ConflictingMeetings); this.registerProperty(AdjacentMeetings); this.registerProperty(Duration); this.registerProperty(TimeZone); this.registerProperty(AppointmentReplyTime); this.registerProperty(AppointmentSequenceNumber); this.registerProperty(AppointmentState); this.registerProperty(Recurrence); this.registerProperty(FirstOccurrence); this.registerProperty(LastOccurrence); this.registerProperty(ModifiedOccurrences); this.registerProperty(DeletedOccurrences); this.registerInternalProperty(MeetingTimeZone); this.registerProperty(StartTimeZone); this.registerProperty(EndTimeZone); this.registerProperty(ConferenceType); this.registerProperty(AllowNewTimeProposal); this.registerProperty(IsOnlineMeeting); this.registerProperty(MeetingWorkspaceUrl); this.registerProperty(NetShowUrl); } /** * Initializes a new instance of the class. */ protected MeetingRequestSchema() { super(); } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.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 org.pentaho.di.job.entries.deletefiles; import static org.pentaho.di.job.entry.validator.AbstractFileValidator.putVariableSpace; import static org.pentaho.di.job.entry.validator.AndValidator.putValidators; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileExistsValidator; import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notNullValidator; import java.io.IOException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSelectInfo; import org.apache.commons.vfs2.FileSelector; import org.apache.commons.vfs2.FileType; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Result; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.Job; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryBase; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.job.entry.validator.ValidatorContext; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.resource.ResourceEntry; import org.pentaho.di.resource.ResourceEntry.ResourceType; import org.pentaho.di.resource.ResourceReference; import org.pentaho.metastore.api.IMetaStore; import org.w3c.dom.Node; /** * This defines a 'delete files' job entry. * * @author Samatar Hassan * @since 06-05-2007 */ public class JobEntryDeleteFiles extends JobEntryBase implements Cloneable, JobEntryInterface { private static Class<?> PKG = JobEntryDeleteFiles.class; // for i18n purposes, needed by Translator2!! public boolean argFromPrevious; public boolean includeSubfolders; public String[] arguments; public String[] filemasks; public JobEntryDeleteFiles( String n ) { super( n, "" ); argFromPrevious = false; arguments = null; includeSubfolders = false; } public JobEntryDeleteFiles() { this( "" ); } public Object clone() { JobEntryDeleteFiles je = (JobEntryDeleteFiles) super.clone(); return je; } public String getXML() { StringBuilder retval = new StringBuilder( 300 ); retval.append( super.getXML() ); retval.append( " " ).append( XMLHandler.addTagValue( "arg_from_previous", argFromPrevious ) ); retval.append( " " ).append( XMLHandler.addTagValue( "include_subfolders", includeSubfolders ) ); retval.append( " <fields>" ).append( Const.CR ); if ( arguments != null ) { for ( int i = 0; i < arguments.length; i++ ) { retval.append( " <field>" ).append( Const.CR ); retval.append( " " ).append( XMLHandler.addTagValue( "name", arguments[i] ) ); retval.append( " " ).append( XMLHandler.addTagValue( "filemask", filemasks[i] ) ); retval.append( " </field>" ).append( Const.CR ); } } retval.append( " </fields>" ).append( Const.CR ); return retval.toString(); } public void loadXML( Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep, IMetaStore metaStore ) throws KettleXMLException { try { super.loadXML( entrynode, databases, slaveServers ); argFromPrevious = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "arg_from_previous" ) ); includeSubfolders = "Y".equalsIgnoreCase( XMLHandler.getTagValue( entrynode, "include_subfolders" ) ); Node fields = XMLHandler.getSubNode( entrynode, "fields" ); // How many field arguments? int nrFields = XMLHandler.countNodes( fields, "field" ); arguments = new String[nrFields]; filemasks = new String[nrFields]; // Read them all... for ( int i = 0; i < nrFields; i++ ) { Node fnode = XMLHandler.getSubNodeByNr( fields, "field", i ); arguments[i] = XMLHandler.getTagValue( fnode, "name" ); filemasks[i] = XMLHandler.getTagValue( fnode, "filemask" ); } } catch ( KettleXMLException xe ) { throw new KettleXMLException( BaseMessages.getString( PKG, "JobEntryDeleteFiles.UnableToLoadFromXml" ), xe ); } } public void loadRep( Repository rep, IMetaStore metaStore, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers ) throws KettleException { try { argFromPrevious = rep.getJobEntryAttributeBoolean( id_jobentry, "arg_from_previous" ); includeSubfolders = rep.getJobEntryAttributeBoolean( id_jobentry, "include_subfolders" ); // How many arguments? int argnr = rep.countNrJobEntryAttributes( id_jobentry, "name" ); arguments = new String[argnr]; filemasks = new String[argnr]; // Read them all... for ( int a = 0; a < argnr; a++ ) { arguments[a] = rep.getJobEntryAttributeString( id_jobentry, a, "name" ); filemasks[a] = rep.getJobEntryAttributeString( id_jobentry, a, "filemask" ); } } catch ( KettleException dbe ) { throw new KettleException( BaseMessages.getString( PKG, "JobEntryDeleteFiles.UnableToLoadFromRepo", String .valueOf( id_jobentry ) ), dbe ); } } public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_job ) throws KettleException { try { rep.saveJobEntryAttribute( id_job, getObjectId(), "arg_from_previous", argFromPrevious ); rep.saveJobEntryAttribute( id_job, getObjectId(), "include_subfolders", includeSubfolders ); // save the arguments... if ( arguments != null ) { for ( int i = 0; i < arguments.length; i++ ) { rep.saveJobEntryAttribute( id_job, getObjectId(), i, "name", arguments[i] ); rep.saveJobEntryAttribute( id_job, getObjectId(), i, "filemask", filemasks[i] ); } } } catch ( KettleDatabaseException dbe ) { throw new KettleException( BaseMessages.getString( PKG, "JobEntryDeleteFiles.UnableToSaveToRepo", String .valueOf( id_job ) ), dbe ); } } public Result execute( Result result, int nr ) throws KettleException { List<RowMetaAndData> rows = result.getRows(); RowMetaAndData resultRow = null; int NrErrFiles = 0; result.setResult( false ); result.setNrErrors( 1 ); if ( argFromPrevious ) { if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobEntryDeleteFiles.FoundPreviousRows", String .valueOf( ( rows != null ? rows.size() : 0 ) ) ) ); } } if ( argFromPrevious && rows != null ) // Copy the input row to the (command line) arguments { for ( int iteration = 0; iteration < rows.size() && !parentJob.isStopped(); iteration++ ) { resultRow = rows.get( iteration ); String args_previous = resultRow.getString( 0, null ); String fmasks_previous = resultRow.getString( 1, null ); // ok we can process this file/folder if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobEntryDeleteFiles.ProcessingRow", args_previous, fmasks_previous ) ); } if ( !ProcessFile( args_previous, fmasks_previous, parentJob ) ) { NrErrFiles++; } } } else if ( arguments != null ) { for ( int i = 0; i < arguments.length && !parentJob.isStopped(); i++ ) { // ok we can process this file/folder if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobEntryDeleteFiles.ProcessingArg", arguments[i], filemasks[i] ) ); } if ( !ProcessFile( arguments[i], filemasks[i], parentJob ) ) { NrErrFiles++; } } } if ( NrErrFiles == 0 ) { result.setResult( true ); result.setNrErrors( 0 ); } else { result.setNrErrors( NrErrFiles ); result.setResult( false ); } return result; } private boolean ProcessFile( String filename, String wildcard, Job parentJob ) { boolean rcode = false; FileObject filefolder = null; String realFilefoldername = environmentSubstitute( filename ); String realwildcard = environmentSubstitute( wildcard ); try { filefolder = KettleVFS.getFileObject( realFilefoldername, this ); if ( filefolder.exists() ) { // the file or folder exists if ( filefolder.getType() == FileType.FOLDER ) { // It's a folder if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobEntryDeleteFiles.ProcessingFolder", realFilefoldername ) ); // Delete Files } int Nr = filefolder.delete( new TextFileSelector( filefolder.toString(), realwildcard, parentJob ) ); if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobEntryDeleteFiles.TotalDeleted", String.valueOf( Nr ) ) ); } rcode = true; } else { // It's a file if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobEntryDeleteFiles.ProcessingFile", realFilefoldername ) ); } boolean deleted = filefolder.delete(); if ( !deleted ) { logError( BaseMessages.getString( PKG, "JobEntryDeleteFiles.CouldNotDeleteFile", realFilefoldername ) ); } else { if ( log.isBasic() ) { logBasic( BaseMessages.getString( PKG, "JobEntryDeleteFiles.FileDeleted", filename ) ); } rcode = true; } } } else { // File already deleted, no reason to try to delete it if ( log.isBasic() ) { logBasic( BaseMessages.getString( PKG, "JobEntryDeleteFiles.FileAlreadyDeleted", realFilefoldername ) ); } rcode = true; } } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "JobEntryDeleteFiles.CouldNotProcess", realFilefoldername, e .getMessage() ), e ); } finally { if ( filefolder != null ) { try { filefolder.close(); } catch ( IOException ex ) { // Ignore } } } return rcode; } private class TextFileSelector implements FileSelector { String fileWildcard = null; String sourceFolder = null; Job parentjob; public TextFileSelector( String sourcefolderin, String filewildcard, Job parentJob ) { if ( !Const.isEmpty( sourcefolderin ) ) { sourceFolder = sourcefolderin; } if ( !Const.isEmpty( filewildcard ) ) { fileWildcard = filewildcard; } parentjob = parentJob; } public boolean includeFile( FileSelectInfo info ) { boolean returncode = false; try { if ( !info.getFile().toString().equals( sourceFolder ) && !parentjob.isStopped() ) { // Pass over the Base folder itself String short_filename = info.getFile().getName().getBaseName(); if ( !info.getFile().getParent().equals( info.getBaseFolder() ) ) { // Not in the Base Folder..Only if include sub folders if ( includeSubfolders && ( info.getFile().getType() == FileType.FILE ) && GetFileWildcard( short_filename, fileWildcard ) ) { if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobEntryDeleteFiles.DeletingFile", info .getFile().toString() ) ); } returncode = true; } } else { // In the Base Folder... if ( ( info.getFile().getType() == FileType.FILE ) && GetFileWildcard( short_filename, fileWildcard ) ) { if ( log.isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobEntryDeleteFiles.DeletingFile", info .getFile().toString() ) ); } returncode = true; } } } } catch ( Exception e ) { log.logError( BaseMessages.getString( PKG, "JobDeleteFiles.Error.Exception.DeleteProcessError" ), BaseMessages .getString( PKG, "JobDeleteFiles.Error.Exception.DeleteProcess", info.getFile().toString(), e .getMessage() ) ); returncode = false; } return returncode; } public boolean traverseDescendents( FileSelectInfo info ) { return true; } } /********************************************************** * * @param selectedfile * @param wildcard * @return True if the selectedfile matches the wildcard **********************************************************/ private boolean GetFileWildcard( String selectedfile, String wildcard ) { boolean getIt = true; if ( !Const.isEmpty( wildcard ) ) { Pattern pattern = Pattern.compile( wildcard ); // First see if the file matches the regular expression! if ( pattern != null ) { Matcher matcher = pattern.matcher( selectedfile ); getIt = matcher.matches(); } } return getIt; } public void setIncludeSubfolders( boolean includeSubfolders ) { this.includeSubfolders = includeSubfolders; } public void setPrevious( boolean argFromPrevious ) { this.argFromPrevious = argFromPrevious; } public boolean evaluates() { return true; } public void check( List<CheckResultInterface> remarks, JobMeta jobMeta, VariableSpace space, Repository repository, IMetaStore metaStore ) { boolean res = andValidator().validate( this, "arguments", remarks, putValidators( notNullValidator() ) ); if ( !res ) { return; } ValidatorContext ctx = new ValidatorContext(); putVariableSpace( ctx, getVariables() ); putValidators( ctx, notNullValidator(), fileExistsValidator() ); for ( int i = 0; i < arguments.length; i++ ) { andValidator().validate( this, "arguments[" + i + "]", remarks, ctx ); } } public List<ResourceReference> getResourceDependencies( JobMeta jobMeta ) { List<ResourceReference> references = super.getResourceDependencies( jobMeta ); if ( arguments != null ) { ResourceReference reference = null; for ( int i = 0; i < arguments.length; i++ ) { String filename = jobMeta.environmentSubstitute( arguments[i] ); if ( reference == null ) { reference = new ResourceReference( this ); references.add( reference ); } reference.getEntries().add( new ResourceEntry( filename, ResourceType.FILE ) ); } } return references; } public boolean isArgFromPrevious() { return argFromPrevious; } public String[] getArguments() { return arguments; } public String[] getFilemasks() { return filemasks; } public boolean isIncludeSubfolders() { return includeSubfolders; } }
/* * Copyright (c) 2010-2013, MoPub Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of 'MoPub Inc.' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mopub.mobileads; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.webkit.WebViewDatabase; import android.widget.FrameLayout; import com.mopub.mobileads.factories.AdViewControllerFactory; import com.mopub.mobileads.factories.CustomEventBannerAdapterFactory; import java.util.*; import static com.mopub.mobileads.MoPubErrorCode.ADAPTER_NOT_FOUND; import static com.mopub.mobileads.util.ResponseHeader.CUSTOM_EVENT_DATA; import static com.mopub.mobileads.util.ResponseHeader.CUSTOM_EVENT_NAME; public class MoPubView extends FrameLayout { public interface BannerAdListener { public void onBannerLoaded(MoPubView banner); public void onBannerFailed(MoPubView banner, MoPubErrorCode errorCode); public void onBannerClicked(MoPubView banner); public void onBannerExpanded(MoPubView banner); public void onBannerCollapsed(MoPubView banner); } public enum LocationAwareness { LOCATION_AWARENESS_NORMAL, LOCATION_AWARENESS_TRUNCATED, LOCATION_AWARENESS_DISABLED } public static final String HOST = "ads.mopub.com"; public static final String HOST_FOR_TESTING = "testing.ads.mopub.com"; public static final String AD_HANDLER = "/m/ad"; public static final int DEFAULT_LOCATION_PRECISION = 6; protected AdViewController mAdViewController; protected CustomEventBannerAdapter mCustomEventBannerAdapter; private Context mContext; private BroadcastReceiver mScreenStateReceiver; private boolean mIsInForeground; private LocationAwareness mLocationAwareness; private boolean mPreviousAutorefreshSetting = false; private BannerAdListener mBannerAdListener; private OnAdWillLoadListener mOnAdWillLoadListener; private OnAdLoadedListener mOnAdLoadedListener; private OnAdFailedListener mOnAdFailedListener; private OnAdPresentedOverlayListener mOnAdPresentedOverlayListener; private OnAdClosedListener mOnAdClosedListener; private OnAdClickedListener mOnAdClickedListener; public MoPubView(Context context) { this(context, null); } public MoPubView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mIsInForeground = (getVisibility() == VISIBLE); mLocationAwareness = LocationAwareness.LOCATION_AWARENESS_NORMAL; setHorizontalScrollBarEnabled(false); setVerticalScrollBarEnabled(false); // There is a rare bug in Froyo/2.2 where creation of a WebView causes a // NullPointerException. (http://code.google.com/p/android/issues/detail?id=10789) // It happens when the WebView can't access the local file store to make a cache file. // Here, we'll work around it by trying to create a file store and then just go inert // if it's not accessible. if (WebViewDatabase.getInstance(context) == null) { Log.e("MoPub", "Disabling MoPub. Local cache file is inaccessible so MoPub will " + "fail if we try to create a WebView. Details of this Android bug found at:" + "http://code.google.com/p/android/issues/detail?id=10789"); return; } mAdViewController = AdViewControllerFactory.create(context, this); registerScreenStateBroadcastReceiver(); } private void registerScreenStateBroadcastReceiver() { if (mAdViewController == null) return; mScreenStateReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { if (mIsInForeground) { Log.d("MoPub", "Screen sleep with ad in foreground, disable refresh"); if (mAdViewController != null) { mPreviousAutorefreshSetting = mAdViewController.getAutorefreshEnabled(); mAdViewController.setAutorefreshEnabled(false); } } else { Log.d("MoPub", "Screen sleep but ad in background; " + "refresh should already be disabled"); } } else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) { if (mIsInForeground) { Log.d("MoPub", "Screen wake / ad in foreground, reset refresh"); if (mAdViewController != null) { mAdViewController.setAutorefreshEnabled(mPreviousAutorefreshSetting); } } else { Log.d("MoPub", "Screen wake but ad in background; don't enable refresh"); } } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); mContext.registerReceiver(mScreenStateReceiver, filter); } private void unregisterScreenStateBroadcastReceiver() { try { mContext.unregisterReceiver(mScreenStateReceiver); } catch (Exception IllegalArgumentException) { Log.d("MoPub", "Failed to unregister screen state broadcast receiver (never registered)."); } } public void loadAd() { if (mAdViewController != null) mAdViewController.loadAd(); } /* * Tears down the ad view: no ads will be shown once this method executes. The parent * Activity's onDestroy implementation must include a call to this method. */ public void destroy() { unregisterScreenStateBroadcastReceiver(); removeAllViews(); if (mAdViewController != null) { mAdViewController.cleanup(); mAdViewController = null; } if (mCustomEventBannerAdapter != null) { mCustomEventBannerAdapter.invalidate(); mCustomEventBannerAdapter = null; } } Integer getAdTimeoutDelay() { return (mAdViewController != null) ? mAdViewController.getAdTimeoutDelay() : null; } protected void loadFailUrl(MoPubErrorCode errorCode) { if (mAdViewController != null) mAdViewController.loadFailUrl(errorCode); } protected void loadCustomEvent(Map<String, String> paramsMap) { if (paramsMap == null) { Log.d("MoPub", "Couldn't invoke custom event because the server did not specify one."); loadFailUrl(ADAPTER_NOT_FOUND); return; } if (mCustomEventBannerAdapter != null) { mCustomEventBannerAdapter.invalidate(); } Log.d("MoPub", "Loading custom event adapter."); mCustomEventBannerAdapter = CustomEventBannerAdapterFactory.create( this, paramsMap.get(CUSTOM_EVENT_NAME.getKey()), paramsMap.get(CUSTOM_EVENT_DATA.getKey())); mCustomEventBannerAdapter.loadAd(); } protected void registerClick() { if (mAdViewController != null) { mAdViewController.registerClick(); // Let any listeners know that an ad was clicked adClicked(); } } protected void trackNativeImpression() { Log.d("MoPub", "Tracking impression for native adapter."); if (mAdViewController != null) mAdViewController.trackImpression(); } @Override protected void onWindowVisibilityChanged(int visibility) { if (mAdViewController == null) return; if (visibility == VISIBLE) { Log.d("MoPub", "Ad Unit ("+ mAdViewController.getAdUnitId()+") going visible: enabling refresh"); mIsInForeground = true; mAdViewController.setAutorefreshEnabled(true); } else { Log.d("MoPub", "Ad Unit ("+ mAdViewController.getAdUnitId()+") going invisible: disabling refresh"); mIsInForeground = false; mAdViewController.setAutorefreshEnabled(false); } } protected void adLoaded() { Log.d("MoPub", "adLoaded"); if (mBannerAdListener != null) { mBannerAdListener.onBannerLoaded(this); } else if (mOnAdLoadedListener != null) { mOnAdLoadedListener.OnAdLoaded(this); } } protected void adFailed(MoPubErrorCode errorCode) { if (mBannerAdListener != null) { mBannerAdListener.onBannerFailed(this, errorCode); } else if (mOnAdFailedListener != null) { mOnAdFailedListener.OnAdFailed(this); } } protected void adPresentedOverlay() { if (mBannerAdListener != null) { mBannerAdListener.onBannerExpanded(this); } else if (mOnAdPresentedOverlayListener != null) { mOnAdPresentedOverlayListener.OnAdPresentedOverlay(this); } } protected void adClosed() { if (mBannerAdListener != null) { mBannerAdListener.onBannerCollapsed(this); } else if (mOnAdClosedListener != null) { mOnAdClosedListener.OnAdClosed(this); } } protected void adClicked() { if (mBannerAdListener != null) { mBannerAdListener.onBannerClicked(this); } else if (mOnAdClickedListener != null) { mOnAdClickedListener.OnAdClicked(this); } } protected void nativeAdLoaded() { if (mAdViewController != null) mAdViewController.scheduleRefreshTimerIfEnabled(); adLoaded(); } //////////////////////////////////////////////////////////////////////////////////////////////// public void setAdUnitId(String adUnitId) { if (mAdViewController != null) mAdViewController.setAdUnitId(adUnitId); } public String getAdUnitId() { return (mAdViewController != null) ? mAdViewController.getAdUnitId() : null; } public void setKeywords(String keywords) { if (mAdViewController != null) mAdViewController.setKeywords(keywords); } public String getKeywords() { return (mAdViewController != null) ? mAdViewController.getKeywords() : null; } public void setFacebookSupported(boolean enabled) { if (mAdViewController != null) mAdViewController.setFacebookSupported(enabled); } public boolean isFacebookSupported() { return (mAdViewController != null) ? mAdViewController.isFacebookSupported() : false; } public void setLocation(Location location) { if (mAdViewController != null) mAdViewController.setLocation(location); } public Location getLocation() { return (mAdViewController != null) ? mAdViewController.getLocation() : null; } public void setTimeout(int milliseconds) { if (mAdViewController != null) mAdViewController.setTimeout(milliseconds); } public int getAdWidth() { return (mAdViewController != null) ? mAdViewController.getAdWidth() : 0; } public int getAdHeight() { return (mAdViewController != null) ? mAdViewController.getAdHeight() : 0; } public String getResponseString() { return (mAdViewController != null) ? mAdViewController.getResponseString() : null; } public void setClickthroughUrl(String url) { if (mAdViewController != null) mAdViewController.setClickthroughUrl(url); } public String getClickthroughUrl() { return (mAdViewController != null) ? mAdViewController.getClickthroughUrl() : null; } public Activity getActivity() { return (Activity) mContext; } public void setBannerAdListener(BannerAdListener listener) { mBannerAdListener = listener; } public BannerAdListener getBannerAdListener() { return mBannerAdListener; } public void setLocationAwareness(LocationAwareness awareness) { mLocationAwareness = awareness; } public LocationAwareness getLocationAwareness() { return mLocationAwareness; } public void setLocationPrecision(int precision) { if (mAdViewController != null) { mAdViewController.setLocationPrecision(precision); } } public int getLocationPrecision() { return (mAdViewController != null) ? mAdViewController.getLocationPrecision() : 0; } public void setLocalExtras(Map<String, Object> localExtras) { if (mAdViewController != null) mAdViewController.setLocalExtras(localExtras); } public Map<String, Object> getLocalExtras() { if (mAdViewController != null) return mAdViewController.getLocalExtras(); return Collections.emptyMap(); } public void setAutorefreshEnabled(boolean enabled) { if (mAdViewController != null) mAdViewController.setAutorefreshEnabled(enabled); } public boolean getAutorefreshEnabled() { if (mAdViewController != null) return mAdViewController.getAutorefreshEnabled(); else { Log.d("MoPub", "Can't get autorefresh status for destroyed MoPubView. " + "Returning false."); return false; } } public void setAdContentView(View view) { if (mAdViewController != null) mAdViewController.setAdContentView(view); } public void setTesting(boolean testing) { if (mAdViewController != null) mAdViewController.setTesting(testing); } public boolean getTesting() { if (mAdViewController != null) return mAdViewController.getTesting(); else { Log.d("MoPub", "Can't get testing status for destroyed MoPubView. " + "Returning false."); return false; } } public void forceRefresh() { if (mCustomEventBannerAdapter != null) { mCustomEventBannerAdapter.invalidate(); mCustomEventBannerAdapter = null; } if (mAdViewController != null) mAdViewController.forceRefresh(); } AdViewController getAdViewController() { return mAdViewController; } @Deprecated public interface OnAdWillLoadListener { public void OnAdWillLoad(MoPubView m, String url); } @Deprecated public interface OnAdLoadedListener { public void OnAdLoaded(MoPubView m); } @Deprecated public interface OnAdFailedListener { public void OnAdFailed(MoPubView m); } @Deprecated public interface OnAdClosedListener { public void OnAdClosed(MoPubView m); } @Deprecated public interface OnAdClickedListener { public void OnAdClicked(MoPubView m); } @Deprecated public interface OnAdPresentedOverlayListener { public void OnAdPresentedOverlay(MoPubView m); } @Deprecated public void setOnAdWillLoadListener(OnAdWillLoadListener listener) { mOnAdWillLoadListener = listener; } @Deprecated public void setOnAdLoadedListener(OnAdLoadedListener listener) { mOnAdLoadedListener = listener; } @Deprecated public void setOnAdFailedListener(OnAdFailedListener listener) { mOnAdFailedListener = listener; } @Deprecated public void setOnAdPresentedOverlayListener(OnAdPresentedOverlayListener listener) { mOnAdPresentedOverlayListener = listener; } @Deprecated public void setOnAdClosedListener(OnAdClosedListener listener) { mOnAdClosedListener = listener; } @Deprecated public void setOnAdClickedListener(OnAdClickedListener listener) { mOnAdClickedListener = listener; } @Deprecated protected void adWillLoad(String url) { Log.d("MoPub", "adWillLoad: " + url); if (mOnAdWillLoadListener != null) mOnAdWillLoadListener.OnAdWillLoad(this, url); } @Deprecated public void customEventDidLoadAd() { if (mAdViewController != null) mAdViewController.customEventDidLoadAd(); } @Deprecated public void customEventDidFailToLoadAd() { if (mAdViewController != null) mAdViewController.customEventDidFailToLoadAd(); } @Deprecated public void customEventActionWillBegin() { if (mAdViewController != null) mAdViewController.customEventActionWillBegin(); } }
/* * Copyright (C) 2015 The Android Open Source Project * * 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. */ // // Test on loop optimizations. // public class Main { static int sResult; // // Various sequence variables used in bound checks. // /// CHECK-START: int Main.linear(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linear(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int linear(int[] x) { int result = 0; for (int i = 0; i < x.length; i++) { result += x[i]; } return result; } /// CHECK-START: int Main.linearDown(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearDown(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int linearDown(int[] x) { int result = 0; for (int i = x.length - 1; i >= 0; i--) { result += x[i]; } return result; } /// CHECK-START: int Main.linearObscure(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearObscure(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int linearObscure(int[] x) { int result = 0; for (int i = x.length - 1; i >= 0; i--) { int k = i + 5; result += x[k - 5]; } return result; } /// CHECK-START: int Main.linearVeryObscure(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearVeryObscure(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int linearVeryObscure(int[] x) { int result = 0; for (int i = 0; i < x.length; i++) { int k = (-i) + (i << 5) + i - (32 * i) + 5 + (int) i; result += x[k - 5]; } return result; } /// CHECK-START: int Main.hiddenStride(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.hiddenStride(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add more statements because of Loop-Peeling. /// CHECK: BoundsCheck /// CHECK: Deoptimize static int hiddenStride(int[] a) { int result = 0; for (int i = 1; i <= 1; i++) { // Obscured unit stride. for (int j = 0; j < a.length; j += i) { result += a[j]; } } return result; } /// CHECK-START: int Main.linearWhile(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearWhile(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int linearWhile(int[] x) { int i = 0; int result = 0; while (i < x.length) { result += x[i++]; } return result; } /// CHECK-START: int Main.linearThreeWayPhi(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearThreeWayPhi(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearThreeWayPhi(int[] x) { int result = 0; for (int i = 0; i < x.length; ) { if (x[i] == 5) { i++; continue; } result += x[i++]; } return result; } /// CHECK-START: int Main.linearFourWayPhi(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearFourWayPhi(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearFourWayPhi(int[] x) { int result = 0; for (int i = 0; i < x.length; ) { if (x[i] == 5) { i++; continue; } else if (x[i] == 6) { i++; result += 7; continue; } result += x[i++]; } return result; } /// CHECK-START: int Main.wrapAroundThenLinear(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.wrapAroundThenLinear(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int wrapAroundThenLinear(int[] x) { // Loop with wrap around (length - 1, 0, 1, 2, ..). int w = x.length - 1; int result = 0; for (int i = 0; i < x.length; i++) { result += x[w]; w = i; } return result; } /// CHECK-START: int Main.wrapAroundThenLinearThreeWayPhi(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.wrapAroundThenLinearThreeWayPhi(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int wrapAroundThenLinearThreeWayPhi(int[] x) { // Loop with wrap around (length - 1, 0, 1, 2, ..). int w = x.length - 1; int result = 0; for (int i = 0; i < x.length; ) { if (x[w] == 1) { w = i++; continue; } result += x[w]; w = i++; } return result; } /// CHECK-START: int[] Main.linearWithParameter(int) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int[] Main.linearWithParameter(int) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int[] linearWithParameter(int n) { int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = i; } return x; } /// CHECK-START: int[] Main.linearCopy(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int[] Main.linearCopy(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int[] linearCopy(int x[]) { int n = x.length; int y[] = new int[n]; for (int i = 0; i < n; i++) { y[i] = x[i]; } return y; } /// CHECK-START: int Main.linearByTwo(int[]) BCE (before) /// CHECK-DAG: BoundsCheck /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearByTwo(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more Deoptimize because of Loop-Peeling. /// CHECK: Deoptimize private static int linearByTwo(int x[]) { int n = x.length / 2; int result = 0; for (int i = 0; i < n; i++) { int ii = i << 1; result += x[ii]; result += x[ii + 1]; } return result; } /// CHECK-START: int Main.linearByTwoSkip1(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearByTwoSkip1(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int linearByTwoSkip1(int x[]) { int result = 0; for (int i = 0; i < x.length / 2; i++) { result += x[2 * i]; } return result; } /// CHECK-START: int Main.linearByTwoSkip2(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearByTwoSkip2(int[]) BCE (after) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearByTwoSkip2(int[]) BCE (after) /// CHECK-NOT: Deoptimize private static int linearByTwoSkip2(int x[]) { int result = 0; // This case is not optimized. for (int i = 0; i < x.length; i+=2) { result += x[i]; } return result; } /// CHECK-START: int Main.linearWithCompoundStride() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearWithCompoundStride() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearWithCompoundStride() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }; int result = 0; for (int i = 0; i <= 12; ) { i++; result += x[i]; i++; } return result; } /// CHECK-START: int Main.linearWithLargePositiveStride() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearWithLargePositiveStride() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearWithLargePositiveStride() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; int result = 0; int k = 0; // Range analysis has no problem with a trip-count defined by a // reasonably large positive stride far away from upper bound. for (int i = 1; i <= 10 * 10000000 + 1; i += 10000000) { result += x[k++]; } return result; } /// CHECK-START: int Main.linearWithVeryLargePositiveStride() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearWithVeryLargePositiveStride() BCE (after) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearWithVeryLargePositiveStride() BCE (after) /// CHECK-NOT: Deoptimize private static int linearWithVeryLargePositiveStride() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; int result = 0; int k = 0; // Range analysis conservatively bails due to potential of wrap-around // arithmetic while computing the trip-count for this very large stride. for (int i = 1; i < Integer.MAX_VALUE; i += 195225786) { result += x[k++]; } return result; } /// CHECK-START: int Main.linearWithLargeNegativeStride() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearWithLargeNegativeStride() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearWithLargeNegativeStride() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; int result = 0; int k = 0; // Range analysis has no problem with a trip-count defined by a // reasonably large negative stride far away from lower bound. for (int i = -1; i >= -10 * 10000000 - 1; i -= 10000000) { result += x[k++]; } return result; } /// CHECK-START: int Main.linearWithVeryLargeNegativeStride() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearWithVeryLargeNegativeStride() BCE (after) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearWithVeryLargeNegativeStride() BCE (after) /// CHECK-NOT: Deoptimize private static int linearWithVeryLargeNegativeStride() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; int result = 0; int k = 0; // Range analysis conservatively bails due to potential of wrap-around // arithmetic while computing the trip-count for this very large stride. for (int i = -2; i > Integer.MIN_VALUE; i -= 195225786) { result += x[k++]; } return result; } /// CHECK-START: int Main.linearForNEUp() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearForNEUp() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearForNEUp() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int result = 0; for (int i = 0; i != 10; i++) { result += x[i]; } return result; } /// CHECK-START: int Main.linearForNEDown() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearForNEDown() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearForNEDown() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int result = 0; for (int i = 9; i != -1; i--) { result += x[i]; } return result; } /// CHECK-START: int Main.linearForNEArrayLengthUp(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearForNEArrayLengthUp(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int linearForNEArrayLengthUp(int[] x) { int result = 0; for (int i = 0; i != x.length; i++) { result += x[i]; } return result; } /// CHECK-START: int Main.linearForNEArrayLengthDown(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearForNEArrayLengthDown(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int linearForNEArrayLengthDown(int[] x) { int result = 0; for (int i = x.length - 1; i != -1; i--) { result += x[i]; } return result; } /// CHECK-START: int Main.linearDoWhileUp() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearDoWhileUp() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearDoWhileUp() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int result = 0; int i = 0; do { result += x[i++]; } while (i < 10); return result; } /// CHECK-START: int Main.linearDoWhileDown() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearDoWhileDown() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearDoWhileDown() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int result = 0; int i = 9; do { result += x[i--]; } while (0 <= i); return result; } /// CHECK-START: int Main.linearLong() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearLong() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearLong() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int result = 0; // Induction on constant interval is done in higher precision than necessary, // but truncated at the use as subscript. for (long i = 0; i < 10; i++) { result += x[(int)i]; } return result; } /// CHECK-START: int Main.linearLongAlt(int[]) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearLongAlt(int[]) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int linearLongAlt(int[] x) { int result = 0; // Induction on array length is done in higher precision than necessary, // but truncated at the use as subscript. for (long i = 0; i < x.length; i++) { result += x[(int)i]; } return result; } /// CHECK-START: int Main.linearShort() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearShort() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearShort() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int result = 0; // Induction is done in short precision, but fits. for (short i = 0; i < 10; i++) { result += x[i]; } return result; } /// CHECK-START: int Main.linearChar() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearChar() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearChar() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int result = 0; // Induction is done in char precision, but fits. for (char i = 0; i < 10; i++) { result += x[i]; } return result; } /// CHECK-START: int Main.linearByte() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.linearByte() BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static int linearByte() { int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int result = 0; // Induction is done in byte precision, but fits. for (byte i = 0; i < 10; i++) { result += x[i]; } return result; } /// CHECK-START: int Main.invariantFromPreLoop(int[], int) BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int Main.invariantFromPreLoop(int[], int) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize // Here we have to add one more BoundsCheck because of Loop-Peeling. /// CHECK: BoundsCheck private static int invariantFromPreLoop(int[] x, int y) { int result = 0; // Strange pre-loop that sets upper bound. int hi; while (true) { y = y % 3; hi = x.length; if (y != 123) break; } for (int i = 0; i < hi; i++) { result += x[i]; } return result; } /// CHECK-START: void Main.linearTriangularOnTwoArrayLengths(int) BCE (before) /// CHECK-DAG: BoundsCheck /// CHECK-DAG: BoundsCheck // /// CHECK-START: void Main.linearTriangularOnTwoArrayLengths(int) BCE (after) /// CHECK-NOT: BoundsCheck // TODO: also CHECK-NOT: Deoptimize, see b/27151190 private static void linearTriangularOnTwoArrayLengths(int n) { int[] a = new int[n]; for (int i = 0; i < a.length; i++) { int[] b = new int[i]; for (int j = 0; j < b.length; j++) { // Need to know j < b.length < a.length for static bce. a[j] += 1; // Need to know just j < b.length for static bce. b[j] += 1; } verifyTriangular(a, b, i, n); } } /// CHECK-START: void Main.linearTriangularOnOneArrayLength(int) BCE (before) /// CHECK-DAG: BoundsCheck /// CHECK-DAG: BoundsCheck // /// CHECK-START: void Main.linearTriangularOnOneArrayLength(int) BCE (after) /// CHECK-NOT: BoundsCheck /// CHECK-NOT: Deoptimize private static void linearTriangularOnOneArrayLength(int n) { int[] a = new int[n]; for (int i = 0; i < a.length; i++) { int[] b = new int[i]; for (int j = 0; j < i; j++) { // Need to know j < i < a.length for static bce. a[j] += 1; // Need to know just j < i for static bce. b[j] += 1; } verifyTriangular(a, b, i, n); } } /// CHECK-START: void Main.linearTriangularOnParameter(int) BCE (before) /// CHECK-DAG: BoundsCheck /// CHECK-DAG: BoundsCheck // /// CHECK-START: void Main.linearTriangularOnParameter(int) BCE (after) /// CHECK-NOT: BoundsCheck // TODO: also CHECK-NOT: Deoptimize, see b/27151190 private static void linearTriangularOnParameter(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { int[] b = new int[i]; for (int j = 0; j < i; j++) { // Need to know j < i < n for static bce. a[j] += 1; // Need to know just j < i for static bce. b[j] += 1; } verifyTriangular(a, b, i, n); } } /// CHECK-START: void Main.linearTriangularVariationsInnerStrict(int) BCE (before) /// CHECK-DAG: BoundsCheck /// CHECK-DAG: BoundsCheck /// CHECK-DAG: BoundsCheck /// CHECK-DAG: BoundsCheck // /// CHECK-START: void Main.linearTriangularVariationsInnerStrict(int) BCE (after) /// CHECK-NOT: BoundsCheck // TODO: also CHECK-NOT: Deoptimize, see b/27151190 private static void linearTriangularVariationsInnerStrict(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { a[j] += 1; } for (int j = i - 1; j > -1; j--) { a[j] += 1; } for (int j = i; j < n; j++) { a[j] += 1; } for (int j = n - 1; j > i - 1; j--) { a[j] += 1; } } verifyTriangular(a); } /// CHECK-START: void Main.linearTriangularVariationsInnerNonStrict(int) BCE (before) /// CHECK-DAG: BoundsCheck /// CHECK-DAG: BoundsCheck /// CHECK-DAG: BoundsCheck /// CHECK-DAG: BoundsCheck // /// CHECK-START: void Main.linearTriangularVariationsInnerNonStrict(int) BCE (after) /// CHECK-NOT: BoundsCheck // TODO: also CHECK-NOT: Deoptimize, see b/27151190 private static void linearTriangularVariationsInnerNonStrict(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { for (int j = 0; j <= i - 1; j++) { a[j] += 1; } for (int j = i - 1; j >= 0; j--) { a[j] += 1; } for (int j = i; j <= n - 1; j++) { a[j] += 1; } for (int j = n - 1; j >= i; j--) { a[j] += 1; } } verifyTriangular(a); } // Verifier for triangular loops. private static void verifyTriangular(int[] a, int[] b, int m, int n) { expectEquals(n, a.length); for (int i = 0, k = m; i < n; i++) { expectEquals(a[i], k); if (k > 0) k--; } expectEquals(m, b.length); for (int i = 0; i < m; i++) { expectEquals(b[i], 1); } } // Verifier for triangular loops. private static void verifyTriangular(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { expectEquals(a[i], n + n); } } /// CHECK-START: int[] Main.linearTriangularOOB() BCE (before) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int[] Main.linearTriangularOOB() BCE (after) /// CHECK-DAG: BoundsCheck // /// CHECK-START: int[] Main.linearTriangularOOB() BCE (after) /// CHECK-NOT: Deoptimize private static int[] linearTriangularOOB() { int[] a = new int[200]; try { for (int i = 0; i < 200; i++) { // Lower bound must be recognized as lower precision induction with arithmetic // wrap-around to -128 when i exceeds 127. for (int j = (byte) i; j < 200; j++) { a[j] += 1; } } } catch (ArrayIndexOutOfBoundsException e) { return a; } return null; // failure if this is reached } // // Verifier. // public static void main(String[] args) { int[] empty = { }; int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Linear and wrap-around. expectEquals(0, linear(empty)); expectEquals(55, linear(x)); expectEquals(0, linearDown(empty)); expectEquals(55, linearDown(x)); expectEquals(0, linearObscure(empty)); expectEquals(55, linearObscure(x)); expectEquals(0, linearVeryObscure(empty)); expectEquals(55, linearVeryObscure(x)); expectEquals(0, hiddenStride(empty)); expectEquals(55, hiddenStride(x)); expectEquals(0, linearWhile(empty)); expectEquals(55, linearWhile(x)); expectEquals(0, linearThreeWayPhi(empty)); expectEquals(50, linearThreeWayPhi(x)); expectEquals(0, linearFourWayPhi(empty)); expectEquals(51, linearFourWayPhi(x)); expectEquals(0, wrapAroundThenLinear(empty)); expectEquals(55, wrapAroundThenLinear(x)); expectEquals(0, wrapAroundThenLinearThreeWayPhi(empty)); expectEquals(54, wrapAroundThenLinearThreeWayPhi(x)); // Linear with parameter. sResult = 0; try { linearWithParameter(-1); } catch (NegativeArraySizeException e) { sResult = 1; } expectEquals(1, sResult); for (int n = 0; n < 32; n++) { int[] r = linearWithParameter(n); expectEquals(n, r.length); for (int i = 0; i < n; i++) { expectEquals(i, r[i]); } } // Linear copy. expectEquals(0, linearCopy(empty).length); { int[] r = linearCopy(x); expectEquals(x.length, r.length); for (int i = 0; i < x.length; i++) { expectEquals(x[i], r[i]); } } // Linear with non-unit strides. expectEquals(55, linearByTwo(x)); expectEquals(25, linearByTwoSkip1(x)); expectEquals(25, linearByTwoSkip2(x)); expectEquals(56, linearWithCompoundStride()); expectEquals(66, linearWithLargePositiveStride()); expectEquals(66, linearWithVeryLargePositiveStride()); expectEquals(66, linearWithLargeNegativeStride()); expectEquals(66, linearWithVeryLargeNegativeStride()); // Special forms. expectEquals(55, linearForNEUp()); expectEquals(55, linearForNEDown()); expectEquals(55, linearForNEArrayLengthUp(x)); expectEquals(55, linearForNEArrayLengthDown(x)); expectEquals(55, linearDoWhileUp()); expectEquals(55, linearDoWhileDown()); expectEquals(55, linearLong()); expectEquals(55, linearLongAlt(x)); expectEquals(55, linearShort()); expectEquals(55, linearChar()); expectEquals(55, linearByte()); expectEquals(55, invariantFromPreLoop(x, 1)); linearTriangularOnTwoArrayLengths(10); linearTriangularOnOneArrayLength(10); linearTriangularOnParameter(10); linearTriangularVariationsInnerStrict(10); linearTriangularVariationsInnerNonStrict(10); { int[] t = linearTriangularOOB(); for (int i = 0; i < 200; i++) { expectEquals(i <= 127 ? i + 1 : 128, t[i]); } } System.out.println("passed"); } private static void expectEquals(int expected, int result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } }
/* * ****************************************************************************** * * Copyright FUJITSU LIMITED 2017 * * Creation Date: 13.02.15 11:25 * * ****************************************************************************** */ package org.oscm.ui.dialog.mp.wizards; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.common.collect.Sets; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.oscm.internal.intf.AccountService; import org.oscm.internal.intf.SubscriptionService; import org.oscm.internal.intf.SubscriptionServiceInternal; import org.oscm.internal.types.enumtypes.ParameterValueType; import org.oscm.internal.types.enumtypes.SubscriptionStatus; import org.oscm.internal.types.enumtypes.UserRoleType; import org.oscm.internal.types.exception.*; import org.oscm.internal.usergroupmgmt.UserGroupService; import org.oscm.internal.vo.*; import org.oscm.json.*; import org.oscm.ui.beans.*; import org.oscm.ui.common.DurationValidation; import org.oscm.ui.common.JSFUtils; import org.oscm.ui.common.UiDelegate; import org.oscm.ui.dialog.mp.serviceDetails.ServiceDetailsModel; import org.oscm.ui.dialog.mp.subscriptionDetails.SubscriptionDetailsCtrlConstants; import org.oscm.ui.dialog.mp.subscriptionwizard.SubscriptionWizardConversation; import org.oscm.ui.dialog.mp.subscriptionwizard.SubscriptionWizardConversationModel; import org.oscm.ui.dialog.mp.userGroups.SubscriptionUnitCtrl; import org.oscm.ui.dialog.mp.userGroups.SubscriptionUnitModel; import org.oscm.ui.model.PriceModel; import org.oscm.ui.model.PricedParameterRow; import org.oscm.ui.model.Service; import org.oscm.ui.model.UdaRow; import org.oscm.ui.stubs.FacesContextStub; import org.oscm.ui.stubs.HttpServletRequestStub; import javax.enterprise.context.Conversation; import javax.faces.application.FacesMessage; import javax.faces.application.FacesMessage.Severity; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import java.io.IOException; import java.util.*; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyList; import static org.mockito.Matchers.anyListOf; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import static org.oscm.ui.dialog.mp.subscriptionDetails.SubscriptionDetailsCtrlConstants.ERROR_TO_PROCEED_SELECT_UNIT; import static org.oscm.ui.dialog.mp.subscriptionDetails.SubscriptionDetailsCtrlConstants.SUBSCRIPTION_NAME_ALREADY_EXISTS; public class SubscriptionWizardConversationTest { public static final String CONFIG_RESPONSE_ERROR = "{\"messageType\":\"CONFIG_RESPONSE\",\"responseCode\":\"CONFIGURATION_FINISHED\"" + ",\"parameters\":[{\"id\":\"ABoolean\",\"value\":\"abcd\"}]}"; private SubscriptionWizardConversationModel model; private SubscriptionUnitCtrl unitCtrl; private SubscriptionUnitModel unitModel; private SubscriptionWizardConversation bean; private ServiceDetailsModel sdm; private Conversation conversation; private UiDelegate ui; private SubscriptionService subscriptionService; private UserGroupService userGroupService; private MenuBean menuBean; private SessionBean sessionBean; private UserBean userBean; private static String CONFIG_RESPONSE = "{\"messageType\":\"CONFIG_RESPONSE\",\"responseCode\":\"CONFIGURATION_FINISHED\"" + ",\"parameters\":[{\"id\":\"ABoolean\",\"value\":\"true\"}]}"; private static final String SUBSCRIPTIONADD_VIEWID = "/marketplace/subscriptions/creation/add.xhtml"; private static String DEFAULT_VALUE = "value"; private SubscriptionServiceInternal subscriptionServiceInternal; private JsonConverter jsonConverter; private PaymentAndBillingVisibleBean pabv; private AccountService accountService; @Before public void setup() { model = spy(new SubscriptionWizardConversationModel()); sdm = mock(ServiceDetailsModel.class); conversation = mock(Conversation.class); ui = mock(UiDelegate.class); subscriptionService = mock(SubscriptionService.class); userGroupService = mock(UserGroupService.class); menuBean = mock(MenuBean.class); sessionBean = mock(SessionBean.class); subscriptionServiceInternal = mock(SubscriptionServiceInternal.class); jsonConverter = spy(new JsonConverter()); jsonConverter.setUiDelegate(ui); userBean = spy(new UserBean()); pabv = mock(PaymentAndBillingVisibleBean.class); accountService = mock(AccountService.class); unitCtrl = new SubscriptionUnitCtrl(); unitModel = new SubscriptionUnitModel(); unitCtrl.setModel(unitModel); bean = spy(new SubscriptionWizardConversation()); decorateBean(); } public void decorateBean() { doReturn(sdm).when(bean).getServiceDetailsModel(); doNothing().when(bean).addMessage(any(FacesMessage.Severity.class), anyString()); when(ui.getRequest()).thenReturn(new HttpServletRequestStub()); when(ui.getViewLocale()).thenReturn(Locale.ENGLISH); when(jsonConverter.getServiceParametersAsJsonString(anyList(), anyBoolean(), anyBoolean())).thenReturn("someJsonString"); model.setService(new Service(new VOService())); bean.setModel(model); bean.setConversation(conversation); bean.setUi(ui); bean.setUserGroupService(userGroupService); bean.setSubscriptionService(subscriptionService); bean.setMenuBean(menuBean); bean.setSessionBean(sessionBean); bean.setSubscriptionServiceInternal(subscriptionServiceInternal); bean.setJsonConverter(jsonConverter); bean.setUserBean(userBean); bean.setAccountingService(accountService); bean.setPaymentAndBillingVisibleBean(pabv); bean.setSubscriptionUnitCtrl(unitCtrl); List<UdaRow> udaRows = new ArrayList<>(); model.setSubscriptionUdaRows(udaRows); } @Test public void testStartSubscriptionExceptions() throws Exception { // given bean = new SubscriptionWizardConversation() { private static final long serialVersionUID = 5838904781636078095L; @Override protected String initializeService(Service selectedService) throws ServiceStateException, ObjectNotFoundException, OrganizationAuthoritiesException, OperationNotPermittedException, ValidationException { throw new ServiceStateException(); } }; bean = spy(bean); decorateBean(); doNothing().when(ui).handleException(any(ServiceStateException.class)); // when bean.startSubscription(); // then verify(ui, times(1)).handleException(any(ServiceStateException.class)); } @Test public void testIsPaymentVisible() throws Exception { //given //when bean.isPaymentInfoVisible(); bean.isBillingContactVisible(); //then verify(model, atLeastOnce()).isAnyPaymentAvailable(); verify(pabv, atLeastOnce()).isBillingContactVisible(); } @Test public void testGotoConfiguration() { // when bean.gotoConfiguration(); // then assertEquals(Boolean.FALSE, Boolean.valueOf(model.isReadOnlyParams())); } @Test public void testStartSubscription() { // given bean = new SubscriptionWizardConversation() { private static final long serialVersionUID = 4321969571075963008L; @Override protected String initializeService(Service selectedService) throws ServiceStateException, ObjectNotFoundException, OrganizationAuthoritiesException, OperationNotPermittedException, ValidationException { setPaymentAndBillingVisibleBean(pabv); return SubscriptionDetailsCtrlConstants.OUTCOME_SHOW_DETAILS_4_CREATION; } }; bean = spy(bean); decorateBean(); doReturn(Collections.emptyList()).when(bean).getEnabledPaymentTypes(); doReturn(Collections.emptyList()).when(bean).getPaymentInfosForSubscription(); // when bean.startSubscription(); } @Test public void selectService() { // given initDataForSelectService(); doNothing().when(bean).addMessage(any(FacesMessage.Severity.class), anyString()); // when String result = bean.selectService(); // then assertEquals("", result); } @Test public void selectServiceHIDE_PAYMENT_INFO() { // given initDataForSelectServiceWithoutParams(); doNothing().when(bean).addMessage(any(FacesMessage.Severity.class), anyString()); doReturn(true).when(subscriptionService).isPaymentInfoHidden(); VOUserDetails voUserDetails = new VOUserDetails(); voUserDetails.setKey(1000L); Set<UserRoleType> userRoles = new HashSet<>(); userRoles.add(UserRoleType.ORGANIZATION_ADMIN); voUserDetails.setUserRoles(userRoles); doReturn(voUserDetails).when(ui).getUserFromSessionWithoutException(); VOSubscriptionDetails subscription = new VOSubscriptionDetails(); bean.getModel().setSubscription(subscription); // when String result = bean.selectService(); // then assertEquals("success", result); } @Test public void testNext() { // given model.setReadOnlyParams(false); // when bean.next(); // then assertTrue(model.isReadOnlyParams()); } @Test public void selectServiceByUnitAdministrator_WithoutUnit() { // given Set<UserRoleType> userRoles = new HashSet<UserRoleType>(); userRoles.add(UserRoleType.UNIT_ADMINISTRATOR); prepareDataForTestUnitSelection(userRoles, false); // when String result = bean.selectService(); // then verify(bean, times(1)).addMessage(FacesMessage.SEVERITY_ERROR, ERROR_TO_PROCEED_SELECT_UNIT); assertEquals("", result); } @Test public void selectServiceByUnitAdministrator_WithUnit() { // given Set<UserRoleType> userRoles = new HashSet<UserRoleType>(); userRoles.add(UserRoleType.UNIT_ADMINISTRATOR); prepareDataForTestUnitSelection(userRoles, true); // when String result = bean.selectService(); // then verify(bean, times(0)).addMessage(any(Severity.class), any(String.class)); assertEquals("success", result); } @Test public void testPreviousFromPayment() { // given // when bean.previousFromPayment(); // then verify(model, times(1)).setReadOnlyParams(false); } @Test public void selectServiceByUnitAdminSubMan_WithoutUnit() { // given Set<UserRoleType> userRoles = new HashSet<UserRoleType>(); userRoles.add(UserRoleType.UNIT_ADMINISTRATOR); userRoles.add(UserRoleType.SUBSCRIPTION_MANAGER); prepareDataForTestUnitSelection(userRoles, false); // when String result = bean.selectService(); // then verify(bean, times(0)).addMessage(any(Severity.class), any(String.class)); assertEquals("success", result); } @Test public void selectServiceByUnitAdminOrgUnit_WithoutUnit() { // given Set<UserRoleType> userRoles = new HashSet<UserRoleType>(); userRoles.add(UserRoleType.UNIT_ADMINISTRATOR); userRoles.add(UserRoleType.ORGANIZATION_ADMIN); prepareDataForTestUnitSelection(userRoles, false); // when String result = bean.selectService(); // then verify(bean, times(0)).addMessage(any(Severity.class), any(String.class)); assertEquals("success", result); } @Test public void testValidateSubscriptionId() throws Exception { // given SubscriptionServiceInternal ssi = mock(SubscriptionServiceInternal.class); doReturn(true).when(ssi).validateSubscriptionIdForOrganization( anyString()); doReturn(ssi).when(bean).getSubscriptionServiceInternal(); UIComponent uiInputMock = mock(UIInput.class); FacesContext contextMock = mock(FacesContext.class); // when bean.validateSubscriptionId(contextMock, uiInputMock, "value"); // then verify(ui, times(1)).handleError(anyString(), eq(SUBSCRIPTION_NAME_ALREADY_EXISTS), anyObject()); } @Test public void validateSubscriptionId_ShowExternalConfiguratorIsTrue() throws Exception { // given model.setShowExternalConfigurator(true); FacesContext context = mock(FacesContext.class); // when UIComponent toValidate = mock(UIComponent.class); doReturn("").when(toValidate).getClientId(); bean.validateSubscriptionId(context, toValidate, new String()); // then assertEquals(Boolean.FALSE, Boolean.valueOf(model.isShowExternalConfigurator())); } @Test public void validateSubscriptionId_ShowExternalConfiguratorIsFalse() throws Exception { // given model.setShowExternalConfigurator(false); UIViewRoot viewRoot = mock(UIViewRoot.class); viewRoot.setViewId(SUBSCRIPTIONADD_VIEWID); FacesContext context = mock(FacesContext.class); context.setViewRoot(viewRoot); // when UIComponent toValidate = mock(UIComponent.class); doReturn("").when(toValidate).getClientId(); bean.validateSubscriptionId(context, toValidate, new String()); // then assertEquals(Boolean.FALSE, Boolean.valueOf(model.isShowExternalConfigurator())); } @Test public void validateSubscriptionId_noneSubIdExist() throws Exception { // given UIComponent toValidate = mock(UIComponent.class); doReturn("").when(toValidate).getClientId(); when( Boolean.valueOf(subscriptionServiceInternal .validateSubscriptionIdForOrganization(anyString()))) .thenReturn(Boolean.FALSE); // when bean.validateSubscriptionId(mock(FacesContext.class), toValidate, new String()); // then verify(subscriptionServiceInternal, times(1)) .validateSubscriptionIdForOrganization(anyString()); } @Test public void subscribe_SYNC_OK() throws Exception { // given prepareServiceAccessible(true); VOSubscription voSubscription = new VOSubscription(); voSubscription.setStatus(SubscriptionStatus.ACTIVE); voSubscription.setSubscriptionId("test"); voSubscription.setSuccessInfo("success mesage"); doReturn(voSubscription).when(subscriptionService).subscribeToService( any(VOSubscriptionDetails.class), any(VOService.class), anyListOf(VOUsageLicense.class), any(VOPaymentInfo.class), any(VOBillingContact.class), anyListOf(VOUda.class)); // when String result = bean.subscribe(); // then verify(ui, times(1)).handle( SubscriptionDetailsCtrlConstants.INFO_SUBSCRIPTION_CREATED, "test", "success mesage"); assertEquals(SubscriptionDetailsCtrlConstants.OUTCOME_SUCCESS, result); } @Test public void subscribe_ASYNC_OK() throws Exception { // given prepareServiceAccessible(true); VOSubscription voSubscription = new VOSubscription(); voSubscription.setSubscriptionId("test"); voSubscription.setStatus(SubscriptionStatus.PENDING); voSubscription.setSuccessInfo("success mesage"); doReturn(voSubscription).when(subscriptionService).subscribeToService( any(VOSubscriptionDetails.class), any(VOService.class), anyListOf(VOUsageLicense.class), any(VOPaymentInfo.class), any(VOBillingContact.class), anyListOf(VOUda.class)); // when String result = bean.subscribe(); // then verify(ui, times(1)) .handle(SubscriptionDetailsCtrlConstants.INFO_SUBSCRIPTION_ASYNC_CREATED, "test", "success mesage"); assertEquals(SubscriptionDetailsCtrlConstants.OUTCOME_SUCCESS, result); } @Test public void subscribe_ObjectNotFoundException_Service() throws Exception { // given prepareServiceAccessible(true); doThrow( new ObjectNotFoundException( DomainObjectException.ClassEnum.SERVICE, "productId")) .when(subscriptionService).subscribeToService( any(VOSubscriptionDetails.class), any(VOService.class), anyListOf(VOUsageLicense.class), any(VOPaymentInfo.class), any(VOBillingContact.class), anyListOf(VOUda.class)); // when String result = bean.subscribe(); // then verify(ui, times(1)).handleError(null, SubscriptionDetailsCtrlConstants.ERROR_SERVICE_INACCESSIBLE); assertEquals(null, result); } @Test public void subscribe_serviceNotAccessible() throws Exception { // given prepareServiceAccessible(false); new FacesContextStub(Locale.ENGLISH); // when String result = bean.subscribe(); // then verify(subscriptionService, never()).subscribeToService( any(VOSubscription.class), any(VOService.class), anyListOf(VOUsageLicense.class), any(VOPaymentInfo.class), any(VOBillingContact.class), anyListOf(VOUda.class)); assertEquals(BaseBean.MARKETPLACE_ACCESS_DENY_PAGE, result); } @Test public void subscribe_serviceAccessible() throws Exception { // given prepareServiceAccessible(true); // when String result = bean.subscribe(); // then verify(subscriptionService, times(1)).subscribeToService( any(VOSubscription.class), any(VOService.class), anyListOf(VOUsageLicense.class), any(VOPaymentInfo.class), any(VOBillingContact.class), anyListOf(VOUda.class)); assertEquals(SubscriptionDetailsCtrlConstants.OUTCOME_PROCESS, result); } @Test public void subscribe_ObjectNotFoundException_BillingContact() throws Exception { // given prepareServiceAccessible(true); new FacesContextStub(Locale.ENGLISH); doThrow( new ObjectNotFoundException( DomainObjectException.ClassEnum.BILLING_CONTACT, "id")) .when(subscriptionService).subscribeToService( any(VOSubscriptionDetails.class), any(VOService.class), anyListOf(VOUsageLicense.class), any(VOPaymentInfo.class), any(VOBillingContact.class), anyListOf(VOUda.class)); // when String result = bean.subscribe(); // then verify(ui, never()).handleError(null, SubscriptionDetailsCtrlConstants.ERROR_SERVICE_INACCESSIBLE); assertEquals(null, result); } @Test public void actionLoadIframe_setShowExternalConfigurator() throws Exception { // given // when bean.actionLoadIframe(); // then assertTrue(model.isShowExternalConfigurator()); } @Test public void actionLoadIframe_success() throws Exception { // given // when String result = bean.actionLoadIframe(); // then assertNull(result); assertTrue(model.getLoadIframe()); assertFalse(model.isHideExternalConfigurator()); assertEquals("someJsonString", model.getServiceParametersAsJSONString()); } @Test public void actionLoadIframe_jsonError() throws Exception { // given when( jsonConverter.getServiceParametersAsJsonString(anyList(), anyBoolean(), anyBoolean())).thenReturn(null); // when String result = bean.actionLoadIframe(); // then assertEquals(SubscriptionDetailsCtrlConstants.OUTCOME_ERROR, result); assertFalse(model.getLoadIframe()); assertTrue(model.isHideExternalConfigurator()); assertNull(model.getServiceParametersAsJSONString()); } @Test public void copyResponseParameters_multipleParameter() throws Exception { // given bean.setJsonConverter(new JsonConverter()); JsonObject configRequest = givenConfigRequest(); addJsonParameter(configRequest, "id1", "3", false); addJsonParameter(configRequest, "id2", "false", false); addJsonParameter(configRequest, "id3", "option1", false); addJsonParameter(configRequest, "id4", "8", false); JsonObject configResponse = givenParameters(); addJsonParameter(configResponse, "id1", "123", true); addJsonParameter(configResponse, "id2", "true", false); addJsonParameter(configResponse, "id3", "option3", false); addJsonParameter(configResponse, "id4", "4781111111", true); // when JsonUtils.copyResponseParameters(configRequest, configResponse); // then assertEquals("123", configRequest.getParameter("id1").getValue()); assertTrue(configRequest.getParameter("id1").isValueError()); assertEquals("true", configRequest.getParameter("id2").getValue()); assertFalse(configRequest.getParameter("id2").isValueError()); assertEquals("option3", configRequest.getParameter("id3").getValue()); assertFalse(configRequest.getParameter("id3").isValueError()); assertEquals("4781111111", configRequest.getParameter("id4").getValue()); assertTrue(configRequest.getParameter("id4").isValueError()); } @Test public void copyResponseParameters_wrongResponseParameters() throws Exception { // given bean.setJsonConverter(new JsonConverter()); JsonObject configRequest = givenConfigRequest(); addJsonParameter(configRequest, "id1", "3", false); addJsonParameter(configRequest, "id2", "false", false); addJsonParameter(configRequest, "id3", "option1", false); addJsonParameter(configRequest, "id4", "8", false); JsonObject configResponse = givenParameters(); addJsonParameter(configResponse, "idx1", "123", true); addJsonParameter(configResponse, "id2", "true", false); addJsonParameter(configResponse, "idd3", "option3", false); addJsonParameter(configResponse, "id4", "4781111111", true); // when JsonUtils.copyResponseParameters(configRequest, configResponse); // then assertEquals("3", configRequest.getParameter("id1").getValue()); assertFalse(configRequest.getParameter("id1").isValueError()); assertEquals("true", configRequest.getParameter("id2").getValue()); assertFalse(configRequest.getParameter("id2").isValueError()); assertEquals("option1", configRequest.getParameter("id3").getValue()); assertFalse(configRequest.getParameter("id3").isValueError()); assertEquals("4781111111", configRequest.getParameter("id4").getValue()); assertTrue(configRequest.getParameter("id4").isValueError()); } @Test public void copyResponseParameters_nullResponse() throws Exception { // given JsonObject configRequest = givenConfigRequest(); addJsonParameter(configRequest, "id1", "3", false); addJsonParameter(configRequest, "id2", "false", false); addJsonParameter(configRequest, "id3", "option1", false); addJsonParameter(configRequest, "id4", "8", false); // when JsonUtils.copyResponseParameters(configRequest, null); // then // ... no exception expected ... } @Test public void validateConfiguredParameters_success() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); model.setServiceParameters(new ArrayList<PricedParameterRow>()); addPricedParameterRow("ABoolean", ParameterValueType.BOOLEAN, false); model.setParameterConfigResponse(CONFIG_RESPONSE); // when String outcome = bean.getJsonValidator().validateConfiguredParameters( bean.getModel()); // then assertNull("Outcome null expected: Stay on page", outcome); assertFalse("No error expected", model.getParameterValidationResult() .getValidationError()); assertNull("No config request expected in validation result", model .getParameterValidationResult().getConfigRequest()); } @SuppressWarnings("unchecked") @Test public void validateConfiguredParameters_validationError() throws Exception { // given JsonConverter converter = spy(new JsonConverter()); JsonParameterValidator validator = new JsonParameterValidator(converter); bean.setJsonValidator(validator); bean.setJsonConverter(converter); prepareServiceAccessible(true); model.setServiceParameters(new ArrayList<PricedParameterRow>()); addPricedParameterRow("ABoolean", ParameterValueType.BOOLEAN, false); model.setParameterConfigResponse(CONFIG_RESPONSE_ERROR); JsonObject configRequest = givenConfigRequest(); addJsonParameter(configRequest, "ABoolean", "false", false); doReturn(configRequest).when(converter) .getServiceParametersAsJsonObject(Matchers.any(List.class), Matchers.anyBoolean(), Matchers.anyBoolean()); // when String outcome = bean.getJsonValidator().validateConfiguredParameters( bean.getModel()); // then assertEquals("Validation error expected: Stay on page", SubscriptionDetailsCtrlConstants.VALIDATION_ERROR, outcome); assertTrue("Error expected", model.getParameterValidationResult() .getValidationError()); String configRequestResult = model.getParameterValidationResult() .getConfigRequest(); assertNotNull("Config request in validation result expected", configRequestResult); assertTrue("Wrong value should be in config request", configRequestResult.contains("\"value\":\"abcd\"")); assertTrue("Validation error expected", configRequestResult.contains("\"valueError\":true")); } @SuppressWarnings("unchecked") @Test public void validateConfiguredParameters_parseError() throws Exception { // given JsonConverter converter = spy(new JsonConverter()); JsonParameterValidator validator = new JsonParameterValidator(converter); bean.setJsonValidator(validator); bean.setJsonConverter(converter); prepareServiceAccessible(true); model.setServiceParameters(new ArrayList<PricedParameterRow>()); addPricedParameterRow("ABoolean", ParameterValueType.BOOLEAN, false); model.setParameterConfigResponse(CONFIG_RESPONSE_ERROR); JsonObject configRequest = givenConfigRequest(); addJsonParameter(configRequest, "ABoolean", "false", false); doThrow(new IOException("Es ist ein Fehler aufgetreten.")).when( converter).parseJsonString(anyString()); doReturn(configRequest).when(converter) .getServiceParametersAsJsonObject(Matchers.any(List.class), Matchers.anyBoolean(), Matchers.anyBoolean()); // when String outcome = bean.getJsonValidator().validateConfiguredParameters( bean.getModel()); // then assertEquals("Validation error expected: Stay on page", SubscriptionDetailsCtrlConstants.VALIDATION_ERROR, outcome); assertTrue("Error expected in validation result", model .getParameterValidationResult().getValidationError()); String configRequestResult = model.getParameterValidationResult() .getConfigRequest(); assertNotNull("Config request in validation result expected", configRequestResult); assertTrue("Value should be unchanged in config request", configRequestResult.contains("\"value\":\"false\"")); assertTrue("No validation, thus no value error in config request", configRequestResult.contains("\"valueError\":false")); } @SuppressWarnings("unchecked") @Test public void validateConfiguredParameters_createJsonError() throws Exception { // given prepareServiceAccessible(true); model.setServiceParameters(new ArrayList<PricedParameterRow>()); bean.setJsonValidator(new JsonParameterValidator(bean .getJsonConverter())); addPricedParameterRow("ABoolean", ParameterValueType.BOOLEAN, false); model.setParameterConfigResponse(CONFIG_RESPONSE_ERROR); JsonObject configRequest = givenConfigRequest(); addJsonParameter(configRequest, "ABoolean", "false", false); doReturn(configRequest).when(jsonConverter) .getServiceParametersAsJsonObject(Matchers.any(List.class), Matchers.anyBoolean(), Matchers.anyBoolean()); doThrow(new JsonMappingException("Error in json mapping")).when( jsonConverter).createJsonString(Matchers.any(JsonObject.class)); // when String outcome = bean.getJsonValidator().validateConfiguredParameters( bean.getModel()); // then assertEquals("Outcome error expected: Rerender parent page", SubscriptionDetailsCtrlConstants.OUTCOME_ERROR, outcome); assertTrue("Error expected in validation result", model .getParameterValidationResult().getValidationError()); assertNull("No config request expected in validation result", model .getParameterValidationResult().getConfigRequest()); } /** * If the parameter configuration was cancelled the subscription model must * not be updated. */ @Test public void updateValueObjects_nullJsonObject() throws Exception { // given JsonObject parameters = null; int originalHash = model.hashCode(); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals(originalHash, model.hashCode()); } @Test public void updateValueObjects_emptyParameters() throws Exception { // given JsonConverter jc = new JsonConverter(); bean.setJsonConverter(spy(jc)); JsonObject parameters = givenParameters(); int originalHash = model.hashCode(); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals(originalHash, model.hashCode()); verify(bean.getJsonConverter(), never()).logParameterNotFound( anyString()); } @Test public void updateValueObjects_oneParameter() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); addParameter(parameters, "id", ParameterValueType.STRING, "123"); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals("123", JsonUtils.findParameterById("id", model.getService()) .getValue()); } @Test public void updateValueObjects_NullParameter() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); addParameter(parameters, "id", ParameterValueType.STRING, null); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals(null, JsonUtils .findParameterById("id", model.getService()).getValue()); } @Test public void updateValueObjects_durationParameter() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); addParameter(parameters, "PERIOD", ParameterValueType.DURATION, "60"); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals("5184000000", JsonUtils.findParameterById("PERIOD", model.getService()) .getValue()); } @Test public void updateValueObjects_emptyDurationParameter() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); addParameter(parameters, "PERIOD", ParameterValueType.DURATION, ""); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals("", JsonUtils.findParameterById("PERIOD", model.getService()) .getValue()); } @Test public void updateValueObjects_booleanParameter() throws Exception { // given prepareServiceAccessible(true); bean.setJsonConverter(new JsonConverter()); JsonObject parameters = givenParameters(); addParameter(parameters, "AFlag", ParameterValueType.BOOLEAN, "tRuE"); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals("true", JsonUtils.findParameterById("AFlag", model.getService()) .getValue()); } @Test public void updateValueObjects_multipleParameter() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); addParameter(parameters, "id1", ParameterValueType.STRING, "123"); addParameter(parameters, "id2", ParameterValueType.STRING, "true"); addParameter(parameters, "id3", ParameterValueType.STRING, "option1"); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals("123", JsonUtils.findParameterById("id1", model.getService()) .getValue()); assertEquals("true", JsonUtils.findParameterById("id2", model.getService()) .getValue()); assertEquals("option1", JsonUtils.findParameterById("id3", model.getService()) .getValue()); assertEquals(3, model.getService().getVO().getParameters().size()); } /** * The JSON parameter string contains only one parameter, whose parameter id * is unknown to BES. But the local value object contains a parameter, the * value of this parameter must not be changed. A warning must be logged. */ @Test public void updateValueObjects_unknownParameter() throws Exception { // given JsonConverter jc = new JsonConverter(); bean.setJsonConverter(spy(jc)); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); addJsonParameter(parameters, "unknownId", "123"); addVoParameter("id"); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals(DEFAULT_VALUE, JsonUtils.findParameterById("id", model.getService()) .getValue()); assertEquals(1, model.getService().getVO().getParameters().size()); verify(bean.getJsonConverter(), times(1)).logParameterNotFound( anyString()); } /** * The JSON parameter string contains one unknown and one known parameter. * The knwon parameter must be updated correctly and a warning must be * logged. */ @Test public void updateValueObjects_oneParameterAndOneUnknownParameter() throws Exception { // given JsonConverter jc = new JsonConverter(); bean.setJsonConverter(spy(jc)); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); addParameter(parameters, "knownParameter", ParameterValueType.STRING, "known"); addJsonParameter(parameters, "unknownId", "123"); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals( "known", JsonUtils.findParameterById("knownParameter", model.getService()).getValue()); assertEquals(1, model.getService().getVO().getParameters().size()); verify(bean.getJsonConverter(), times(1)).logParameterNotFound( anyString()); } @Test public void updateValueObjects_sameParameterTwice() throws Exception { // given JsonConverter jc = new JsonConverter(); bean.setJsonConverter(spy(jc)); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); addParameter(parameters, "knownParameter", ParameterValueType.STRING, "known"); addJsonParameter(parameters, "knownParameter", "known123"); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals( "known123", JsonUtils.findParameterById("knownParameter", model.getService()).getValue()); assertEquals(1, model.getService().getVO().getParameters().size()); verify(bean.getJsonConverter(), never()).logParameterNotFound( anyString()); } @Test public void updateValueObjects_sameParameterDurationTwice_Bug10833() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); long durationInMs = 410 * DurationValidation.MILLISECONDS_PER_DAY; addParameter(parameters, "knownParameter", ParameterValueType.DURATION, "410", Long.toString(durationInMs)); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals( Long.toString(durationInMs), JsonUtils.findParameterById("knownParameter", model.getService()).getValue()); } @Test public void updateValueObjects_changeParameterDurationFromNull_Bug10833() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); long durationInMs = 410 * DurationValidation.MILLISECONDS_PER_DAY; addParameter(parameters, "knownParameter", ParameterValueType.DURATION, "410", null); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals( Long.toString(durationInMs), JsonUtils.findParameterById("knownParameter", model.getService()).getValue()); } @Test public void updateValueObjects__changeParameterDurationToNull_Bug10833() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); JsonObject parameters = givenParameters(); long durationInMs = 410 * DurationValidation.MILLISECONDS_PER_DAY; addParameter(parameters, "knownParameter", ParameterValueType.DURATION, "", Long.toString(durationInMs)); // when bean.getJsonConverter().updateValueObjects(parameters, bean.getModel().getService()); // then assertEquals( "", JsonUtils.findParameterById("knownParameter", model.getService()).getValue()); } @Test public void validateParameters_multipleParameters() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); addPricedParameterRow("ABoolean", ParameterValueType.BOOLEAN, false); addPricedParameterRow("Number1", ParameterValueType.INTEGER, true, 10l, 50l); addPricedParameterRow("Long1", ParameterValueType.LONG, false, 100000l, null); addPricedParameterRow("Enum1", ParameterValueType.ENUMERATION, true, "Option1", "Option2", "Option3", "Option4"); addPricedParameterRow("PERIOD", ParameterValueType.DURATION, true, 0l, null); JsonObject configResponse = givenParameters(); addJsonParameter(configResponse, "PERIOD", "106751991168"); addJsonParameter(configResponse, "Enum1", "Option3"); addJsonParameter(configResponse, "ABoolean", "xyz"); addJsonParameter(configResponse, "Number1", "20"); addJsonParameter(configResponse, "Long1", "8888888888"); // when boolean validationError = bean.getJsonValidator().validateParameters( configResponse, new FacesContextStub(Locale.JAPAN), model.getServiceParameters()); // then assertTrue("Some parameters were not valid", validationError); assertTrue("Parameter value was invalid", configResponse.getParameter("PERIOD").isValueError()); assertFalse("Parameter value was valid", configResponse.getParameter("Enum1").isValueError()); assertTrue("Parameter value was invalid", configResponse.getParameter("ABoolean").isValueError()); assertFalse("Parameter value was valid", configResponse.getParameter("Number1").isValueError()); assertFalse("Parameter value was valid", configResponse.getParameter("Long1").isValueError()); } @Test public void validateParameters_emptyParameters() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); addPricedParameterRow("ABoolean", ParameterValueType.BOOLEAN, false); addPricedParameterRow("Number1", ParameterValueType.INTEGER, true, 10l, 50l); addPricedParameterRow("Long1", ParameterValueType.LONG, false, 100000l, null); addPricedParameterRow("Enum1", ParameterValueType.ENUMERATION, true, "Option1", "Option2", "Option3", "Option4"); addPricedParameterRow("PERIOD", ParameterValueType.DURATION, true, 0l, null); JsonObject configResponse = givenParameters(); addJsonParameter(configResponse, "PERIOD", ""); addJsonParameter(configResponse, "Enum1", ""); addJsonParameter(configResponse, "ABoolean", ""); addJsonParameter(configResponse, "Number1", ""); addJsonParameter(configResponse, "Long1", ""); // when boolean validationError = bean.getJsonValidator().validateParameters( configResponse, new FacesContextStub(Locale.JAPAN), model.getServiceParameters()); // then assertTrue("Some parameters were not valid", validationError); assertTrue("Value of mandatory parameter was empty", configResponse .getParameter("PERIOD").isValueError()); assertTrue("Value of mandatory parameter was empty", configResponse .getParameter("Enum1").isValueError()); assertFalse("Empty value allowed because parameter is not mandatory", configResponse.getParameter("ABoolean").isValueError()); assertTrue("Value of mandatory parameter was empty", configResponse .getParameter("Number1").isValueError()); assertFalse("Empty value allowed because parameter is not mandatory", configResponse.getParameter("Long1").isValueError()); } @Test public void validateParameters_unknownParameter() throws Exception { // given bean.setJsonConverter(new JsonConverter()); prepareServiceAccessible(true); addPricedParameterRow("ABoolean", ParameterValueType.BOOLEAN, false); addPricedParameterRow("Number1", ParameterValueType.INTEGER, true, 10l, 50l); addPricedParameterRow("Long1", ParameterValueType.LONG, false, null, 1000000l); JsonObject configResponse = givenParameters(); addJsonParameter(configResponse, "ABoolean", "true"); addJsonParameter(configResponse, "UnknownNumber", "4711"); addJsonParameter(configResponse, "Long1", "8888"); // when boolean validationError = bean.getJsonValidator().validateParameters( configResponse, new FacesContextStub(Locale.JAPAN), model.getServiceParameters()); // then assertTrue("Validation Error expected", validationError); assertFalse("Parameter value was valid", configResponse.getParameter("ABoolean").isValueError()); assertFalse("Parameter value was valid", configResponse.getParameter("Long1").isValueError()); } /** * Helper methods. */ private void prepareServiceAccessible(boolean isAccessible) throws Exception { VOUserDetails voUserDetails = new VOUserDetails(); voUserDetails.setKey(1000L); VOService voService = new VOService(); voService.setKey(1001L); Service service = new Service(voService); model.setService(service); doReturn(voUserDetails).when(ui).getUserFromSessionWithoutException(); VOSubscriptionDetails subsDetails = new VOSubscriptionDetails(); subsDetails.setSubscribedService(voService); subsDetails.setSubscriptionId("test"); model.setSubscription(subsDetails); model.setServiceParameters(new ArrayList<PricedParameterRow>()); List<Long> invisibleServiceKeys = new ArrayList<>(); if (!isAccessible) { invisibleServiceKeys.add(service.getKey()); } invisibleServiceKeys.add(1002L); doReturn(invisibleServiceKeys).when(userGroupService) .getInvisibleProductKeysForUser(voUserDetails.getKey()); } private void initDataForSelectService() { VOService vo = new VOService(); vo.setConfiguratorUrl("http://"); List<VOParameter> parameters = new ArrayList<>(); VOParameter parameter = new VOParameter(); VOParameterDefinition parameterDefinition = new VOParameterDefinition(); parameterDefinition.setMandatory(true); parameterDefinition.setKey(100L); parameter.setParameterDefinition(parameterDefinition); parameters.add(parameter); vo.setParameters(parameters); vo.setKey(1000L); Service s = new Service(vo); bean.getModel().setService(s); List<PricedParameterRow> pricedParameterRows = new ArrayList<>(); PricedParameterRow pricedParameterRow = new PricedParameterRow(); pricedParameterRows.add(pricedParameterRow); bean.getModel().setServiceParameters(pricedParameterRows); bean.getModel().getUseExternalConfigurator(); bean.getModel().setHideExternalConfigurator(false); } private void initDataForSelectServiceWithoutParams() { VOService vo = new VOService(); vo.setConfiguratorUrl("http://"); List<VOParameter> parameters = new ArrayList<>(); vo.setParameters(parameters); vo.setKey(1000L); Service s = new Service(vo); bean.getModel().setService(s); List<PricedParameterRow> pricedParameterRows = new ArrayList<>(); PricedParameterRow pricedParameterRow = new PricedParameterRow(); pricedParameterRows.add(pricedParameterRow); bean.getModel().setServiceParameters(pricedParameterRows); bean.getModel().getUseExternalConfigurator(); bean.getModel().setHideExternalConfigurator(false); } private void addJsonParameter(JsonObject jsonObject, String id, String value, boolean valueError) { addJsonParameter(jsonObject, id, value, null, valueError); } private void addJsonParameter(JsonObject jsonObject, String id, String value, ParameterValueType valueType, boolean valueError) { JsonParameter jsonParameter = new JsonParameter(); jsonParameter.setId(id); jsonParameter.setValue(value); if (valueType != null) { jsonParameter.setValueType(valueType.name()); } jsonParameter.setValueError(valueError); jsonObject.getParameters().add(jsonParameter); } private JsonObject givenConfigRequest() { JsonObject configRequest = new JsonObject(); configRequest.setMessageType(MessageType.CONFIG_REQUEST); configRequest.setLocale("en"); configRequest.setParameters(new ArrayList<JsonParameter>()); return configRequest; } private JsonObject givenParameters() { JsonObject parameters = new JsonObject(); parameters.setLocale("en"); parameters.setMessageType(MessageType.CONFIG_RESPONSE); parameters.setResponseCode(ResponseCode.CONFIGURATION_FINISHED); parameters.setParameters(new ArrayList<JsonParameter>()); return parameters; } private void addPricedParameterRow(VOParameter parameter) { PricedParameterRow pricedParRow = new PricedParameterRow(parameter, null, null, null, false); model.getServiceParameters().add(pricedParRow); } private void addPricedParameterRow(String id, ParameterValueType valueType, boolean mandatory, String... optionIds) { VOParameter parameter = addVoParameter(createParDefinition(id, valueType, mandatory, null, null, optionIds)); addPricedParameterRow(parameter); } private VOParameter addVoParameter(String id, ParameterValueType valueType) { VOParameterDefinition voParameterDef = new VOParameterDefinition(); voParameterDef.setParameterId(id); if (valueType != null) { voParameterDef.setValueType(valueType); } VOParameter voParameter = new VOParameter(voParameterDef); voParameter.setValue(DEFAULT_VALUE); model.getService().getVO().getParameters().add(voParameter); return voParameter; } private VOParameter addVoParameter(VOParameterDefinition voParameterDef) { VOParameter voParameter = new VOParameter(voParameterDef); voParameter.setValue(DEFAULT_VALUE); model.getService().getVO().getParameters().add(voParameter); return voParameter; } private VOParameterDefinition createParDefinition(String id, ParameterValueType valueType, boolean mandatory, Long minValue, Long maxValue, String... optionIds) { VOParameterDefinition parDefinition = new VOParameterDefinition(); parDefinition.setParameterId(id); parDefinition.setMandatory(mandatory); parDefinition.setValueType(valueType); parDefinition.setMinValue(minValue); parDefinition.setMaxValue(maxValue); if (optionIds.length > 0) { List<VOParameterOption> options = new ArrayList<>(); for (String optionId : optionIds) { options.add(new VOParameterOption(optionId, optionId + "Description", id)); } parDefinition.setParameterOptions(options); } return parDefinition; } private VOParameter byId(String id) { return JsonUtils.findParameterById(id, model.getService()); } private void addParameter(JsonObject parameters, String id, ParameterValueType valueType, String value) { addJsonParameter(parameters, id, value, valueType, false); addVoParameter(id, valueType); } private void addParameter(JsonObject parameters, String id, ParameterValueType valueType, String value, String voValue) { addJsonParameter(parameters, id, value, valueType, false); addVoParameter(id, valueType, voValue); } private VOParameter addVoParameter(String id) { return addVoParameter(id, null); } private VOParameter addVoParameter(String id, ParameterValueType valueType, String value) { VOParameterDefinition voParameterDef = new VOParameterDefinition(); voParameterDef.setParameterId(id); if (valueType != null) { voParameterDef.setValueType(valueType); } VOParameter voParameter = new VOParameter(voParameterDef); voParameter.setValue(value); model.getService().getVO().getParameters().add(voParameter); return voParameter; } private void addJsonParameter(JsonObject parameters, String id, String value) { addJsonParameter(parameters, id, value, false); } private void addPricedParameterRow(String id, ParameterValueType valueType, boolean mandatory, Long minValue, Long maxValue) { VOParameter parameter = addVoParameter(createParDefinition(id, valueType, mandatory, minValue, maxValue)); addPricedParameterRow(parameter); } @Test public void isServiceForSubscription_NotSubscriptionManager() { // given Service service = new Service(new VOService()); service.setSubscribable(true); VOUserDetails emptyRoleUser = mockUserDetailsWithRoles(); doReturn(emptyRoleUser).when(userBean) .getUserFromSessionWithoutException(); // when boolean result = bean.isServiceReadyForSubscription(service); // then assertFalse(result); } @Test public void isServiceForSubscription_SubscriptionManager() { // given Service service = new Service(new VOService()); service.setSubscribable(true); VOUserDetails subscriptionManager = mockUserDetailsWithRoles(UserRoleType.SUBSCRIPTION_MANAGER); doReturn(subscriptionManager).when(userBean) .getUserFromSessionWithoutException(); // when boolean result = bean.isServiceReadyForSubscription(service); // then assertTrue(result); } @Test public void isServiceForSubscription_UnitAdmin() { // given Service service = new Service(new VOService()); service.setSubscribable(true); VOUserDetails unitAdministrator = mockUserDetailsWithRoles(UserRoleType.UNIT_ADMINISTRATOR); doReturn(unitAdministrator).when(userBean) .getUserFromSessionWithoutException(); // when boolean result = bean.isServiceReadyForSubscription(service); // then assertTrue(result); } private VOUserDetails mockUserDetailsWithRoles(UserRoleType... roles) { VOUserDetails userDetails = new VOUserDetails(); userDetails.setUserRoles(Sets.newHashSet(roles)); return userDetails; } private void prepareDataForTestUnitSelection(Set<UserRoleType> userRoles, boolean isUnitSelected) { VOUserDetails voUserDetails = new VOUserDetails(); voUserDetails.setKey(1001L); voUserDetails.setUserRoles(userRoles); doReturn(voUserDetails).when(ui).getUserFromSessionWithoutException(); mock(JSFUtils.class); if (isUnitSelected) { unitCtrl.getModel().setSelectedUnitId(1000L); } else { unitCtrl.getModel().setSelectedUnitId(0L); } bean.getModel().getService().setPriceModel(new PriceModel(new VOPriceModel())); doNothing().when(bean).updateSelectedUnit(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.flink.streaming.connectors.kinesis.proxy; import org.apache.flink.streaming.connectors.kinesis.internals.publisher.fanout.FanOutRecordPublisherConfiguration; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; import software.amazon.awssdk.services.kinesis.model.DeregisterStreamConsumerRequest; import software.amazon.awssdk.services.kinesis.model.DeregisterStreamConsumerResponse; import software.amazon.awssdk.services.kinesis.model.DescribeStreamConsumerRequest; import software.amazon.awssdk.services.kinesis.model.DescribeStreamConsumerResponse; import software.amazon.awssdk.services.kinesis.model.DescribeStreamSummaryRequest; import software.amazon.awssdk.services.kinesis.model.DescribeStreamSummaryResponse; import software.amazon.awssdk.services.kinesis.model.LimitExceededException; import software.amazon.awssdk.services.kinesis.model.RegisterStreamConsumerRequest; import software.amazon.awssdk.services.kinesis.model.RegisterStreamConsumerResponse; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler; import java.util.Properties; import java.util.concurrent.CompletableFuture; import static java.util.Collections.emptyList; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.DEREGISTER_STREAM_BACKOFF_BASE; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.DEREGISTER_STREAM_BACKOFF_EXPONENTIAL_CONSTANT; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.DEREGISTER_STREAM_BACKOFF_MAX; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.DESCRIBE_STREAM_CONSUMER_BACKOFF_BASE; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.DESCRIBE_STREAM_CONSUMER_BACKOFF_EXPONENTIAL_CONSTANT; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.DESCRIBE_STREAM_CONSUMER_BACKOFF_MAX; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.EFO_CONSUMER_NAME; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.RECORD_PUBLISHER_TYPE; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.REGISTER_STREAM_BACKOFF_BASE; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.REGISTER_STREAM_BACKOFF_EXPONENTIAL_CONSTANT; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.REGISTER_STREAM_BACKOFF_MAX; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.RecordPublisherType.EFO; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.STREAM_DESCRIBE_BACKOFF_BASE; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.STREAM_DESCRIBE_BACKOFF_EXPONENTIAL_CONSTANT; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.STREAM_DESCRIBE_BACKOFF_MAX; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.STREAM_DESCRIBE_RETRIES; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.SUBSCRIBE_TO_SHARD_BACKOFF_BASE; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.SUBSCRIBE_TO_SHARD_BACKOFF_EXPONENTIAL_CONSTANT; import static org.apache.flink.streaming.connectors.kinesis.config.ConsumerConfigConstants.SUBSCRIBE_TO_SHARD_BACKOFF_MAX; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** Test for methods in the {@link KinesisProxyV2} class. */ public class KinesisProxyV2Test { private static final long EXPECTED_SUBSCRIBE_TO_SHARD_MAX = 1; private static final long EXPECTED_SUBSCRIBE_TO_SHARD_BASE = 2; private static final double EXPECTED_SUBSCRIBE_TO_SHARD_POW = 0.1; private static final long EXPECTED_REGISTRATION_MAX = 2; private static final long EXPECTED_REGISTRATION_BASE = 3; private static final double EXPECTED_REGISTRATION_POW = 0.2; private static final long EXPECTED_DEREGISTRATION_MAX = 3; private static final long EXPECTED_DEREGISTRATION_BASE = 4; private static final double EXPECTED_DEREGISTRATION_POW = 0.3; private static final long EXPECTED_DESCRIBE_CONSUMER_MAX = 4; private static final long EXPECTED_DESCRIBE_CONSUMER_BASE = 5; private static final double EXPECTED_DESCRIBE_CONSUMER_POW = 0.4; private static final long EXPECTED_DESCRIBE_STREAM_MAX = 5; private static final long EXPECTED_DESCRIBE_STREAM_BASE = 6; private static final double EXPECTED_DESCRIBE_STREAM_POW = 0.5; private static final int EXPECTED_DESCRIBE_STREAM_RETRIES = 10; @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void testSubscribeToShard() { KinesisAsyncClient kinesis = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( kinesis, mock(SdkAsyncHttpClient.class), createConfiguration(), mock(FullJitterBackoff.class)); SubscribeToShardRequest request = SubscribeToShardRequest.builder().build(); SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler.builder().subscriber(event -> {}).build(); proxy.subscribeToShard(request, responseHandler); verify(kinesis).subscribeToShard(eq(request), eq(responseHandler)); } @Test public void testCloseInvokesClientClose() { SdkAsyncHttpClient httpClient = mock(SdkAsyncHttpClient.class); KinesisAsyncClient kinesis = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( kinesis, httpClient, createConfiguration(), mock(FullJitterBackoff.class)); proxy.close(); verify(kinesis).close(); verify(httpClient).close(); } @Test public void testRegisterStreamConsumer() throws Exception { KinesisAsyncClient client = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( client, mock(SdkAsyncHttpClient.class), createConfiguration(), mock(FullJitterBackoff.class)); RegisterStreamConsumerResponse expected = RegisterStreamConsumerResponse.builder().build(); ArgumentCaptor<RegisterStreamConsumerRequest> requestCaptor = ArgumentCaptor.forClass(RegisterStreamConsumerRequest.class); when(client.registerStreamConsumer(requestCaptor.capture())) .thenReturn(CompletableFuture.completedFuture(expected)); RegisterStreamConsumerResponse actual = proxy.registerStreamConsumer("arn", "name"); assertEquals(expected, actual); RegisterStreamConsumerRequest request = requestCaptor.getValue(); assertEquals("arn", request.streamARN()); assertEquals("name", request.consumerName()); } @Test public void testRegisterStreamConsumerBackoffJitter() throws Exception { FullJitterBackoff backoff = mock(FullJitterBackoff.class); KinesisAsyncClient client = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( client, mock(SdkAsyncHttpClient.class), createConfiguration(), backoff); when(client.registerStreamConsumer(any(RegisterStreamConsumerRequest.class))) .thenThrow(new RuntimeException(LimitExceededException.builder().build())) .thenReturn( CompletableFuture.completedFuture( RegisterStreamConsumerResponse.builder().build())); proxy.registerStreamConsumer("arn", "name"); verify(backoff).sleep(anyLong()); verify(backoff) .calculateFullJitterBackoff( EXPECTED_REGISTRATION_BASE, EXPECTED_REGISTRATION_MAX, EXPECTED_REGISTRATION_POW, 1); } @Test public void testDeregisterStreamConsumer() throws Exception { KinesisAsyncClient client = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( client, mock(SdkAsyncHttpClient.class), createConfiguration(), mock(FullJitterBackoff.class)); DeregisterStreamConsumerResponse expected = DeregisterStreamConsumerResponse.builder().build(); ArgumentCaptor<DeregisterStreamConsumerRequest> requestCaptor = ArgumentCaptor.forClass(DeregisterStreamConsumerRequest.class); when(client.deregisterStreamConsumer(requestCaptor.capture())) .thenReturn(CompletableFuture.completedFuture(expected)); DeregisterStreamConsumerResponse actual = proxy.deregisterStreamConsumer("arn"); assertEquals(expected, actual); DeregisterStreamConsumerRequest request = requestCaptor.getValue(); assertEquals("arn", request.consumerARN()); } @Test public void testDeregisterStreamConsumerBackoffJitter() throws Exception { FullJitterBackoff backoff = mock(FullJitterBackoff.class); KinesisAsyncClient client = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( client, mock(SdkAsyncHttpClient.class), createConfiguration(), backoff); when(client.deregisterStreamConsumer(any(DeregisterStreamConsumerRequest.class))) .thenThrow(new RuntimeException(LimitExceededException.builder().build())) .thenReturn( CompletableFuture.completedFuture( DeregisterStreamConsumerResponse.builder().build())); proxy.deregisterStreamConsumer("arn"); verify(backoff).sleep(anyLong()); verify(backoff) .calculateFullJitterBackoff( EXPECTED_DEREGISTRATION_BASE, EXPECTED_DEREGISTRATION_MAX, EXPECTED_DEREGISTRATION_POW, 1); } @Test public void testDescribeStreamConsumerWithStreamConsumerArn() throws Exception { KinesisAsyncClient client = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( client, mock(SdkAsyncHttpClient.class), createConfiguration(), mock(FullJitterBackoff.class)); DescribeStreamConsumerResponse expected = DescribeStreamConsumerResponse.builder().build(); ArgumentCaptor<DescribeStreamConsumerRequest> requestCaptor = ArgumentCaptor.forClass(DescribeStreamConsumerRequest.class); when(client.describeStreamConsumer(requestCaptor.capture())) .thenReturn(CompletableFuture.completedFuture(expected)); DescribeStreamConsumerResponse actual = proxy.describeStreamConsumer("arn"); assertEquals(expected, actual); DescribeStreamConsumerRequest request = requestCaptor.getValue(); assertEquals("arn", request.consumerARN()); } @Test public void testDescribeStreamConsumerWithStreamArnAndConsumerName() throws Exception { KinesisAsyncClient client = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( client, mock(SdkAsyncHttpClient.class), createConfiguration(), mock(FullJitterBackoff.class)); DescribeStreamConsumerResponse expected = DescribeStreamConsumerResponse.builder().build(); ArgumentCaptor<DescribeStreamConsumerRequest> requestCaptor = ArgumentCaptor.forClass(DescribeStreamConsumerRequest.class); when(client.describeStreamConsumer(requestCaptor.capture())) .thenReturn(CompletableFuture.completedFuture(expected)); DescribeStreamConsumerResponse actual = proxy.describeStreamConsumer("arn", "name"); assertEquals(expected, actual); DescribeStreamConsumerRequest request = requestCaptor.getValue(); assertEquals("arn", request.streamARN()); assertEquals("name", request.consumerName()); } @Test public void testDescribeStreamConsumerBackoffJitter() throws Exception { FullJitterBackoff backoff = mock(FullJitterBackoff.class); KinesisAsyncClient client = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( client, mock(SdkAsyncHttpClient.class), createConfiguration(), backoff); when(client.describeStreamConsumer(any(DescribeStreamConsumerRequest.class))) .thenThrow(new RuntimeException(LimitExceededException.builder().build())) .thenReturn( CompletableFuture.completedFuture( DescribeStreamConsumerResponse.builder().build())); proxy.describeStreamConsumer("arn"); verify(backoff).sleep(anyLong()); verify(backoff) .calculateFullJitterBackoff( EXPECTED_DESCRIBE_CONSUMER_BASE, EXPECTED_DESCRIBE_CONSUMER_MAX, EXPECTED_DESCRIBE_CONSUMER_POW, 1); } @Test public void testDescribeStreamSummary() throws Exception { KinesisAsyncClient client = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( client, mock(SdkAsyncHttpClient.class), createConfiguration(), mock(FullJitterBackoff.class)); DescribeStreamSummaryResponse expected = DescribeStreamSummaryResponse.builder().build(); ArgumentCaptor<DescribeStreamSummaryRequest> requestCaptor = ArgumentCaptor.forClass(DescribeStreamSummaryRequest.class); when(client.describeStreamSummary(requestCaptor.capture())) .thenReturn(CompletableFuture.completedFuture(expected)); DescribeStreamSummaryResponse actual = proxy.describeStreamSummary("stream"); assertEquals(expected, actual); DescribeStreamSummaryRequest request = requestCaptor.getValue(); assertEquals("stream", request.streamName()); } @Test public void testDescribeStreamSummaryBackoffJitter() throws Exception { FullJitterBackoff backoff = mock(FullJitterBackoff.class); KinesisAsyncClient client = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( client, mock(SdkAsyncHttpClient.class), createConfiguration(), backoff); when(client.describeStreamSummary(any(DescribeStreamSummaryRequest.class))) .thenThrow(new RuntimeException(LimitExceededException.builder().build())) .thenReturn( CompletableFuture.completedFuture( DescribeStreamSummaryResponse.builder().build())); proxy.describeStreamSummary("arn"); verify(backoff).sleep(anyLong()); verify(backoff) .calculateFullJitterBackoff( EXPECTED_DESCRIBE_STREAM_BASE, EXPECTED_DESCRIBE_STREAM_MAX, EXPECTED_DESCRIBE_STREAM_POW, 1); } @Test public void testDescribeStreamSummaryFailsAfterMaxRetries() throws Exception { exception.expect(RuntimeException.class); exception.expectMessage("Retries exceeded - all 10 retry attempts failed."); FullJitterBackoff backoff = mock(FullJitterBackoff.class); KinesisAsyncClient client = mock(KinesisAsyncClient.class); KinesisProxyV2 proxy = new KinesisProxyV2( client, mock(SdkAsyncHttpClient.class), createConfiguration(), backoff); when(client.describeStreamSummary(any(DescribeStreamSummaryRequest.class))) .thenThrow(new RuntimeException(LimitExceededException.builder().build())); proxy.describeStreamSummary("arn"); } private FanOutRecordPublisherConfiguration createConfiguration() { return new FanOutRecordPublisherConfiguration(createEfoProperties(), emptyList()); } private Properties createEfoProperties() { Properties config = new Properties(); config.setProperty(RECORD_PUBLISHER_TYPE, EFO.name()); config.setProperty(EFO_CONSUMER_NAME, "dummy-efo-consumer"); config.setProperty( SUBSCRIBE_TO_SHARD_BACKOFF_BASE, String.valueOf(EXPECTED_SUBSCRIBE_TO_SHARD_BASE)); config.setProperty( SUBSCRIBE_TO_SHARD_BACKOFF_MAX, String.valueOf(EXPECTED_SUBSCRIBE_TO_SHARD_MAX)); config.setProperty( SUBSCRIBE_TO_SHARD_BACKOFF_EXPONENTIAL_CONSTANT, String.valueOf(EXPECTED_SUBSCRIBE_TO_SHARD_POW)); config.setProperty( REGISTER_STREAM_BACKOFF_BASE, String.valueOf(EXPECTED_REGISTRATION_BASE)); config.setProperty(REGISTER_STREAM_BACKOFF_MAX, String.valueOf(EXPECTED_REGISTRATION_MAX)); config.setProperty( REGISTER_STREAM_BACKOFF_EXPONENTIAL_CONSTANT, String.valueOf(EXPECTED_REGISTRATION_POW)); config.setProperty( DEREGISTER_STREAM_BACKOFF_BASE, String.valueOf(EXPECTED_DEREGISTRATION_BASE)); config.setProperty( DEREGISTER_STREAM_BACKOFF_MAX, String.valueOf(EXPECTED_DEREGISTRATION_MAX)); config.setProperty( DEREGISTER_STREAM_BACKOFF_EXPONENTIAL_CONSTANT, String.valueOf(EXPECTED_DEREGISTRATION_POW)); config.setProperty( DESCRIBE_STREAM_CONSUMER_BACKOFF_BASE, String.valueOf(EXPECTED_DESCRIBE_CONSUMER_BASE)); config.setProperty( DESCRIBE_STREAM_CONSUMER_BACKOFF_MAX, String.valueOf(EXPECTED_DESCRIBE_CONSUMER_MAX)); config.setProperty( DESCRIBE_STREAM_CONSUMER_BACKOFF_EXPONENTIAL_CONSTANT, String.valueOf(EXPECTED_DESCRIBE_CONSUMER_POW)); config.setProperty( STREAM_DESCRIBE_BACKOFF_BASE, String.valueOf(EXPECTED_DESCRIBE_STREAM_BASE)); config.setProperty( STREAM_DESCRIBE_BACKOFF_MAX, String.valueOf(EXPECTED_DESCRIBE_STREAM_MAX)); config.setProperty( STREAM_DESCRIBE_BACKOFF_EXPONENTIAL_CONSTANT, String.valueOf(EXPECTED_DESCRIBE_STREAM_POW)); config.setProperty( STREAM_DESCRIBE_RETRIES, String.valueOf(EXPECTED_DESCRIBE_STREAM_RETRIES)); return config; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 java.util; import com.google.j2objc.annotations.Weak; import com.google.j2objc.annotations.WeakOuter; /** * LinkedHashMap is an implementation of {@link Map} that guarantees iteration order. * All optional operations are supported. * * <p>All elements are permitted as keys or values, including null. * * <p>Entries are kept in a doubly-linked list. The iteration order is, by default, the * order in which keys were inserted. Reinserting an already-present key doesn't change the * order. If the three argument constructor is used, and {@code accessOrder} is specified as * {@code true}, the iteration will be in the order that entries were accessed. * The access order is affected by {@code put}, {@code get}, and {@code putAll} operations, * but not by operations on the collection views. * * <p>Note: the implementation of {@code LinkedHashMap} is not synchronized. * If one thread of several threads accessing an instance modifies the map * structurally, access to the map needs to be synchronized. For * insertion-ordered instances a structural modification is an operation that * removes or adds an entry. Access-ordered instances also are structurally * modified by {@code put}, {@code get}, and {@code putAll} since these methods * change the order of the entries. Changes in the value of an entry are not structural changes. * * <p>The {@code Iterator} created by calling the {@code iterator} method * may throw a {@code ConcurrentModificationException} if the map is structurally * changed while an iterator is used to iterate over the elements. Only the * {@code remove} method that is provided by the iterator allows for removal of * elements during iteration. It is not possible to guarantee that this * mechanism works in all cases of unsynchronized concurrent modification. It * should only be used for debugging purposes. */ public class LinkedHashMap<K, V> extends HashMap<K, V> { /** * A dummy entry in the circular linked list of entries in the map. * The first real entry is header.nxt, and the last is header.prv. * If the map is empty, header.nxt == header && header.prv == header. */ transient LinkedEntry<K, V> header; /** * True if access ordered, false if insertion ordered. */ private final boolean accessOrder; /** * Constructs a new empty {@code LinkedHashMap} instance. */ public LinkedHashMap() { init(); accessOrder = false; } /** * Constructs a new {@code LinkedHashMap} instance with the specified * capacity. * * @param initialCapacity * the initial capacity of this map. * @throws IllegalArgumentException * when the capacity is less than zero. */ public LinkedHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * Constructs a new {@code LinkedHashMap} instance with the specified * capacity and load factor. * * @param initialCapacity * the initial capacity of this map. * @param loadFactor * the initial load factor. * @throws IllegalArgumentException * when the capacity is less than zero or the load factor is * less or equal to zero. */ public LinkedHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, false); } /** * Constructs a new {@code LinkedHashMap} instance with the specified * capacity, load factor and a flag specifying the ordering behavior. * * @param initialCapacity * the initial capacity of this hash map. * @param loadFactor * the initial load factor. * @param accessOrder * {@code true} if the ordering should be done based on the last * access (from least-recently accessed to most-recently * accessed), and {@code false} if the ordering should be the * order in which the entries were inserted. * @throws IllegalArgumentException * when the capacity is less than zero or the load factor is * less or equal to zero. */ public LinkedHashMap( int initialCapacity, float loadFactor, boolean accessOrder) { super(initialCapacity, loadFactor); init(); this.accessOrder = accessOrder; } /** * Constructs a new {@code LinkedHashMap} instance containing the mappings * from the specified map. The order of the elements is preserved. * * @param map * the mappings to add. */ public LinkedHashMap(Map<? extends K, ? extends V> map) { this(capacityForInitSize(map.size())); constructorPutAll(map); } @Override void init() { header = new LinkedEntry<K, V>(); } /** * LinkedEntry adds nxt/prv double-links to plain HashMapEntry. */ static class LinkedEntry<K, V> extends HashMapEntry<K, V> { @Weak LinkedEntry<K, V> nxt; @Weak LinkedEntry<K, V> prv; /** Create the header entry */ LinkedEntry() { super(null, null, 0, null); nxt = prv = this; } /** Create a normal entry */ LinkedEntry(K key, V value, int hash, HashMapEntry<K, V> next, LinkedEntry<K, V> nxt, LinkedEntry<K, V> prv) { super(key, value, hash, next); this.nxt = nxt; this.prv = prv; } } /** * Returns the eldest entry in the map, or {@code null} if the map is empty. * @hide */ public Entry<K, V> eldest() { LinkedEntry<K, V> eldest = header.nxt; return eldest != header ? eldest : null; } /** * Evicts eldest entry if instructed, creates a new entry and links it in * as head of linked list. This method should call constructorNewEntry * (instead of duplicating code) if the performance of your VM permits. * * <p>It may seem strange that this method is tasked with adding the entry * to the hash table (which is properly the province of our superclass). * The alternative of passing the "next" link in to this method and * returning the newly created element does not work! If we remove an * (eldest) entry that happens to be the first entry in the same bucket * as the newly created entry, the "next" link would become invalid, and * the resulting hash table corrupt. * * Modified to avoid extra retain/autorelease calls. */ @Override native void addNewEntry(K key, V value, int hash, int index) /*-[ JavaUtilLinkedHashMap_LinkedEntry *header = self->header_; JavaUtilLinkedHashMap_LinkedEntry *eldest = header->nxt_; if (eldest != header && [self removeEldestEntryWithJavaUtilMap_Entry:eldest]) { [self removeWithId:eldest->key_]; } JavaUtilLinkedHashMap_LinkedEntry *oldTail = header->prv_; JavaUtilLinkedHashMap_LinkedEntry *newTail = [[JavaUtilLinkedHashMap_LinkedEntry alloc] initWithId:key withId:value withInt:hash_ withJavaUtilHashMap_HashMapEntry:nil withJavaUtilLinkedHashMap_LinkedEntry:header withJavaUtilLinkedHashMap_LinkedEntry:oldTail]; newTail->next_ = self->table_->buffer_[index]; self->table_->buffer_[index] = oldTail->nxt_ = header->prv_ = newTail; ]-*/; @Override native void addNewEntryForNullKey(V value) /*-[ JavaUtilLinkedHashMap_LinkedEntry *header = self->header_; JavaUtilLinkedHashMap_LinkedEntry *eldest = header->nxt_; if (eldest != header && [self removeEldestEntryWithJavaUtilMap_Entry:eldest]) { [self removeWithId:eldest->key_]; } JavaUtilLinkedHashMap_LinkedEntry *oldTail = header->prv_; JavaUtilLinkedHashMap_LinkedEntry *newTail = [[JavaUtilLinkedHashMap_LinkedEntry alloc] initWithId:nil withId:value withInt:0 withJavaUtilHashMap_HashMapEntry:nil withJavaUtilLinkedHashMap_LinkedEntry:header withJavaUtilLinkedHashMap_LinkedEntry:oldTail]; JavaUtilHashMap_setAndConsume_entryForNullKey_(self, oldTail->nxt_ = header->prv_ = newTail); ]-*/; /** * As above, but without eviction. * * This native method has a modified contract from the original version. * It must return a retained entry object. And it must avoid retaining the * "first" parameter when setting it to the "next" field of the new entry. */ @Override native HashMapEntry<K, V> constructorNewRetainedEntry( K key, V value, int hash, HashMapEntry<K, V> next) /*-[ JavaUtilLinkedHashMap_LinkedEntry *header = self->header_; JavaUtilLinkedHashMap_LinkedEntry *oldTail = header->prv_; JavaUtilLinkedHashMap_LinkedEntry *newTail = [[JavaUtilLinkedHashMap_LinkedEntry alloc] initWithId:key withId:value withInt:hash_ withJavaUtilHashMap_HashMapEntry:nil withJavaUtilLinkedHashMap_LinkedEntry:header withJavaUtilLinkedHashMap_LinkedEntry:oldTail]; newTail->next_ = next; return oldTail->nxt_ = header->prv_ = newTail; ]-*/; /** * Returns the value of the mapping with the specified key. * * @param key * the key. * @return the value of the mapping with the specified key, or {@code null} * if no mapping for the specified key is found. */ @Override public V get(Object key) { /* * This method is overridden to eliminate the need for a polymorphic * invocation in superclass at the expense of code duplication. */ if (key == null) { HashMapEntry<K, V> e = entryForNullKey; if (e == null) return null; if (accessOrder) makeTail((LinkedEntry<K, V>) e); return e.value; } int hash = Collections.secondaryHash(key); HashMapEntry<K, V>[] tab = table; for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { K eKey = e.key; if (eKey == key || (e.hash == hash && key.equals(eKey))) { if (accessOrder) makeTail((LinkedEntry<K, V>) e); return e.value; } } return null; } /** * Relinks the given entry to the tail of the list. Under access ordering, * this method is invoked whenever the value of a pre-existing entry is * read by Map.get or modified by Map.put. */ private void makeTail(LinkedEntry<K, V> e) { // Unlink e e.prv.nxt = e.nxt; e.nxt.prv = e.prv; // Relink e as tail LinkedEntry<K, V> header = this.header; LinkedEntry<K, V> oldTail = header.prv; e.nxt = header; e.prv = oldTail; oldTail.nxt = header.prv = e; modCount++; } @Override void preModify(HashMapEntry<K, V> e) { if (accessOrder) { makeTail((LinkedEntry<K, V>) e); } } @Override void postRemove(HashMapEntry<K, V> e) { LinkedEntry<K, V> le = (LinkedEntry<K, V>) e; le.prv.nxt = le.nxt; le.nxt.prv = le.prv; le.nxt = le.prv = null; // Help the GC (for performance) } /** * This override is done for LinkedHashMap performance: iteration is cheaper * via LinkedHashMap nxt links. */ @Override public boolean containsValue(Object value) { if (value == null) { for (LinkedEntry<K, V> header = this.header, e = header.nxt; e != header; e = e.nxt) { if (e.value == null) { return true; } } return false; } // value is non-null for (LinkedEntry<K, V> header = this.header, e = header.nxt; e != header; e = e.nxt) { if (value.equals(e.value)) { return true; } } return false; } public void clear() { super.clear(); // Clear all links to help GC LinkedEntry<K, V> header = this.header; for (LinkedEntry<K, V> e = header.nxt; e != header; ) { LinkedEntry<K, V> nxt = e.nxt; e.nxt = e.prv = null; e = nxt; } header.nxt = header.prv = header; } @WeakOuter private abstract class LinkedHashIterator<T> implements Iterator<T> { LinkedEntry<K, V> next = header.nxt; LinkedEntry<K, V> lastReturned = null; int expectedModCount = modCount; public final boolean hasNext() { return next != header; } final LinkedEntry<K, V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); LinkedEntry<K, V> e = next; if (e == header) throw new NoSuchElementException(); next = e.nxt; return lastReturned = e; } public final void remove() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (lastReturned == null) throw new IllegalStateException(); LinkedHashMap.this.remove(lastReturned.key); lastReturned = null; expectedModCount = modCount; } } private final class KeyIterator extends LinkedHashIterator<K> { public final K next() { return nextEntry().key; } } private final class ValueIterator extends LinkedHashIterator<V> { public final V next() { return nextEntry().value; } } private final class EntryIterator extends LinkedHashIterator<Map.Entry<K, V>> { public final Map.Entry<K, V> next() { return nextEntry(); } } // Override view iterator methods to generate correct iteration order @Override Iterator<K> newKeyIterator() { return new KeyIterator(); } @Override Iterator<V> newValueIterator() { return new ValueIterator(); } @Override Iterator<Map.Entry<K, V>> newEntryIterator() { return new EntryIterator(); } protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return false; } private static final long serialVersionUID = 3801124242820219131L; /*-[ - (NSUInteger)enumerateEntriesWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { __unsafe_unretained JavaUtilLinkedHashMap_LinkedEntry *entry; if (state->state == 0) { state->state = 1; state->mutationsPtr = (unsigned long *) &modCount_; entry = header_->nxt_; } else { entry = (void *) state->extra[0]; } state->itemsPtr = stackbuf; NSUInteger objCount = 0; while (entry != header_ && objCount < len) { *stackbuf++ = entry; objCount++; entry = entry->nxt_; } state->extra[0] = (unsigned long) entry; return objCount; } ]-*/ }
/* * Copyright 2016 Lawrence Ruffin, Leland Lopez, Brittany Cruz, Stephen Anspach * * Developed in collaboration with the Hawaii State Digital Archives. * * 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.hida.controller; import com.hida.model.BadParameterException; import com.hida.model.DefaultSetting; import com.hida.model.IdGenerator; import com.hida.model.Pid; import com.hida.model.Token; import com.hida.service.MinterService; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.Map; import java.util.Set; import org.springframework.web.bind.annotation.ExceptionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.locks.ReentrantLock; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; /** * A Controller that handles the requests and responses between the user and the * Minter. * * @author lruffin */ @RestController @RequestMapping("/Minter") public class MinterController { /* * Logger; logfile to be stored in resource folder */ private static final Logger LOGGER = LoggerFactory.getLogger(MinterController.class); /** * A fair lock used to synchronize access to the minter service. */ private static final ReentrantLock requestLock_ = new ReentrantLock(true); /** * The service to use to mint IDs. */ @Autowired private MinterService minterService_; /** * Using values sent from the /administration end point, this method updates * the DefaultSetting object, database, and the properties file. The names * of the requested parameters are given by the name attributes in the * administration panel. * * @param prepend String of characters that determine the domain of each Pid * @param idprefix String of characters that prefixes each Pid * @param cacheSize The size of the cache that'll be generated whenever the * context is refreshed. If an empty String is returned to cacheSize then * the cacheSize will not be updated. * @param mintType Auto Generator is used if true, Custom Generator if false * @param mintOrder Pids are generated randomly if true, ordered if false * @param sansvowel Pids will contain vowels if true, false othwerise * @param idlength the length of the pid's root name * @param charmapping the mapping used when Custom Generator is selected * @param digits digits is included if selected * @param lowercase lowercase is included if selected * @param uppercase uppercase is included if selected * @param request HTTP request from the administration panel * @param response HTTP response that redirects to the administration panel * after updating the new settings. * @throws Exception */ @RequestMapping(value = {"/administration"}, method = {RequestMethod.POST}) public void handleForm(@RequestParam(required = false) String prepend, @RequestParam(required = false) String idprefix, @RequestParam(required = false) String cacheSize, @RequestParam String mintType, @RequestParam String mintOrder, @RequestParam(defaultValue = "true") boolean sansvowel, @RequestParam(required = false, defaultValue = "-1") int idlength, @RequestParam(required = false) String charmapping, @RequestParam(required = false) boolean digits, @RequestParam(required = false) boolean lowercase, @RequestParam(required = false) boolean uppercase, HttpServletRequest request, HttpServletResponse response) throws Exception { // prevents other clients from accessing the database whenever the form is submitted requestLock_.lock(); try { DefaultSetting oldSetting = minterService_.getStoredSetting(); DefaultSetting newSetting; LOGGER.info("in handleForm"); boolean auto = mintType.equals("auto"); boolean random = mintOrder.equals("random"); long size; if (cacheSize.isEmpty()) { size = oldSetting.getCacheSize(); } else { size = Long.parseLong(cacheSize); } // assign values based on which minter type was selected if (auto) { // gets the token value Token tokenType; if (digits && !lowercase && !uppercase) { tokenType = Token.DIGIT; } else if (!digits && lowercase && !uppercase) { tokenType = (sansvowel) ? Token.LOWER_CONSONANTS : Token.LOWER_ALPHABET; } else if (!digits && !lowercase && uppercase) { tokenType = (sansvowel) ? Token.UPPER_CONSONANTS : Token.UPPER_ALPHABET; } else if (!digits && lowercase && uppercase) { tokenType = (sansvowel) ? Token.MIXED_CONSONANTS : Token.MIXED_ALPHABET; } else if (digits && lowercase && !uppercase) { tokenType = (sansvowel) ? Token.LOWER_CONSONANTS_EXTENDED : Token.LOWER_ALPHABET_EXTENDED; } else if (digits && !lowercase && uppercase) { tokenType = (sansvowel) ? Token.UPPER_CONSONANTS_EXTENDED : Token.UPPER_ALPHABET_EXTENDED; } else if (digits && lowercase && uppercase) { tokenType = (sansvowel) ? Token.MIXED_CONSONANTS_EXTENDED : Token.MIXED_ALPHABET_EXTENDED; } else { throw new BadParameterException(); } // create new defaultsetting object newSetting = new DefaultSetting(prepend, idprefix, size, tokenType, oldSetting.getCharMap(), idlength, sansvowel, auto, random); } else { // validate charmapping if (charmapping == null || charmapping.isEmpty()) { throw new BadParameterException(); } // create new defaultsetting object newSetting = new DefaultSetting(prepend, idprefix, size, oldSetting.getTokenType(), charmapping, oldSetting.getRootLength(), sansvowel, auto, random); } minterService_.updateCurrentSetting(newSetting); } finally { // unlocks RequestLock and gives access to longest waiting thread requestLock_.unlock(); LOGGER.warn("Request to update default settings finished, UNLOCKING MINTER"); } // redirect to the administration panel response.sendRedirect("administration"); } /** * Creates a path to mint ids. If parameters aren't given then mintPids will * resort to using the default values found in DefaultSetting.properties * * @param requestedAmount requested number of ids to mint * @param parameters parameters given by user to instill variety in ids * @return paths user to mint.jsp * @throws Exception catches all sorts of exceptions that may be thrown by * any methods */ @ResponseStatus(code = HttpStatus.CREATED) @RequestMapping(value = {"/mint/{requestedAmount}"}, method = {RequestMethod.GET}, produces = "application/json") public Set<Pid> mintPids(@PathVariable long requestedAmount, @RequestParam Map<String, String> parameters) throws Exception { // ensure that only one thread access the minter at any given time requestLock_.lock(); Set<Pid> pidSet; try { LOGGER.info("Request to Minter made, LOCKING MINTER"); // validate amount validateAmount(requestedAmount); // override default settings where applicable DefaultSetting tempSetting = overrideDefaultSetting(parameters, minterService_.getStoredSetting()); // create the set of ids pidSet = minterService_.mint(requestedAmount, tempSetting); } finally { // unlocks RequestLock and gives access to longest waiting thread requestLock_.unlock(); LOGGER.info("Request to Minter Finished, UNLOCKING MINTER"); } // return the generated set of Pids return pidSet; } /** * Maps to the administration panel on the administration path. * * @return name of the index page * @throws Exception */ @RequestMapping(value = {"/administration"}, method = {RequestMethod.GET}) public ModelAndView displayAdministrationPanel() throws Exception { ModelAndView model = new ModelAndView(); // retrieve default values stored in the database DefaultSetting defaultSetting = minterService_.getStoredSetting(); // add the values to the settings page so that they can be displayed LOGGER.info("index page called"); model.addObject("prepend", defaultSetting.getPrepend()); model.addObject("prefix", defaultSetting.getPrefix()); model.addObject("cacheSize", defaultSetting.getCacheSize()); model.addObject("charMap", defaultSetting.getCharMap()); model.addObject("tokenType", defaultSetting.getTokenType()); model.addObject("rootLength", defaultSetting.getRootLength()); model.addObject("isAuto", defaultSetting.isAuto()); model.addObject("isRandom", defaultSetting.isRandom()); model.addObject("sansVowel", defaultSetting.isSansVowels()); model.setViewName("settings"); return model; } /** * Maps to the root of the application * * @return */ @RequestMapping(value = {""}, method = {RequestMethod.GET}) public String displayIndex() { return ""; } /** * Handles any exception that may be caught within the program * * @param req the HTTP request * @param exception the caught exception * @return The view of the error message */ @ResponseStatus(code = HttpStatus.BAD_REQUEST) @ExceptionHandler(Exception.class) public ModelAndView handleGeneralError(HttpServletRequest req, Exception exception) { ModelAndView mav = new ModelAndView(); mav.addObject("status", 500); mav.addObject("exception", exception.getClass().getSimpleName()); mav.addObject("message", exception.getMessage()); LOGGER.error("General Error", exception); StackTraceElement[] s = exception.getStackTrace(); String trace = ""; for (StackTraceElement g : s) { trace += g + "\n"; } mav.addObject("stacktrace", trace); mav.setViewName("error"); return mav; } /** * Overrides the default value of cached value with values given in the * parameter. If the parameters do not contain any of the valid parameters, * the default values are maintained. * * @param parameters List of parameters given by the client. * @param entity * @return The settings used for the particular session it was called. * @throws BadParameterException */ private DefaultSetting overrideDefaultSetting(final Map<String, String> parameters, final DefaultSetting entity) throws BadParameterException { String prepend = (parameters.containsKey("prepend")) ? parameters.get("prepend") : entity.getPrepend(); String prefix = (parameters.containsKey("prefix")) ? validatePrefix(parameters.get("prefix")) : entity.getPrefix(); int rootLength = (parameters.containsKey("rootLength")) ? validateRootLength(Integer.parseInt(parameters.get("rootLength"))) : entity.getRootLength(); String charMap = (parameters.containsKey("charMap")) ? validateCharMap(parameters.get("charMap")) : entity.getCharMap(); Token tokenType = (parameters.containsKey("tokenType")) ? Token.valueOf(parameters.get("tokenType")) : entity.getTokenType(); boolean isAuto = (parameters.containsKey("auto")) ? convertBoolean(parameters.get("auto"), "auto") : entity.isAuto(); boolean isSansVowels = (parameters.containsKey("sansVowels")) ? convertBoolean(parameters.get("sansVowels"), "sansVowels") : entity.isSansVowels(); return new DefaultSetting(prepend, prefix, entity.getCacheSize(), tokenType, charMap, rootLength, isSansVowels, isAuto, entity.isRandom()); } /** * This method is used to check whether or not the given parameter is * explicitly equivalent to "true" or "false" and returns them respectively. * * @param parameter the given string to convert. * @param parameterType the type of the parameter. * @throws BadParameterException Thrown whenever parameter is neither "true" * nor "false" * @return true if the parameter is "true", false if the parameter is * "false" */ private boolean convertBoolean(String parameter, String parameterType) throws BadParameterException { if (parameter.equals("true")) { return true; } else if (parameter.equals("false")) { return false; } else { throw new BadParameterException(parameter, parameterType); } } /** * Asserts the validity of a CharMap using the minter service. * * @param charMap A sequence of characters used to configure PIDs * @return Returns the given charMap if nothing wrong was detected * @throws BadParameterException Thrown whenever a bad parameter is * detected. */ private String validateCharMap(String charMap) throws BadParameterException { if (!IdGenerator.isValidCharMap(charMap)) { throw new BadParameterException(charMap, "charMap"); } return charMap; } /** * Asserts the validity of an amount using the minter service. A valid * amount is greater than or equal to 0. * * @param amount The number of PIDs to be created * @throws BadParameterException Thrown whenever a bad parameter is * detected. */ private void validateAmount(long amount) throws BadParameterException { if (!IdGenerator.isValidAmount(amount)) { throw new BadParameterException(amount, "amount"); } } /** * Asserts the validity of a rootLength is valid. * * @param rootLength * @return * @throws BadParameterException */ private int validateRootLength(int rootLength) throws BadParameterException { if (!IdGenerator.isValidRootLength(rootLength)) { throw new BadParameterException(rootLength, "rootLength"); } return rootLength; } /** * Asserts the validity of prefix is valid. * * @param prefix A sequence of characters that appear in the beginning of * PIDs * @return Returns the given prefix if nothing wrong was detected * @throws BadParameterException Thrown whenever a bad parameter is * detected. */ private String validatePrefix(String prefix) throws BadParameterException { if (!IdGenerator.isValidPrefix(prefix)) { throw new BadParameterException(prefix, "prefix"); } return prefix; } }
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.machinelearning; import javax.annotation.Generated; import com.amazonaws.services.machinelearning.model.*; /** * Abstract implementation of {@code AmazonMachineLearningAsync}. Convenient method forms pass through to the * corresponding overload that takes a request object and an {@code AsyncHandler}, which throws an * {@code UnsupportedOperationException}. */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AbstractAmazonMachineLearningAsync extends AbstractAmazonMachineLearning implements AmazonMachineLearningAsync { protected AbstractAmazonMachineLearningAsync() { } @Override public java.util.concurrent.Future<AddTagsResult> addTagsAsync(AddTagsRequest request) { return addTagsAsync(request, null); } @Override public java.util.concurrent.Future<AddTagsResult> addTagsAsync(AddTagsRequest request, com.amazonaws.handlers.AsyncHandler<AddTagsRequest, AddTagsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateBatchPredictionResult> createBatchPredictionAsync(CreateBatchPredictionRequest request) { return createBatchPredictionAsync(request, null); } @Override public java.util.concurrent.Future<CreateBatchPredictionResult> createBatchPredictionAsync(CreateBatchPredictionRequest request, com.amazonaws.handlers.AsyncHandler<CreateBatchPredictionRequest, CreateBatchPredictionResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateDataSourceFromRDSResult> createDataSourceFromRDSAsync(CreateDataSourceFromRDSRequest request) { return createDataSourceFromRDSAsync(request, null); } @Override public java.util.concurrent.Future<CreateDataSourceFromRDSResult> createDataSourceFromRDSAsync(CreateDataSourceFromRDSRequest request, com.amazonaws.handlers.AsyncHandler<CreateDataSourceFromRDSRequest, CreateDataSourceFromRDSResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateDataSourceFromRedshiftResult> createDataSourceFromRedshiftAsync(CreateDataSourceFromRedshiftRequest request) { return createDataSourceFromRedshiftAsync(request, null); } @Override public java.util.concurrent.Future<CreateDataSourceFromRedshiftResult> createDataSourceFromRedshiftAsync(CreateDataSourceFromRedshiftRequest request, com.amazonaws.handlers.AsyncHandler<CreateDataSourceFromRedshiftRequest, CreateDataSourceFromRedshiftResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateDataSourceFromS3Result> createDataSourceFromS3Async(CreateDataSourceFromS3Request request) { return createDataSourceFromS3Async(request, null); } @Override public java.util.concurrent.Future<CreateDataSourceFromS3Result> createDataSourceFromS3Async(CreateDataSourceFromS3Request request, com.amazonaws.handlers.AsyncHandler<CreateDataSourceFromS3Request, CreateDataSourceFromS3Result> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateEvaluationResult> createEvaluationAsync(CreateEvaluationRequest request) { return createEvaluationAsync(request, null); } @Override public java.util.concurrent.Future<CreateEvaluationResult> createEvaluationAsync(CreateEvaluationRequest request, com.amazonaws.handlers.AsyncHandler<CreateEvaluationRequest, CreateEvaluationResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateMLModelResult> createMLModelAsync(CreateMLModelRequest request) { return createMLModelAsync(request, null); } @Override public java.util.concurrent.Future<CreateMLModelResult> createMLModelAsync(CreateMLModelRequest request, com.amazonaws.handlers.AsyncHandler<CreateMLModelRequest, CreateMLModelResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<CreateRealtimeEndpointResult> createRealtimeEndpointAsync(CreateRealtimeEndpointRequest request) { return createRealtimeEndpointAsync(request, null); } @Override public java.util.concurrent.Future<CreateRealtimeEndpointResult> createRealtimeEndpointAsync(CreateRealtimeEndpointRequest request, com.amazonaws.handlers.AsyncHandler<CreateRealtimeEndpointRequest, CreateRealtimeEndpointResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteBatchPredictionResult> deleteBatchPredictionAsync(DeleteBatchPredictionRequest request) { return deleteBatchPredictionAsync(request, null); } @Override public java.util.concurrent.Future<DeleteBatchPredictionResult> deleteBatchPredictionAsync(DeleteBatchPredictionRequest request, com.amazonaws.handlers.AsyncHandler<DeleteBatchPredictionRequest, DeleteBatchPredictionResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteDataSourceResult> deleteDataSourceAsync(DeleteDataSourceRequest request) { return deleteDataSourceAsync(request, null); } @Override public java.util.concurrent.Future<DeleteDataSourceResult> deleteDataSourceAsync(DeleteDataSourceRequest request, com.amazonaws.handlers.AsyncHandler<DeleteDataSourceRequest, DeleteDataSourceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteEvaluationResult> deleteEvaluationAsync(DeleteEvaluationRequest request) { return deleteEvaluationAsync(request, null); } @Override public java.util.concurrent.Future<DeleteEvaluationResult> deleteEvaluationAsync(DeleteEvaluationRequest request, com.amazonaws.handlers.AsyncHandler<DeleteEvaluationRequest, DeleteEvaluationResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteMLModelResult> deleteMLModelAsync(DeleteMLModelRequest request) { return deleteMLModelAsync(request, null); } @Override public java.util.concurrent.Future<DeleteMLModelResult> deleteMLModelAsync(DeleteMLModelRequest request, com.amazonaws.handlers.AsyncHandler<DeleteMLModelRequest, DeleteMLModelResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteRealtimeEndpointResult> deleteRealtimeEndpointAsync(DeleteRealtimeEndpointRequest request) { return deleteRealtimeEndpointAsync(request, null); } @Override public java.util.concurrent.Future<DeleteRealtimeEndpointResult> deleteRealtimeEndpointAsync(DeleteRealtimeEndpointRequest request, com.amazonaws.handlers.AsyncHandler<DeleteRealtimeEndpointRequest, DeleteRealtimeEndpointResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DeleteTagsResult> deleteTagsAsync(DeleteTagsRequest request) { return deleteTagsAsync(request, null); } @Override public java.util.concurrent.Future<DeleteTagsResult> deleteTagsAsync(DeleteTagsRequest request, com.amazonaws.handlers.AsyncHandler<DeleteTagsRequest, DeleteTagsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DescribeBatchPredictionsResult> describeBatchPredictionsAsync(DescribeBatchPredictionsRequest request) { return describeBatchPredictionsAsync(request, null); } @Override public java.util.concurrent.Future<DescribeBatchPredictionsResult> describeBatchPredictionsAsync(DescribeBatchPredictionsRequest request, com.amazonaws.handlers.AsyncHandler<DescribeBatchPredictionsRequest, DescribeBatchPredictionsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } /** * Simplified method form for invoking the DescribeBatchPredictions operation. * * @see #describeBatchPredictionsAsync(DescribeBatchPredictionsRequest) */ @Override public java.util.concurrent.Future<DescribeBatchPredictionsResult> describeBatchPredictionsAsync() { return describeBatchPredictionsAsync(new DescribeBatchPredictionsRequest()); } /** * Simplified method form for invoking the DescribeBatchPredictions operation with an AsyncHandler. * * @see #describeBatchPredictionsAsync(DescribeBatchPredictionsRequest, com.amazonaws.handlers.AsyncHandler) */ @Override public java.util.concurrent.Future<DescribeBatchPredictionsResult> describeBatchPredictionsAsync( com.amazonaws.handlers.AsyncHandler<DescribeBatchPredictionsRequest, DescribeBatchPredictionsResult> asyncHandler) { return describeBatchPredictionsAsync(new DescribeBatchPredictionsRequest(), asyncHandler); } @Override public java.util.concurrent.Future<DescribeDataSourcesResult> describeDataSourcesAsync(DescribeDataSourcesRequest request) { return describeDataSourcesAsync(request, null); } @Override public java.util.concurrent.Future<DescribeDataSourcesResult> describeDataSourcesAsync(DescribeDataSourcesRequest request, com.amazonaws.handlers.AsyncHandler<DescribeDataSourcesRequest, DescribeDataSourcesResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } /** * Simplified method form for invoking the DescribeDataSources operation. * * @see #describeDataSourcesAsync(DescribeDataSourcesRequest) */ @Override public java.util.concurrent.Future<DescribeDataSourcesResult> describeDataSourcesAsync() { return describeDataSourcesAsync(new DescribeDataSourcesRequest()); } /** * Simplified method form for invoking the DescribeDataSources operation with an AsyncHandler. * * @see #describeDataSourcesAsync(DescribeDataSourcesRequest, com.amazonaws.handlers.AsyncHandler) */ @Override public java.util.concurrent.Future<DescribeDataSourcesResult> describeDataSourcesAsync( com.amazonaws.handlers.AsyncHandler<DescribeDataSourcesRequest, DescribeDataSourcesResult> asyncHandler) { return describeDataSourcesAsync(new DescribeDataSourcesRequest(), asyncHandler); } @Override public java.util.concurrent.Future<DescribeEvaluationsResult> describeEvaluationsAsync(DescribeEvaluationsRequest request) { return describeEvaluationsAsync(request, null); } @Override public java.util.concurrent.Future<DescribeEvaluationsResult> describeEvaluationsAsync(DescribeEvaluationsRequest request, com.amazonaws.handlers.AsyncHandler<DescribeEvaluationsRequest, DescribeEvaluationsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } /** * Simplified method form for invoking the DescribeEvaluations operation. * * @see #describeEvaluationsAsync(DescribeEvaluationsRequest) */ @Override public java.util.concurrent.Future<DescribeEvaluationsResult> describeEvaluationsAsync() { return describeEvaluationsAsync(new DescribeEvaluationsRequest()); } /** * Simplified method form for invoking the DescribeEvaluations operation with an AsyncHandler. * * @see #describeEvaluationsAsync(DescribeEvaluationsRequest, com.amazonaws.handlers.AsyncHandler) */ @Override public java.util.concurrent.Future<DescribeEvaluationsResult> describeEvaluationsAsync( com.amazonaws.handlers.AsyncHandler<DescribeEvaluationsRequest, DescribeEvaluationsResult> asyncHandler) { return describeEvaluationsAsync(new DescribeEvaluationsRequest(), asyncHandler); } @Override public java.util.concurrent.Future<DescribeMLModelsResult> describeMLModelsAsync(DescribeMLModelsRequest request) { return describeMLModelsAsync(request, null); } @Override public java.util.concurrent.Future<DescribeMLModelsResult> describeMLModelsAsync(DescribeMLModelsRequest request, com.amazonaws.handlers.AsyncHandler<DescribeMLModelsRequest, DescribeMLModelsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } /** * Simplified method form for invoking the DescribeMLModels operation. * * @see #describeMLModelsAsync(DescribeMLModelsRequest) */ @Override public java.util.concurrent.Future<DescribeMLModelsResult> describeMLModelsAsync() { return describeMLModelsAsync(new DescribeMLModelsRequest()); } /** * Simplified method form for invoking the DescribeMLModels operation with an AsyncHandler. * * @see #describeMLModelsAsync(DescribeMLModelsRequest, com.amazonaws.handlers.AsyncHandler) */ @Override public java.util.concurrent.Future<DescribeMLModelsResult> describeMLModelsAsync( com.amazonaws.handlers.AsyncHandler<DescribeMLModelsRequest, DescribeMLModelsResult> asyncHandler) { return describeMLModelsAsync(new DescribeMLModelsRequest(), asyncHandler); } @Override public java.util.concurrent.Future<DescribeTagsResult> describeTagsAsync(DescribeTagsRequest request) { return describeTagsAsync(request, null); } @Override public java.util.concurrent.Future<DescribeTagsResult> describeTagsAsync(DescribeTagsRequest request, com.amazonaws.handlers.AsyncHandler<DescribeTagsRequest, DescribeTagsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetBatchPredictionResult> getBatchPredictionAsync(GetBatchPredictionRequest request) { return getBatchPredictionAsync(request, null); } @Override public java.util.concurrent.Future<GetBatchPredictionResult> getBatchPredictionAsync(GetBatchPredictionRequest request, com.amazonaws.handlers.AsyncHandler<GetBatchPredictionRequest, GetBatchPredictionResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetDataSourceResult> getDataSourceAsync(GetDataSourceRequest request) { return getDataSourceAsync(request, null); } @Override public java.util.concurrent.Future<GetDataSourceResult> getDataSourceAsync(GetDataSourceRequest request, com.amazonaws.handlers.AsyncHandler<GetDataSourceRequest, GetDataSourceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetEvaluationResult> getEvaluationAsync(GetEvaluationRequest request) { return getEvaluationAsync(request, null); } @Override public java.util.concurrent.Future<GetEvaluationResult> getEvaluationAsync(GetEvaluationRequest request, com.amazonaws.handlers.AsyncHandler<GetEvaluationRequest, GetEvaluationResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetMLModelResult> getMLModelAsync(GetMLModelRequest request) { return getMLModelAsync(request, null); } @Override public java.util.concurrent.Future<GetMLModelResult> getMLModelAsync(GetMLModelRequest request, com.amazonaws.handlers.AsyncHandler<GetMLModelRequest, GetMLModelResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<PredictResult> predictAsync(PredictRequest request) { return predictAsync(request, null); } @Override public java.util.concurrent.Future<PredictResult> predictAsync(PredictRequest request, com.amazonaws.handlers.AsyncHandler<PredictRequest, PredictResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateBatchPredictionResult> updateBatchPredictionAsync(UpdateBatchPredictionRequest request) { return updateBatchPredictionAsync(request, null); } @Override public java.util.concurrent.Future<UpdateBatchPredictionResult> updateBatchPredictionAsync(UpdateBatchPredictionRequest request, com.amazonaws.handlers.AsyncHandler<UpdateBatchPredictionRequest, UpdateBatchPredictionResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateDataSourceResult> updateDataSourceAsync(UpdateDataSourceRequest request) { return updateDataSourceAsync(request, null); } @Override public java.util.concurrent.Future<UpdateDataSourceResult> updateDataSourceAsync(UpdateDataSourceRequest request, com.amazonaws.handlers.AsyncHandler<UpdateDataSourceRequest, UpdateDataSourceResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateEvaluationResult> updateEvaluationAsync(UpdateEvaluationRequest request) { return updateEvaluationAsync(request, null); } @Override public java.util.concurrent.Future<UpdateEvaluationResult> updateEvaluationAsync(UpdateEvaluationRequest request, com.amazonaws.handlers.AsyncHandler<UpdateEvaluationRequest, UpdateEvaluationResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<UpdateMLModelResult> updateMLModelAsync(UpdateMLModelRequest request) { return updateMLModelAsync(request, null); } @Override public java.util.concurrent.Future<UpdateMLModelResult> updateMLModelAsync(UpdateMLModelRequest request, com.amazonaws.handlers.AsyncHandler<UpdateMLModelRequest, UpdateMLModelResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } }
/* * This command line interface is used to convert a pathway that has a diagram inside the reactome * database to GPML format. */ package org.gk.gpml; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.gk.model.GKInstance; import org.gk.model.ReactomeJavaConstants; import org.gk.persistence.MySQLAdaptor; import org.gk.schema.SchemaAttribute; import org.gk.schema.SchemaClass; import org.reactome.convert.common.AbstractConverterFromReactome; public class CLIConverter { public static void main(String[] args) throws Exception { if (args.length < 6) { // printUsage(); System.err .println("Please provide the following parameters in order: dbhost dbName dbUser dbPwd dbPort outputDir"); System.exit(1); } MySQLAdaptor adaptor = new MySQLAdaptor(args[0], args[1], args[2], args[3], Integer.parseInt(args[4])); File dir = new File(args[5]); dir.mkdirs(); CLIConverter converter = new CLIConverter(adaptor); /* * Boolean true to save ATXML files */ converter.convertReactomeToGPMLByID((long) 69620, dir, false); // converter.convertReactomeToGPMLByID((long) 73857, dir, false); // converter.convertReactomeToGPMLByID((long) 2032785, dir, false); // converter.dumpHumanPathwayDiagrams(dir, false); // converter.convertPlantPathwayDiagrams(dir, false); // converter.getSpeciesDbID(); } private static void printUsage() throws Exception { System.out .println("Usage: java org.gk.gpml.CLIConverter dbhost dbName user pwd port DB_ID [outputfile]"); System.out.println(); System.out .println("DB_ID is the Reactome ID of a pathway that has a diagram inside the database."); } private final MySQLAdaptor adaptor; private final ReactometoGPML2013 r2g3Converter; private final Map<Long, String> notRenderable; private final Map<Long, String> Renderable; private CLIConverter(MySQLAdaptor adaptor) { this(adaptor, new ReactometoGPML2013()); } private CLIConverter(MySQLAdaptor adaptor, ReactometoGPML2013 r2g3Converter) { notRenderable = new HashMap<Long, String>(); Renderable = new HashMap<Long, String>(); this.adaptor = adaptor; this.r2g3Converter = r2g3Converter; this.r2g3Converter.setMySQLAdaptor(adaptor); } private void convertPlantPathwayDiagrams(File dir, boolean saveatxml) { Collection<?> diagrams; try { diagrams = adaptor .fetchInstancesByClass(ReactomeJavaConstants.PathwayDiagram); SchemaClass cls = adaptor.fetchSchema().getClassByName( ReactomeJavaConstants.PathwayDiagram); SchemaAttribute att = cls .getAttribute(ReactomeJavaConstants.representedPathway); adaptor.loadInstanceAttributeValues(diagrams, att); // Group all human pathways for (Object name : diagrams) { GKInstance diagram = (GKInstance) name; GKInstance pathway = (GKInstance) diagram .getAttributeValue(ReactomeJavaConstants.representedPathway); GKInstance species = (GKInstance) pathway .getAttributeValue(ReactomeJavaConstants.species); if (species == null) { continue; } else { try { String fileName = AbstractConverterFromReactome .getFileName(pathway); if (saveatxml) { File atxmlfile = new File(dir, fileName + ".atxml"); atxmlfile.createNewFile(); r2g3Converter.queryATXML(pathway, atxmlfile); } File gpmlfile = new File(dir, fileName + ".gpml"); gpmlfile.createNewFile(); convertReactomeToGPML(pathway, gpmlfile); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } } private void convertReactomeToGPML(GKInstance pathway, File gpmlfilename) { Long dbID = pathway.getDBID(); System.out.println("converting pathway #" + dbID + " " + pathway.getDisplayName() + "..."); if (!r2g3Converter.convertPathway(pathway, gpmlfilename)) { notRenderable.put(dbID, pathway.getDisplayName()); } else { Renderable.put(dbID, pathway.getDisplayName()); } System.out.println("Not Rendered " + notRenderable); System.out.println("Rendered " + Renderable); } /** * Convert Reactome pathways using their IDs * * @param dbID * Stable ID of the pathway * @param dir * Directory to save converted gpml file * @param saveatxml * Boolean true if atxml files should be saved as well */ public void convertReactomeToGPMLByID(Long dbID, File dir, Boolean saveatxml) { GKInstance pathway; try { pathway = adaptor.fetchInstance(dbID); String fileName = AbstractConverterFromReactome .getFileName(pathway); if (saveatxml) { File atxmlfile = new File(dir, fileName + ".atxml"); atxmlfile.createNewFile(); r2g3Converter.queryATXML(pathway, atxmlfile); } File gpmlfile = new File(dir, fileName + ".gpml"); gpmlfile.createNewFile(); convertReactomeToGPML(pathway, gpmlfile); } catch (Exception e) { e.printStackTrace(); } } public void dumpHumanPathwayDiagrams(File dir, Boolean saveatxml) { notRenderable.clear(); Collection<?> diagrams; try { diagrams = adaptor .fetchInstancesByClass(ReactomeJavaConstants.PathwayDiagram); SchemaClass cls = adaptor.fetchSchema().getClassByName( ReactomeJavaConstants.PathwayDiagram); SchemaAttribute att = cls .getAttribute(ReactomeJavaConstants.representedPathway); adaptor.loadInstanceAttributeValues(diagrams, att); // Group all human pathways for (Object name : diagrams) { GKInstance diagram = (GKInstance) name; GKInstance pathway = (GKInstance) diagram .getAttributeValue(ReactomeJavaConstants.representedPathway); GKInstance species = (GKInstance) pathway .getAttributeValue(ReactomeJavaConstants.species); if (species == null) { continue; } // for (int i = 0; i <= 5; i++) { if (species.getDBID().equals(48887L)) { String fileName = AbstractConverterFromReactome .getFileName(pathway); String gpmlfile = fileName + ".gpml"; File[] listOfFiles = dir.listFiles(); boolean convert = true; for (File listOfFile : listOfFiles) if (gpmlfile.equalsIgnoreCase(listOfFile.getName())) { convert = false; } if (convert) { Long id = pathway.getDBID(); convertReactomeToGPMLByID(id, dir, saveatxml); } } } // } } catch (Exception e) { e.printStackTrace(); } System.out.println("Not rendered" + notRenderable); } /** * This method gets the DB id for the species * * @throws Exception */ public void getSpeciesDbID() { Collection<?> diagrams; try { diagrams = adaptor .fetchInstancesByClass(ReactomeJavaConstants.PathwayDiagram); SchemaClass cls = adaptor.fetchSchema().getClassByName( ReactomeJavaConstants.PathwayDiagram); SchemaAttribute att = cls .getAttribute(ReactomeJavaConstants.representedPathway); adaptor.loadInstanceAttributeValues(diagrams, att); // Group all human pathways for (Object name : diagrams) { GKInstance diagram = (GKInstance) name; GKInstance pathway = (GKInstance) diagram .getAttributeValue(ReactomeJavaConstants.representedPathway); GKInstance species = (GKInstance) pathway .getAttributeValue(ReactomeJavaConstants.species); if (species == null) { continue; } else { System.out.println(species.getDBID() + "\t" + species.getDisplayName()); } } } catch (Exception e) { e.printStackTrace(); } } }
package org.cthul.parser.lexer.simple; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.cthul.parser.api.*; import org.cthul.parser.lexer.LexerBase; import org.cthul.parser.lexer.api.InputEval; import org.cthul.parser.lexer.ScanException; import org.cthul.parser.util.Format; /** * * @param <I> input produced by this lexer */ public class SimpleLexer<I extends Input<?>> extends LexerBase<I> { protected final RuleSet<?, ? extends I, ?> ruleSet; public SimpleLexer(RuleSet<?, ? extends I, ?> ruleSet) { this.ruleSet = ruleSet; } @Override public I scan(Context<StringInput> context) { return ruleSet.scan(context); } @Override public String toString() { return getClass().getSimpleName() + ruleSet; } /** * Helper class to hide the generic parameters * @param <Token> tokens created by rules and consumed by {@code S} * @param <I> input created by {@code S} * @param <S> the lexer state used by rules */ public static abstract class RuleSet<Token, I extends Input<?>, S extends State<? extends Token, ? extends I>> { protected final List<Rule<? extends Token, ? super S>> rules = new ArrayList<>(); public RuleSet(Collection<Rule<? extends Token, ? super S>> rules) { this.rules.addAll(rules); } public I scan(Context<StringInput> context) { return newState(context).scan(); } protected abstract S newState(Context<StringInput> context); @Override public String toString() { return Format.join("{", ", ", "}", 512, "...}", rules); } } /** * * @param <Token> tokens created by matching rules * @param <I> input that is created */ public static abstract class State<Token, I extends Input<?>> { protected final Context<StringInput> context; private final List<? extends Rule<? extends Token, ?>> rules; private int position = 0; public State(Context<StringInput> context, List<? extends Rule<? extends Token, ?>> rules) { this.context = context; this.rules = rules; } // workaround so State doesn't need a third generic parameter @SuppressWarnings("unchecked") protected <S extends State<?,?>> List<? extends Rule<? extends Token, S>> rules() { return (List) rules; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } protected I scan() { final StringInput input = context.getInput(); final List<Token> tokens = new ArrayList<>(); final int len = input.getLength(); Token lastMatch = null; position = 0; while (position < len) { Token t = null; for (Rule<? extends Token, State<?,?>> r: rules()) { t = r.scan(context, input, this); if (t != null) break; } if (t != null) { lastMatch = t; addToken(tokens, t); } else { throw new ScanException( lastMatch, input.getString(), position, null, null); } } return createInput(input.getString(), tokens); } protected abstract I createInput(String input, List<Token> tokens); protected void addToken(final List<Token> tokens, Token t) { tokens.add(t); } } /** * * @param <Token> tokens created * @param <S> additional state */ protected static abstract class Rule<Token, S extends State<?,?>> implements Comparable<Rule<?,?>> { protected final RuleKey key; private final int id; public Rule(RuleKey key, int id) { this.key = key; this.id = id; } public abstract Token scan(Context<StringInput> context, StringInput input, S state); @Override public int compareTo(Rule<?,?> o) { int c = o.key.getPriority() - key.getPriority(); if (c != 0) return c; return id - o.id; } @Override public String toString() { String s = Format.productionKey(key.getSymbol(), key.getPriority()); String m = matchString(); if (m != null) s = s + " ::= " + m; return s; } protected String matchString() { return null; } } protected static abstract class MatchingRule<Token, Match, S extends State<?,?>> extends Rule<Token, S> { private final InputEval<? extends Token, ? super Match> eval; public MatchingRule(RuleKey key, int id, InputEval<? extends Token, ? super Match> eval) { super(key, id); this.eval = eval; } @Override public Token scan(Context<StringInput> context, StringInput input, S state) { int start = state.getPosition(); Match m = match(context, input, state, start); if (m == null) return null; return eval.eval(context, m, start, state.getPosition()); } protected abstract Match match(Context<StringInput> context, StringInput input, S state, int start); } protected static abstract class StringRule<Token, Match, S extends State<?,?>> extends MatchingRule<Token, Match, S> { private final String[] strings; public StringRule(RuleKey key, int id, InputEval<? extends Token, ? super Match> eval, String[] strings) { super(key, id, eval); this.strings = strings; } @Override protected Match match(Context<StringInput> context, StringInput input, S state, int start) { final String str = input.getString(); for (String s: strings) { if (str.startsWith(s, start)) { state.setPosition(start + s.length()); return match(context, input, state, start, s); } } return null; } @Override protected String matchString() { return Format.join("(", "|", ")", 64, "...)", strings); } protected abstract Match match(Context<StringInput> context, StringInput input, S state, int start, String match); } protected static abstract class RegexRule<Token, Match, S extends State<?,?>> extends MatchingRule<Token, Match, S> { private final Pattern pattern; public RegexRule(RuleKey key, int id, InputEval<? extends Token, ? super Match> eval, Pattern pattern) { super(key, id, eval); this.pattern = pattern; } @Override protected Match match(Context<StringInput> context, StringInput input, S state, int start) { final String str = input.getString(); Matcher m = pattern.matcher(str); if (!m.find(start) || m.start() != start) return null; state.setPosition(m.end()); return match(context, input, state, start, m); } @Override protected String matchString() { return pattern.pattern(); } protected abstract Match match(Context<StringInput> context, StringInput input, S state, int start, MatchResult match); } }
import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import java.net.*; import java.util.Arrays; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class blackoutA extends PApplet { //clears the board OPC opc; int numPixels = 60; //per ring float angleOfFirst = PI; public void setup() { size(240, 240); // Connect to the local instance of fcserver opc = new OPC(this, "127.0.0.1", 7890); // Map an 8x8 grid of rings of LEDs to the center of the window int numPixelsPerRing = numPixels; opc.ledRingGrid(width, height, numPixelsPerRing); background(0, 0, 0); } public void draw() { background(0); } /* * Simple Open Pixel Control client for Processing, * designed to sample each LED's color from some point on the canvas. * * Micah Elizabeth Scott, 2013 * This file is released into the public domain. */ public class OPC { Socket socket; OutputStream output; String host; int port; int[] pixelLocations; byte[] packetData; byte firmwareConfig; String colorCorrection; boolean enableShowLocations; OPC(PApplet parent, String host, int port) { this.host = host; this.port = port; this.enableShowLocations = true; parent.registerDraw(this); } // Set the location of a single LED public void led(int index, int x, int y) { // For convenience, automatically grow the pixelLocations array. We do want this to be an array, // instead of a HashMap, to keep draw() as fast as it can be. if (pixelLocations == null) { pixelLocations = new int[index + 1]; } else if (index >= pixelLocations.length) { pixelLocations = Arrays.copyOf(pixelLocations, index + 1); } pixelLocations[index] = x + width * y; } // Set the locations of a ring of LEDs. The center of the ring is at (x, y), // with "radius" pixels between the center and each LED. The first LED is at // the indicated angle, in radians, measured clockwise from +X. public void ledRing(int index, int count, float x, float y, float radius, float angle, boolean inverted) { float pi = PI; if(inverted == true) pi *= -1; for (int i = 0; i < count; i++) { float a = angle + i * 2 * pi / count; led(index + i, (int)(x - radius * cos(a) + 0.5f), (int)(y - radius * sin(a) + 0.5f)); } } //Draws an 8x8 grid of pixel rings. //Grid is drawn column by column, starting at the bottom left, //and is relative to screen size. public void ledRingGrid(int screenWidth, int screenHeight, int numPixels) { int xPosition = screenWidth / 16; int index = 0; float radius = ((screenWidth + screenHeight) / 2) / 20; float angleOfFirstPixel = PI; boolean inverted = false; if(numPixels == 16) inverted = true; for(int x = 0; x < 8; x++) { int yPosition = screenHeight - (screenHeight / 16); for(int y = 0; y < 8; y++) { ledRing(index, numPixels, xPosition, yPosition, radius, angleOfFirstPixel, inverted); yPosition -= screenHeight / 8; index += numPixels; } xPosition += screenHeight / 8; } } // Should the pixel sampling locations be visible? This helps with debugging. // Showing locations is enabled by default. You might need to disable it if our drawing // is interfering with your processing sketch, or if you'd simply like the screen to be // less cluttered. public void showLocations(boolean enabled) { enableShowLocations = enabled; } // Enable or disable dithering. Dithering avoids the "stair-stepping" artifact and increases color // resolution by quickly jittering between adjacent 8-bit brightness levels about 400 times a second. // Dithering is on by default. public void setDithering(boolean enabled) { if (enabled) firmwareConfig &= ~0x01; else firmwareConfig |= 0x01; sendFirmwareConfigPacket(); } // Enable or disable frame interpolation. Interpolation automatically blends between consecutive frames // in hardware, and it does so with 16-bit per channel resolution. Combined with dithering, this helps make // fades very smooth. Interpolation is on by default. public void setInterpolation(boolean enabled) { if (enabled) firmwareConfig &= ~0x02; else firmwareConfig |= 0x02; sendFirmwareConfigPacket(); } // Put the Fadecandy onboard LED under automatic control. It blinks any time the firmware processes a packet. // This is the default configuration for the LED. public void statusLedAuto() { firmwareConfig &= 0x0C; sendFirmwareConfigPacket(); } // Manually turn the Fadecandy onboard LED on or off. This disables automatic LED control. public void setStatusLed(boolean on) { firmwareConfig |= 0x04; // Manual LED control if (on) firmwareConfig |= 0x08; else firmwareConfig &= ~0x08; sendFirmwareConfigPacket(); } // Set the color correction parameters public void setColorCorrection(float gamma, float red, float green, float blue) { colorCorrection = "{ \"gamma\": " + gamma + ", \"whitepoint\": [" + red + "," + green + "," + blue + "]}"; sendColorCorrectionPacket(); } // Set custom color correction parameters from a string public void setColorCorrection(String s) { colorCorrection = s; sendColorCorrectionPacket(); } // Send a packet with the current firmware configuration settings public void sendFirmwareConfigPacket() { if (output == null) { // We'll do this when we reconnect return; } byte[] packet = new byte[9]; packet[0] = 0; // Channel (reserved) packet[1] = (byte)0xFF; // Command (System Exclusive) packet[2] = 0; // Length high byte packet[3] = 5; // Length low byte packet[4] = 0x00; // System ID high byte packet[5] = 0x01; // System ID low byte packet[6] = 0x00; // Command ID high byte packet[7] = 0x02; // Command ID low byte packet[8] = firmwareConfig; try { output.write(packet); } catch (Exception e) { dispose(); } } // Send a packet with the current color correction settings public void sendColorCorrectionPacket() { if (colorCorrection == null) { // No color correction defined return; } if (output == null) { // We'll do this when we reconnect return; } byte[] content = colorCorrection.getBytes(); int packetLen = content.length + 4; byte[] header = new byte[8]; header[0] = 0; // Channel (reserved) header[1] = (byte)0xFF; // Command (System Exclusive) header[2] = (byte)(packetLen >> 8); header[3] = (byte)(packetLen & 0xFF); header[4] = 0x00; // System ID high byte header[5] = 0x01; // System ID low byte header[6] = 0x00; // Command ID high byte header[7] = 0x01; // Command ID low byte try { output.write(header); output.write(content); } catch (Exception e) { dispose(); } } // Automatically called at the end of each draw(). // This handles the automatic Pixel to LED mapping. // If you aren't using that mapping, this function has no effect. // In that case, you can call setPixelCount(), setPixel(), and writePixels() // separately. public void draw() { if (pixelLocations == null) { // No pixels defined yet return; } if (output == null) { // Try to (re)connect connect(); } if (output == null) { return; } int numPixels = pixelLocations.length; int ledAddress = 4; setPixelCount(numPixels); loadPixels(); for (int i = 0; i < numPixels; i++) { int pixelLocation = pixelLocations[i]; int pixel = pixels[pixelLocation]; packetData[ledAddress] = (byte)(pixel >> 16); packetData[ledAddress + 1] = (byte)(pixel >> 8); packetData[ledAddress + 2] = (byte)pixel; ledAddress += 3; if (enableShowLocations) { pixels[pixelLocation] = 0xFFFFFF ^ pixel; } } writePixels(); if (enableShowLocations) { updatePixels(); } } // Change the number of pixels in our output packet. // This is normally not needed; the output packet is automatically sized // by draw() and by setPixel(). public void setPixelCount(int numPixels) { int numBytes = 3 * numPixels; int packetLen = 4 + numBytes; if (packetData == null || packetData.length != packetLen) { // Set up our packet buffer packetData = new byte[packetLen]; packetData[0] = 0; // Channel packetData[1] = 0; // Command (Set pixel colors) packetData[2] = (byte)(numBytes >> 8); packetData[3] = (byte)(numBytes & 0xFF); } } // Directly manipulate a pixel in the output buffer. This isn't needed // for pixels that are mapped to the screen. public void setPixel(int number, int c) { int offset = 4 + number * 3; if (packetData == null || packetData.length < offset + 3) { setPixelCount(number + 1); } packetData[offset] = (byte) (c >> 16); packetData[offset + 1] = (byte) (c >> 8); packetData[offset + 2] = (byte) c; } // Read a pixel from the output buffer. If the pixel was mapped to the display, // this returns the value we captured on the previous frame. public int getPixel(int number) { int offset = 4 + number * 3; if (packetData == null || packetData.length < offset + 3) { return 0; } return (packetData[offset] << 16) | (packetData[offset + 1] << 8) | packetData[offset + 2]; } // Transmit our current buffer of pixel values to the OPC server. This is handled // automatically in draw() if any pixels are mapped to the screen, but if you haven't // mapped any pixels to the screen you'll want to call this directly. public void writePixels() { if (packetData == null || packetData.length == 0) { // No pixel buffer return; } if (output == null) { // Try to (re)connect connect(); } if (output == null) { return; } try { output.write(packetData); } catch (Exception e) { dispose(); } } public void dispose() { // Destroy the socket. Called internally when we've disconnected. if (output != null) { println("Disconnected from OPC server"); } socket = null; output = null; } public void connect() { // Try to connect to the OPC server. This normally happens automatically in draw() try { socket = new Socket(host, port); socket.setTcpNoDelay(true); output = socket.getOutputStream(); println("Connected to OPC server"); } catch (ConnectException e) { dispose(); } catch (IOException e) { dispose(); } sendColorCorrectionPacket(); sendFirmwareConfigPacket(); } } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "blackoutA" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } }
/** * Copyright 2017 Netflix, Inc. * * <p>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 * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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.netflix.priam.restore; import com.google.inject.Provider; import com.netflix.priam.backup.AbstractBackupPath; import com.netflix.priam.backup.IBackupFileSystem; import com.netflix.priam.backup.MetaData; import com.netflix.priam.compress.CompressionType; import com.netflix.priam.compress.ICompression; import com.netflix.priam.config.IConfiguration; import com.netflix.priam.cred.ICredentialGeneric; import com.netflix.priam.cryptography.IFileCryptography; import com.netflix.priam.defaultimpl.ICassandraProcess; import com.netflix.priam.health.InstanceState; import com.netflix.priam.identity.InstanceIdentity; import com.netflix.priam.scheduler.NamedThreadPoolExecutor; import com.netflix.priam.utils.RetryableCallable; import com.netflix.priam.utils.Sleeper; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import org.bouncycastle.util.io.Streams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Provides common functionality applicable to all restore strategies */ public abstract class EncryptedRestoreBase extends AbstractRestore { private static final Logger logger = LoggerFactory.getLogger(EncryptedRestoreBase.class); private static final String TMP_SUFFIX = ".tmp"; private final String jobName; private final ICredentialGeneric pgpCredential; private final IFileCryptography fileCryptography; private final ICompression compress; private final ThreadPoolExecutor executor; protected EncryptedRestoreBase( IConfiguration config, IBackupFileSystem fs, String jobName, Sleeper sleeper, ICassandraProcess cassProcess, Provider<AbstractBackupPath> pathProvider, InstanceIdentity instanceIdentity, RestoreTokenSelector tokenSelector, ICredentialGeneric pgpCredential, IFileCryptography fileCryptography, ICompression compress, MetaData metaData, InstanceState instanceState, IPostRestoreHook postRestoreHook) { super( config, fs, jobName, sleeper, pathProvider, instanceIdentity, tokenSelector, cassProcess, metaData, instanceState, postRestoreHook); this.jobName = jobName; this.pgpCredential = pgpCredential; this.fileCryptography = fileCryptography; this.compress = compress; executor = new NamedThreadPoolExecutor(config.getRestoreThreads(), jobName); executor.allowCoreThreadTimeOut(true); logger.info( "Trying to restore cassandra cluster with filesystem: {}, RestoreStrategy: {}, Encryption: ON, Compression: {}", fs.getClass(), jobName, compress.getClass()); } @Override protected final Future<Path> downloadFile(final AbstractBackupPath path) throws Exception { final char[] passPhrase = new String(this.pgpCredential.getValue(ICredentialGeneric.KEY.PGP_PASSWORD)) .toCharArray(); File restoreLocation = path.newRestoreFile(); File tempFile = new File(restoreLocation.getAbsolutePath() + TMP_SUFFIX); return executor.submit( new RetryableCallable<Path>() { @Override public Path retriableCall() throws Exception { // == download object from source bucket try { // Not retrying to download file here as it is already in RetryCallable. fs.downloadFile(path, TMP_SUFFIX, 0 /* retries */); } catch (Exception ex) { // This behavior is retryable; therefore, lets get to a clean state // before each retry. if (tempFile.exists()) { tempFile.createNewFile(); } throw new Exception( "Exception downloading file from: " + path.getRemotePath() + " to: " + tempFile.getAbsolutePath(), ex); } // == object downloaded successfully from source, decrypt it. File decryptedFile = new File(tempFile.getAbsolutePath() + ".decrypted"); try (OutputStream fOut = new BufferedOutputStream( new FileOutputStream( decryptedFile)); // destination file after // decryption) InputStream in = new BufferedInputStream( new FileInputStream(tempFile.getAbsolutePath()))) { InputStream encryptedDataInputStream = fileCryptography.decryptStream( in, passPhrase, tempFile.getAbsolutePath()); Streams.pipeAll(encryptedDataInputStream, fOut); logger.info( "Completed decrypting file: {} to final file dest: {}", tempFile.getAbsolutePath(), decryptedFile.getAbsolutePath()); } catch (Exception ex) { // This behavior is retryable; therefore, lets get to a clean state // before each retry. if (tempFile.exists()) { tempFile.createNewFile(); } if (decryptedFile.exists()) { decryptedFile.createNewFile(); } throw new Exception( "Exception during decryption file: " + decryptedFile.getAbsolutePath(), ex); } // == object is downloaded and decrypted, now uncompress it if necessary if (path.getCompression() == CompressionType.NONE) { Files.move(decryptedFile.toPath(), restoreLocation.toPath()); } else { logger.info( "Start uncompressing file: {} to the FINAL destination stream", decryptedFile.getAbsolutePath()); try (InputStream is = new BufferedInputStream( new FileInputStream(decryptedFile)); BufferedOutputStream finalDestination = new BufferedOutputStream( new FileOutputStream(restoreLocation))) { compress.decompressAndClose(is, finalDestination); } catch (Exception ex) { throw new Exception( "Exception uncompressing file: " + decryptedFile.getAbsolutePath() + " to the FINAL destination stream", ex); } logger.info( "Completed uncompressing file: {} to the FINAL destination stream " + " current worker: {}", decryptedFile.getAbsolutePath(), Thread.currentThread().getName()); } // if here, everything was successful for this object, lets remove unneeded // file(s) if (tempFile.exists()) tempFile.delete(); if (decryptedFile.exists()) { decryptedFile.delete(); } return Paths.get(path.getRemotePath()); } }); } @Override public String getName() { return this.jobName; } }
/* * Copyright 2015-2017 the original author or authors. * * 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 org.springframework.cloud.dataflow.core.dsl; import java.util.ArrayList; import java.util.List; import org.springframework.util.Assert; /** * The base class for tokenizers. Knows about tokenization in general but * not specific to a DSL variant. Provides state management and utility methods * to real tokenizer subclasses. * * @author Andy Clement */ public abstract class AbstractTokenizer { private final int[] NO_LINEBREAKS = new int[0]; /** * The string to be tokenized. */ protected String expressionString; /** * The expressionString as a char array. */ protected char[] toProcess; /** * Length of input data. */ protected int max; /** * Current lexing position in the input data. */ protected int pos; /** * Output stream of tokens. */ protected List<Token> tokens = new ArrayList<Token>(); /** * Positions of linebreaks in the parsed string. */ protected int[] linebreaks = NO_LINEBREAKS; abstract void process(); public Tokens getTokens(String inputData) { this.expressionString = inputData; this.toProcess = (inputData + "\0").toCharArray(); this.max = toProcess.length; this.pos = 0; this.tokens.clear(); process(); return new Tokens(inputData, tokens, linebreaks); } /** * Check if this might be a two character token. */ protected boolean isTwoCharToken(TokenKind kind) { Assert.isTrue(kind.tokenChars.length == 2); Assert.isTrue(toProcess[pos] == kind.tokenChars[0]); return toProcess[pos + 1] == kind.tokenChars[1]; } /** * Push a token of just one character in length. */ protected void pushCharToken(TokenKind kind) { tokens.add(new Token(kind, pos, pos + 1)); pos++; } /** * Push a token of two characters in length. */ protected void pushPairToken(TokenKind kind) { tokens.add(new Token(kind, pos, pos + 2)); pos += 2; } protected boolean isIdentifier(char ch) { return isAlphabetic(ch) || isDigit(ch) || ch == '_' || ch == '$' || ch == '-'; } protected boolean isQuote(char ch) { return ch == '\'' || ch == '"'; } protected boolean isWhitespace(char ch) { return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; } protected boolean isDigit(char ch) { if (ch > 255) { return false; } return (flags[ch] & IS_DIGIT) != 0; } protected boolean isAlphabetic(char ch) { if (ch > 255) { return false; } return (flags[ch] & IS_ALPHA) != 0; } protected char[] subArray(int start, int end) { char[] result = new char[end - start]; System.arraycopy(toProcess, start, result, 0, end - start); return result; } protected void lexIdentifier() { int start = pos; do { pos++; } while (isIdentifier(toProcess[pos])); char[] subarray = subArray(start, pos); tokens.add(new Token(TokenKind.IDENTIFIER, subarray, start, pos)); } /** * Lex a string literal which uses single quotes as delimiters. To include * a single quote within the literal, use a pair ''. */ protected void lexQuotedStringLiteral() { lexStringLiteral('\'',DSLMessage.NON_TERMINATING_QUOTED_STRING); } /** * Lex a string literal which uses double quotes as delimiters. To include * a single quote within the literal, use a pair "". */ protected void lexDoubleQuotedStringLiteral() { lexStringLiteral('"',DSLMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING); } private void lexStringLiteral(char quoteChar, DSLMessage messageOnNonTerminationError) { int start = pos; boolean terminated = false; while (!terminated) { pos++; char ch = toProcess[pos]; if (ch == quoteChar) { // may not be the end if the char after is also a quoteChar if (toProcess[pos + 1] == quoteChar) { pos++; // skip over that too, and continue } else { terminated = true; } } if (ch == 0) { throw new ParseException(expressionString, start, messageOnNonTerminationError); } } pos++; tokens.add(new Token(TokenKind.LITERAL_STRING, subArray(start, pos), start, pos)); } /** * For the variant tokenizer (used following an '=' to parse an * argument value) we only terminate that identifier if * encountering a small set of characters. If the argument has * included a ' to put something in quotes, we remember * that and don't allow ' ' (space) and '\t' (tab) to terminate * the value. */ protected boolean isArgValueIdentifierTerminator(char ch, boolean quoteOpen) { return (ch == '|' && !quoteOpen) || (ch == ';' && !quoteOpen) || ch == '\0' || (ch == ' ' && !quoteOpen) || (ch == '\t' && !quoteOpen) || (ch == '>' && !quoteOpen) || ch == '\r' || ch == '\n'; } /** * To prevent the need to quote all argument values, this identifier * lexing function is used just after an '=' when we are about to * digest an arg value. It is much more relaxed about what it will * include in the identifier. */ protected void lexArgValueIdentifier() { // Much of the complexity in here relates to supporting cases like these: // 'hi'+payload // 'hi'+'world' // In these situations it looks like a quoted string and that perhaps the entire // argument value is being quoted, but in fact half way through it is discovered that the // entire value is not quoted, only the first part of the argument value is a string literal. int start = pos; boolean quoteOpen = false; int quoteClosedCount = 0; // Enables identification of this pattern: 'hello'+'world' Character quoteInUse = null; // If set, indicates this is being treated as a quoted string if (isQuote(toProcess[pos])) { quoteOpen = true; quoteInUse = toProcess[pos++]; } do { char ch = toProcess[pos]; if ((quoteInUse != null && ch == quoteInUse) || (quoteInUse == null && isQuote(ch))) { if (quoteInUse != null && quoteInUse == '\'' && ch == '\'' && toProcess[pos + 1] == '\'') { pos++; // skip over that too, and continue } else { quoteOpen = !quoteOpen; if (!quoteOpen) { quoteClosedCount++; } } } pos++; } while (!isArgValueIdentifierTerminator(toProcess[pos], quoteOpen)); char[] subarray = null; if (quoteInUse != null && quoteInUse == '"' && quoteClosedCount == 0 ) { throw new ParseException(expressionString, start, DSLMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING); } else if (quoteInUse != null && quoteInUse == '\'' && quoteClosedCount == 0) { throw new ParseException(expressionString, start, DSLMessage.NON_TERMINATING_QUOTED_STRING); } else if (quoteClosedCount == 1 && sameQuotes(start, pos - 1)) { tokens.add(new Token(TokenKind.LITERAL_STRING, subArray(start, pos), start, pos)); } else { subarray = subArray(start, pos); tokens.add(new Token(TokenKind.IDENTIFIER, subarray, start, pos)); } } protected boolean sameQuotes(int pos1, int pos2) { if (toProcess[pos1] == '\'') { return toProcess[pos2] == '\''; } else if (toProcess[pos1] == '"') { return toProcess[pos2] == '"'; } return false; } @Override public String toString() { StringBuilder s = new StringBuilder(); s.append(this.expressionString).append("\n"); for (int i = 0; i < this.pos; i++) { s.append(" "); } s.append("^\n"); s.append(tokens).append("\n"); return s.toString(); } public void raiseException(DSLMessage message, Object... inserts) { throw new ParseException(expressionString, pos, message, inserts); } protected void addLinebreak() { int[] newLinebreaks = new int[linebreaks.length+1]; System.arraycopy(linebreaks, 0, newLinebreaks, 0, linebreaks.length); newLinebreaks[linebreaks.length] = pos; linebreaks = newLinebreaks; pos++; } private static final byte flags[] = new byte[256]; private static final byte IS_DIGIT = 0x01; private static final byte IS_HEXDIGIT = 0x02; private static final byte IS_ALPHA = 0x04; static { for (int ch = '0'; ch <= '9'; ch++) { flags[ch] |= IS_DIGIT | IS_HEXDIGIT; } for (int ch = 'A'; ch <= 'F'; ch++) { flags[ch] |= IS_HEXDIGIT; } for (int ch = 'a'; ch <= 'f'; ch++) { flags[ch] |= IS_HEXDIGIT; } for (int ch = 'A'; ch <= 'Z'; ch++) { flags[ch] |= IS_ALPHA; } for (int ch = 'a'; ch <= 'z'; ch++) { flags[ch] |= IS_ALPHA; } } }
package com.tinkerrocks.structure; import com.tinkerrocks.storage.StorageConstants; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.io.FileUtils; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.engine.StandardTraversalEngine; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.stream.IntStream; /** * <p> * Test class * </p> * Created by ashishn on 8/11/15. */ public class RocksTest { private RocksGraph graph; @Before public void setup() throws IOException, InstantiationException { String path = "/tmp/databases_1"; Configuration configuration = new BaseConfiguration(); configuration.setProperty(StorageConstants.STORAGE_DIR_PROPERTY, path); FileUtils.deleteDirectory(new File(path)); FileUtils.forceMkdir(new File(path)); graph = RocksGraph.open(configuration); } @Test public void testMultiValues() { Vertex marko = graph.addVertex(T.label, "person", T.id, "jumbaho", "name", "marko", "age", 29); graph.createIndex("country", Vertex.class); marko.property(VertexProperty.Cardinality.list, "country", "usa"); marko.property(VertexProperty.Cardinality.set, "country", "uk"); marko.property(VertexProperty.Cardinality.set, "country", "uk"); marko.property(VertexProperty.Cardinality.list, "country", "japan"); GraphTraversalSource g = graph.traversal(GraphTraversalSource.build().engine(StandardTraversalEngine.build())); System.out.println(g.V("jumbaho").has("country", P.within("usa1", "usa2", "uk")).properties().toList()); } @Test public void addVertexTest() { graph.createIndex("age", Vertex.class); graph.createIndex("weight", Edge.class); GraphTraversalSource g = graph.traversal(GraphTraversalSource.build().engine(StandardTraversalEngine.build())); //System.out.println("g=" + g); System.out.println("traversed edge" + g.V().toList()); //.bothE("knows").has("weight", 0.5f).tryNext().orElse(null)); //g.addV() //g.addV().addE() Vertex marko = graph.addVertex(T.label, "person", T.id, 1, "name", "marko", "age", 29); Vertex vadas = graph.addVertex(T.label, "person", T.id, 2, "name", "vadas", "age", 27); Vertex lop = graph.addVertex(T.label, "software", T.id, 3, "name", "lop", "lang", "java"); Vertex josh = graph.addVertex(T.label, "person", T.id, 4, "name", "josh", "age", 32); Vertex ripple = graph.addVertex(T.label, "software", T.id, 5, "name", "ripple", "lang", "java"); Vertex peter = graph.addVertex(T.label, "person", T.id, 6, "name", "peter", "age", 35); marko.addEdge("knows", vadas, T.id, 7, "weight", 0.5f, "weight1", 10.6f); marko.addEdge("knows", josh, T.id, 8, "weight", 1.0f); marko.addEdge("created", lop, T.id, 9, "weight", 0.4f); josh.addEdge("created", ripple, T.id, 10, "weight", 1.0f); josh.addEdge("created", lop, T.id, 11, "weight", 0.4f); peter.addEdge("created", lop, T.id, 12, "weight", 0.2f); Iterator<Vertex> iter = graph.vertices(1); while (iter.hasNext()) { Vertex test = iter.next(); Iterator<VertexProperty<Object>> properties = test.properties(); while (properties.hasNext()) { System.out.println("vertex:" + test + "\tproperties:" + properties.next()); } Iterator<Edge> edges = test.edges(Direction.BOTH); while (edges.hasNext()) { Edge edge = edges.next(); System.out.println("Edge: " + edge); Iterator<Property<Object>> edge_properties = edge.properties(); while (edge_properties.hasNext()) { System.out.println("edge:" + test + "\tproperties:" + edge_properties.next()); } } //System.out.println(iter.next().edges(Direction.BOTH).hasNext()); } } @Test public void PerfTest() { graph.createIndex("name", Vertex.class); long start = System.currentTimeMillis(); int ITERATIONS = 10000; for (int i = 0; i < ITERATIONS; i++) { graph.addVertex(T.label, "person", T.id, 200 + i, "name", "marko" + i, "age", 29); } long end = System.currentTimeMillis() - start; System.out.println("write time takes to add " + ITERATIONS + " vertices (ms):\t" + end); start = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { graph.vertices(200 + i).next().property("name"); } end = System.currentTimeMillis() - start; System.out.println("read time takes to read " + ITERATIONS + " vertices (ms):\t" + end); start = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { graph.vertices(200).next().property("name"); } end = System.currentTimeMillis() - start; System.out.println("read time takes to access same vertex " + ITERATIONS + " times (ms):\t" + end); Vertex supernode = graph.vertices(200).next(); Vertex supernodeSink = graph.vertices(201).next(); start = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { supernode.addEdge("knows", supernodeSink, T.id, 700 + i, "weight", 0.5f); } end = System.currentTimeMillis() - start; System.out.println("time to add " + ITERATIONS + " edges (ms):\t" + end); start = System.currentTimeMillis(); supernode.edges(Direction.BOTH); end = System.currentTimeMillis() - start; System.out.println("time to read " + ITERATIONS + " edges (ms):\t" + end); start = System.currentTimeMillis(); Iterator<Edge> test = supernode.edges(Direction.OUT, "knows"); end = System.currentTimeMillis() - start; System.out.println("time to read " + ITERATIONS + " cached edges (ms):\t" + end); long count = IteratorUtils.count(test); System.out.println("got edges: " + count); } @Test public void IndexTest() { graph.createIndex("age", Vertex.class); System.out.println("started writing..."); int i = 0; long startw = System.currentTimeMillis(); while (i < 500) { graph.addVertex(T.label, "person", T.id, "index" + i, "name", "marko", "age", 29); i++; } while (i < 500) { graph.addVertex(T.label, "personal", T.id, "index" + (5000 + i), "name", "marko", "age", 29); i++; } while (i < 200000) { graph.addVertex(T.label, "movie", T.id, "index" + (10000 + i), "name", "marko"); i++; } graph.addVertex(T.label, "personal", T.id, ++i, "name", "marko", "age", 30); graph.addVertex(T.label, "personal", T.id, ++i, "name", "marko", "age", 31); graph.addVertex(T.label, "personal", T.id, ++i, "name", "marko", "age", 31); long endw = System.currentTimeMillis(); System.out.println("time taken to write:" + (endw - startw)); GraphTraversalSource g = graph.traversal(GraphTraversalSource.build().engine(StandardTraversalEngine.build())); System.out.println("starting search...."); long start = System.currentTimeMillis(); System.out.println(g.V().has("age", 31).toList()); long end = System.currentTimeMillis(); System.out.println("time taken to search:" + (end - start)); } @Test public void edgeIndexTest() { Vertex v = graph.addVertex(T.label, "personal", T.id, "indextest" + 1, "name", "marko", "age", 30); Vertex outV = graph.addVertex(T.label, "personal", T.id, "indextest" + 2, "name", "polo", "age", 30); //graph.createIndex("directed", Edge.class); IntStream.range(0, 1000000).forEach(value -> { v.addEdge("movie", outV, T.id, value, "directed", "test1" + (value % 10000)); }); GraphTraversalSource g = graph.traversal(GraphTraversalSource.build().engine(StandardTraversalEngine.build())); long start; String value = "test1" + 10; //for (int i = 0; i < 10; i++) { start = System.currentTimeMillis(); g.E().has("directed", value).toList(); System.out.println("time taken to search:" + (System.currentTimeMillis() - start)); //} } @Test public void edgeLabelsTest() { Vertex v = graph.addVertex(T.label, "personal", T.id, "edgeTest" + 1, "name", "marko", "age", 30); Vertex outV = graph.addVertex(T.label, "personal", T.id, "edgeTest" + 2, "name", "polo", "age", 30); int i = 0; while (i < 2) { v.addEdge("person", outV, T.id, "index" + i); i++; } while (i < 10000) { v.addEdge("person1", outV, T.id, "index" + i); i++; } while (i < 200000) { v.addEdge("person2", outV, T.id, "index" + i); i++; } GraphTraversalSource g = graph.traversal(GraphTraversalSource.build().engine(StandardTraversalEngine.build())); long start = System.currentTimeMillis(); g.V("edgeTest" + 1).outE("person").toList(); long end = System.currentTimeMillis() - start; System.out.println("time taken:" + end); } @After public void close() throws Exception { this.graph.close(); } }
package com.clockwork.bullet.joints; import com.bulletphysics.dynamics.constraintsolver.SliderConstraint; import com.bulletphysics.linearmath.Transform; import com.clockwork.bullet.objects.PhysicsRigidBody; import com.clockwork.bullet.util.Converter; import com.clockwork.export.InputCapsule; import com.clockwork.export.CWExporter; import com.clockwork.export.CWImporter; import com.clockwork.export.OutputCapsule; import com.clockwork.math.Matrix3f; import com.clockwork.math.Vector3f; import java.io.IOException; /** * <i>From bullet manual:</i> * The slider constraint allows the body to rotate around one axis and translate along this axis. */ public class SliderJoint extends PhysicsJoint { protected Matrix3f rotA, rotB; protected boolean useLinearReferenceFrameA; public SliderJoint() { } /** * @param pivotA local translation of the joint connection point in node A * @param pivotB local translation of the joint connection point in node B */ public SliderJoint(PhysicsRigidBody nodeA, PhysicsRigidBody nodeB, Vector3f pivotA, Vector3f pivotB, Matrix3f rotA, Matrix3f rotB, boolean useLinearReferenceFrameA) { super(nodeA, nodeB, pivotA, pivotB); this.rotA=rotA; this.rotB=rotB; this.useLinearReferenceFrameA=useLinearReferenceFrameA; createJoint(); } /** * @param pivotA local translation of the joint connection point in node A * @param pivotB local translation of the joint connection point in node B */ public SliderJoint(PhysicsRigidBody nodeA, PhysicsRigidBody nodeB, Vector3f pivotA, Vector3f pivotB, boolean useLinearReferenceFrameA) { super(nodeA, nodeB, pivotA, pivotB); this.rotA=new Matrix3f(); this.rotB=new Matrix3f(); this.useLinearReferenceFrameA=useLinearReferenceFrameA; createJoint(); } public float getLowerLinLimit() { return ((SliderConstraint) constraint).getLowerLinLimit(); } public void setLowerLinLimit(float lowerLinLimit) { ((SliderConstraint) constraint).setLowerLinLimit(lowerLinLimit); } public float getUpperLinLimit() { return ((SliderConstraint) constraint).getUpperLinLimit(); } public void setUpperLinLimit(float upperLinLimit) { ((SliderConstraint) constraint).setUpperLinLimit(upperLinLimit); } public float getLowerAngLimit() { return ((SliderConstraint) constraint).getLowerAngLimit(); } public void setLowerAngLimit(float lowerAngLimit) { ((SliderConstraint) constraint).setLowerAngLimit(lowerAngLimit); } public float getUpperAngLimit() { return ((SliderConstraint) constraint).getUpperAngLimit(); } public void setUpperAngLimit(float upperAngLimit) { ((SliderConstraint) constraint).setUpperAngLimit(upperAngLimit); } public float getSoftnessDirLin() { return ((SliderConstraint) constraint).getSoftnessDirLin(); } public void setSoftnessDirLin(float softnessDirLin) { ((SliderConstraint) constraint).setSoftnessDirLin(softnessDirLin); } public float getRestitutionDirLin() { return ((SliderConstraint) constraint).getRestitutionDirLin(); } public void setRestitutionDirLin(float restitutionDirLin) { ((SliderConstraint) constraint).setRestitutionDirLin(restitutionDirLin); } public float getDampingDirLin() { return ((SliderConstraint) constraint).getDampingDirLin(); } public void setDampingDirLin(float dampingDirLin) { ((SliderConstraint) constraint).setDampingDirLin(dampingDirLin); } public float getSoftnessDirAng() { return ((SliderConstraint) constraint).getSoftnessDirAng(); } public void setSoftnessDirAng(float softnessDirAng) { ((SliderConstraint) constraint).setSoftnessDirAng(softnessDirAng); } public float getRestitutionDirAng() { return ((SliderConstraint) constraint).getRestitutionDirAng(); } public void setRestitutionDirAng(float restitutionDirAng) { ((SliderConstraint) constraint).setRestitutionDirAng(restitutionDirAng); } public float getDampingDirAng() { return ((SliderConstraint) constraint).getDampingDirAng(); } public void setDampingDirAng(float dampingDirAng) { ((SliderConstraint) constraint).setDampingDirAng(dampingDirAng); } public float getSoftnessLimLin() { return ((SliderConstraint) constraint).getSoftnessLimLin(); } public void setSoftnessLimLin(float softnessLimLin) { ((SliderConstraint) constraint).setSoftnessLimLin(softnessLimLin); } public float getRestitutionLimLin() { return ((SliderConstraint) constraint).getRestitutionLimLin(); } public void setRestitutionLimLin(float restitutionLimLin) { ((SliderConstraint) constraint).setRestitutionLimLin(restitutionLimLin); } public float getDampingLimLin() { return ((SliderConstraint) constraint).getDampingLimLin(); } public void setDampingLimLin(float dampingLimLin) { ((SliderConstraint) constraint).setDampingLimLin(dampingLimLin); } public float getSoftnessLimAng() { return ((SliderConstraint) constraint).getSoftnessLimAng(); } public void setSoftnessLimAng(float softnessLimAng) { ((SliderConstraint) constraint).setSoftnessLimAng(softnessLimAng); } public float getRestitutionLimAng() { return ((SliderConstraint) constraint).getRestitutionLimAng(); } public void setRestitutionLimAng(float restitutionLimAng) { ((SliderConstraint) constraint).setRestitutionLimAng(restitutionLimAng); } public float getDampingLimAng() { return ((SliderConstraint) constraint).getDampingLimAng(); } public void setDampingLimAng(float dampingLimAng) { ((SliderConstraint) constraint).setDampingLimAng(dampingLimAng); } public float getSoftnessOrthoLin() { return ((SliderConstraint) constraint).getSoftnessOrthoLin(); } public void setSoftnessOrthoLin(float softnessOrthoLin) { ((SliderConstraint) constraint).setSoftnessOrthoLin(softnessOrthoLin); } public float getRestitutionOrthoLin() { return ((SliderConstraint) constraint).getRestitutionOrthoLin(); } public void setRestitutionOrthoLin(float restitutionOrthoLin) { ((SliderConstraint) constraint).setRestitutionOrthoLin(restitutionOrthoLin); } public float getDampingOrthoLin() { return ((SliderConstraint) constraint).getDampingOrthoLin(); } public void setDampingOrthoLin(float dampingOrthoLin) { ((SliderConstraint) constraint).setDampingOrthoLin(dampingOrthoLin); } public float getSoftnessOrthoAng() { return ((SliderConstraint) constraint).getSoftnessOrthoAng(); } public void setSoftnessOrthoAng(float softnessOrthoAng) { ((SliderConstraint) constraint).setSoftnessOrthoAng(softnessOrthoAng); } public float getRestitutionOrthoAng() { return ((SliderConstraint) constraint).getRestitutionOrthoAng(); } public void setRestitutionOrthoAng(float restitutionOrthoAng) { ((SliderConstraint) constraint).setRestitutionOrthoAng(restitutionOrthoAng); } public float getDampingOrthoAng() { return ((SliderConstraint) constraint).getDampingOrthoAng(); } public void setDampingOrthoAng(float dampingOrthoAng) { ((SliderConstraint) constraint).setDampingOrthoAng(dampingOrthoAng); } public boolean isPoweredLinMotor() { return ((SliderConstraint) constraint).getPoweredLinMotor(); } public void setPoweredLinMotor(boolean poweredLinMotor) { ((SliderConstraint) constraint).setPoweredLinMotor(poweredLinMotor); } public float getTargetLinMotorVelocity() { return ((SliderConstraint) constraint).getTargetLinMotorVelocity(); } public void setTargetLinMotorVelocity(float targetLinMotorVelocity) { ((SliderConstraint) constraint).setTargetLinMotorVelocity(targetLinMotorVelocity); } public float getMaxLinMotorForce() { return ((SliderConstraint) constraint).getMaxLinMotorForce(); } public void setMaxLinMotorForce(float maxLinMotorForce) { ((SliderConstraint) constraint).setMaxLinMotorForce(maxLinMotorForce); } public boolean isPoweredAngMotor() { return ((SliderConstraint) constraint).getPoweredAngMotor(); } public void setPoweredAngMotor(boolean poweredAngMotor) { ((SliderConstraint) constraint).setPoweredAngMotor(poweredAngMotor); } public float getTargetAngMotorVelocity() { return ((SliderConstraint) constraint).getTargetAngMotorVelocity(); } public void setTargetAngMotorVelocity(float targetAngMotorVelocity) { ((SliderConstraint) constraint).setTargetAngMotorVelocity(targetAngMotorVelocity); } public float getMaxAngMotorForce() { return ((SliderConstraint) constraint).getMaxAngMotorForce(); } public void setMaxAngMotorForce(float maxAngMotorForce) { ((SliderConstraint) constraint).setMaxAngMotorForce(maxAngMotorForce); } @Override public void write(CWExporter ex) throws IOException { super.write(ex); OutputCapsule capsule = ex.getCapsule(this); //TODO: standard values.. capsule.write(((SliderConstraint) constraint).getDampingDirAng(), "dampingDirAng", 0f); capsule.write(((SliderConstraint) constraint).getDampingDirLin(), "dampingDirLin", 0f); capsule.write(((SliderConstraint) constraint).getDampingLimAng(), "dampingLimAng", 0f); capsule.write(((SliderConstraint) constraint).getDampingLimLin(), "dampingLimLin", 0f); capsule.write(((SliderConstraint) constraint).getDampingOrthoAng(), "dampingOrthoAng", 0f); capsule.write(((SliderConstraint) constraint).getDampingOrthoLin(), "dampingOrthoLin", 0f); capsule.write(((SliderConstraint) constraint).getLowerAngLimit(), "lowerAngLimit", 0f); capsule.write(((SliderConstraint) constraint).getLowerLinLimit(), "lowerLinLimit", 0f); capsule.write(((SliderConstraint) constraint).getMaxAngMotorForce(), "maxAngMotorForce", 0f); capsule.write(((SliderConstraint) constraint).getMaxLinMotorForce(), "maxLinMotorForce", 0f); capsule.write(((SliderConstraint) constraint).getPoweredAngMotor(), "poweredAngMotor", false); capsule.write(((SliderConstraint) constraint).getPoweredLinMotor(), "poweredLinMotor", false); capsule.write(((SliderConstraint) constraint).getRestitutionDirAng(), "restitutionDirAng", 0f); capsule.write(((SliderConstraint) constraint).getRestitutionDirLin(), "restitutionDirLin", 0f); capsule.write(((SliderConstraint) constraint).getRestitutionLimAng(), "restitutionLimAng", 0f); capsule.write(((SliderConstraint) constraint).getRestitutionLimLin(), "restitutionLimLin", 0f); capsule.write(((SliderConstraint) constraint).getRestitutionOrthoAng(), "restitutionOrthoAng", 0f); capsule.write(((SliderConstraint) constraint).getRestitutionOrthoLin(), "restitutionOrthoLin", 0f); capsule.write(((SliderConstraint) constraint).getSoftnessDirAng(), "softnessDirAng", 0f); capsule.write(((SliderConstraint) constraint).getSoftnessDirLin(), "softnessDirLin", 0f); capsule.write(((SliderConstraint) constraint).getSoftnessLimAng(), "softnessLimAng", 0f); capsule.write(((SliderConstraint) constraint).getSoftnessLimLin(), "softnessLimLin", 0f); capsule.write(((SliderConstraint) constraint).getSoftnessOrthoAng(), "softnessOrthoAng", 0f); capsule.write(((SliderConstraint) constraint).getSoftnessOrthoLin(), "softnessOrthoLin", 0f); capsule.write(((SliderConstraint) constraint).getTargetAngMotorVelocity(), "targetAngMotorVelicoty", 0f); capsule.write(((SliderConstraint) constraint).getTargetLinMotorVelocity(), "targetLinMotorVelicoty", 0f); capsule.write(((SliderConstraint) constraint).getUpperAngLimit(), "upperAngLimit", 0f); capsule.write(((SliderConstraint) constraint).getUpperLinLimit(), "upperLinLimit", 0f); capsule.write(useLinearReferenceFrameA, "useLinearReferenceFrameA", false); } @Override public void read(CWImporter im) throws IOException { super.read(im); InputCapsule capsule = im.getCapsule(this); float dampingDirAng = capsule.readFloat("dampingDirAng", 0f); float dampingDirLin = capsule.readFloat("dampingDirLin", 0f); float dampingLimAng = capsule.readFloat("dampingLimAng", 0f); float dampingLimLin = capsule.readFloat("dampingLimLin", 0f); float dampingOrthoAng = capsule.readFloat("dampingOrthoAng", 0f); float dampingOrthoLin = capsule.readFloat("dampingOrthoLin", 0f); float lowerAngLimit = capsule.readFloat("lowerAngLimit", 0f); float lowerLinLimit = capsule.readFloat("lowerLinLimit", 0f); float maxAngMotorForce = capsule.readFloat("maxAngMotorForce", 0f); float maxLinMotorForce = capsule.readFloat("maxLinMotorForce", 0f); boolean poweredAngMotor = capsule.readBoolean("poweredAngMotor", false); boolean poweredLinMotor = capsule.readBoolean("poweredLinMotor", false); float restitutionDirAng = capsule.readFloat("restitutionDirAng", 0f); float restitutionDirLin = capsule.readFloat("restitutionDirLin", 0f); float restitutionLimAng = capsule.readFloat("restitutionLimAng", 0f); float restitutionLimLin = capsule.readFloat("restitutionLimLin", 0f); float restitutionOrthoAng = capsule.readFloat("restitutionOrthoAng", 0f); float restitutionOrthoLin = capsule.readFloat("restitutionOrthoLin", 0f); float softnessDirAng = capsule.readFloat("softnessDirAng", 0f); float softnessDirLin = capsule.readFloat("softnessDirLin", 0f); float softnessLimAng = capsule.readFloat("softnessLimAng", 0f); float softnessLimLin = capsule.readFloat("softnessLimLin", 0f); float softnessOrthoAng = capsule.readFloat("softnessOrthoAng", 0f); float softnessOrthoLin = capsule.readFloat("softnessOrthoLin", 0f); float targetAngMotorVelicoty = capsule.readFloat("targetAngMotorVelicoty", 0f); float targetLinMotorVelicoty = capsule.readFloat("targetLinMotorVelicoty", 0f); float upperAngLimit = capsule.readFloat("upperAngLimit", 0f); float upperLinLimit = capsule.readFloat("upperLinLimit", 0f); useLinearReferenceFrameA = capsule.readBoolean("useLinearReferenceFrameA", false); createJoint(); ((SliderConstraint)constraint).setDampingDirAng(dampingDirAng); ((SliderConstraint)constraint).setDampingDirLin(dampingDirLin); ((SliderConstraint)constraint).setDampingLimAng(dampingLimAng); ((SliderConstraint)constraint).setDampingLimLin(dampingLimLin); ((SliderConstraint)constraint).setDampingOrthoAng(dampingOrthoAng); ((SliderConstraint)constraint).setDampingOrthoLin(dampingOrthoLin); ((SliderConstraint)constraint).setLowerAngLimit(lowerAngLimit); ((SliderConstraint)constraint).setLowerLinLimit(lowerLinLimit); ((SliderConstraint)constraint).setMaxAngMotorForce(maxAngMotorForce); ((SliderConstraint)constraint).setMaxLinMotorForce(maxLinMotorForce); ((SliderConstraint)constraint).setPoweredAngMotor(poweredAngMotor); ((SliderConstraint)constraint).setPoweredLinMotor(poweredLinMotor); ((SliderConstraint)constraint).setRestitutionDirAng(restitutionDirAng); ((SliderConstraint)constraint).setRestitutionDirLin(restitutionDirLin); ((SliderConstraint)constraint).setRestitutionLimAng(restitutionLimAng); ((SliderConstraint)constraint).setRestitutionLimLin(restitutionLimLin); ((SliderConstraint)constraint).setRestitutionOrthoAng(restitutionOrthoAng); ((SliderConstraint)constraint).setRestitutionOrthoLin(restitutionOrthoLin); ((SliderConstraint)constraint).setSoftnessDirAng(softnessDirAng); ((SliderConstraint)constraint).setSoftnessDirLin(softnessDirLin); ((SliderConstraint)constraint).setSoftnessLimAng(softnessLimAng); ((SliderConstraint)constraint).setSoftnessLimLin(softnessLimLin); ((SliderConstraint)constraint).setSoftnessOrthoAng(softnessOrthoAng); ((SliderConstraint)constraint).setSoftnessOrthoLin(softnessOrthoLin); ((SliderConstraint)constraint).setTargetAngMotorVelocity(targetAngMotorVelicoty); ((SliderConstraint)constraint).setTargetLinMotorVelocity(targetLinMotorVelicoty); ((SliderConstraint)constraint).setUpperAngLimit(upperAngLimit); ((SliderConstraint)constraint).setUpperLinLimit(upperLinLimit); } protected void createJoint(){ Transform transA = new Transform(Converter.convert(rotA)); Converter.convert(pivotA, transA.origin); Converter.convert(rotA, transA.basis); Transform transB = new Transform(Converter.convert(rotB)); Converter.convert(pivotB, transB.origin); Converter.convert(rotB, transB.basis); constraint = new SliderConstraint(nodeA.getObjectId(), nodeB.getObjectId(), transA, transB, useLinearReferenceFrameA); } }
/** * Copyright 2008-2017 Qualogy Solutions B.V. * * 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.qualogy.qafe.mgwt.client.vo.ui; import java.util.ArrayList; import java.util.List; /** * @author rjankie */ public class DataGridGVO extends EditableComponentGVO { private Integer maxRows ; private Integer minRows ; private Integer pageSize; private DataGridColumnGVO[] columns; private Boolean delete=Boolean.FALSE; private Boolean add = Boolean.FALSE; private Boolean pageScroll=Boolean.FALSE; private Boolean export=Boolean.FALSE; private Boolean importEnabled=Boolean.FALSE; public Boolean getImportEnabled() { return importEnabled; } public void setImportEnabled(Boolean importEnabled) { this.importEnabled = importEnabled; } private ComponentGVO saveComponent; private ComponentGVO addComponent; private ComponentGVO deleteComponent; private ComponentGVO refreshComponent; private ComponentGVO cancelComponent; private ComponentGVO pageSizeComponent; private ComponentGVO offSetComponent; private ComponentGVO exportComponent; private Boolean multipleSelect=Boolean.FALSE; private String[] rowColors; // private List<String> idFields = new ArrayList<String>(); // // public List<String> getIdFields() { // return idFields; // } // // // public void setIdFields(List<String> idFields) { // this.idFields = idFields; // } public Boolean getMultipleSelect() { return multipleSelect; } public void setMultipleSelect(Boolean multipleSelect) { this.multipleSelect = multipleSelect; } private PanelGVO overflow; public ComponentGVO[] getComponents() { List<ComponentGVO> cs = new ArrayList<ComponentGVO>(); cs.add(saveComponent); return cs.toArray(new ComponentGVO[]{}); } public Boolean getAdd() { return add; } public void setAdd(Boolean add) { this.add = add; } public String getClassName() { return "com.qualogy.qafe.gwt.client.vo.ui.DataGridGVO"; } public DataGridColumnGVO[] getColumns() { return columns; } public void setColumns(DataGridColumnGVO[] columns) { this.columns = columns; } public Integer getMaxRows() { return maxRows; } public void setMaxRows(Integer maxRows) { this.maxRows = maxRows; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Boolean getDelete() { return delete; } public void setDelete(Boolean delete) { this.delete = delete; } public ComponentGVO getCancelComponent() { return cancelComponent; } public void setCancelComponent(ComponentGVO cancelComponent) { this.cancelComponent = cancelComponent; } public ComponentGVO getRefreshComponent() { return refreshComponent; } public void setRefreshComponent(ComponentGVO refreshComponent) { this.refreshComponent = refreshComponent; } public ComponentGVO getAddComponent() { return addComponent; } public void setAddComponent(ComponentGVO addComponent) { this.addComponent = addComponent; } public ComponentGVO getDeleteComponent() { return deleteComponent; } public void setDeleteComponent(ComponentGVO deleteComponent) { this.deleteComponent = deleteComponent; } public ComponentGVO getSaveComponent() { return saveComponent; } public void setSaveComponent(ComponentGVO saveComponent) { this.saveComponent = saveComponent; } public ComponentGVO getOffSetComponent() { return offSetComponent; } public void setOffSetComponent(ComponentGVO offSetComponent) { this.offSetComponent = offSetComponent; } public ComponentGVO getPageSizeComponent() { return pageSizeComponent; } public void setPageSizeComponent(ComponentGVO pageSizeComponent) { this.pageSizeComponent = pageSizeComponent; } public Integer getMinRows() { return minRows; } public void setMinRows(Integer minRows) { this.minRows = minRows; } public Boolean getExport() { return export; } public void setExport(Boolean export) { this.export = export; } public PanelGVO getOverflow() { return overflow; } public void setOverflow(PanelGVO overflow) { this.overflow = overflow; } public boolean hasColumns(){ return (columns!=null); } public boolean hasOverFlow(){ return (overflow!=null); } public ComponentGVO getExportComponent() { return exportComponent; } public void setExportComponent(ComponentGVO exportComponent) { this.exportComponent = exportComponent; } public String[] getRowColors() { return rowColors; } public void setRowColors(String[] rowColors) { this.rowColors = rowColors; } public Boolean getPageScroll() { return pageScroll; } public void setPageScroll(Boolean pageScroll) { this.pageScroll = pageScroll; } public DataGridGVO clone() { DataGridGVO dataGridGVO = new DataGridGVO(); dataGridGVO.setAdd(add); dataGridGVO.setDelete(delete); dataGridGVO.setExport(export); dataGridGVO.setImportEnabled(importEnabled); dataGridGVO.setMaxRows(maxRows); dataGridGVO.setMinRows(minRows); dataGridGVO.setPageSize(pageSize); dataGridGVO.setPageScroll(pageScroll); dataGridGVO.setAddComponent(addComponent); dataGridGVO.setCancelComponent(cancelComponent); dataGridGVO.setDeleteComponent(deleteComponent); dataGridGVO.setSaveComponent(saveComponent); dataGridGVO.setRefreshComponent(refreshComponent); dataGridGVO.setPageSizeComponent(pageSizeComponent); dataGridGVO.setOffSetComponent(offSetComponent); dataGridGVO.setExportComponent(exportComponent); dataGridGVO.setMultipleSelect(multipleSelect); dataGridGVO.setRowColors(rowColors); dataGridGVO.setOverflow(overflow); dataGridGVO.setEditable(editable); dataGridGVO.setConditionalStyleRef(conditionalStyleRef); dataGridGVO.setId(id); dataGridGVO.setDisabled(disabled); dataGridGVO.setVisible(visible); dataGridGVO.setStyleClass(styleClass); dataGridGVO.setStyleProperties(styleProperties); dataGridGVO.setEvents(events); dataGridGVO.setMenu(menu); dataGridGVO.setWindow(getWindow()); dataGridGVO.setTooltip(getTooltip()); dataGridGVO.setFieldName(getFieldName()); dataGridGVO.setWidth(getWidth()); dataGridGVO.setHeight(getHeight()); dataGridGVO.setParent(getParent()); dataGridGVO.setContext(getContext()); dataGridGVO.setUuid(getUuid()); dataGridGVO.setColumns(columns); dataGridGVO.setGroup(getGroup()); return dataGridGVO; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.rya.indexing.entity.storage.mongo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.apache.rya.api.domain.RyaType; import org.apache.rya.api.domain.RyaURI; import org.apache.rya.indexing.entity.model.Entity; import org.apache.rya.indexing.entity.model.Property; import org.apache.rya.indexing.entity.model.Type; import org.apache.rya.indexing.entity.model.TypedEntity; import org.apache.rya.indexing.entity.storage.EntityStorage; import org.apache.rya.indexing.entity.storage.EntityStorage.EntityAlreadyExistsException; import org.apache.rya.indexing.entity.storage.EntityStorage.EntityStorageException; import org.apache.rya.indexing.entity.storage.EntityStorage.StaleUpdateException; import org.apache.rya.mongodb.MongoTestBase; import org.junit.Test; import org.openrdf.model.vocabulary.XMLSchema; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; /** * Integration tests the methods of {@link MongoEntityStorage}. */ public class MongoEntityStorageIT extends MongoTestBase { private static final String RYA_INSTANCE_NAME = "testInstance"; @Test public void create_and_get() throws Exception { // An Entity that will be stored. final Entity entity = Entity.builder() .setSubject(new RyaURI("urn:GTIN-14/00012345600012")) .setExplicitType(new RyaURI("urn:icecream")) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:brand"), new RyaType(XMLSchema.STRING, "Awesome Icecream"))) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:flavor"), new RyaType(XMLSchema.STRING, "Chocolate"))) .build(); // Create it. final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME); storage.create(entity); // Get it. final Optional<Entity> storedEntity = storage.get(new RyaURI("urn:GTIN-14/00012345600012")); // Verify the correct value was returned. assertEquals(entity, storedEntity.get()); } @Test public void can_not_create_with_same_subject() throws Exception { // A Type that will be stored. final Entity entity = Entity.builder() .setSubject(new RyaURI("urn:GTIN-14/00012345600012")) .setExplicitType(new RyaURI("urn:icecream")) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:brand"), new RyaType(XMLSchema.STRING, "Awesome Icecream"))) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:flavor"), new RyaType(XMLSchema.STRING, "Chocolate"))) .build(); // Create it. final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME); storage.create(entity); // Try to create it again. This will fail. boolean failed = false; try { storage.create(entity); } catch(final EntityAlreadyExistsException e) { failed = true; } assertTrue(failed); } @Test public void get_noneExisting() throws Exception { // Get a Type that hasn't been created. final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME); final Optional<Entity> storedEntity = storage.get(new RyaURI("urn:GTIN-14/00012345600012")); // Verify nothing was returned. assertFalse(storedEntity.isPresent()); } @Test public void delete() throws Exception { // An Entity that will be stored. final Entity entity = Entity.builder() .setSubject(new RyaURI("urn:GTIN-14/00012345600012")) .setExplicitType(new RyaURI("urn:icecream")) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:brand"), new RyaType(XMLSchema.STRING, "Awesome Icecream"))) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:flavor"), new RyaType(XMLSchema.STRING, "Chocolate"))) .build(); // Create it. final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME); storage.create(entity); // Delete it. final boolean deleted = storage.delete( new RyaURI("urn:GTIN-14/00012345600012") ); // Verify a document was deleted. assertTrue( deleted ); } @Test public void delete_nonExisting() throws Exception { // Delete an Entity that has not been created. final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME); final boolean deleted = storage.delete( new RyaURI("urn:GTIN-14/00012345600012") ); // Verify no document was deleted. assertFalse( deleted ); } @Test public void search_byDataType() throws Exception { final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME); // The Type we will search by. final Type icecreamType = new Type(new RyaURI("urn:icecream"), ImmutableSet.<RyaURI>builder() .add(new RyaURI("urn:brand")) .add(new RyaURI("urn:flavor")) .add(new RyaURI("urn:cost")) .build()); // Some Person typed entities. final Entity alice = Entity.builder() .setSubject( new RyaURI("urn:SSN/111-11-1111") ) .setExplicitType(new RyaURI("urn:person")) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "Alice"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "30"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "blue"))) .build(); final Entity bob = Entity.builder() .setSubject( new RyaURI("urn:SSN/222-22-2222") ) .setExplicitType(new RyaURI("urn:person")) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "Bob"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "57"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "blue"))) .build(); // Some Icecream typed objects. final Entity chocolateIcecream = Entity.builder() .setSubject(new RyaURI("urn:GTIN-14/00012345600012")) .setExplicitType(new RyaURI("urn:icecream")) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:brand"), new RyaType(XMLSchema.STRING, "Awesome Icecream"))) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:flavor"), new RyaType(XMLSchema.STRING, "Chocolate"))) .build(); final Entity vanillaIcecream = Entity.builder() .setSubject( new RyaURI("urn:GTIN-14/22356325213432") ) .setExplicitType(new RyaURI("urn:icecream")) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:brand"), new RyaType(XMLSchema.STRING, "Awesome Icecream"))) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:flavor"), new RyaType(XMLSchema.STRING, "Vanilla"))) .build(); final Entity strawberryIcecream = Entity.builder() .setSubject( new RyaURI("urn:GTIN-14/77544325436721") ) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:brand"), new RyaType(XMLSchema.STRING, "Awesome Icecream"))) .setProperty(new RyaURI("urn:icecream"), new Property(new RyaURI("urn:flavor"), new RyaType(XMLSchema.STRING, "Strawberry"))) .build(); // Create the objects in the storage. storage.create(alice); storage.create(bob); storage.create(chocolateIcecream); storage.create(vanillaIcecream); storage.create(strawberryIcecream); // Search for all icecreams. final Set<TypedEntity> objects = new HashSet<>(); try(final ConvertingCursor<TypedEntity> it = storage.search(Optional.empty(), icecreamType, new HashSet<>())) { while(it.hasNext()) { objects.add(it.next()); } } // Verify the expected results were returned. final Set<TypedEntity> expected = Sets.newHashSet( chocolateIcecream.makeTypedEntity(new RyaURI("urn:icecream")).get(), vanillaIcecream.makeTypedEntity(new RyaURI("urn:icecream")).get()); assertEquals(expected, objects); } @Test public void search_byFields() throws Exception { final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME); // A Type that defines a Person. final Type personType = new Type(new RyaURI("urn:person"), ImmutableSet.<RyaURI>builder() .add(new RyaURI("urn:name")) .add(new RyaURI("urn:age")) .add(new RyaURI("urn:eye")) .build()); // Some Person typed objects. final Entity alice = Entity.builder() .setSubject( new RyaURI("urn:SSN/111-11-1111") ) .setExplicitType(new RyaURI("urn:person")) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "Alice"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "30"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "blue"))) .build(); final Entity bob = Entity.builder() .setSubject( new RyaURI("urn:SSN/222-22-2222") ) .setExplicitType(new RyaURI("urn:person")) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "Bob"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "57"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "blue"))) .build(); final Entity charlie = Entity.builder() .setSubject( new RyaURI("urn:SSN/333-33-3333") ) .setExplicitType( new RyaURI("urn:person") ) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "Charlie"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "30"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "blue"))) .build(); final Entity david = Entity.builder() .setSubject( new RyaURI("urn:SSN/444-44-4444") ) .setExplicitType( new RyaURI("urn:person") ) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "David"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "30"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "brown"))) .build(); final Entity eve = Entity.builder() .setSubject( new RyaURI("urn:SSN/555-55-5555") ) .setExplicitType( new RyaURI("urn:person") ) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "Eve"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "30"))) .build(); final Entity frank = Entity.builder() .setSubject( new RyaURI("urn:SSN/666-66-6666") ) .setExplicitType( new RyaURI("urn:person") ) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "Frank"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "blue"))) .setProperty(new RyaURI("urn:someOtherType"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "30"))) .build(); final Entity george = Entity.builder() .setSubject( new RyaURI("urn:SSN/777-77-7777") ) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "George"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "30"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "blue"))) .build(); // Create the objects in the storage. storage.create(alice); storage.create(bob); storage.create(charlie); storage.create(david); storage.create(eve); storage.create(frank); storage.create(george); // Search for all people who are 30 and have blue eyes. final Set<TypedEntity> objects = new HashSet<>(); final Set<Property> searchValues = Sets.newHashSet( new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "blue")), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "30"))); try(final ConvertingCursor<TypedEntity> it = storage.search(Optional.empty(), personType, searchValues)) { while(it.hasNext()) { objects.add(it.next()); } } // Verify the expected results were returned. assertEquals(2, objects.size()); assertTrue(objects.contains(alice.makeTypedEntity(new RyaURI("urn:person")).get())); assertTrue(objects.contains(charlie.makeTypedEntity(new RyaURI("urn:person")).get())); } @Test public void update() throws Exception { final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME); // Store Alice in the repository. final Entity alice = Entity.builder() .setSubject( new RyaURI("urn:SSN/111-11-1111") ) .setExplicitType(new RyaURI("urn:person")) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "Alice"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "30"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "blue"))) .build(); storage.create(alice); // Show Alice was stored. Optional<Entity> latest = storage.get(new RyaURI("urn:SSN/111-11-1111")); assertEquals(alice, latest.get()); // Change Alice's eye color to brown. final Entity updated = Entity.builder(alice) .setVersion(latest.get().getVersion() + 1) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "brown"))) .build(); storage.update(alice, updated); // Fetch the Alice object and ensure it has the new value. latest = storage.get(new RyaURI("urn:SSN/111-11-1111")); assertEquals(updated, latest.get()); } @Test(expected = StaleUpdateException.class) public void update_stale() throws Exception { final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME); // Store Alice in the repository. final Entity alice = Entity.builder() .setSubject( new RyaURI("urn:SSN/111-11-1111") ) .setExplicitType(new RyaURI("urn:person")) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:name"), new RyaType(XMLSchema.STRING, "Alice"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:age"), new RyaType(XMLSchema.INT, "30"))) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "blue"))) .build(); storage.create(alice); // Show Alice was stored. final Optional<Entity> latest = storage.get(new RyaURI("urn:SSN/111-11-1111")); assertEquals(alice, latest.get()); // Create the wrong old state and try to change Alice's eye color to brown. final Entity wrongOld = Entity.builder(alice) .setVersion(500) .build(); final Entity updated = Entity.builder(alice) .setVersion(501) .setProperty(new RyaURI("urn:person"), new Property(new RyaURI("urn:eye"), new RyaType(XMLSchema.STRING, "brown"))) .build(); storage.update(wrongOld, updated); } @Test(expected = EntityStorageException.class) public void update_differentSubjects() throws Exception { // Two objects that do not have the same Subjects. final Entity old = Entity.builder() .setSubject( new RyaURI("urn:SSN/111-11-1111") ) .setExplicitType( new RyaURI("urn:person") ) .build(); final Entity updated = Entity.builder() .setSubject( new RyaURI("urn:SSN/222-22-2222") ) .setExplicitType( new RyaURI("urn:person") ) .build(); // The update will fail. final EntityStorage storage = new MongoEntityStorage(super.getMongoClient(), RYA_INSTANCE_NAME); storage.update(old, updated); } }
/* * Title: CloudSim Toolkit Description: CloudSim (Cloud Simulation) Toolkit for Modeling and * Simulation of Clouds Licence: GPL - http://www.gnu.org/copyleft/gpl.html * * Copyright (c) 2009-2012, The University of Melbourne, Australia */ package org.cloudbus.cloudsim; import java.util.ArrayList; import java.util.List; import org.cloudbus.cloudsim.core.CloudSim; import org.cloudbus.cloudsim.lists.PeList; import org.cloudbus.cloudsim.provisioners.BwProvisioner; import org.cloudbus.cloudsim.provisioners.RamProvisioner; /** * A Host is a Physical Machine (PM) inside a Datacenter. It is also called as a Server. * It executes actions related to management of virtual machines (e.g., creation and destruction). * A host has a defined policy for provisioning memory and bw, as well as an allocation policy for * Pe's to virtual machines. A host is associated to a datacenter. It can host virtual machines. * * @author Rodrigo N. Calheiros * @author Anton Beloglazov * @since CloudSim Toolkit 1.0 */ public class Host { /** The id of the host. */ private int id; /** The storage capacity. */ private long storage; /** The ram provisioner. */ private RamProvisioner ramProvisioner; /** The bw provisioner. */ private BwProvisioner bwProvisioner; /** The allocation policy for scheduling VM execution. */ private VmScheduler vmScheduler; /** The list of VMs assigned to the host. */ private final List<? extends Vm> vmList = new ArrayList<Vm>(); /** The Processing Elements (PEs) of the host, that * represent the CPU cores of it, and thus, its processing capacity. */ private List<? extends Pe> peList; /** Tells whether this host is working properly or has failed. */ private boolean failed; /** The VMs migrating in. */ private final List<Vm> vmsMigratingIn = new ArrayList<Vm>(); /** The datacenter where the host is placed. */ private Datacenter datacenter; /** * Instantiates a new host. * * @param id the host id * @param ramProvisioner the ram provisioner * @param bwProvisioner the bw provisioner * @param storage the storage capacity * @param peList the host's PEs list * @param vmScheduler the vm scheduler */ public Host( int id, RamProvisioner ramProvisioner, BwProvisioner bwProvisioner, long storage, List<? extends Pe> peList, VmScheduler vmScheduler) { setId(id); setRamProvisioner(ramProvisioner); setBwProvisioner(bwProvisioner); setStorage(storage); setVmScheduler(vmScheduler); setPeList(peList); setFailed(false); } /** * Requests updating of cloudlets' processing in VMs running in this host. * * @param currentTime the current time * @return expected time of completion of the next cloudlet in all VMs in this host or * {@link Double#MAX_VALUE} if there is no future events expected in this host * @pre currentTime >= 0.0 * @post $none * @todo there is an inconsistency between the return value of this method * and the individual call of {@link Vm#updateVmProcessing(double, java.util.List), * and consequently the {@link CloudletScheduler#updateVmProcessing(double, java.util.List)}. * The current method returns {@link Double#MAX_VALUE} while the other ones * return 0. It has to be checked if there is a reason for this * difference.} */ public double updateVmsProcessing(double currentTime) { double smallerTime = Double.MAX_VALUE; for (Vm vm : getVmList()) { double time = vm.updateVmProcessing( currentTime, getVmScheduler().getAllocatedMipsForVm(vm)); if (time > 0.0 && time < smallerTime) { smallerTime = time; } } return smallerTime; } /** * Adds a VM migrating into the current host. * * @param vm the vm */ public void addMigratingInVm(Vm vm) { vm.setInMigration(true); if (!getVmsMigratingIn().contains(vm)) { if (getStorage() < vm.getSize()) { Log.printConcatLine("[VmScheduler.addMigratingInVm] Allocation of VM #", vm.getId(), " to Host #", getId(), " failed by storage"); System.exit(0); } if (!getRamProvisioner().allocateRamForVm(vm, vm.getCurrentRequestedRam())) { Log.printConcatLine("[VmScheduler.addMigratingInVm] Allocation of VM #", vm.getId(), " to Host #", getId(), " failed by RAM"); System.exit(0); } if (!getBwProvisioner().allocateBwForVm(vm, vm.getCurrentRequestedBw())) { Log.printLine("[VmScheduler.addMigratingInVm] Allocation of VM #" + vm.getId() + " to Host #" + getId() + " failed by BW"); System.exit(0); } getVmScheduler().getVmsMigratingIn().add(vm.getUid()); if (!getVmScheduler().allocatePesForVm(vm, vm.getCurrentRequestedMips())) { Log.printLine("[VmScheduler.addMigratingInVm] Allocation of VM #" + vm.getId() + " to Host #" + getId() + " failed by MIPS"); System.exit(0); } setStorage(getStorage() - vm.getSize()); getVmsMigratingIn().add(vm); getVmList().add(vm); updateVmsProcessing(CloudSim.clock()); vm.getHost().updateVmsProcessing(CloudSim.clock()); } } /** * Removes a migrating in vm. * * @param vm the vm */ public void removeMigratingInVm(Vm vm) { vmDeallocate(vm); getVmsMigratingIn().remove(vm); getVmList().remove(vm); getVmScheduler().getVmsMigratingIn().remove(vm.getUid()); vm.setInMigration(false); } /** * Reallocate migrating in vms. Gets the VM in the migrating in queue * and allocate them on the host. */ public void reallocateMigratingInVms() { for (Vm vm : getVmsMigratingIn()) { if (!getVmList().contains(vm)) { getVmList().add(vm); } if (!getVmScheduler().getVmsMigratingIn().contains(vm.getUid())) { getVmScheduler().getVmsMigratingIn().add(vm.getUid()); } getRamProvisioner().allocateRamForVm(vm, vm.getCurrentRequestedRam()); getBwProvisioner().allocateBwForVm(vm, vm.getCurrentRequestedBw()); getVmScheduler().allocatePesForVm(vm, vm.getCurrentRequestedMips()); setStorage(getStorage() - vm.getSize()); } } /** * Checks if the host is suitable for vm. If it has enough resources * to attend the VM. * * @param vm the vm * @return true, if is suitable for vm */ public boolean isSuitableForVm(Vm vm) { return (getVmScheduler().getPeCapacity() >= vm.getCurrentRequestedMaxMips() && getVmScheduler().getAvailableMips() >= vm.getCurrentRequestedTotalMips() && getRamProvisioner().isSuitableForVm(vm, vm.getCurrentRequestedRam()) && getBwProvisioner() .isSuitableForVm(vm, vm.getCurrentRequestedBw())); } /** * Try to allocate resources to a new VM in the Host. * * @param vm Vm being started * @return $true if the VM could be started in the host; $false otherwise * @pre $none * @post $none */ public boolean vmCreate(Vm vm) { if (getStorage() < vm.getSize()) { Log.printConcatLine("[VmScheduler.vmCreate] Allocation of VM #", vm.getId(), " to Host #", getId(), " failed by storage"); return false; } if (!getRamProvisioner().allocateRamForVm(vm, vm.getCurrentRequestedRam())) { Log.printConcatLine("[VmScheduler.vmCreate] Allocation of VM #", vm.getId(), " to Host #", getId(), " failed by RAM"); return false; } if (!getBwProvisioner().allocateBwForVm(vm, vm.getCurrentRequestedBw())) { Log.printConcatLine("[VmScheduler.vmCreate] Allocation of VM #", vm.getId(), " to Host #", getId(), " failed by BW"); getRamProvisioner().deallocateRamForVm(vm); return false; } if (!getVmScheduler().allocatePesForVm(vm, vm.getCurrentRequestedMips())) { Log.printConcatLine("[VmScheduler.vmCreate] Allocation of VM #", vm.getId(), " to Host #", getId(), " failed by MIPS"); getRamProvisioner().deallocateRamForVm(vm); getBwProvisioner().deallocateBwForVm(vm); return false; } setStorage(getStorage() - vm.getSize()); getVmList().add(vm); vm.setHost(this); return true; } /** * Destroys a VM running in the host. * * @param vm the VM * @pre $none * @post $none */ public void vmDestroy(Vm vm) { if (vm != null) { vmDeallocate(vm); getVmList().remove(vm); vm.setHost(null); } } /** * Destroys all VMs running in the host. * * @pre $none * @post $none */ public void vmDestroyAll() { vmDeallocateAll(); for (Vm vm : getVmList()) { vm.setHost(null); setStorage(getStorage() + vm.getSize()); } getVmList().clear(); } /** * Deallocate all resources of a VM. * * @param vm the VM */ protected void vmDeallocate(Vm vm) { getRamProvisioner().deallocateRamForVm(vm); getBwProvisioner().deallocateBwForVm(vm); getVmScheduler().deallocatePesForVm(vm); setStorage(getStorage() + vm.getSize()); } /** * Deallocate all resources of all VMs. */ protected void vmDeallocateAll() { getRamProvisioner().deallocateRamForAllVms(); getBwProvisioner().deallocateBwForAllVms(); getVmScheduler().deallocatePesForAllVms(); } /** * Gets a VM by its id and user. * * @param vmId the vm id * @param userId ID of VM's owner * @return the virtual machine object, $null if not found * @pre $none * @post $none */ public Vm getVm(int vmId, int userId) { for (Vm vm : getVmList()) { if (vm.getId() == vmId && vm.getUserId() == userId) { return vm; } } return null; } /** * Gets the pes number. * * @return the pes number */ public int getNumberOfPes() { return getPeList().size(); } /** * Gets the free pes number. * * @return the free pes number */ public int getNumberOfFreePes() { return PeList.getNumberOfFreePes(getPeList()); } /** * Gets the total mips. * * @return the total mips */ public int getTotalMips() { return PeList.getTotalMips(getPeList()); } /** * Allocates PEs for a VM. * * @param vm the vm * @param mipsShare the list of MIPS share to be allocated to the VM * @return $true if this policy allows a new VM in the host, $false otherwise * @pre $none * @post $none */ public boolean allocatePesForVm(Vm vm, List<Double> mipsShare) { return getVmScheduler().allocatePesForVm(vm, mipsShare); } /** * Releases PEs allocated to a VM. * * @param vm the vm * @pre $none * @post $none */ public void deallocatePesForVm(Vm vm) { getVmScheduler().deallocatePesForVm(vm); } /** * Gets the MIPS share of each Pe that is allocated to a given VM. * * @param vm the vm * @return an array containing the amount of MIPS of each pe that is available to the VM * @pre $none * @post $none */ public List<Double> getAllocatedMipsForVm(Vm vm) { return getVmScheduler().getAllocatedMipsForVm(vm); } /** * Gets the total allocated MIPS for a VM along all its PEs. * * @param vm the vm * @return the allocated mips for vm */ public double getTotalAllocatedMipsForVm(Vm vm) { return getVmScheduler().getTotalAllocatedMipsForVm(vm); } /** * Returns the maximum available MIPS among all the PEs of the host. * * @return max mips */ public double getMaxAvailableMips() { return getVmScheduler().getMaxAvailableMips(); } /** * Gets the total free MIPS available at the host. * * @return the free mips */ public double getAvailableMips() { return getVmScheduler().getAvailableMips(); } /** * Gets the host bw. * * @return the host bw * @pre $none * @post $result > 0 */ public long getBw() { return getBwProvisioner().getBw(); } /** * Gets the host memory. * * @return the host memory * @pre $none * @post $result > 0 */ public int getRam() { return getRamProvisioner().getRam(); } /** * Gets the host storage. * * @return the host storage * @pre $none * @post $result >= 0 */ public long getStorage() { return storage; } /** * Gets the host id. * * @return the host id */ public int getId() { return id; } /** * Sets the host id. * * @param id the new host id */ protected void setId(int id) { this.id = id; } /** * Gets the ram provisioner. * * @return the ram provisioner */ public RamProvisioner getRamProvisioner() { return ramProvisioner; } /** * Sets the ram provisioner. * * @param ramProvisioner the new ram provisioner */ protected void setRamProvisioner(RamProvisioner ramProvisioner) { this.ramProvisioner = ramProvisioner; } /** * Gets the bw provisioner. * * @return the bw provisioner */ public BwProvisioner getBwProvisioner() { return bwProvisioner; } /** * Sets the bw provisioner. * * @param bwProvisioner the new bw provisioner */ protected void setBwProvisioner(BwProvisioner bwProvisioner) { this.bwProvisioner = bwProvisioner; } /** * Gets the VM scheduler. * * @return the VM scheduler */ public VmScheduler getVmScheduler() { return vmScheduler; } /** * Sets the VM scheduler. * * @param vmScheduler the vm scheduler */ protected void setVmScheduler(VmScheduler vmScheduler) { this.vmScheduler = vmScheduler; } /** * Gets the pe list. * * @param <T> the generic type * @return the pe list */ @SuppressWarnings("unchecked") public <T extends Pe> List<T> getPeList() { return (List<T>) peList; } /** * Sets the pe list. * * @param <T> the generic type * @param peList the new pe list */ protected <T extends Pe> void setPeList(List<T> peList) { this.peList = peList; } /** * Gets the vm list. * * @param <T> the generic type * @return the vm list */ @SuppressWarnings("unchecked") public <T extends Vm> List<T> getVmList() { return (List<T>) vmList; } /** * Sets the storage. * * @param storage the new storage */ protected void setStorage(long storage) { this.storage = storage; } /** * Checks if the host PEs have failed. * * @return true, if the host PEs have failed; false otherwise */ public boolean isFailed() { return failed; } /** * Sets the PEs of the host to a FAILED status. NOTE: <tt>resName</tt> is used for debugging * purposes, which is <b>ON</b> by default. Use {@link #setFailed(boolean)} if you do not want * this information. * * @param resName the name of the resource * @param failed the failed * @return <tt>true</tt> if successful, <tt>false</tt> otherwise */ public boolean setFailed(String resName, boolean failed) { // all the PEs are failed (or recovered, depending on fail) this.failed = failed; PeList.setStatusFailed(getPeList(), resName, getId(), failed); return true; } /** * Sets the PEs of the host to a FAILED status. * * @param failed the failed * @return <tt>true</tt> if successful, <tt>false</tt> otherwise */ public boolean setFailed(boolean failed) { // all the PEs are failed (or recovered, depending on fail) this.failed = failed; PeList.setStatusFailed(getPeList(), failed); return true; } /** * Sets the particular Pe status on the host. * * @param peId the pe id * @param status Pe status, either <tt>Pe.FREE</tt> or <tt>Pe.BUSY</tt> * @return <tt>true</tt> if the Pe status has changed, <tt>false</tt> otherwise (Pe id might not * be exist) * @pre peID >= 0 * @post $none */ public boolean setPeStatus(int peId, int status) { return PeList.setPeStatus(getPeList(), peId, status); } /** * Gets the vms migrating in. * * @return the vms migrating in */ public List<Vm> getVmsMigratingIn() { return vmsMigratingIn; } /** * Gets the data center of the host. * * @return the data center where the host runs */ public Datacenter getDatacenter() { return datacenter; } /** * Sets the data center of the host. * * @param datacenter the data center from this host */ public void setDatacenter(Datacenter datacenter) { this.datacenter = datacenter; } }
package org.meteogroup.griblibrary.grib2.gdstemplates; import org.meteogroup.griblibrary.exception.BinaryNumberConversionException; import org.meteogroup.griblibrary.grib2.model.gdstemplates.GDSTemplate; import org.meteogroup.griblibrary.grib2.model.gdstemplates.GaussianGDSTemplate; import org.meteogroup.griblibrary.util.BytesToPrimitiveHelper; public class GaussianTemplateReader implements GridTemplateReader{ private static final int POSITION_SHAPE_OF_EARTH = 14; private static final int POSITION_SCALE_FACTOR_RADIUS_SPHERICALEARTH = 15; private static final int POSITION_SCALE_VALUE_RADIUS_SPHERICALEARTH_1 = 16; private static final int POSITION_SCALE_VALUE_RADIUS_SPHERICALEARTH_2 = 17; private static final int POSITION_SCALE_VALUE_RADIUS_SPHERICALEARTH_3 = 18; private static final int POSITION_SCALE_VALUE_RADIUS_SPHERICALEARTH_4 = 19; private static final int POSITION_SCALE_FACTORMAJOR_AXIS_SPHERICALEARTH = 20; private static final int POSITION_SCALE_VALUE_MAJOR_AXIS_SPHERICALEARTH_1 = 21; private static final int POSITION_SCALE_VALUE_MAJOR_AXIS_SPHERICALEARTH_2 = 22; private static final int POSITION_SCALE_VALUE_MAJOR_AXIS_SPHERICALEARTH_3 = 23; private static final int POSITION_SCALE_VALUE_MAJOR_AXIS_SPHERICALEARTH_4 = 24; private static final int POSITION_SCALE_FACTORMINOR_AXIS_SPHERICALEARTH = 25; private static final int POSITION_SCALE_VALUE_MINOR_AXIS_SPHERICALEARTH_1 = 26; private static final int POSITION_SCALE_VALUE_MINOR_AXIS_SPHERICALEARTH_2 = 27; private static final int POSITION_SCALE_VALUE_MINOR_AXIS_SPHERICALEARTH_3 = 28; private static final int POSITION_SCALE_VALUE_MINOR_AXIS_SPHERICALEARTH_4 = 29; private static final int POSITION_NI_1 = 30; private static final int POSITION_NI_2 = 31; private static final int POSITION_NI_3 = 32; private static final int POSITION_NI_4 = 33; private static final int POSITION_NJ_1 = 34; private static final int POSITION_NJ_2 = 35; private static final int POSITION_NJ_3 = 36; private static final int POSITION_NJ_4 = 37; private static final int POSITION_ANGLE_INIT_PROD_DOM_1 = 38; private static final int POSITION_ANGLE_INIT_PROD_DOM_2 = 39; private static final int POSITION_ANGLE_INIT_PROD_DOM_3 = 40; private static final int POSITION_ANGLE_INIT_PROD_DOM_4 = 41; private static final int POSITION_ANGLE_SUBDIVISIONS_1 = 42; private static final int POSITION_ANGLE_SUBDIVISIONS_2 = 43; private static final int POSITION_ANGLE_SUBDIVISIONS_3 = 44; private static final int POSITION_ANGLE_SUBDIVISIONS_4 = 45; private static final int POSITION_LA1_1 = 46; private static final int POSITION_LA1_2 = 47; private static final int POSITION_LA1_3 = 48; private static final int POSITION_LA1_4 = 49; private static final int POSITION_LO1_1 = 50; private static final int POSITION_LO1_2 = 51; private static final int POSITION_LO1_3 = 52; private static final int POSITION_LO1_4 = 53; private static final int POSITION_RESOLUTION_COMPONENT_FLAGS = 54; private static final int POSITION_LA2_1 = 55; private static final int POSITION_LA2_2 = 56; private static final int POSITION_LA2_3 = 57; private static final int POSITION_LA2_4 = 58; private static final int POSITION_LO2_1 = 59; private static final int POSITION_LO2_2 = 60; private static final int POSITION_LO2_3 = 61; private static final int POSITION_LO2_4 = 62; private static final int POSITION_DIRECTION_INCREMENT_1 = 63; private static final int POSITION_DIRECTION_INCREMENT_2 = 64; private static final int POSITION_DIRECTION_INCREMENT_3 = 65; private static final int POSITION_DIRECTION_INCREMENT_4 = 66; private static final int POSITION_NUMBER_OF_PARALLELS_1 = 67; private static final int POSITION_NUMBER_OF_PARALLELS_2 = 68; private static final int POSITION_NUMBER_OF_PARALLELS_3 = 69; private static final int POSITION_NUMBER_OF_PARALLELS_4 = 70; private static final int POSITION_SCANNING_MODE_FLAGS = 71; private static final int POSITION_START_POINTS_PER_PARALLEL = 72; protected int readShapeOfEarth(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return gdsValues[POSITION_SHAPE_OF_EARTH + headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK; } protected int readScaleFactorRadiusEarth(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return gdsValues[POSITION_SCALE_FACTOR_RADIUS_SPHERICALEARTH + headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK; } protected int readScaleValueRadiusEarth(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.bytesToInteger(gdsValues[POSITION_SCALE_VALUE_RADIUS_SPHERICALEARTH_1 + headerOffSet], gdsValues[POSITION_SCALE_VALUE_RADIUS_SPHERICALEARTH_2 + headerOffSet], gdsValues[POSITION_SCALE_VALUE_RADIUS_SPHERICALEARTH_3 + headerOffSet], gdsValues[POSITION_SCALE_VALUE_RADIUS_SPHERICALEARTH_4 + headerOffSet]); } protected int readScaleFactorMajorAxisEarth(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return gdsValues[POSITION_SCALE_FACTORMAJOR_AXIS_SPHERICALEARTH + headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK; } protected int readScaleValueMajorAxisEarth(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.bytesToInteger(gdsValues[POSITION_SCALE_VALUE_MAJOR_AXIS_SPHERICALEARTH_1 + headerOffSet], gdsValues[POSITION_SCALE_VALUE_MAJOR_AXIS_SPHERICALEARTH_2 + headerOffSet], gdsValues[POSITION_SCALE_VALUE_MAJOR_AXIS_SPHERICALEARTH_3 + headerOffSet], gdsValues[POSITION_SCALE_VALUE_MAJOR_AXIS_SPHERICALEARTH_4 + headerOffSet]); } protected int readScaleFactorMinorAxisEarth(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return gdsValues[POSITION_SCALE_FACTORMINOR_AXIS_SPHERICALEARTH + headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK; } protected int readScaleValueMinorAxisEarth(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.bytesToInteger(gdsValues[POSITION_SCALE_VALUE_MINOR_AXIS_SPHERICALEARTH_1 + headerOffSet], gdsValues[POSITION_SCALE_VALUE_MINOR_AXIS_SPHERICALEARTH_2 + headerOffSet], gdsValues[POSITION_SCALE_VALUE_MINOR_AXIS_SPHERICALEARTH_3 + headerOffSet], gdsValues[POSITION_SCALE_VALUE_MINOR_AXIS_SPHERICALEARTH_4 + headerOffSet]); } protected int readNi(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.bytesToInteger(gdsValues[POSITION_NI_1 + headerOffSet], gdsValues[POSITION_NI_2 + headerOffSet], gdsValues[POSITION_NI_3 + headerOffSet], gdsValues[POSITION_NI_4 + headerOffSet]); } protected int readNj(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.bytesToInteger(gdsValues[POSITION_NJ_1 + headerOffSet], gdsValues[POSITION_NJ_2 + headerOffSet], gdsValues[POSITION_NJ_3 + headerOffSet], gdsValues[POSITION_NJ_4 + headerOffSet]); } protected float readLa1(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.bytesToInteger( gdsValues[POSITION_LA1_1 + headerOffSet], gdsValues[POSITION_LA1_2 + headerOffSet], gdsValues[POSITION_LA1_3 + headerOffSet], gdsValues[POSITION_LA1_4 + headerOffSet]) / 1000000f; } protected float readLo1(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.bytesToInteger( gdsValues[POSITION_LO1_1 + headerOffSet], gdsValues[POSITION_LO1_2 + headerOffSet], gdsValues[POSITION_LO1_3 + headerOffSet], gdsValues[POSITION_LO1_4 + headerOffSet]) / 1000000f; } protected float readLa2(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.signedBytesToInt( gdsValues[POSITION_LA2_1 + headerOffSet], gdsValues[POSITION_LA2_2 + headerOffSet], gdsValues[POSITION_LA2_3 + headerOffSet], gdsValues[POSITION_LA2_4 + headerOffSet]) / 1000000f; } protected float readLo2(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.bytesToInteger( gdsValues[POSITION_LO2_1 + headerOffSet], gdsValues[POSITION_LO2_2 + headerOffSet], gdsValues[POSITION_LO2_3 + headerOffSet], gdsValues[POSITION_LO2_4 + headerOffSet]) / 1000000f; } protected float readDirectionIncrement(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { // Di return BytesToPrimitiveHelper.bytesToInteger( gdsValues[POSITION_DIRECTION_INCREMENT_1 + headerOffSet], gdsValues[POSITION_DIRECTION_INCREMENT_2 + headerOffSet], gdsValues[POSITION_DIRECTION_INCREMENT_3 + headerOffSet], gdsValues[POSITION_DIRECTION_INCREMENT_4 + headerOffSet]) / 1000000f; } protected int readNumberOfParallelsPoleEquator(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.bytesToInteger( gdsValues[POSITION_NUMBER_OF_PARALLELS_1 + headerOffSet], gdsValues[POSITION_NUMBER_OF_PARALLELS_2 + headerOffSet], gdsValues[POSITION_NUMBER_OF_PARALLELS_3 + headerOffSet], gdsValues[POSITION_NUMBER_OF_PARALLELS_4 + headerOffSet]); } protected int[] readNumberOfPointsPerParallel(byte[] gdsValues, int headerOffSet, int numberOfParallels) throws BinaryNumberConversionException { int[] pointsPerParallel = new int[numberOfParallels]; for (int i = 0; i < numberOfParallels; i++){ pointsPerParallel[i] = BytesToPrimitiveHelper.bytesToInteger( gdsValues[POSITION_START_POINTS_PER_PARALLEL + (2 * i) + headerOffSet], gdsValues[POSITION_START_POINTS_PER_PARALLEL + (2 * i) + 1 + headerOffSet]); } return pointsPerParallel; } @Override public GaussianGDSTemplate readTemplate(byte[] gdsValues, int headerOffSet) throws BinaryNumberConversionException { GaussianGDSTemplate gaussianTemplate = new GaussianGDSTemplate(); gaussianTemplate.setShapeOfEarth(readShapeOfEarth(gdsValues, headerOffSet)); gaussianTemplate.setScaleFactorRadiusEarth(readScaleFactorRadiusEarth(gdsValues, headerOffSet)); gaussianTemplate.setScaleValueRadiusEarth(readScaleValueRadiusEarth(gdsValues, headerOffSet)); gaussianTemplate.setScaleFactorMajorAxisOblateSphericalEarth(readScaleFactorMajorAxisEarth(gdsValues, headerOffSet)); gaussianTemplate.setScaledValueMajorAxisOblateSphericalEarth(readScaleValueMajorAxisEarth(gdsValues, headerOffSet)); gaussianTemplate.setScaleFactorMinorAxisOblateSphericalEarth(readScaleFactorMinorAxisEarth(gdsValues, headerOffSet)); gaussianTemplate.setScaledValueMinorAxisOblateSphericalEarth(readScaleValueMinorAxisEarth(gdsValues, headerOffSet)); // TODO Handle Basic angle of the initial production domain // TODO Handle Subdivisions of basic angle gaussianTemplate.setNi(readNi(gdsValues, headerOffSet)); gaussianTemplate.setNj(readNj(gdsValues, headerOffSet)); gaussianTemplate.setLa1(readLa1(gdsValues, headerOffSet)); gaussianTemplate.setLo1(readLo1(gdsValues, headerOffSet)); gaussianTemplate.setLa2(readLa2(gdsValues, headerOffSet)); gaussianTemplate.setLo2(readLo2(gdsValues, headerOffSet)); gaussianTemplate.setDiDirectionIncrement(readDirectionIncrement(gdsValues, headerOffSet)); gaussianTemplate.setNumberOfParallelsBetweenPoleAndEquator(readNumberOfParallelsPoleEquator(gdsValues, headerOffSet)); // TODO Handle Resolution and component flags // TODO Add condition for missing NumberOfPointsAlongParallel gaussianTemplate.setNumberOfPointsAlongParallel( readNumberOfPointsPerParallel(gdsValues, headerOffSet, gaussianTemplate.getNumberOfParallelsBetweenPoleAndEquator() * 2)); // TODO Handle Scanning Mode flags return gaussianTemplate; } }
/* * Copyright 2014 PRISMA by MIUR * * 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 it.prisma.presentationlayer.webui.datavalidation.forms.paas; import it.prisma.utils.validation.RegularExpressionList; import java.io.Serializable; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email; /** * * @author <a href="mailto:m.bassi@reply.it">Matteo Bassi</a> * @version 0.1.0 * @since 0.1.0 * @see <a * href="http://www.istc.cnr.it/project/prisma-piattaforme-cloud-interoperabili-smart-government">Progetto * PRISMA</a> */ public class EnvForm implements Serializable { private static final long serialVersionUID = 6400126423611738676L; /*--------------------------------------------------*/ /*--------- CONFIGURAZIONE GENERALE -------------*/ /*--------------------------------------------------*/ @Size(min = 4, max = 30) @Pattern(regexp = RegularExpressionList.ALPHANUMERIC_HYPHEN_PATTERN) private String serviceName; @Size(min = 4, max = 200) private String description; private String url; private String domainName; private String publicip; private String secureConnection; @Email private String notificationEmail; /*------------------------------------------------------*/ /*--------- Configurazione del Servizio -------------*/ /*------------------------------------------------------*/ private String zoneSelect; private String qosSelect; private String flavorSelect; @NotNull private String serverType; @NotNull private String serverName; private String scalingSelect; /*------------------------------------------------*/ /*------------ SELZIONA SORGENTE --------------*/ /*------------------------------------------------*/ @NotNull private String source; private String sourceLabel; private String appVisibility; private Long fileuploadId; private String urlStorage; private String sourceLabelPRISMA; private String appVisibilityPRISMA; private Long fileURLId; private Long inputPrivateId; private Long inputPublicId; public Long getFileuploadId() { return fileuploadId; } public void setFileuploadId(Long fileuploadId) { this.fileuploadId = fileuploadId; } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public String getDescription() { return description; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDomainName() { return domainName; } public void setDomainName(String domainName) { this.domainName = domainName; } public void setDescription(String description) { this.description = description; } public String getPublicip() { return publicip; } public void setPublicip(String publicip) { this.publicip = publicip; } public String getSecureConnection() { return secureConnection; } public void setSecureConnection(String secureConnection) { this.secureConnection = secureConnection; } public String getNotificationEmail() { return notificationEmail; } public void setNotificationEmail(String notificationEmail) { this.notificationEmail = notificationEmail; } public String getZoneSelect() { return zoneSelect; } public void setZoneSelect(String zoneSelect) { this.zoneSelect = zoneSelect; } public String getQosSelect() { return qosSelect; } public void setQosSelect(String qosSelect) { this.qosSelect = qosSelect; } public String getFlavorSelect() { return flavorSelect; } public void setFlavorSelect(String flavorSelect) { this.flavorSelect = flavorSelect; } public String getServerType() { return serverType; } public void setServerType(String serverType) { this.serverType = serverType; } public String getServerName() { return serverName; } public void setServerName(String serverName) { this.serverName = serverName; } public String getScalingSelect() { return scalingSelect; } public void setScalingSelect(String scalingSelect) { this.scalingSelect = scalingSelect; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getSourceLabel() { return sourceLabel; } public void setSourceLabel(String sourceLabel) { this.sourceLabel = sourceLabel; } public String getAppVisibility() { return appVisibility; } public void setAppVisibility(String appVisibility) { this.appVisibility = appVisibility; } public String getUrlStorage() { return urlStorage; } public void setUrlStorage(String urlStorage) { this.urlStorage = urlStorage; } public String getSourceLabelPRISMA() { return sourceLabelPRISMA; } public void setSourceLabelPRISMA(String sourceLabelPRISMA) { this.sourceLabelPRISMA = sourceLabelPRISMA; } public String getAppVisibilityPRISMA() { return appVisibilityPRISMA; } public void setAppVisibilityPRISMA(String appVisibilityPRISMA) { this.appVisibilityPRISMA = appVisibilityPRISMA; } public Long getFileURLId() { return fileURLId; } public void setFileURLId(Long fileURLId) { this.fileURLId = fileURLId; } public Long getInputPublicId() { return inputPublicId; } public void setInputPublicId(Long inputPublicId) { this.inputPublicId = inputPublicId; } public Long getInputPrivateId() { return inputPrivateId; } public void setInputPrivateId(Long inputPrivateId) { this.inputPrivateId = inputPrivateId; } }
package io.github.droidkaigi.confsched.activity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.widget.LinearLayoutManager; import android.text.Editable; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.TextWatcher; import android.text.style.TextAppearanceSpan; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import org.parceler.Parcels; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import io.github.droidkaigi.confsched.R; import io.github.droidkaigi.confsched.dao.CategoryDao; import io.github.droidkaigi.confsched.dao.PlaceDao; import io.github.droidkaigi.confsched.dao.SessionDao; import io.github.droidkaigi.confsched.databinding.ActivitySearchBinding; import io.github.droidkaigi.confsched.databinding.ItemSearchResultBinding; import io.github.droidkaigi.confsched.model.SearchResult; import io.github.droidkaigi.confsched.model.Session; import io.github.droidkaigi.confsched.util.AnalyticsTracker; import io.github.droidkaigi.confsched.util.LocaleUtil; import io.github.droidkaigi.confsched.widget.ArrayRecyclerAdapter; import io.github.droidkaigi.confsched.widget.BindingHolder; import io.github.droidkaigi.confsched.widget.itemdecoration.DividerItemDecoration; import rx.Observable; public class SearchActivity extends BaseActivity implements TextWatcher { public static final String RESULT_STATUS_CHANGED_SESSIONS = "statusChangedSessions"; private static final int REQ_DETAIL = 1; private static final int REQ_SEARCH_PLACES_AND_CATEGORIES_VIEW = 2; @Inject AnalyticsTracker analyticsTracker; @Inject ActivityNavigator activityNavigator; @Inject SessionDao sessionDao; @Inject PlaceDao placeDao; @Inject CategoryDao categoryDao; List<Session> statusChangedSessions = new ArrayList<>(); private SearchResultsAdapter adapter; private ActivitySearchBinding binding; static void start(@NonNull Fragment fragment, int requestCode) { Intent intent = new Intent(fragment.getContext(), SearchActivity.class); fragment.startActivityForResult(intent, requestCode); fragment.getActivity().overridePendingTransition(0, R.anim.activity_fade_exit); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_search); getComponent().inject(this); initToolbar(); initRecyclerView(); initPlacesAndCategoriesView(); loadData(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(RESULT_STATUS_CHANGED_SESSIONS, Parcels.wrap(statusChangedSessions)); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); statusChangedSessions = Parcels.unwrap(savedInstanceState.getParcelable(RESULT_STATUS_CHANGED_SESSIONS)); } private void initPlacesAndCategoriesView() { binding.searchPlacesAndCategoriesView.addPlaces(placeDao.findAll()); binding.searchPlacesAndCategoriesView.addCategories(categoryDao.findAll()); binding.searchPlacesAndCategoriesView.setOnClickSearchGroup(searchGroup -> startActivityForResult(SearchedSessionsActivity.createIntent(SearchActivity.this, searchGroup), REQ_SEARCH_PLACES_AND_CATEGORIES_VIEW)); } @Override protected void onStart() { super.onStart(); analyticsTracker.sendScreenView("search"); } private void initToolbar() { setSupportActionBar(binding.searchToolbar.getToolbar()); ActionBar bar = getSupportActionBar(); if (bar != null) { bar.setDisplayHomeAsUpEnabled(true); bar.setDisplayShowHomeEnabled(true); bar.setDisplayShowTitleEnabled(false); bar.setHomeButtonEnabled(true); } binding.searchToolbar.addTextChangedListener(this); } private void initRecyclerView() { adapter = new SearchResultsAdapter(this); binding.recyclerView.setAdapter(adapter); binding.recyclerView.addItemDecoration(new DividerItemDecoration(this)); binding.recyclerView.setLayoutManager(new LinearLayoutManager(this)); } private void loadData() { // TODO It's waste logic... List<Session> sessions = sessionDao.findAll().toBlocking().single(); List<SearchResult> titleResults = Observable.from(sessions) .map(SearchResult::createTitleType) .toList().toBlocking().single(); List<SearchResult> descriptionResults = Observable.from(sessions) .map(SearchResult::createDescriptionType) .toList().toBlocking().single(); List<SearchResult> speakerResults = Observable.from(sessions) .map(SearchResult::createSpeakerType) .toList().toBlocking().single(); titleResults.addAll(descriptionResults); titleResults.addAll(speakerResults); adapter.setAllList(titleResults); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return super.onOptionsItemSelected(item); } @Override public void finish() { Intent intent = new Intent(); intent.putExtra(RESULT_STATUS_CHANGED_SESSIONS, Parcels.wrap(statusChangedSessions)); setResult(Activity.RESULT_OK, intent); overridePendingTransition(0, R.anim.activity_fade_exit); super.finish(); } @Override public void onBackPressed() { finish(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.getFilter().filter(s); } @Override public void afterTextChanged(Editable s) { if (TextUtils.isEmpty(s)) { binding.searchPlacesAndCategoriesView.setVisibility(View.VISIBLE); binding.recyclerView.setVisibility(View.GONE); } else { binding.searchPlacesAndCategoriesView.setVisibility(View.GONE); binding.recyclerView.setVisibility(View.VISIBLE); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_DETAIL: { if (resultCode != Activity.RESULT_OK) { return; } Session session = Parcels.unwrap(data.getParcelableExtra(Session.class.getSimpleName())); statusChangedSessions.add(session); break; } case REQ_SEARCH_PLACES_AND_CATEGORIES_VIEW: { if (resultCode != Activity.RESULT_OK) { return; } List<Session> sessions = Parcels.unwrap(data.getParcelableExtra(RESULT_STATUS_CHANGED_SESSIONS)); statusChangedSessions.addAll(sessions); break; } } } private class SearchResultsAdapter extends ArrayRecyclerAdapter<SearchResult, BindingHolder<ItemSearchResultBinding>> implements Filterable { private static final String ELLIPSIZE_TEXT = "..."; private static final int ELLIPSIZE_LIMIT_COUNT = 30; private TextAppearanceSpan textAppearanceSpan; private List<SearchResult> filteredList; private List<SearchResult> allList; public SearchResultsAdapter(@NonNull Context context) { super(context); this.filteredList = new ArrayList<>(); this.textAppearanceSpan = new TextAppearanceSpan(context, R.style.SearchResultAppearance); } public void setAllList(List<SearchResult> searchResults) { this.allList = searchResults; } @Override public BindingHolder<ItemSearchResultBinding> onCreateViewHolder(ViewGroup parent, int viewType) { return new BindingHolder<>(getContext(), parent, R.layout.item_search_result); } @Override public void onBindViewHolder(BindingHolder<ItemSearchResultBinding> holder, int position) { SearchResult searchResult = getItem(position); ItemSearchResultBinding itemBinding = holder.binding; itemBinding.setSearchResult(searchResult); Drawable icon = ContextCompat.getDrawable(getContext(), searchResult.iconRes); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { itemBinding.txtType.setCompoundDrawablesRelativeWithIntrinsicBounds(icon, null, null, null); } else if (LocaleUtil.shouldRtl()) { itemBinding.txtType.setCompoundDrawablesWithIntrinsicBounds(null, null, icon, null); } else { itemBinding.txtType.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); } bindText(itemBinding.txtSearchResult, searchResult, binding.searchToolbar.getText()); itemBinding.getRoot().setOnClickListener(v -> activityNavigator.showSessionDetail(SearchActivity.this, searchResult.session, REQ_DETAIL)); } private void bindText(TextView textView, SearchResult searchResult, String searchText) { String text = searchResult.text; if (TextUtils.isEmpty(text)) return; text = text.replace("\n", " "); if (TextUtils.isEmpty(searchText)) { textView.setText(text); } else { int idx = text.toLowerCase().indexOf(searchText.toLowerCase()); if (idx >= 0) { SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append(text); builder.setSpan( textAppearanceSpan, idx, idx + searchText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ); if (idx > ELLIPSIZE_LIMIT_COUNT && searchResult.isDescriptionType()) { builder.delete(0, idx - ELLIPSIZE_LIMIT_COUNT); builder.insert(0, ELLIPSIZE_TEXT); } textView.setText(builder); } else { textView.setText(text); } } } @Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { filteredList.clear(); FilterResults results = new FilterResults(); if (constraint.length() > 0) { final String filterPattern = constraint.toString().toLowerCase().trim(); Observable.from(allList) .filter(searchResult -> searchResult.text.toLowerCase().contains(filterPattern)) .forEach(filteredList::add); } results.values = filteredList; results.count = filteredList.size(); return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { clear(); addAll((List<SearchResult>) results.values); notifyDataSetChanged(); } }; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.ignite.internal.processors.query.h2.sql; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.Reader; import java.io.Serializable; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.affinity.AffinityKey; import org.apache.ignite.cache.query.SqlFieldsQuery; import org.apache.ignite.cache.query.annotations.QuerySqlField; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.util.typedef.X; /** * Executes one big query (and subqueries of the big query) to compare query results from h2 database instance and * mixed ignite caches (replicated and partitioned) which have the same data models and data content. * * * <pre> * * -------------------------------------> rootOrderId (virtual) <-------------------------- * | | | * | | | * | --------------------- | | * | ------------------ --part.ReplaceOrder-- | | * | --part.CustOrder-- --------------------- | | * | ------------------ - id PK - | | * | - orderId PK - <-- <---> - orderId - | | * -- - rootOrderId - | - rootOrderId - ----------- | * - origOrderId - | - refOrderId - // = origOrderId | * - date - | - date - | * - alias - | - alias - | * - archSeq - | - archSeq - ------------------- | * ------------------ | --------------------- ----part.Exec------ | * | ------------------- | * ----------------- | - rootOrderId PK - ---- * ---part.Cancel--- | - date - * ----------------- | --------------------- - execShares int - * - id PK - | --part.OrderParams--- - price int - * - refOrderId - ---| --------------------- - lastMkt int - * - date - | - id PK - ------------------- * ----------------- ------- - orderId - * - date - * - parentAlgo - * --------------------- * </pre> * */ public class H2CompareBigQueryTest extends AbstractH2CompareQueryTest { /** Root order count. */ private static final int ROOT_ORDER_CNT = 1000; /** Dates count. */ private static final int DATES_CNT = 5; /** Full the big query. */ private String bigQry = getBigQry(); /** Cache cust ord. */ private static IgniteCache<Integer, CustOrder> cacheCustOrd; /** Cache repl ord. */ private static IgniteCache<Object, ReplaceOrder> cacheReplOrd; /** Cache ord parameter. */ private static IgniteCache<Object, OrderParams> cacheOrdParam; /** Cache cancel. */ private static IgniteCache<Object, Cancel> cacheCancel; /** Cache execute. */ private static IgniteCache<Object, Exec> cacheExec; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); cfg.setCacheConfiguration( cacheConfiguration("custord", CacheMode.PARTITIONED, Integer.class, CustOrder.class), cacheConfiguration("replord", CacheMode.PARTITIONED, useColocatedData() ? AffinityKey.class : Integer.class, ReplaceOrder.class), cacheConfiguration("ordparam", CacheMode.PARTITIONED, useColocatedData() ? AffinityKey.class : Integer.class, OrderParams.class), cacheConfiguration("cancel", CacheMode.PARTITIONED, useColocatedData() ? AffinityKey.class : Integer.class, Cancel.class), cacheConfiguration("exec", CacheMode.REPLICATED, useColocatedData() ? AffinityKey.class : Integer.class, Exec.class)); return cfg; } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { super.afterTestsStopped(); cacheCustOrd = null; cacheReplOrd = null; cacheOrdParam = null; cacheCancel = null; cacheExec = null; } /** * Extracts the big query from file. * * @return Big query. */ private String getBigQry() { String res = ""; Reader isr = new InputStreamReader(getClass().getResourceAsStream("bigQuery.sql")); try(BufferedReader reader = new BufferedReader(isr)) { for(String line; (line = reader.readLine()) != null; ) if (!line.startsWith("--")) // Skip commented lines. res += line + '\n'; } catch (Throwable e) { e.printStackTrace(); fail(); } return res; } /** * @return Use colocated data. */ private boolean useColocatedData() { return !distributedJoins(); } /** * @return Whehter to use distrubutedJoins or not. */ protected boolean distributedJoins() { return false; } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void createCaches() { cacheCustOrd = ignite.cache("custord"); cacheReplOrd = ignite.cache("replord"); cacheOrdParam = ignite.cache("ordparam"); cacheCancel = ignite.cache("cancel"); cacheExec = ignite.cache("exec"); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void initCacheAndDbData() throws SQLException { final AtomicInteger idGen = new AtomicInteger(); final Iterable<Integer> rootOrderIds = new ArrayList<Integer>(){{ for (int i = 0; i < ROOT_ORDER_CNT; i++) add(idGen.incrementAndGet()); }}; final Date curDate = new Date(new java.util.Date().getTime()); final List<Date> dates = new ArrayList<Date>(){{ for (int i = 0; i < DATES_CNT; i++) add(new Date(curDate.getTime() - i * 24 * 60 * 60 * 1000)); // Minus i days. }}; final Iterable<CustOrder> orders = new ArrayList<CustOrder>(){{ for (int rootOrderId : rootOrderIds) { // Generate 1 - 5 orders for 1 root order. for (int i = 0; i < rootOrderId % 5; i++) { int orderId = idGen.incrementAndGet(); CustOrder order = new CustOrder(orderId, rootOrderId, dates.get(orderId % dates.size()) , orderId % 2 == 0 ? "CUSTOM" : "OTHER", orderId); add(order); cacheCustOrd.put(order.orderId, order); insertInDb(order); } } }}; final Collection<OrderParams> params = new ArrayList<OrderParams>(){{ for (CustOrder o : orders) { OrderParams op = new OrderParams(idGen.incrementAndGet(), o.orderId, o.date, o.orderId % 2 == 0 ? "Algo 1" : "Algo 2"); add(op); cacheOrdParam.put(op.key(useColocatedData()), op); insertInDb(op); } }}; final Collection<ReplaceOrder> replaces = new ArrayList<ReplaceOrder>(){{ for (CustOrder o : orders) { if (o.orderId % 7 == 0) { ReplaceOrder replace = new ReplaceOrder(idGen.incrementAndGet(), o.orderId, o.rootOrderId, o.alias, new Date(o.date.getTime() + 12 * 60 * 60 * 1000), o.orderId); // Plus a half of day. add(replace); cacheReplOrd.put(replace.key(useColocatedData()), replace); insertInDb(replace); } } }}; final Collection<Cancel> cancels = new ArrayList<Cancel>(){{ for (CustOrder o : orders) { if (o.orderId % 9 == 0) { Cancel c = new Cancel(idGen.incrementAndGet(), o.orderId, new Date(o.date.getTime() + 12 * 60 * 60 * 1000));// Plus a half of day. add(c); cacheCancel.put(c.key(useColocatedData()), c); insertInDb(c); } } }}; final Collection<Exec> execs = new ArrayList<Exec>(){{ for (int rootOrderId : rootOrderIds) { int execShares = 10000 + rootOrderId; int price = 1000 + rootOrderId; int latsMkt = 3000 + rootOrderId; Exec exec = new Exec(idGen.incrementAndGet(), rootOrderId, dates.get(rootOrderId % dates.size()), execShares, price, latsMkt); add(exec); cacheExec.put(exec.key(useColocatedData()), exec); insertInDb(exec); } }}; } /** * @throws Exception If failed. */ @Override protected void checkAllDataEquals() throws Exception { compareQueryRes0(cacheCustOrd, "select _key, _val, date, orderId, rootOrderId, alias, archSeq, origOrderId " + "from \"custord\".CustOrder"); compareQueryRes0(cacheReplOrd, "select _key, _val, id, date, orderId, rootOrderId, alias, archSeq, refOrderId " + "from \"replord\".ReplaceOrder"); compareQueryRes0(cacheOrdParam, "select _key, _val, id, date, orderId, parentAlgo from \"ordparam\".OrderParams\n"); compareQueryRes0(cacheCancel, "select _key, _val, id, date, refOrderId from \"cancel\".Cancel\n"); compareQueryRes0(cacheExec, "select _key, _val, date, rootOrderId, execShares, price, lastMkt from \"exec\".Exec\n"); } /** * @throws Exception If failed. */ public void testBigQuery() throws Exception { X.println(); X.println(bigQry); X.println(); X.println(" Plan: \n" + cacheCustOrd.query(new SqlFieldsQuery("EXPLAIN " + bigQry) .setDistributedJoins(distributedJoins())).getAll()); List<List<?>> res = compareQueryRes0(cacheCustOrd, bigQry, distributedJoins(), new Object[0], Ordering.RANDOM); X.println(" Result size: " + res.size()); assertTrue(!res.isEmpty()); // Ensure we set good testing data at database. } /** {@inheritDoc} */ @Override protected Statement initializeH2Schema() throws SQLException { Statement st = super.initializeH2Schema(); st.execute("CREATE SCHEMA \"custord\""); st.execute("CREATE SCHEMA \"replord\""); st.execute("CREATE SCHEMA \"ordparam\""); st.execute("CREATE SCHEMA \"cancel\""); st.execute("CREATE SCHEMA \"exec\""); final String keyType = useColocatedData() ? "other" : "int"; st.execute("create table \"custord\".CustOrder" + " (" + " _key int not null," + " _val other not null," + " orderId int unique," + " rootOrderId int," + " origOrderId int," + " archSeq int," + " date Date, " + " alias varchar(255)" + " )"); st.execute("create table \"replord\".ReplaceOrder" + " (" + " _key " + keyType + " not null," + " _val other not null," + " id int unique," + " orderId int ," + " rootOrderId int," + " refOrderId int," + " archSeq int," + " date Date, " + " alias varchar(255)" + " )"); st.execute("create table \"ordparam\".OrderParams" + " (" + " _key " + keyType + " not null," + " _val other not null," + " id int unique," + " orderId int ," + " date Date, " + " parentAlgo varchar(255)" + " )"); st.execute("create table \"cancel\".Cancel" + " (" + " _key " + keyType + " not null," + " _val other not null," + " id int unique," + " date Date, " + " refOrderId int" + " )"); st.execute("create table \"exec\".Exec" + " (" + " _key " + keyType + " not null," + " _val other not null," + " rootOrderId int unique," + " date Date, " + " execShares int," + " price int," + " lastMkt int" + " )"); conn.commit(); return st; } /** * Insert {@link CustOrder} at h2 database. * * @param o CustOrder. */ private void insertInDb(CustOrder o) throws SQLException { try(PreparedStatement st = conn.prepareStatement( "insert into \"custord\".CustOrder (_key, _val, orderId, rootOrderId, date, alias, archSeq, origOrderId) " + "values(?, ?, ?, ?, ?, ?, ?, ?)")) { int i = 0; st.setObject(++i, o.orderId); st.setObject(++i, o); st.setObject(++i, o.orderId); st.setObject(++i, o.rootOrderId); st.setObject(++i, o.date); st.setObject(++i, o.alias); st.setObject(++i, o.archSeq); st.setObject(++i, o.origOrderId); st.executeUpdate(); } } /** * Insert {@link ReplaceOrder} at h2 database. * * @param o ReplaceOrder. */ private void insertInDb(ReplaceOrder o) throws SQLException { try(PreparedStatement st = conn.prepareStatement( "insert into \"replord\".ReplaceOrder (_key, _val, id, orderId, rootOrderId, date, alias, archSeq, refOrderId) " + "values(?, ?, ?, ?, ?, ?, ?, ?, ?)")) { int i = 0; st.setObject(++i, o.key(useColocatedData())); st.setObject(++i, o); st.setObject(++i, o.id); st.setObject(++i, o.orderId); st.setObject(++i, o.rootOrderId); st.setObject(++i, o.date); st.setObject(++i, o.alias); st.setObject(++i, o.archSeq); st.setObject(++i, o.refOrderId); st.executeUpdate(); } } /** * Insert {@link OrderParams} at h2 database. * * @param o OrderParams. */ private void insertInDb(OrderParams o) throws SQLException { try(PreparedStatement st = conn.prepareStatement( "insert into \"ordparam\".OrderParams (_key, _val, id, date, orderId, parentAlgo) values(?, ?, ?, ?, ?, ?)")) { int i = 0; st.setObject(++i, o.key(useColocatedData())); st.setObject(++i, o); st.setObject(++i, o.id); st.setObject(++i, o.date); st.setObject(++i, o.orderId); st.setObject(++i, o.parentAlgo); st.executeUpdate(); } } /** * Insert {@link Cancel} at h2 database. * * @param o Cancel. */ private void insertInDb(Cancel o) throws SQLException { try(PreparedStatement st = conn.prepareStatement( "insert into \"cancel\".Cancel (_key, _val, id, date, refOrderId) values(?, ?, ?, ?, ?)")) { int i = 0; st.setObject(++i, o.key(useColocatedData())); st.setObject(++i, o); st.setObject(++i, o.id); st.setObject(++i, o.date); st.setObject(++i, o.refOrderId); st.executeUpdate(); } } /** * Insert {@link Exec} at h2 database. * * @param o Execution. */ private void insertInDb(Exec o) throws SQLException { try(PreparedStatement st = conn.prepareStatement( "insert into \"exec\".Exec (_key, _val, date, rootOrderId, execShares, price, lastMkt) " + "values(?, ?, ?, ?, ?, ?, ?)")) { int i = 0; st.setObject(++i, o.key(useColocatedData())); st.setObject(++i, o); st.setObject(++i, o.date); st.setObject(++i, o.rootOrderId); st.setObject(++i, o.execShares); st.setObject(++i, o.price); st.setObject(++i, o.lastMkt); st.executeUpdate(); } } /** * Custom Order. */ static class CustOrder implements Serializable { /** Primary key. */ @QuerySqlField(index = true) private int orderId; /** Root order ID*/ @QuerySqlField private int rootOrderId; /** Orig order ID*/ @QuerySqlField private int origOrderId; /** Date */ @QuerySqlField private Date date ; /** */ @QuerySqlField private String alias = "CUSTOM"; /** */ @QuerySqlField private int archSeq = 11; // TODO: use it. /** * @param orderId Order id. * @param rootOrderId Root order id. * @param date Date. * @param alias Alias. * @param origOrderId Orig order id. */ CustOrder(int orderId, int rootOrderId, Date date, String alias, int origOrderId) { this.orderId = orderId; this.rootOrderId = rootOrderId; this.origOrderId = origOrderId; this.date = date; this.alias = alias; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { return this == o || o instanceof CustOrder && orderId == ((CustOrder)o).orderId; } /** {@inheritDoc} */ @Override public int hashCode() { return orderId; } } /** * Replace Order. */ static class ReplaceOrder implements Serializable { /** Primary key. */ @QuerySqlField(index = true) private int id; /** Order id. */ @QuerySqlField(index = true) private int orderId; /** Root order ID*/ @QuerySqlField private int rootOrderId; /** Ref order ID*/ @QuerySqlField private int refOrderId; /** Date */ @QuerySqlField private Date date ; /** */ @QuerySqlField private String alias = "CUSTOM"; /** */ @QuerySqlField private int archSeq = 111; // TODO: use it. /** * @param id Id. * @param orderId Order id. * @param rootOrderId Root order id. * @param alias Alias. * @param date Date. * @param refOrderId Reference order id. */ ReplaceOrder(int id, int orderId, int rootOrderId, String alias, Date date, int refOrderId) { this.id = id; this.orderId = orderId; this.rootOrderId = rootOrderId; this.refOrderId = refOrderId; this.date = date; this.alias = alias; } /** * @param useColocatedData Use colocated data. * @return Key. */ public Object key(boolean useColocatedData) { return useColocatedData ? new AffinityKey<>(id, orderId) : id; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { return this == o || o instanceof ReplaceOrder && id == ((ReplaceOrder)o).id; } /** {@inheritDoc} */ @Override public int hashCode() { return id; } } /** * Order params. */ static class OrderParams implements Serializable { /** Primary key. */ @QuerySqlField(index = true) private int id; /** Order id. */ @QuerySqlField(index = true) private int orderId; /** Date */ @QuerySqlField private Date date ; /** */ @QuerySqlField private String parentAlgo = "CUSTOM_ALGO"; /** * @param id Id. * @param orderId Order id. * @param date Date. * @param parentAlgo Parent algo. */ OrderParams(int id, int orderId, Date date, String parentAlgo) { this.id = id; this.orderId = orderId; this.date = date; this.parentAlgo = parentAlgo; } /** * @param useColocatedData Use colocated data.* * @return Key. */ public Object key(boolean useColocatedData) { return useColocatedData ? new AffinityKey<>(id, orderId) : id; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { return this == o || o instanceof OrderParams && id == ((OrderParams)o).id; } /** {@inheritDoc} */ @Override public int hashCode() { return id; } } /** * Cancel Order. */ static class Cancel implements Serializable { /** Primary key. */ @QuerySqlField(index = true) private int id; /** Order id. */ @QuerySqlField(index = true) private int refOrderId; /** Date */ @QuerySqlField private Date date; /** * @param id ID. * @param refOrderId Reference order id. * @param date Date. */ Cancel(int id, int refOrderId, Date date) { this.id = id; this.refOrderId = refOrderId; this.date = date; } /** * @param useColocatedData Use colocated data. * @return Key. */ public Object key(boolean useColocatedData) { return useColocatedData ? new AffinityKey<>(id, refOrderId) : id; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { return this == o || o instanceof Cancel && id == ((Cancel)o).id; } /** {@inheritDoc} */ @Override public int hashCode() { return id; } } /** * Execute information about root query. */ static class Exec implements Serializable { /** */ @QuerySqlField private int id; /** */ @QuerySqlField(index = true) private int rootOrderId; /** Date */ @QuerySqlField private Date date ; /** */ @QuerySqlField private int execShares; /** */ @QuerySqlField private int price; /** */ @QuerySqlField private int lastMkt; /** * @param id ID. * @param rootOrderId Root order id. * @param date Date. * @param execShares Execute shares. * @param price Price. * @param lastMkt Last mkt. */ Exec(int id, int rootOrderId, Date date, int execShares, int price, int lastMkt) { this.id = id; this.rootOrderId = rootOrderId; this.date = date; this.execShares = execShares; this.price = price; this.lastMkt = lastMkt; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { return this == o || o instanceof Exec && id == ((Exec)o).id; } /** {@inheritDoc} */ @Override public int hashCode() { return id; } public Object key(boolean useColocatedData) { return useColocatedData ? new AffinityKey<>(id, rootOrderId) : id; } } }
/* * @(#)TreeSet.java 1.32 03/12/19 * * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package benchmarks.instrumented.java15.util; /** * This class implements the <tt>Set</tt> interface, backed by a * <tt>TreeMap</tt> instance. This class guarantees that the sorted set will * be in ascending element order, sorted according to the <i>natural order</i> * of the elements (see <tt>Comparable</tt>), or by the comparator provided at * set creation time, depending on which constructor is used.<p> * * This implementation provides guaranteed log(n) time cost for the basic * operations (<tt>add</tt>, <tt>remove</tt> and <tt>contains</tt>).<p> * * Note that the ordering maintained by a set (whether or not an explicit * comparator is provided) must be <i>consistent with equals</i> if it is to * correctly implement the <tt>Set</tt> interface. (See <tt>Comparable</tt> * or <tt>Comparator</tt> for a precise definition of <i>consistent with * equals</i>.) This is so because the <tt>Set</tt> interface is defined in * terms of the <tt>equals</tt> operation, but a <tt>TreeSet</tt> instance * performs all key comparisons using its <tt>compareTo</tt> (or * <tt>compare</tt>) method, so two keys that are deemed equal by this method * are, from the standpoint of the set, equal. The behavior of a set * <i>is</i> well-defined even if its ordering is inconsistent with equals; it * just fails to obey the general contract of the <tt>Set</tt> interface.<p> * * <b>Note that this implementation is not synchronized.</b> If multiple * threads access a set concurrently, and at least one of the threads modifies * the set, it <i>must</i> be synchronized externally. This is typically * accomplished by synchronizing on some object that naturally encapsulates * the set. If no such object exists, the set should be "wrapped" using the * <tt>Collections.synchronizedSet</tt> method. This is best done at creation * time, to prevent accidental unsynchronized access to the set: <pre> * SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...)); * </pre><p> * * The Iterators returned by this class's <tt>iterator</tt> method are * <i>fail-fast</i>: if the set is modified at any time after the iterator is * created, in any way except through the iterator's own <tt>remove</tt> * method, the iterator will throw a <tt>ConcurrentModificationException</tt>. * Thus, in the face of concurrent modification, the iterator fails quickly * and cleanly, rather than risking arbitrary, non-deterministic behavior at * an undetermined time in the future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i><p> * * This class is a member of the * <a href="{@docRoot}/../guide/collections/index.html"> * Java Collections Framework</a>. * * @author Josh Bloch * @version 1.32, 12/19/03 * @see Collection * @see Set * @see HashSet * @see Comparable * @see Comparator * @see Collections#synchronizedSortedSet(SortedSet) * @see TreeMap * @since 1.2 */ public class TreeSet<E> extends AbstractSet<E> implements SortedSet<E>, Cloneable, java.io.Serializable { private transient SortedMap<E,Object> m; // The backing Map private transient Set<E> keySet; // The keySet view of the backing Map // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); /** * Constructs a set backed by the specified sorted map. */ private TreeSet(SortedMap<E,Object> m) { this.m = m; keySet = m.keySet(); } /** * Constructs a new, empty set, sorted according to the elements' natural * order. All elements inserted into the set must implement the * <tt>Comparable</tt> interface. Furthermore, all such elements must be * <i>mutually comparable</i>: <tt>e1.compareTo(e2)</tt> must not throw a * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and * <tt>e2</tt> in the set. If the user attempts to add an element to the * set that violates this constraint (for example, the user attempts to * add a string element to a set whose elements are integers), the * <tt>add(Object)</tt> call will throw a <tt>ClassCastException</tt>. * * @see Comparable */ public TreeSet() { this(new TreeMap<E,Object>()); } /** * Constructs a new, empty set, sorted according to the specified * comparator. All elements inserted into the set must be <i>mutually * comparable</i> by the specified comparator: <tt>comparator.compare(e1, * e2)</tt> must not throw a <tt>ClassCastException</tt> for any elements * <tt>e1</tt> and <tt>e2</tt> in the set. If the user attempts to add * an element to the set that violates this constraint, the * <tt>add(Object)</tt> call will throw a <tt>ClassCastException</tt>. * * @param c the comparator that will be used to sort this set. A * <tt>null</tt> value indicates that the elements' <i>natural * ordering</i> should be used. */ public TreeSet(Comparator<? super E> c) { this(new TreeMap<E,Object>(c)); } /** * Constructs a new set containing the elements in the specified * collection, sorted according to the elements' <i>natural order</i>. * All keys inserted into the set must implement the <tt>Comparable</tt> * interface. Furthermore, all such keys must be <i>mutually * comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a * <tt>ClassCastException</tt> for any elements <tt>k1</tt> and * <tt>k2</tt> in the set. * * @param c The elements that will comprise the new set. * * @throws ClassCastException if the keys in the specified collection are * not comparable, or are not mutually comparable. * @throws NullPointerException if the specified collection is null. */ public TreeSet(Collection<? extends E> c) { this(); addAll(c); } /** * Constructs a new set containing the same elements as the specified * sorted set, sorted according to the same ordering. * * @param s sorted set whose elements will comprise the new set. * @throws NullPointerException if the specified sorted set is null. */ public TreeSet(SortedSet<E> s) { this(s.comparator()); addAll(s); } /** * Returns an iterator over the elements in this set. The elements * are returned in ascending order. * * @return an iterator over the elements in this set. */ public Iterator<E> iterator() { return keySet.iterator(); } /** * Returns the number of elements in this set (its cardinality). * * @return the number of elements in this set (its cardinality). */ public int size() { return m.size(); } /** * Returns <tt>true</tt> if this set contains no elements. * * @return <tt>true</tt> if this set contains no elements. */ public boolean isEmpty() { return m.isEmpty(); } /** * Returns <tt>true</tt> if this set contains the specified element. * * @param o the object to be checked for containment in this set. * @return <tt>true</tt> if this set contains the specified element. * * @throws ClassCastException if the specified object cannot be compared * with the elements currently in the set. */ public boolean contains(Object o) { return m.containsKey(o); } /** * Adds the specified element to this set if it is not already present. * * @param o element to be added to this set. * @return <tt>true</tt> if the set did not already contain the specified * element. * * @throws ClassCastException if the specified object cannot be compared * with the elements currently in the set. */ public boolean add(E o) { return m.put(o, PRESENT)==null; } /** * Removes the specified element from this set if it is present. * * @param o object to be removed from this set, if present. * @return <tt>true</tt> if the set contained the specified element. * * @throws ClassCastException if the specified object cannot be compared * with the elements currently in the set. */ public boolean remove(Object o) { return m.remove(o)==PRESENT; } /** * Removes all of the elements from this set. */ public void clear() { m.clear(); } /** * Adds all of the elements in the specified collection to this set. * * @param c elements to be added * @return <tt>true</tt> if this set changed as a result of the call. * * @throws ClassCastException if the elements provided cannot be compared * with the elements currently in the set. * @throws NullPointerException of the specified collection is null. */ public boolean addAll(Collection<? extends E> c) { // Use linear-time version if applicable if (m.size()==0 && c.size() > 0 && // FIXME(VFORCE) Work-around for bug in compiler c instanceof SortedSet && m instanceof TreeMap) { SortedSet<Map.Entry<E, Object>> set = (SortedSet<Map.Entry<E, Object>>) (SortedSet) c; TreeMap<E,Object> map = (TreeMap<E, Object>) m; Comparator<? super E> cc = (Comparator<E>) set.comparator(); Comparator<? super E> mc = map.comparator(); if (cc==mc || (cc != null && cc.equals(mc))) { map.addAllForTreeSet(set, PRESENT); return true; } } return super.addAll(c); } /** * Returns a view of the portion of this set whose elements range from * <tt>fromElement</tt>, inclusive, to <tt>toElement</tt>, exclusive. (If * <tt>fromElement</tt> and <tt>toElement</tt> are equal, the returned * sorted set is empty.) The returned sorted set is backed by this set, * so changes in the returned sorted set are reflected in this set, and * vice-versa. The returned sorted set supports all optional Set * operations.<p> * * The sorted set returned by this method will throw an * <tt>IllegalArgumentException</tt> if the user attempts to insert an * element outside the specified range.<p> * * Note: this method always returns a <i>half-open range</i> (which * includes its low endpoint but not its high endpoint). If you need a * <i>closed range</i> (which includes both endpoints), and the element * type allows for calculation of the successor of a specified value, * merely request the subrange from <tt>lowEndpoint</tt> to * <tt>successor(highEndpoint)</tt>. For example, suppose that <tt>s</tt> * is a sorted set of strings. The following idiom obtains a view * containing all of the strings in <tt>s</tt> from <tt>low</tt> to * <tt>high</tt>, inclusive: <pre> * SortedSet sub = s.subSet(low, high+"\0"); * </pre> * * A similar technique can be used to generate an <i>open range</i> (which * contains neither endpoint). The following idiom obtains a view * containing all of the strings in <tt>s</tt> from <tt>low</tt> to * <tt>high</tt>, exclusive: <pre> * SortedSet sub = s.subSet(low+"\0", high); * </pre> * * @param fromElement low endpoint (inclusive) of the subSet. * @param toElement high endpoint (exclusive) of the subSet. * @return a view of the portion of this set whose elements range from * <tt>fromElement</tt>, inclusive, to <tt>toElement</tt>, * exclusive. * @throws ClassCastException if <tt>fromElement</tt> and * <tt>toElement</tt> cannot be compared to one another using * this set's comparator (or, if the set has no comparator, * using natural ordering). * @throws IllegalArgumentException if <tt>fromElement</tt> is greater than * <tt>toElement</tt>. * @throws NullPointerException if <tt>fromElement</tt> or * <tt>toElement</tt> is <tt>null</tt> and this set uses natural * order, or its comparator does not tolerate <tt>null</tt> * elements. */ public SortedSet<E> subSet(E fromElement, E toElement) { return new TreeSet<E>(m.subMap(fromElement, toElement)); } /** * Returns a view of the portion of this set whose elements are strictly * less than <tt>toElement</tt>. The returned sorted set is backed by * this set, so changes in the returned sorted set are reflected in this * set, and vice-versa. The returned sorted set supports all optional set * operations.<p> * * The sorted set returned by this method will throw an * <tt>IllegalArgumentException</tt> if the user attempts to insert an * element greater than or equal to <tt>toElement</tt>.<p> * * Note: this method always returns a view that does not contain its * (high) endpoint. If you need a view that does contain this endpoint, * and the element type allows for calculation of the successor of a * specified value, merely request a headSet bounded by * <tt>successor(highEndpoint)</tt>. For example, suppose that <tt>s</tt> * is a sorted set of strings. The following idiom obtains a view * containing all of the strings in <tt>s</tt> that are less than or equal * to <tt>high</tt>: <pre> SortedSet head = s.headSet(high+"\0");</pre> * * @param toElement high endpoint (exclusive) of the headSet. * @return a view of the portion of this set whose elements are strictly * less than toElement. * @throws ClassCastException if <tt>toElement</tt> is not compatible * with this set's comparator (or, if the set has no comparator, * if <tt>toElement</tt> does not implement <tt>Comparable</tt>). * @throws IllegalArgumentException if this set is itself a subSet, * headSet, or tailSet, and <tt>toElement</tt> is not within the * specified range of the subSet, headSet, or tailSet. * @throws NullPointerException if <tt>toElement</tt> is <tt>null</tt> and * this set uses natural ordering, or its comparator does * not tolerate <tt>null</tt> elements. */ public SortedSet<E> headSet(E toElement) { return new TreeSet<E>(m.headMap(toElement)); } /** * Returns a view of the portion of this set whose elements are * greater than or equal to <tt>fromElement</tt>. The returned sorted set * is backed by this set, so changes in the returned sorted set are * reflected in this set, and vice-versa. The returned sorted set * supports all optional set operations.<p> * * The sorted set returned by this method will throw an * <tt>IllegalArgumentException</tt> if the user attempts to insert an * element less than <tt>fromElement</tt>. * * Note: this method always returns a view that contains its (low) * endpoint. If you need a view that does not contain this endpoint, and * the element type allows for calculation of the successor of a specified * value, merely request a tailSet bounded by * <tt>successor(lowEndpoint)</tt>. For example, suppose that <tt>s</tt> * is a sorted set of strings. The following idiom obtains a view * containing all of the strings in <tt>s</tt> that are strictly greater * than <tt>low</tt>: <pre> * SortedSet tail = s.tailSet(low+"\0"); * </pre> * * @param fromElement low endpoint (inclusive) of the tailSet. * @return a view of the portion of this set whose elements are * greater than or equal to <tt>fromElement</tt>. * @throws ClassCastException if <tt>fromElement</tt> is not compatible * with this set's comparator (or, if the set has no comparator, * if <tt>fromElement</tt> does not implement <tt>Comparable</tt>). * @throws IllegalArgumentException if this set is itself a subSet, * headSet, or tailSet, and <tt>fromElement</tt> is not within the * specified range of the subSet, headSet, or tailSet. * @throws NullPointerException if <tt>fromElement</tt> is <tt>null</tt> * and this set uses natural ordering, or its comparator does * not tolerate <tt>null</tt> elements. */ public SortedSet<E> tailSet(E fromElement) { return new TreeSet<E>(m.tailMap(fromElement)); } /** * Returns the comparator used to order this sorted set, or <tt>null</tt> * if this tree set uses its elements natural ordering. * * @return the comparator used to order this sorted set, or <tt>null</tt> * if this tree set uses its elements natural ordering. */ public Comparator<? super E> comparator() { return m.comparator(); } /** * Returns the first (lowest) element currently in this sorted set. * * @return the first (lowest) element currently in this sorted set. * @throws NoSuchElementException sorted set is empty. */ public E first() { return m.firstKey(); } /** * Returns the last (highest) element currently in this sorted set. * * @return the last (highest) element currently in this sorted set. * @throws NoSuchElementException sorted set is empty. */ public E last() { return m.lastKey(); } /** * Returns a shallow copy of this <tt>TreeSet</tt> instance. (The elements * themselves are not cloned.) * * @return a shallow copy of this set. */ public Object clone() { TreeSet<E> clone = null; try { clone = (TreeSet<E>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } clone.m = new TreeMap<E,Object>(m); clone.keySet = clone.m.keySet(); return clone; } /** * Save the state of the <tt>TreeSet</tt> instance to a stream (that is, * serialize it). * * @serialData Emits the comparator used to order this set, or * <tt>null</tt> if it obeys its elements' natural ordering * (Object), followed by the size of the set (the number of * elements it contains) (int), followed by all of its * elements (each an Object) in order (as determined by the * set's Comparator, or by the elements' natural ordering if * the set has no Comparator). */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden stuff s.defaultWriteObject(); // Write out Comparator s.writeObject(m.comparator()); // Write out size s.writeInt(m.size()); // Write out all elements in the proper order. for (Iterator i=m.keySet().iterator(); i.hasNext(); ) s.writeObject(i.next()); } /** * Reconstitute the <tt>TreeSet</tt> instance from a stream (that is, * deserialize it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in any hidden stuff s.defaultReadObject(); // Read in Comparator Comparator<E> c = (Comparator<E>) s.readObject(); // Create backing TreeMap and keySet view TreeMap<E,Object> tm; if (c==null) tm = new TreeMap<E,Object>(); else tm = new TreeMap<E,Object>(c); m = tm; keySet = m.keySet(); // Read in size int size = s.readInt(); tm.readTreeSet(size, s, PRESENT); } private static final long serialVersionUID = -2479143000061671589L; }
/* * Copyright Terracotta, 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. */ package org.terracotta.dynamic_config.api.model; import org.junit.Test; import java.nio.file.Paths; import java.util.stream.Stream; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.terracotta.dynamic_config.api.model.Setting.CLIENT_LEASE_DURATION; import static org.terracotta.dynamic_config.api.model.Setting.CLIENT_RECONNECT_WINDOW; import static org.terracotta.dynamic_config.api.model.Setting.CLUSTER_NAME; import static org.terracotta.dynamic_config.api.model.Setting.DATA_DIRS; import static org.terracotta.dynamic_config.api.model.Setting.FAILOVER_PRIORITY; import static org.terracotta.dynamic_config.api.model.Setting.NODE_BACKUP_DIR; import static org.terracotta.dynamic_config.api.model.Setting.NODE_BIND_ADDRESS; import static org.terracotta.dynamic_config.api.model.Setting.NODE_GROUP_BIND_ADDRESS; import static org.terracotta.dynamic_config.api.model.Setting.NODE_GROUP_PORT; import static org.terracotta.dynamic_config.api.model.Setting.NODE_HOSTNAME; import static org.terracotta.dynamic_config.api.model.Setting.NODE_LOGGER_OVERRIDES; import static org.terracotta.dynamic_config.api.model.Setting.NODE_LOG_DIR; import static org.terracotta.dynamic_config.api.model.Setting.NODE_METADATA_DIR; import static org.terracotta.dynamic_config.api.model.Setting.NODE_NAME; import static org.terracotta.dynamic_config.api.model.Setting.NODE_PORT; import static org.terracotta.dynamic_config.api.model.Setting.OFFHEAP_RESOURCES; import static org.terracotta.dynamic_config.api.model.Setting.SECURITY_AUDIT_LOG_DIR; import static org.terracotta.dynamic_config.api.model.Setting.SECURITY_AUTHC; import static org.terracotta.dynamic_config.api.model.Setting.SECURITY_DIR; import static org.terracotta.dynamic_config.api.model.Setting.SECURITY_SSL_TLS; import static org.terracotta.dynamic_config.api.model.Setting.SECURITY_WHITELIST; import static org.terracotta.dynamic_config.api.model.Setting.TC_PROPERTIES; import static org.terracotta.testing.ExceptionMatcher.throwing; /** * @author Mathieu Carbou */ public class SettingValidatorTest { @Test public void test_CLUSTER_NAME() { validateOptional(CLUSTER_NAME); CLUSTER_NAME.validate(null); // cluster name can be set to null when loading config file CLUSTER_NAME.validate(""); // cluster name can be set to null when loading config file CLUSTER_NAME.validate("foo"); } @Test public void test_NODE_NAME() { validateRequired(NODE_NAME); assertThat( () -> NODE_NAME.validate(""), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + NODE_NAME + "' requires a value"))))); Stream.of("d", "D", "h", "c", "i", "H", "n", "o", "a", "v", "t", "(").forEach(c -> { assertThat( () -> NODE_NAME.validate("%" + c), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo(NODE_NAME + " cannot contain substitution parameters"))))); }); NODE_NAME.validate("foo"); } @Test public void test_NODE_HOSTNAME() { validateRequired(NODE_HOSTNAME); assertThat( () -> NODE_HOSTNAME.validate(".."), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("<address> specified in hostname=<address> must be a valid hostname or IP address"))))); assertThat( () -> NODE_HOSTNAME.validate(""), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + NODE_HOSTNAME + "' requires a value"))))); NODE_HOSTNAME.validate("foo"); } @Test public void test_NODE_PORT() { Stream.of(NODE_PORT).forEach(setting -> { validateRequired(setting); assertThat( () -> setting.validate("foo"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("<port> specified in " + setting + "=<port> must be an integer between 1 and 65535"))))); assertThat( () -> setting.validate("0"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("<port> specified in " + setting + "=<port> must be an integer between 1 and 65535"))))); assertThat( () -> setting.validate("65536"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("<port> specified in " + setting + "=<port> must be an integer between 1 and 65535"))))); assertThat( () -> setting.validate(""), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + setting + "' requires a value"))))); setting.validate("9410"); }); } @Test public void test_NODE_GROUP_PORT() { Stream.of(NODE_GROUP_PORT).forEach(setting -> { validateRequired(setting); assertThat( () -> setting.validate("foo"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("<port> specified in " + setting + "=<port> must be an integer between 1 and 65535"))))); assertThat( () -> setting.validate("0"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("<port> specified in " + setting + "=<port> must be an integer between 1 and 65535"))))); assertThat( () -> setting.validate("65536"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("<port> specified in " + setting + "=<port> must be an integer between 1 and 65535"))))); assertThat( () -> setting.validate(""), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + setting + "' requires a value"))))); setting.validate("9410"); setting.validate(null); // unset - switch back to default value }); } @Test public void test_bind_addresses() { Stream.of(NODE_BIND_ADDRESS, NODE_GROUP_BIND_ADDRESS).forEach(setting -> { validateRequired(setting); assertThat( () -> setting.validate("my-hostname"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("<address> specified in " + setting + "=<address> must be a valid IP address"))))); assertThat( () -> setting.validate(""), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + setting + "' requires a value"))))); setting.validate(null); // unset - switch back to default value setting.validate("0.0.0.0"); }); } @Test public void test_paths() { Stream.of(NODE_LOG_DIR, NODE_METADATA_DIR).forEach(setting -> { validateRequired(setting); assertThat( () -> setting.validate("/\u0000/"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Invalid path specified for setting " + setting + ": /\u0000/"))))); assertThat( () -> setting.validate(""), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + setting + "' requires a value"))))); setting.validate("."); setting.validate(null); // unset - switch back to default value }); Stream.of(NODE_BACKUP_DIR, SECURITY_DIR, SECURITY_AUDIT_LOG_DIR).forEach(setting -> { validateOptional(setting); assertThat( () -> setting.validate("/\u0000/"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Invalid path specified for setting " + setting + ": /\u0000/"))))); setting.validate(null); // ok setting.validate("."); }); } @Test public void test_TIMES() { Stream.of(CLIENT_RECONNECT_WINDOW, CLIENT_LEASE_DURATION).forEach(setting -> { validateRequired(setting); setting.validate("0s"); // ok - 0 allowed setting.validate(null); // unset - switch back to default value assertThat( () -> setting.validate("foo"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Invalid measure: 'foo'. <unit> is missing or not recognized. It must be one of " + setting.getAllowedUnits() + "."))))); assertThat( () -> setting.validate("1"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Invalid measure: '1'. <unit> is missing or not recognized. It must be one of " + setting.getAllowedUnits() + "."))))); assertThat( () -> setting.validate("1_"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Invalid measure: '1_'. <unit> is missing or not recognized. It must be one of " + setting.getAllowedUnits() + "."))))); assertThat( () -> setting.validate("1bad-unit"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Invalid measure: '1bad-unit'. <unit> is missing or not recognized. It must be one of " + setting.getAllowedUnits() + "."))))); assertThat( () -> setting.validate("-1s"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Quantity measure cannot be negative"))))); assertThat( () -> setting.validate(""), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + setting + "' requires a value"))))); }); } @Test public void test_FAILOVER_PRIORITY() { validateOptional(FAILOVER_PRIORITY); Stream.of( "foo", "availability:8", "availability:foo", "consistency:-1", "consistency:foo", "consistency:", "1:consistency", "consistency:1:2", ":", ":::", "consistency-1", "??" // :D ).forEach(value -> assertThat( value, () -> FAILOVER_PRIORITY.validate(value), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("failover-priority should be either 'availability', 'consistency', or 'consistency:N' (where 'N' is the voter count expressed as a non-negative integer)"))))) ); } @Test public void test_SECURITY_AUTHC() { validateOptional(SECURITY_AUTHC); SECURITY_AUTHC.validate("ldap"); SECURITY_AUTHC.validate("certificate"); SECURITY_AUTHC.validate("file"); assertThat( () -> SECURITY_AUTHC.validate("foo"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("authc should be one of: [file, ldap, certificate]")))) ); SECURITY_AUTHC.validate(null); // unset - switch back to default value SECURITY_AUTHC.validate(""); } @Test public void test_WHITELIST_SSLTLS() { Stream.of(SECURITY_SSL_TLS, SECURITY_WHITELIST).forEach(setting -> { validateRequired(setting); setting.validate(null); // unset - switch back to default value setting.validate("true"); setting.validate("false"); setting.validate(null, null); // unset - switch back to default value setting.validate(null, "true"); setting.validate(null, "false"); assertThat( () -> setting.validate(""), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + setting + "' requires a value"))))); assertThat( () -> setting.validate(null, ""), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + setting + "' requires a value"))))); assertThat( () -> setting.validate("foo"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo(setting + " should be one of: [true, false]"))))); assertThat( () -> setting.validate("FALSE"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo(setting + " should be one of: [true, false]"))))); assertThat( () -> setting.validate("TRUE"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo(setting + " should be one of: [true, false]"))))); }); } @Test public void test_OFFHEAP_RESOURCES() { OFFHEAP_RESOURCES.validate(null); // unset - switch back to default value OFFHEAP_RESOURCES.validate(null, null); OFFHEAP_RESOURCES.validate("main", null); OFFHEAP_RESOURCES.validate("main", "1GB"); OFFHEAP_RESOURCES.validate("main", ""); OFFHEAP_RESOURCES.validate(null, "main:1GB"); OFFHEAP_RESOURCES.validate(null, "main:1GB,second:2GB"); OFFHEAP_RESOURCES.validate(null, ""); OFFHEAP_RESOURCES.validate(""); // set to empty map assertThat( () -> OFFHEAP_RESOURCES.validate(null, "bar"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("offheap-resources should be specified in the format <resource-name>:<quantity><unit>,<resource-name>:<quantity><unit>..."))))); assertThat( () -> OFFHEAP_RESOURCES.validate(null, "bar:"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("offheap-resources should be specified in the format <resource-name>:<quantity><unit>,<resource-name>:<quantity><unit>..."))))); assertThat( () -> OFFHEAP_RESOURCES.validate(null, "bar: "), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("offheap-resources should be specified in the format <resource-name>:<quantity><unit>,<resource-name>:<quantity><unit>..."))))); assertThat( () -> OFFHEAP_RESOURCES.validate(null, ":value"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("offheap-resources should be specified in the format <resource-name>:<quantity><unit>,<resource-name>:<quantity><unit>..."))))); assertThat( () -> OFFHEAP_RESOURCES.validate(null, " :value"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("offheap-resources should be specified in the format <resource-name>:<quantity><unit>,<resource-name>:<quantity><unit>..."))))); assertThat( () -> OFFHEAP_RESOURCES.validate(null, "bar:1,second:2GB"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("offheap-resources.bar is invalid: Invalid measure: '1'. <unit> is missing or not recognized. It must be one of [B, KB, MB, GB, TB, PB]."))))); assertThat( () -> OFFHEAP_RESOURCES.validate("foo", "bar"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("offheap-resources.foo is invalid: Invalid measure: 'bar'. <unit> is missing or not recognized. It must be one of [B, KB, MB, GB, TB, PB]."))))); } @Test public void test_DATA_DIRS() { DATA_DIRS.validate(null); // unset - switch back to default value DATA_DIRS.validate(null, null); DATA_DIRS.validate("main", null); DATA_DIRS.validate("main", ""); DATA_DIRS.validate(null, ""); DATA_DIRS.validate(""); // set to empty map // Valid Relative paths DATA_DIRS.validate("main", "foo/bar"); DATA_DIRS.validate(null, "main:foo/bar"); DATA_DIRS.validate(null, "main:foo/bar,second:foo/baz"); // Valid Absolute paths String absPath1 = Paths.get("/foo/bar").toAbsolutePath().toString(); // resolves to C:\foo\bar on Windows String absPath2 = Paths.get("/foo/baz").toAbsolutePath().toString(); DATA_DIRS.validate("main", absPath1); DATA_DIRS.validate(null, "main:" + absPath1); DATA_DIRS.validate(null, "main:" + absPath1 + ",second:" + absPath2); // Invalid paths assertThat( () -> DATA_DIRS.validate(null, "main:"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("data-dirs should be specified in the format <resource-name>:<path>,<resource-name>:<path>..."))))); assertThat( () -> DATA_DIRS.validate(null, "main: "), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("data-dirs should be specified in the format <resource-name>:<path>,<resource-name>:<path>..."))))); assertThat( () -> DATA_DIRS.validate(null, ":value"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("data-dirs should be specified in the format <resource-name>:<path>,<resource-name>:<path>..."))))); assertThat( () -> DATA_DIRS.validate(null, " :value"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("data-dirs should be specified in the format <resource-name>:<path>,<resource-name>:<path>..."))))); assertThat( () -> DATA_DIRS.validate("foo", "/\u0000/"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("data-dirs.foo is invalid: Bad path: /\u0000/"))))); } @Test public void test_TC_PROPERTIES() { TC_PROPERTIES.validate(null); // unset - switch back to default value TC_PROPERTIES.validate(""); // set to empty map TC_PROPERTIES.validate(null, null); TC_PROPERTIES.validate(null, ""); TC_PROPERTIES.validate("key", null); TC_PROPERTIES.validate("key", "value"); TC_PROPERTIES.validate("key", ""); TC_PROPERTIES.validate(null, "key:value"); TC_PROPERTIES.validate(null, "key1:value,key2:value"); assertThat( () -> TC_PROPERTIES.validate(null, "key:"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("tc-properties should be specified in the format <key>:<value>,<key>:<value>..."))))); assertThat( () -> TC_PROPERTIES.validate(null, "key: "), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("tc-properties should be specified in the format <key>:<value>,<key>:<value>..."))))); assertThat( () -> TC_PROPERTIES.validate(null, ":value"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("tc-properties should be specified in the format <key>:<value>,<key>:<value>..."))))); assertThat( () -> TC_PROPERTIES.validate(null, " :value"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("tc-properties should be specified in the format <key>:<value>,<key>:<value>..."))))); } @Test public void test_NODE_LOGGER_OVERRIDES() { NODE_LOGGER_OVERRIDES.validate(null); // unset - switch back to default value NODE_LOGGER_OVERRIDES.validate(""); // set to empty map NODE_LOGGER_OVERRIDES.validate(null, null); NODE_LOGGER_OVERRIDES.validate(null, ""); NODE_LOGGER_OVERRIDES.validate("key", null); NODE_LOGGER_OVERRIDES.validate("key", ""); NODE_LOGGER_OVERRIDES.validate("key", "INFO"); NODE_LOGGER_OVERRIDES.validate(null, "key:INFO"); NODE_LOGGER_OVERRIDES.validate(null, "key1:INFO,key2:WARN"); NODE_LOGGER_OVERRIDES.validate("com.foo", "TRACE"); NODE_LOGGER_OVERRIDES.validate("com.foo", "DEBUG"); NODE_LOGGER_OVERRIDES.validate("com.foo", "INFO"); NODE_LOGGER_OVERRIDES.validate("com.foo", "WARN"); NODE_LOGGER_OVERRIDES.validate("com.foo", "ERROR"); assertThat( () -> NODE_LOGGER_OVERRIDES.validate(null, "key:"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("logger-overrides should be specified in the format <logger>:<level>,<logger>:<level>..."))))); assertThat( () -> NODE_LOGGER_OVERRIDES.validate(null, "key: "), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("logger-overrides should be specified in the format <logger>:<level>,<logger>:<level>..."))))); assertThat( () -> NODE_LOGGER_OVERRIDES.validate(null, ":value"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("logger-overrides should be specified in the format <logger>:<level>,<logger>:<level>..."))))); assertThat( () -> NODE_LOGGER_OVERRIDES.validate(null, " :value"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("logger-overrides should be specified in the format <logger>:<level>,<logger>:<level>..."))))); assertThat( () -> NODE_LOGGER_OVERRIDES.validate("com.foo", "FATAL"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("logger-overrides.com.foo is invalid: Bad level: FATAL"))))); } private void validateOptional(Setting setting) { assertThat( () -> setting.validate("foo", "bar"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo(setting + " is not a map"))))); setting.validate("\u0000"); setting.validate(" "); } private void validateRequired(Setting setting) { assertThat( () -> setting.validate("foo", "bar"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo(setting + " is not a map"))))); assertThat( () -> setting.validate("\u0000"), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + setting + "' requires a value"))))); assertThat( () -> setting.validate(" "), is(throwing(instanceOf(IllegalArgumentException.class)).andMessage(is(equalTo("Setting '" + setting + "' requires a value"))))); } }
/* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.server.utilities; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import javax.mail.util.ByteArrayDataSource; import org.fcrepo.server.search.Condition; import org.fcrepo.server.types.gen.ArrayOfString; import org.fcrepo.utilities.DateUtility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A utility class for converting back and forth from the internal Fedora type * classes in org.fcrepo.server.storage.types and the generated type classes * produced by the wsdl2java emitter in org.fcrepo.server.types.gen.gen. * * @author Ross Wayland */ public abstract class TypeUtility { private static final Logger logger = LoggerFactory .getLogger(TypeUtility.class); private static final String EMPTY_STRING = ""; private static final int INITIAL_SIZE = 1024 * 1024; private static final int BUFFER_SIZE = 1024; public static org.fcrepo.server.types.gen.Datastream convertDatastreamToGenDatastream(org.fcrepo.server.storage.types.Datastream in) { if (in == null) { return null; } org.fcrepo.server.types.gen.Datastream out = new org.fcrepo.server.types.gen.Datastream(); String group = in.DSControlGrp; out.setControlGroup(org.fcrepo.server.types.gen.DatastreamControlGroup .fromValue(group)); if ("R".equals(group) || "E".equals(group)) { // only given location if it's a redirect or external datastream out.setLocation(in.DSLocation); } out.setCreateDate(DateUtility.convertDateToString(in.DSCreateDT)); out.setID(in.DatastreamID); org.fcrepo.server.types.gen.ArrayOfString altIDs = new org.fcrepo.server.types.gen.ArrayOfString(); if (in.DatastreamAltIDs != null) altIDs.getItem().addAll(Arrays.asList(in.DatastreamAltIDs)); out.setAltIDs(altIDs); out.setLabel(in.DSLabel); out.setVersionable(in.DSVersionable); out.setMIMEType(in.DSMIME); out.setFormatURI(in.DSFormatURI); out.setSize(in.DSSize); out.setState(in.DSState); out.setVersionID(in.DSVersionID); out.setChecksum(in.DSChecksum); out.setChecksumType(in.DSChecksumType); return out; } public static org.fcrepo.server.types.gen.FieldSearchResult convertFieldSearchResultToGenFieldSearchResult(org.fcrepo.server.search.FieldSearchResult result) { if (result == null) { return null; } org.fcrepo.server.types.gen.FieldSearchResult ret = new org.fcrepo.server.types.gen.FieldSearchResult(); ret.setResultList(convertSearchObjectFieldsListToGenObjectFieldsArray(result .objectFieldsList())); if (result.getToken() != null) { org.fcrepo.server.types.gen.ListSession sess = new org.fcrepo.server.types.gen.ListSession(); org.fcrepo.server.types.gen.ObjectFactory factory = new org.fcrepo.server.types.gen.ObjectFactory(); sess.setToken(result.getToken()); if (result.getCursor() > -1) { sess.setCursor(new BigInteger("" + result.getCursor())); } if (result.getCompleteListSize() > -1) { sess.setCompleteListSize(new BigInteger("" + result.getCompleteListSize())); } if (result.getExpirationDate() != null) { sess.setExpirationDate(factory.createListSessionExpirationDate(DateUtility .convertDateToString(result.getExpirationDate()))); } ret.setListSession(factory.createFieldSearchResultListSession(sess)); } return ret; } public static org.fcrepo.server.search.FieldSearchQuery convertGenFieldSearchQueryToFieldSearchQuery(org.fcrepo.server.types.gen.FieldSearchQuery gen) throws org.fcrepo.server.errors.InvalidOperatorException, org.fcrepo.server.errors.QueryParseException { if (gen == null) { return null; } if (gen.getTerms() != null) { return new org.fcrepo.server.search.FieldSearchQuery(gen.getTerms() .getValue()); } else if (gen.getConditions() != null) { return new org.fcrepo.server.search.FieldSearchQuery(convertGenConditionArrayToSearchConditionList(gen .getConditions().getValue())); } else { return new org.fcrepo.server.search.FieldSearchQuery(EMPTY_STRING); } } public static List<Condition> convertGenConditionArrayToSearchConditionList(org.fcrepo.server.types.gen.FieldSearchQuery.Conditions genConditions) throws org.fcrepo.server.errors.InvalidOperatorException, org.fcrepo.server.errors.QueryParseException { if (genConditions == null) { return null; } ArrayList<Condition> list = new ArrayList<Condition>(); if (genConditions != null && genConditions.getCondition() != null) { for (org.fcrepo.server.types.gen.Condition c : genConditions .getCondition()) { list.add(new org.fcrepo.server.search.Condition(c.getProperty(), c.getOperator() != null ? c .getOperator() .value() : null, c.getValue())); } } return list; } private static org.fcrepo.server.types.gen.FieldSearchResult.ResultList convertSearchObjectFieldsListToGenObjectFieldsArray(List<org.fcrepo.server.search.ObjectFields> sfList) { if (sfList == null) { return null; } org.fcrepo.server.types.gen.FieldSearchResult.ResultList genFields = new org.fcrepo.server.types.gen.FieldSearchResult.ResultList(); for (int i = 0; i < sfList.size(); i++) { org.fcrepo.server.types.gen.ObjectFields gf = new org.fcrepo.server.types.gen.ObjectFields(); org.fcrepo.server.search.ObjectFields sf = sfList.get(i); org.fcrepo.server.types.gen.ObjectFactory factory = new org.fcrepo.server.types.gen.ObjectFactory(); // Repository key fields if (sf.getPid() != null) { gf.setPid(factory.createObjectFieldsPid(sf.getPid())); } if (sf.getLabel() != null) { gf.setLabel(factory.createObjectFieldsLabel(sf.getLabel())); } if (sf.getState() != null) { gf.setState(factory.createObjectFieldsState(sf.getState())); } if (sf.getOwnerId() != null) { gf.setOwnerId(factory.createObjectFieldsOwnerId(sf.getOwnerId())); } if (sf.getCDate() != null) { gf.setCDate(factory.createObjectFieldsCDate(DateUtility .convertDateToString(sf.getCDate()))); } if (sf.getMDate() != null) { gf.setMDate(factory.createObjectFieldsMDate(DateUtility .convertDateToString(sf.getMDate()))); } if (sf.getDCMDate() != null) { gf.setDcmDate(factory.createObjectFieldsDcmDate(DateUtility .convertDateToString(sf.getDCMDate()))); } // Dublin core fields if (sf.titles().size() != 0) { gf.getTitle().addAll(toStringList(sf.titles())); } if (sf.creators().size() != 0) { gf.getCreator().addAll(toStringList(sf.creators())); } if (sf.subjects().size() != 0) { gf.getSubject().addAll(toStringList(sf.subjects())); } if (sf.descriptions().size() != 0) { gf.getDescription().addAll(toStringList(sf.descriptions())); } if (sf.publishers().size() != 0) { gf.getPublisher().addAll(toStringList(sf.publishers())); } if (sf.contributors().size() != 0) { gf.getContributor().addAll(toStringList(sf.contributors())); } if (sf.dates().size() != 0) { gf.getDate().addAll(toStringList(sf.dates())); } if (sf.types().size() != 0) { gf.getType().addAll(toStringList(sf.types())); } if (sf.formats().size() != 0) { gf.getFormat().addAll(toStringList(sf.formats())); } if (sf.identifiers().size() != 0) { gf.getIdentifier().addAll(toStringList(sf.identifiers())); } if (sf.sources().size() != 0) { gf.getSource().addAll(toStringList(sf.sources())); } if (sf.languages().size() != 0) { gf.getLanguage().addAll(toStringList(sf.languages())); } if (sf.relations().size() != 0) { gf.getRelation().addAll(toStringList(sf.relations())); } if (sf.coverages().size() != 0) { gf.getCoverage().addAll(toStringList(sf.coverages())); } if (sf.rights().size() != 0) { gf.getRights().addAll(toStringList(sf.rights())); } genFields.getObjectFields().add(gf); } return genFields; } public static String[] toStringArray(List<DCField> l) { if (l == null) { return null; } String[] ret = new String[l.size()]; for (int i = 0; i < l.size(); i++) { ret[i] = l.get(i) != null ? l.get(i).getValue() : null; } return ret; } private static List<String> toStringList(List<DCField> dcFields) { if (dcFields == null) { return null; } List<String> ret = new ArrayList<String>(dcFields.size()); for (DCField dcField : dcFields) { ret.add(dcField != null ? dcField.getValue() : null); } return ret; } public static org.fcrepo.server.types.gen.MethodParmDef convertMethodParmDefToGenMethodParmDef(org.fcrepo.server.storage.types.MethodParmDef methodParmDef) { if (methodParmDef != null) { org.fcrepo.server.types.gen.MethodParmDef genMethodParmDef = new org.fcrepo.server.types.gen.MethodParmDef(); genMethodParmDef.setParmName(methodParmDef.parmName); genMethodParmDef.setParmLabel(methodParmDef.parmLabel); genMethodParmDef .setParmDefaultValue(methodParmDef.parmDefaultValue); org.fcrepo.server.types.gen.ArrayOfString parmDomainVals = new org.fcrepo.server.types.gen.ArrayOfString(); if (methodParmDef.parmDomainValues != null) parmDomainVals.getItem() .addAll(Arrays.asList(methodParmDef.parmDomainValues)); genMethodParmDef.setParmDomainValues(parmDomainVals); genMethodParmDef.setParmRequired(methodParmDef.parmRequired); genMethodParmDef.setParmType(methodParmDef.parmType); genMethodParmDef.setParmPassBy(methodParmDef.parmPassBy); return genMethodParmDef; } else { return null; } } public static org.fcrepo.server.types.gen.MIMETypedStream convertMIMETypedStreamToGenMIMETypedStream(org.fcrepo.server.storage.types.MIMETypedStream mimeTypedStream) { if (mimeTypedStream != null) { org.fcrepo.server.types.gen.MIMETypedStream genMIMETypedStream = new org.fcrepo.server.types.gen.MIMETypedStream(); genMIMETypedStream.setMIMEType(mimeTypedStream.MIMEType); org.fcrepo.server.storage.types.Property[] header = mimeTypedStream.header; org.fcrepo.server.types.gen.MIMETypedStream.Header head = new org.fcrepo.server.types.gen.MIMETypedStream.Header(); if (header != null) { for (org.fcrepo.server.storage.types.Property property : header) { head.getProperty() .add(convertPropertyToGenProperty(property)); } } genMIMETypedStream.setHeader(head); ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); InputStream is = mimeTypedStream.getStream(); int byteStream = 0; try { byte[] buffer = new byte[255]; while ((byteStream = is.read(buffer)) != -1) { baos.write(buffer, 0, byteStream); } } catch (IOException ioe) { logger.error("Error converting types", ioe); } byte[] bytes = baos.toByteArray(); genMIMETypedStream.setStream(bytes); mimeTypedStream.close(); mimeTypedStream.setStream(new ByteArrayInputStream(bytes)); return genMIMETypedStream; } else { return null; } } // The MIMETypedStream is the only WS data type that differs between // the standard and MTOM implementations public static org.fcrepo.server.types.mtom.gen.MIMETypedStream convertMIMETypedStreamToGenMIMETypedStreamMTOM(org.fcrepo.server.storage.types.MIMETypedStream mimeTypedStream) { if (mimeTypedStream != null) { org.fcrepo.server.types.mtom.gen.MIMETypedStream genMIMETypedStream = new org.fcrepo.server.types.mtom.gen.MIMETypedStream(); genMIMETypedStream.setMIMEType(mimeTypedStream.MIMEType); org.fcrepo.server.storage.types.Property[] header = mimeTypedStream.header; org.fcrepo.server.types.mtom.gen.MIMETypedStream.Header head = new org.fcrepo.server.types.mtom.gen.MIMETypedStream.Header(); if (header != null) { for (org.fcrepo.server.storage.types.Property property : header) { head.getProperty() .add(convertPropertyToGenProperty(property)); } } genMIMETypedStream.setHeader(head); ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); InputStream is = mimeTypedStream.getStream(); int byteStream = 0; try { byte[] buffer = new byte[255]; while ((byteStream = is.read(buffer)) != -1) { baos.write(buffer, 0, byteStream); } } catch (IOException ioe) { logger.error("Error converting types", ioe); } genMIMETypedStream .setStream(new DataHandler(new ByteArrayDataSource(baos .toByteArray(), "text/html"))); mimeTypedStream.close(); mimeTypedStream.setStream(new ByteArrayInputStream(baos .toByteArray())); return genMIMETypedStream; } else { return null; } } public static List<org.fcrepo.server.types.gen.ObjectMethodsDef> convertObjectMethodsDefArrayToGenObjectMethodsDefList(org.fcrepo.server.storage.types.ObjectMethodsDef[] objectMethodDefs) { if (objectMethodDefs != null) { List<org.fcrepo.server.types.gen.ObjectMethodsDef> genObjectMethodDefs = new ArrayList<org.fcrepo.server.types.gen.ObjectMethodsDef>(objectMethodDefs.length); for (org.fcrepo.server.storage.types.ObjectMethodsDef objectMethodsDef : objectMethodDefs) { org.fcrepo.server.types.gen.ObjectMethodsDef genObjectMethodDef = new org.fcrepo.server.types.gen.ObjectMethodsDef(); genObjectMethodDef.setPID(objectMethodsDef.PID); genObjectMethodDef .setServiceDefinitionPID(objectMethodsDef.sDefPID); genObjectMethodDef.setMethodName(objectMethodsDef.methodName); org.fcrepo.server.storage.types.MethodParmDef[] methodParmDefs = objectMethodsDef.methodParmDefs; org.fcrepo.server.types.gen.ObjectMethodsDef.MethodParmDefs genMethodParmDefs = new org.fcrepo.server.types.gen.ObjectMethodsDef.MethodParmDefs(); if (methodParmDefs != null) { for (org.fcrepo.server.storage.types.MethodParmDef methodParmDef : methodParmDefs) { genMethodParmDefs .getMethodParmDef() .add(convertMethodParmDefToGenMethodParmDef(methodParmDef)); } } genObjectMethodDef.setMethodParmDefs(genMethodParmDefs); genObjectMethodDefs.add(genObjectMethodDef); } return genObjectMethodDefs; } else { return null; } } public static org.fcrepo.server.types.gen.ObjectProfile convertObjectProfileToGenObjectProfile(org.fcrepo.server.access.ObjectProfile objectProfile) { if (objectProfile != null) { org.fcrepo.server.types.gen.ObjectProfile genObjectProfile = new org.fcrepo.server.types.gen.ObjectProfile(); genObjectProfile.setPid(objectProfile.PID); genObjectProfile.setObjLabel(objectProfile.objectLabel); org.fcrepo.server.types.gen.ObjectProfile.ObjModels objModels = new org.fcrepo.server.types.gen.ObjectProfile.ObjModels(); if (objectProfile.objectModels != null) { objModels.getModel().addAll(objectProfile.objectModels); } genObjectProfile.setObjModels(objModels); genObjectProfile.setObjCreateDate(DateUtility .convertDateToString(objectProfile.objectCreateDate)); genObjectProfile.setObjLastModDate(DateUtility .convertDateToString(objectProfile.objectLastModDate)); genObjectProfile .setObjDissIndexViewURL(objectProfile.dissIndexViewURL); genObjectProfile .setObjItemIndexViewURL(objectProfile.itemIndexViewURL); return genObjectProfile; } else { return null; } } public static org.fcrepo.server.types.gen.RepositoryInfo convertReposInfoToGenReposInfo(org.fcrepo.server.access.RepositoryInfo repositoryInfo) { if (repositoryInfo != null) { org.fcrepo.server.types.gen.RepositoryInfo genRepositoryInfo = new org.fcrepo.server.types.gen.RepositoryInfo(); genRepositoryInfo.setRepositoryName(repositoryInfo.repositoryName); genRepositoryInfo .setRepositoryBaseURL(repositoryInfo.repositoryBaseURL); genRepositoryInfo .setRepositoryVersion(repositoryInfo.repositoryVersion); genRepositoryInfo .setRepositoryPIDNamespace(repositoryInfo.repositoryPIDNamespace); genRepositoryInfo .setDefaultExportFormat(repositoryInfo.defaultExportFormat); genRepositoryInfo.setOAINamespace(repositoryInfo.OAINamespace); if (repositoryInfo.adminEmailList != null) { org.fcrepo.server.types.gen.ArrayOfString val = new org.fcrepo.server.types.gen.ArrayOfString(); val.getItem() .addAll(Arrays.asList(repositoryInfo.adminEmailList)); genRepositoryInfo.setAdminEmailList(val); } genRepositoryInfo.setSamplePID(repositoryInfo.samplePID); genRepositoryInfo .setSampleOAIIdentifier(repositoryInfo.sampleOAIIdentifer); genRepositoryInfo .setSampleSearchURL(repositoryInfo.sampleSearchURL); genRepositoryInfo .setSampleAccessURL(repositoryInfo.sampleAccessURL); genRepositoryInfo.setSampleOAIURL(repositoryInfo.sampleOAIURL); if (repositoryInfo.retainPIDs != null) { org.fcrepo.server.types.gen.ArrayOfString val = new org.fcrepo.server.types.gen.ArrayOfString(); val.getItem().addAll(Arrays.asList(repositoryInfo.retainPIDs)); genRepositoryInfo.setRetainPIDs(val); } return genRepositoryInfo; } else { return null; } } public static org.fcrepo.server.storage.types.Property[] convertGenPropertyArrayToPropertyArray(org.fcrepo.server.types.gen.GetDissemination.Parameters genProperties) { if (genProperties != null) { org.fcrepo.server.storage.types.Property[] properties = new org.fcrepo.server.storage.types.Property[genProperties .getParameter() == null ? 0 : genProperties .getParameter().size()]; int i = 0; for (org.fcrepo.server.types.gen.Property prop : genProperties .getParameter()) { org.fcrepo.server.storage.types.Property property = new org.fcrepo.server.storage.types.Property(); property = convertGenPropertyToProperty(prop); properties[i++] = property; } return properties; } else { return null; } } public static org.fcrepo.server.storage.types.Property[] convertGenPropertyArrayToPropertyArray(org.fcrepo.server.types.mtom.gen.GetDissemination.Parameters genProperties) { if (genProperties != null) { org.fcrepo.server.storage.types.Property[] properties = new org.fcrepo.server.storage.types.Property[genProperties .getParameter() == null ? 0 : genProperties .getParameter().size()]; int i = 0; for (org.fcrepo.server.types.gen.Property prop : genProperties .getParameter()) { org.fcrepo.server.storage.types.Property property = new org.fcrepo.server.storage.types.Property(); property = convertGenPropertyToProperty(prop); properties[i++] = property; } return properties; } else { return null; } } public static org.fcrepo.server.storage.types.Property convertGenPropertyToProperty(org.fcrepo.server.types.gen.Property genProperty) { org.fcrepo.server.storage.types.Property property = new org.fcrepo.server.storage.types.Property(); if (genProperty != null) { property.name = genProperty.getName(); property.value = genProperty.getValue(); } return property; } public static org.fcrepo.server.types.gen.Property convertPropertyToGenProperty(org.fcrepo.server.storage.types.Property property) { org.fcrepo.server.types.gen.Property genProperty = new org.fcrepo.server.types.gen.Property(); if (property != null) { genProperty.setName(property.name); genProperty.setValue(property.value); } return genProperty; } public static org.fcrepo.server.types.gen.RelationshipTuple convertRelsTupleToGenRelsTuple(org.fcrepo.server.storage.types.RelationshipTuple in) { if (in == null) { return null; } org.fcrepo.server.types.gen.RelationshipTuple out = new org.fcrepo.server.types.gen.RelationshipTuple(); out.setSubject(in.subject); out.setPredicate(in.predicate); out.setObject(in.object); out.setIsLiteral(in.isLiteral); if (in.datatype == null) out.setDatatype(null); else out.setDatatype(in.datatype.toString()); return out; } public static org.fcrepo.server.types.gen.DatastreamDef convertDatastreamDefToGenDatastreamDef(org.fcrepo.server.storage.types.DatastreamDef in) { if (in == null) { return null; } org.fcrepo.server.types.gen.DatastreamDef out = new org.fcrepo.server.types.gen.DatastreamDef(); out.setID(in.dsID); out.setLabel(in.dsLabel); out.setMIMEType(in.dsMIME); return out; } public static List<org.fcrepo.server.types.gen.DatastreamDef> convertDatastreamDefArrayToGenDatastreamDefList(org.fcrepo.server.storage.types.DatastreamDef[] dsDefs) { if (dsDefs != null) { List<org.fcrepo.server.types.gen.DatastreamDef> genDatastreamDefs = new ArrayList<org.fcrepo.server.types.gen.DatastreamDef>(dsDefs.length); for (org.fcrepo.server.storage.types.DatastreamDef dsDef : dsDefs) { genDatastreamDefs .add(convertDatastreamDefToGenDatastreamDef(dsDef)); } return genDatastreamDefs; } else { return null; } } public static org.fcrepo.server.types.gen.Validation convertValidationToGenValidation(org.fcrepo.server.storage.types.Validation validation) { if (validation == null) { return null; } org.fcrepo.server.types.gen.Validation genvalid = new org.fcrepo.server.types.gen.Validation(); genvalid.setValid(validation.isValid()); genvalid.setPid(validation.getPid()); org.fcrepo.server.types.gen.Validation.ObjModels objModels = new org.fcrepo.server.types.gen.Validation.ObjModels(); objModels.getModel().addAll(validation.getContentModels()); genvalid.setObjModels(objModels); org.fcrepo.server.types.gen.Validation.ObjProblems objProblems = new org.fcrepo.server.types.gen.Validation.ObjProblems(); objProblems.getProblem().addAll(validation.getObjectProblems()); genvalid.setObjProblems(objProblems); Map<String, List<String>> dsprobs = validation.getDatastreamProblems(); org.fcrepo.server.types.gen.Validation.DatastreamProblems problems = new org.fcrepo.server.types.gen.Validation.DatastreamProblems(); if (dsprobs != null) { for (String key : dsprobs.keySet()) { org.fcrepo.server.types.gen.DatastreamProblem dsProblem = new org.fcrepo.server.types.gen.DatastreamProblem(); dsProblem.setDatastreamID(key); dsProblem.getProblem().addAll(dsprobs.get(key)); problems.getDatastream().add(dsProblem); } } genvalid.setDatastreamProblems(problems); return genvalid; } public static byte[] convertDataHandlerToBytes(DataHandler dh) { if (dh != null) { ByteArrayOutputStream bos = new ByteArrayOutputStream(INITIAL_SIZE); InputStream in; try { in = dh.getInputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) { bos.write(buffer, 0, bytesRead); } return bos.toByteArray(); } catch (IOException e) { return null; } } else return null; } public static DataHandler convertBytesToDataHandler(byte[] content) { if (content != null) { return new DataHandler(new ByteArrayDataSource(content, "text/xml")); } else return null; } public static ArrayOfString convertStringtoAOS(String[] arr) { if (arr != null) { ArrayOfString arofs = new ArrayOfString(); arofs.getItem().addAll(Arrays.asList(arr)); return arofs; } else return null; } }
/** * Copyright 2005-2013 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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 org.kuali.rice.kew.docsearch; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.Years; import org.junit.Test; import org.kuali.rice.kew.api.KewApiConstants; import org.kuali.rice.kew.api.WorkflowDocument; import org.kuali.rice.kew.api.WorkflowDocumentFactory; import org.kuali.rice.kew.api.action.RequestedActions; import org.kuali.rice.kew.api.document.Document; import org.kuali.rice.kew.api.document.DocumentStatus; import org.kuali.rice.kew.api.document.DocumentStatusCategory; import org.kuali.rice.kew.api.document.search.DocumentSearchCriteria; import org.kuali.rice.kew.api.document.search.DocumentSearchResult; import org.kuali.rice.kew.api.document.search.DocumentSearchResults; import org.kuali.rice.kew.api.document.search.RouteNodeLookupLogic; import org.kuali.rice.kew.docsearch.service.DocumentSearchService; import org.kuali.rice.kew.doctype.bo.DocumentType; import org.kuali.rice.kew.doctype.service.DocumentTypeService; import org.kuali.rice.kew.engine.node.RouteNode; import org.kuali.rice.kew.service.KEWServiceLocator; import org.kuali.rice.kew.test.KEWTestCase; import org.kuali.rice.kew.useroptions.UserOptions; import org.kuali.rice.kew.useroptions.UserOptionsService; import org.kuali.rice.kim.api.identity.Person; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.kuali.rice.test.BaselineTestCase; import org.kuali.rice.test.TestHarnessServiceLocator; import org.springframework.jdbc.core.JdbcTemplate; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.Assert.*; @BaselineTestCase.BaselineMode(BaselineTestCase.Mode.CLEAR_DB) public class DocumentSearchTest extends KEWTestCase { private static final String KREW_DOC_HDR_T = "KREW_DOC_HDR_T"; private static final String INITIATOR_COL = "INITR_PRNCPL_ID"; DocumentSearchService docSearchService; UserOptionsService userOptionsService; @Override protected void loadTestData() throws Exception { loadXmlFile("SearchAttributeConfig.xml"); } @Override protected void setUpAfterDataLoad() throws Exception { docSearchService = (DocumentSearchService)KEWServiceLocator.getDocumentSearchService(); userOptionsService = (UserOptionsService)KEWServiceLocator.getUserOptionsService(); } @Test public void testDocSearch() throws Exception { Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("bmcgough"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); DocumentSearchResults results = null; criteria.setTitle("*IN"); criteria.setSaveName("bytitle"); results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); criteria = DocumentSearchCriteria.Builder.create(); criteria.setTitle("*IN-CFSG"); criteria.setSaveName("for in accounts"); results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); criteria = DocumentSearchCriteria.Builder.create(); criteria.setDateApprovedFrom(new DateTime(2004, 9, 16, 0, 0)); results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); criteria = DocumentSearchCriteria.Builder.create(); user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("bmcgough"); DocumentSearchCriteria savedCriteria = docSearchService.getNamedSearchCriteria(user.getPrincipalId(), "bytitle"); assertNotNull(savedCriteria); assertEquals("bytitle", savedCriteria.getSaveName()); savedCriteria = docSearchService.getNamedSearchCriteria(user.getPrincipalId(), "for in accounts"); assertNotNull(savedCriteria); assertEquals("for in accounts", savedCriteria.getSaveName()); } // KULRICE-5755 tests that the Document in the DocumentResult is properly populated @Test public void testDocSearchDocumentResult() throws Exception { String[] docIds = routeTestDocs(); Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("bmcgough"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); DocumentSearchResults results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); assertEquals(3, results.getSearchResults().size()); DocumentSearchResult result = results.getSearchResults().get(0); Document doc = result.getDocument(); // check all the DocumentContract properties assertNotNull(doc.getApplicationDocumentStatus()); assertNotNull(doc.getApplicationDocumentStatusDate()); assertNotNull(doc.getDateApproved()); assertNotNull(doc.getDateCreated()); assertNotNull(doc.getDateFinalized()); assertNotNull(doc.getDocumentId()); assertNotNull(doc.getDocumentTypeName()); assertNotNull(doc.getApplicationDocumentId()); assertNotNull(doc.getDateLastModified()); assertNotNull(doc.getDocumentHandlerUrl()); assertNotNull(doc.getDocumentTypeId()); assertNotNull(doc.getInitiatorPrincipalId()); assertNotNull(doc.getRoutedByPrincipalId()); assertNotNull(doc.getStatus()); assertNotNull(doc.getTitle()); // route variables are currently excluded assertTrue(doc.getVariables().isEmpty()); } @Test public void testDocSearch_appDocStatuses() throws Exception { String[] docIds = routeTestDocs(); DateTime now = DateTime.now(); DateTime before = now.minusDays(2); DateTime after = now.plusDays(2); String principalId = getPrincipalId("bmcgough"); // first test basic multi-appDocStatus search without dates. search for 2 out of 3 existing statuses List<String> appDocStatusSearch = Arrays.asList("Submitted", "Pending"); DocumentSearchResults results = doAppStatusDocSearch(principalId, appDocStatusSearch, null, null); assertEquals("should have matched one doc for each status", 2, results.getSearchResults().size()); for (DocumentSearchResult result : results.getSearchResults()) { assertTrue("app doc status should be in " + StringUtils.join(appDocStatusSearch, ", "), appDocStatusSearch.contains(result.getDocument().getApplicationDocumentStatus())); } // use times to verify app doc status change date functionality // first try to bring all 3 docs back with a range that includes all the test docs appDocStatusSearch = Arrays.asList("Submitted", "Pending", "Completed"); results = doAppStatusDocSearch(principalId, appDocStatusSearch, before, after); assertEquals("all docs are in the date range, should have matched them all", 3, results.getSearchResults().size()); for (DocumentSearchResult result : results.getSearchResults()) { assertTrue("app doc status should be in " + StringUtils.join(appDocStatusSearch, ", "), appDocStatusSearch.contains(result.getDocument().getApplicationDocumentStatus())); } // test that the app doc status list still limits the results when a date range is set appDocStatusSearch = Arrays.asList("Submitted", "Pending"); results = doAppStatusDocSearch(principalId, appDocStatusSearch, before, after); assertEquals("should have matched one doc for each status", 2, results.getSearchResults().size()); for (DocumentSearchResult result : results.getSearchResults()) { assertTrue("app doc status should be in " + StringUtils.join(appDocStatusSearch, ", "), appDocStatusSearch.contains(result.getDocument().getApplicationDocumentStatus())); } // test that the date range limits the results too. No docs will be in this range. appDocStatusSearch = Arrays.asList("Submitted", "Pending", "Completed"); results = doAppStatusDocSearch(principalId, appDocStatusSearch, after, after.plusDays(1)); assertEquals("none of the docs should be in the date range", 0, results.getSearchResults().size()); // finally, test a legacy form of the search to make sure that the criteria is still respected DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); criteria.setApplicationDocumentStatus("Submitted"); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals("legacy style app doc status search should have matched one document", 1, results.getSearchResults().size()); assertTrue("app doc status should match the search criteria", "Submitted".equals(results.getSearchResults().get(0).getDocument().getApplicationDocumentStatus())); } private DocumentSearchResults doAppStatusDocSearch(String principalId, List<String> appDocStatuses, DateTime appStatusChangedFrom, DateTime appStatusChangedTo) { DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); criteria.setApplicationDocumentStatuses(appDocStatuses); criteria.setDateApplicationDocumentStatusChangedFrom(appStatusChangedFrom); criteria.setDateApplicationDocumentStatusChangedTo(appStatusChangedTo); return docSearchService.lookupDocuments(principalId, criteria.build()); } @Test public void testDocSearch_maxResults() throws Exception { String[] docIds = routeTestDocs(); String principalId = getPrincipalId("bmcgough"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); criteria.setMaxResults(5); DocumentSearchResults results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(3, results.getSearchResults().size()); criteria.setMaxResults(2); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(2, results.getSearchResults().size()); // test search result document population // break out into separate test if/when we have more fields to test assertEquals("_blank", results.getSearchResults().get(0).getDocument().getDocumentHandlerUrl()); } @Test public void testDocSearch_maxResultsIsNull() throws Exception { String[] docIds = routeTestDocs(); String principalId = getPrincipalId("bmcgough"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); criteria.setMaxResults(5); DocumentSearchResults results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(3, results.getSearchResults().size()); criteria.setMaxResults(null); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(3, results.getSearchResults().size()); } @Test public void testDocSearch_maxResultsIsZero() throws Exception { String[] docIds = routeTestDocs(); String principalId = getPrincipalId("bmcgough"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); criteria.setMaxResults(5); DocumentSearchResults results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(3, results.getSearchResults().size()); criteria.setMaxResults(0); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(0, results.getSearchResults().size()); } @Test public void testDocSearch_startAtIndex() throws Exception { String[] docIds = routeTestDocs(); String principalId = getPrincipalId("bmcgough"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); criteria.setMaxResults(5); DocumentSearchResults results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(3, results.getSearchResults().size()); criteria.setStartAtIndex(1); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(2, results.getSearchResults().size()); } @Test public void testDocSearch_startAtIndexMoreThanResuls() throws Exception { String[] docIds = routeTestDocs(); String principalId = getPrincipalId("bmcgough"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); criteria.setMaxResults(5); DocumentSearchResults results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(3, results.getSearchResults().size()); criteria.setStartAtIndex(5); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(0, results.getSearchResults().size()); } @Test public void testDocSearch_startAtIndexNegative() throws Exception { String[] docIds = routeTestDocs(); String principalId = getPrincipalId("bmcgough"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); criteria.setMaxResults(5); DocumentSearchResults results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(3, results.getSearchResults().size()); criteria.setStartAtIndex(-1); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(0, results.getSearchResults().size()); } @Test public void testDocSearch_startAtIndexZero() throws Exception { String[] docIds = routeTestDocs(); String principalId = getPrincipalId("bmcgough"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); criteria.setMaxResults(5); DocumentSearchResults results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(3, results.getSearchResults().size()); criteria.setStartAtIndex(0); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(3, results.getSearchResults().size()); } /** * Tests that performing a search automatically saves the last search criteria */ @Test public void testUnnamedDocSearchPersistence() throws Exception { Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("bmcgough"); Collection<UserOptions> allUserOptions_before = userOptionsService.findByWorkflowUser(user.getPrincipalId()); List<UserOptions> namedSearches_before = userOptionsService.findByUserQualified(user.getPrincipalId(), "DocSearch.NamedSearch.%"); assertEquals(0, namedSearches_before.size()); assertEquals(0, allUserOptions_before.size()); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setTitle("*IN"); criteria.setDateCreatedFrom(DateTime.now().minus(Years.ONE)); // otherwise one is set for us DocumentSearchCriteria c1 = criteria.build(); DocumentSearchResults results = docSearchService.lookupDocuments(user.getPrincipalId(), c1); Collection<UserOptions> allUserOptions_after = userOptionsService.findByWorkflowUser(user.getPrincipalId()); List<UserOptions> namedSearches_after = userOptionsService.findByUserQualified(user.getPrincipalId(), "DocSearch.NamedSearch.%"); // saves the "last doc search criteria" // and a pointer to the "last doc search criteria" assertEquals(allUserOptions_before.size() + 2, allUserOptions_after.size()); assertEquals(namedSearches_before.size(), namedSearches_after.size()); assertEquals("DocSearch.LastSearch.Holding0", userOptionsService.findByOptionId("DocSearch.LastSearch.Order".toString(), user.getPrincipalId()).getOptionVal()); assertEquals(marshall(c1), userOptionsService.findByOptionId("DocSearch.LastSearch.Holding0", user.getPrincipalId()).getOptionVal()); // 2nd search criteria = DocumentSearchCriteria.Builder.create(); criteria.setTitle("*IN-CFSG*"); criteria.setDateCreatedFrom(DateTime.now().minus(Years.ONE)); // otherwise one is set for us DocumentSearchCriteria c2 = criteria.build(); results = docSearchService.lookupDocuments(user.getPrincipalId(), c2); // still only 2 more user options assertEquals(allUserOptions_before.size() + 2, allUserOptions_after.size()); assertEquals(namedSearches_before.size(), namedSearches_after.size()); assertEquals("DocSearch.LastSearch.Holding1,DocSearch.LastSearch.Holding0", userOptionsService.findByOptionId("DocSearch.LastSearch.Order", user.getPrincipalId()).getOptionVal()); assertEquals(marshall(c1), userOptionsService.findByOptionId("DocSearch.LastSearch.Holding0", user.getPrincipalId()).getOptionVal()); assertEquals(marshall(c2), userOptionsService.findByOptionId("DocSearch.LastSearch.Holding1", user.getPrincipalId()).getOptionVal()); } /** * Tests that performing a named search automatically saves the last search criteria as well as named search */ @Test public void testNamedDocSearchPersistence() throws Exception { Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("bmcgough"); Collection<UserOptions> allUserOptions_before = userOptionsService.findByWorkflowUser(user.getPrincipalId()); List<UserOptions> namedSearches_before = userOptionsService.findByUserQualified(user.getPrincipalId(), "DocSearch.NamedSearch.%"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setTitle("*IN"); criteria.setSaveName("bytitle"); criteria.setDateCreatedFrom(DateTime.now().minus(Years.ONE)); // otherwise one is set for us DocumentSearchCriteria c1 = criteria.build(); DocumentSearchResults results = docSearchService.lookupDocuments(user.getPrincipalId(), c1); Collection<UserOptions> allUserOptions_after = userOptionsService.findByWorkflowUser(user.getPrincipalId()); List<UserOptions> namedSearches_after = userOptionsService.findByUserQualified(user.getPrincipalId(), "DocSearch.NamedSearch.%"); assertEquals(allUserOptions_before.size() + 1, allUserOptions_after.size()); assertEquals(namedSearches_before.size() + 1, namedSearches_after.size()); assertEquals(marshall(c1), userOptionsService.findByOptionId("DocSearch.NamedSearch." + criteria.getSaveName(), user.getPrincipalId()).getOptionVal()); // second search criteria = DocumentSearchCriteria.Builder.create(); criteria.setTitle("*IN"); criteria.setSaveName("bytitle2"); criteria.setDateCreatedFrom(DateTime.now().minus(Years.ONE)); // otherwise one is set for us DocumentSearchCriteria c2 = criteria.build(); results = docSearchService.lookupDocuments(user.getPrincipalId(), c2); allUserOptions_after = userOptionsService.findByWorkflowUser(user.getPrincipalId()); namedSearches_after = userOptionsService.findByUserQualified(user.getPrincipalId(), "DocSearch.NamedSearch.%"); // saves a second named search assertEquals(allUserOptions_before.size() + 2, allUserOptions_after.size()); assertEquals(namedSearches_before.size() + 2, namedSearches_after.size()); assertEquals(marshall(c2), userOptionsService.findByOptionId("DocSearch.NamedSearch." + criteria.getSaveName(), user.getPrincipalId()).getOptionVal()); } protected static String marshall(DocumentSearchCriteria criteria) throws Exception { return DocumentSearchInternalUtils.marshalDocumentSearchCriteria(criteria); } @Test public void testDocSearch_criteriaModified() throws Exception { String principalId = getPrincipalId("ewestfal"); // if no criteria is specified, the dateCreatedFrom is defaulted to today DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); DocumentSearchResults results = docSearchService.lookupDocuments(principalId, criteria.build()); assertTrue("criteria should have been modified", results.isCriteriaModified()); assertNull("original date created from should have been null", criteria.getDateCreatedFrom()); assertNotNull("modified date created from should be non-null", results.getCriteria().getDateCreatedFrom()); assertEquals("Criteria date minus today's date should equal the constant value", KewApiConstants.DOCUMENT_SEARCH_NO_CRITERIA_CREATE_DATE_DAYS_AGO.intValue(), getDifferenceInDays(results.getCriteria().getDateCreatedFrom())); // now set some attributes which should still result in modified criteria since they don't count toward // determining if the criteria is empty or not criteria.setMaxResults(new Integer(50)); criteria.setSaveName("myRadSearch"); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertTrue("criteria should have been modified", results.isCriteriaModified()); assertNotNull("modified date created from should be non-null", results.getCriteria().getDateCreatedFrom()); // now set the title, when only title is specified, date created from is defaulted criteria.setTitle("My rad title search!"); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertTrue("criteria should have been modified", results.isCriteriaModified()); assertNotNull("modified date created from should be non-null", results.getCriteria().getDateCreatedFrom()); assertEquals("Criteria date minus today's date should equal the constant value", Math.abs(KewApiConstants.DOCUMENT_SEARCH_DOC_TITLE_CREATE_DATE_DAYS_AGO.intValue()), getDifferenceInDays(results.getCriteria().getDateCreatedFrom())); // now set another field on the criteria, modification should *not* occur criteria.setApplicationDocumentId("12345"); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertFalse("criteria should *not* have been modified", results.isCriteriaModified()); assertNull("modified date created from should still be null", results.getCriteria().getDateCreatedFrom()); assertEquals("both criterias should be equal", criteria.build(), results.getCriteria()); } /** * Test for https://test.kuali.org/jira/browse/KULRICE-1968 - Document search fails when users are missing * Tests that we can safely search on docs whose initiator no longer exists in the identity management system * This test searches by doc type name criteria. * @throws Exception */ @Test public void testDocSearch_MissingInitiator() throws Exception { String documentTypeName = "SearchDocType"; DocumentType docType = ((DocumentTypeService)KEWServiceLocator.getService(KEWServiceLocator.DOCUMENT_TYPE_SERVICE)).findByName(documentTypeName); String userNetworkId = "arh14"; // route a document to enroute and route one to final WorkflowDocument workflowDocument = WorkflowDocumentFactory.createDocument(getPrincipalId(userNetworkId), documentTypeName); workflowDocument.setTitle("testDocSearch_MissingInitiator"); workflowDocument.route("routing this document."); // verify the document is enroute for jhopf workflowDocument = WorkflowDocumentFactory.loadDocument(getPrincipalId("jhopf"),workflowDocument.getDocumentId()); assertTrue(workflowDocument.isEnroute()); assertTrue(workflowDocument.isApprovalRequested()); // now nuke the initiator... new JdbcTemplate(TestHarnessServiceLocator.getDataSource()).execute("update " + KREW_DOC_HDR_T + " set " + INITIATOR_COL + " = 'bogus user' where DOC_HDR_ID = " + workflowDocument.getDocumentId()); Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("jhopf"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName(documentTypeName); DocumentSearchResults results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); assertEquals("Search returned invalid number of documents", 1, results.getSearchResults().size()); } /** * Test for https://test.kuali.org/jira/browse/KULRICE-1968 - Tests that we get an error if we try and search on an initiator that doesn't exist in the IDM system * @throws Exception */ @Test public void testDocSearch_SearchOnMissingInitiator() throws Exception { String documentTypeName = "SearchDocType"; DocumentType docType = ((DocumentTypeService)KEWServiceLocator.getService(KEWServiceLocator.DOCUMENT_TYPE_SERVICE)).findByName(documentTypeName); String userNetworkId = "arh14"; // route a document to enroute and route one to final WorkflowDocument workflowDocument = WorkflowDocumentFactory.createDocument(getPrincipalId(userNetworkId), documentTypeName); workflowDocument.setTitle("testDocSearch_MissingInitiator"); workflowDocument.route("routing this document."); // verify the document is enroute for jhopf workflowDocument = WorkflowDocumentFactory.loadDocument(getPrincipalId("jhopf"),workflowDocument.getDocumentId()); assertTrue(workflowDocument.isEnroute()); assertTrue(workflowDocument.isApprovalRequested()); // now nuke the initiator... new JdbcTemplate(TestHarnessServiceLocator.getDataSource()).execute("update " + KREW_DOC_HDR_T + " set " + INITIATOR_COL + " = 'bogus user' where DOC_HDR_ID = " + workflowDocument.getDocumentId()); Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName("jhopf"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setInitiatorPrincipalName("bogus user"); DocumentSearchResults results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); int size = results.getSearchResults().size(); assertTrue("Searching by an invalid initiator should return nothing", size == 0); } @Test public void testDocSearch_RouteNodeName() throws Exception { loadXmlFile("DocSearchTest_RouteNode.xml"); String documentTypeName = "SearchDocType_RouteNodeTest"; DocumentType docType = ((DocumentTypeService)KEWServiceLocator.getService(KEWServiceLocator.DOCUMENT_TYPE_SERVICE)).findByName(documentTypeName); String userNetworkId = "rkirkend"; // route a document to enroute and route one to final WorkflowDocument workflowDocument = WorkflowDocumentFactory.createDocument(getPrincipalId(userNetworkId), documentTypeName); workflowDocument.setTitle("Routing style"); workflowDocument.route("routing this document."); // verify the document is enroute for jhopf workflowDocument = WorkflowDocumentFactory.loadDocument(getPrincipalId("jhopf"),workflowDocument.getDocumentId()); assertTrue(workflowDocument.isEnroute()); assertTrue(workflowDocument.isApprovalRequested()); workflowDocument.approve(""); workflowDocument = WorkflowDocumentFactory.loadDocument(getPrincipalId("jhopf"),workflowDocument.getDocumentId()); assertTrue(workflowDocument.isFinal()); workflowDocument = WorkflowDocumentFactory.createDocument(getPrincipalId(userNetworkId), documentTypeName); workflowDocument.setTitle("Routing style"); workflowDocument.route("routing this document."); // verify the document is enroute for jhopf workflowDocument = WorkflowDocumentFactory.loadDocument(getPrincipalId("jhopf"),workflowDocument.getDocumentId()); assertTrue(workflowDocument.isEnroute()); assertTrue(workflowDocument.isApprovalRequested()); Person user = KimApiServiceLocator.getPersonService().getPersonByPrincipalName(userNetworkId); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName(documentTypeName); DocumentSearchResults results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); assertEquals("Search returned invalid number of documents", 2, results.getSearchResults().size()); criteria.setRouteNodeName(getRouteNodeForSearch(documentTypeName,workflowDocument.getNodeNames())); criteria.setRouteNodeLookupLogic(RouteNodeLookupLogic.EXACTLY); results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); assertEquals("Search returned invalid number of documents", 1, results.getSearchResults().size()); // load the document type again to change the route node ids loadXmlFile("DocSearchTest_RouteNode.xml"); workflowDocument = WorkflowDocumentFactory.loadDocument(getPrincipalId("jhopf"),workflowDocument.getDocumentId()); assertTrue(workflowDocument.isEnroute()); assertTrue(workflowDocument.isApprovalRequested()); criteria.setRouteNodeName(getRouteNodeForSearch(documentTypeName, workflowDocument.getNodeNames())); results = docSearchService.lookupDocuments(user.getPrincipalId(), criteria.build()); assertEquals("Search returned invalid number of documents", 1, results.getSearchResults().size()); } private String getRouteNodeForSearch(String documentTypeName, Set<String> nodeNames) { assertEquals(1, nodeNames.size()); String expectedNodeName = nodeNames.iterator().next(); List routeNodes = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(KEWServiceLocator.getDocumentTypeService().findByName(documentTypeName), true); for (Iterator iterator = routeNodes.iterator(); iterator.hasNext();) { RouteNode node = (RouteNode) iterator.next(); if (expectedNodeName.equals(node.getRouteNodeName())) { return node.getRouteNodeName(); } } return null; } @Test public void testGetNamedDocSearches() throws Exception { List namedSearches = docSearchService.getNamedSearches(getPrincipalId("bmcgough")); assertNotNull(namedSearches); } private static int getDifferenceInDays(DateTime compareDate) { return Days.daysBetween(compareDate, new DateTime()).getDays(); } /** * Tests searching against document search attrs * @throws Exception */ @Test public void testDocSearchWithAttributes() throws Exception { String[] docIds = routeTestDocs(); String principalId = getPrincipalId("bmcgough"); DocumentSearchCriteria.Builder builder = DocumentSearchCriteria.Builder.create(); builder.setDocumentTypeName("SearchDocType"); builder.setSaveName("testDocSearchWithAttributes"); Map<String, List<String>> docAttrs = new HashMap<String, List<String>>(); docAttrs.put(TestXMLSearchableAttributeString.SEARCH_STORAGE_KEY, Arrays.asList(new String[]{TestXMLSearchableAttributeString.SEARCH_STORAGE_VALUE})); builder.setDocumentAttributeValues(docAttrs); DocumentSearchResults results = docSearchService.lookupDocuments(principalId, builder.build()); assertEquals(docIds.length, results.getSearchResults().size()); DocumentSearchCriteria loaded = docSearchService.getNamedSearchCriteria(principalId, builder.getSaveName()); assertNotNull(loaded); assertEquals(docAttrs, loaded.getDocumentAttributeValues()); // re-run saved search results = docSearchService.lookupDocuments(principalId, loaded); assertEquals(docIds.length, results.getSearchResults().size()); } /** * Tests the usage of wildcards on the regular document search attributes. * @throws Exception */ @Test public void testDocSearch_WildcardsOnRegularAttributes() throws Exception { // TODO: Add some wildcard testing for the document type attribute once wildcards are usable with it. // Route some test documents. String[] docIds = routeTestDocs(); String principalId = getPrincipalId("bmcgough"); DocumentSearchCriteria.Builder criteria = null; DocumentSearchResults results = null; /** * BEGIN - commenting out until we can resolve issues with person service not returning proper persons based on wildcards and various things */ // Test the wildcards on the initiator attribute. String[] searchStrings = {"!quickstart", "!quickstart&&!rkirkend", "!admin", "user1", "quickstart|bmcgough", "admin|rkirkend", ">bmcgough", ">=rkirkend", "<bmcgough", "<=quickstart", ">bmcgough&&<=rkirkend", "<rkirkend&&!bmcgough", "?mc?oug?", "*t", "*i?k*", "*", "!quick*", "!*g*&&!*k*", "quickstart..rkirkend"}; int[] expectedResults = {2, 1, 3, 0, 2, 1, 2, 1, 0, 2, 2, 1, 1, 1, 2, 3, 2, 0, 2/*1*/}; for (int i = 0; i < searchStrings.length; i++) { criteria = DocumentSearchCriteria.Builder.create(); criteria.setInitiatorPrincipalName(searchStrings[i]); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals("Initiator search at index " + i + " retrieved the wrong number of documents.", expectedResults[i], results.getSearchResults().size()); } // Test the wildcards on the approver attribute. searchStrings = new String[] {"jhopf","!jhopf", ">jhopf", "<jjopf", ">=quickstart", "<=jhopf", "jhope..jhopg", "?hopf", "*i*", "!*f", "j*"}; expectedResults = new int[] {1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1}; for (int i = 0; i < searchStrings.length; i++) { criteria = DocumentSearchCriteria.Builder.create(); criteria.setApproverPrincipalName(searchStrings[i]); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals("Approver search at index " + i + " retrieved the wrong number of documents.", expectedResults[i], results.getSearchResults().size()); } // Test the wildcards on the viewer attribute. searchStrings = new String[] {"jhopf","!jhopf", ">jhopf", "<jjopf", ">=quickstart", "<=jhopf", "jhope..jhopg", "?hopf", "*i*", "!*f", "j*"}; expectedResults = new int[] {3, 0, 0, 3, 0, 3, 3, 3, 0, 0, 3}; for (int i = 0; i < searchStrings.length; i++) { criteria = DocumentSearchCriteria.Builder.create(); criteria.setViewerPrincipalName(searchStrings[i]); results = docSearchService.lookupDocuments(principalId, criteria.build()); if(expectedResults[i] != results.getSearchResults().size()){ assertEquals("Viewer search at index " + i + " retrieved the wrong number of documents.", expectedResults[i], results.getSearchResults().size()); } } /** * END */ // Test the wildcards on the document/notification ID attribute. The string wildcards should work, since the doc ID is not a string. searchStrings = new String[] {"!"+docIds[0], docIds[1]+"|"+docIds[2], "<="+docIds[1], ">="+docIds[2], "<"+docIds[0]+"&&>"+docIds[2], ">"+docIds[1], "<"+docIds[2]+"&&!"+docIds[0], docIds[0]+".."+docIds[2], "?"+docIds[1]+"*", "?"+docIds[1].substring(1)+"*", "?9*7"}; expectedResults = new int[] {2, 2, 2, 1, 0, 1, 1, 3, 0, 1, 0}; for (int i = 0; i < searchStrings.length; i++) { criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentId(searchStrings[i]); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals("Doc ID search at index " + i + " retrieved the wrong number of documents.", expectedResults[i], results.getSearchResults().size()); } // Test the wildcards on the application document/notification ID attribute. The string wildcards should work, since the app doc ID is a string. searchStrings = new String[] {"6543", "5432|4321", ">4321", "<=5432", ">=6543", "<3210", "!3210", "!5432", "!4321!5432", ">4321&&!6543", "*5?3*", "*", "?3?1", "!*43*", "!???2", ">43*1", "<=5432&&!?32?", "5432..6543"}; expectedResults = new int[] {1, 2, 2, 2, 1, 0, 3, 2, 1, 1, 2, 3, 1, 0, 2, 3, 1, 2/*1*/}; for (int i = 0; i < searchStrings.length; i++) { criteria = DocumentSearchCriteria.Builder.create(); criteria.setApplicationDocumentId(searchStrings[i]); results = docSearchService.lookupDocuments(principalId, criteria.build()); if(expectedResults[i] != results.getSearchResults().size()){ assertEquals("App doc ID search at index " + i + " retrieved the wrong number of documents.", expectedResults[i], results.getSearchResults().size()); } } // Test the wildcards on the title attribute. searchStrings = new String[] {"Some New Document", "Document Number 2|The New Doc", "!The New Doc", "!Some New Document!Document Number 2", "!The New Doc&&!Some New Document", ">Document Number 2", "<=Some New Document", ">=The New Doc&&<Some New Document", ">A New Doc", "<Some New Document|The New Doc", ">=Document Number 2&&!Some New Document", "*Docu??nt*", "*New*", "The ??? Doc", "*Doc*", "*Number*", "Some New Document..The New Doc", "Document..The", "*New*&&!*Some*", "!The ??? Doc|!*New*"}; expectedResults = new int[] {1, 2, 2, 1, 1, 2, 2, 0, 3, 2, 2, 2, 2, 1, 3, 1, 2/*1*/, 2, 1, 2}; for (int i = 0; i < searchStrings.length; i++) { criteria = DocumentSearchCriteria.Builder.create(); criteria.setTitle(searchStrings[i]); results = docSearchService.lookupDocuments(principalId, criteria.build()); if(expectedResults[i] != results.getSearchResults().size()){ assertEquals("Doc title search at index " + i + " retrieved the wrong number of documents.", expectedResults[i], results.getSearchResults().size()); } } } @Test public void testAdditionalDocumentTypesCriteria() throws Exception { String[] docIds = routeTestDocs(); String docId2 = routeTestDoc2(); String principalId = getPrincipalId("bmcgough"); DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); // TODO finish this test DocumentSearchResults results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(3, results.getSearchResults().size()); criteria.setDocumentTypeName("SearchDocType2"); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(1, results.getSearchResults().size()); criteria.getAdditionalDocumentTypeNames().add("SearchDocType"); results = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals(4, results.getSearchResults().size()); } /** * Tests searching on document status and document status category */ @Test public void testDocumentStatusSearching() { String dt = "SearchDocType"; String pid = getPrincipalIdForName("quickstart"); WorkflowDocument initiated = WorkflowDocumentFactory.createDocument(pid, dt); WorkflowDocument saved = WorkflowDocumentFactory.createDocument(pid, dt); saved.saveDocument("saved"); assertEquals(DocumentStatus.SAVED, saved.getStatus()); WorkflowDocument enroute = WorkflowDocumentFactory.createDocument(pid, dt); enroute.route("routed"); assertEquals(DocumentStatus.ENROUTE, enroute.getStatus()); WorkflowDocument exception = WorkflowDocumentFactory.createDocument(pid, dt); exception.route("routed"); exception.placeInExceptionRouting("placed in exception routing"); assertEquals(DocumentStatus.EXCEPTION, exception.getStatus()); // no acks on this doc, can't test? //WorkflowDocument processed = WorkflowDocumentFactory.createDocument(pid, dt); //processed.route("routed"); WorkflowDocument finl = WorkflowDocumentFactory.createDocument(pid, dt); finl.route("routed"); finl.switchPrincipal(getPrincipalId("jhopf")); finl.approve("approved"); assertEquals(DocumentStatus.FINAL, finl.getStatus()); WorkflowDocument canceled = WorkflowDocumentFactory.createDocument(pid, dt); canceled.cancel("canceled"); assertEquals(DocumentStatus.CANCELED, canceled.getStatus()); WorkflowDocument disapproved = WorkflowDocumentFactory.createDocument(pid, dt); disapproved.route("routed"); disapproved.switchPrincipal(getPrincipalId("jhopf")); RequestedActions ra = disapproved.getRequestedActions(); disapproved.disapprove("disapproved"); assertEquals(DocumentStatus.DISAPPROVED, disapproved.getStatus()); assertDocumentStatuses(dt, pid, 1, 1, 1, 1, 0, 1, 1, 1); } /** * Asserts that documents are present in the given statuses, including document status categories (this requires that * no docs are in the system prior to routing of the test docs) */ protected void assertDocumentStatuses(String documentType, String principalId, int initiated, int saved, int enroute, int exception, int processed, int finl, int canceled, int disapproved) { assertDocumentStatus(documentType, principalId, DocumentStatus.INITIATED, initiated); assertDocumentStatus(documentType, principalId, DocumentStatus.SAVED, saved); assertDocumentStatus(documentType, principalId, DocumentStatus.ENROUTE, enroute); assertDocumentStatus(documentType, principalId, DocumentStatus.EXCEPTION, exception); assertDocumentStatusCategory(documentType, principalId, DocumentStatusCategory.PENDING, initiated + saved + enroute + exception); assertDocumentStatus(documentType, principalId, DocumentStatus.PROCESSED, processed); assertDocumentStatus(documentType, principalId, DocumentStatus.FINAL, finl); assertDocumentStatusCategory(documentType, principalId, DocumentStatusCategory.SUCCESSFUL, processed + finl); assertDocumentStatus(documentType, principalId, DocumentStatus.CANCELED, canceled); assertDocumentStatus(documentType, principalId, DocumentStatus.DISAPPROVED, finl); assertDocumentStatusCategory(documentType, principalId, DocumentStatusCategory.UNSUCCESSFUL, canceled + disapproved); } /** * Asserts that there are a certain number of docs in the given status */ protected void assertDocumentStatus(String documentType, String principalId, DocumentStatus status, int num) { DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName(documentType); criteria.setDocumentStatuses(Arrays.asList(new DocumentStatus[] { status })); DocumentSearchResults result = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals("Expected " + num + " documents in status " + status, num, result.getSearchResults().size()); } /** * Asserts that there are a certain number of docs in the given document status category */ protected void assertDocumentStatusCategory(String documentType, String principalId, DocumentStatusCategory status, int num) { DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName(documentType); criteria.setDocumentStatusCategories(Arrays.asList(new DocumentStatusCategory[]{status})); DocumentSearchResults result = docSearchService.lookupDocuments(principalId, criteria.build()); assertEquals("Expected " + num + " documents in status category " + status, num, result.getSearchResults().size()); } private static final class TestDocData { private TestDocData() { throw new IllegalStateException("leave me alone"); } static String docTypeName = "SearchDocType"; static String[] principalNames = {"bmcgough", "quickstart", "rkirkend"}; static String[] titles = {"The New Doc", "Document Number 2", "Some New Document"}; static String[] appDocIds = {"6543", "5432", "4321"}; static String[] appDocStatuses = {"Submitted", "Pending", "Completed"}; static String[] approverNames = {null, "jhopf", null}; } /** * Routes some test docs for searching * @return String[] of doc ids */ protected String[] routeTestDocs() { // Route some test documents. String[] docIds = new String[TestDocData.titles.length]; for (int i = 0; i < TestDocData.titles.length; i++) { WorkflowDocument workflowDocument = WorkflowDocumentFactory.createDocument( getPrincipalId(TestDocData.principalNames[i]), TestDocData.docTypeName); workflowDocument.setTitle(TestDocData.titles[i]); workflowDocument.setApplicationDocumentId(TestDocData.appDocIds[i]); workflowDocument.route("routing this document."); docIds[i] = workflowDocument.getDocumentId(); if (TestDocData.approverNames[i] != null) { workflowDocument.switchPrincipal(getPrincipalId(TestDocData.approverNames[i])); workflowDocument.approve("approving this document."); } workflowDocument.setApplicationDocumentStatus(TestDocData.appDocStatuses[i]); workflowDocument.saveDocumentData(); } return docIds; } /** * "Saves" a single instance of a "SearchDocType2" document and returns it's id. */ protected String routeTestDoc2() { // Route some test documents. String docTypeName = "SearchDocType2"; WorkflowDocument workflowDocument = WorkflowDocumentFactory.createDocument(getPrincipalId("ewestfal"), docTypeName); workflowDocument.setTitle("Search Doc Type 2!"); workflowDocument.saveDocument("saving the document"); return workflowDocument.getDocumentId(); } private String getPrincipalId(String principalName) { return KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(principalName).getPrincipalId(); } @Test public void testDocSearch_maxResultsCap() throws Exception { DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); int maxResultsCap = docSearchService.getMaxResultCap(criteria.build()); assertEquals(500, maxResultsCap); criteria.setMaxResults(5); int maxResultsCap1 = docSearchService.getMaxResultCap(criteria.build()); assertEquals(5, maxResultsCap1); criteria.setMaxResults(2); int maxResultsCap2 = docSearchService.getMaxResultCap(criteria.build()); assertEquals(2, maxResultsCap2); } @Test public void testDocSearch_fetchMoreIterationLimit() throws Exception { DocumentSearchCriteria.Builder criteria = DocumentSearchCriteria.Builder.create(); criteria.setDocumentTypeName("SearchDocType"); int fetchIterationLimit = docSearchService.getFetchMoreIterationLimit(); assertEquals(10, fetchIterationLimit); } }
/* * Copyright 2011-2013 David Karnok * * 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 hu.akarnokd.reactive4java.base; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * A class representing a value, an exception or nothing. * These classes are used by <code>materialize</code> and <code>dematerialize</code> * operators. * @author akarnokd * @param <T> the type of the contained object */ public abstract class Option<T> { /** @return query for the value. */ public abstract T value(); /** * @return true if this option has a value (not error). * @since 0.97 */ public boolean hasValue() { return false; } /** * @return true if this option has an error (not value). * @since 0.97 */ public boolean hasError() { return false; } /** * @return true if this option is empty. * @since 0.97 */ public boolean isNone() { return false; } /** * The helper class representing an option holding nothing. * @author akarnokd * * @param <T> the type of the nothing - not really used but required by the types */ public static final class None<T> extends Option<T> { /** Single instance! */ private None() { } @Override public T value() { throw new UnsupportedOperationException(); } @Override public boolean isNone() { return true; } @Override public String toString() { return "None"; } @Override public boolean equals(Object obj) { return obj == NONE; } @Override public int hashCode() { return super.hashCode(); } } /** * A helper class representing an option holding something of T. * @author akarnokd * * @param <T> the type of the contained stuff */ public static final class Some<T> extends Option<T> { /** The value that is hold by this option. */ private final T value; /** * Construct the some with a value. * @param value the value. */ private Some(T value) { this.value = value; } @Override public T value() { return value; } @Override public boolean hasValue() { return true; } @Override public String toString() { return "Some with " + value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Some<?> other = (Some<?>)obj; if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } } /** * Class representing an error option. * Calling value on this will throw a RuntimeException which wraps * the original exception. * @author akarnokd, 2011.01.30. * @param <T> the element type */ public static final class Error<T> extends Option<T> { /** The exception held. */ @Nonnull private final Throwable ex; /** * Constructor. * @param ex the exception to hold */ private Error(@Nonnull Throwable ex) { this.ex = ex; } @Override public T value() { if (ex instanceof RuntimeException) { throw (RuntimeException)ex; } throw new RuntimeException(ex); } @Override public boolean hasError() { return true; } @Override public String toString() { return "Error of " + ex.toString(); } /** @return the contained throwable value. */ @Nonnull public Throwable error() { return ex; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((ex == null) ? 0 : ex.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Error<?> other = (Error<?>)obj; if (ex == null) { if (other.ex != null) { return false; } } else if (!ex.equals(other.ex)) { return false; } return true; } } /** The single instance of the nothingness. */ @Nonnull private static final None<Void> NONE = new None<Void>(); /** * Returns a none of T. * @param <T> the type of the T * @return the None of T */ @SuppressWarnings("unchecked") @Nonnull public static <T> None<T> none() { return (None<T>)NONE; } /** * Create a new Some instance with the supplied value. * @param <T> the value type * @param value the initial value * @return the some object */ @Nonnull public static <T> Some<T> some(T value) { return new Some<T>(value); } /** * Create an error instance with the given Throwable. * @param <T> the element type, irrelevant * @param t the throwable * @return the error instance */ @Nonnull public static <T> Error<T> error(@Nonnull Throwable t) { return new Error<T>(t); } /** * Returns true if the option is of type Error. * @param o the option * @return true if the option is of type Error. */ public static boolean isError(@Nullable Option<?> o) { return o != null && o.hasError(); } /** * Returns true if the option is of type None. * @param o the option * @return true if the option is of type None. */ public static boolean isNone(@Nullable Option<?> o) { return o == NONE; } /** * Returns true if the option is of type Some. * @param o the option * @return true if the option is of type Some. */ public static boolean isSome(@Nullable Option<?> o) { return o != null && o.hasValue(); } /** * Extracts the error value from the option. * It throws an IllegalArgumentException if o is not an <code>Error</code> instance. * @param o the option to get the error from * @return the inner throwable */ @Nonnull public static Throwable getError(Option<?> o) { if (isError(o)) { return ((Error<?>)o).error(); } throw new IllegalArgumentException("o is not an error"); } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. /** * DescribeRegions.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.1 Built on : Oct 19, 2009 (10:59:34 EDT) */ package com.amazon.ec2; /** * DescribeRegions bean class */ public class DescribeRegions implements org.apache.axis2.databinding.ADBBean{ public static final javax.xml.namespace.QName MY_QNAME = new javax.xml.namespace.QName( "http://ec2.amazonaws.com/doc/2010-11-15/", "DescribeRegions", "ns1"); private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://ec2.amazonaws.com/doc/2010-11-15/")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for DescribeRegions */ protected com.amazon.ec2.DescribeRegionsType localDescribeRegions ; /** * Auto generated getter method * @return com.amazon.ec2.DescribeRegionsType */ public com.amazon.ec2.DescribeRegionsType getDescribeRegions(){ return localDescribeRegions; } /** * Auto generated setter method * @param param DescribeRegions */ public void setDescribeRegions(com.amazon.ec2.DescribeRegionsType param){ this.localDescribeRegions=param; } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,MY_QNAME){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { DescribeRegions.this.serialize(MY_QNAME,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( MY_QNAME,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ //We can safely assume an element has only one type associated with it if (localDescribeRegions==null){ throw new org.apache.axis2.databinding.ADBException("Property cannot be null!"); } localDescribeRegions.serialize(MY_QNAME,factory,xmlWriter); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ //We can safely assume an element has only one type associated with it return localDescribeRegions.getPullParser(MY_QNAME); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static DescribeRegions parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ DescribeRegions object = new DescribeRegions(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); while(!reader.isEndElement()) { if (reader.isStartElement() ){ if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/","DescribeRegions").equals(reader.getName())){ object.setDescribeRegions(com.amazon.ec2.DescribeRegionsType.Factory.parse(reader)); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } } else { reader.next(); } } // end of while loop } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
package com.andrew.apolloMod.helpers.utils; import java.util.Arrays; import java.util.Formatter; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import android.app.Activity; import android.app.SearchManager; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.RemoteException; import android.provider.BaseColumns; import android.provider.MediaStore; import android.provider.MediaStore.Audio; import android.provider.MediaStore.Audio.AlbumColumns; import android.provider.MediaStore.Audio.ArtistColumns; import android.provider.MediaStore.Audio.AudioColumns; import android.provider.MediaStore.Audio.Genres; import android.provider.MediaStore.Audio.GenresColumns; import android.provider.MediaStore.Audio.Playlists; import android.provider.MediaStore.Audio.PlaylistsColumns; import android.provider.MediaStore.MediaColumns; import android.provider.Settings; import android.widget.ImageButton; import android.widget.Toast; import com.andrew.apolloMod.IApolloService; import com.andrew.apolloMod.R; import com.andrew.apolloMod.service.ApolloService; import com.andrew.apolloMod.service.ServiceBinder; import com.andrew.apolloMod.service.ServiceToken; import static com.andrew.apolloMod.Constants.EXTERNAL; import static com.andrew.apolloMod.Constants.GENRES_DB; import static com.andrew.apolloMod.Constants.PLAYLIST_NAME_FAVORITES; import static com.andrew.apolloMod.Constants.PLAYLIST_NEW; import static com.andrew.apolloMod.Constants.PLAYLIST_QUEUE; /** * Various methods used to help with specific music statements */ public class MusicUtils { // Used to make number of albums/songs/time strings private final static StringBuilder sFormatBuilder = new StringBuilder(); private final static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault()); public static IApolloService mService = null; private static HashMap<Context, ServiceBinder> sConnectionMap = new HashMap<Context, ServiceBinder>(); private final static long[] sEmptyList = new long[0]; private static final Object[] sTimeArgs = new Object[5]; private static ContentValues[] sContentValuesCache = null; /** * @param context * @return */ public static ServiceToken bindToService(Activity context) { return bindToService(context, null); } /** * @param context * @param callback * @return */ public static ServiceToken bindToService(Context context, ServiceConnection callback) { Activity realActivity = ((Activity)context).getParent(); if (realActivity == null) { realActivity = (Activity)context; } ContextWrapper cw = new ContextWrapper(realActivity); cw.startService(new Intent(cw, ApolloService.class)); ServiceBinder sb = new ServiceBinder(callback); if (cw.bindService((new Intent()).setClass(cw, ApolloService.class), sb, 0)) { sConnectionMap.put(cw, sb); return new ServiceToken(cw); } return null; } /** * @param token */ public static void unbindFromService(ServiceToken token) { if (token == null) { return; } ContextWrapper cw = token.mWrappedContext; ServiceBinder sb = sConnectionMap.remove(cw); if (sb == null) { return; } cw.unbindService(sb); if (sConnectionMap.isEmpty()) { mService = null; } } /** * @param context * @param numalbums * @param numsongs * @param isUnknown * @return a string based on the number of albums for an artist or songs for * an album */ public static String makeAlbumsLabel(Context mContext, int numalbums, int numsongs, boolean isUnknown) { StringBuilder songs_albums = new StringBuilder(); Resources r = mContext.getResources(); if (isUnknown) { String f = r.getQuantityText(R.plurals.Nsongs, numsongs).toString(); sFormatBuilder.setLength(0); sFormatter.format(f, Integer.valueOf(numsongs)); songs_albums.append(sFormatBuilder); } else { String f = r.getQuantityText(R.plurals.Nalbums, numalbums).toString(); sFormatBuilder.setLength(0); sFormatter.format(f, Integer.valueOf(numalbums)); songs_albums.append(sFormatBuilder); songs_albums.append("\n"); } return songs_albums.toString(); } /** * @param mContext * @return */ public static int getCardId(Context mContext) { ContentResolver res = mContext.getContentResolver(); Cursor c = res.query(Uri.parse("content://media/external/fs_id"), null, null, null, null); int id = -1; if (c != null) { c.moveToFirst(); id = c.getInt(0); c.close(); } return id; } /** * @param context * @param uri * @param projection * @param selection * @param selectionArgs * @param sortOrder * @param limit * @return */ public static Cursor query(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, int limit) { try { ContentResolver resolver = context.getContentResolver(); if (resolver == null) { return null; } if (limit > 0) { uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build(); } return resolver.query(uri, projection, selection, selectionArgs, sortOrder); } catch (UnsupportedOperationException ex) { return null; } } /** * @param context * @param uri * @param projection * @param selection * @param selectionArgs * @param sortOrder * @return */ public static Cursor query(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { return query(context, uri, projection, selection, selectionArgs, sortOrder, 0); } /** * @param context * @param cursor */ public static void shuffleAll(Context context, Cursor cursor) { playAll(context, cursor, 0, true); } /** * @param context * @param cursor */ public static void playAll(Context context, Cursor cursor) { playAll(context, cursor, 0, false); } /** * @param context * @param cursor * @param position */ public static void playAll(Context context, Cursor cursor, int position) { playAll(context, cursor, position, false); } /** * @param context * @param list * @param position */ public static void playAll(Context context, long[] list, int position) { playAll(context, list, position, false); } /** * @param context * @param cursor * @param position * @param force_shuffle */ private static void playAll(Context context, Cursor cursor, int position, boolean force_shuffle) { long[] list = getSongListForCursor(cursor); playAll(context, list, position, force_shuffle); } /** * @param cursor * @return */ public static long[] getSongListForCursor(Cursor cursor) { if (cursor == null) { return sEmptyList; } int len = cursor.getCount(); long[] list = new long[len]; cursor.moveToFirst(); int colidx = -1; try { colidx = cursor.getColumnIndexOrThrow(Audio.Playlists.Members.AUDIO_ID); } catch (IllegalArgumentException ex) { colidx = cursor.getColumnIndexOrThrow(BaseColumns._ID); } for (int i = 0; i < len; i++) { list[i] = cursor.getLong(colidx); cursor.moveToNext(); } return list; } /** * @param context * @param list * @param position * @param force_shuffle */ private static void playAll(Context context, long[] list, int position, boolean force_shuffle) { if (list.length == 0 || mService == null) { return; } try { if (force_shuffle) { mService.setShuffleMode(ApolloService.SHUFFLE_NORMAL); } long curid = mService.getAudioId(); int curpos = mService.getQueuePosition(); if (position != -1 && curpos == position && curid == list[position]) { // The selected file is the file that's currently playing; // figure out if we need to restart with a new playlist, // or just launch the playback activity. long[] playlist = mService.getQueue(); if (Arrays.equals(list, playlist)) { // we don't need to set a new list, but we should resume // playback if needed mService.play(); return; } } if (position < 0) { position = 0; } mService.open(list, force_shuffle ? -1 : position); mService.play(); } catch (RemoteException ex) { ex.printStackTrace(); } } /** * @return */ public static long[] getQueue() { if (mService == null) return sEmptyList; try { return mService.getQueue(); } catch (RemoteException e) { e.printStackTrace(); } return sEmptyList; } /** * @param context * @param name * @param def * @return number of weeks used to create the Recent tab */ public static int getIntPref(Context context, String name, int def) { SharedPreferences prefs = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE); return prefs.getInt(name, def); } /** * @param context * @param id * @return */ public static long[] getSongListForArtist(Context context, long id) { final String[] projection = new String[] { BaseColumns._ID }; String selection = AudioColumns.ARTIST_ID + "=" + id + " AND " + AudioColumns.IS_MUSIC + "=1"; String sortOrder = AudioColumns.ALBUM_KEY + "," + AudioColumns.TRACK; Uri uri = Audio.Media.EXTERNAL_CONTENT_URI; Cursor cursor = query(context, uri, projection, selection, null, sortOrder); if (cursor != null) { long[] list = getSongListForCursor(cursor); cursor.close(); return list; } return sEmptyList; } /** * @param context * @param id * @return */ public static long[] getSongListForAlbum(Context context, long id) { final String[] projection = new String[] { BaseColumns._ID }; String selection = AudioColumns.ALBUM_ID + "=" + id + " AND " + AudioColumns.IS_MUSIC + "=1"; String sortOrder = AudioColumns.TRACK; Uri uri = Audio.Media.EXTERNAL_CONTENT_URI; Cursor cursor = query(context, uri, projection, selection, null, sortOrder); if (cursor != null) { long[] list = getSongListForCursor(cursor); cursor.close(); return list; } return sEmptyList; } /** * @param context * @param id * @return */ public static long[] getSongListForGenre(Context context, long id) { String[] projection = new String[] { BaseColumns._ID }; StringBuilder selection = new StringBuilder(); selection.append(AudioColumns.IS_MUSIC + "=1"); selection.append(" AND " + MediaColumns.TITLE + "!=''"); Uri uri = Genres.Members.getContentUri(EXTERNAL, id); Cursor cursor = context.getContentResolver().query(uri, projection, selection.toString(), null, null); if (cursor != null) { long[] list = getSongListForCursor(cursor); cursor.close(); return list; } return sEmptyList; } /** * @param context * @param id * @return */ public static long[] getSongListForPlaylist(Context context, long id) { final String[] projection = new String[] { Audio.Playlists.Members.AUDIO_ID }; String sortOrder = Playlists.Members.DEFAULT_SORT_ORDER; Uri uri = Playlists.Members.getContentUri(EXTERNAL, id); Cursor cursor = query(context, uri, projection, null, null, sortOrder); if (cursor != null) { long[] list = getSongListForCursor(cursor); cursor.close(); return list; } return sEmptyList; } /** * @param context * @param name * @return */ public static long createPlaylist(Context context, String name) { if (name != null && name.length() > 0) { ContentResolver resolver = context.getContentResolver(); String[] cols = new String[] { PlaylistsColumns.NAME }; String whereclause = PlaylistsColumns.NAME + " = '" + name + "'"; Cursor cur = resolver.query(Audio.Playlists.EXTERNAL_CONTENT_URI, cols, whereclause, null, null); if (cur.getCount() <= 0) { ContentValues values = new ContentValues(1); values.put(PlaylistsColumns.NAME, name); Uri uri = resolver.insert(Audio.Playlists.EXTERNAL_CONTENT_URI, values); return Long.parseLong(uri.getLastPathSegment()); } return -1; } return -1; } /** * @param context * @return */ public static long getFavoritesId(Context context) { long favorites_id = -1; String favorites_where = PlaylistsColumns.NAME + "='" + "Favorites" + "'"; String[] favorites_cols = new String[] { BaseColumns._ID }; Uri favorites_uri = Audio.Playlists.EXTERNAL_CONTENT_URI; Cursor cursor = query(context, favorites_uri, favorites_cols, favorites_where, null, null); if (cursor.getCount() <= 0) { favorites_id = createPlaylist(context, "Favorites"); } else { cursor.moveToFirst(); favorites_id = cursor.getLong(0); cursor.close(); } return favorites_id; } /** * @param context * @param id */ public static void setRingtone(Context context, long id) { ContentResolver resolver = context.getContentResolver(); // Set the flag in the database to mark this as a ringtone Uri ringUri = ContentUris.withAppendedId(Audio.Media.EXTERNAL_CONTENT_URI, id); try { ContentValues values = new ContentValues(2); values.put(AudioColumns.IS_RINGTONE, "1"); values.put(AudioColumns.IS_ALARM, "1"); resolver.update(ringUri, values, null, null); } catch (UnsupportedOperationException ex) { // most likely the card just got unmounted return; } String[] cols = new String[] { BaseColumns._ID, MediaColumns.DATA, MediaColumns.TITLE }; String where = BaseColumns._ID + "=" + id; Cursor cursor = query(context, Audio.Media.EXTERNAL_CONTENT_URI, cols, where, null, null); try { if (cursor != null && cursor.getCount() == 1) { // Set the system setting to make this the current ringtone cursor.moveToFirst(); Settings.System.putString(resolver, Settings.System.RINGTONE, ringUri.toString()); String message = context.getString(R.string.set_as_ringtone, cursor.getString(2)); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } finally { if (cursor != null) { cursor.close(); } } } /** * @param context * @param plid */ public static void clearPlaylist(Context context, int plid) { Uri uri = Audio.Playlists.Members.getContentUri(EXTERNAL, plid); context.getContentResolver().delete(uri, null, null); return; } /** * @param context * @param ids * @param playlistid */ public static void addToPlaylist(Context context, long[] ids, long playlistid) { if (ids == null) { } else { int size = ids.length; ContentResolver resolver = context.getContentResolver(); // need to determine the number of items currently in the playlist, // so the play_order field can be maintained. String[] cols = new String[] { "count(*)" }; Uri uri = Audio.Playlists.Members.getContentUri(EXTERNAL, playlistid); Cursor cur = resolver.query(uri, cols, null, null, null); cur.moveToFirst(); int base = cur.getInt(0); cur.close(); int numinserted = 0; for (int i = 0; i < size; i += 1000) { makeInsertItems(ids, i, 1000, base); numinserted += resolver.bulkInsert(uri, sContentValuesCache); } String message = context.getResources().getQuantityString( R.plurals.NNNtrackstoplaylist, numinserted, numinserted); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } /** * @param ids * @param offset * @param len * @param base */ private static void makeInsertItems(long[] ids, int offset, int len, int base) { // adjust 'len' if would extend beyond the end of the source array if (offset + len > ids.length) { len = ids.length - offset; } // allocate the ContentValues array, or reallocate if it is the wrong // size if (sContentValuesCache == null || sContentValuesCache.length != len) { sContentValuesCache = new ContentValues[len]; } // fill in the ContentValues array with the right values for this pass for (int i = 0; i < len; i++) { if (sContentValuesCache[i] == null) { sContentValuesCache[i] = new ContentValues(); } sContentValuesCache[i].put(Playlists.Members.PLAY_ORDER, base + offset + i); sContentValuesCache[i].put(Playlists.Members.AUDIO_ID, ids[offset + i]); } } /** * Toggle favorites */ public static void toggleFavorite() { if (mService == null) return; try { mService.toggleFavorite(); } catch (RemoteException e) { e.printStackTrace(); } } /** * @param context * @param id */ public static void addToFavorites(Context context, long id) { long favorites_id; if (id < 0) { } else { ContentResolver resolver = context.getContentResolver(); String favorites_where = PlaylistsColumns.NAME + "='" + PLAYLIST_NAME_FAVORITES + "'"; String[] favorites_cols = new String[] { BaseColumns._ID }; Uri favorites_uri = Audio.Playlists.EXTERNAL_CONTENT_URI; Cursor cursor = resolver.query(favorites_uri, favorites_cols, favorites_where, null, null); if (cursor.getCount() <= 0) { favorites_id = createPlaylist(context, PLAYLIST_NAME_FAVORITES); } else { cursor.moveToFirst(); favorites_id = cursor.getLong(0); cursor.close(); } String[] cols = new String[] { Playlists.Members.AUDIO_ID }; Uri uri = Playlists.Members.getContentUri(EXTERNAL, favorites_id); Cursor cur = resolver.query(uri, cols, null, null, null); int base = cur.getCount(); cur.moveToFirst(); while (!cur.isAfterLast()) { if (cur.getLong(0) == id) return; cur.moveToNext(); } cur.close(); ContentValues values = new ContentValues(); values.put(Playlists.Members.AUDIO_ID, id); values.put(Playlists.Members.PLAY_ORDER, base + 1); resolver.insert(uri, values); } } /** * @param context * @param id * @return */ public static boolean isFavorite(Context context, long id) { long favorites_id; if (id < 0) { } else { ContentResolver resolver = context.getContentResolver(); String favorites_where = PlaylistsColumns.NAME + "='" + PLAYLIST_NAME_FAVORITES + "'"; String[] favorites_cols = new String[] { BaseColumns._ID }; Uri favorites_uri = Audio.Playlists.EXTERNAL_CONTENT_URI; Cursor cursor = resolver.query(favorites_uri, favorites_cols, favorites_where, null, null); if (cursor.getCount() <= 0) { favorites_id = createPlaylist(context, PLAYLIST_NAME_FAVORITES); } else { cursor.moveToFirst(); favorites_id = cursor.getLong(0); cursor.close(); } String[] cols = new String[] { Playlists.Members.AUDIO_ID }; Uri uri = Playlists.Members.getContentUri(EXTERNAL, favorites_id); Cursor cur = resolver.query(uri, cols, null, null, null); cur.moveToFirst(); while (!cur.isAfterLast()) { if (cur.getLong(0) == id) { cur.close(); return true; } cur.moveToNext(); } cur.close(); return false; } return false; } /** * @param context * @param id */ public static void removeFromFavorites(Context context, long id) { long favorites_id; if (id < 0) { } else { ContentResolver resolver = context.getContentResolver(); String favorites_where = PlaylistsColumns.NAME + "='" + PLAYLIST_NAME_FAVORITES + "'"; String[] favorites_cols = new String[] { BaseColumns._ID }; Uri favorites_uri = Audio.Playlists.EXTERNAL_CONTENT_URI; Cursor cursor = resolver.query(favorites_uri, favorites_cols, favorites_where, null, null); if (cursor.getCount() <= 0) { favorites_id = createPlaylist(context, PLAYLIST_NAME_FAVORITES); } else { cursor.moveToFirst(); favorites_id = cursor.getLong(0); cursor.close(); } Uri uri = Playlists.Members.getContentUri(EXTERNAL, favorites_id); resolver.delete(uri, Playlists.Members.AUDIO_ID + "=" + id, null); } } /** * @param mService * @param mImageButton * @param id */ public static void setFavoriteImage(ImageButton mImageButton) { try { if (MusicUtils.mService.isFavorite(MusicUtils.mService.getAudioId())) { mImageButton.setImageResource(R.drawable.apollo_holo_light_favorite_selected); } else { mImageButton.setImageResource(R.drawable.apollo_holo_light_favorite_normal); // Theme chooser ThemeUtils.setImageButton(mImageButton.getContext(), mImageButton, "apollo_favorite_normal"); } } catch (RemoteException e) { e.printStackTrace(); } } /** * @param mContext * @param id * @param name */ public static void renamePlaylist(Context mContext, long id, String name) { if (name != null && name.length() > 0) { ContentResolver resolver = mContext.getContentResolver(); ContentValues values = new ContentValues(1); values.put(PlaylistsColumns.NAME, name); resolver.update(Audio.Playlists.EXTERNAL_CONTENT_URI, values, BaseColumns._ID + "=?", new String[] { String.valueOf(id) }); Toast.makeText(mContext, "Playlist renamed", Toast.LENGTH_SHORT).show(); } } /** * @param mContext * @param list */ public static void addToCurrentPlaylist(Context mContext, long[] list) { if (mService == null) return; try { mService.enqueue(list, ApolloService.LAST); String message = mContext.getResources().getQuantityString( R.plurals.NNNtrackstoplaylist, list.length, Integer.valueOf(list.length)); Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show(); } catch (RemoteException ex) { } } /** * @param context * @param secs * @return time String */ public static String makeTimeString(Context context, long secs) { String durationformat = context.getString(secs < 3600 ? R.string.durationformatshort : R.string.durationformatlong); /* * Provide multiple arguments so the format can be changed easily by * modifying the xml. */ sFormatBuilder.setLength(0); final Object[] timeArgs = sTimeArgs; timeArgs[0] = secs / 3600; timeArgs[1] = secs / 60; timeArgs[2] = secs / 60 % 60; timeArgs[3] = secs; timeArgs[4] = secs % 60; return sFormatter.format(durationformat, timeArgs).toString(); } /** * @return current album ID */ public static long getCurrentAlbumId() { if (mService != null) { try { return mService.getAlbumId(); } catch (RemoteException ex) { } } return -1; } /** * @return current artist ID */ public static long getCurrentArtistId() { if (MusicUtils.mService != null) { try { return mService.getArtistId(); } catch (RemoteException ex) { } } return -1; } /** * @return current track ID */ public static long getCurrentAudioId() { if (MusicUtils.mService != null) { try { return mService.getAudioId(); } catch (RemoteException ex) { } } return -1; } /** * @return current artist name */ public static String getArtistName() { if (mService != null) { try { return mService.getArtistName(); } catch (RemoteException ex) { } } return null; } /** * @return current album name */ public static String getAlbumName() { if (mService != null) { try { return mService.getAlbumName(); } catch (RemoteException ex) { } } return null; } /** * @return current track name */ public static String getTrackName() { if (mService != null) { try { return mService.getTrackName(); } catch (RemoteException ex) { } } return null; } /** * @return duration of a track */ public static long getDuration() { if (mService != null) { try { return mService.duration(); } catch (RemoteException e) { } } return 0; } /** * Create a Search Chooser */ public static void doSearch(Context mContext, Cursor mCursor, int index) { CharSequence title = null; Intent i = new Intent(); i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); String query = mCursor.getString(index); title = ""; i.putExtra("", query); title = title + " " + query; title = "Search " + title; i.putExtra(SearchManager.QUERY, query); mContext.startActivity(Intent.createChooser(i, title)); } /** * Method that removes all tracks from the current queue */ public static void removeAllTracks() { try { if (mService == null) { long[] current = MusicUtils.getQueue(); if (current != null) { mService.removeTracks(0, current.length-1); } } } catch (RemoteException e) { } } /** * @param id * @return removes track from a playlist */ public static int removeTrack(long id) { if (mService == null) return 0; try { return mService.removeTrack(id); } catch (RemoteException e) { e.printStackTrace(); } return 0; } /** * @param index */ public static void setQueuePosition(int index) { if (mService == null) return; try { mService.setQueuePosition(index); } catch (RemoteException e) { } } public static String getArtistName(Context mContext, long artist_id, boolean default_name) { String where = BaseColumns._ID + "=" + artist_id; String[] cols = new String[] { ArtistColumns.ARTIST }; Uri uri = Audio.Artists.EXTERNAL_CONTENT_URI; Cursor cursor = mContext.getContentResolver().query(uri, cols, where, null, null); if (cursor == null){ return MediaStore.UNKNOWN_STRING; } if (cursor.getCount() <= 0) { if (default_name) return mContext.getString(R.string.unknown); else return MediaStore.UNKNOWN_STRING; } else { cursor.moveToFirst(); String name = cursor.getString(0); cursor.close(); if (name == null || MediaStore.UNKNOWN_STRING.equals(name)) { if (default_name) return mContext.getString(R.string.unknown); else return MediaStore.UNKNOWN_STRING; } return name; } } /** * @param mContext * @param album_id * @param default_name * @return album name */ public static String getAlbumName(Context mContext, long album_id, boolean default_name) { String where = BaseColumns._ID + "=" + album_id; String[] cols = new String[] { AlbumColumns.ALBUM }; Uri uri = Audio.Albums.EXTERNAL_CONTENT_URI; Cursor cursor = mContext.getContentResolver().query(uri, cols, where, null, null); if (cursor == null){ return MediaStore.UNKNOWN_STRING; } if (cursor.getCount() <= 0) { if (default_name) return mContext.getString(R.string.unknown); else return MediaStore.UNKNOWN_STRING; } else { cursor.moveToFirst(); String name = cursor.getString(0); cursor.close(); if (name == null || MediaStore.UNKNOWN_STRING.equals(name)) { if (default_name) return mContext.getString(R.string.unknown); else return MediaStore.UNKNOWN_STRING; } return name; } } /** * @param playlist_id * @return playlist name */ public static String getPlaylistName(Context mContext, long playlist_id) { String where = BaseColumns._ID + "=" + playlist_id; String[] cols = new String[] { PlaylistsColumns.NAME }; Uri uri = Audio.Playlists.EXTERNAL_CONTENT_URI; Cursor cursor = mContext.getContentResolver().query(uri, cols, where, null, null); if (cursor == null){ return ""; } if (cursor.getCount() <= 0) return ""; cursor.moveToFirst(); String name = cursor.getString(0); cursor.close(); return name; } /** * @param mContext * @param genre_id * @param default_name * @return genre name */ public static String getGenreName(Context mContext, long genre_id, boolean default_name) { String where = BaseColumns._ID + "=" + genre_id; String[] cols = new String[] { GenresColumns.NAME }; Uri uri = Audio.Genres.EXTERNAL_CONTENT_URI; Cursor cursor = mContext.getContentResolver().query(uri, cols, where, null, null); if (cursor == null){ return MediaStore.UNKNOWN_STRING; } if (cursor.getCount() <= 0) { if (default_name) return mContext.getString(R.string.unknown); else return MediaStore.UNKNOWN_STRING; } else { cursor.moveToFirst(); String name = cursor.getString(0); cursor.close(); if (name == null || MediaStore.UNKNOWN_STRING.equals(name)) { if (default_name) return mContext.getString(R.string.unknown); else return MediaStore.UNKNOWN_STRING; } return name; } } /** * @param genre * @return parsed genre name */ public static String parseGenreName(Context mContext, String genre) { int genre_id = -1; if (genre == null || genre.trim().length() <= 0) return mContext.getResources().getString(R.string.unknown); try { genre_id = Integer.parseInt(genre); } catch (NumberFormatException e) { return genre; } if (genre_id >= 0 && genre_id < GENRES_DB.length) return GENRES_DB[genre_id]; else return mContext.getResources().getString(R.string.unknown); } /** * @return if music is playing */ public static boolean isPlaying() { if (mService == null) return false; try { return mService.isPlaying(); } catch (RemoteException e) { } return false; } /** * @return current track's queue position */ public static int getQueuePosition() { if (mService == null) return 0; try { return mService.getQueuePosition(); } catch (RemoteException e) { } return 0; } /** * @param mContext * @param create_shortcut * @param list */ public static void makePlaylistList(Context mContext, boolean create_shortcut, List<Map<String, String>> list) { Map<String, String> map; String[] cols = new String[] { Audio.Playlists._ID, Audio.Playlists.NAME }; StringBuilder where = new StringBuilder(); ContentResolver resolver = mContext.getContentResolver(); if (resolver == null) { System.out.println("resolver = null"); } else { where.append(Audio.Playlists.NAME + " != ''"); where.append(" AND " + Audio.Playlists.NAME + " != '" + PLAYLIST_NAME_FAVORITES + "'"); Cursor cur = resolver.query(Audio.Playlists.EXTERNAL_CONTENT_URI, cols, where.toString(), null, Audio.Playlists.NAME); list.clear(); // map = new HashMap<String, String>(); // map.put("id", String.valueOf(PLAYLIST_FAVORITES)); // map.put("name", mContext.getString(R.string.favorite)); // list.add(map); map = new HashMap<String, String>(); map.put("id", String.valueOf(PLAYLIST_QUEUE)); map.put("name", mContext.getString(R.string.queue)); list.add(map); map = new HashMap<String, String>(); map.put("id", String.valueOf(PLAYLIST_NEW)); map.put("name", mContext.getString(R.string.new_playlist)); list.add(map); if (cur != null && cur.getCount() > 0) { cur.moveToFirst(); while (!cur.isAfterLast()) { map = new HashMap<String, String>(); map.put("id", String.valueOf(cur.getLong(0))); map.put("name", cur.getString(1)); list.add(map); cur.moveToNext(); } } if (cur != null) { cur.close(); } } } public static void notifyWidgets(String what){ try { mService.notifyChange(what); } catch (Exception e) { } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.kafka.connect.storage; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.common.errors.RetriableException; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.apache.kafka.common.utils.Time; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaAndValue; import org.apache.kafka.connect.data.SchemaBuilder; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.runtime.AbstractStatus; import org.apache.kafka.connect.runtime.ConnectorStatus; import org.apache.kafka.connect.runtime.TaskStatus; import org.apache.kafka.connect.runtime.WorkerConfig; import org.apache.kafka.connect.runtime.distributed.DistributedConfig; import org.apache.kafka.connect.util.Callback; import org.apache.kafka.connect.util.ConnectorTaskId; import org.apache.kafka.connect.util.KafkaBasedLog; import org.apache.kafka.connect.util.Table; import org.apache.kafka.connect.util.TopicAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * StatusBackingStore implementation which uses a compacted topic for storage * of connector and task status information. When a state change is observed, * the new state is written to the compacted topic. The new state will not be * visible until it has been read back from the topic. * * In spite of their names, the putSafe() methods cannot guarantee the safety * of the write (since Kafka itself cannot provide such guarantees currently), * but it can avoid specific unsafe conditions. In particular, we putSafe() * allows writes in the following conditions: * * 1) It is (probably) safe to overwrite the state if there is no previous * value. * 2) It is (probably) safe to overwrite the state if the previous value was * set by a worker with the same workerId. * 3) It is (probably) safe to overwrite the previous state if the current * generation is higher than the previous . * * Basically all these conditions do is reduce the window for conflicts. They * obviously cannot take into account in-flight requests. * */ public class KafkaStatusBackingStore implements StatusBackingStore { private static final Logger log = LoggerFactory.getLogger(KafkaStatusBackingStore.class); private static final String TASK_STATUS_PREFIX = "status-task-"; private static final String CONNECTOR_STATUS_PREFIX = "status-connector-"; public static final String STATE_KEY_NAME = "state"; public static final String TRACE_KEY_NAME = "trace"; public static final String WORKER_ID_KEY_NAME = "worker_id"; public static final String GENERATION_KEY_NAME = "generation"; private static final Schema STATUS_SCHEMA_V0 = SchemaBuilder.struct() .field(STATE_KEY_NAME, Schema.STRING_SCHEMA) .field(TRACE_KEY_NAME, SchemaBuilder.string().optional().build()) .field(WORKER_ID_KEY_NAME, Schema.STRING_SCHEMA) .field(GENERATION_KEY_NAME, Schema.INT32_SCHEMA) .build(); private final Time time; private final Converter converter; private final Table<String, Integer, CacheEntry<TaskStatus>> tasks; private final Map<String, CacheEntry<ConnectorStatus>> connectors; private String topic; private KafkaBasedLog<String, byte[]> kafkaLog; private int generation; public KafkaStatusBackingStore(Time time, Converter converter) { this.time = time; this.converter = converter; this.tasks = new Table<>(); this.connectors = new HashMap<>(); } // visible for testing KafkaStatusBackingStore(Time time, Converter converter, String topic, KafkaBasedLog<String, byte[]> kafkaLog) { this(time, converter); this.kafkaLog = kafkaLog; this.topic = topic; } @Override public void configure(final WorkerConfig config) { this.topic = config.getString(DistributedConfig.STATUS_STORAGE_TOPIC_CONFIG); if (this.topic == null || this.topic.trim().length() == 0) throw new ConfigException("Must specify topic for connector status."); Map<String, Object> originals = config.originals(); Map<String, Object> producerProps = new HashMap<>(originals); producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); producerProps.put(ProducerConfig.RETRIES_CONFIG, 0); // we handle retries in this class Map<String, Object> consumerProps = new HashMap<>(originals); consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); Map<String, Object> adminProps = new HashMap<>(originals); NewTopic topicDescription = TopicAdmin.defineTopic(topic). compacted(). partitions(config.getInt(DistributedConfig.STATUS_STORAGE_PARTITIONS_CONFIG)). replicationFactor(config.getShort(DistributedConfig.STATUS_STORAGE_REPLICATION_FACTOR_CONFIG)). build(); Callback<ConsumerRecord<String, byte[]>> readCallback = new Callback<ConsumerRecord<String, byte[]>>() { @Override public void onCompletion(Throwable error, ConsumerRecord<String, byte[]> record) { read(record); } }; this.kafkaLog = createKafkaBasedLog(topic, producerProps, consumerProps, readCallback, topicDescription, adminProps); } private KafkaBasedLog<String, byte[]> createKafkaBasedLog(String topic, Map<String, Object> producerProps, Map<String, Object> consumerProps, Callback<ConsumerRecord<String, byte[]>> consumedCallback, final NewTopic topicDescription, final Map<String, Object> adminProps) { Runnable createTopics = new Runnable() { @Override public void run() { log.debug("Creating admin client to manage Connect internal status topic"); try (TopicAdmin admin = new TopicAdmin(adminProps)) { admin.createTopics(topicDescription); } } }; return new KafkaBasedLog<>(topic, producerProps, consumerProps, consumedCallback, time, createTopics); } @Override public void start() { kafkaLog.start(); // read to the end on startup to ensure that api requests see the most recent states kafkaLog.readToEnd(); } @Override public void stop() { kafkaLog.stop(); } @Override public void put(final ConnectorStatus status) { sendConnectorStatus(status, false); } @Override public void putSafe(final ConnectorStatus status) { sendConnectorStatus(status, true); } @Override public void put(final TaskStatus status) { sendTaskStatus(status, false); } @Override public void putSafe(final TaskStatus status) { sendTaskStatus(status, true); } @Override public void flush() { kafkaLog.flush(); } private void sendConnectorStatus(final ConnectorStatus status, boolean safeWrite) { String connector = status.id(); CacheEntry<ConnectorStatus> entry = getOrAdd(connector); String key = CONNECTOR_STATUS_PREFIX + connector; send(key, status, entry, safeWrite); } private void sendTaskStatus(final TaskStatus status, boolean safeWrite) { ConnectorTaskId taskId = status.id(); CacheEntry<TaskStatus> entry = getOrAdd(taskId); String key = TASK_STATUS_PREFIX + taskId.connector() + "-" + taskId.task(); send(key, status, entry, safeWrite); } private <V extends AbstractStatus> void send(final String key, final V status, final CacheEntry<V> entry, final boolean safeWrite) { final int sequence; synchronized (this) { this.generation = status.generation(); if (safeWrite && !entry.canWriteSafely(status)) return; sequence = entry.increment(); } final byte[] value = status.state() == ConnectorStatus.State.DESTROYED ? null : serialize(status); kafkaLog.send(key, value, new org.apache.kafka.clients.producer.Callback() { @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (exception == null) return; if (exception instanceof RetriableException) { synchronized (KafkaStatusBackingStore.this) { if (entry.isDeleted() || status.generation() != generation || (safeWrite && !entry.canWriteSafely(status, sequence))) return; } kafkaLog.send(key, value, this); } else { log.error("Failed to write status update", exception); } } }); } private synchronized CacheEntry<ConnectorStatus> getOrAdd(String connector) { CacheEntry<ConnectorStatus> entry = connectors.get(connector); if (entry == null) { entry = new CacheEntry<>(); connectors.put(connector, entry); } return entry; } private synchronized void remove(String connector) { CacheEntry<ConnectorStatus> removed = connectors.remove(connector); if (removed != null) removed.delete(); Map<Integer, CacheEntry<TaskStatus>> tasks = this.tasks.remove(connector); if (tasks != null) { for (CacheEntry<TaskStatus> taskEntry : tasks.values()) taskEntry.delete(); } } private synchronized CacheEntry<TaskStatus> getOrAdd(ConnectorTaskId task) { CacheEntry<TaskStatus> entry = tasks.get(task.connector(), task.task()); if (entry == null) { entry = new CacheEntry<>(); tasks.put(task.connector(), task.task(), entry); } return entry; } private synchronized void remove(ConnectorTaskId id) { CacheEntry<TaskStatus> removed = tasks.remove(id.connector(), id.task()); if (removed != null) removed.delete(); } @Override public synchronized TaskStatus get(ConnectorTaskId id) { CacheEntry<TaskStatus> entry = tasks.get(id.connector(), id.task()); return entry == null ? null : entry.get(); } @Override public synchronized ConnectorStatus get(String connector) { CacheEntry<ConnectorStatus> entry = connectors.get(connector); return entry == null ? null : entry.get(); } @Override public synchronized Collection<TaskStatus> getAll(String connector) { List<TaskStatus> res = new ArrayList<>(); for (CacheEntry<TaskStatus> statusEntry : tasks.row(connector).values()) { TaskStatus status = statusEntry.get(); if (status != null) res.add(status); } return res; } @Override public synchronized Set<String> connectors() { return new HashSet<>(connectors.keySet()); } private ConnectorStatus parseConnectorStatus(String connector, byte[] data) { try { SchemaAndValue schemaAndValue = converter.toConnectData(topic, data); if (!(schemaAndValue.value() instanceof Map)) { log.error("Invalid connector status type {}", schemaAndValue.value().getClass()); return null; } @SuppressWarnings("unchecked") Map<String, Object> statusMap = (Map<String, Object>) schemaAndValue.value(); TaskStatus.State state = TaskStatus.State.valueOf((String) statusMap.get(STATE_KEY_NAME)); String trace = (String) statusMap.get(TRACE_KEY_NAME); String workerUrl = (String) statusMap.get(WORKER_ID_KEY_NAME); int generation = ((Long) statusMap.get(GENERATION_KEY_NAME)).intValue(); return new ConnectorStatus(connector, state, trace, workerUrl, generation); } catch (Exception e) { log.error("Failed to deserialize connector status", e); return null; } } private TaskStatus parseTaskStatus(ConnectorTaskId taskId, byte[] data) { try { SchemaAndValue schemaAndValue = converter.toConnectData(topic, data); if (!(schemaAndValue.value() instanceof Map)) { log.error("Invalid task status type {}", schemaAndValue.value().getClass()); return null; } @SuppressWarnings("unchecked") Map<String, Object> statusMap = (Map<String, Object>) schemaAndValue.value(); TaskStatus.State state = TaskStatus.State.valueOf((String) statusMap.get(STATE_KEY_NAME)); String trace = (String) statusMap.get(TRACE_KEY_NAME); String workerUrl = (String) statusMap.get(WORKER_ID_KEY_NAME); int generation = ((Long) statusMap.get(GENERATION_KEY_NAME)).intValue(); return new TaskStatus(taskId, state, workerUrl, generation, trace); } catch (Exception e) { log.error("Failed to deserialize task status", e); return null; } } private byte[] serialize(AbstractStatus status) { Struct struct = new Struct(STATUS_SCHEMA_V0); struct.put(STATE_KEY_NAME, status.state().name()); if (status.trace() != null) struct.put(TRACE_KEY_NAME, status.trace()); struct.put(WORKER_ID_KEY_NAME, status.workerId()); struct.put(GENERATION_KEY_NAME, status.generation()); return converter.fromConnectData(topic, STATUS_SCHEMA_V0, struct); } private String parseConnectorStatusKey(String key) { return key.substring(CONNECTOR_STATUS_PREFIX.length()); } private ConnectorTaskId parseConnectorTaskId(String key) { String[] parts = key.split("-"); if (parts.length < 4) return null; try { int taskNum = Integer.parseInt(parts[parts.length - 1]); String connectorName = Utils.join(Arrays.copyOfRange(parts, 2, parts.length - 1), "-"); return new ConnectorTaskId(connectorName, taskNum); } catch (NumberFormatException e) { log.warn("Invalid task status key {}", key); return null; } } private void readConnectorStatus(String key, byte[] value) { String connector = parseConnectorStatusKey(key); if (connector == null || connector.isEmpty()) { log.warn("Discarding record with invalid connector status key {}", key); return; } if (value == null) { log.trace("Removing status for connector {}", connector); remove(connector); return; } ConnectorStatus status = parseConnectorStatus(connector, value); if (status == null) return; synchronized (this) { log.trace("Received connector {} status update {}", connector, status); CacheEntry<ConnectorStatus> entry = getOrAdd(connector); entry.put(status); } } private void readTaskStatus(String key, byte[] value) { ConnectorTaskId id = parseConnectorTaskId(key); if (id == null) { log.warn("Discarding record with invalid task status key {}", key); return; } if (value == null) { log.trace("Removing task status for {}", id); remove(id); return; } TaskStatus status = parseTaskStatus(id, value); if (status == null) { log.warn("Failed to parse task status with key {}", key); return; } synchronized (this) { log.trace("Received task {} status update {}", id, status); CacheEntry<TaskStatus> entry = getOrAdd(id); entry.put(status); } } // visible for testing void read(ConsumerRecord<String, byte[]> record) { String key = record.key(); if (key.startsWith(CONNECTOR_STATUS_PREFIX)) { readConnectorStatus(key, record.value()); } else if (key.startsWith(TASK_STATUS_PREFIX)) { readTaskStatus(key, record.value()); } else { log.warn("Discarding record with invalid key {}", key); } } private static class CacheEntry<T extends AbstractStatus> { private T value = null; private int sequence = 0; private boolean deleted = false; public int increment() { return ++sequence; } public void put(T value) { this.value = value; } public T get() { return value; } public void delete() { this.deleted = true; } public boolean isDeleted() { return deleted; } public boolean canWriteSafely(T status) { return value == null || value.workerId().equals(status.workerId()) || value.generation() <= status.generation(); } public boolean canWriteSafely(T status, int sequence) { return canWriteSafely(status) && this.sequence == sequence; } } }
/* * Copyright 2011-2018 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.importer.release; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Lists.newArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; import com.b2international.commons.CompareUtils; import com.b2international.snowowl.snomed.common.ContentSubType; /** * Provides a way to validate if a set of relative paths constitute a valid * release directory or archive, and converts symbolic component types into path * names. * * @since 1.3 */ public class ReleaseFileSet { /* * "The Country|Namespace element of the filename helps to identify the * organization responsible for developing and maintaining the file. Its * format is 2-10 alphanumeric characters consisting of 0, 2 or 3 * upper-case letters followed by 0 or 7 digits." * * Note: we're not checking valid ISO country codes and dates at the moment */ private static final ReleaseIdentifier INITIAL_RELEASE_IDENTIFIER = new ReleaseIdentifier( "(INT|SG|INT[0-9]{7}|[A-Z]{2}[0-9]{7}|[0-9]{7}|SG[0-9]{7}|[A-Z]{2}[0-9]{7}|[0-9]{7})", "([2-9][0-9]{3}[0-1][0-9][0-3][0-9])"); private static final String INITIAL_RELEASE_ROOT = ".*"; public enum ReleaseComponentType { CONCEPT, DESCRIPTION, RELATIONSHIP, STATED_RELATIONSHIP, LANGUAGE_REFERENCE_SET, TEXT_DEFINITION } private final Map<ReleaseComponentType, ReleaseFile> releaseFiles; private final boolean testRelease; private final List<String> refSetPaths; private ReleaseIdentifier releaseIdentifier = INITIAL_RELEASE_IDENTIFIER; private String relativeRoot = INITIAL_RELEASE_ROOT; /** * Creates a new release file set instance. * * @param testRelease * <code>true</code> if this set is considered a test release, * <code>false</code> otherwise * * @param releaseFiles * a map containing {@link ReleaseFile} descriptors for * {@link ReleaseComponentType} keys * * @param refSetPaths * a list of relative paths where reference sets can be located */ public ReleaseFileSet(boolean testRelease, Map<ReleaseComponentType, ReleaseFile> releaseFiles, List<String> refSetPaths) { this.testRelease = testRelease; this.releaseFiles = releaseFiles; this.refSetPaths = refSetPaths; } /** * Checks if the contents of an archive or directory would be a valid * release by looking for matching file names in the specified list with the * specified content subtype. * * @param relativeLocations the contents of the archive or directory (a list * of relative paths) * * @param contentSubType the content subtype to look for (may not be * {@code null}) * * @return <code>true</code> if the items in the list form a valid release * set, <code>false</code> otherwise */ public boolean isValidReleaseRoot(List<String> relativeLocations, ContentSubType contentSubType) { if (relativeLocations.isEmpty()) { return false; } releaseIdentifier = INITIAL_RELEASE_IDENTIFIER; relativeRoot = INITIAL_RELEASE_ROOT; boolean matchFound = true; for (ReleaseFile releaseFile : releaseFiles.values()) { Pattern patternToMatch = releaseFile.createPattern(testRelease, contentSubType, releaseIdentifier, relativeRoot); boolean matchFoundForReleaseFile = false; for (String relativeLocation : relativeLocations) { Matcher matcher = patternToMatch.matcher(relativeLocation); if (matcher.matches()) { // This should be set on the first occasion, i.e. when a concept file is matched if (relativeRoot == INITIAL_RELEASE_ROOT) { relativeRoot = Pattern.quote(matcher.group(1)); } if (releaseIdentifier == INITIAL_RELEASE_IDENTIFIER) { releaseIdentifier = new ReleaseIdentifier(matcher.group(2), matcher.group(3)); } matchFoundForReleaseFile = true; break; } } if (!matchFoundForReleaseFile && !releaseFile.isOptional()) { matchFound = false; break; } } return matchFound; } /** * Extracts a path name for the specified component type from the list of * paths. * * @param relativeLocations the locations to check * @param type the requested component type * @param contentSubType the requested subtype * @return a file path for the component, or an empty string if no matching * path could be found */ @Nullable public String getFileName(List<String> relativeLocations, ReleaseComponentType type, ContentSubType contentSubType) { if (CompareUtils.isEmpty(relativeLocations)) { return null; } ReleaseFile releaseFile = releaseFiles.get(type); if (releaseFile == null) { return null; } Pattern patternToMatch = releaseFile.createPattern(testRelease, contentSubType, releaseIdentifier, relativeRoot); for (String relativeLocation : relativeLocations) { Matcher matcher = patternToMatch.matcher(relativeLocation); if (matcher.matches()) { return matcher.group(); } } return null; } /** * Extracts a path names for a specified component type from the list of * paths. * * @param relativeLocations the locations to check * @param type the requested component type * @param contentSubType the requested subtype * @return a collection file path for the component. could be empty collection if no match could be found */ public Collection<String> getAllFileName(Iterable<String> relativeLocations, ReleaseComponentType type, ContentSubType contentSubType) { if (CompareUtils.isEmpty(relativeLocations)) { return Collections.emptySet(); } ReleaseFile releaseFile = releaseFiles.get(type); if (releaseFile == null) { return Collections.emptySet(); } Pattern patternToMatch = releaseFile.createPattern(testRelease, contentSubType, releaseIdentifier, relativeRoot); List<String> fileNames = newArrayList(); for (String relativeLocation : relativeLocations) { Matcher matcher = patternToMatch.matcher(relativeLocation); if (matcher.matches()) { fileNames.add(matcher.group()); } } return fileNames; } /** * @return the matched release identifier, if it could be extracted during a * previous call to {@link #isValidReleaseRoot(List)} * * @throws IllegalArgumentException * if the release identifier could not be determined yet */ public ReleaseIdentifier getReleaseIdentifier() { checkState(releaseIdentifier != INITIAL_RELEASE_IDENTIFIER, "Release identifier has not been determined yet."); return releaseIdentifier; } public String getRelativeRoot() { checkState(relativeRoot != INITIAL_RELEASE_ROOT, "Release root has not been determined yet."); if (relativeRoot.length() > 4) { return relativeRoot.substring(2, relativeRoot.length() - 2); // Remove regexp quote characters } else { return relativeRoot; } } /** * @return <code>true</code> if this set is considered a test release, * <code>false</code> otherwise */ public boolean isTestRelease() { return testRelease; } /** * @return a list of path names from which possible reference set files can * be collected */ public List<String> getRefSetPaths() { return refSetPaths; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You 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 org.apache.geode.internal.cache.execute; import static org.junit.Assert.assertNotNull; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import java.util.Set; import org.junit.Test; import org.apache.geode.DataSerializable; import org.apache.geode.DataSerializer; import org.apache.geode.cache.AttributesFactory; import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.EntryOperation; import org.apache.geode.cache.PartitionAttributes; import org.apache.geode.cache.PartitionAttributesFactory; import org.apache.geode.cache.PartitionResolver; import org.apache.geode.cache.Region; import org.apache.geode.distributed.DistributedSystem; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.internal.cache.partitioned.RegionAdvisor; import org.apache.geode.internal.logging.InternalLogWriter; import org.apache.geode.test.dunit.Assert; import org.apache.geode.test.dunit.Host; import org.apache.geode.test.dunit.Invoke; import org.apache.geode.test.dunit.LogWriterUtils; import org.apache.geode.test.dunit.SerializableRunnable; import org.apache.geode.test.dunit.VM; import org.apache.geode.test.dunit.Wait; import org.apache.geode.test.dunit.WaitCriterion; import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase; public class ColocationFailoverDUnitTest extends JUnit4DistributedTestCase { private static final long serialVersionUID = 1L; protected static Cache cache = null; protected static VM dataStore1 = null; protected static VM dataStore2 = null; protected static VM dataStore3 = null; protected static VM dataStore4 = null; protected static Region customerPR = null; protected static Region orderPR = null; protected static Region shipmentPR = null; public static String customerPR_Name = "ColocationFailoverDUnitTest_CustomerPR"; public static String orderPR_Name = "ColocationFailoverDUnitTest_OrderPR"; public static String shipmentPR_Name = "ColocationFailoverDUnitTest_ShipmentPR"; @Override public final void postSetUp() throws Exception { Host host = Host.getHost(0); dataStore1 = host.getVM(0); dataStore2 = host.getVM(1); dataStore3 = host.getVM(2); dataStore4 = host.getVM(3); } @Test public void testPrimaryColocationFailover() throws Throwable { createCacheInAllVms(); createCustomerPR(); createOrderPR(); createShipmentPR(); putInPRs(); verifyColocationInAllVms(); dataStore1.invoke(() -> ColocationFailoverDUnitTest.closeCache()); verifyPrimaryColocationAfterFailover(); } @Test public void testColocationFailover() throws Throwable { createCacheInAllVms(); createCustomerPR(); createOrderPR(); createShipmentPR(); putInPRs(); verifyColocationInAllVms(); dataStore1.invoke(() -> ColocationFailoverDUnitTest.closeCache()); Wait.pause(5000); // wait for volunteering primary verifyColocationAfterFailover(); } private void verifyColocationInAllVms() { verifyColocation(); dataStore1.invoke(() -> ColocationFailoverDUnitTest.verifyColocation()); dataStore2.invoke(() -> ColocationFailoverDUnitTest.verifyColocation()); dataStore3.invoke(() -> ColocationFailoverDUnitTest.verifyColocation()); dataStore4.invoke(() -> ColocationFailoverDUnitTest.verifyColocation()); } private void verifyPrimaryColocationAfterFailover() { verifyPrimaryColocation(); dataStore2.invoke(() -> ColocationFailoverDUnitTest.verifyPrimaryColocation()); dataStore3.invoke(() -> ColocationFailoverDUnitTest.verifyPrimaryColocation()); dataStore4.invoke(() -> ColocationFailoverDUnitTest.verifyPrimaryColocation()); } private void verifyColocationAfterFailover() { verifyColocation(); dataStore2.invoke(() -> ColocationFailoverDUnitTest.verifyColocation()); dataStore3.invoke(() -> ColocationFailoverDUnitTest.verifyColocation()); dataStore4.invoke(() -> ColocationFailoverDUnitTest.verifyColocation()); } public static void closeCache() { if (cache != null) { cache.close(); } } protected static boolean tryVerifyPrimaryColocation() { HashMap customerPrimaryMap = new HashMap(); RegionAdvisor customeAdvisor = ((PartitionedRegion) customerPR).getRegionAdvisor(); Iterator customerIterator = customeAdvisor.getBucketSet().iterator(); while (customerIterator.hasNext()) { Integer bucketId = (Integer) customerIterator.next(); if (customeAdvisor.isPrimaryForBucket(bucketId.intValue())) { customerPrimaryMap.put(bucketId, customeAdvisor.getPrimaryMemberForBucket(bucketId.intValue()).getId()); } } HashMap orderPrimaryMap = new HashMap(); RegionAdvisor orderAdvisor = ((PartitionedRegion) orderPR).getRegionAdvisor(); Iterator orderIterator = orderAdvisor.getBucketSet().iterator(); while (orderIterator.hasNext()) { Integer bucketId = (Integer) orderIterator.next(); if (orderAdvisor.isPrimaryForBucket(bucketId.intValue())) { orderPrimaryMap.put(bucketId, orderAdvisor.getPrimaryMemberForBucket(bucketId.intValue()).getId()); } } HashMap shipmentPrimaryMap = new HashMap(); RegionAdvisor shipmentAdvisor = ((PartitionedRegion) shipmentPR).getRegionAdvisor(); Iterator shipmentIterator = shipmentAdvisor.getBucketSet().iterator(); while (shipmentIterator.hasNext()) { Integer bucketId = (Integer) shipmentIterator.next(); if (shipmentAdvisor.isPrimaryForBucket(bucketId.intValue())) { shipmentPrimaryMap.put(bucketId, shipmentAdvisor.getPrimaryMemberForBucket(bucketId.intValue()).getId()); } } // verification for primary int s1, s2; s1 = customerPrimaryMap.size(); s2 = orderPrimaryMap.size(); if (s1 != s2) { excuse = "customerPrimaryMap size (" + s1 + ") != orderPrimaryMap size (" + s2 + ")"; return false; } if (!customerPrimaryMap.entrySet().equals(orderPrimaryMap.entrySet())) { excuse = "customerPrimaryMap entrySet != orderPrimaryMap entrySet"; return false; } if (!customerPrimaryMap.entrySet().equals(shipmentPrimaryMap.entrySet())) { excuse = "customerPrimaryMap entrySet != shipmentPrimaryMap entrySet"; return false; } if (!customerPrimaryMap.equals(orderPrimaryMap)) { excuse = "customerPrimaryMap != orderPrimaryMap"; return false; } if (!customerPrimaryMap.equals(shipmentPrimaryMap)) { excuse = "customerPrimaryMap != shipmentPrimaryMap"; return false; } return true; } private static void verifyPrimaryColocation() { WaitCriterion wc = new WaitCriterion() { public boolean done() { return tryVerifyPrimaryColocation(); } public String description() { dump(); return excuse; } }; Wait.waitForCriterion(wc, 60 * 1000, 1000, true); } protected static void dump() { final InternalLogWriter logger = LogWriterUtils.getLogWriter(); ((PartitionedRegion) customerPR).dumpAllBuckets(false); ((PartitionedRegion) orderPR).dumpAllBuckets(false); ((PartitionedRegion) shipmentPR).dumpAllBuckets(false); for (int i = 0; i < 6; i++) { ((PartitionedRegion) customerPR).dumpB2NForBucket(i); } for (int i = 0; i < 6; i++) { ((PartitionedRegion) orderPR).dumpB2NForBucket(i); } for (int i = 0; i < 6; i++) { ((PartitionedRegion) shipmentPR).dumpB2NForBucket(i); } } protected static String excuse; /** * @return true if verified */ protected static boolean tryVerifyColocation() { HashMap customerMap = new HashMap(); HashMap customerPrimaryMap = new HashMap(); RegionAdvisor customeAdvisor = ((PartitionedRegion) customerPR).getRegionAdvisor(); Iterator customerIterator = customeAdvisor.getBucketSet().iterator(); while (customerIterator.hasNext()) { Integer bucketId = (Integer) customerIterator.next(); Set someOwners = customeAdvisor.getBucketOwners(bucketId.intValue()); customerMap.put(bucketId, someOwners); if (customeAdvisor.isPrimaryForBucket(bucketId.intValue())) { customerPrimaryMap.put(bucketId, customeAdvisor.getPrimaryMemberForBucket(bucketId.intValue()).getId()); } } HashMap orderMap = new HashMap(); HashMap orderPrimaryMap = new HashMap(); RegionAdvisor orderAdvisor = ((PartitionedRegion) orderPR).getRegionAdvisor(); Iterator orderIterator = orderAdvisor.getBucketSet().iterator(); while (orderIterator.hasNext()) { Integer bucketId = (Integer) orderIterator.next(); Set someOwners = orderAdvisor.getBucketOwners(bucketId.intValue()); orderMap.put(bucketId, someOwners); if (orderAdvisor.isPrimaryForBucket(bucketId.intValue())) { orderPrimaryMap.put(bucketId, orderAdvisor.getPrimaryMemberForBucket(bucketId.intValue()).getId()); } } HashMap shipmentMap = new HashMap(); HashMap shipmentPrimaryMap = new HashMap(); RegionAdvisor shipmentAdvisor = ((PartitionedRegion) shipmentPR).getRegionAdvisor(); Iterator shipmentIterator = shipmentAdvisor.getBucketSet().iterator(); while (shipmentIterator.hasNext()) { Integer bucketId = (Integer) shipmentIterator.next(); Set someOwners = shipmentAdvisor.getBucketOwners(bucketId.intValue()); shipmentMap.put(bucketId, someOwners); if (!customerMap.get(bucketId).equals(someOwners)) { excuse = "customerMap at " + bucketId + " has wrong owners"; return false; } if (!orderMap.get(bucketId).equals(someOwners)) { excuse = "orderMap at " + bucketId + " has wrong owners"; return false; } if (shipmentAdvisor.isPrimaryForBucket(bucketId.intValue())) { shipmentPrimaryMap.put(bucketId, shipmentAdvisor.getPrimaryMemberForBucket(bucketId.intValue()).getId()); } } // verification for primary if (customerPrimaryMap.size() != orderPrimaryMap.size()) { excuse = "customerPrimaryMap and orderPrimaryMap have different sizes"; return false; } if (customerPrimaryMap.size() != shipmentPrimaryMap.size()) { excuse = "customerPrimaryMap and shipmentPrimaryMap have different sizes"; return false; } if (!customerPrimaryMap.entrySet().equals(orderPrimaryMap.entrySet())) { excuse = "customerPrimaryMap and orderPrimaryMap have different entrySets"; return false; } if (!customerPrimaryMap.entrySet().equals(shipmentPrimaryMap.entrySet())) { excuse = "customerPrimaryMap and shipmentPrimaryMap have different entrySets"; return false; } if (!customerPrimaryMap.equals(orderPrimaryMap)) { excuse = "customerPrimaryMap and orderPrimaryMap not equal"; return false; } if (!customerPrimaryMap.equals(shipmentPrimaryMap)) { excuse = "customerPrimaryMap and shipmentPrimaryMap not equal"; return false; } // verification for all if (customerMap.size() != orderMap.size()) { excuse = "customerMap and orderMap have different sizes"; return false; } if (customerMap.size() != shipmentMap.size()) { excuse = "customerMap and shipmentMap have different sizes"; return false; } if (!customerMap.entrySet().equals(orderMap.entrySet())) { excuse = "customerMap and orderMap have different entrySets"; return false; } if (!customerMap.entrySet().equals(shipmentMap.entrySet())) { excuse = "customerMap and shipmentMap have different entrySets"; return false; } if (!customerMap.equals(orderMap)) { excuse = "customerMap and orderMap not equal"; return false; } if (!customerMap.equals(shipmentMap)) { excuse = "customerMap and shipmentMap not equal"; return false; } return true; } private static void verifyColocation() { // TODO does having this WaitCriterion help? WaitCriterion wc = new WaitCriterion() { public boolean done() { return tryVerifyColocation(); } public String description() { return excuse; } }; Wait.waitForCriterion(wc, 2 * 60 * 1000, 1000, true); } public static void createCacheInAllVms() { createCacheInVm(); dataStore1.invoke(() -> ColocationFailoverDUnitTest.createCacheInVm()); dataStore2.invoke(() -> ColocationFailoverDUnitTest.createCacheInVm()); dataStore3.invoke(() -> ColocationFailoverDUnitTest.createCacheInVm()); dataStore4.invoke(() -> ColocationFailoverDUnitTest.createCacheInVm()); } public static void createCacheInVm() { new ColocationFailoverDUnitTest().createCache(); } public void createCache() { try { Properties props = new Properties(); DistributedSystem ds = getSystem(props); assertNotNull(ds); ds.disconnect(); ds = getSystem(props); cache = CacheFactory.create(ds); assertNotNull(cache); } catch (Exception e) { Assert.fail("Failed while creating the cache", e); } } private static void createCustomerPR() { Object args[] = new Object[] {customerPR_Name, new Integer(1), new Integer(50), new Integer(6), null}; createPR(customerPR_Name, new Integer(1), new Integer(50), new Integer(6), null); dataStore1.invoke(ColocationFailoverDUnitTest.class, "createPR", args); dataStore2.invoke(ColocationFailoverDUnitTest.class, "createPR", args); dataStore3.invoke(ColocationFailoverDUnitTest.class, "createPR", args); dataStore4.invoke(ColocationFailoverDUnitTest.class, "createPR", args); } private static void createOrderPR() { Object args[] = new Object[] {orderPR_Name, new Integer(1), new Integer(50), new Integer(6), customerPR_Name}; createPR(orderPR_Name, new Integer(1), new Integer(50), new Integer(6), customerPR_Name); dataStore1.invoke(ColocationFailoverDUnitTest.class, "createPR", args); dataStore2.invoke(ColocationFailoverDUnitTest.class, "createPR", args); dataStore3.invoke(ColocationFailoverDUnitTest.class, "createPR", args); dataStore4.invoke(ColocationFailoverDUnitTest.class, "createPR", args); } private static void createShipmentPR() { Object args[] = new Object[] {shipmentPR_Name, new Integer(1), new Integer(50), new Integer(6), orderPR_Name}; createPR(shipmentPR_Name, new Integer(1), new Integer(50), new Integer(6), orderPR_Name); dataStore1.invoke(ColocationFailoverDUnitTest.class, "createPR", args); dataStore2.invoke(ColocationFailoverDUnitTest.class, "createPR", args); dataStore3.invoke(ColocationFailoverDUnitTest.class, "createPR", args); dataStore4.invoke(ColocationFailoverDUnitTest.class, "createPR", args); } public static void createPR(String partitionedRegionName, Integer redundancy, Integer localMaxMemory, Integer totalNumBuckets, String colocatedWith) { PartitionAttributesFactory paf = new PartitionAttributesFactory(); PartitionAttributes prAttr = paf.setRedundantCopies(redundancy.intValue()) .setLocalMaxMemory(localMaxMemory.intValue()).setTotalNumBuckets(totalNumBuckets.intValue()) .setColocatedWith(colocatedWith).setPartitionResolver(new KeyPartitionResolver()).create(); AttributesFactory attr = new AttributesFactory(); attr.setPartitionAttributes(prAttr); assertNotNull(cache); if (partitionedRegionName.equals(customerPR_Name)) { customerPR = cache.createRegion(partitionedRegionName, attr.create()); assertNotNull(customerPR); LogWriterUtils.getLogWriter().info( "Partitioned Region " + partitionedRegionName + " created Successfully :" + customerPR); } if (partitionedRegionName.equals(orderPR_Name)) { orderPR = cache.createRegion(partitionedRegionName, attr.create()); assertNotNull(orderPR); LogWriterUtils.getLogWriter().info( "Partitioned Region " + partitionedRegionName + " created Successfully :" + orderPR); } if (partitionedRegionName.equals(shipmentPR_Name)) { shipmentPR = cache.createRegion(partitionedRegionName, attr.create()); assertNotNull(shipmentPR); LogWriterUtils.getLogWriter().info( "Partitioned Region " + partitionedRegionName + " created Successfully :" + shipmentPR); } } private static void putInPRs() { put(); dataStore1.invoke(() -> ColocationFailoverDUnitTest.put()); dataStore2.invoke(() -> ColocationFailoverDUnitTest.put()); dataStore3.invoke(() -> ColocationFailoverDUnitTest.put()); dataStore4.invoke(() -> ColocationFailoverDUnitTest.put()); } public static void put() { for (int i = 0; i < 20; i++) { customerPR.put("CPing--" + i, "CPong--" + i); orderPR.put("OPing--" + i, "OPong--" + i); shipmentPR.put("SPing--" + i, "SPong--" + i); } } @Override public final void preTearDown() throws Exception { closeCache(); Invoke.invokeInEveryVM(new SerializableRunnable() { public void run() { closeCache(); } }); } } class KeyPartitionResolver implements PartitionResolver { public KeyPartitionResolver() {} public String getName() { return this.getClass().getName(); } public Serializable getRoutingObject(EntryOperation opDetails) { // Serializable routingbject = null; String key = (String) opDetails.getKey(); return new RoutingObject("" + key.charAt(key.length() - 1)); } public void close() {} public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof KeyPartitionResolver)) return false; KeyPartitionResolver otherKeyPartitionResolver = (KeyPartitionResolver) o; return otherKeyPartitionResolver.getName().equals(getName()); } } class RoutingObject implements DataSerializable { public RoutingObject(String value) { this.value = value; } private String value; public void fromData(DataInput in) throws IOException, ClassNotFoundException { this.value = DataSerializer.readString(in); } public void toData(DataOutput out) throws IOException { DataSerializer.writeString(this.value, out); } public int hashCode() { return Integer.parseInt(this.value); } }
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.stepfunctions.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/states-2016-11-23/UntagResource" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UntagResourceRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The Amazon Resource Name (ARN) for the Step Functions state machine or activity. * </p> */ private String resourceArn; /** * <p> * The list of tags to remove from the resource. * </p> */ private java.util.List<String> tagKeys; /** * <p> * The Amazon Resource Name (ARN) for the Step Functions state machine or activity. * </p> * * @param resourceArn * The Amazon Resource Name (ARN) for the Step Functions state machine or activity. */ public void setResourceArn(String resourceArn) { this.resourceArn = resourceArn; } /** * <p> * The Amazon Resource Name (ARN) for the Step Functions state machine or activity. * </p> * * @return The Amazon Resource Name (ARN) for the Step Functions state machine or activity. */ public String getResourceArn() { return this.resourceArn; } /** * <p> * The Amazon Resource Name (ARN) for the Step Functions state machine or activity. * </p> * * @param resourceArn * The Amazon Resource Name (ARN) for the Step Functions state machine or activity. * @return Returns a reference to this object so that method calls can be chained together. */ public UntagResourceRequest withResourceArn(String resourceArn) { setResourceArn(resourceArn); return this; } /** * <p> * The list of tags to remove from the resource. * </p> * * @return The list of tags to remove from the resource. */ public java.util.List<String> getTagKeys() { return tagKeys; } /** * <p> * The list of tags to remove from the resource. * </p> * * @param tagKeys * The list of tags to remove from the resource. */ public void setTagKeys(java.util.Collection<String> tagKeys) { if (tagKeys == null) { this.tagKeys = null; return; } this.tagKeys = new java.util.ArrayList<String>(tagKeys); } /** * <p> * The list of tags to remove from the resource. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTagKeys(java.util.Collection)} or {@link #withTagKeys(java.util.Collection)} if you want to override * the existing values. * </p> * * @param tagKeys * The list of tags to remove from the resource. * @return Returns a reference to this object so that method calls can be chained together. */ public UntagResourceRequest withTagKeys(String... tagKeys) { if (this.tagKeys == null) { setTagKeys(new java.util.ArrayList<String>(tagKeys.length)); } for (String ele : tagKeys) { this.tagKeys.add(ele); } return this; } /** * <p> * The list of tags to remove from the resource. * </p> * * @param tagKeys * The list of tags to remove from the resource. * @return Returns a reference to this object so that method calls can be chained together. */ public UntagResourceRequest withTagKeys(java.util.Collection<String> tagKeys) { setTagKeys(tagKeys); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getResourceArn() != null) sb.append("ResourceArn: ").append(getResourceArn()).append(","); if (getTagKeys() != null) sb.append("TagKeys: ").append(getTagKeys()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UntagResourceRequest == false) return false; UntagResourceRequest other = (UntagResourceRequest) obj; if (other.getResourceArn() == null ^ this.getResourceArn() == null) return false; if (other.getResourceArn() != null && other.getResourceArn().equals(this.getResourceArn()) == false) return false; if (other.getTagKeys() == null ^ this.getTagKeys() == null) return false; if (other.getTagKeys() != null && other.getTagKeys().equals(this.getTagKeys()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getResourceArn() == null) ? 0 : getResourceArn().hashCode()); hashCode = prime * hashCode + ((getTagKeys() == null) ? 0 : getTagKeys().hashCode()); return hashCode; } @Override public UntagResourceRequest clone() { return (UntagResourceRequest) super.clone(); } }
/* * Copyright 2015 West Coast Informatics, LLC */ package com.wci.umls.server.jpa.workflow; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.search.annotations.Analyze; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.FieldBridge; import org.hibernate.search.annotations.Fields; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.Store; import org.hibernate.search.bridge.builtin.EnumBridge; import org.hibernate.search.bridge.builtin.LongBridge; import com.wci.umls.server.Project; import com.wci.umls.server.jpa.ProjectJpa; import com.wci.umls.server.jpa.content.ConceptJpa; import com.wci.umls.server.jpa.helpers.CollectionToCsvBridge; import com.wci.umls.server.model.content.Concept; import com.wci.umls.server.model.workflow.TrackingRecord; import com.wci.umls.server.model.workflow.WorkflowStatus; /** * JAXB and JPA enabled implementation of {@link TrackingRecord}. */ @Entity @Table(name = "tracking_records") @Indexed @XmlRootElement(name = "trackingRecord") public class TrackingRecordJpa implements TrackingRecord { /** The id. */ @TableGenerator(name = "EntityIdGenWorkflow", table = "table_generator_wf", pkColumnValue = "Entity") @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "EntityIdGenWorkflow") private Long id; /** The last modified. */ @Column(nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date lastModified = new Date(); /** The last modified. */ @Column(nullable = false) private String lastModifiedBy; /** the timestamp. */ @Column(nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date timestamp = null; /** The component ids . */ @ElementCollection @CollectionTable(name = "component_ids") @Fetch(value = FetchMode.SELECT) private Set<Long> componentIds = new HashSet<>(); /** The cluster id. */ @Column(nullable = false) private Long clusterId; /** The cluster type. */ @Column(nullable = false) private String clusterType; /** The terminology. */ @Column(nullable = false) private String terminology; /** The version. */ @Column(nullable = false) private String version; /** The workflow bin. */ @Column(nullable = true) private String workflowBinName; /** The worklist name. */ @Column(nullable = true) private String worklistName; /** The checklist name. */ @Column(nullable = true) private String checklistName; /** The original concept ids . */ @ElementCollection @CollectionTable(name = "orig_concept_ids") private Set<Long> origConceptIds = new HashSet<>(); /** The concepts. */ @Transient private List<Concept> concepts = new ArrayList<>(); /** The project. */ @ManyToOne(targetEntity = ProjectJpa.class, optional = false) private Project project; /** The workflow status. */ @Enumerated(EnumType.STRING) @Column(nullable = true) private WorkflowStatus workflowStatus; /** The indexed data. */ @Column(nullable = true, length = 4000) private String indexedData; /** The finished. */ @Column(nullable = false) private boolean finished = false; /** * Instantiates an empty {@link TrackingRecordJpa}. */ public TrackingRecordJpa() { // do nothing } /** * Instantiates a {@link TrackingRecordJpa} from the specified parameters. * * @param record the record */ public TrackingRecordJpa(TrackingRecord record) { id = record.getId(); lastModified = record.getLastModified(); lastModifiedBy = record.getLastModifiedBy(); timestamp = record.getTimestamp(); clusterId = record.getClusterId(); clusterType = record.getClusterType(); terminology = record.getTerminology(); version = record.getVersion(); componentIds = new HashSet<>(record.getComponentIds()); origConceptIds = new HashSet<>(record.getOrigConceptIds()); workflowBinName = record.getWorkflowBinName(); worklistName = record.getWorklistName(); checklistName = record.getChecklistName(); project = record.getProject(); workflowStatus = record.getWorkflowStatus(); indexedData = record.getIndexedData(); finished = record.isFinished(); } /* see superclass */ @Override @FieldBridge(impl = LongBridge.class) @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) public Long getId() { return this.id; } /* see superclass */ @Override public void setId(Long id) { this.id = id; } /* see superclass */ @Override public Date getLastModified() { return lastModified; } /* see superclass */ @Override public void setLastModified(Date lastModified) { this.lastModified = lastModified; } /* see superclass */ @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) @Override public String getLastModifiedBy() { return lastModifiedBy; } /* see superclass */ @Override public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } /* see superclass */ @Field(bridge = @FieldBridge(impl = CollectionToCsvBridge.class), index = Index.YES, analyze = Analyze.YES, store = Store.NO) @Override public Set<Long> getComponentIds() { if (componentIds == null) { componentIds = new HashSet<>(); } return componentIds; } /* see superclass */ @Override public void setComponentIds(Set<Long> componentIds) { this.componentIds = componentIds; } /* see superclass */ @Field(bridge = @FieldBridge(impl = CollectionToCsvBridge.class), index = Index.YES, analyze = Analyze.YES, store = Store.NO) @Override public Set<Long> getOrigConceptIds() { if (origConceptIds == null) { origConceptIds = new HashSet<>(); } return origConceptIds; } /* see superclass */ @Override public void setOrigConceptIds(Set<Long> origConceptIds) { this.origConceptIds = origConceptIds; } /* see superclass */ @Override @XmlElement(type = ConceptJpa.class) public List<Concept> getConcepts() { if (concepts == null) { concepts = new ArrayList<>(); } return concepts; } /* see superclass */ @Override public void setConcepts(List<Concept> concepts) { this.concepts = concepts; } /* see superclass */ @Override @Fields({ @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO, bridge = @FieldBridge(impl = LongBridge.class)), @Field(name = "clusterIdSort", index = Index.YES, analyze = Analyze.NO, store = Store.NO) }) public Long getClusterId() { return clusterId; } /* see superclass */ @Override public void setClusterId(Long clusterId) { this.clusterId = clusterId; } /* see superclass */ @Override public Date getTimestamp() { return timestamp; } /* see superclass */ @Override public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } /* see superclass */ @Override @XmlTransient public Project getProject() { return project; } /* see superclass */ @Override public void setProject(Project project) { this.project = project; } /** * Returns the project id. * * @return the project id */ @FieldBridge(impl = LongBridge.class) @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) public Long getProjectId() { return project == null ? null : project.getId(); } /** * Sets the project id. * * @param projectId the project id */ public void setProjectId(Long projectId) { if (project == null) { project = new ProjectJpa(); } project.setId(projectId); } /* see superclass */ @Override @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) public String getTerminology() { return terminology; } /* see superclass */ @Override public void setTerminology(String terminology) { this.terminology = terminology; } /* see superclass */ @Override @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) public String getVersion() { return version; } /* see superclass */ @Override public void setVersion(String version) { this.version = version; } /* see superclass */ @Fields({ @Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO), @Field(name = "indexedDataSort", index = Index.YES, analyze = Analyze.NO, store = Store.NO) }) @Override public String getIndexedData() { return indexedData; } /* see superclass */ @Override public void setIndexedData(String indexedData) { if (indexedData.length() > 4000) { this.indexedData = indexedData.substring(0, 3999); } else { this.indexedData = indexedData; } } /* see superclass */ @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) @Override public String getClusterType() { return clusterType; } /* see superclass */ @Override public void setClusterType(String clusterType) { this.clusterType = clusterType; } /* see superclass */ @Override @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) public String getWorkflowBinName() { return workflowBinName; } /* see superclass */ @Override public void setWorkflowBinName(String workflowBin) { this.workflowBinName = workflowBin; } /* see superclass */ @Override @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) public String getWorklistName() { return worklistName; } /* see superclass */ @Override public void setWorklistName(String worklist) { this.worklistName = worklist; } /* see superclass */ @Override @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) public String getChecklistName() { return checklistName; } /* see superclass */ @Override public void setChecklistName(String checklistName) { this.checklistName = checklistName; } /* see superclass */ @Override @FieldBridge(impl = EnumBridge.class) @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) public WorkflowStatus getWorkflowStatus() { return workflowStatus; } /* see superclass */ @Override public void setWorkflowStatus(WorkflowStatus workflowStatus) { this.workflowStatus = workflowStatus; } /* see superclass */ @Override @Field(index = Index.YES, analyze = Analyze.NO, store = Store.NO) public boolean isFinished() { return finished; } /* see superclass */ @Override public void setFinished(boolean finished) { this.finished = finished; } /* see superclass */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((clusterId == null) ? 0 : clusterId.hashCode()); result = prime * result + ((clusterType == null) ? 0 : clusterType.hashCode()); result = prime * result + ((componentIds == null) ? 0 : componentIds.hashCode()); result = prime * result + ((origConceptIds == null) ? 0 : origConceptIds.hashCode()); result = prime * result + ((project == null) ? 0 : project.hashCode()); result = prime * result + ((terminology == null) ? 0 : terminology.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); result = prime * result + ((workflowBinName == null) ? 0 : workflowBinName.hashCode()); result = prime * result + ((worklistName == null) ? 0 : worklistName.hashCode()); result = prime * result + ((checklistName == null) ? 0 : checklistName.hashCode()); result = prime * result + (finished ? 1231 : 1237); return result; } /* see superclass */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TrackingRecordJpa other = (TrackingRecordJpa) obj; if (clusterId == null) { if (other.clusterId != null) return false; } else if (!clusterId.equals(other.clusterId)) return false; if (clusterType == null) { if (other.clusterType != null) return false; } else if (!clusterType.equals(other.clusterType)) return false; if (componentIds == null) { if (other.componentIds != null) return false; } else if (!componentIds.equals(other.componentIds)) return false; if (origConceptIds == null) { if (other.origConceptIds != null) return false; } else if (!origConceptIds.equals(other.origConceptIds)) return false; if (project == null) { if (other.project != null) return false; } else if (!project.equals(other.project)) return false; if (terminology == null) { if (other.terminology != null) return false; } else if (!terminology.equals(other.terminology)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; if (workflowBinName == null) { if (other.workflowBinName != null) return false; } else if (!workflowBinName.equals(other.workflowBinName)) return false; if (worklistName == null) { if (other.worklistName != null) return false; } else if (!worklistName.equals(other.worklistName)) return false; if (checklistName == null) { if (other.checklistName != null) return false; } else if (!checklistName.equals(other.checklistName)) return false; if (finished != other.finished) return false; return true; } /* see superclass */ @Override public String toString() { return "TrackingRecordJpa [id=" + id + ", lastModified=" + lastModified + ", lastModifiedBy=" + lastModifiedBy + ", timestamp=" + timestamp + ", componentIds=" + componentIds + ", clusterId=" + clusterId + ", clusterType=" + clusterType + ", terminology=" + terminology + ", version=" + version + ", origConceptIds=" + origConceptIds + ", project=" + project + "]"; } }
package hudson.cli; import com.google.common.collect.Lists; import hudson.Functions; import hudson.Launcher; import hudson.Proc; import hudson.model.AllView; import hudson.model.Item; import hudson.model.User; import hudson.util.ProcessTree; import hudson.util.StreamTaskListener; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintWriter; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import jenkins.model.Jenkins; import jenkins.security.ApiTokenProperty; import jenkins.security.apitoken.ApiTokenTestHelper; import jenkins.util.FullDuplexHttpService; import jenkins.util.Timer; import org.apache.commons.io.FileUtils; import org.apache.commons.io.output.TeeOutputStream; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.LoggerRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.TestExtension; import org.jvnet.hudson.test.recipes.PresetData; import org.jvnet.hudson.test.recipes.PresetData.DataSet; public class CLIActionTest { @Rule public JenkinsRule j = new JenkinsRule(); @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Rule public LoggerRule logging = new LoggerRule(); private ExecutorService pool; @Test @PresetData(DataSet.NO_ANONYMOUS_READACCESS) @Issue("SECURITY-192") public void serveCliActionToAnonymousUserWithoutPermissions() throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); // The behavior changed due to SECURITY-192. index page is no longer accessible to anonymous wc.assertFails("cli", HttpURLConnection.HTTP_FORBIDDEN); } @Test public void serveCliActionToAnonymousUserWithAnonymousUserWithPermissions() throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); wc.goTo("cli"); } @Issue({"JENKINS-12543", "JENKINS-41745"}) @Test public void authentication() throws Exception { ApiTokenTestHelper.enableLegacyBehavior(); logging.record(PlainCLIProtocol.class, Level.FINE); File jar = tmp.newFile("jenkins-cli.jar"); FileUtils.copyURLToFile(j.jenkins.getJnlpJars("jenkins-cli.jar").getURL(), jar); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to(ADMIN)); j.createFreeStyleProject("p"); // CLICommand with @Argument: assertExitCode(6, false, jar, "get-job", "p"); // SECURITY-754 requires Overall/Read for nearly all CLICommands. assertExitCode(0, true, jar, "get-job", "p"); // but API tokens do work under HTTP protocol // @CLIMethod: assertExitCode(6, false, jar, "disable-job", "p"); // AccessDeniedException from CLIRegisterer? assertExitCode(0, true, jar, "disable-job", "p"); // If we have anonymous read access, then the situation is simpler. j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to(ADMIN).grant(Jenkins.READ, Item.READ).everywhere().toEveryone()); assertExitCode(6, false, jar, "get-job", "p"); // AccessDeniedException from AbstractItem.writeConfigDotXml assertExitCode(0, true, jar, "get-job", "p"); // works with API tokens assertExitCode(6, false, jar, "disable-job", "p"); // AccessDeniedException from AbstractProject.doDisable assertExitCode(0, true, jar, "disable-job", "p"); } private static final String ADMIN = "admin@mycorp.com"; private void assertExitCode(int code, boolean useApiToken, File jar, String... args) throws IOException, InterruptedException { List<String> commands = Lists.newArrayList("java", "-jar", jar.getAbsolutePath(), "-s", j.getURL().toString(), /* not covering SSH keys in this test */ "-noKeyAuth"); if (useApiToken) { commands.add("-auth"); commands.add(ADMIN + ":" + User.get(ADMIN).getProperty(ApiTokenProperty.class).getApiToken()); } commands.addAll(Arrays.asList(args)); final Launcher.LocalLauncher launcher = new Launcher.LocalLauncher(StreamTaskListener.fromStderr()); final Proc proc = launcher.launch().cmds(commands).stdout(System.out).stderr(System.err).start(); if (!Functions.isWindows()) { // Try to get a thread dump of the client if it hangs. Timer.get().schedule(new Runnable() { @Override public void run() { try { if (proc.isAlive()) { Field procF = Proc.LocalProc.class.getDeclaredField("proc"); procF.setAccessible(true); ProcessTree.OSProcess osp = ProcessTree.get().get((Process) procF.get(proc)); if (osp != null) { launcher.launch().cmds("kill", "-QUIT", Integer.toString(osp.getPid())).stdout(System.out).stderr(System.err).join(); } } } catch (Exception x) { throw new AssertionError(x); } } }, 1, TimeUnit.MINUTES); } assertEquals(code, proc.join()); } @Issue("JENKINS-41745") @Test public void encodingAndLocale() throws Exception { File jar = tmp.newFile("jenkins-cli.jar"); FileUtils.copyURLToFile(j.jenkins.getJnlpJars("jenkins-cli.jar").getURL(), jar); ByteArrayOutputStream baos = new ByteArrayOutputStream(); assertEquals(0, new Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().cmds( "java", "-Dfile.encoding=ISO-8859-2", "-Duser.language=cs", "-Duser.country=CZ", "-jar", jar.getAbsolutePath(), "-s", j.getURL().toString()./* just checking */replaceFirst("/$", ""), "-noKeyAuth", "test-diagnostic"). stdout(baos).stderr(System.err).join()); assertEquals("encoding=ISO-8859-2 locale=cs_CZ", baos.toString().trim()); // TODO test that stdout/stderr are in expected encoding (not true of -remoting mode!) // -ssh mode does not pass client locale or encoding } @Issue("JENKINS-41745") @Test public void interleavedStdio() throws Exception { logging.record(PlainCLIProtocol.class, Level.FINE).record(FullDuplexHttpService.class, Level.FINE); File jar = tmp.newFile("jenkins-cli.jar"); FileUtils.copyURLToFile(j.jenkins.getJnlpJars("jenkins-cli.jar").getURL(), jar); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(pis); PrintWriter pw = new PrintWriter(new TeeOutputStream(pos, System.err), true); Proc proc = new Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().cmds( "java", "-jar", jar.getAbsolutePath(), "-s", j.getURL().toString(), "-noKeyAuth", "groovysh"). stdout(new TeeOutputStream(baos, System.out)).stderr(System.err).stdin(pis).start(); while (!baos.toString().contains("000")) { // cannot just search for, say, "groovy:000> " since there are ANSI escapes there (cf. StringEscapeUtils.escapeJava) Thread.sleep(100); } pw.println("11 * 11"); while (!baos.toString().contains("121")) { // ditto not "===> 121" Thread.sleep(100); } Thread.sleep(31_000); // aggravate org.eclipse.jetty.io.IdleTimeout (cf. AbstractConnector._idleTimeout) pw.println("11 * 11 * 11"); while (!baos.toString().contains("1331")) { Thread.sleep(100); } pw.println(":q"); assertEquals(0, proc.join()); } @Issue("SECURITY-754") @Test public void noPreAuthOptionHandlerInfoLeak() throws Exception { File jar = tmp.newFile("jenkins-cli.jar"); FileUtils.copyURLToFile(j.jenkins.getJnlpJars("jenkins-cli.jar").getURL(), jar); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.addView(new AllView("v1")); j.jenkins.addNode(j.createSlave("n1", null, null)); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to(ADMIN)); // No anonymous read access assertExitCode(6, false, jar, "get-view", "v1"); assertExitCode(6, false, jar, "get-view", "v2"); // Error code 3 before SECURITY-754 assertExitCode(6, false, jar, "get-node", "n1"); assertExitCode(6, false, jar, "get-node", "n2"); // Error code 3 before SECURITY-754 // Authenticated with no read access assertExitCode(6, false, jar, "-auth", "user:user", "get-view", "v1"); assertExitCode(6, false, jar, "-auth", "user:user", "get-view", "v2"); // Error code 3 before SECURITY-754 assertExitCode(6, false, jar, "-auth", "user:user", "get-node", "n1"); assertExitCode(6, false, jar, "-auth", "user:user", "get-node", "n2"); // Error code 3 before SECURITY-754 // Anonymous read access j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to(ADMIN).grant(Jenkins.READ, Item.READ).everywhere().toEveryone()); assertExitCode(6, false, jar, "get-view", "v1"); assertExitCode(6, false, jar, "get-view", "v2"); // Error code 3 before SECURITY-754 } @TestExtension("encodingAndLocale") public static class TestDiagnosticCommand extends CLICommand { @Override public String getShortDescription() { return "Print information about the command environment."; } @Override protected int run() throws Exception { stdout.println("encoding=" + getClientCharset() + " locale=" + locale); return 0; } } }
package de.hpi.petrinet; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.w3c.dom.Document; import de.hpi.PTnet.PTNet; import de.hpi.PTnet.PTNetFactory; import de.hpi.diagram.verification.SyntaxChecker; import de.hpi.petrinet.serialization.PetriNetPNMLExporter; import de.hpi.petrinet.serialization.XMLFileLoaderSaver; import de.hpi.petrinet.verification.PetriNetInterpreter; import de.hpi.petrinet.verification.PetriNetSyntaxChecker; /** * Copyright (c) 2008 Gero Decker, Matthias Weidlich * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ public class PetriNet implements Cloneable { protected List<Place> places; protected List<Transition> transitions; protected List<FlowRelationship> flowRelationships; protected List<Place> finalPlaces; protected List<Place> initialPlaces; protected TransitiveClosure transitiveClosure; protected Map<Node,Set<Node>> dominators; protected Map<Node,Set<Node>> postdominators; protected String id; public List<FlowRelationship> getFlowRelationships() { if (flowRelationships == null) flowRelationships = new MyFlowRelationshipList(); return flowRelationships; } public List<Place> getPlaces() { if (places == null) places = new ArrayList<Place>(); return places; } public List<Transition> getTransitions() { if (transitions == null) transitions = new ArrayList<Transition>(); return transitions; } public List<Node> getLabeledTransitions() { List<Node> result = new ArrayList<Node>(); for(Transition t : getTransitions()) if (t instanceof LabeledTransition) result.add((LabeledTransition)t); return result; } public List<Node> getNodes() { List<Node> nodes = new ArrayList<Node>(); nodes.addAll(getPlaces()); nodes.addAll(getTransitions()); return nodes; } public SyntaxChecker getSyntaxChecker() { return new PetriNetSyntaxChecker(this); } /** * Creates a deep copy of whole Petri net. All places, * transitions and flows are copied, whereas the source * and targets for the latter are also set accordingly. * * @return the clone of the Petri net */ @Override public Object clone() throws CloneNotSupportedException { PetriNet clone = (PetriNet) super.clone(); Map<Node,Node> nodeCopies = new HashMap<Node, Node>(); clone.setPlaces(new ArrayList<Place>()); // will be generated when needed clone.setInitialPlaces(null); clone.setFinalPlaces(null); for(Place p : this.getPlaces()) { Place p2 = (Place) p.clone(); clone.getPlaces().add(p2); nodeCopies.put(p, p2); } clone.setTransitions(new ArrayList<Transition>()); for(Transition t : this.getTransitions()) { Transition t2 = (Transition) t.clone(); clone.getTransitions().add(t2); nodeCopies.put(t, t2); } clone.setFlowRelationships(new MyFlowRelationshipList()); for(FlowRelationship f : this.getFlowRelationships()) { FlowRelationship newF = (FlowRelationship) f.clone(); newF.setSource(nodeCopies.get(f.getSource())); newF.setTarget(nodeCopies.get(f.getTarget())); clone.getFlowRelationships().add(newF); } // will be generated if needed clone.setTransitiveClosure(null); return clone; } public PetriNetFactory getFactory() { return PetriNetFactory.eINSTANCE; } public Marking getInitialMarking() { return null; } // public void optimize(Map<String,Boolean> parameters) { // boolean changed = false; // do { // changed = false; // if (parameters != null) // for (Iterator<Entry<String,Boolean>> it=parameters.entrySet().iterator(); it.hasNext(); ) { // Entry<String,Boolean> e = it.next(); // if (e.getValue().booleanValue()) // changed |= doOptimization(e.getKey()); // } // } while (changed); // } // // protected boolean doOptimization(String parameter) { // return false; // } // protected boolean doOptimization(Map<String,Boolean> parameters, String parameter) { // if (parameters == null) // return false; // Boolean b = parameters.get(parameter); // if (b == null) // return false; // else // return b.booleanValue(); // } public PetriNetInterpreter getInterpreter() { return null; } @Override public String toString() { try { XMLFileLoaderSaver ls = new XMLFileLoaderSaver(); Document doc = ls.createNewDocument(); new PetriNetPNMLExporter().savePetriNet(doc, this); return ls.serializeToString(doc); } catch (Exception e) { return super.toString(); } } /** * Returns all final places of this petri net (cached). */ public List<Place> getFinalPlaces(){ if (finalPlaces == null) { finalPlaces = new LinkedList<Place>(); for (Place place : this.getPlaces()) { if (place.isFinalPlace()) { finalPlaces.add(place); } } } return finalPlaces; } /** * Returns the first final place, intended for use in workflow nets. */ public Place getFinalPlace(){ return this.getFinalPlaces().get(0); } /** * Returns all initial places of this petri net (cached). */ public List<Place> getInitialPlaces(){ if (initialPlaces == null) { initialPlaces = new LinkedList<Place>(); for (Place place : this.getPlaces()) { if (place.isInitialPlace()) { initialPlaces.add(place); } } } return initialPlaces; } /** * Returns the first initial place, intended for use in workflow nets. */ public Place getInitialPlace(){ return this.getInitialPlaces().get(0); } /** * Checks whether the net is a free choice net. * * @return true, if the net is free-choice */ public boolean isFreeChoiceNet() { boolean isFC = true; outer: for(Transition t1 : this.getTransitions()) { for(Transition t2 : this.getTransitions()) { if (t1.equals(t2)) continue; Collection<Node> preT1 = t1.getPrecedingNodes(); Collection<Node> preT2 = t2.getPrecedingNodes(); if (CollectionUtils.containsAny(preT1, preT2)) { preT1.retainAll(preT2); boolean tmp = (preT1.size() == preT2.size()); isFC &= tmp; if (!isFC) break outer; } } } return isFC; } /** * Checks whether the net is a workflow net. Such a net has * exactly one initial and one final place and every place and * transition is one a path from i to o. * * @return true, if the net is a workflow net */ public boolean isWorkflowNet() { boolean isWF = (this.getInitialPlaces().size() == 1) && (this.getFinalPlaces().size() == 1); // maybe we already know that the net is not a workflow net if (!isWF) return isWF; Node in = this.getInitialPlace(); Node out = this.getFinalPlace(); for (Node n : this.getNodes()) { if (n.equals(in) || n.equals(out)) continue; isWF &= this.getTransitiveClosure().isPath(in, n); isWF &= this.getTransitiveClosure().isPath(n, out); } return isWF; } public PTNet getSubnet(Collection<Node> nodes) { PTNet net = PTNetFactory.eINSTANCE.createPetriNet(); Map<Node,Node> nodeCopies = new HashMap<Node, Node>(); try { for(Node n : nodes) { if (nodes.contains(n)) { if (n instanceof Place) { Place c = (Place) ((Place) n).clone(); net.getPlaces().add(c); nodeCopies.put(n, c); } else { Transition c = (Transition) ((Transition) n).clone(); net.getTransitions().add(c); nodeCopies.put(n, c); } } } for(FlowRelationship f : this.getFlowRelationships()) { if (nodes.contains(f.getSource()) && nodes.contains(f.getTarget())) { FlowRelationship c = new FlowRelationship(); c.setSource(nodeCopies.get(f.getSource())); c.setTarget(nodeCopies.get(f.getTarget())); net.getFlowRelationships().add(f); } } } catch (Exception e) { e.printStackTrace(); } return net; } /** * Checks whether the net is an S-net. * * @return true, if net is an S-net. */ public boolean isSNet() { boolean result = true; for (Transition t : this.getTransitions()) result &= (t.getIncomingFlowRelationships().size() == 1) && ((t.getOutgoingFlowRelationships().size() == 1)); return result; } /** * Checks whether the net is a T-net. * * @return true, if net is a T-net. */ public boolean isTNet() { boolean result = true; for (Place p : this.getPlaces()) result &= (p.getIncomingFlowRelationships().size() == 1) && ((p.getOutgoingFlowRelationships().size() == 1)); return result; } public Map<Node, Set<Node>> getDominators() { if (this.dominators == null) this.dominators = deriveDominators(false); return this.dominators; } public Map<Node, Set<Node>> getPostDominators() { if (this.postdominators == null) this.postdominators = deriveDominators(true); return this.postdominators; } protected Map<Node,Set<Node>> deriveDominators(boolean reverse) { int initIndex = reverse ? this.getNodes().indexOf(this.getFinalPlace()) : this.getNodes().indexOf(this.getInitialPlace()); int size = this.getNodes().size(); final BitSet[] dom = new BitSet[size]; final BitSet ALL = new BitSet(size); for (Node n : this.getNodes()) ALL.set(this.getNodes().indexOf(n)); for (Node n : this.getNodes()) { int index = this.getNodes().indexOf(n); BitSet curDoms = new BitSet(size); dom[index] = curDoms; if (index != initIndex) curDoms.or(ALL); else curDoms.set(initIndex); } boolean changed = true; /* * While we change the dom relation for a node */ while (changed) { changed = false; for (Node n : this.getNodes()) { int index = this.getNodes().indexOf(n); if (index == initIndex) continue; final BitSet old = dom[index]; final BitSet curDoms = new BitSet(size); curDoms.or(old); Collection<Node> predecessors = reverse ? n.getSucceedingNodes() : n.getPrecedingNodes(); for (Node p : predecessors) { int index2 = this.getNodes().indexOf(p); curDoms.and(dom[index2]); } curDoms.set(index); if (!curDoms.equals(old)) { changed = true; dom[index] = curDoms; } } } Map<Node,Set<Node>> dominators = new HashMap<Node, Set<Node>>(); for (Node n : this.getNodes()) { int index = this.getNodes().indexOf(n); dominators.put(n, new HashSet<Node>()); for (int i = 0; i < size; i++) if (dom[index].get(i)) dominators.get(n).add(this.getNodes().get(i)); } return dominators; } protected class MyFlowRelationshipList extends ArrayList<FlowRelationship> { private static final long serialVersionUID = 7350067193890668068L; @Override public FlowRelationship remove(int index) { FlowRelationship rel = super.remove(index); if (rel != null) { rel.setSource(null); rel.setTarget(null); } return rel; } @Override public boolean remove(Object o) { boolean removed = super.remove(o); if (removed) { ((FlowRelationship)o).setSource(null); ((FlowRelationship)o).setTarget(null); } return removed; } @Override protected void removeRange(int fromIndex, int toIndex) { for (int i=fromIndex; i<toIndex; i++) { FlowRelationship rel = get(i); rel.setSource(null); rel.setTarget(null); } super.removeRange(fromIndex, toIndex); } @Override public boolean removeAll(Collection<?> mylist) { for (Iterator<?> it=mylist.iterator(); it.hasNext(); ) { FlowRelationship rel = (FlowRelationship)it.next(); rel.setSource(null); rel.setTarget(null); } return super.removeAll(mylist); } } public TransitiveClosure getTransitiveClosure() { if (this.transitiveClosure == null) this.transitiveClosure = new TransitiveClosure(this); return this.transitiveClosure; } public void setPlaces(List<Place> places) { this.places = places; } public void setTransitions(List<Transition> transitions) { this.transitions = transitions; } public void setFlowRelationships(List<FlowRelationship> flowRelationships) { this.flowRelationships = flowRelationships; } public void setFinalPlaces(List<Place> finalPlaces) { this.finalPlaces = finalPlaces; } public void setInitialPlaces(List<Place> initialPlaces) { this.initialPlaces = initialPlaces; } public void setTransitiveClosure(TransitiveClosure transitiveClosure) { this.transitiveClosure = transitiveClosure; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.builder.component.dsl; import javax.annotation.Generated; import org.apache.camel.Component; import org.apache.camel.builder.component.AbstractComponentBuilder; import org.apache.camel.builder.component.ComponentBuilder; import org.apache.camel.component.websocket.WebsocketComponent; /** * Expose websocket endpoints using Jetty. * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.ComponentDslMojo") public interface WebsocketComponentBuilderFactory { /** * Jetty Websocket (camel-websocket) * Expose websocket endpoints using Jetty. * * Category: websocket * Since: 2.10 * Maven coordinates: org.apache.camel:camel-websocket * * @return the dsl builder */ static WebsocketComponentBuilder websocket() { return new WebsocketComponentBuilderImpl(); } /** * Builder for the Jetty Websocket component. */ interface WebsocketComponentBuilder extends ComponentBuilder<WebsocketComponent> { /** * The hostname. The default value is 0.0.0.0. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: 0.0.0.0 * Group: common * * @param host the value to set * @return the dsl builder */ default WebsocketComponentBuilder host(java.lang.String host) { doSetProperty("host", host); return this; } /** * The port number. The default value is 9292. * * The option is a: &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Default: 9292 * Group: common * * @param port the value to set * @return the dsl builder */ default WebsocketComponentBuilder port(java.lang.Integer port) { doSetProperty("port", port); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default WebsocketComponentBuilder bridgeErrorHandler( boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Set a resource path for static resources (such as .html files etc). * The resources can be loaded from classpath, if you prefix with * classpath:, otherwise the resources is loaded from file system or * from JAR files. For example to load from root classpath use * classpath:., or classpath:WEB-INF/static If not configured (eg null) * then no static resource is in use. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: consumer * * @param staticResources the value to set * @return the dsl builder */ default WebsocketComponentBuilder staticResources( java.lang.String staticResources) { doSetProperty("staticResources", staticResources); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default WebsocketComponentBuilder lazyStartProducer( boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default WebsocketComponentBuilder autowiredEnabled( boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * If this option is true, Jetty JMX support will be enabled for this * endpoint. See Jetty JMX support for more details. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param enableJmx the value to set * @return the dsl builder */ default WebsocketComponentBuilder enableJmx(boolean enableJmx) { doSetProperty("enableJmx", enableJmx); return this; } /** * To set a value for maximum number of threads in server thread pool. * MaxThreads/minThreads or threadPool fields are required due to switch * to Jetty9. The default values for maxThreads is 1 2 noCores. * * The option is a: &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Group: advanced * * @param maxThreads the value to set * @return the dsl builder */ default WebsocketComponentBuilder maxThreads( java.lang.Integer maxThreads) { doSetProperty("maxThreads", maxThreads); return this; } /** * To set a value for minimum number of threads in server thread pool. * MaxThreads/minThreads or threadPool fields are required due to switch * to Jetty9. The default values for minThreads is 1. * * The option is a: &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Group: advanced * * @param minThreads the value to set * @return the dsl builder */ default WebsocketComponentBuilder minThreads( java.lang.Integer minThreads) { doSetProperty("minThreads", minThreads); return this; } /** * To use a custom thread pool for the server. MaxThreads/minThreads or * threadPool fields are required due to switch to Jetty9. * * The option is a: * &lt;code&gt;org.eclipse.jetty.util.thread.ThreadPool&lt;/code&gt; * type. * * Group: advanced * * @param threadPool the value to set * @return the dsl builder */ default WebsocketComponentBuilder threadPool( org.eclipse.jetty.util.thread.ThreadPool threadPool) { doSetProperty("threadPool", threadPool); return this; } /** * To configure security using SSLContextParameters. * * The option is a: * &lt;code&gt;org.apache.camel.support.jsse.SSLContextParameters&lt;/code&gt; type. * * Group: security * * @param sslContextParameters the value to set * @return the dsl builder */ default WebsocketComponentBuilder sslContextParameters( org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) { doSetProperty("sslContextParameters", sslContextParameters); return this; } /** * The password for the keystore when using SSL. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param sslKeyPassword the value to set * @return the dsl builder */ default WebsocketComponentBuilder sslKeyPassword( java.lang.String sslKeyPassword) { doSetProperty("sslKeyPassword", sslKeyPassword); return this; } /** * The path to the keystore. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param sslKeystore the value to set * @return the dsl builder */ default WebsocketComponentBuilder sslKeystore( java.lang.String sslKeystore) { doSetProperty("sslKeystore", sslKeystore); return this; } /** * The password when using SSL. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param sslPassword the value to set * @return the dsl builder */ default WebsocketComponentBuilder sslPassword( java.lang.String sslPassword) { doSetProperty("sslPassword", sslPassword); return this; } /** * Enable usage of global SSL context parameters. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useGlobalSslContextParameters the value to set * @return the dsl builder */ default WebsocketComponentBuilder useGlobalSslContextParameters( boolean useGlobalSslContextParameters) { doSetProperty("useGlobalSslContextParameters", useGlobalSslContextParameters); return this; } } class WebsocketComponentBuilderImpl extends AbstractComponentBuilder<WebsocketComponent> implements WebsocketComponentBuilder { @Override protected WebsocketComponent buildConcreteComponent() { return new WebsocketComponent(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "host": ((WebsocketComponent) component).setHost((java.lang.String) value); return true; case "port": ((WebsocketComponent) component).setPort((java.lang.Integer) value); return true; case "bridgeErrorHandler": ((WebsocketComponent) component).setBridgeErrorHandler((boolean) value); return true; case "staticResources": ((WebsocketComponent) component).setStaticResources((java.lang.String) value); return true; case "lazyStartProducer": ((WebsocketComponent) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((WebsocketComponent) component).setAutowiredEnabled((boolean) value); return true; case "enableJmx": ((WebsocketComponent) component).setEnableJmx((boolean) value); return true; case "maxThreads": ((WebsocketComponent) component).setMaxThreads((java.lang.Integer) value); return true; case "minThreads": ((WebsocketComponent) component).setMinThreads((java.lang.Integer) value); return true; case "threadPool": ((WebsocketComponent) component).setThreadPool((org.eclipse.jetty.util.thread.ThreadPool) value); return true; case "sslContextParameters": ((WebsocketComponent) component).setSslContextParameters((org.apache.camel.support.jsse.SSLContextParameters) value); return true; case "sslKeyPassword": ((WebsocketComponent) component).setSslKeyPassword((java.lang.String) value); return true; case "sslKeystore": ((WebsocketComponent) component).setSslKeystore((java.lang.String) value); return true; case "sslPassword": ((WebsocketComponent) component).setSslPassword((java.lang.String) value); return true; case "useGlobalSslContextParameters": ((WebsocketComponent) component).setUseGlobalSslContextParameters((boolean) value); return true; default: return false; } } } }
package jabs; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.AbstractMap; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * ABS Functional layer as Java 8 API. */ public final class Functional { private static final String ANSI_RESET = "\u001B[0m"; private static final String ANSI_GREEN = "\u001B[32m"; private static final String ANSI_RED = "\u001B[31m"; private static final Random RANDOM = new Random(Clock.systemUTC().millis()); /** * A pattern matching abstraction in Java 8. * * @param <X> * @param <Y> */ public static interface Match<X, Y> extends Function<X, Optional<Y>> { static <X, Y> Function<X, Optional<Y>> F(Predicate<X> cond, Function<X, Y> what) { Function<X, Optional<Y>> f = (x) -> cond.test(x) ? Optional.ofNullable(what.apply(x)) : Optional.empty(); return f; } static <X, Y> Match<X, Y> of(Predicate<X> cond, Function<X, Y> what) { Match<X, Y> m = input -> F(cond, what).apply(input); return m; } static <X, Y> Match<X, Y> of(Y origin) { Predicate<X> cond = ignored -> true; Function<X, Y> what = x -> origin; return of(cond, what); } static <X, Y> Match<X, Y> ofNull(Function<X, Y> what) { return of(x -> x == null, what); } static <X, Y> Match<X, Y> equals(X x, Y y) { Predicate<X> cond = input -> Objects.equals(x, input); Function<X, Y> what = ignored -> y; return of(cond, what); } default Match<X, Y> orDefault(Function<X, Y> what) { return or(ignored -> true, what); } default Match<X, Y> orEquals(X x, Y y) { Predicate<X> cond = input -> Objects.equals(x, input); Function<X, Y> what = ignored -> y; return or(cond, what); } default Match<X, Y> or(Predicate<X> cond, Function<X, Y> what) { Match<X, Y> orM = input -> { Optional<Y> thisMatch = apply(input); return thisMatch.isPresent() ? thisMatch : of(cond, what).apply(input); }; return orM; } } /** * An extension over {@link Map.Entry} * * @param <X> * @param <Y> */ public static interface Pair<X, Y> extends Map.Entry<X, Y> { /** * An implementation of {@link Pair} using * {@link SimpleEntry}. * * @param <X> * @param <Y> */ static class SimplePair<X, Y> extends AbstractMap.SimpleEntry<X, Y> implements Pair<X, Y> { private static final long serialVersionUID = 1L; /** * Ctor. * * @param key the first element * @param value the second element */ public SimplePair(X key, Y value) { super(key, value); } } public static <A, B> Pair<A, B> newPair(A a, B b) { return new SimplePair<A, B>(a, b); } default X getFirst() { return getKey(); } default Y getSecond() { return getValue(); } default void setSecond(Y second) { setValue(second); } } // -- Pair Constructor // --- Arithmetic public static <X> X max(X x, X y) { if (x instanceof Comparable == false) { return Objects.equals(x, y) ? x : null; } Comparable<X> cx = (Comparable<X>) x; final int c = cx.compareTo(y); return c >= 0 ? x : y; } public static <X> X min(X x, X y) { X max = max(x, y); return max == null ? null : max == x ? y : x; } public static int random(int bound) { return RANDOM.nextInt(bound); } // --- Logical public static boolean and(final boolean a, final boolean b) { return a && b; } public static boolean not(final boolean a) { return !a; } public static boolean or(final boolean a, final boolean b) { return a || b; } // --- List /** * Same as {@link #emptyList()}. * * @return a new empty {@link List}. * @deprecated Use {@link #emptyList()}. */ public static <E> List<E> EmptyList() { return emptyList(); } public static <E> List<E> Nil() { return emptyList(); } public static <E> List<E> emptyList() { return new LinkedList<>(); } public static <E> List<E> insert(E e, List<E> list) { if (list == null) { list = emptyList(); } return (List<E>) insertCollection(e, list); } /** * Same as {@link #insert(Object, List)} * * @param list the list * @param e the element * @return the updated list * @deprecated Use {@link #insert(Object, List)} */ public static <E> List<E> insertElement(List<E> list, E e) { return (List<E>) insertCollection(e, list); } public static <E> List<E> remove(List<E> list, E e) { return (List<E>) removeCollection(e, list); } public static <E> List<E> list(Set<E> set) { final List<E> list = emptyList(); if (set == null) { return list; } list.addAll(set); return list; } public static <E> List<E> list(E... args) { if (args == null || args.length == 0) { return emptyList(); } List<E> asList = Arrays.asList(args); List<E> result = emptyList(); result.addAll(asList); return result; } public static <E> boolean contains(List<E> list, E e) { return containsCollection(e, list); } public static <E> int size(List<E> list) { return sizeCollection(list); } public static <E> int length(List<E> list) { return size(list); } public static <E> boolean isEmpty(List<E> list) { return isEmptyCollection(list); } /** * Same as {@link #isEmpty(List)} * * @param list the list * @return <code>true</code> if the list is empty; otherwise * <code>false</code> * @deprecated Use {@link #isEmpty(List)} */ public static <E> boolean emptyList(List<E> list) { return isEmptyCollection(list); } public static <E> E get(List<E> list, int index) { if (index >= size(list)) { throw new IllegalArgumentException("Index out of bound: " + index); } return list.get(index); } public static <E> List<E> without(List<E> list, E e) { return remove(list, e); } public static <E> List<E> concatenate(List<E> list1, List<E> list2) { final List<E> result = emptyList(); result.addAll(list1); result.addAll(list2); return result; } public static <E> List<E> appendRight(List<E> list, E e) { return (List<E>) insertCollection(e, list); } public static <E> List<E> reverse(List<E> list) { Collections.reverse(list); return list; } public static <E> List<E> copy(final E value, final int n) { return IntStream.range(0, n).mapToObj(i -> value).collect(Collectors.toList()); } public static <E> List<E> tail(List<E> list) { if (list == null || list.isEmpty()) { return null; } return list.subList(1, list.size()); } public static <E> E head(List<E> list) { if (list == null || list.isEmpty()) { return null; } return list.get(0); } /** * Same as {@link #insert(Object, List)}. * * @param e the element * @param list the list * @return the updated list * @deprecated Please {@link #insert(Object, List)}. */ public static <E> List<E> Cons(E e, List<E> list) { return insert(e, list); } // --- Set /** * Same as {@link #emptySet()}. * * @return a new empty {@link Set} * @deprecated Use {@link #EmptySet()}. */ public static <E> Set<E> EmptySet() { return emptySet(); } public static <E> Set<E> emptySet() { return new HashSet<>(); } public static <E> Set<E> insert(E e, Set<E> set) { if (set == null) { set = emptySet(); } return (Set<E>) insertCollection(e, set); } /** * Same as {@link #insert(Object, Set)} * * @param set the set * @param e the element * @return the updated set * @deprecated Use {@link #insert(Object, Set)} */ public static <E> Set<E> insertElement(Set<E> set, E e) { return (Set<E>) insertCollection(e, set); } public static <E> Set<E> remove(Set<E> set, E e) { return (Set<E>) removeCollection(e, set); } public static <E> Set<E> set(List<E> list) { return set_java(list); } public static <E> boolean contains(E e, Set<E> set) { return containsCollection(e, set); } public static <E> int size(Set<E> set) { return sizeCollection(set); } public static <E> int length(Set<E> set) { return size(set); } public static <E> boolean isEmpty(Set<E> set) { return isEmptyCollection(set); } /** * Same as {@link #isEmpty(Set)} * * @param set the set * @return <code>true</code> if the set is empty; otherwise * <code>false</code> * @deprecated Use {@link #isEmpty(Set)} */ public static <E> boolean emptySet(Set<E> set) { return isEmptyCollection(set); } public static <E> E take(Set<E> set) { return next(set); } public static <E> boolean hasNext(Set<E> set) { return hastNext(set); } public static <E> Set<E> union(Set<E> set1, Set<E> set2) { final Set<E> union = emptySet(); union.addAll(set1); union.addAll(set2); return union; } public static <E> Set<E> intersection(Set<E> set1, Set<E> set2) { final Set<E> inter = emptySet(); inter.addAll(set1); inter.retainAll(set2); return inter; } public static <E> Set<E> difference(Set<E> set1, Set<E> set2) { final Set<E> diff = emptySet(); diff.addAll(set1); diff.removeAll(set2); return diff; } // --- Map /** * Same as {@link #emptyMap()} * * @return a new empty {@link Map} * @deprecated Use {@link #emptyMap()}. */ public static <K, V> Map<K, V> EmptyMap() { return emptyMap(); } public static <K, V> Map<K, V> emptyMap() { return new ConcurrentHashMap<>(); } public static <K, V> Map<K, V> insert(Map<K, V> map, K key, V value) { if (map == null) { map = emptyMap(); } map.put(key, value); return map; } public static <K, V> Map<K, V> insert(Map<K, V> map, Pair<K, V> pair) { return insert(pair, map); } public static <K, V> Map<K, V> insert(Entry<K, V> pair, Map<K, V> map) { return insert(map, pair.getKey(), pair.getValue()); } public static <K, V> Map<K, V> put(Map<K, V> map, K key, V value) { return insert(map, key, value); } /** * Creates a new {@link Pair}. * * @param key the first element * @param value the second element * @return an instance of {@link Pair} * @deprecated Try to use {@link #pair(Object, Object)} which * uses standard Java's {@link Entry}. */ public static <K, V> Pair<K, V> Pair(K key, V value) { return Pair.newPair(key, value); } /** * Returns the first element in a {@link Pair}. * * @param pair the pair instance * @return the first element * @deprecated Usage is not recommended. */ public static <K, V> K fst(Entry<K, V> pair) { return pair.getKey(); } /** * Retrieves the second element in a {@link Pair}. * * @param pair the pair instance * @return the second element * @deprecated Usage is not recommended. */ public static <K, V> V snd(Entry<K, V> pair) { return pair.getValue(); } public static <K, V> Map.Entry<K, V> pair(K key, V value) { return new AbstractMap.SimpleEntry<K, V>(key, value); } public static <K, V> Map<K, V> map(List<K> keys, List<V> values) { if (keys == null || values == null || keys.size() != values.size()) { throw new IllegalArgumentException( "Keys and values do not match for map construction: " + keys + " -> " + values); } ConcurrentMap<K, V> map = IntStream.range(0, keys.size()).boxed() .collect(Collectors.toConcurrentMap(index -> keys.get(index), index -> values.get(index))); return map; } public static <K, V> Map<K, V> map(Collection<Entry<K, V>> entries) { return new ArrayList<>(entries).stream().collect( Collectors.toConcurrentMap((Entry<K, V> e) -> e.getKey(), (Entry<K, V> e) -> e.getValue())); } public static <K, V> Map<K, V> removeKey(Map<K, V> map, K key) { map.remove(key); return map; } public static <K, V, C extends Collection<K>> C keys(Map<K, V> map) { return (C) map.keySet(); } public static <K, V> Collection<V> values(Map<K, V> map) { return map.values(); } public static <K, V> Optional<V> lookup(Map<K, V> map, K key) { return Optional.ofNullable(map.get(key)); } public static <K, V> V lookupDefault(Map<K, V> map, K key, V defaultValue) { return lookup(map, key).orElse(defaultValue); } public static <K, V> V lookupUnsafe(Map<K, V> map, K key) { return lookup(map, key).orElse(null); } public static <V> V fromJust(Optional<V> value) { return value.orElse(null); } // --- Strings public static String substr(String s, int beginIndex, int length) { return s.substring(beginIndex, beginIndex + length); } public static int strlen(String s) { return s.length(); } public static String toString(Object o) { return Objects.toString(o, "null"); } public static String concatenate(String s1, String s2) { return new StringBuilder().append(s1).append(s2).toString(); } // --- I/O public static void println(String format, Object... args) { System.out.println(String.format(format, args)); } public static void println(Object o) { System.out.println(o); } public static void print(Object o) { System.out.print(o); } /** * Print a boolean with ANSI color support. This is a specific * method with <code>GREEN</code> and <code>RED</code> color * support on ANSI terminal. Use with caution. * * @param bool the value */ public static void println(final boolean bool) { if (bool) { println("%sTRUE%s", ANSI_GREEN, ANSI_RESET); } else { println("%sFALSE%s", ANSI_RED, ANSI_RESET); } } public static String readln() { return System.console().readLine(); } // --- Time public static Duration duration(long duration, TimeUnit unit) { return Duration.ofMillis(unit.toMillis(duration)); } public static Duration duration(long millis) { return Duration.ofMillis(millis); } public static boolean durationLessThan(Duration d1, Duration d2) { return d1.compareTo(d2) < 0; } public static Duration subtractFromDuration(Duration d, long v) { if (isDurationInfinite(d)) { return d; } Duration d2 = d.minusMillis(v); return d2.isNegative() || d2.isZero() ? d : d2; } public static Duration infinity() { return ChronoUnit.FOREVER.getDuration(); } public static boolean isDurationInfinite(Duration d) { return d == null || infinity().equals(d); } public static long currentms() { return ContextClock.CLOCK.millis(); } public static Instant now() { return ContextClock.CLOCK.instant(); } public static long timeDifference(Instant t1, Instant t2) { return Duration.between(t1, t2).abs().toMillis(); } public static Instant addDuration(Instant t, Duration d) { return t.plus(d); } public static Instant subtractDuration(Instant t, Duration d) { return t.minus(d); } public static Duration lowlevelDeadline(Long millis) { return millis == null || millis <= 0 ? infinity() : duration(millis); } public static Duration deadline(Duration d) { return d; } public static Duration deadline(Long millis) { return lowlevelDeadline(millis); } // --- Internal protected static <E> Collection<E> insertCollection(E e, Collection<E> col) { col.add(e); return col; } protected static <E> Collection<E> removeCollection(E e, Collection<E> col) { col.remove(e); return col; } protected static <E> boolean containsCollection(E e, Collection<E> col) { return col.contains(e); } protected static <E> int sizeCollection(Collection<E> col) { return col == null ? 0 : col.size(); } protected static <E> boolean isEmptyCollection(Collection<E> col) { return col.isEmpty(); } protected static <E> E next(Iterable<E> it) { return it == null || !it.iterator().hasNext() ? null : it.iterator().next(); } protected static <E> boolean hastNext(Iterable<E> it) { return it == null ? false : it.iterator().hasNext(); } protected static <E> Set<E> set_java(List<E> list) { Set<E> set = emptySet(); if (list == null) { return set; } set.addAll(list); return set; } protected static <E> Set<E> set_func(List<E> list) { Match<List<E>, Set<E>> m = Match.ofNull((List<E> ignored) -> (Set<E>) emptySet()) .or(l -> l.isEmpty(), ignored -> emptySet()) .orDefault((List<E> l) -> insert(l.get(0), set_func(l.subList(1, l.size())))); return m.apply(list).get(); } }
package com.bv.eidss.generated; import android.content.Context; import android.database.Cursor; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.view.View; import android.widget.CompoundButton; import android.widget.AdapterView; import com.bv.eidss.EidssBaseBindableFragment; import com.bv.eidss.HumanCaseFragment; import com.bv.eidss.VetCaseFragment; import com.bv.eidss.AnimalFragment; import com.bv.eidss.ASDiseaseFragment; import com.bv.eidss.ASSampleFragment; import com.bv.eidss.FarmFragment; import com.bv.eidss.HumanCaseSampleFragment; import com.bv.eidss.VetCaseSampleFragment; import com.bv.eidss.ASSessionFragment; import com.bv.eidss.R; import com.bv.eidss.ReferenciesProvider; import com.bv.eidss.data.EidssDatabase; import com.bv.eidss.model.BaseReference; import com.bv.eidss.model.BaseReferenceType; import com.bv.eidss.model.CaseTypeHACode; import com.bv.eidss.model.HumanCase; import com.bv.eidss.model.VetCase; import com.bv.eidss.model.ASSession; import android.content.Intent; import android.widget.Spinner; import com.bv.eidss.model.Species; import com.bv.eidss.model.Animal; import com.bv.eidss.model.ASDisease; import com.bv.eidss.model.ASSample; import com.bv.eidss.model.Farm; import com.bv.eidss.model.HumanCaseSample; import com.bv.eidss.model.VetCaseSample; import com.bv.eidss.utils.DateHelpers; import com.bv.eidss.utils.EidssUtils; import com.bv.eidss.utils.OnEditTextChangeListener; import java.util.List; public class ASSample_binding { public static final int NO_ACTION_ID = 1028; public static final int datFieldCollectionDate_DialogID = 1029; private static final int LOADER_AnimalGender = 1100; private static SimpleCursorAdapter adapterAnimalGender; private static Spinner spinnerAnimalGender; public static void Bind(final EidssBaseBindableFragment fragment, final View v, final ASSample mCase, final List<String> mandatoryFields, final List<String> invisibleFields, final String lang, final int page) { if (page == 0) { v.findViewById(R.id.ScanAnimalIdButton).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ((com.bv.eidss.barcode.BarcodeTestActivity)fragment.getActivity()).launchSimpleActivity(v); } }); fragment.EditTextBind(R.id.strColor, v, mCase.getColor(), new OnEditTextChangeListener() { @Override public void onEditTextChanged(String text) { mCase.setColor(text); } }, true, ASSample.eidss_Color, mandatoryFields, invisibleFields); spinnerAnimalGender = (Spinner)v.findViewById(R.id.idfsAnimalGender); adapterAnimalGender = fragment.LookupBind(spinnerAnimalGender, v, ReferenciesProvider.NAME, new AdapterView.OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> parent, View arg1, int pos, long id) { if (mCase.getAnimalGender() != id) mCase.setAnimalGender(id); } public void onNothingSelected(AdapterView<?> arg0) { mCase.setAnimalGender(0); } }, ASSample.eidss_AnimalGender, mandatoryFields, invisibleFields); if (adapterAnimalGender != null) fragment.getActivity().getSupportLoaderManager().initLoader(LOADER_AnimalGender, null, (ASSampleFragment)fragment); fragment.EditTextBind(R.id.strName, v, mCase.getName(), new OnEditTextChangeListener() { @Override public void onEditTextChanged(String text) { mCase.setName(text); } }, true, ASSample.eidss_Name, mandatoryFields, invisibleFields); fragment.EditTextBind(R.id.strDescription, v, mCase.getDescription(), new OnEditTextChangeListener() { @Override public void onEditTextChanged(String text) { mCase.setDescription(text); } }, true, ASSample.eidss_Description, mandatoryFields, invisibleFields); fragment.EditTextBind(R.id.strFieldBarcode, v, mCase.getFieldBarcode(), new OnEditTextChangeListener() { @Override public void onEditTextChanged(String text) { mCase.setFieldBarcode(text); } }, true, ASSample.eidss_FieldBarcode, mandatoryFields, invisibleFields); fragment.DateBind(R.id.datFieldCollectionDate, v, R.id.datFieldCollectionDateClearButton, new View.OnClickListener() { @Override public void onClick(View arg0) { com.bv.eidss.EidssAndroidHelpers.DatePickerFragment.Show(fragment.getActivity().getSupportFragmentManager(), datFieldCollectionDate_DialogID, null, mCase.getFieldCollectionDate()); } }, new View.OnClickListener() { @Override public void onClick(View arg0) { mCase.setFieldCollectionDate(null); DateHelpers.DisplayDate(R.id.datFieldCollectionDate, v, mCase.getFieldCollectionDate()); } }, mCase.getFieldCollectionDate(), ASSample.eidss_FieldCollectionDate, mandatoryFields, invisibleFields); } } public static Loader<Cursor> onCreateLoader(final int id, final String lang, final ASSample mCase, Context context) { String[] sels; switch (id) { case LOADER_AnimalGender: sels = new String[4]; sels[0] = lang; sels[1] = String.valueOf(BaseReferenceType.rftAnimalSex); sels[2] = String.valueOf(CaseTypeHACode.LIVESTOCK); sels[3] = String.valueOf(mCase.getAnimalGender()); return new CursorLoader(context, ReferenciesProvider.CONTENT_URI, null, null, sels, null); default: return null; } } public static void onLoadFinished(final int id, Cursor data, final ASSample mCase) { switch (id) { case LOADER_AnimalGender: onLoadFinishedAnimalGender(data, mCase); break; default: break; } } public static void onLoaderReset(final int id) { switch (id) { case LOADER_AnimalGender: adapterAnimalGender.swapCursor(null); break; default: break; } } private static void onLoadFinishedAnimalGender(Cursor data, final ASSample mCase) { adapterAnimalGender.swapCursor(data); int rowCount = data.getCount(); if (rowCount > 1) { // set selected int cpos = 0; for (int i = 0; i < rowCount; i++){ data.moveToPosition(i); long temp = data.getLong(0); if (temp == mCase.getAnimalGender()) { cpos = i; break; } } spinnerAnimalGender.setSelection(cpos); spinnerAnimalGender.setEnabled(true); } else { spinnerAnimalGender.setEnabled(false); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.hadoop.hbase.regionserver; import static org.apache.hadoop.hbase.HBaseTestingUtility.fam1; import static org.apache.hadoop.hbase.HBaseTestingUtility.fam2; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.CompareOperator; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MultithreadedTestUtil; import org.apache.hadoop.hbase.MultithreadedTestUtil.TestContext; import org.apache.hadoop.hbase.MultithreadedTestUtil.TestThread; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Append; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Increment; import org.apache.hadoop.hbase.client.IsolationLevel; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.RowMutations; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.TableDescriptor; import org.apache.hadoop.hbase.filter.BinaryComparator; import org.apache.hadoop.hbase.io.HeapSize; import org.apache.hadoop.hbase.io.hfile.BlockCache; import org.apache.hadoop.hbase.io.hfile.CacheConfig; import org.apache.hadoop.hbase.testclassification.LargeTests; import org.apache.hadoop.hbase.testclassification.VerySlowRegionServerTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.wal.WAL; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Testing of HRegion.incrementColumnValue, HRegion.increment, * and HRegion.append */ @Category({VerySlowRegionServerTests.class, LargeTests.class}) // Starts 100 threads public class TestAtomicOperation { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestAtomicOperation.class); private static final Logger LOG = LoggerFactory.getLogger(TestAtomicOperation.class); @Rule public TestName name = new TestName(); HRegion region = null; private HBaseTestingUtility TEST_UTIL = HBaseTestingUtility.createLocalHTU(); // Test names static byte[] tableName; static final byte[] qual1 = Bytes.toBytes("qual1"); static final byte[] qual2 = Bytes.toBytes("qual2"); static final byte[] qual3 = Bytes.toBytes("qual3"); static final byte[] value1 = Bytes.toBytes("value1"); static final byte[] value2 = Bytes.toBytes("value2"); static final byte [] row = Bytes.toBytes("rowA"); static final byte [] row2 = Bytes.toBytes("rowB"); @Before public void setup() { tableName = Bytes.toBytes(name.getMethodName()); } @After public void teardown() throws IOException { if (region != null) { CacheConfig cacheConfig = region.getStores().get(0).getCacheConfig(); region.close(); WAL wal = region.getWAL(); if (wal != null) { wal.close(); } cacheConfig.getBlockCache().ifPresent(BlockCache::shutdown); region = null; } } ////////////////////////////////////////////////////////////////////////////// // New tests that doesn't spin up a mini cluster but rather just test the // individual code pieces in the HRegion. ////////////////////////////////////////////////////////////////////////////// /** * Test basic append operation. * More tests in * @see org.apache.hadoop.hbase.client.TestFromClientSide#testAppend() */ @Test public void testAppend() throws IOException { initHRegion(tableName, name.getMethodName(), fam1); String v1 = "Ultimate Answer to the Ultimate Question of Life,"+ " The Universe, and Everything"; String v2 = " is... 42."; Append a = new Append(row); a.setReturnResults(false); a.addColumn(fam1, qual1, Bytes.toBytes(v1)); a.addColumn(fam1, qual2, Bytes.toBytes(v2)); assertTrue(region.append(a, HConstants.NO_NONCE, HConstants.NO_NONCE).isEmpty()); a = new Append(row); a.addColumn(fam1, qual1, Bytes.toBytes(v2)); a.addColumn(fam1, qual2, Bytes.toBytes(v1)); Result result = region.append(a, HConstants.NO_NONCE, HConstants.NO_NONCE); assertEquals(0, Bytes.compareTo(Bytes.toBytes(v1+v2), result.getValue(fam1, qual1))); assertEquals(0, Bytes.compareTo(Bytes.toBytes(v2+v1), result.getValue(fam1, qual2))); } @Test public void testAppendWithMultipleFamilies() throws IOException { final byte[] fam3 = Bytes.toBytes("colfamily31"); initHRegion(tableName, name.getMethodName(), fam1, fam2, fam3); String v1 = "Appended"; String v2 = "Value"; Append a = new Append(row); a.setReturnResults(false); a.addColumn(fam1, qual1, Bytes.toBytes(v1)); a.addColumn(fam2, qual2, Bytes.toBytes(v2)); Result result = region.append(a, HConstants.NO_NONCE, HConstants.NO_NONCE); assertTrue("Expected an empty result but result contains " + result.size() + " keys", result.isEmpty()); a = new Append(row); a.addColumn(fam2, qual2, Bytes.toBytes(v1)); a.addColumn(fam1, qual1, Bytes.toBytes(v2)); a.addColumn(fam3, qual3, Bytes.toBytes(v2)); a.addColumn(fam1, qual2, Bytes.toBytes(v1)); result = region.append(a, HConstants.NO_NONCE, HConstants.NO_NONCE); byte[] actualValue1 = result.getValue(fam1, qual1); byte[] actualValue2 = result.getValue(fam2, qual2); byte[] actualValue3 = result.getValue(fam3, qual3); byte[] actualValue4 = result.getValue(fam1, qual2); assertNotNull("Value1 should bot be null", actualValue1); assertNotNull("Value2 should bot be null", actualValue2); assertNotNull("Value3 should bot be null", actualValue3); assertNotNull("Value4 should bot be null", actualValue4); assertEquals(0, Bytes.compareTo(Bytes.toBytes(v1 + v2), actualValue1)); assertEquals(0, Bytes.compareTo(Bytes.toBytes(v2 + v1), actualValue2)); assertEquals(0, Bytes.compareTo(Bytes.toBytes(v2), actualValue3)); assertEquals(0, Bytes.compareTo(Bytes.toBytes(v1), actualValue4)); } @Test public void testAppendWithNonExistingFamily() throws IOException { initHRegion(tableName, name.getMethodName(), fam1); final String v1 = "Value"; final Append a = new Append(row); a.addColumn(fam1, qual1, Bytes.toBytes(v1)); a.addColumn(fam2, qual2, Bytes.toBytes(v1)); Result result = null; try { result = region.append(a, HConstants.NO_NONCE, HConstants.NO_NONCE); fail("Append operation should fail with NoSuchColumnFamilyException."); } catch (NoSuchColumnFamilyException e) { assertEquals(null, result); } catch (Exception e) { fail("Append operation should fail with NoSuchColumnFamilyException."); } } @Test public void testIncrementWithNonExistingFamily() throws IOException { initHRegion(tableName, name.getMethodName(), fam1); final Increment inc = new Increment(row); inc.addColumn(fam1, qual1, 1); inc.addColumn(fam2, qual2, 1); inc.setDurability(Durability.ASYNC_WAL); try { region.increment(inc, HConstants.NO_NONCE, HConstants.NO_NONCE); } catch (NoSuchColumnFamilyException e) { final Get g = new Get(row); final Result result = region.get(g); assertEquals(null, result.getValue(fam1, qual1)); assertEquals(null, result.getValue(fam2, qual2)); } catch (Exception e) { fail("Increment operation should fail with NoSuchColumnFamilyException."); } } /** * Test multi-threaded increments. */ @Test public void testIncrementMultiThreads() throws IOException { boolean fast = true; LOG.info("Starting test testIncrementMultiThreads"); // run a with mixed column families (1 and 3 versions) initHRegion(tableName, name.getMethodName(), new int[] {1,3}, fam1, fam2); // Create 100 threads, each will increment by its own quantity. All 100 threads update the // same row over two column families. int numThreads = 100; int incrementsPerThread = 1000; Incrementer[] all = new Incrementer[numThreads]; int expectedTotal = 0; // create all threads for (int i = 0; i < numThreads; i++) { all[i] = new Incrementer(region, i, i, incrementsPerThread); expectedTotal += (i * incrementsPerThread); } // run all threads for (int i = 0; i < numThreads; i++) { all[i].start(); } // wait for all threads to finish for (int i = 0; i < numThreads; i++) { try { all[i].join(); } catch (InterruptedException e) { LOG.info("Ignored", e); } } assertICV(row, fam1, qual1, expectedTotal, fast); assertICV(row, fam1, qual2, expectedTotal*2, fast); assertICV(row, fam2, qual3, expectedTotal*3, fast); LOG.info("testIncrementMultiThreads successfully verified that total is " + expectedTotal); } private void assertICV(byte [] row, byte [] familiy, byte[] qualifier, long amount, boolean fast) throws IOException { // run a get and see? Get get = new Get(row); if (fast) get.setIsolationLevel(IsolationLevel.READ_UNCOMMITTED); get.addColumn(familiy, qualifier); Result result = region.get(get); assertEquals(1, result.size()); Cell kv = result.rawCells()[0]; long r = Bytes.toLong(CellUtil.cloneValue(kv)); assertEquals(amount, r); } private void initHRegion (byte [] tableName, String callingMethod, byte[] ... families) throws IOException { initHRegion(tableName, callingMethod, null, families); } private void initHRegion (byte [] tableName, String callingMethod, int [] maxVersions, byte[] ... families) throws IOException { HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName)); int i=0; for(byte [] family : families) { HColumnDescriptor hcd = new HColumnDescriptor(family); hcd.setMaxVersions(maxVersions != null ? maxVersions[i++] : 1); htd.addFamily(hcd); } HRegionInfo info = new HRegionInfo(htd.getTableName(), null, null, false); region = TEST_UTIL.createLocalHRegion(info, htd); } /** * A thread that makes increment calls always on the same row, this.row against two column * families on this row. */ public static class Incrementer extends Thread { private final Region region; private final int numIncrements; private final int amount; public Incrementer(Region region, int threadNumber, int amount, int numIncrements) { super("Incrementer." + threadNumber); this.region = region; this.numIncrements = numIncrements; this.amount = amount; setDaemon(true); } @Override public void run() { for (int i = 0; i < numIncrements; i++) { try { Increment inc = new Increment(row); inc.addColumn(fam1, qual1, amount); inc.addColumn(fam1, qual2, amount*2); inc.addColumn(fam2, qual3, amount*3); inc.setDurability(Durability.ASYNC_WAL); Result result = region.increment(inc); if (result != null) { assertEquals(Bytes.toLong(result.getValue(fam1, qual1))*2, Bytes.toLong(result.getValue(fam1, qual2))); assertTrue(result.getValue(fam2, qual3) != null); assertEquals(Bytes.toLong(result.getValue(fam1, qual1))*3, Bytes.toLong(result.getValue(fam2, qual3))); assertEquals(Bytes.toLong(result.getValue(fam1, qual1))*2, Bytes.toLong(result.getValue(fam1, qual2))); long fam1Increment = Bytes.toLong(result.getValue(fam1, qual1))*3; long fam2Increment = Bytes.toLong(result.getValue(fam2, qual3)); assertEquals("fam1=" + fam1Increment + ", fam2=" + fam2Increment, fam1Increment, fam2Increment); } } catch (IOException e) { e.printStackTrace(); } } } } @Test public void testAppendMultiThreads() throws IOException { LOG.info("Starting test testAppendMultiThreads"); // run a with mixed column families (1 and 3 versions) initHRegion(tableName, name.getMethodName(), new int[] {1,3}, fam1, fam2); int numThreads = 100; int opsPerThread = 100; AtomicOperation[] all = new AtomicOperation[numThreads]; final byte[] val = new byte[]{1}; AtomicInteger failures = new AtomicInteger(0); // create all threads for (int i = 0; i < numThreads; i++) { all[i] = new AtomicOperation(region, opsPerThread, null, failures) { @Override public void run() { for (int i=0; i<numOps; i++) { try { Append a = new Append(row); a.addColumn(fam1, qual1, val); a.addColumn(fam1, qual2, val); a.addColumn(fam2, qual3, val); a.setDurability(Durability.ASYNC_WAL); region.append(a, HConstants.NO_NONCE, HConstants.NO_NONCE); Get g = new Get(row); Result result = region.get(g); assertEquals(result.getValue(fam1, qual1).length, result.getValue(fam1, qual2).length); assertEquals(result.getValue(fam1, qual1).length, result.getValue(fam2, qual3).length); } catch (IOException e) { e.printStackTrace(); failures.incrementAndGet(); fail(); } } } }; } // run all threads for (int i = 0; i < numThreads; i++) { all[i].start(); } // wait for all threads to finish for (int i = 0; i < numThreads; i++) { try { all[i].join(); } catch (InterruptedException e) { } } assertEquals(0, failures.get()); Get g = new Get(row); Result result = region.get(g); assertEquals(10000, result.getValue(fam1, qual1).length); assertEquals(10000, result.getValue(fam1, qual2).length); assertEquals(10000, result.getValue(fam2, qual3).length); } /** * Test multi-threaded row mutations. */ @Test public void testRowMutationMultiThreads() throws IOException { LOG.info("Starting test testRowMutationMultiThreads"); initHRegion(tableName, name.getMethodName(), fam1); // create 10 threads, each will alternate between adding and // removing a column int numThreads = 10; int opsPerThread = 250; AtomicOperation[] all = new AtomicOperation[numThreads]; AtomicLong timeStamps = new AtomicLong(0); AtomicInteger failures = new AtomicInteger(0); // create all threads for (int i = 0; i < numThreads; i++) { all[i] = new AtomicOperation(region, opsPerThread, timeStamps, failures) { @Override public void run() { boolean op = true; for (int i=0; i<numOps; i++) { try { // throw in some flushes if (i%10==0) { synchronized(region) { LOG.debug("flushing"); region.flush(true); if (i%100==0) { region.compact(false); } } } long ts = timeStamps.incrementAndGet(); RowMutations rm = new RowMutations(row); if (op) { Put p = new Put(row, ts); p.addColumn(fam1, qual1, value1); p.setDurability(Durability.ASYNC_WAL); rm.add(p); Delete d = new Delete(row); d.addColumns(fam1, qual2, ts); d.setDurability(Durability.ASYNC_WAL); rm.add(d); } else { Delete d = new Delete(row); d.addColumns(fam1, qual1, ts); d.setDurability(Durability.ASYNC_WAL); rm.add(d); Put p = new Put(row, ts); p.addColumn(fam1, qual2, value2); p.setDurability(Durability.ASYNC_WAL); rm.add(p); } region.mutateRow(rm); op ^= true; // check: should always see exactly one column Get g = new Get(row); Result r = region.get(g); if (r.size() != 1) { LOG.debug(Objects.toString(r)); failures.incrementAndGet(); fail(); } } catch (IOException e) { e.printStackTrace(); failures.incrementAndGet(); fail(); } } } }; } // run all threads for (int i = 0; i < numThreads; i++) { all[i].start(); } // wait for all threads to finish for (int i = 0; i < numThreads; i++) { try { all[i].join(); } catch (InterruptedException e) { } } assertEquals(0, failures.get()); } /** * Test multi-threaded region mutations. */ @Test public void testMultiRowMutationMultiThreads() throws IOException { LOG.info("Starting test testMultiRowMutationMultiThreads"); initHRegion(tableName, name.getMethodName(), fam1); // create 10 threads, each will alternate between adding and // removing a column int numThreads = 10; int opsPerThread = 250; AtomicOperation[] all = new AtomicOperation[numThreads]; AtomicLong timeStamps = new AtomicLong(0); AtomicInteger failures = new AtomicInteger(0); final List<byte[]> rowsToLock = Arrays.asList(row, row2); // create all threads for (int i = 0; i < numThreads; i++) { all[i] = new AtomicOperation(region, opsPerThread, timeStamps, failures) { @Override public void run() { boolean op = true; for (int i=0; i<numOps; i++) { try { // throw in some flushes if (i%10==0) { synchronized(region) { LOG.debug("flushing"); region.flush(true); if (i%100==0) { region.compact(false); } } } long ts = timeStamps.incrementAndGet(); List<Mutation> mrm = new ArrayList<>(); if (op) { Put p = new Put(row2, ts); p.addColumn(fam1, qual1, value1); p.setDurability(Durability.ASYNC_WAL); mrm.add(p); Delete d = new Delete(row); d.addColumns(fam1, qual1, ts); d.setDurability(Durability.ASYNC_WAL); mrm.add(d); } else { Delete d = new Delete(row2); d.addColumns(fam1, qual1, ts); d.setDurability(Durability.ASYNC_WAL); mrm.add(d); Put p = new Put(row, ts); p.setDurability(Durability.ASYNC_WAL); p.addColumn(fam1, qual1, value2); mrm.add(p); } region.mutateRowsWithLocks(mrm, rowsToLock, HConstants.NO_NONCE, HConstants.NO_NONCE); op ^= true; // check: should always see exactly one column Scan s = new Scan(row); RegionScanner rs = region.getScanner(s); List<Cell> r = new ArrayList<>(); while (rs.next(r)) ; rs.close(); if (r.size() != 1) { LOG.debug(Objects.toString(r)); failures.incrementAndGet(); fail(); } } catch (IOException e) { e.printStackTrace(); failures.incrementAndGet(); fail(); } } } }; } // run all threads for (int i = 0; i < numThreads; i++) { all[i].start(); } // wait for all threads to finish for (int i = 0; i < numThreads; i++) { try { all[i].join(); } catch (InterruptedException e) { } } assertEquals(0, failures.get()); } public static class AtomicOperation extends Thread { protected final HRegion region; protected final int numOps; protected final AtomicLong timeStamps; protected final AtomicInteger failures; protected final Random r = new Random(); public AtomicOperation(HRegion region, int numOps, AtomicLong timeStamps, AtomicInteger failures) { this.region = region; this.numOps = numOps; this.timeStamps = timeStamps; this.failures = failures; } } private static CountDownLatch latch = new CountDownLatch(1); private enum TestStep { INIT, // initial put of 10 to set value of the cell PUT_STARTED, // began doing a put of 50 to cell PUT_COMPLETED, // put complete (released RowLock, but may not have advanced MVCC). CHECKANDPUT_STARTED, // began checkAndPut: if 10 -> 11 CHECKANDPUT_COMPLETED // completed checkAndPut // NOTE: at the end of these steps, the value of the cell should be 50, not 11! } private static volatile TestStep testStep = TestStep.INIT; private final String family = "f1"; /** * Test written as a verifier for HBASE-7051, CheckAndPut should properly read * MVCC. * * Moved into TestAtomicOperation from its original location, TestHBase7051 */ @Test public void testPutAndCheckAndPutInParallel() throws Exception { Configuration conf = TEST_UTIL.getConfiguration(); conf.setClass(HConstants.REGION_IMPL, MockHRegion.class, HeapSize.class); HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name.getMethodName())) .addFamily(new HColumnDescriptor(family)); this.region = TEST_UTIL.createLocalHRegion(htd, null, null); Put[] puts = new Put[1]; Put put = new Put(Bytes.toBytes("r1")); put.addColumn(Bytes.toBytes(family), Bytes.toBytes("q1"), Bytes.toBytes("10")); puts[0] = put; region.batchMutate(puts); MultithreadedTestUtil.TestContext ctx = new MultithreadedTestUtil.TestContext(conf); ctx.addThread(new PutThread(ctx, region)); ctx.addThread(new CheckAndPutThread(ctx, region)); ctx.startThreads(); while (testStep != TestStep.CHECKANDPUT_COMPLETED) { Thread.sleep(100); } ctx.stop(); Scan s = new Scan(); RegionScanner scanner = region.getScanner(s); List<Cell> results = new ArrayList<>(); ScannerContext scannerContext = ScannerContext.newBuilder().setBatchLimit(2).build(); scanner.next(results, scannerContext); for (Cell keyValue : results) { assertEquals("50",Bytes.toString(CellUtil.cloneValue(keyValue))); } } private class PutThread extends TestThread { private Region region; PutThread(TestContext ctx, Region region) { super(ctx); this.region = region; } @Override public void doWork() throws Exception { Put[] puts = new Put[1]; Put put = new Put(Bytes.toBytes("r1")); put.addColumn(Bytes.toBytes(family), Bytes.toBytes("q1"), Bytes.toBytes("50")); puts[0] = put; testStep = TestStep.PUT_STARTED; region.batchMutate(puts); } } private class CheckAndPutThread extends TestThread { private Region region; CheckAndPutThread(TestContext ctx, Region region) { super(ctx); this.region = region; } @Override public void doWork() throws Exception { Put[] puts = new Put[1]; Put put = new Put(Bytes.toBytes("r1")); put.addColumn(Bytes.toBytes(family), Bytes.toBytes("q1"), Bytes.toBytes("11")); puts[0] = put; while (testStep != TestStep.PUT_COMPLETED) { Thread.sleep(100); } testStep = TestStep.CHECKANDPUT_STARTED; region.checkAndMutate(Bytes.toBytes("r1"), Bytes.toBytes(family), Bytes.toBytes("q1"), CompareOperator.EQUAL, new BinaryComparator(Bytes.toBytes("10")), put); testStep = TestStep.CHECKANDPUT_COMPLETED; } } public static class MockHRegion extends HRegion { public MockHRegion(Path tableDir, WAL log, FileSystem fs, Configuration conf, final RegionInfo regionInfo, final TableDescriptor htd, RegionServerServices rsServices) { super(tableDir, log, fs, conf, regionInfo, htd, rsServices); } @Override public RowLock getRowLockInternal(final byte[] row, boolean readLock, final RowLock prevRowlock) throws IOException { if (testStep == TestStep.CHECKANDPUT_STARTED) { latch.countDown(); } return new WrappedRowLock(super.getRowLockInternal(row, readLock, null)); } public class WrappedRowLock implements RowLock { private final RowLock rowLock; private WrappedRowLock(RowLock rowLock) { this.rowLock = rowLock; } @Override public void release() { if (testStep == TestStep.INIT) { this.rowLock.release(); return; } if (testStep == TestStep.PUT_STARTED) { try { testStep = TestStep.PUT_COMPLETED; this.rowLock.release(); // put has been written to the memstore and the row lock has been released, but the // MVCC has not been advanced. Prior to fixing HBASE-7051, the following order of // operations would cause the non-atomicity to show up: // 1) Put releases row lock (where we are now) // 2) CheckAndPut grabs row lock and reads the value prior to the put (10) // because the MVCC has not advanced // 3) Put advances MVCC // So, in order to recreate this order, we wait for the checkAndPut to grab the rowLock // (see below), and then wait some more to give the checkAndPut time to read the old // value. latch.await(); Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } else if (testStep == TestStep.CHECKANDPUT_STARTED) { this.rowLock.release(); } } } } }
/* 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 org.camunda.bpm.engine.rest; import static com.jayway.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.either; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import javax.ws.rs.core.Response.Status; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.rest.helper.MockObjectValue; import org.camunda.bpm.engine.rest.helper.MockProvider; import org.camunda.bpm.engine.rest.helper.MockVariableInstanceBuilder; import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; import org.camunda.bpm.engine.rest.util.container.TestContainerRule; import org.camunda.bpm.engine.runtime.VariableInstance; import org.camunda.bpm.engine.runtime.VariableInstanceQuery; import org.camunda.bpm.engine.variable.Variables; import org.camunda.bpm.engine.variable.type.ValueType; import org.camunda.bpm.engine.variable.value.FileValue; import org.camunda.bpm.engine.variable.value.ObjectValue; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import com.jayway.restassured.http.ContentType; import com.jayway.restassured.response.Response; /** * @author Daniel Meyer * */ public class VariableInstanceRestServiceInteractionTest extends AbstractRestServiceTest { @ClassRule public static TestContainerRule rule = new TestContainerRule(); protected static final String SERVICE_URL = TEST_RESOURCE_ROOT_PATH + "/variable-instance"; protected static final String VARIABLE_INSTANCE_URL = SERVICE_URL + "/{id}"; protected static final String VARIABLE_INSTANCE_BINARY_DATA_URL = VARIABLE_INSTANCE_URL + "/data"; protected RuntimeService runtimeServiceMock; protected VariableInstanceQuery variableInstanceQueryMock; @Before public void setupTestData() { runtimeServiceMock = mock(RuntimeService.class); variableInstanceQueryMock = mock(VariableInstanceQuery.class); // mock runtime service. when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); when(runtimeServiceMock.createVariableInstanceQuery()).thenReturn(variableInstanceQueryMock); } @Test public void testGetSingleVariableInstance() { MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance(); VariableInstance variableInstanceMock = builder.build(); when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) .then().expect().statusCode(Status.OK.getStatusCode()) .and() .body("id", equalTo(builder.getId())) .body("name", equalTo(builder.getName())) .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) .body("value", equalTo(builder.getTypedValue().getValue())) .body("processInstanceId", equalTo(builder.getProcessInstanceId())) .body("executionId", equalTo(builder.getExecutionId())) .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) .body("taskId", equalTo(builder.getTaskId())) .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) .body("errorMessage", equalTo(builder.getErrorMessage())) .when().get(VARIABLE_INSTANCE_URL); verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); } @Test public void testGetSingleVariableInstanceDeserialized() { ObjectValue serializedValue = MockObjectValue.fromObjectValue( Variables.objectValue("a value").serializationDataFormat("aDataFormat").create()) .objectTypeName("aTypeName"); MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance().typedValue(serializedValue); VariableInstance variableInstanceMock = builder.build(); when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); given() .pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) .then().expect().statusCode(Status.OK.getStatusCode()) .and() .body("id", equalTo(builder.getId())) .body("name", equalTo(builder.getName())) .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) .body("value", equalTo("a value")) .body("valueInfo.serializationDataFormat", equalTo("aDataFormat")) .body("valueInfo.objectTypeName", equalTo("aTypeName")) .body("processInstanceId", equalTo(builder.getProcessInstanceId())) .body("executionId", equalTo(builder.getExecutionId())) .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) .body("taskId", equalTo(builder.getTaskId())) .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) .body("errorMessage", equalTo(builder.getErrorMessage())) .when().get(VARIABLE_INSTANCE_URL); verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); verify(variableInstanceQueryMock, never()).disableCustomObjectDeserialization(); } @Test public void testGetSingleVariableInstanceSerialized() { ObjectValue serializedValue = Variables.serializedObjectValue("a serialized value") .serializationDataFormat("aDataFormat").objectTypeName("aTypeName").create(); MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance().typedValue(serializedValue); VariableInstance variableInstanceMock = builder.build(); when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); given() .pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) .queryParam("deserializeValue", false) .then().expect().statusCode(Status.OK.getStatusCode()) .and() .body("id", equalTo(builder.getId())) .body("name", equalTo(builder.getName())) .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) .body("value", equalTo("a serialized value")) .body("valueInfo.serializationDataFormat", equalTo("aDataFormat")) .body("valueInfo.objectTypeName", equalTo("aTypeName")) .body("processInstanceId", equalTo(builder.getProcessInstanceId())) .body("executionId", equalTo(builder.getExecutionId())) .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) .body("taskId", equalTo(builder.getTaskId())) .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) .body("errorMessage", equalTo(builder.getErrorMessage())) .when().get(VARIABLE_INSTANCE_URL); verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); verify(variableInstanceQueryMock, times(1)).disableCustomObjectDeserialization(); } @Test public void testGetSingleVariableInstanceForBinaryVariable() { MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance(); VariableInstance variableInstanceMock = builder .typedValue(Variables.byteArrayValue(null)) .build(); when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) .then().expect().statusCode(Status.OK.getStatusCode()) .and() .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.BYTES))) .body("value", nullValue()) .when().get(VARIABLE_INSTANCE_URL); verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); } @Test public void testGetNonExistingVariableInstance() { String nonExistingId = "nonExistingId"; when(variableInstanceQueryMock.variableId(nonExistingId)).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.singleResult()).thenReturn(null); given().pathParam("id", nonExistingId) .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) .body(containsString("Variable instance with Id 'nonExistingId' does not exist.")) .when().get(VARIABLE_INSTANCE_URL); verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); } @Test public void testBinaryDataForBinaryVariable() { final byte[] byteContent = "some bytes".getBytes(); VariableInstance variableInstanceMock = MockProvider.mockVariableInstance() .typedValue(Variables.byteArrayValue(byteContent)) .build(); when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); Response response = given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) .then().expect() .statusCode(Status.OK.getStatusCode()) .contentType(ContentType.BINARY.toString()) .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); byte[] responseBytes = response.getBody().asByteArray(); Assert.assertEquals(new String(byteContent), new String(responseBytes)); verify(variableInstanceQueryMock, never()).disableBinaryFetching(); verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); } @Test public void testBinaryDataForNonBinaryVariable() { VariableInstance variableInstanceMock = MockProvider.createMockVariableInstance(); when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) .then().expect() .statusCode(Status.BAD_REQUEST.getStatusCode()) .body(containsString("Value of Variable instance aVariableInstanceId is not a binary value")) .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); verify(variableInstanceQueryMock, never()).disableBinaryFetching(); verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); } @Test public void testGetBinaryDataForNonExistingVariableInstance() { String nonExistingId = "nonExistingId"; when(variableInstanceQueryMock.variableId(nonExistingId)).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.singleResult()).thenReturn(null); given().pathParam("id", nonExistingId) .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) .body(containsString("Variable instance with Id 'nonExistingId' does not exist.")) .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); verify(variableInstanceQueryMock, never()).disableBinaryFetching(); verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); } @Test public void testGetBinaryDataForFileVariable() { String filename = "test.txt"; byte[] byteContent = "test".getBytes(); String encoding = "UTF-8"; FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance(); VariableInstance variableInstanceMock = builder .typedValue(variableValue) .build(); when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); Response response = given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) .then().expect().statusCode(Status.OK.getStatusCode()) .and() .header("Content-Disposition", "attachment; filename="+filename) .and() .body(is(equalTo(new String(byteContent)))) .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); //due to some problems with wildfly we gotta check this separately String contentType = response.getContentType(); assertThat(contentType, is(either(CoreMatchers.<Object>equalTo(ContentType.TEXT.toString() + "; charset=UTF-8")).or(CoreMatchers.<Object>equalTo(ContentType.TEXT.toString() + ";charset=UTF-8")))); } @Test public void testGetBinaryDataForNullFileVariable() { String filename = "test.txt"; byte[] byteContent = null; FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create(); MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance(); VariableInstance variableInstanceMock = builder .typedValue(variableValue) .build(); when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) .then().expect().statusCode(Status.OK.getStatusCode()) .and() .contentType(ContentType.TEXT) .and() .body(is(equalTo(new String()))) .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); } }
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.client.impl.protocol.codec.builtin; import com.hazelcast.cache.CacheEventType; import com.hazelcast.cache.impl.CacheEventDataImpl; import com.hazelcast.cluster.Address; import com.hazelcast.config.BitmapIndexOptions; import com.hazelcast.config.BitmapIndexOptions.UniqueKeyTransformation; import com.hazelcast.config.CacheSimpleEntryListenerConfig; import com.hazelcast.config.EventJournalConfig; import com.hazelcast.config.HotRestartConfig; import com.hazelcast.config.IndexConfig; import com.hazelcast.config.IndexType; import com.hazelcast.config.MerkleTreeConfig; import com.hazelcast.config.NearCachePreloaderConfig; import com.hazelcast.core.HazelcastException; import com.hazelcast.instance.EndpointQualifier; import com.hazelcast.instance.ProtocolType; import com.hazelcast.internal.management.dto.ClientBwListEntryDTO; import com.hazelcast.internal.serialization.Data; import com.hazelcast.internal.serialization.impl.compact.FieldDescriptor; import com.hazelcast.internal.serialization.impl.compact.Schema; import com.hazelcast.map.impl.SimpleEntryView; import com.hazelcast.map.impl.querycache.event.DefaultQueryCacheEventData; import com.hazelcast.nio.serialization.FieldType; import com.hazelcast.sql.SqlColumnMetadata; import com.hazelcast.sql.SqlColumnType; import javax.annotation.Nonnull; import java.net.UnknownHostException; import java.util.Comparator; import java.util.List; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import static com.hazelcast.config.CacheSimpleConfig.ExpiryPolicyFactoryConfig.DurationConfig; import static com.hazelcast.config.CacheSimpleConfig.ExpiryPolicyFactoryConfig.TimedExpiryPolicyFactoryConfig; import static com.hazelcast.config.CacheSimpleConfig.ExpiryPolicyFactoryConfig.TimedExpiryPolicyFactoryConfig.ExpiryPolicyType; @SuppressWarnings("checkstyle:ClassDataAbstractionCoupling") public final class CustomTypeFactory { private CustomTypeFactory() { } public static Address createAddress(String host, int port) { try { return new Address(host, port); } catch (UnknownHostException e) { throw new HazelcastException(e); } } public static CacheEventDataImpl createCacheEventData(String name, int cacheEventType, Data dataKey, Data dataValue, Data dataOldValue, boolean oldValueAvailable) { return new CacheEventDataImpl(name, CacheEventType.getByType(cacheEventType), dataKey, dataValue, dataOldValue, oldValueAvailable); } public static TimedExpiryPolicyFactoryConfig createTimedExpiryPolicyFactoryConfig(int expiryPolicyType, DurationConfig durationConfig) { return new TimedExpiryPolicyFactoryConfig(ExpiryPolicyType.getById(expiryPolicyType), durationConfig); } public static CacheSimpleEntryListenerConfig createCacheSimpleEntryListenerConfig(boolean oldValueRequired, boolean synchronous, String cacheEntryListenerFactory, String cacheEntryEventFilterFactory) { CacheSimpleEntryListenerConfig config = new CacheSimpleEntryListenerConfig(); config.setOldValueRequired(oldValueRequired); config.setSynchronous(synchronous); config.setCacheEntryListenerFactory(cacheEntryListenerFactory); config.setCacheEntryEventFilterFactory(cacheEntryEventFilterFactory); return config; } public static EventJournalConfig createEventJournalConfig(boolean enabled, int capacity, int timeToLiveSeconds) { EventJournalConfig config = new EventJournalConfig(); config.setEnabled(enabled); config.setCapacity(capacity); config.setTimeToLiveSeconds(timeToLiveSeconds); return config; } public static HotRestartConfig createHotRestartConfig(boolean enabled, boolean fsync) { HotRestartConfig config = new HotRestartConfig(); config.setEnabled(enabled); config.setFsync(fsync); return config; } public static MerkleTreeConfig createMerkleTreeConfig(boolean enabled, int depth, boolean isEnabledSetExists, boolean isEnabledSet) { MerkleTreeConfig config = new MerkleTreeConfig(); if (!isEnabledSetExists || isEnabledSet) { config.setEnabled(enabled); } config.setDepth(depth); return config; } public static NearCachePreloaderConfig createNearCachePreloaderConfig(boolean enabled, String directory, int storeInitialDelaySeconds, int storeIntervalSeconds) { NearCachePreloaderConfig config = new NearCachePreloaderConfig(); config.setEnabled(enabled); config.setDirectory(directory); config.setStoreInitialDelaySeconds(storeInitialDelaySeconds); config.setStoreIntervalSeconds(storeIntervalSeconds); return config; } public static SimpleEntryView<Data, Data> createSimpleEntryView(Data key, Data value, long cost, long creationTime, long expirationTime, long hits, long lastAccessTime, long lastStoredTime, long lastUpdateTime, long version, long ttl, long maxIdle) { SimpleEntryView<Data, Data> entryView = new SimpleEntryView<>(); entryView.setKey(key); entryView.setValue(value); entryView.setCost(cost); entryView.setCreationTime(creationTime); entryView.setExpirationTime(expirationTime); entryView.setHits(hits); entryView.setLastAccessTime(lastAccessTime); entryView.setLastStoredTime(lastStoredTime); entryView.setLastUpdateTime(lastUpdateTime); entryView.setVersion(version); entryView.setTtl(ttl); entryView.setMaxIdle(maxIdle); return entryView; } public static DefaultQueryCacheEventData createQueryCacheEventData(Data dataKey, Data dataNewValue, long sequence, int eventType, int partitionId) { DefaultQueryCacheEventData eventData = new DefaultQueryCacheEventData(); eventData.setDataKey(dataKey); eventData.setDataNewValue(dataNewValue); eventData.setSequence(sequence); eventData.setEventType(eventType); eventData.setPartitionId(partitionId); return eventData; } public static DurationConfig createDurationConfig(long durationAmount, int timeUnitId) { TimeUnit timeUnit; if (timeUnitId == 0) { timeUnit = TimeUnit.NANOSECONDS; } else if (timeUnitId == 1) { timeUnit = TimeUnit.MICROSECONDS; } else if (timeUnitId == 2) { timeUnit = TimeUnit.MILLISECONDS; } else if (timeUnitId == 3) { timeUnit = TimeUnit.SECONDS; } else if (timeUnitId == 4) { timeUnit = TimeUnit.MINUTES; } else if (timeUnitId == 5) { timeUnit = TimeUnit.HOURS; } else if (timeUnitId == 6) { timeUnit = TimeUnit.DAYS; } else { timeUnit = null; } return new DurationConfig(durationAmount, timeUnit); } public static IndexConfig createIndexConfig(String name, int type, List<String> attributes, BitmapIndexOptions bitmapIndexOptions) { IndexType type0 = IndexType.getById(type); return new IndexConfig() .setName(name) .setType(type0) .setAttributes(attributes) .setBitmapIndexOptions(bitmapIndexOptions); } public static BitmapIndexOptions createBitmapIndexOptions(String uniqueKey, int uniqueKeyTransformation) { UniqueKeyTransformation resolvedUniqueKeyTransformation = UniqueKeyTransformation.fromId(uniqueKeyTransformation); return new BitmapIndexOptions().setUniqueKey(uniqueKey).setUniqueKeyTransformation(resolvedUniqueKeyTransformation); } public static ClientBwListEntryDTO createClientBwListEntry(int type, String value) { ClientBwListEntryDTO.Type entryType = ClientBwListEntryDTO.Type.getById(type); if (entryType == null) { throw new HazelcastException("Unexpected client B/W list entry type = [" + type + "]"); } return new ClientBwListEntryDTO(entryType, value); } public static EndpointQualifier createEndpointQualifier(int type, String identifier) { ProtocolType protocolType = ProtocolType.getById(type); if (protocolType == null) { throw new HazelcastException("Unexpected protocol type = [" + type + "]"); } return EndpointQualifier.resolve(protocolType, identifier); } public static SqlColumnMetadata createSqlColumnMetadata(String name, int type, boolean isNullableExists, boolean nullability) { SqlColumnType sqlColumnType = SqlColumnType.getById(type); if (sqlColumnType == null) { throw new HazelcastException("Unexpected SQL column type = [" + type + "]"); } if (isNullableExists) { return new SqlColumnMetadata(name, sqlColumnType, nullability); } return new SqlColumnMetadata(name, sqlColumnType, true); } public static FieldDescriptor createFieldDescriptor(@Nonnull String fieldName, int type) { FieldType fieldType = FieldType.get((byte) type); return new FieldDescriptor(fieldName, fieldType); } public static Schema createSchema(String typeName, List<FieldDescriptor> fields) { TreeMap<String, FieldDescriptor> map = new TreeMap<>(Comparator.naturalOrder()); for (FieldDescriptor field : fields) { map.put(field.getFieldName(), field); } return new Schema(typeName, map); } }
/* * Copyright 2014 Google Inc. All rights reserved. * * 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.google.samples.apps.iosched.map; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.IndoorBuilding; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.TileOverlay; import com.google.android.gms.maps.model.TileOverlayOptions; import com.google.samples.apps.iosched.R; import com.google.samples.apps.iosched.map.util.CachedTileProvider; import com.google.samples.apps.iosched.map.util.MarkerLoadingTask; import com.google.samples.apps.iosched.map.util.MarkerModel; import com.google.samples.apps.iosched.map.util.TileLoadingTask; import com.google.samples.apps.iosched.provider.ScheduleContract; import com.google.samples.apps.iosched.util.AnalyticsHelper; import com.google.samples.apps.iosched.util.MapUtils; import com.jakewharton.disklrucache.DiskLruCache; import android.app.Activity; import android.app.LoaderManager; import android.app.LoaderManager.LoaderCallbacks; import android.content.Loader; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Rect; import android.os.Bundle; import android.os.Handler; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.google.samples.apps.iosched.util.LogUtils.LOGD; import static com.google.samples.apps.iosched.util.LogUtils.makeLogTag; /** * Shows a map of the conference venue. */ public class MapFragment extends com.google.android.gms.maps.MapFragment implements GoogleMap.OnMarkerClickListener, GoogleMap.OnIndoorStateChangeListener, GoogleMap.OnMapClickListener, OnMapReadyCallback { private static final LatLng MOSCONE = new LatLng(37.783107, -122.403789); private static final LatLng MOSCONE_CAMERA = new LatLng(37.78308931536713, -122.40409433841705); private static final String EXTRAS_HIGHLIGHT_ROOM = "EXTRAS_HIGHLIGHT_ROOM"; private static final String EXTRAS_ACTIVE_FLOOR = "EXTRAS_ACTIVE_FLOOR"; // Initial camera zoom private static final float CAMERA_ZOOM = 18.19f; private static final float CAMERA_BEARING = 234.2f; private static final int INVALID_FLOOR = Integer.MIN_VALUE; // Estimated number of floors used to initialise data structures with appropriate capacity private static final int INITIAL_FLOOR_COUNT = 3; // Default level (index of level in IndoorBuilding object for Moscone) private static final int MOSCONE_DEFAULT_LEVEL_INDEX = 1; private static final String TAG = makeLogTag(MapFragment.class); // Tile Providers private SparseArray<CachedTileProvider> mTileProviders = new SparseArray<>(INITIAL_FLOOR_COUNT); private SparseArray<TileOverlay> mTileOverlays = new SparseArray<>(INITIAL_FLOOR_COUNT); private DiskLruCache mTileCache; // Markers stored by id private HashMap<String, MarkerModel> mMarkers = new HashMap<>(); // Markers stored by floor private SparseArray<ArrayList<Marker>> mMarkersFloor = new SparseArray<>(INITIAL_FLOOR_COUNT); // Screen DPI private float mDPI = 0; // Indoor maps representation of Moscone Center private IndoorBuilding mMosconeBuilding = null; // currently displayed floor private int mFloor = INVALID_FLOOR; private Marker mActiveMarker = null; private BitmapDescriptor ICON_ACTIVE; private BitmapDescriptor ICON_NORMAL; private boolean mAtMoscone = false; private Marker mMosconeMaker = null; private GoogleMap mMap; private Rect mMapInsets = new Rect(); private String mHighlightedRoomId = null; private MarkerModel mHighlightedRoom = null; private int mInitialFloor = MOSCONE_DEFAULT_LEVEL_INDEX; private static final int TOKEN_LOADER_MARKERS = 0x1; private static final int TOKEN_LOADER_TILES = 0x2; //For Analytics tracking public static final String SCREEN_LABEL = "Map"; public interface Callbacks { void onInfoHide(); void onInfoShowMoscone(); void onInfoShowTitle(String label, int roomType); void onInfoShowSessionlist(String roomId, String roomTitle, int roomType); void onInfoShowFirstSessionTitle(String roomId, String roomTitle, int roomType); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onInfoHide() { } @Override public void onInfoShowMoscone() { } @Override public void onInfoShowTitle(String label, int roomType) { } @Override public void onInfoShowSessionlist(String roomId, String roomTitle, int roomType) { } @Override public void onInfoShowFirstSessionTitle(String roomId, String roomTitle, int roomType) { } }; private Callbacks mCallbacks = sDummyCallbacks; public static MapFragment newInstance() { return new MapFragment(); } public static MapFragment newInstance(String highlightedRoomId) { MapFragment fragment = new MapFragment(); Bundle arguments = new Bundle(); arguments.putString(EXTRAS_HIGHLIGHT_ROOM, highlightedRoomId); fragment.setArguments(arguments); return fragment; } public static MapFragment newInstance(Bundle savedState) { MapFragment fragment = new MapFragment(); fragment.setArguments(savedState); return fragment; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mActiveMarker != null) { // A marker is currently selected, restore its selection. outState.putString(EXTRAS_HIGHLIGHT_ROOM, mActiveMarker.getTitle()); outState.putInt(EXTRAS_ACTIVE_FLOOR, INVALID_FLOOR); } else if (mAtMoscone) { // No marker is selected, store the active floor if at Moscone. outState.putInt(EXTRAS_ACTIVE_FLOOR, mFloor); outState.putString(EXTRAS_HIGHLIGHT_ROOM, null); } LOGD(TAG, "Saved state: " + outState); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ANALYTICS SCREEN: View the Map screen // Contains: Nothing (Page name is a constant) AnalyticsHelper.sendScreenView(SCREEN_LABEL); // get DPI mDPI = getActivity().getResources().getDisplayMetrics().densityDpi / 160f; ICON_ACTIVE = BitmapDescriptorFactory.fromResource(R.drawable.map_marker_selected); ICON_NORMAL = BitmapDescriptorFactory.fromResource(R.drawable.map_marker_unselected); // Get the arguments and restore the highlighted room or displayed floor. Bundle data = getArguments(); if (data != null) { mHighlightedRoomId = data.getString(EXTRAS_HIGHLIGHT_ROOM, null); mInitialFloor = data.getInt(EXTRAS_ACTIVE_FLOOR, MOSCONE_DEFAULT_LEVEL_INDEX); } getMapAsync(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mapView = super.onCreateView(inflater, container, savedInstanceState); setMapInsets(mMapInsets); return mapView; } public void setMapInsets(int left, int top, int right, int bottom) { mMapInsets.set(left, top, right, bottom); if (mMap != null) { mMap.setPadding(mMapInsets.left, mMapInsets.top, mMapInsets.right, mMapInsets.bottom); } } public void setMapInsets(Rect insets) { mMapInsets.set(insets.left, insets.top, insets.right, insets.bottom); if (mMap != null) { mMap.setPadding(mMapInsets.left, mMapInsets.top, mMapInsets.right, mMapInsets.bottom); } } @Override public void onStop() { super.onStop(); closeTileCache(); } /** * Closes the caches of all allocated tile providers. * * @see CachedTileProvider#closeCache() */ private void closeTileCache() { for (int i = 0; i < mTileProviders.size(); i++) { try { mTileProviders.valueAt(i).closeCache(); } catch (IOException e) { } } } /** * Clears the map and initialises all map variables that hold markers and overlays. */ private void clearMap() { if (mMap != null) { mMap.clear(); } // Close all tile provider caches closeTileCache(); // Clear all map elements mTileProviders.clear(); mTileOverlays.clear(); mMarkers.clear(); mMarkersFloor.clear(); mFloor = INVALID_FLOOR; } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setIndoorEnabled(true); mMap.setMyLocationEnabled(false); mMap.setOnMarkerClickListener(this); mMap.setOnIndoorStateChangeListener(this); mMap.setOnMapClickListener(this); UiSettings mapUiSettings = mMap.getUiSettings(); mapUiSettings.setZoomControlsEnabled(false); mapUiSettings.setMapToolbarEnabled(false); // load all markers LoaderManager lm = getLoaderManager(); lm.initLoader(TOKEN_LOADER_MARKERS, null, mMarkerLoader).forceLoad(); // load the tile overlays lm.initLoader(TOKEN_LOADER_TILES, null, mTileLoader).forceLoad(); setupMap(true); } private void setupMap(boolean resetCamera) { // Add a Marker for Moscone mMosconeMaker = mMap .addMarker(MapUtils.createMosconeMarker(MOSCONE).visible(false)); if (resetCamera) { // Move camera directly to Moscone centerOnMoscone(false); } LOGD(TAG, "Map setup complete."); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException( "Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; activity.getContentResolver().registerContentObserver( ScheduleContract.MapMarkers.CONTENT_URI, true, mObserver); activity.getContentResolver().registerContentObserver( ScheduleContract.MapTiles.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; getActivity().getContentResolver().unregisterContentObserver(mObserver); } /** * Moves the camera to Moscone Center (as defined in {@link #MOSCONE} and {@link #CAMERA_ZOOM}. * * @param animate Animates the camera if true, otherwise it is moved */ private void centerOnMoscone(boolean animate) { CameraUpdate camera = CameraUpdateFactory.newCameraPosition( new CameraPosition.Builder().bearing(CAMERA_BEARING).target(MOSCONE_CAMERA) .zoom(CAMERA_ZOOM).tilt(0f).build()); if (animate) { mMap.animateCamera(camera); } else { mMap.moveCamera(camera); } } /** * Switches the displayed floor for which elements are displayed. * If the map is not initialised yet or no data has been loaded, nothing will be displayed. * If an invalid floor is specified and elements are currently on the map, all visible * elements will be hidden. * If this floor is not active for the indoor building, it is made active. * * @param floor index of the floor to display. It requires an overlay and at least one Marker * to * be defined for it and it has to be a valid index in the * {@link com.google.android.gms.maps.model.IndoorBuilding} object that * describes Moscone. */ private void showFloorElementsIndex(int floor) { LOGD(TAG, "Show floor " + floor); // Hide previous floor elements if the floor has changed if (mFloor != floor) { setFloorElementsVisible(mFloor, false); } mFloor = floor; if (isValidFloor(mFloor) && mAtMoscone) { // Always hide the Moscone marker if a floor is shown mMosconeMaker.setVisible(false); setFloorElementsVisible(mFloor, true); } else { // Show Moscone marker if not at Moscone or at an invalid floor mMosconeMaker.setVisible(true); } } /** * Change the active floor of Moscone Center * to the given floor index. See {@link #showFloorElementsIndex(int)}. * * @param floor Index of the floor to show. * @see #showFloorElementsIndex(int) */ private void showFloorIndex(int floor) { if (isValidFloor(floor) && mAtMoscone) { if (mMap.getFocusedBuilding().getActiveLevelIndex() == floor) { // This floor is already active, show its elements showFloorElementsIndex(floor); } else { // This floor is not shown yet, switch to this floor on the map mMap.getFocusedBuilding().getLevels().get(floor).activate(); } } else { LOGD(TAG, "Can't show floor index " + floor + "."); } } /** * Change the visibility of all Markers and TileOverlays for a floor. */ private void setFloorElementsVisible(int floor, boolean visible) { // Overlays final TileOverlay overlay = mTileOverlays.get(floor); if (overlay != null) { overlay.setVisible(visible); } // Markers final ArrayList<Marker> markers = mMarkersFloor.get(floor); if (markers != null) { for (Marker m : markers) { m.setVisible(visible); } } } /** * A floor is valid if the Moscone building contains that floor. It is not required for a floor * to have a tile overlay and markers. */ private boolean isValidFloor(int floor) { return floor < mMosconeBuilding.getLevels().size(); } /** * Display map features if Moscone is the current building. * This explicitly re-enables all elements that should be displayed at the current floor. */ private void enableMapElements() { if (mMosconeBuilding != null && mAtMoscone) { onIndoorLevelActivated(mMosconeBuilding); } } private void onDefocusMoscone() { // Hide all markers and tile overlays deselectActiveMarker(); showFloorElementsIndex(INVALID_FLOOR); mCallbacks.onInfoShowMoscone(); } private void onFocusMoscone() { // Highlight a room if argument is set and it exists, otherwise show the default floor if (mHighlightedRoomId != null && mMarkers.containsKey(mHighlightedRoomId)) { highlightRoom(mHighlightedRoomId); showFloorIndex(mHighlightedRoom.floor); // Reset highlighted room because it has just been displayed. mHighlightedRoomId = null; } else { // Hide the bottom sheet that is displaying the Moscone details at this point mCallbacks.onInfoHide(); // Switch to the default level for Moscone and reset its value showFloorIndex(mInitialFloor); } mInitialFloor = MOSCONE_DEFAULT_LEVEL_INDEX; } @Override public void onIndoorBuildingFocused() { IndoorBuilding building = mMap.getFocusedBuilding(); if (building != null && mMosconeBuilding == null && mMap.getProjection().getVisibleRegion().latLngBounds.contains(MOSCONE)) { // Store the first active building. This will always be Moscone mMosconeBuilding = building; } if (!mAtMoscone && building != null && building.equals(mMosconeBuilding)) { // Map is focused on Moscone Center mAtMoscone = true; onFocusMoscone(); } else if (mAtMoscone && mMosconeBuilding != null && !mMosconeBuilding.equals(building)) { // Map is no longer focused on Moscone Center mAtMoscone = false; onDefocusMoscone(); } onIndoorLevelActivated(building); } @Override public void onIndoorLevelActivated(IndoorBuilding indoorBuilding) { if (indoorBuilding != null && indoorBuilding.equals(mMosconeBuilding)) { onMosconeFloorActivated(indoorBuilding.getActiveLevelIndex()); } } /** * Called when an indoor floor level in the Moscone building has been activated. * If a room is to be highlighted, the map is centered and its marker is activated. */ private void onMosconeFloorActivated(int activeLevelIndex) { if (mHighlightedRoom != null && mFloor == mHighlightedRoom.floor) { // A room highlight is pending. Highlight the marker and display info details. onMarkerClick(mHighlightedRoom.marker); centerMap(mHighlightedRoom.marker.getPosition()); // Remove the highlight room flag, because the room has just been highlighted. mHighlightedRoom = null; mHighlightedRoomId = null; } else if (mFloor != activeLevelIndex) { // Deselect and hide the info details. deselectActiveMarker(); mCallbacks.onInfoHide(); } // Show map elements for this floor showFloorElementsIndex(activeLevelIndex); } @Override public void onMapClick(LatLng latLng) { deselectActiveMarker(); mCallbacks.onInfoHide(); } private void deselectActiveMarker() { if (mActiveMarker != null) { mActiveMarker.setIcon(ICON_NORMAL); mActiveMarker = null; } } private void selectActiveMarker(Marker marker) { if (mActiveMarker == marker) { return; } if (marker != null) { mActiveMarker = marker; mActiveMarker.setIcon(ICON_ACTIVE); } } @Override public boolean onMarkerClick(Marker marker) { final String title = marker.getTitle(); final MarkerModel model = mMarkers.get(title); // Log clicks on all markers (regardless of type) // ANALYTICS EVENT: Click on marker on the map. // Contains: Marker ID (for example room UUID) AnalyticsHelper.sendEvent("Map", "markerclick", title); deselectActiveMarker(); // The Moscone marker can be compared directly. // For all other markers the model needs to be looked up first. if (marker.equals(mMosconeMaker)) { // Return camera to Moscone LOGD(TAG, "Clicked on Moscone marker, return to initial display."); centerOnMoscone(true); } else if (model != null && MapUtils.hasInfoTitleOnly(model.type)) { // Show a basic info window with a title only mCallbacks.onInfoShowTitle(model.label, model.type); selectActiveMarker(marker); } else if (model != null && MapUtils.hasInfoSessionList(model.type)) { // Type has sessions to display mCallbacks.onInfoShowSessionlist(model.id, model.label, model.type); selectActiveMarker(marker); } else if (model != null && MapUtils.hasInfoFirstDescriptionOnly(model.type)) { // Display the description of the first session only mCallbacks.onInfoShowFirstSessionTitle(model.id, model.label, model.type); selectActiveMarker(marker); } else { // Hide the bottom sheet for unknown markers mCallbacks.onInfoHide(); } return true; } private void centerMap(LatLng position) { mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, CAMERA_ZOOM)); } private void highlightRoom(String roomId) { MarkerModel m = mMarkers.get(roomId); if (m != null) { mHighlightedRoom = m; showFloorIndex(m.floor); } } private void onMarkersLoaded(List<MarkerLoadingTask.MarkerEntry> list) { if (list != null) { for (MarkerLoadingTask.MarkerEntry entry : list) { // Skip incomplete entries if (entry.options == null || entry.model == null) { break; } // Add marker to the map Marker m = mMap.addMarker(entry.options); MarkerModel model = entry.model; model.marker = m; // Store the marker and its model ArrayList<Marker> markerList = mMarkersFloor.get(model.floor); if (markerList == null) { // Initialise the list of Markers for this floor markerList = new ArrayList<>(); mMarkersFloor.put(model.floor, markerList); } markerList.add(m); mMarkers.put(model.id, model); } } enableMapElements(); } private void onTilesLoaded(List<TileLoadingTask.TileEntry> list) { if (list != null) { // Display tiles if they have been loaded, skip them otherwise but display the rest of // the map. for (TileLoadingTask.TileEntry entry : list) { TileOverlayOptions tileOverlay = new TileOverlayOptions() .tileProvider(entry.provider).visible(false); // Store the tile overlay and provider mTileProviders.put(entry.floor, entry.provider); mTileOverlays.put(entry.floor, mMap.addTileOverlay(tileOverlay)); } } enableMapElements(); } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (!isAdded()) { return; } //clear map reload all data clearMap(); setupMap(false); // reload data from loaders LoaderManager lm = getActivity().getLoaderManager(); Loader<Cursor> loader = lm.getLoader(TOKEN_LOADER_MARKERS); if (loader != null) { loader.forceLoad(); } loader = lm.getLoader(TOKEN_LOADER_TILES); if (loader != null) { loader.forceLoad(); } } }; /** * LoaderCallbacks for the {@link MarkerLoadingTask} that loads all markers for the map. */ private LoaderCallbacks<List<MarkerLoadingTask.MarkerEntry>> mMarkerLoader = new LoaderCallbacks<List<MarkerLoadingTask.MarkerEntry>>() { @Override public Loader<List<MarkerLoadingTask.MarkerEntry>> onCreateLoader(int id, Bundle args) { return new MarkerLoadingTask(getActivity()); } @Override public void onLoadFinished(Loader<List<MarkerLoadingTask.MarkerEntry>> loader, List<MarkerLoadingTask.MarkerEntry> data) { onMarkersLoaded(data); } @Override public void onLoaderReset(Loader<List<MarkerLoadingTask.MarkerEntry>> loader) { } }; /** * LoaderCallbacks for the {@link TileLoadingTask} that loads all tile overlays for the map. */ private LoaderCallbacks<List<TileLoadingTask.TileEntry>> mTileLoader = new LoaderCallbacks<List<TileLoadingTask.TileEntry>>() { @Override public Loader<List<TileLoadingTask.TileEntry>> onCreateLoader(int id, Bundle args) { return new TileLoadingTask(getActivity(), mDPI); } @Override public void onLoadFinished(Loader<List<TileLoadingTask.TileEntry>> loader, List<TileLoadingTask.TileEntry> data) { onTilesLoaded(data); } @Override public void onLoaderReset(Loader<List<TileLoadingTask.TileEntry>> loader) { } }; }
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver15; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFAsyncConfigPropFlowStatsMasterVer15 implements OFAsyncConfigPropFlowStatsMaster { private static final Logger logger = LoggerFactory.getLogger(OFAsyncConfigPropFlowStatsMasterVer15.class); // version: 1.5 final static byte WIRE_VERSION = 6; final static int LENGTH = 8; private final static long DEFAULT_MASK = 0x0L; // OF message fields private final long mask; // // Immutable default instance final static OFAsyncConfigPropFlowStatsMasterVer15 DEFAULT = new OFAsyncConfigPropFlowStatsMasterVer15( DEFAULT_MASK ); // package private constructor - used by readers, builders, and factory OFAsyncConfigPropFlowStatsMasterVer15(long mask) { this.mask = U32.normalize(mask); } // Accessors for OF message fields @Override public int getType() { return 0xd; } @Override public long getMask() { return mask; } @Override public OFVersion getVersion() { return OFVersion.OF_15; } public OFAsyncConfigPropFlowStatsMaster.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFAsyncConfigPropFlowStatsMaster.Builder { final OFAsyncConfigPropFlowStatsMasterVer15 parentMessage; // OF message fields private boolean maskSet; private long mask; BuilderWithParent(OFAsyncConfigPropFlowStatsMasterVer15 parentMessage) { this.parentMessage = parentMessage; } @Override public int getType() { return 0xd; } @Override public long getMask() { return mask; } @Override public OFAsyncConfigPropFlowStatsMaster.Builder setMask(long mask) { this.mask = mask; this.maskSet = true; return this; } @Override public OFVersion getVersion() { return OFVersion.OF_15; } @Override public OFAsyncConfigPropFlowStatsMaster build() { long mask = this.maskSet ? this.mask : parentMessage.mask; // return new OFAsyncConfigPropFlowStatsMasterVer15( mask ); } } static class Builder implements OFAsyncConfigPropFlowStatsMaster.Builder { // OF message fields private boolean maskSet; private long mask; @Override public int getType() { return 0xd; } @Override public long getMask() { return mask; } @Override public OFAsyncConfigPropFlowStatsMaster.Builder setMask(long mask) { this.mask = mask; this.maskSet = true; return this; } @Override public OFVersion getVersion() { return OFVersion.OF_15; } // @Override public OFAsyncConfigPropFlowStatsMaster build() { long mask = this.maskSet ? this.mask : DEFAULT_MASK; return new OFAsyncConfigPropFlowStatsMasterVer15( mask ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFAsyncConfigPropFlowStatsMaster> { @Override public OFAsyncConfigPropFlowStatsMaster readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property type == 0xd short type = bb.readShort(); if(type != (short) 0xd) throw new OFParseError("Wrong type: Expected=0xd(0xd), got="+type); int length = U16.f(bb.readShort()); if(length != 8) throw new OFParseError("Wrong length: Expected=8(8), got="+length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); long mask = U32.f(bb.readInt()); OFAsyncConfigPropFlowStatsMasterVer15 asyncConfigPropFlowStatsMasterVer15 = new OFAsyncConfigPropFlowStatsMasterVer15( mask ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", asyncConfigPropFlowStatsMasterVer15); return asyncConfigPropFlowStatsMasterVer15; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFAsyncConfigPropFlowStatsMasterVer15Funnel FUNNEL = new OFAsyncConfigPropFlowStatsMasterVer15Funnel(); static class OFAsyncConfigPropFlowStatsMasterVer15Funnel implements Funnel<OFAsyncConfigPropFlowStatsMasterVer15> { private static final long serialVersionUID = 1L; @Override public void funnel(OFAsyncConfigPropFlowStatsMasterVer15 message, PrimitiveSink sink) { // fixed value property type = 0xd sink.putShort((short) 0xd); // fixed value property length = 8 sink.putShort((short) 0x8); sink.putLong(message.mask); } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFAsyncConfigPropFlowStatsMasterVer15> { @Override public void write(ByteBuf bb, OFAsyncConfigPropFlowStatsMasterVer15 message) { // fixed value property type = 0xd bb.writeShort((short) 0xd); // fixed value property length = 8 bb.writeShort((short) 0x8); bb.writeInt(U32.t(message.mask)); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFAsyncConfigPropFlowStatsMasterVer15("); b.append("mask=").append(mask); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFAsyncConfigPropFlowStatsMasterVer15 other = (OFAsyncConfigPropFlowStatsMasterVer15) obj; if( mask != other.mask) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (int) (mask ^ (mask >>> 32)); return result; } }
/* * * * NetworkWSTest.java * * Copyright (C) 2018 DataArt * * 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.github.devicehive.websocket; import com.github.devicehive.rest.ApiClient; import com.github.devicehive.rest.api.AuthApi; import com.github.devicehive.rest.api.NetworkApi; import com.github.devicehive.rest.auth.ApiKeyAuth; import com.github.devicehive.rest.model.JwtAccessToken; import com.github.devicehive.rest.model.JwtRefreshToken; import com.github.devicehive.rest.model.NetworkUpdate; import com.github.devicehive.rest.model.SortField; import com.github.devicehive.rest.model.SortOrder; import com.github.devicehive.websocket.api.NetworkWS; import com.github.devicehive.websocket.listener.NetworkListener; import com.github.devicehive.websocket.model.repsonse.ErrorResponse; import com.github.devicehive.websocket.model.repsonse.NetworkGetResponse; import com.github.devicehive.websocket.model.repsonse.NetworkInsertResponse; import com.github.devicehive.websocket.model.repsonse.NetworkListResponse; import com.github.devicehive.websocket.model.repsonse.ResponseAction; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Random; import java.util.concurrent.CountDownLatch; import retrofit2.Response; public class NetworkWSTest extends Helper { private static final String JAVA_LIB_TEST = "JavaLibTest"; private CountDownLatch latch; private NetworkWS networkWS; private long networkId; private boolean networkWasDeleted = false; private String networkName; ApiClient apiClient = new ApiClient(getRestUrl()); @Before public void preTest() throws InterruptedException, IOException { authenticate(); latch = new CountDownLatch(1); networkWS = client.createNetworkWS(); networkName = JAVA_LIB_TEST + new Random().nextInt(); } @After() public void clear() throws IOException { if (networkWasDeleted) { return; } deleteNetwork(networkWS, networkId); } @Test public void insert() throws InterruptedException { networkWS.setListener(new NetworkListener() { @Override public void onList(NetworkListResponse response) { } @Override public void onGet(NetworkGetResponse response) { } @Override public void onInsert(NetworkInsertResponse response) { networkId = response.getNetwork().getId(); Assert.assertTrue(true); latch.countDown(); } @Override public void onDelete(ResponseAction response) { } @Override public void onUpdate(ResponseAction response) { } @Override public void onError(ErrorResponse error) { } }); NetworkUpdate networkUpdate = new NetworkUpdate(); networkUpdate.setName(JAVA_LIB_TEST + new Random().nextLong()); networkWS.insert(null, networkUpdate); latch.await(awaitTimeout, awaitTimeUnit); Assert.assertEquals(latch.getCount(), 0); } @Test public void get() throws InterruptedException, IOException { networkId = insertNetwork(); networkWS.setListener(new NetworkListener() { @Override public void onList(NetworkListResponse response) { } @Override public void onGet(NetworkGetResponse response) { Assert.assertTrue(true); latch.countDown(); } @Override public void onInsert(NetworkInsertResponse response) { } @Override public void onDelete(ResponseAction response) { } @Override public void onUpdate(ResponseAction response) { } @Override public void onError(ErrorResponse error) { } }); networkWS.get(null, networkId); latch.await(awaitTimeout, awaitTimeUnit); Assert.assertEquals(latch.getCount(), 0); } @Test public void list() throws InterruptedException, IOException { networkId = insertNetwork(); networkWS.setListener(new NetworkListener() { @Override public void onList(NetworkListResponse response) { Assert.assertTrue(true); latch.countDown(); } @Override public void onGet(NetworkGetResponse response) { } @Override public void onInsert(NetworkInsertResponse response) { } @Override public void onDelete(ResponseAction response) { } @Override public void onUpdate(ResponseAction response) { } @Override public void onError(ErrorResponse error) { Assert.assertTrue(false); latch.countDown(); } }); networkWS.list(null, null, null, SortField.ID, SortOrder.DESC, 30, 0); latch.await(awaitTimeout, awaitTimeUnit); Assert.assertEquals(latch.getCount(), 0); } @Test public void update() throws InterruptedException, IOException { networkId = insertNetwork(); networkWS.setListener(new NetworkListener() { @Override public void onList(NetworkListResponse response) { } @Override public void onGet(NetworkGetResponse response) { } @Override public void onInsert(NetworkInsertResponse response) { } @Override public void onDelete(ResponseAction response) { } @Override public void onUpdate(ResponseAction response) { Assert.assertTrue(true); latch.countDown(); } @Override public void onError(ErrorResponse error) { System.out.println(error); Assert.assertTrue(false); } }); NetworkUpdate networkUpdate = new NetworkUpdate(); networkUpdate.setDescription("aaaa"); networkWS.update(null, networkId, networkUpdate); latch.await(awaitTimeout, awaitTimeUnit); Assert.assertEquals(latch.getCount(), 0); } @Test public void delete() throws InterruptedException, IOException { networkId = insertNetwork(); networkWS.setListener(new NetworkListener() { @Override public void onList(NetworkListResponse response) { } @Override public void onGet(NetworkGetResponse response) { } @Override public void onInsert(NetworkInsertResponse response) { } @Override public void onDelete(ResponseAction response) { Assert.assertTrue(true); networkWasDeleted = true; latch.countDown(); } @Override public void onUpdate(ResponseAction response) { } @Override public void onError(ErrorResponse error) { System.out.println(error); Assert.assertTrue(false); } }); networkWS.delete(null, networkId); latch.await(awaitTimeout, awaitTimeUnit); Assert.assertEquals(latch.getCount(), 0); } private long insertNetwork() throws IOException { AuthApi authApi = apiClient.createService(AuthApi.class); JwtRefreshToken refreshToken = new JwtRefreshToken(); refreshToken.setRefreshToken(getRefreshToken()); Response<JwtAccessToken> response = authApi.refreshTokenRequest(refreshToken).execute(); if (response.isSuccessful()) { String accessToken = response.body().getAccessToken(); NetworkUpdate networkUpdate = getNetworkUpdate(networkName); apiClient.addAuthorization(ApiClient.AUTH_API_KEY, ApiKeyAuth.newInstance(accessToken)); return apiClient.createService(NetworkApi.class).insert(networkUpdate).execute().body().getId(); } else { throw new IOException("Can't get the token"); } } }
package org.apache.lucene.facet.sortedset; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import org.apache.lucene.facet.FacetResult; import org.apache.lucene.facet.Facets; import org.apache.lucene.facet.FacetsCollector; import org.apache.lucene.facet.FacetsCollector.MatchingDocs; import org.apache.lucene.facet.FacetsConfig; import org.apache.lucene.facet.LabelAndValue; import org.apache.lucene.facet.TopOrdAndIntQueue; import org.apache.lucene.facet.sortedset.SortedSetDocValuesReaderState.OrdRange; import org.apache.lucene.index.AtomicReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.MultiDocValues; import org.apache.lucene.index.MultiDocValues.MultiSortedSetDocValues; import org.apache.lucene.index.ReaderUtil; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.LongValues; /** Compute facets counts from previously * indexed {@link SortedSetDocValuesFacetField}, * without require a separate taxonomy index. Faceting is * a bit slower (~25%), and there is added cost on every * {@link IndexReader} open to create a new {@link * SortedSetDocValuesReaderState}. Furthermore, this does * not support hierarchical facets; only flat (dimension + * label) facets, but it uses quite a bit less RAM to do * so. * * <p><b>NOTE</b>: this class should be instantiated and * then used from a single thread, because it holds a * thread-private instance of {@link SortedSetDocValues}. * * <p><b>NOTE:</b>: tie-break is by unicode sort order * * @lucene.experimental */ public class SortedSetDocValuesFacetCounts extends Facets { final SortedSetDocValuesReaderState state; final SortedSetDocValues dv; final String field; final int[] counts; /** Sparse faceting: returns any dimension that had any * hits, topCount labels per dimension. */ public SortedSetDocValuesFacetCounts(SortedSetDocValuesReaderState state, FacetsCollector hits) throws IOException { this.state = state; this.field = state.getField(); dv = state.getDocValues(); counts = new int[state.getSize()]; //System.out.println("field=" + field); count(hits.getMatchingDocs()); } @Override public FacetResult getTopChildren(int topN, String dim, String... path) throws IOException { if (topN <= 0) { throw new IllegalArgumentException("topN must be > 0 (got: " + topN + ")"); } if (path.length > 0) { throw new IllegalArgumentException("path should be 0 length"); } OrdRange ordRange = state.getOrdRange(dim); if (ordRange == null) { throw new IllegalArgumentException("dimension \"" + dim + "\" was not indexed"); } return getDim(dim, ordRange, topN); } private final FacetResult getDim(String dim, OrdRange ordRange, int topN) { TopOrdAndIntQueue q = null; int bottomCount = 0; int dimCount = 0; int childCount = 0; TopOrdAndIntQueue.OrdAndValue reuse = null; //System.out.println("getDim : " + ordRange.start + " - " + ordRange.end); for(int ord=ordRange.start; ord<=ordRange.end; ord++) { //System.out.println(" ord=" + ord + " count=" + counts[ord]); if (counts[ord] > 0) { dimCount += counts[ord]; childCount++; if (counts[ord] > bottomCount) { if (reuse == null) { reuse = new TopOrdAndIntQueue.OrdAndValue(); } reuse.ord = ord; reuse.value = counts[ord]; if (q == null) { // Lazy init, so we don't create this for the // sparse case unnecessarily q = new TopOrdAndIntQueue(topN); } reuse = q.insertWithOverflow(reuse); if (q.size() == topN) { bottomCount = q.top().value; } } } } if (q == null) { return null; } LabelAndValue[] labelValues = new LabelAndValue[q.size()]; for(int i=labelValues.length-1;i>=0;i--) { TopOrdAndIntQueue.OrdAndValue ordAndValue = q.pop(); final BytesRef term = dv.lookupOrd(ordAndValue.ord); String[] parts = FacetsConfig.stringToPath(term.utf8ToString()); labelValues[i] = new LabelAndValue(parts[1], ordAndValue.value); } return new FacetResult(dim, new String[0], dimCount, labelValues, childCount); } /** Does all the "real work" of tallying up the counts. */ private final void count(List<MatchingDocs> matchingDocs) throws IOException { //System.out.println("ssdv count"); MultiDocValues.OrdinalMap ordinalMap; // TODO: is this right? really, we need a way to // verify that this ordinalMap "matches" the leaves in // matchingDocs... if (dv instanceof MultiSortedSetDocValues && matchingDocs.size() > 1) { ordinalMap = ((MultiSortedSetDocValues) dv).mapping; } else { ordinalMap = null; } IndexReader origReader = state.getOrigReader(); for(MatchingDocs hits : matchingDocs) { AtomicReader reader = hits.context.reader(); //System.out.println(" reader=" + reader); // LUCENE-5090: make sure the provided reader context "matches" // the top-level reader passed to the // SortedSetDocValuesReaderState, else cryptic // AIOOBE can happen: if (ReaderUtil.getTopLevelContext(hits.context).reader() != origReader) { throw new IllegalStateException("the SortedSetDocValuesReaderState provided to this class does not match the reader being searched; you must create a new SortedSetDocValuesReaderState every time you open a new IndexReader"); } SortedSetDocValues segValues = reader.getSortedSetDocValues(field); if (segValues == null) { continue; } DocIdSetIterator docs = hits.bits.iterator(); // TODO: yet another option is to count all segs // first, only in seg-ord space, and then do a // merge-sort-PQ in the end to only "resolve to // global" those seg ords that can compete, if we know // we just want top K? ie, this is the same algo // that'd be used for merging facets across shards // (distributed faceting). but this has much higher // temp ram req'ts (sum of number of ords across all // segs) if (ordinalMap != null) { final int segOrd = hits.context.ord; final LongValues ordMap = ordinalMap.getGlobalOrds(segOrd); int numSegOrds = (int) segValues.getValueCount(); if (hits.totalHits < numSegOrds/10) { //System.out.println(" remap as-we-go"); // Remap every ord to global ord as we iterate: int doc; while ((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { //System.out.println(" doc=" + doc); segValues.setDocument(doc); int term = (int) segValues.nextOrd(); while (term != SortedSetDocValues.NO_MORE_ORDS) { //System.out.println(" segOrd=" + segOrd + " ord=" + term + " globalOrd=" + ordinalMap.getGlobalOrd(segOrd, term)); counts[(int) ordMap.get(term)]++; term = (int) segValues.nextOrd(); } } } else { //System.out.println(" count in seg ord first"); // First count in seg-ord space: final int[] segCounts = new int[numSegOrds]; int doc; while ((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { //System.out.println(" doc=" + doc); segValues.setDocument(doc); int term = (int) segValues.nextOrd(); while (term != SortedSetDocValues.NO_MORE_ORDS) { //System.out.println(" ord=" + term); segCounts[term]++; term = (int) segValues.nextOrd(); } } // Then, migrate to global ords: for(int ord=0;ord<numSegOrds;ord++) { int count = segCounts[ord]; if (count != 0) { //System.out.println(" migrate segOrd=" + segOrd + " ord=" + ord + " globalOrd=" + ordinalMap.getGlobalOrd(segOrd, ord)); counts[(int) ordMap.get(ord)] += count; } } } } else { // No ord mapping (e.g., single segment index): // just aggregate directly into counts: int doc; while ((doc = docs.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { segValues.setDocument(doc); int term = (int) segValues.nextOrd(); while (term != SortedSetDocValues.NO_MORE_ORDS) { counts[term]++; term = (int) segValues.nextOrd(); } } } } } @Override public Number getSpecificValue(String dim, String... path) { if (path.length != 1) { throw new IllegalArgumentException("path must be length=1"); } int ord = (int) dv.lookupTerm(new BytesRef(FacetsConfig.pathToString(dim, path))); if (ord < 0) { return -1; } return counts[ord]; } @Override public List<FacetResult> getAllDims(int topN) throws IOException { List<FacetResult> results = new ArrayList<>(); for(Map.Entry<String,OrdRange> ent : state.getPrefixToOrdRange().entrySet()) { FacetResult fr = getDim(ent.getKey(), ent.getValue(), topN); if (fr != null) { results.add(fr); } } // Sort by highest count: Collections.sort(results, new Comparator<FacetResult>() { @Override public int compare(FacetResult a, FacetResult b) { if (a.value.intValue() > b.value.intValue()) { return -1; } else if (b.value.intValue() > a.value.intValue()) { return 1; } else { return a.dim.compareTo(b.dim); } } }); return results; } }
// Copyright 2014 Palantir Technologies // // 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.palantir.stash.stashbot.hooks; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import javax.annotation.Nonnull; import org.slf4j.Logger; import com.atlassian.bitbucket.hook.HookResponse; import com.atlassian.bitbucket.hook.PostReceiveHook; import com.atlassian.bitbucket.repository.RefChange; import com.atlassian.bitbucket.repository.RefChangeType; import com.atlassian.bitbucket.repository.Repository; import com.atlassian.bitbucket.scm.CommandOutputHandler; import com.atlassian.bitbucket.scm.git.command.GitCommandBuilderFactory; import com.atlassian.bitbucket.scm.git.command.GitScmCommandBuilder; import com.atlassian.bitbucket.scm.git.command.revlist.GitRevListBuilder; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.palantir.stash.stashbot.config.ConfigurationPersistenceService; import com.palantir.stash.stashbot.jobtemplate.JobType; import com.palantir.stash.stashbot.logger.PluginLoggerFactory; import com.palantir.stash.stashbot.managers.JenkinsManager; import com.palantir.stash.stashbot.outputhandler.CommandOutputHandlerFactory; import com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration; import com.palantir.stash.stashbot.persistence.RepositoryConfiguration; /* * NOTE: this cannot be an async hook, nor a repositorypushevent listener, because frequently people will merge a pull * request and check the "delete this branch" checkbox, meaning the branch goes away during the merge, so anything * running later (or asynchronously) will see the commit as not existing in any other branches, and thus will try to * build it a second time. * Note that PostReceiveHook does NOT get run when a PR is merged, because stupid APIs are stupid. * That case is handled separately in the PullRequestListener class */ public class TriggerJenkinsBuildHook implements PostReceiveHook { private final ConfigurationPersistenceService cpm; private final JenkinsManager jenkinsManager; private final GitCommandBuilderFactory gcbf; private final CommandOutputHandlerFactory cohf; private final Logger log; public TriggerJenkinsBuildHook(ConfigurationPersistenceService cpm, JenkinsManager jenkinsManager, GitCommandBuilderFactory gcbf, CommandOutputHandlerFactory cohf, PluginLoggerFactory lf) { this.cpm = cpm; this.jenkinsManager = jenkinsManager; this.gcbf = gcbf; this.cohf = cohf; this.log = lf.getLoggerForThis(this); } @Override public void onReceive(@Nonnull Repository repo, @Nonnull Collection<RefChange> changes, @Nonnull HookResponse response) { final RepositoryConfiguration rc; try { rc = cpm.getRepositoryConfigurationForRepository(repo); } catch (SQLException e) { throw new RuntimeException("Failed to get repositoryConfiguration for repo " + repo.toString()); } if (!rc.getCiEnabled()) { log.debug("CI disabled for repo " + repo.getName()); return; } Set<String> publishBuilds = new HashSet<String>(); // First trigger all publish builds (if they are enabled) if (cpm.getJobTypeStatusMapping(rc, JobType.PUBLISH)) { for (RefChange refChange : changes) { if (!refChange.getRefId().matches(rc.getPublishBranchRegex())) { continue; } // deletes have a tohash of "0000000000000000000000000000000000000000" // but it seems more reliable to use RefChangeType if (refChange.getType().equals(RefChangeType.DELETE)) { log.debug("Detected delete, not triggering a build for this change"); continue; } // if matches publication regex, no verify build needed for that hash // Only perform publish builds of the "to ref", not commits between // I.E. if you have A-B-C and you push -D-E-F, a verify build of D and E might be triggered, but F would be // published and not verified, if the ref matches both build and verify. log.info("Stashbot Trigger: Triggering PUBLISH build for commit " + refChange.getToHash()); // trigger a publication build jenkinsManager.triggerBuild(repo, JobType.PUBLISH, refChange.getToHash(), refChange.getRefId()); publishBuilds.add(refChange.getToHash()); } } // Nothing to do if VERIFY_COMMIT not enabled if (!cpm.getJobTypeStatusMapping(rc, JobType.VERIFY_COMMIT)) { return; } // Calculate the sum of all new commits introduced by this change // This would be: // (existing refs matching regex, deleted refs, changed refs old values)..(added refs, changed refs new values) // We will need a list of branches first GitScmCommandBuilder gcb = gcbf.builder(repo).command("branch"); CommandOutputHandler<Object> gboh = cohf.getBranchContainsOutputHandler(); gcb.build(gboh).call(); @SuppressWarnings("unchecked") ImmutableList<String> branches = (ImmutableList<String>) gboh.getOutput(); HashSet<String> plusBranches = new HashSet<String>(); HashSet<String> minusBranches = new HashSet<String>(); // add verify-matching branches to the minusBranches set minusBranches.addAll(ImmutableList.copyOf(Iterables.filter(branches, new Predicate<String>() { @Override public boolean apply(String input) { if (input.matches(rc.getVerifyBranchRegex())) { return true; } return false; } }))); // now calculate the changed/added/deleted refs for (RefChange refChange : changes) { if (!refChange.getRefId().matches(rc.getVerifyBranchRegex())) { continue; } // Since we are a verify branch that changed, we need to not be in minusBranches anymore minusBranches.remove(refChange.getRefId()); switch (refChange.getType()) { case DELETE: minusBranches.add(refChange.getFromHash()); break; case ADD: plusBranches.add(refChange.getToHash()); break; case UPDATE: minusBranches.add(refChange.getFromHash()); plusBranches.add(refChange.getToHash()); break; default: throw new IllegalStateException("Unknown change type " + refChange.getType().toString()); } } // we can now calculate all the new commits introduced by this change in one revwalk. GitScmCommandBuilder gscb = gcbf.builder(repo); GitRevListBuilder grlb = gscb.revList(); for (String mb : minusBranches) { grlb.revs("^" + mb); } for (String pb : plusBranches) { grlb.revs(pb); } Integer maxVerifyChain = getMaxVerifyChain(rc); if (maxVerifyChain != 0) { log.debug("Limiting to " + maxVerifyChain.toString() + " commits for verification"); grlb.limit(maxVerifyChain); } CommandOutputHandler<Object> rloh = cohf.getRevlistOutputHandler(); grlb.build(rloh).call(); // returns in old-to-new order, already limited by max-verify-build limiter @SuppressWarnings("unchecked") ImmutableList<String> changesets = (ImmutableList<String>) rloh.getOutput(); // For each new commit for (String cs : changesets) { if (publishBuilds.contains(cs)) { log.info("Stashbot Trigger: NOT triggering VERIFICATION build for commit " + cs + " because it already triggered a PUBLISH build"); continue; } log.info("Stashbot Trigger: Triggering VERIFICATION build for commit " + cs); // trigger a verification build (no merge) jenkinsManager.triggerBuild(repo, JobType.VERIFY_COMMIT, cs, ""); } } private Integer getMaxVerifyChain(RepositoryConfiguration rc) { JenkinsServerConfiguration jsc; try { jsc = cpm.getJenkinsServerConfiguration(rc.getJenkinsServerName()); } catch (SQLException e) { log.error("Error getting jenkins server configuration for repo id " + rc.getRepoId().toString(), e); return rc.getMaxVerifyChain(); } Integer serverMaxChain = jsc.getMaxVerifyChain(); Integer repoMaxChain = rc.getMaxVerifyChain(); if (serverMaxChain == 0) { // no server limits, just use repo limit return repoMaxChain; } if (repoMaxChain == 0) { // repo unlimited, server limited, use server limit return serverMaxChain; } // neither is unlimited, return lower limit if (serverMaxChain < repoMaxChain) { return serverMaxChain; } return repoMaxChain; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-548 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.11.20 at 12:00:33 PM CST // package com.mastercard.api.repower.v1.repower.domain; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="TransactionReference" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="CardNumber" type="{http://www.w3.org/2001/XMLSchema}long"/> * &lt;element name="TransactionAmount"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Value" type="{http://www.w3.org/2001/XMLSchema}long"/> * &lt;element name="Currency" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="LocalDate" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="LocalTime" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="Channel" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="ICA" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="ProcessorId" type="{http://www.w3.org/2001/XMLSchema}long"/> * &lt;element name="RoutingAndTransitNumber" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="MerchantType" type="{http://www.w3.org/2001/XMLSchema}short"/> * &lt;element name="CardAcceptor"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Name" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="City" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="State" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="PostalCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="Country" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "transactionReference", "cardNumber", "transactionAmount", "localDate", "localTime", "channel", "ica", "processorId", "routingAndTransitNumber", "merchantType", "cardAcceptor" }) @XmlRootElement(name = "RepowerRequest") public class RepowerRequest { @XmlElement(name = "TransactionReference", required = true) protected String transactionReference; @XmlElement(name = "CardNumber") protected long cardNumber; @XmlElement(name = "TransactionAmount", required = true) protected TransactionAmount transactionAmount; @XmlElement(name = "LocalDate", required = true) protected String localDate; @XmlElement(name = "LocalTime", required = true) protected String localTime; @XmlElement(name = "Channel", required = true) protected String channel; @XmlElement(name = "ICA") protected String ica; @XmlElement(name = "ProcessorId") protected long processorId; @XmlElement(name = "RoutingAndTransitNumber") protected int routingAndTransitNumber; @XmlElement(name = "MerchantType") protected short merchantType; @XmlElement(name = "CardAcceptor", required = true) protected CardAcceptor cardAcceptor; /** * Gets the value of the transactionReference property. * * @return * possible object is * {@link String } * */ public String getTransactionReference() { return transactionReference; } /** * Sets the value of the transactionReference property. * * @param value * allowed object is * {@link String } * */ public void setTransactionReference(String value) { this.transactionReference = value; } /** * Gets the value of the cardNumber property. * */ public long getCardNumber() { return cardNumber; } /** * Sets the value of the cardNumber property. * */ public void setCardNumber(long value) { this.cardNumber = value; } /** * Gets the value of the transactionAmount property. * * @return * possible object is * {@link com.mastercard.api.repower.v1.repower.domain.RepowerRequest.TransactionAmount } * */ public TransactionAmount getTransactionAmount() { return transactionAmount; } /** * Sets the value of the transactionAmount property. * * @param value * allowed object is * {@link com.mastercard.api.repower.v1.repower.domain.RepowerRequest.TransactionAmount } * */ public void setTransactionAmount(TransactionAmount value) { this.transactionAmount = value; } /** * Gets the value of the localDate property. * * @return * possible object is * {@link String } * */ public String getLocalDate() { return localDate; } /** * Sets the value of the localDate property. * * @param value * allowed object is * {@link String } * */ public void setLocalDate(String value) { this.localDate = value; } /** * Gets the value of the localTime property. * * @return * possible object is * {@link String } * */ public String getLocalTime() { return localTime; } /** * Sets the value of the localTime property. * * @param value * allowed object is * {@link String } * */ public void setLocalTime(String value) { this.localTime = value; } /** * Gets the value of the channel property. * * @return * possible object is * {@link String } * */ public String getChannel() { return channel; } /** * Sets the value of the channel property. * * @param value * allowed object is * {@link String } * */ public void setChannel(String value) { this.channel = value; } /** * Gets the value of the ica property. * */ public String getICA() { return ica; } /** * Sets the value of the ica property. * */ public void setICA(String value) { this.ica = value; } /** * Gets the value of the processorId property. * */ public long getProcessorId() { return processorId; } /** * Sets the value of the processorId property. * */ public void setProcessorId(long value) { this.processorId = value; } /** * Gets the value of the routingAndTransitNumber property. * */ public int getRoutingAndTransitNumber() { return routingAndTransitNumber; } /** * Sets the value of the routingAndTransitNumber property. * */ public void setRoutingAndTransitNumber(int value) { this.routingAndTransitNumber = value; } /** * Gets the value of the merchantType property. * */ public short getMerchantType() { return merchantType; } /** * Sets the value of the merchantType property. * */ public void setMerchantType(short value) { this.merchantType = value; } /** * Gets the value of the cardAcceptor property. * * @return * possible object is * {@link com.mastercard.api.repower.v1.repower.domain.RepowerRequest.CardAcceptor } * */ public CardAcceptor getCardAcceptor() { return cardAcceptor; } /** * Sets the value of the cardAcceptor property. * * @param value * allowed object is * {@link com.mastercard.api.repower.v1.repower.domain.RepowerRequest.CardAcceptor } * */ public void setCardAcceptor(CardAcceptor value) { this.cardAcceptor = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Name" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="City" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="State" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="PostalCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="Country" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "name", "city", "state", "postalCode", "country" }) public static class CardAcceptor { @XmlElement(name = "Name", required = true) protected String name; @XmlElement(name = "City", required = true) protected String city; @XmlElement(name = "State", required = true) protected String state; @XmlElement(name = "PostalCode", required = true) protected String postalCode; @XmlElement(name = "Country", required = true) protected String country; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the city property. * * @return * possible object is * {@link String } * */ public String getCity() { return city; } /** * Sets the value of the city property. * * @param value * allowed object is * {@link String } * */ public void setCity(String value) { this.city = value; } /** * Gets the value of the state property. * * @return * possible object is * {@link String } * */ public String getState() { return state; } /** * Sets the value of the state property. * * @param value * allowed object is * {@link String } * */ public void setState(String value) { this.state = value; } /** * Gets the value of the postalCode property. * * @return * possible object is * {@link String } * */ public String getPostalCode() { return postalCode; } /** * Sets the value of the postalCode property. * * @param value * allowed object is * {@link String } * */ public void setPostalCode(String value) { this.postalCode = value; } /** * Gets the value of the country property. * * @return * possible object is * {@link String } * */ public String getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link String } * */ public void setCountry(String value) { this.country = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Value" type="{http://www.w3.org/2001/XMLSchema}long"/> * &lt;element name="Currency" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value", "currency" }) public static class TransactionAmount { @XmlElement(name = "Value") protected long value; @XmlElement(name = "Currency", required = true) protected String currency; /** * Gets the value of the value property. * */ public long getValue() { return value; } /** * Sets the value of the value property. * */ public void setValue(long value) { this.value = value; } /** * Gets the value of the currency property. * * @return * possible object is * {@link String } * */ public String getCurrency() { return currency; } /** * Sets the value of the currency property. * * @param value * allowed object is * {@link String } * */ public void setCurrency(String value) { this.currency = value; } } }
package io.github.jonestimd.swing.table.model; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.BiPredicate; import java.util.stream.Collectors; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import com.google.common.collect.Lists; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import static io.github.jonestimd.swing.table.model.TableModelEventMatcher.*; import static java.util.Collections.*; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; public class BufferedBeanListTableModelTest { private static final ColumnAdapter<TestBean, String> COLUMN_ADAPTER1 = new TestColumnAdapter<>("column1", String.class, TestBean::getColumn1, TestBean::setColumn1); private static final ColumnAdapter<TestBean, String> COLUMN_ADAPTER2 = new TestColumnAdapter<>("column2", String.class, TestBean::getColumn2, TestBean::setColumn2); private static final BiPredicate<TestBean, TestBean> ID_PREDICATE = (b1, b2) -> Objects.equals(b1.id, b2.id); private TableModelListener listener = mock(TableModelListener.class); private BufferedBeanListTableModel<TestBean> model = new BufferedBeanListTableModel<>(COLUMN_ADAPTER1, COLUMN_ADAPTER2); @Before public void setUp() { model.addTableModelListener(listener); } @Test public void testSetValue() throws Exception { final TestBean bean = new TestBean(); model.setBeans(Lists.newArrayList(bean, new TestBean())); assertThat(model.isChanged()).isFalse(); assertThat(model.getChangedRows().collect(Collectors.toList())).isEmpty(); model.setValueAt("value1", 0, 0); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isTrue(); assertThat(model.isChangedAt(0, 1)).isFalse(); assertThat(model.getPendingUpdates().collect(Collectors.toList())).containsExactly(bean); model.setValueAt("value2", 0, 1); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isTrue(); assertThat(model.isChangedAt(0, 1)).isTrue(); assertThat(model.getPendingUpdates().collect(Collectors.toList())).containsExactly(bean); assertThat(model.getValueAt(0, 0)).isEqualTo("value1"); assertThat(model.getValueAt(0, 1)).isEqualTo("value2"); InOrder inOrder = inOrder(listener); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, Integer.MAX_VALUE, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, 0)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, 1)); verifyNoMoreInteractions(listener); } @Test public void testRevert() throws Exception { model.setBeans(Arrays.asList(new TestBean(), new TestBean())); assertThat(model.isChanged()).isFalse(); model.setValueAt("value1", 0, 0); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isTrue(); assertThat(model.isChangedAt(0, 1)).isFalse(); model.queueAdd(new TestBean()); assertThat(model.isChangedAt(2, 0)).isTrue(); assertThat(model.isChangedAt(2, 1)).isTrue(); model.queueDelete(model.getRow(1)); assertThat(model.isChangedAt(1, 0)); assertThat(model.isChangedAt(1, 1)); model.revert(); assertThat(model.getBeans()).hasSize(2); assertThat(model.isChanged()).isFalse(); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.isChangedAt(0, 1)).isFalse(); assertThat(model.isChangedAt(1, 0)).isFalse(); assertThat(model.isChangedAt(1, 1)).isFalse(); model.setValueAt("value2", 0, 1); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.isChangedAt(0, 1)).isTrue(); assertThat(model.getValueAt(0, 0)).isNull(); assertThat(model.getValueAt(0, 1)).isEqualTo("value2"); model.setValueAt(null, 0, 1); assertThat(model.isChanged()).isFalse(); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.isChangedAt(0, 1)).isFalse(); assertThat(model.getValueAt(0, 0)).isNull(); assertThat(model.getValueAt(0, 1)).isNull(); InOrder inOrder = inOrder(listener); // setBeans() inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, Integer.MAX_VALUE, -1)); // setValueAt() inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, 0)); // pendingAdd() inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.INSERT, 2, 2, -1)); // pendingDelete() inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 1, 1, -1)); // revert() inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.DELETE, 2, 2, -1)); // undo add inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 1, 1, -1)); // undo delete inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, 0)); // undo setValue inOrder.verify(listener, times(2)).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, 1)); verifyNoMoreInteractions(listener); } @Test public void testCommit() throws Exception { model.setBeans(Arrays.asList(new TestBean(), new TestBean())); assertThat(model.isChanged()).isFalse(); model.setValueAt("value1", 0, 0); assertThat(model.getPendingUpdates().collect(Collectors.toList())).containsExactly(model.getBean(0)); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isTrue(); assertThat(model.isChangedAt(0, 1)).isFalse(); model.queueAdd(new TestBean()); assertThat(model.getPendingAdds()).containsExactly(model.getBean(2)); assertThat(model.isChangedAt(2, 0)).isTrue(); assertThat(model.isChangedAt(2, 1)).isTrue(); model.queueDelete(model.getRow(1)); assertThat(model.getPendingDeletes()).containsExactly(model.getBean(1)); assertThat(model.isChangedAt(1, 0)).isTrue(); assertThat(model.isChangedAt(1, 1)).isTrue(); List<TestBean> beans = model.getChangedRows().collect(Collectors.toList()); assertThat(beans).hasSize(3); assertThat(beans.containsAll(model.getBeans())).isTrue(); model.commit(); assertThat(model.getPendingAdds()).isEmpty(); assertThat(model.getPendingDeletes()).isEmpty(); assertThat(model.getPendingUpdates().collect(Collectors.toList())).isEmpty(); assertThat(model.getBeans()).hasSize(2); assertThat(model.getBeans()).containsOnly(beans.get(0), beans.get(1)); assertThat(model.isChanged()).isFalse(); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.isChangedAt(0, 1)).isFalse(); assertThat(model.isChangedAt(1, 0)).isFalse(); assertThat(model.isChangedAt(1, 1)).isFalse(); model.setValueAt("value2", 0, 1); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.isChangedAt(0, 1)).isTrue(); model.revert(); assertThat(model.isChanged()).isFalse(); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.isChangedAt(0, 1)).isFalse(); assertThat(model.getValueAt(0, 0)).isEqualTo("value1"); assertThat(model.getValueAt(0, 1)).isNull(); InOrder inOrder = inOrder(listener); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, Integer.MAX_VALUE, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, 0)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.INSERT, 2, 2, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 1, 1, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 2, 2, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.DELETE, 1, 1, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, -1)); inOrder.verify(listener, times(2)).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, 1)); verifyNoMoreInteractions(listener); } @Test public void testRemoveChangedRow() throws Exception { TestBean testBean = new TestBean(); model.setBeans(Arrays.asList(testBean, new TestBean())); assertThat(model.isChanged()).isFalse(); model.setValueAt("value1", 0, 0); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isTrue(); model.queueDelete(model.getRow(0)); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isTrue(); assertThat(model.isChangedAt(0, 1)).isTrue(); assertThat(model.isPendingDelete(0)).isTrue(); List<TestBean> beans = model.getChangedRows().collect(Collectors.toList()); assertThat(beans).containsExactly(testBean, testBean).as("both changed and to be deleted"); assertThat(testBean.column1).isEqualTo("value1").as("still the changed value"); InOrder inOrder = inOrder(listener); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, Integer.MAX_VALUE, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, 0)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, -1)); verifyNoMoreInteractions(listener); } @Test public void testAddRow() throws Exception { model.setBeans(singletonList(new TestBean())); model.queueAdd(new TestBean()); assertThat(model.getPendingAdds()).containsExactly(model.getBean(1)); assertThat(model.isPendingAdd(1)).isTrue(); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.isChangedAt(0, 1)).isFalse(); assertThat(model.isChangedAt(1, 0)).isTrue(); assertThat(model.isChangedAt(1, 1)).isTrue(); model.queueAdd(0, new TestBean()); assertThat(model.getPendingAdds()).containsExactly(model.getBean(2), model.getBean(0)); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isTrue(); assertThat(model.isChangedAt(0, 1)).isTrue(); assertThat(model.isChangedAt(1, 0)).isFalse(); assertThat(model.isChangedAt(1, 1)).isFalse(); assertThat(model.isChangedAt(2, 0)).isTrue(); assertThat(model.isChangedAt(2, 1)).isTrue(); model.setValueAt("value1", 0, 0); assertThat(model.getBeans().get(0).column1).isEqualTo("value1").as("write-through on added rows"); assertThat(model.isChangedAt(0, 0)).isTrue(); List<TestBean> beans = model.getChangedRows().collect(Collectors.toList()); assertThat(beans).hasSize(2); assertThat(beans.contains(model.getBeans().get(0))).isTrue(); assertThat(beans.contains(model.getBeans().get(2))).isTrue(); model.commit(); assertThat(model.getPendingAdds()).isEmpty(); assertThat(model.isChanged()).isFalse(); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.isChangedAt(0, 1)).isFalse(); assertThat(model.isChangedAt(2, 0)).isFalse(); assertThat(model.isChangedAt(2, 1)).isFalse(); InOrder inOrder = inOrder(listener); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, Integer.MAX_VALUE, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.INSERT, 1, 1, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.INSERT, 0, 0, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, 0)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 2, 2, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, -1)); verifyNoMoreInteractions(listener); } @Test public void testCancelAddedRow() throws Exception { model.setBeans(singletonList(new TestBean())); model.queueAdd(new TestBean()); assertThat(model.isPendingAdd(1)).isTrue(); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.isChangedAt(0, 1)).isFalse(); assertThat(model.isChangedAt(1, 0)).isTrue(); assertThat(model.isChangedAt(1, 1)).isTrue(); assertThat(model.queueDelete(model.getRow(1))).isFalse(); assertThat(model.isChanged()).isFalse(); InOrder inOrder = inOrder(listener); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, Integer.MAX_VALUE, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.INSERT, 1, 1, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.DELETE, 1, 1, -1)); verifyNoMoreInteractions(listener); } @Test public void testSetBeansClearsChanges() throws Exception { model.setBeans(Arrays.asList(new TestBean(), new TestBean())); assertThat(model.isChanged()).isFalse(); model.queueAdd(new TestBean()); assertThat(model.isPendingAdd(2)).isTrue(); assertThat(model.isChanged()).isTrue(); model.setValueAt("value1", 0, 0); assertThat(model.isChanged()).isTrue(); assertThat(model.queueDelete(model.getRow(1))).isTrue(); assertThat(model.isChanged()).isTrue(); model.setBeans(singletonList(new TestBean())); assertThat(model.isChanged()).isFalse(); } @Test public void testPendingDelete() throws Exception { TestBean bean = new TestBean(); model.setBeans(singletonList(bean)); assertThat(model.isCellEditable(0, 0)).isTrue(); assertThat(model.queueDelete(bean)).isTrue(); assertThat(model.isChanged()).isTrue(); assertThat(model.isChangedAt(0, 0)).isTrue(); assertThat(model.isChangedAt(0, 1)).isTrue(); assertThat(model.isCellEditable(0, 0)).isFalse(); assertThat(model.getBeans()).contains(bean); InOrder inOrder = inOrder(listener); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, Integer.MAX_VALUE, -1)); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, -1)); verifyNoMoreInteractions(listener); } @Test public void undoDelete() throws Exception { TestBean bean = new TestBean(); model.setBeans(Arrays.asList(bean, new TestBean())); model.queueDelete(bean); assertThat(model.isCellEditable(0, 0)).isFalse(); model.undoDelete(0); assertThat(model.isChanged()).isFalse(); assertThat(model.isCellEditable(0, 0)).isTrue(); assertThat(model.getBeans().contains(bean)).isTrue(); InOrder inOrder = inOrder(listener); inOrder.verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, Integer.MAX_VALUE, -1)); inOrder.verify(listener, times(2)).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, -1)); verifyNoMoreInteractions(listener); } @Test public void undoDeleteDoesNothingIfNotPendingDelete() throws Exception { model.setBeans(singletonList(new TestBean())); model.undoDelete(0); verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, Integer.MAX_VALUE, -1)); verifyNoMoreInteractions(listener); } @Test public void undoChangeAtRevertsChange() throws Exception { model.setBeans(singletonList(new TestBean())); model.setValueAt("x", 0, 0); assertThat(model.isChangedAt(0, 0)).isTrue(); model.undoChangedAt(0, 0); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.getValueAt(0, 0)).isNull(); } @Test public void setRowUpdatesPendingDelete() throws Exception { TestBean bean1 = new TestBean(1L, "a"); model.setBeans(singleton(bean1)); model.queueDelete(bean1); TestBean bean2 = new TestBean(1L, "b"); reset(listener); model.setRow(0, bean2); assertThat(bean2.column1).isEqualTo("b"); assertThat(bean2.column2).isNull(); assertThat(model.getBeanCount()).isEqualTo(1); assertThat(model.getValueAt(0, 0)).isEqualTo("b"); assertThat(model.isPendingDelete(0)).isTrue(); assertThat(model.getChangedRows().count()).isEqualTo(1); assertThat(model.getChangedRows().anyMatch(bean1::equals)).isFalse(); assertThat(model.getChangedRows().anyMatch(bean2::equals)).isTrue(); verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, -1)); verifyNoMoreInteractions(listener); } @Test public void setRowUpdatesPendingAdd() throws Exception { TestBean bean1 = new TestBean(1L, "a"); model.queueAdd(0, bean1); TestBean bean2 = new TestBean(1L, "b"); reset(listener); model.setRow(0, bean2); assertThat(bean2.column1).isEqualTo("b"); assertThat(bean2.column2).isNull(); assertThat(model.getBeanCount()).isEqualTo(1); assertThat(model.getValueAt(0, 0)).isEqualTo("b"); assertThat(model.isPendingAdd(0)).isTrue(); assertThat(model.getChangedRows().count()).isEqualTo(1); assertThat(model.getChangedRows().anyMatch(bean1::equals)).isFalse(); assertThat(model.getChangedRows().anyMatch(bean2::equals)).isTrue(); verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, -1)); verifyNoMoreInteractions(listener); } @Test public void setRowRetainsPendingChange() throws Exception { TestBean bean1 = new TestBean(1L, null); model.setBeans(singleton(bean1)); model.setValue("x", 0, 0); TestBean bean2 = new TestBean(1L, null); reset(listener); model.setRow(0, bean2); assertThat(bean2.column1).isEqualTo("x"); assertThat(bean2.column2).isNull(); assertThat(model.getBeanCount()).isEqualTo(1); assertThat(model.getValueAt(0, 0)).isEqualTo("x"); assertThat(model.isChangedAt(0, 0)).isTrue(); assertThat(model.getChangedRows().count()).isEqualTo(1); assertThat(model.getChangedRows().anyMatch(bean1::equals)).isFalse(); assertThat(model.getChangedRows().anyMatch(bean2::equals)).isTrue(); verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, -1)); verifyNoMoreInteractions(listener); } @Test public void setRowUpdatesOriginalValue() throws Exception { TestBean bean1 = new TestBean(1L, "a"); model.setBeans(singleton(bean1)); model.setValue("x", 0, 0); TestBean bean2 = new TestBean(1L, "y"); reset(listener); model.setRow(0, bean2); model.revert();; assertThat(bean2.column1).isEqualTo("y"); assertThat(model.getValueAt(0, 0)).isEqualTo("y"); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.getChangedRows().count()).isEqualTo(0); verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, -1)); verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, 0)); verifyNoMoreInteractions(listener); } @Test public void setRowClearsObsoleteChange() throws Exception { TestBean bean1 = new TestBean(1L, "a"); model.setBeans(singleton(bean1)); model.setValue("x", 0, 0); TestBean bean2 = new TestBean(1L, "x"); reset(listener); model.setRow(0, bean2); assertThat(bean2.column1).isEqualTo("x"); assertThat(bean2.column2).isNull(); assertThat(model.getBeanCount()).isEqualTo(1); assertThat(model.getValueAt(0, 0)).isEqualTo("x"); assertThat(model.isChangedAt(0, 0)).isFalse(); assertThat(model.getChangedRows().count()).isEqualTo(0); verify(listener).tableChanged(tableModelEvent(TableModelEvent.UPDATE, 0, 0, -1)); verifyNoMoreInteractions(listener); } public static class TestBean { private final long id; private String column1; private String column2; public TestBean() { this(1L, null); } public TestBean(long id, String column1) { this.id = id; this.column1 = column1; } public String getColumn1() { return column1; } public void setColumn1(String column1) { this.column1 = column1; } public String getColumn2() { return column2; } public void setColumn2(String column2) { this.column2 = column2; } } }
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.codeInsight.daemon.impl; import com.intellij.codeInsight.daemon.GutterMark; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.ex.RangeHighlighterEx; import com.intellij.openapi.editor.impl.SweepProcessor; import com.intellij.openapi.editor.impl.DocumentMarkupModel; import com.intellij.openapi.editor.impl.RedBlackTree; import com.intellij.openapi.editor.markup.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.*; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.util.Consumer; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.*; import java.util.List; public class UpdateHighlightersUtil { private static final Comparator<HighlightInfo> BY_START_OFFSET_NODUPS = (o1, o2) -> { int d = o1.getActualStartOffset() - o2.getActualStartOffset(); if (d != 0) return d; d = o1.getActualEndOffset() - o2.getActualEndOffset(); if (d != 0) return d; d = Comparing.compare(o1.getSeverity(), o2.getSeverity()); if (d != 0) return -d; // higher severity first, to prevent warnings overlap errors if (!Comparing.equal(o1.type, o2.type)) { return String.valueOf(o1.type).compareTo(String.valueOf(o2.type)); } if (!Comparing.equal(o1.getGutterIconRenderer(), o2.getGutterIconRenderer())) { return String.valueOf(o1.getGutterIconRenderer()).compareTo(String.valueOf(o2.getGutterIconRenderer())); } if (!Comparing.equal(o1.forcedTextAttributes, o2.forcedTextAttributes)) { return String.valueOf(o1.getGutterIconRenderer()).compareTo(String.valueOf(o2.getGutterIconRenderer())); } if (!Comparing.equal(o1.forcedTextAttributesKey, o2.forcedTextAttributesKey)) { return String.valueOf(o1.getGutterIconRenderer()).compareTo(String.valueOf(o2.getGutterIconRenderer())); } return Comparing.compare(o1.getDescription(), o2.getDescription()); }; private static boolean isCoveredByOffsets(HighlightInfo info, HighlightInfo coveredBy) { return coveredBy.startOffset <= info.startOffset && info.endOffset <= coveredBy.endOffset && info.getGutterIconRenderer() == null; } static void addHighlighterToEditorIncrementally(@NotNull Project project, @NotNull Document document, @NotNull PsiFile file, int startOffset, int endOffset, @NotNull final HighlightInfo info, @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used final int group, @NotNull Map<TextRange, RangeMarker> ranges2markersCache) { ApplicationManager.getApplication().assertIsDispatchThread(); if (isFileLevelOrGutterAnnotation(info)) return; if (info.getStartOffset() < startOffset || info.getEndOffset() > endOffset) return; MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true); final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project); final boolean myInfoIsError = isSevere(info, severityRegistrar); Processor<HighlightInfo> otherHighlightInTheWayProcessor = oldInfo -> { if (!myInfoIsError && isCovered(info, severityRegistrar, oldInfo)) { return false; } return oldInfo.getGroup() != group || !oldInfo.equalsByActualOffset(info); }; boolean allIsClear = DaemonCodeAnalyzerEx.processHighlights(document, project, null, info.getActualStartOffset(), info.getActualEndOffset(), otherHighlightInTheWayProcessor); if (allIsClear) { createOrReuseHighlighterFor(info, colorsScheme, document, group, file, (MarkupModelEx)markup, null, ranges2markersCache, severityRegistrar); clearWhiteSpaceOptimizationFlag(document); assertMarkupConsistent(markup, project); } } public static boolean isFileLevelOrGutterAnnotation(HighlightInfo info) { return info.isFileLevelAnnotation() || info.getGutterIconRenderer() != null; } public static void setHighlightersToEditor(@NotNull Project project, @NotNull Document document, int startOffset, int endOffset, @NotNull Collection<HighlightInfo> highlights, @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used int group) { TextRange range = new TextRange(startOffset, endOffset); ApplicationManager.getApplication().assertIsDispatchThread(); PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document); final DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project); codeAnalyzer.cleanFileLevelHighlights(project, group, psiFile); MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true); assertMarkupConsistent(markup, project); setHighlightersInRange(project, document, range, colorsScheme, new ArrayList<>(highlights), (MarkupModelEx)markup, group); } @Deprecated //for teamcity public static void setHighlightersToEditor(@NotNull Project project, @NotNull Document document, int startOffset, int endOffset, @NotNull Collection<HighlightInfo> highlights, int group) { setHighlightersToEditor(project, document, startOffset, endOffset, highlights, null, group); } // set highlights inside startOffset,endOffset but outside priorityRange static void setHighlightersOutsideRange(@NotNull final Project project, @NotNull final Document document, @NotNull final PsiFile psiFile, @NotNull final List<HighlightInfo> infos, @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used final int startOffset, final int endOffset, @NotNull final ProperTextRange priorityRange, final int group) { ApplicationManager.getApplication().assertIsDispatchThread(); final DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project); if (startOffset == 0 && endOffset == document.getTextLength()) { codeAnalyzer.cleanFileLevelHighlights(project, group, psiFile); } final MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true); assertMarkupConsistent(markup, project); final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project); final HighlightersRecycler infosToRemove = new HighlightersRecycler(); ContainerUtil.quickSort(infos, BY_START_OFFSET_NODUPS); Set<HighlightInfo> infoSet = new THashSet<>(infos); Processor<HighlightInfo> processor = info -> { if (info.getGroup() == group) { RangeHighlighter highlighter = info.getHighlighter(); int hiStart = highlighter.getStartOffset(); int hiEnd = highlighter.getEndOffset(); if (!info.isFromInjection() && hiEnd < document.getTextLength() && (hiEnd <= startOffset || hiStart >= endOffset)) { return true; // injections are oblivious to restricting range } boolean toRemove = infoSet.contains(info) || !priorityRange.containsRange(hiStart, hiEnd) && (hiEnd != document.getTextLength() || priorityRange.getEndOffset() != document.getTextLength()); if (toRemove) { infosToRemove.recycleHighlighter(highlighter); info.setHighlighter(null); } } return true; }; DaemonCodeAnalyzerEx.processHighlightsOverlappingOutside(document, project, null, priorityRange.getStartOffset(), priorityRange.getEndOffset(), processor); final Map<TextRange, RangeMarker> ranges2markersCache = new THashMap<>(10); final boolean[] changed = {false}; SweepProcessor.Generator<HighlightInfo> generator = proc -> ContainerUtil.process(infos, proc); SweepProcessor.sweep(generator, (offset, info, atStart, overlappingIntervals) -> { if (!atStart) return true; if (!info.isFromInjection() && info.getEndOffset() < document.getTextLength() && (info.getEndOffset() <= startOffset || info.getStartOffset()>=endOffset)) return true; // injections are oblivious to restricting range if (info.isFileLevelAnnotation()) { codeAnalyzer.addFileLevelHighlight(project, group, info, psiFile); changed[0] = true; return true; } if (isWarningCoveredByError(info, overlappingIntervals, severityRegistrar)) { return true; } if (info.getStartOffset() < priorityRange.getStartOffset() || info.getEndOffset() > priorityRange.getEndOffset()) { createOrReuseHighlighterFor(info, colorsScheme, document, group, psiFile, (MarkupModelEx)markup, infosToRemove, ranges2markersCache, severityRegistrar); changed[0] = true; } return true; }); for (RangeHighlighter highlighter : infosToRemove.forAllInGarbageBin()) { highlighter.dispose(); changed[0] = true; } if (changed[0]) { clearWhiteSpaceOptimizationFlag(document); } assertMarkupConsistent(markup, project); } static void setHighlightersInRange(@NotNull final Project project, @NotNull final Document document, @NotNull final TextRange range, @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used @NotNull final List<HighlightInfo> infos, @NotNull final MarkupModelEx markup, final int group) { ApplicationManager.getApplication().assertIsDispatchThread(); final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project); final HighlightersRecycler infosToRemove = new HighlightersRecycler(); DaemonCodeAnalyzerEx.processHighlights(document, project, null, range.getStartOffset(), range.getEndOffset(), info -> { if (info.getGroup() == group) { RangeHighlighter highlighter = info.getHighlighter(); int hiStart = highlighter.getStartOffset(); int hiEnd = highlighter.getEndOffset(); boolean willBeRemoved = hiEnd == document.getTextLength() && range.getEndOffset() == document.getTextLength() /*|| range.intersectsStrict(hiStart, hiEnd)*/ || range.containsRange(hiStart, hiEnd) /*|| hiStart <= range.getStartOffset() && hiEnd >= range.getEndOffset()*/; if (willBeRemoved) { infosToRemove.recycleHighlighter(highlighter); info.setHighlighter(null); } } return true; }); ContainerUtil.quickSort(infos, BY_START_OFFSET_NODUPS); final Map<TextRange, RangeMarker> ranges2markersCache = new THashMap<>(10); final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document); final DaemonCodeAnalyzerEx codeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(project); final boolean[] changed = {false}; SweepProcessor.Generator<HighlightInfo> generator = (Processor<HighlightInfo> processor) -> ContainerUtil.process(infos, processor); SweepProcessor.sweep(generator, (offset, info, atStart, overlappingIntervals) -> { if (!atStart) { return true; } if (info.isFileLevelAnnotation() && psiFile != null && psiFile.getViewProvider().isPhysical()) { codeAnalyzer.addFileLevelHighlight(project, group, info, psiFile); changed[0] = true; return true; } if (isWarningCoveredByError(info, overlappingIntervals, severityRegistrar)) { return true; } if (info.getStartOffset() >= range.getStartOffset() && info.getEndOffset() <= range.getEndOffset() && psiFile != null) { createOrReuseHighlighterFor(info, colorsScheme, document, group, psiFile, markup, infosToRemove, ranges2markersCache, severityRegistrar); changed[0] = true; } return true; }); for (RangeHighlighter highlighter : infosToRemove.forAllInGarbageBin()) { highlighter.dispose(); changed[0] = true; } if (changed[0]) { clearWhiteSpaceOptimizationFlag(document); } assertMarkupConsistent(markup, project); } private static boolean isWarningCoveredByError(@NotNull HighlightInfo info, @NotNull Collection<HighlightInfo> overlappingIntervals, @NotNull SeverityRegistrar severityRegistrar) { if (!isSevere(info, severityRegistrar)) { for (HighlightInfo overlapping : overlappingIntervals) { if (isCovered(info, severityRegistrar, overlapping)) return true; } } return false; } private static boolean isCovered(@NotNull HighlightInfo warning, @NotNull SeverityRegistrar severityRegistrar, @NotNull HighlightInfo candidate) { if (!isCoveredByOffsets(warning, candidate)) return false; HighlightSeverity severity = candidate.getSeverity(); if (severity == HighlightInfoType.SYMBOL_TYPE_SEVERITY) return false; // syntax should not interfere with warnings return isSevere(candidate, severityRegistrar); } private static boolean isSevere(@NotNull HighlightInfo info, @NotNull SeverityRegistrar severityRegistrar) { HighlightSeverity severity = info.getSeverity(); return severityRegistrar.compare(HighlightSeverity.ERROR, severity) <= 0 || severity == HighlightInfoType.SYMBOL_TYPE_SEVERITY; } private static void createOrReuseHighlighterFor(@NotNull final HighlightInfo info, @Nullable final EditorColorsScheme colorsScheme, // if null global scheme will be used @NotNull final Document document, final int group, @NotNull final PsiFile psiFile, @NotNull MarkupModelEx markup, @Nullable HighlightersRecycler infosToRemove, @NotNull final Map<TextRange, RangeMarker> ranges2markersCache, @NotNull SeverityRegistrar severityRegistrar) { int infoStartOffset = info.startOffset; int infoEndOffset = info.endOffset; final int docLength = document.getTextLength(); if (infoEndOffset > docLength) { infoEndOffset = docLength; infoStartOffset = Math.min(infoStartOffset, infoEndOffset); } if (infoEndOffset == infoStartOffset && !info.isAfterEndOfLine()) { if (infoEndOffset == docLength) return; // empty highlighter beyond file boundaries infoEndOffset++; //show something in case of empty highlightinfo } info.setGroup(group); int layer = getLayer(info, severityRegistrar); RangeHighlighterEx highlighter = infosToRemove == null ? null : (RangeHighlighterEx)infosToRemove.pickupHighlighterFromGarbageBin(info.startOffset, info.endOffset, layer); final TextRange finalInfoRange = new TextRange(infoStartOffset, infoEndOffset); final TextAttributes infoAttributes = info.getTextAttributes(psiFile, colorsScheme); Consumer<RangeHighlighterEx> changeAttributes = finalHighlighter -> { if (infoAttributes != null) { finalHighlighter.setTextAttributes(infoAttributes); } info.setHighlighter(finalHighlighter); finalHighlighter.setAfterEndOfLine(info.isAfterEndOfLine()); Color color = info.getErrorStripeMarkColor(psiFile, colorsScheme); finalHighlighter.setErrorStripeMarkColor(color); if (info != finalHighlighter.getErrorStripeTooltip()) { finalHighlighter.setErrorStripeTooltip(info); } GutterMark renderer = info.getGutterIconRenderer(); finalHighlighter.setGutterIconRenderer((GutterIconRenderer)renderer); ranges2markersCache.put(finalInfoRange, info.getHighlighter()); if (info.quickFixActionRanges != null) { List<Pair<HighlightInfo.IntentionActionDescriptor, RangeMarker>> list = new ArrayList<>(info.quickFixActionRanges.size()); for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : info.quickFixActionRanges) { TextRange textRange = pair.second; RangeMarker marker = getOrCreate(document, ranges2markersCache, textRange); list.add(Pair.create(pair.first, marker)); } info.quickFixActionMarkers = ContainerUtil.createLockFreeCopyOnWriteList(list); } ProperTextRange fixRange = info.getFixTextRange(); if (finalInfoRange.equals(fixRange)) { info.fixMarker = null; // null means it the same as highlighter' } else { info.fixMarker = getOrCreate(document, ranges2markersCache, fixRange); } }; if (highlighter == null) { highlighter = markup.addRangeHighlighterAndChangeAttributes(infoStartOffset, infoEndOffset, layer, null, HighlighterTargetArea.EXACT_RANGE, false, changeAttributes); } else { markup.changeAttributesInBatch(highlighter, changeAttributes); } boolean attributesSet = Comparing.equal(infoAttributes, highlighter.getTextAttributes()); assert attributesSet : "Info: " + infoAttributes + "; colorsScheme: " + (colorsScheme == null ? "[global]" : colorsScheme.getName()) + "; highlighter:" + highlighter.getTextAttributes(); } private static int getLayer(@NotNull HighlightInfo info, @NotNull SeverityRegistrar severityRegistrar) { final HighlightSeverity severity = info.getSeverity(); int layer; if (severity == HighlightSeverity.WARNING) { layer = HighlighterLayer.WARNING; } else if (severity == HighlightSeverity.WEAK_WARNING) { layer = HighlighterLayer.WEAK_WARNING; } else if (severityRegistrar.compare(severity, HighlightSeverity.ERROR) >= 0) { layer = HighlighterLayer.ERROR; } else if (severity == HighlightInfoType.INJECTED_FRAGMENT_SEVERITY) { layer = HighlighterLayer.CARET_ROW-1; } else if (severity == HighlightInfoType.ELEMENT_UNDER_CARET_SEVERITY) { layer = HighlighterLayer.ELEMENT_UNDER_CARET; } else { layer = HighlighterLayer.ADDITIONAL_SYNTAX; } return layer; } @NotNull private static RangeMarker getOrCreate(@NotNull Document document, @NotNull Map<TextRange, RangeMarker> ranges2markersCache, @NotNull TextRange textRange) { return ranges2markersCache.computeIfAbsent(textRange, __ -> document.createRangeMarker(textRange)); } private static final Key<Boolean> TYPING_INSIDE_HIGHLIGHTER_OCCURRED = Key.create("TYPING_INSIDE_HIGHLIGHTER_OCCURRED"); static boolean isWhitespaceOptimizationAllowed(@NotNull Document document) { return document.getUserData(TYPING_INSIDE_HIGHLIGHTER_OCCURRED) == null; } private static void disableWhiteSpaceOptimization(@NotNull Document document) { document.putUserData(TYPING_INSIDE_HIGHLIGHTER_OCCURRED, Boolean.TRUE); } private static void clearWhiteSpaceOptimizationFlag(@NotNull Document document) { document.putUserData(TYPING_INSIDE_HIGHLIGHTER_OCCURRED, null); } static void updateHighlightersByTyping(@NotNull Project project, @NotNull DocumentEvent e) { ApplicationManager.getApplication().assertIsDispatchThread(); final Document document = e.getDocument(); if (document instanceof DocumentEx && ((DocumentEx)document).isInBulkUpdate()) return; final MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true); assertMarkupConsistent(markup, project); final int start = e.getOffset() - 1; final int end = start + e.getOldLength(); final List<HighlightInfo> toRemove = new ArrayList<>(); DaemonCodeAnalyzerEx.processHighlights(document, project, null, start, end, info -> { if (!info.needUpdateOnTyping()) return true; RangeHighlighter highlighter = info.getHighlighter(); int highlighterStart = highlighter.getStartOffset(); int highlighterEnd = highlighter.getEndOffset(); if (info.isAfterEndOfLine()) { if (highlighterStart < document.getTextLength()) { highlighterStart += 1; } if (highlighterEnd < document.getTextLength()) { highlighterEnd += 1; } } if (!highlighter.isValid() || start < highlighterEnd && highlighterStart <= end) { toRemove.add(info); } return true; }); for (HighlightInfo info : toRemove) { if (!info.getHighlighter().isValid() || info.type.equals(HighlightInfoType.WRONG_REF)) { info.getHighlighter().dispose(); } } assertMarkupConsistent(markup, project); if (!toRemove.isEmpty()) { disableWhiteSpaceOptimization(document); } } private static void assertMarkupConsistent(@NotNull final MarkupModel markup, @NotNull Project project) { if (!RedBlackTree.VERIFY) { return; } Document document = markup.getDocument(); DaemonCodeAnalyzerEx.processHighlights(document, project, null, 0, document.getTextLength(), info -> { assert ((MarkupModelEx)markup).containsHighlighter(info.getHighlighter()); return true; }); RangeHighlighter[] allHighlighters = markup.getAllHighlighters(); for (RangeHighlighter highlighter : allHighlighters) { if (!highlighter.isValid()) continue; Object tooltip = highlighter.getErrorStripeTooltip(); if (!(tooltip instanceof HighlightInfo)) { continue; } final HighlightInfo info = (HighlightInfo)tooltip; boolean contains = !DaemonCodeAnalyzerEx .processHighlights(document, project, null, info.getActualStartOffset(), info.getActualEndOffset(), highlightInfo -> BY_START_OFFSET_NODUPS.compare(highlightInfo, info) != 0); assert contains: info; } } }
/* * Copyright (C) 2008 The Guava Authors * * 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.google.common.collect; public class ForMapMultimapAsMapImplementsMapTest_gwt extends com.google.gwt.junit.client.GWTTestCase { @Override public String getModuleName() { return "com.google.common.collect.testModule"; } public void testClear() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testClear(); } public void testContainsKey() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testContainsKey(); } public void testContainsValue() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testContainsValue(); } public void testEntrySet() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySet(); } public void testEntrySetAddAndAddAll() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetAddAndAddAll(); } public void testEntrySetClear() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetClear(); } public void testEntrySetContainsEntryIncompatibleKey() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetContainsEntryIncompatibleKey(); } public void testEntrySetContainsEntryNullKeyMissing() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetContainsEntryNullKeyMissing(); } public void testEntrySetContainsEntryNullKeyPresent() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetContainsEntryNullKeyPresent(); } public void testEntrySetForEmptyMap() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetForEmptyMap(); } public void testEntrySetIteratorRemove() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetIteratorRemove(); } public void testEntrySetRemove() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetRemove(); } public void testEntrySetRemoveAll() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetRemoveAll(); } public void testEntrySetRemoveAllNullFromEmpty() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetRemoveAllNullFromEmpty(); } public void testEntrySetRemoveDifferentValue() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetRemoveDifferentValue(); } public void testEntrySetRemoveMissingKey() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetRemoveMissingKey(); } public void testEntrySetRemoveNullKeyMissing() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetRemoveNullKeyMissing(); } public void testEntrySetRemoveNullKeyPresent() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetRemoveNullKeyPresent(); } public void testEntrySetRetainAll() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetRetainAll(); } public void testEntrySetRetainAllNullFromEmpty() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetRetainAllNullFromEmpty(); } public void testEntrySetSetValue() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetSetValue(); } public void testEntrySetSetValueSameValue() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEntrySetSetValueSameValue(); } public void testEqualsForEmptyMap() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEqualsForEmptyMap(); } public void testEqualsForEqualMap() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEqualsForEqualMap(); } public void testEqualsForLargerMap() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEqualsForLargerMap(); } public void testEqualsForSmallerMap() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testEqualsForSmallerMap(); } public void testGet() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testGet(); } public void testGetForEmptyMap() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testGetForEmptyMap(); } public void testGetNull() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testGetNull(); } public void testHashCode() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testHashCode(); } public void testHashCodeForEmptyMap() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testHashCodeForEmptyMap(); } public void testKeySetClear() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testKeySetClear(); } public void testKeySetRemove() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testKeySetRemove(); } public void testKeySetRemoveAll() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testKeySetRemoveAll(); } public void testKeySetRemoveAllNullFromEmpty() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testKeySetRemoveAllNullFromEmpty(); } public void testKeySetRetainAll() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testKeySetRetainAll(); } public void testKeySetRetainAllNullFromEmpty() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testKeySetRetainAllNullFromEmpty(); } public void testPutAllExistingKey() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testPutAllExistingKey(); } public void testPutAllNewKey() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testPutAllNewKey(); } public void testPutExistingKey() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testPutExistingKey(); } public void testPutNewKey() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testPutNewKey(); } public void testPutNullKey() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testPutNullKey(); } public void testPutNullValue() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testPutNullValue(); } public void testPutNullValueForExistingKey() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testPutNullValueForExistingKey(); } public void testRemove() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testRemove(); } public void testRemoveMissingKey() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testRemoveMissingKey(); } public void testSize() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testSize(); } public void testValues() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testValues(); } public void testValuesClear() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testValuesClear(); } public void testValuesIteratorRemove() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testValuesIteratorRemove(); } public void testValuesRemove() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testValuesRemove(); } public void testValuesRemoveAll() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testValuesRemoveAll(); } public void testValuesRemoveAllNullFromEmpty() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testValuesRemoveAllNullFromEmpty(); } public void testValuesRemoveMissing() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testValuesRemoveMissing(); } public void testValuesRetainAll() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testValuesRetainAll(); } public void testValuesRetainAllNullFromEmpty() throws Exception { com.google.common.collect.ForMapMultimapAsMapImplementsMapTest testCase = new com.google.common.collect.ForMapMultimapAsMapImplementsMapTest(); testCase.testValuesRetainAllNullFromEmpty(); } }
package com.linuxtek.kona.app.sales.service; import java.util.Date; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linuxtek.kona.app.core.entity.KAccount; import com.linuxtek.kona.app.core.entity.KUser; import com.linuxtek.kona.app.core.service.KAbstractService; import com.linuxtek.kona.app.core.service.KUserService; import com.linuxtek.kona.app.sales.entity.KProduct; import com.linuxtek.kona.app.sales.entity.KPurchase; import com.linuxtek.kona.app.sales.entity.KPromo; import com.linuxtek.kona.data.mybatis.KMyBatisUtil; import com.linuxtek.kona.util.KDateUtil; public abstract class KAbstractPurchaseService<PURCHASE extends KPurchase, PURCHASE_EXAMPLE, PRODUCT extends KProduct, PROMO extends KPromo, USER extends KUser, ACCOUNT extends KAccount> extends KAbstractService<PURCHASE,PURCHASE_EXAMPLE> implements KPurchaseService<PURCHASE> { private static Logger logger = LoggerFactory.getLogger(KAbstractPurchaseService.class); // ---------------------------------------------------------------------------- protected abstract PURCHASE getNewObject(); protected abstract <S extends KPromoService<PROMO,ACCOUNT,PRODUCT>> S getPromoService(); protected abstract <S extends KUserService<USER>> S getUserService(); protected abstract <S extends KProductService<PRODUCT>> S getProductService(); protected abstract void sendPendingProductExpirationEmail(PURCHASE purchase, int days); // ---------------------------------------------------------------------------- @Override public void validate(PURCHASE purchase) { if (purchase.getCreatedDate() == null) { purchase.setCreatedDate(new Date()); } if (purchase.getUid() == null) { purchase.setUid(uuid()); } purchase.setUpdatedDate(new Date()); } // ---------------------------------------------------------------------------- @Override public PURCHASE update(PURCHASE purchase) { super.update(purchase); List<PURCHASE> children = fetchByParentId(purchase.getId()); if (children != null && children.size()>0) { for (PURCHASE child : children) { child.setEnabled(purchase.isEnabled()); child.setExpirationDate(purchase.getExpirationDate()); update(child); } } return purchase; } // ---------------------------------------------------------------------------- @Override public List<PURCHASE> fetchSubscriptionsByExpirationDate(Date startDate, Date endDate, Boolean autoRenew) { if (endDate == null) { endDate = startDate; } // .andExpirationDateIsNotNull() Map<String,Object> filter = KMyBatisUtil.createFilter("!expirationDate", null); // .andExpirationDateGreaterThanOrEqualTo(startDate) filter.put(">=expirationDate", startDate); // .andExpirationDateLessThanOrEqualTo(endDate); filter.put("<=expirationDate", endDate); if (autoRenew != null) { filter.put("autoRenew", autoRenew); } return fetchByCriteria(0, 99999, null, filter, false); } // ---------------------------------------------------------------------------- private List<PURCHASE> fetchExpired() { Date now = new Date(); // .andExpirationDateIsNotNull() Map<String,Object> filter = KMyBatisUtil.createFilter("!expirationDate", null); // .andExpirationDateLessThanOrEqualTo(now); filter.put("<=expirationDate", now); return fetchByCriteria(0, 99999, null, filter, false); } // ---------------------------------------------------------------------------- @Override public PURCHASE fetchByAccountIdAndProductId(Long accountId, Long productId) { Map<String,Object> filter = KMyBatisUtil.createFilter("accountId", accountId); filter.put("productId", productId); //filter.put("enabled", true); return KMyBatisUtil.fetchOne(fetchByCriteria(0, 99999, null, filter, false)); } // ---------------------------------------------------------------------------- @Override public List<PURCHASE> fetchByAccountId(Long accountId) { Map<String,Object> filter = KMyBatisUtil.createFilter("accountId", accountId); //filter.put("enabled", true); return fetchByCriteria(0, 99999, null, filter, false); } // ---------------------------------------------------------------------------- @Override public List<PURCHASE> fetchByParentId(Long parentId) { Map<String,Object> filter = KMyBatisUtil.createFilter("parentId", parentId); return fetchByCriteria(0, 99999, null, filter, false); } // ---------------------------------------------------------------------------- // NOTE: appId is optional. if set to null, then all products for account are returned. @Override public List<PURCHASE> fetchByAccountIdAndAppId(Long accountId, Long appId) { Map<String,Object> filter = KMyBatisUtil.createFilter("accountId", accountId); if (appId != null) { filter.put("appId", appId); } //filter.put("enabled", true); return fetchByCriteria(0, 99999, null, filter, false); } // ---------------------------------------------------------------------------- @Override public void expireSubscriptions() { List<PURCHASE> result = fetchExpired(); for (PURCHASE purchase : result) { logger.debug("expireProducts: removing Purchase:\n" + purchase); purchase.setAutoRenew(false); purchase.setExpirationDate(new Date()); update(purchase); } } // ---------------------------------------------------------------------------- @Override public List<PURCHASE> fetchSubscriptionsPendingExpiration(int days) { Date startDate = new Date(); Date endDate = KDateUtil.addDays(startDate, days); return fetchSubscriptionsByExpirationDate(startDate, endDate, false); } // ---------------------------------------------------------------------------- @Override public void remindSubscriptionsPendingExpiration(int days) { List<PURCHASE> purchaseList = fetchSubscriptionsPendingExpiration(days); for (PURCHASE purchase : purchaseList) { if (purchase.getProductId() == null || purchase.isAutoRenew()) continue; try { sendPendingProductExpirationEmail(purchase, days); } catch (Exception e) { logger.error(e.getMessage(), e); } } } // ---------------------------------------------------------------------------- @Override public PURCHASE savePromoPurchase(Long userId, Long productId, Long promoId) { USER user = getUserService().fetchById(userId); PRODUCT product = getProductService().fetchById(productId); PROMO promo = getPromoService().fetchById(promoId); PURCHASE purchase = fetchByAccountIdAndProductId(user.getAccountId(), product.getId()); if (purchase == null) { purchase = getNewObject(); purchase.setAccountId(user.getAccountId()); purchase.setUserId(userId); purchase.setAppId(product.getAppId()); purchase.setProductId(productId); purchase.setCreatedDate(new Date()); } purchase.setPromoId(promoId); purchase.setAutoRenew(false); purchase.setEnabled(true); Integer days = promo.getSubscriptionDays(); if (days != null && days >= 0) { Date expirationDate = KDateUtil.addDays(new Date(), days); purchase.setExpirationDate(expirationDate); } else { purchase.setExpirationDate(null); } if (purchase.getId() == null) { purchase = add(purchase); } else { purchase = update(purchase); } return purchase; } }
/** * Copyright 2015 West Coast Informatics, LLC */ package org.ihtsdo.otf.refset.helpers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Properties; import java.util.Scanner; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status.Family; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.lang3.time.FastDateFormat; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; import com.fasterxml.jackson.databind.AnnotationIntrospector; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; /** * Loads and serves configuration. */ public class ConfigUtility { /** The Constant DEFAULT. */ public final static String DEFAULT = "DEFAULT"; /** The date format. */ public final static FastDateFormat DATE_FORMAT = FastDateFormat .getInstance("yyyyMMdd"); /** The Constant DATE_FORMAT2. */ public final static FastDateFormat DATE_FORMAT2 = FastDateFormat .getInstance("yyyy_MM_dd"); /** The Constant DATE_FORMAT3. */ public final static FastDateFormat DATE_FORMAT3 = FastDateFormat .getInstance("yyyy"); /** The config. */ public static Properties config = null; /** The transformer for DOM -> XML. */ private static Transformer transformer; /** The date format. */ public final static FastDateFormat format = FastDateFormat .getInstance("yyyyMMdd"); static { try { TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer(); // Indent output. transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "4"); // Skip XML declaration header. transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } } /** * Indicates whether or not the server is active. * * @return <code>true</code> if so, <code>false</code> otherwise * @throws Exception the exception */ public static boolean isServerActive() throws Exception { if (config == null) config = ConfigUtility.getConfigProperties(); try { // Attempt to logout to verify service is up (this works like a "ping"). Client client = ClientBuilder.newClient(); WebTarget target = client.target(config.getProperty("base.url") + "/security/logout/dummy"); Response response = target.request(MediaType.APPLICATION_JSON).get(); if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { return true; } else { return false; } } catch (Exception e) { return false; } } /** * Returns the config properties. * @return the config properties * * @throws Exception the exception */ public static Properties getConfigProperties() throws Exception { if (config == null) { // Need to determine the label (default "") String label = ""; Properties labelProp = new Properties(); // If no resource is available, go with the default // ONLY setups that explicitly intend to override the setting // cause it to be something other than the default. InputStream input = ConfigUtility.class.getResourceAsStream("/label.prop"); if (input != null) { labelProp.load(input); // If a refset.config.label override can be found, use it String candidateLabel = labelProp.getProperty("refset.config.label"); // If the default, uninterpolated value is used, stick again with the // default if (candidateLabel != null && !candidateLabel.equals("${refset.config.label}")) { label = candidateLabel; } } else { Logger.getLogger(ConfigUtility.class.getName()).info( " label.prop resource cannot be found, using default"); } Logger.getLogger(ConfigUtility.class.getName()).info( " refset.config.label = " + label); // Now get the properties from the corresponding setting // This is a complicated mechanism to support multiple simulataneous // installations within the same container (e.g. tomcat). // Default setups do not require this. String configFileName = System.getProperty("refset.config" + (label.isEmpty() ? "" : "." + label)); Logger.getLogger(ConfigUtility.class.getName()).info( " refset.config." + (label.isEmpty() ? "" : "." + label) + " = " + configFileName); config = new Properties(); FileReader in = new FileReader(new File(configFileName)); config.load(in); in.close(); Logger.getLogger(ConfigUtility.class).info(" properties = " + config); } return config; } /** * New handler instance. * * @param <T> the * @param handler the handler * @param handlerClass the handler class * @param type the type * @return the object * @throws Exception the exception */ @SuppressWarnings("unchecked") public static <T> T newHandlerInstance(String handler, String handlerClass, Class<T> type) throws Exception { if (handlerClass == null) { throw new Exception("Handler class " + handlerClass + " is not defined"); } Class<?> toInstantiate = Class.forName(handlerClass); if (toInstantiate == null) { throw new Exception("Unable to find class " + handlerClass); } Object o = null; try { o = toInstantiate.newInstance(); } catch (Exception e) { // do nothing } if (o == null) { throw new Exception("Unable to instantiate class " + handlerClass + ", check for default constructor."); } if (type.isAssignableFrom(o.getClass())) { return (T) o; } throw new Exception("Handler is not assignable from " + type.getName()); } /** * Instantiates a handler using standard setup and configures it with * properties. * * @param <T> the * @param property the property * @param handlerName the handler name * @param type the type * @return the t * @throws Exception the exception */ public static <T extends Configurable> T newStandardHandlerInstanceWithConfiguration( String property, String handlerName, Class<T> type) throws Exception { // Instantiate the handler // property = "metadata.service.handler" (e.g) // handlerName = "SNOMED" (e.g.) String classKey = property + "." + handlerName + ".class"; if (config.getProperty(classKey) == null) { throw new Exception("Unexpected null classkey " + classKey); } String handlerClass = config.getProperty(classKey); Logger.getLogger(ConfigUtility.class).info("Instantiate " + handlerClass); T handler = ConfigUtility.newHandlerInstance(handlerName, handlerClass, type); // Look up and build properties Properties handlerProperties = new Properties(); handlerProperties.setProperty("security.handler", handlerName); for (Object key : config.keySet()) { // Find properties like "metadata.service.handler.SNOMED.class" if (key.toString().startsWith(property + "." + handlerName + ".")) { String shortKey = key.toString().substring( (property + "." + handlerName + ".").length()); Logger.getLogger(ConfigUtility.class).info( " property " + shortKey + " = " + config.getProperty(key.toString())); handlerProperties.put(shortKey, config.getProperty(key.toString())); } } handler.setProperties(handlerProperties); return handler; } /** * Returns the graph for string. * * @param xml the xml * @param graphClass the graph class * @return the graph for string * @throws JAXBException the JAXB exception */ public static Object getGraphForString(String xml, Class<?> graphClass) throws JAXBException { JAXBContext context = JAXBContext.newInstance(graphClass); Unmarshaller unmarshaller = context.createUnmarshaller(); return unmarshaller.unmarshal(new StreamSource(new StringReader(xml))); } /** * Returns the graph for json. * * @param json the json * @param graphClass the graph class * @return the graph for json * @throws Exception the exception */ public static Object getGraphForJson(String json, Class<?> graphClass) throws Exception { InputStream in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory()); mapper.setAnnotationIntrospector(introspector); return mapper.readValue(in, graphClass); } /** * Returns the graph for file. * * @param file the file * @param graphClass the graph class * @return the graph for file * @throws FileNotFoundException the file not found exception * @throws JAXBException the JAXB exception */ @SuppressWarnings("resource") public static Object getGraphForFile(File file, Class<?> graphClass) throws FileNotFoundException, JAXBException { return getGraphForString(new Scanner(file, "UTF-8").useDelimiter("\\A") .next(), graphClass); } /** * Returns the graph for stream. * * @param in the in * @param graphClass the graph class * @return the graph for stream * @throws FileNotFoundException the file not found exception * @throws JAXBException the JAXB exception */ @SuppressWarnings("resource") public static Object getGraphForStream(InputStream in, Class<?> graphClass) throws FileNotFoundException, JAXBException { return getGraphForString(new Scanner(in, "UTF-8").useDelimiter("\\A") .next(), graphClass); } /** * Returns the XML string for for graph object. * * @param object the object * @return the string for for graph * @throws JAXBException the JAXB exception */ public static String getStringForGraph(Object object) throws JAXBException { StringWriter writer = new StringWriter(); JAXBContext jaxbContext = null; jaxbContext = JAXBContext.newInstance(object.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.marshal(object, writer); return writer.toString(); } /** * Returns the json for graph. * * @param object the object * @return the json for graph * @throws Exception the exception */ public static String getJsonForGraph(Object object) throws Exception { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory()); mapper.setAnnotationIntrospector(introspector); return mapper.writeValueAsString(object); } /** * Returns the node for string. * * @param xml the xml * @return the node for string * @throws ParserConfigurationException the parser configuration exception * @throws SAXException the SAX exception * @throws IOException Signals that an I/O exception has occurred. */ public static Node getNodeForString(String xml) throws ParserConfigurationException, SAXException, IOException { InputStream in = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); // Parse XML file. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(in); Node rootNode = document.getFirstChild(); return rootNode; } /** * Returns the node for file. * * @param file the file * @return the node for file * @throws ParserConfigurationException the parser configuration exception * @throws SAXException the SAX exception * @throws IOException Signals that an I/O exception has occurred. */ public static Node getNodeForFile(File file) throws ParserConfigurationException, SAXException, IOException { InputStream in = new FileInputStream(file); // Parse XML file. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(in); Node rootNode = document.getFirstChild(); in.close(); return rootNode; } /** * Returns the string for node. * * @param root the root node * @return the string for node * @throws TransformerException the transformer exception * @throws ParserConfigurationException the parser configuration exception */ public static String getStringForNode(Node root) throws TransformerException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); document.appendChild(document.importNode(root, true)); DOMSource source = new DOMSource(document); StringWriter out = new StringWriter(); StreamResult result = new StreamResult(out); transformer.transform(source, result); return out.toString(); } /** * Returns the graph for node. * * @param node the node * @param graphClass the graph class * @return the graph for node * @throws JAXBException the JAXB exception * @throws TransformerException the transformer exception * @throws ParserConfigurationException the parser configuration exception */ public static Object getGraphForNode(Node node, Class<?> graphClass) throws JAXBException, TransformerException, ParserConfigurationException { return getGraphForString(getStringForNode(node), graphClass); } /** * Returns the node for graph. * * @param object the object * @return the node for graph * @throws ParserConfigurationException the parser configuration exception * @throws SAXException the SAX exception * @throws IOException Signals that an I/O exception has occurred. * @throws JAXBException the JAXB exception */ public static Node getNodeForGraph(Object object) throws ParserConfigurationException, SAXException, IOException, JAXBException { return getNodeForString(getStringForGraph(object)); } /** * Pretty format. * * @param input the input * @param indent the indent * @return the string */ public static String prettyFormat(String input, int indent) { try { Source xmlInput = new StreamSource(new StringReader(input)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Exception e) { // simple exception handling, please review it throw new RuntimeException(e); } } /** * Merge-sort two files. * * @param files1 the first set of files * @param files2 the second set of files * @param comp the comparator * @param dir the sort dir * @param headerLine the header_line * @return the sorted {@link File} * @throws IOException Signals that an I/O exception has occurred. */ public static File mergeSortedFiles(File files1, File files2, Comparator<String> comp, File dir, String headerLine) throws IOException { final BufferedReader in1 = new BufferedReader(new FileReader(files1)); final BufferedReader in2 = new BufferedReader(new FileReader(files2)); final File outFile = File.createTempFile("t+~", ".tmp", dir); final BufferedWriter out = new BufferedWriter(new FileWriter(outFile)); String line1 = in1.readLine(); String line2 = in2.readLine(); String line = null; if (!headerLine.isEmpty()) { line = headerLine; out.write(line); out.newLine(); } while (line1 != null || line2 != null) { if (line1 == null) { line = line2; line2 = in2.readLine(); } else if (line2 == null) { line = line1; line1 = in1.readLine(); } else if (comp.compare(line1, line2) < 0) { line = line1; line1 = in1.readLine(); } else { line = line2; line2 = in2.readLine(); } // if a header line, do not write if (!line.startsWith("id")) { out.write(line); out.newLine(); } } out.flush(); out.close(); in1.close(); in2.close(); return outFile; } /** * Delete directory. * * @param path the path * @return true, if successful */ static public boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return (path.delete()); } /** * Sends email. * * @param subject the subject * @param from the from * @param recipients the recipients * @param body the body * @param details the details * @param authFlag the auth flag * @throws Exception the exception */ public static void sendEmail(String subject, String from, String recipients, String body, Properties details, boolean authFlag) throws Exception { // avoid sending mail if disabled if ("false".equals(details.getProperty("mail.enabled"))) { // do nothing return; } Session session = null; if (authFlag) { Authenticator auth = new SMTPAuthenticator(); session = Session.getInstance(details, auth); } else { session = Session.getInstance(details); } MimeMessage msg = new MimeMessage(session); if (body.contains("<html")) { msg.setContent(body.toString(), "text/html; charset=utf-8"); } else { msg.setText(body.toString()); } msg.setSubject(subject); msg.setFrom(new InternetAddress(from)); String[] recipientsArray = recipients.split(";"); for (String recipient : recipientsArray) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } Transport.send(msg); } /** * SMTPAuthenticator. */ public static class SMTPAuthenticator extends javax.mail.Authenticator { /** * Instantiates an empty {@link SMTPAuthenticator}. */ public SMTPAuthenticator() { // do nothing } /* see superclass */ @Override public PasswordAuthentication getPasswordAuthentication() { Properties config = null; try { config = ConfigUtility.getConfigProperties(); } catch (Exception e) { // do nothing } if (config == null) { return null; } else { return new PasswordAuthentication(config.getProperty("mail.smtp.user"), config.getProperty("mail.smtp.password")); } } } /** * Reflection sort. * * @param <T> the * @param classes the classes * @param clazz the clazz * @param sortField the sort field * @throws Exception the exception */ public static <T> void reflectionSort(List<T> classes, Class<T> clazz, String sortField) throws Exception { final Method getMethod = clazz.getMethod("get" + sortField.substring(0, 1).toUpperCase() + sortField.substring(1)); if (getMethod.getReturnType().isAssignableFrom(Comparable.class)) { throw new Exception("Referenced sort field is not comparable"); } Collections.sort(classes, new Comparator<T>() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public int compare(T o1, T o2) { try { Comparable f1 = (Comparable) getMethod.invoke(o1, new Object[] {}); Comparable f2 = (Comparable) getMethod.invoke(o2, new Object[] {}); return f1.compareTo(f2); } catch (Exception e) { // do nothing } return 0; } }); } /** * To arabic. * * @param number the number * @return the int * @throws Exception the exception */ public static int toArabic(String number) throws Exception { if (number.isEmpty()) return 0; if (number.startsWith("M")) return 1000 + toArabic(number.substring(1)); if (number.startsWith("CM")) return 900 + toArabic(number.substring(2)); if (number.startsWith("D")) return 500 + toArabic(number.substring(1)); if (number.startsWith("CD")) return 400 + toArabic(number.substring(2)); if (number.startsWith("C")) return 100 + toArabic(number.substring(1)); if (number.startsWith("XC")) return 90 + toArabic(number.substring(2)); if (number.startsWith("L")) return 50 + toArabic(number.substring(1)); if (number.startsWith("XL")) return 40 + toArabic(number.substring(2)); if (number.startsWith("X")) return 10 + toArabic(number.substring(1)); if (number.startsWith("IX")) return 9 + toArabic(number.substring(2)); if (number.startsWith("V")) return 5 + toArabic(number.substring(1)); if (number.startsWith("IV")) return 4 + toArabic(number.substring(2)); if (number.startsWith("I")) return 1 + toArabic(number.substring(1)); throw new Exception("something bad happened"); } /** * Indicates whether or not roman numeral is the case. * * @param number the number * @return <code>true</code> if so, <code>false</code> otherwise */ public static boolean isRomanNumeral(String number) { return number .matches("^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$"); } /** * Returns the indent for level. * * @param level the level * @return the indent for level */ public static String getIndentForLevel(int level) { StringBuilder sb = new StringBuilder().append(" "); for (int i = 0; i < level; i++) { sb.append(" "); } return sb.toString(); } }
/* * Copyright 2016-present Facebook, 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. */ package com.facebook.buck.haskell; import com.facebook.buck.cxx.Archive; import com.facebook.buck.cxx.CxxPreprocessables; import com.facebook.buck.cxx.CxxPreprocessorInput; import com.facebook.buck.cxx.CxxSource; import com.facebook.buck.cxx.CxxSourceRuleFactory; import com.facebook.buck.cxx.CxxSourceTypes; import com.facebook.buck.cxx.CxxToolFlags; import com.facebook.buck.cxx.ExplicitCxxToolFlags; import com.facebook.buck.cxx.PreprocessorFlags; import com.facebook.buck.cxx.toolchain.ArchiveContents; import com.facebook.buck.cxx.toolchain.CxxPlatform; import com.facebook.buck.cxx.toolchain.CxxPlatforms; import com.facebook.buck.cxx.toolchain.linker.Linker; import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkable; import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInput; import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkables; import com.facebook.buck.file.WriteFile; import com.facebook.buck.graph.AbstractBreadthFirstTraversal; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargets; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.InternalFlavor; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.Tool; import com.facebook.buck.rules.args.Arg; import com.facebook.buck.rules.args.SourcePathArg; import com.facebook.buck.rules.args.StringArg; import com.facebook.buck.util.MoreIterables; import com.facebook.buck.util.RichStream; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import java.nio.file.Path; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import java.util.stream.Stream; public class HaskellDescriptionUtils { private HaskellDescriptionUtils() {} static final Flavor PROF = InternalFlavor.of("prof"); static final ImmutableList<String> PROF_FLAGS = ImmutableList.of("-prof", "-osuf", "p_o", "-hisuf", "p_hi"); static final ImmutableList<String> PIC_FLAGS = ImmutableList.of("-dynamic", "-fPIC", "-hisuf", "dyn_hi"); /** * Create a Haskell compile rule that compiles all the given haskell sources in one step and pulls * interface files from all transitive haskell dependencies. */ private static HaskellCompileRule createCompileRule( BuildTarget target, final ProjectFilesystem projectFilesystem, BuildRuleParams baseParams, final BuildRuleResolver resolver, SourcePathRuleFinder ruleFinder, ImmutableSet<BuildRule> deps, HaskellPlatform platform, final Linker.LinkableDepType depType, boolean hsProfile, Optional<String> main, Optional<HaskellPackageInfo> packageInfo, ImmutableList<String> flags, HaskellSources sources) { CxxPlatform cxxPlatform = platform.getCxxPlatform(); final Map<BuildTarget, ImmutableList<String>> depFlags = new TreeMap<>(); final Map<BuildTarget, ImmutableList<SourcePath>> depIncludes = new TreeMap<>(); final ImmutableSortedMap.Builder<String, HaskellPackage> exposedPackagesBuilder = ImmutableSortedMap.naturalOrder(); final ImmutableSortedMap.Builder<String, HaskellPackage> packagesBuilder = ImmutableSortedMap.naturalOrder(); new AbstractBreadthFirstTraversal<BuildRule>(deps) { private final ImmutableSet<BuildRule> empty = ImmutableSet.of(); @Override public Iterable<BuildRule> visit(BuildRule rule) { Iterable<BuildRule> ruleDeps = empty; if (rule instanceof HaskellCompileDep) { HaskellCompileDep haskellCompileDep = (HaskellCompileDep) rule; ruleDeps = haskellCompileDep.getCompileDeps(platform); HaskellCompileInput compileInput = haskellCompileDep.getCompileInput(platform, depType, hsProfile); depFlags.put(rule.getBuildTarget(), compileInput.getFlags()); depIncludes.put(rule.getBuildTarget(), compileInput.getIncludes()); // We add packages from first-order deps as expose modules, and transitively included // packages as hidden ones. boolean firstOrderDep = deps.contains(rule); for (HaskellPackage pkg : compileInput.getPackages()) { if (firstOrderDep) { exposedPackagesBuilder.put(pkg.getInfo().getIdentifier(), pkg); } else { packagesBuilder.put(pkg.getInfo().getIdentifier(), pkg); } } } return ruleDeps; } }.start(); Collection<CxxPreprocessorInput> cxxPreprocessorInputs = CxxPreprocessables.getTransitiveCxxPreprocessorInput(cxxPlatform, deps); ExplicitCxxToolFlags.Builder toolFlagsBuilder = CxxToolFlags.explicitBuilder(); PreprocessorFlags.Builder ppFlagsBuilder = PreprocessorFlags.builder(); toolFlagsBuilder.setPlatformFlags( StringArg.from(CxxSourceTypes.getPlatformPreprocessFlags(cxxPlatform, CxxSource.Type.C))); for (CxxPreprocessorInput input : cxxPreprocessorInputs) { ppFlagsBuilder.addAllIncludes(input.getIncludes()); ppFlagsBuilder.addAllFrameworkPaths(input.getFrameworks()); toolFlagsBuilder.addAllRuleFlags(input.getPreprocessorFlags().get(CxxSource.Type.C)); } ppFlagsBuilder.setOtherFlags(toolFlagsBuilder.build()); PreprocessorFlags ppFlags = ppFlagsBuilder.build(); ImmutableList<String> compileFlags = ImmutableList.<String>builder() .addAll(platform.getCompilerFlags()) .addAll(flags) .addAll(Iterables.concat(depFlags.values())) .build(); ImmutableList<SourcePath> includes = ImmutableList.copyOf(Iterables.concat(depIncludes.values())); ImmutableSortedMap<String, HaskellPackage> exposedPackages = exposedPackagesBuilder.build(); ImmutableSortedMap<String, HaskellPackage> packages = packagesBuilder.build(); return HaskellCompileRule.from( target, projectFilesystem, baseParams, ruleFinder, platform.getCompiler().resolve(resolver), platform.getHaskellVersion(), compileFlags, ppFlags, cxxPlatform, depType == Linker.LinkableDepType.STATIC ? CxxSourceRuleFactory.PicType.PDC : CxxSourceRuleFactory.PicType.PIC, hsProfile, main, packageInfo, includes, exposedPackages, packages, sources, CxxSourceTypes.getPreprocessor(cxxPlatform, CxxSource.Type.C).resolve(resolver)); } protected static BuildTarget getCompileBuildTarget( BuildTarget target, HaskellPlatform platform, Linker.LinkableDepType depType, boolean hsProfile) { target = target.withFlavors( platform.getFlavor(), InternalFlavor.of("objects-" + depType.toString().toLowerCase().replace('_', '-'))); if (hsProfile) { target = target.withAppendedFlavors(PROF); } return target; } public static HaskellCompileRule requireCompileRule( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, BuildRuleResolver resolver, SourcePathRuleFinder ruleFinder, ImmutableSet<BuildRule> deps, HaskellPlatform platform, Linker.LinkableDepType depType, boolean hsProfile, Optional<String> main, Optional<HaskellPackageInfo> packageInfo, ImmutableList<String> flags, HaskellSources srcs) { return (HaskellCompileRule) resolver.computeIfAbsent( getCompileBuildTarget(buildTarget, platform, depType, hsProfile), target -> HaskellDescriptionUtils.createCompileRule( target, projectFilesystem, params, resolver, ruleFinder, deps, platform, depType, hsProfile, main, packageInfo, flags, srcs)); } /** * Create a Haskell link rule that links the given inputs to a executable or shared library and * pulls in transitive native linkable deps from the given dep roots. */ public static HaskellLinkRule createLinkRule( BuildTarget target, ProjectFilesystem projectFilesystem, BuildRuleParams baseParams, BuildRuleResolver resolver, SourcePathRuleFinder ruleFinder, HaskellPlatform platform, Linker.LinkType linkType, ImmutableList<Arg> linkerFlags, Iterable<Arg> linkerInputs, Iterable<? extends NativeLinkable> deps, ImmutableSet<BuildTarget> linkWholeDeps, Linker.LinkableDepType depType, Path outputPath, Optional<String> soname, boolean hsProfile) { Tool linker = platform.getLinker().resolve(resolver); ImmutableList.Builder<Arg> linkerArgsBuilder = ImmutableList.builder(); ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder(); // Add the base flags from the `.buckconfig` first. argsBuilder.addAll(StringArg.from(platform.getLinkerFlags())); // Pass in the appropriate flags to link a shared library. if (linkType.equals(Linker.LinkType.SHARED)) { argsBuilder.addAll(StringArg.from("-shared", "-dynamic")); soname.ifPresent( name -> argsBuilder.addAll( StringArg.from( MoreIterables.zipAndConcat( Iterables.cycle("-optl"), platform.getCxxPlatform().getLd().resolve(resolver).soname(name))))); } // Add in extra flags passed into this function. argsBuilder.addAll(linkerFlags); // We pass in the linker inputs and all native linkable deps by prefixing with `-optl` so that // the args go straight to the linker, and preserve their order. linkerArgsBuilder.addAll(linkerInputs); for (NativeLinkable nativeLinkable : NativeLinkables.getNativeLinkables(platform.getCxxPlatform(), deps, depType).values()) { NativeLinkable.Linkage link = nativeLinkable.getPreferredLinkage(platform.getCxxPlatform()); NativeLinkableInput input = nativeLinkable.getNativeLinkableInput( platform.getCxxPlatform(), NativeLinkables.getLinkStyle(link, depType), linkWholeDeps.contains(nativeLinkable.getBuildTarget()), ImmutableSet.of()); linkerArgsBuilder.addAll(input.getArgs()); } // Since we use `-optl` to pass all linker inputs directly to the linker, the haskell linker // will complain about not having any input files. So, create a dummy archive with an empty // module and pass that in normally to work around this. BuildTarget emptyModuleTarget = target.withAppendedFlavors(InternalFlavor.of("empty-module")); WriteFile emptyModule = resolver.addToIndex( new WriteFile( emptyModuleTarget, projectFilesystem, baseParams, "module Unused where", BuildTargets.getGenPath(projectFilesystem, emptyModuleTarget, "%s/Unused.hs"), /* executable */ false)); HaskellCompileRule emptyCompiledModule = resolver.addToIndex( createCompileRule( target.withAppendedFlavors(InternalFlavor.of("empty-compiled-module")), projectFilesystem, baseParams, resolver, ruleFinder, // TODO(agallagher): We shouldn't need any deps to compile an empty module, but ghc // implicitly tries to load the prelude and in some setups this is provided via a // Buck dependency. RichStream.from(deps) .filter(BuildRule.class) .toImmutableSortedSet(Ordering.natural()), platform, depType, hsProfile, Optional.empty(), Optional.empty(), ImmutableList.of(), HaskellSources.builder() .putModuleMap("Unused", emptyModule.getSourcePathToOutput()) .build())); BuildTarget emptyArchiveTarget = target.withAppendedFlavors(InternalFlavor.of("empty-archive")); Archive emptyArchive = resolver.addToIndex( Archive.from( emptyArchiveTarget, projectFilesystem, resolver, ruleFinder, platform.getCxxPlatform(), ArchiveContents.NORMAL, BuildTargets.getGenPath(projectFilesystem, emptyArchiveTarget, "%s/libempty.a"), emptyCompiledModule.getObjects(), /* cacheable */ true)); argsBuilder.add(SourcePathArg.of(emptyArchive.getSourcePathToOutput())); ImmutableList<Arg> args = argsBuilder.build(); ImmutableList<Arg> linkerArgs = linkerArgsBuilder.build(); return resolver.addToIndex( new HaskellLinkRule( target, projectFilesystem, baseParams .withDeclaredDeps( ImmutableSortedSet.<BuildRule>naturalOrder() .addAll(linker.getDeps(ruleFinder)) .addAll( Stream.of(args, linkerArgs) .flatMap(Collection::stream) .flatMap(arg -> arg.getDeps(ruleFinder).stream()) .iterator()) .build()) .withoutExtraDeps(), linker, outputPath, args, linkerArgs, platform.shouldCacheLinks())); } /** Accumulate parse-time deps needed by Haskell descriptions in depsBuilder. */ public static void getParseTimeDeps( Iterable<HaskellPlatform> platforms, ImmutableCollection.Builder<BuildTarget> depsBuilder) { RichStream.from(platforms) .forEach( platform -> { // Since this description generates haskell link/compile/package rules, make sure the // parser includes deps for these tools. depsBuilder.addAll(platform.getCompiler().getParseTimeDeps()); depsBuilder.addAll(platform.getLinker().getParseTimeDeps()); depsBuilder.addAll(platform.getPackager().getParseTimeDeps()); // We use the C/C++ linker's Linker object to find out how to pass in the soname, so just // add all C/C++ platform parse time deps. depsBuilder.addAll(CxxPlatforms.getParseTimeDeps(platform.getCxxPlatform())); }); } }
/* * Copyright 2021 Google LLC * * 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 * * https://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.google.ads.googleads.v9.resources; import com.google.api.pathtemplate.PathTemplate; import com.google.api.resourcenames.ResourceName; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. @Generated("by gapic-generator-java") public class OfflineUserDataJobName implements ResourceName { private static final PathTemplate CUSTOMER_ID_OFFLINE_USER_DATA_UPDATE_ID = PathTemplate.createWithoutUrlEncoding( "customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}"); private volatile Map<String, String> fieldValuesMap; private final String customerId; private final String offlineUserDataUpdateId; @Deprecated protected OfflineUserDataJobName() { customerId = null; offlineUserDataUpdateId = null; } private OfflineUserDataJobName(Builder builder) { customerId = Preconditions.checkNotNull(builder.getCustomerId()); offlineUserDataUpdateId = Preconditions.checkNotNull(builder.getOfflineUserDataUpdateId()); } public String getCustomerId() { return customerId; } public String getOfflineUserDataUpdateId() { return offlineUserDataUpdateId; } public static Builder newBuilder() { return new Builder(); } public Builder toBuilder() { return new Builder(this); } public static OfflineUserDataJobName of(String customerId, String offlineUserDataUpdateId) { return newBuilder() .setCustomerId(customerId) .setOfflineUserDataUpdateId(offlineUserDataUpdateId) .build(); } public static String format(String customerId, String offlineUserDataUpdateId) { return newBuilder() .setCustomerId(customerId) .setOfflineUserDataUpdateId(offlineUserDataUpdateId) .build() .toString(); } public static OfflineUserDataJobName parse(String formattedString) { if (formattedString.isEmpty()) { return null; } Map<String, String> matchMap = CUSTOMER_ID_OFFLINE_USER_DATA_UPDATE_ID.validatedMatch( formattedString, "OfflineUserDataJobName.parse: formattedString not in valid format"); return of(matchMap.get("customer_id"), matchMap.get("offline_user_data_update_id")); } public static List<OfflineUserDataJobName> parseList(List<String> formattedStrings) { List<OfflineUserDataJobName> list = new ArrayList<>(formattedStrings.size()); for (String formattedString : formattedStrings) { list.add(parse(formattedString)); } return list; } public static List<String> toStringList(List<OfflineUserDataJobName> values) { List<String> list = new ArrayList<>(values.size()); for (OfflineUserDataJobName value : values) { if (value == null) { list.add(""); } else { list.add(value.toString()); } } return list; } public static boolean isParsableFrom(String formattedString) { return CUSTOMER_ID_OFFLINE_USER_DATA_UPDATE_ID.matches(formattedString); } @Override public Map<String, String> getFieldValuesMap() { if (fieldValuesMap == null) { synchronized (this) { if (fieldValuesMap == null) { ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder(); if (customerId != null) { fieldMapBuilder.put("customer_id", customerId); } if (offlineUserDataUpdateId != null) { fieldMapBuilder.put("offline_user_data_update_id", offlineUserDataUpdateId); } fieldValuesMap = fieldMapBuilder.build(); } } } return fieldValuesMap; } public String getFieldValue(String fieldName) { return getFieldValuesMap().get(fieldName); } @Override public String toString() { return CUSTOMER_ID_OFFLINE_USER_DATA_UPDATE_ID.instantiate( "customer_id", customerId, "offline_user_data_update_id", offlineUserDataUpdateId); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o != null || getClass() == o.getClass()) { OfflineUserDataJobName that = ((OfflineUserDataJobName) o); return Objects.equals(this.customerId, that.customerId) && Objects.equals(this.offlineUserDataUpdateId, that.offlineUserDataUpdateId); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= Objects.hashCode(customerId); h *= 1000003; h ^= Objects.hashCode(offlineUserDataUpdateId); return h; } /** Builder for customers/{customer_id}/offlineUserDataJobs/{offline_user_data_update_id}. */ public static class Builder { private String customerId; private String offlineUserDataUpdateId; protected Builder() {} public String getCustomerId() { return customerId; } public String getOfflineUserDataUpdateId() { return offlineUserDataUpdateId; } public Builder setCustomerId(String customerId) { this.customerId = customerId; return this; } public Builder setOfflineUserDataUpdateId(String offlineUserDataUpdateId) { this.offlineUserDataUpdateId = offlineUserDataUpdateId; return this; } private Builder(OfflineUserDataJobName offlineUserDataJobName) { this.customerId = offlineUserDataJobName.customerId; this.offlineUserDataUpdateId = offlineUserDataJobName.offlineUserDataUpdateId; } public OfflineUserDataJobName build() { return new OfflineUserDataJobName(this); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package proyecto2j17; import java.util.ArrayList; /** * * @author Oswaldo */ public class Sintactico extends Interfaz{ ArrayList<MiniToken> tokens; int pos = 0; int pre; private Errores CabezaEr; Errores error; Errores temporalEr; String ExR = ""; String Titulo; private String Inicio; private ArrayList NT = new ArrayList(); private ArrayList T = new ArrayList(); private ArrayList R = new ArrayList(); boolean NoT = false; boolean Te = false; boolean Re = false; private ArrayList<ExpresionRegular> ER = new ArrayList(); private ArrayList<Producciones> Prod = new ArrayList(); boolean PR = false; boolean PR2 = false; boolean panicoS = false; boolean PanicoSe = false; public Sintactico(ArrayList<MiniToken> tokens){ this.tokens = tokens; CabezaEr = new Errores("","","","",0,0,null); pos = 0; } public void analizar(){ panicoS = false; PanicoSe = false; pre = tokens.get(pos).getId(); ER.clear(); Prod.clear(); S(); if(pos != tokens.size()){ Error("Tokens terminados antes de completar analisis"); } else{ } } public void Parea(int analisis){ if (pre == analisis){ if (PR){ ExR = ExR +"//"+ tokens.get(pos).getLexema(); } if (PR2){ ExR = ExR + "//"+tokens.get(pos).getLexema(); } pos++; if(pos==tokens.size()){ pre = -1; }else{ pre= tokens.get(pos).getId(); } }else{ // System.out.println("Se esperaba idToken:" + analisis + "Tengo " + pre); Error("Se esperaba idToken:" + analisis + "Tengo " + pre); } } //S -> [lenguaje] GRAM RESERV GRADEF [-lenguaje] public void S() { Parea(140); Parea(45); Parea(145); GRAM(); RESERV(); GRADEF(); Parea(140); Parea(150); Parea(45); Parea(145); } //GRAM -> [[componentes lexicos]] CL public void GRAM() { Parea(140); Parea(140); Parea(30); Parea(145); Parea(145); CL(); } // CL-> PR $ CL' public void CL() { PP(); PR = false; ListaER(); Parea(90); CLP(); } // CL'-> PR $ CL' // |eps public void CLP(){ if(pre == 95 || pre == 165 || pre == 155 || pre == 55){ PP(); PR = false; ListaER(); Parea(90); CLP(); } } // PP -> id ::= PR public void PP(){ Titulo = tokens.get(pos).getLexema(); Parea(55); Parea(60); PR(); } // PR -> Q PR' public void PR() { PR = true; Q(); PRP(); } // PR' -> Q PR' // |eps public void PRP(){ if(pre == 95 || pre == 165 || pre == 155 || pre == 55){ Q(); PRP(); } } // Q -> R Q' public void Q(){ R(); QP(); } // Q' -> '|'R Q' // |eps public void QP(){ if(pre == 85){ Parea(85); R(); QP(); } } // R -> T R' public void R(){ T(); RP(); } // R' -> .T R' // |eps public void RP(){ if(pre == 80){ Parea(80); T(); RP(); } } // T -> U* // |U? // |U+ // |U public void T(){ U(); if (pre==70){ Parea(70); }else if(pre==75){ Parea(75); }else if(pre==65){ Parea(65); } } //U -> (Q) // |'"' Q '"' // |'simbolo' // |letra // |numero public void U(){ if (pre == 95){ Parea(95); Q(); Parea(100); }else if(pre == 165){ Parea(165); }else if(pre == 155){ Parea(155); }else if(pre == 55){ Parea(55); }else{ Error("Se esperaba ( '\"' Simbolo o identificador"); } } // RESERV -> [[reservadas]]RES public void RESERV(){ Parea(140); Parea(140); Parea(35); Parea(145); Parea(145); RES(); } // RES -> L $ RES' public void RES(){ L(); Parea(90); RESP(); } // RES' -> L $ RES' // |eps public void RESP(){ if(pre == 55){ L(); Parea(90); RESP(); } } // L-> id::="id" public void L(){ for(int i = 0; i<getER().size();i++){ if (tokens.get(pos).getLexema().equals(getER().get(i).getTitulo())){ ErrorS("Nombre repetido",tokens.get(pos).getLexema()); } } for(int i = 0;i < getR().size();i++){ if (tokens.get(pos).getLexema().equals(getR().get(i))){ ErrorS("Nombre repetido",tokens.get(pos).getLexema()); } } getR().add(tokens.get(pos).getLexema()); Parea(55); Parea(60); Parea(160); } // GRADEF -> [[Gramatica: id]]NT public void GRADEF(){ Parea(140); Parea(140); Parea(40); Parea(165); Parea(55); Parea(145); Parea(145); NT(); } // NT -> No_Terminales={LID} TE public void NT(){ NoT = true; Parea(5); Parea(130); Parea(105); LID(); NoT = false; Parea(110); TE(); } // TE -> Terminales={LID} IN public void TE(){ Te = true; Parea(10); Parea(130); Parea(105); LID(); Te = false; Parea(110); IN(); } // LID -> id LID' public void LID(){ if(NoT){ getNT().add(tokens.get(pos).getLexema().toLowerCase()); chequeoTerminales(tokens.get(pos).getLexema().toLowerCase()); chequeoRepetidoNT(tokens.get(pos).getLexema().toLowerCase()); }else if(Te){ getT().add(tokens.get(pos).getLexema().toLowerCase()); chequeoDeclarado(tokens.get(pos).getLexema().toLowerCase()); chequeoNoTerminales(tokens.get(pos).getLexema().toLowerCase()); chequeoRepetidoT(tokens.get(pos).getLexema().toLowerCase()); } Parea(55); LIDP(); } // LID' -> ,id LID' // |eps public void LIDP(){ if(pre == 115){ Parea(115); if(NoT){ getNT().add(tokens.get(pos).getLexema().toLowerCase()); chequeoTerminales(tokens.get(pos).getLexema().toLowerCase()); chequeoRepetidoNT(tokens.get(pos).getLexema().toLowerCase()); }else if(Te){ getT().add(tokens.get(pos).getLexema().toLowerCase()); chequeoDeclarado(tokens.get(pos).getLexema().toLowerCase()); chequeoNoTerminales(tokens.get(pos).getLexema().toLowerCase()); chequeoRepetidoT(tokens.get(pos).getLexema().toLowerCase()); } Parea(55); LIDP(); } } // IN -> Inicio=<id> PROD public void IN(){ Parea(15); Parea(130); Parea(120); Inicio = tokens.get(pos).getLexema().toLowerCase(); Parea(55); Parea(125); PROD(); } // PROD -> Producciones={ LPRO } public void PROD(){ Parea(20); Parea(130); Parea(105); LPRO(); Parea(110); } // LPRO -> IP $ LPRO' public void LPRO(){ IP(); PR2 = false; ListaPRO(); Parea(90); LPROP(); } // LPRO' -> IP $ LPRO' // |eps public void LPROP(){ if(pre == 120){ IP(); PR2 = false; ListaPRO(); Parea(90); LPROP(); } } // IP -> <id> ::= PO public void IP(){ Parea(120); Titulo = "<" + tokens.get(pos).getLexema()+">" ; Parea(55); Parea(125); Parea(60); PO(); } // PO -> POT PO' public void PO(){ PR2 = true; POT(); POP(); } // PO' -> POT PO' // |eps public void POP(){ if ( pre == 55 || pre == 120){ POT(); POP(); } } // POT -> POF POT' public void POT(){ POF(); POTP(); } // POT' -> |POF POT' // |eps public void POTP(){ if (pre == 85){ Parea(85); POF(); POTP(); } } // POF -> id // |<id> // |'epsilon' public void POF(){ if (pre == 55){ Parea(55); }else if (pre == 120){ Parea(120); Parea(55); Parea(125); }else if (pre == 25){ Parea(25); }else{ Error("Se Esperaba id o <id>"); } } /** * @return the CabezaEr */ public Errores getCabezaEr() { return CabezaEr; } private void Error(String Descripcion) { panicoS = true; error = new Errores(tokens.get(pos).getLexema(),Descripcion,"Sintactico","",tokens.get(pos).getFila(),tokens.get(pos).getColumna(),null); temporalEr = getCabezaEr(); while (temporalEr.getSiguiente() != null){ temporalEr = temporalEr.getSiguiente(); } temporalEr.setSiguiente(error); } private void ListaER() { debugeo(); getER().add(new ExpresionRegular(Titulo, ExR)); for (int i =0;i< getER().size()-1;i++){ if (Titulo.equals(getER().get(i).getTitulo())){ ErrorS("Nombre repetido",Titulo); } } ExR=""; } private void debugeo() { int xy = 2; } /** * @return the ER */ public ArrayList<ExpresionRegular> getER() { return ER; } /** * @return the Prod */ public ArrayList<Producciones> getProd() { return Prod; } private void ListaPRO() { debugeo(); getProd().add(new Producciones(Titulo, ExR)); ExR=""; } /** * @return the Inicio */ public String getInicio() { return Inicio; } /** * @return the NT */ public ArrayList getNT() { return NT; } /** * @return the T */ public ArrayList getT() { return T; } /** * @return the R */ public ArrayList getR() { return R; } private void ErrorS(String Descripcion,String Error) { PanicoSe = true; error = new Errores(Error,Descripcion,"Semantico","",tokens.get(pos).getFila(),tokens.get(pos).getColumna(),null); temporalEr = getCabezaEr(); while (temporalEr.getSiguiente() != null){ temporalEr = temporalEr.getSiguiente(); } temporalEr.setSiguiente(error); } private void chequeoDeclarado(String compara) { boolean declara = false; for(int i = 0;i< getER().size();i++){ if (compara.equals(getER().get(i).getTitulo().toLowerCase())){ declara = true; } } for(int i = 0;i<getR().size();i++){ if (compara.equals(getR().get(i).toString().toLowerCase())){ declara = true; } } if (declara){ }else{ ErrorS("No Esta Declarada", compara); declara = false; } } private void chequeoTerminales(String compara) { boolean nova = false; for(int i = 0;i< getER().size();i++){ if (compara.equals(getER().get(i).getTitulo().toLowerCase())){ nova = true; } } for(int i = 0;i<getR().size();i++){ if (compara.equals(getR().get(i).toString().toLowerCase())){ nova = true; } } if(nova){ ErrorS("Terminal en No Teminales",compara); nova = false; } } private void chequeoNoTerminales(String compara) { boolean novat = false; for(int i =0; i<getNT().size();i++){ if(compara.equals(getNT().get(i).toString().toLowerCase())){ novat = true; } } if(novat){ ErrorS("No Terminal en Terminales",compara); novat = false; } } private void chequeoRepetidoNT(String compara) { boolean igual = false; for(int i = 0; i<getNT().size()-1;i++){ if(compara.equals(getNT().get(i).toString().toLowerCase())){ igual = true; } } if (igual){ ErrorS("No Terminal se repite en conjunto", compara); igual = false; } } private void chequeoRepetidoT(String compara) { boolean igual = false; for(int i = 0; i<getT().size()-1;i++){ if(compara.equals(getT().get(i).toString().toLowerCase())){ igual = true; } } if (igual){ ErrorS("Terminal se repite en conjunto", compara); igual = false; } } }
/* * #%L * BroadleafCommerce Open Admin Platform * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.openadmin.server.dao; import org.apache.commons.collections4.map.LRUMap; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.broadleafcommerce.common.money.Money; import org.broadleafcommerce.common.persistence.EntityConfiguration; import org.broadleafcommerce.common.presentation.AdminPresentationClass; import org.broadleafcommerce.common.presentation.client.PersistencePerspectiveItemType; import org.broadleafcommerce.common.presentation.client.SupportedFieldType; import org.broadleafcommerce.common.presentation.client.VisibilityEnum; import org.broadleafcommerce.common.util.dao.DynamicDaoHelper; import org.broadleafcommerce.common.util.dao.DynamicDaoHelperImpl; import org.broadleafcommerce.common.util.dao.EJB3ConfigurationDao; import org.broadleafcommerce.openadmin.dto.BasicFieldMetadata; import org.broadleafcommerce.openadmin.dto.ClassTree; import org.broadleafcommerce.openadmin.dto.FieldMetadata; import org.broadleafcommerce.openadmin.dto.ForeignKey; import org.broadleafcommerce.openadmin.dto.MergedPropertyType; import org.broadleafcommerce.openadmin.dto.PersistencePerspective; import org.broadleafcommerce.openadmin.server.dao.provider.metadata.FieldMetadataProvider; import org.broadleafcommerce.openadmin.server.dao.provider.metadata.request.AddMetadataFromFieldTypeRequest; import org.broadleafcommerce.openadmin.server.dao.provider.metadata.request.LateStageAddMetadataRequest; import org.broadleafcommerce.openadmin.server.service.AppConfigurationService; import org.broadleafcommerce.openadmin.server.service.persistence.module.FieldManager; import org.broadleafcommerce.openadmin.server.service.persistence.validation.FieldNamePropertyValidator; import org.broadleafcommerce.openadmin.server.service.type.FieldProviderResponse; import org.hibernate.Criteria; import org.hibernate.MappingException; import org.hibernate.SessionFactory; import org.hibernate.ejb.HibernateEntityManager; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.type.ComponentType; import org.hibernate.type.Type; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Resource; import javax.persistence.EntityManager; /** * * @author jfischer * */ @Component("blDynamicEntityDao") @Scope("prototype") public class DynamicEntityDaoImpl implements DynamicEntityDao, ApplicationContextAware { private static final Log LOG = LogFactory.getLog(DynamicEntityDaoImpl.class); protected static final Map<String,Map<String, FieldMetadata>> METADATA_CACHE = new LRUMap<String, Map<String, FieldMetadata>>(1000); /* * This is the same as POLYMORPHIC_ENTITY_CACHE, except that it does not contain classes that are abstract or have been marked for exclusion * from polymorphism */ protected EntityManager standardEntityManager; @Resource(name="blMetadata") protected Metadata metadata; @Resource(name="blEJB3ConfigurationDao") protected EJB3ConfigurationDao ejb3ConfigurationDao; @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; @Resource(name="blMetadataProviders") protected List<FieldMetadataProvider> fieldMetadataProviders = new ArrayList<FieldMetadataProvider>(); @Resource(name= "blDefaultFieldMetadataProvider") protected FieldMetadataProvider defaultFieldMetadataProvider; @Resource(name="blAppConfigurationRemoteService") protected AppConfigurationService appConfigurationRemoteService; protected DynamicDaoHelper dynamicDaoHelper = new DynamicDaoHelperImpl(); @Value("${cache.entity.dao.metadata.ttl}") protected int cacheEntityMetaDataTtl; protected long lastCacheFlushTime = System.currentTimeMillis(); protected ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public Criteria createCriteria(Class<?> entityClass) { return ((HibernateEntityManager) getStandardEntityManager()).getSession().createCriteria(entityClass); } @Override public <T> T persist(T entity) { standardEntityManager.persist(entity); standardEntityManager.flush(); return entity; } @Override public Object find(Class<?> entityClass, Object key) { return standardEntityManager.find(entityClass, key); } @Override public <T> T merge(T entity) { T response = standardEntityManager.merge(entity); standardEntityManager.flush(); return response; } @Override public void flush() { standardEntityManager.flush(); } @Override public void detach(Serializable entity) { standardEntityManager.detach(entity); } @Override public void refresh(Serializable entity) { standardEntityManager.refresh(entity); } @Override public Serializable retrieve(Class<?> entityClass, Object primaryKey) { return (Serializable) standardEntityManager.find(entityClass, primaryKey); } @Override public void remove(Serializable entity) { standardEntityManager.remove(entity); standardEntityManager.flush(); } @Override public void clear() { standardEntityManager.clear(); } @Override public PersistentClass getPersistentClass(String targetClassName) { return ejb3ConfigurationDao.getConfiguration().getClassMapping(targetClassName); } @Override public boolean useCache() { if (cacheEntityMetaDataTtl < 0) { return true; } if (cacheEntityMetaDataTtl == 0) { return false; } else { if ((System.currentTimeMillis() - lastCacheFlushTime) > cacheEntityMetaDataTtl) { lastCacheFlushTime = System.currentTimeMillis(); METADATA_CACHE.clear(); DynamicDaoHelperImpl.POLYMORPHIC_ENTITY_CACHE.clear(); DynamicDaoHelperImpl.POLYMORPHIC_ENTITY_CACHE_WO_EXCLUSIONS.clear(); return true; // cache is empty } else { return true; } } } @Override public Class<?>[] getAllPolymorphicEntitiesFromCeiling(Class<?> ceilingClass) { return getAllPolymorphicEntitiesFromCeiling(ceilingClass, true); } @Override public Class<?>[] getAllPolymorphicEntitiesFromCeiling(Class<?> ceilingClass, boolean includeUnqualifiedPolymorphicEntities) { return dynamicDaoHelper.getAllPolymorphicEntitiesFromCeiling(ceilingClass, getSessionFactory(), includeUnqualifiedPolymorphicEntities, useCache()); } @Override public Class<?>[] getUpDownInheritance(Class<?> testClass) { return dynamicDaoHelper.getUpDownInheritance(testClass, getSessionFactory(), true, useCache(), ejb3ConfigurationDao); } public Class<?>[] sortEntities(Class<?> ceilingClass, List<Class<?>> entities) { return dynamicDaoHelper.sortEntities(ceilingClass, entities); } protected void addClassToTree(Class<?> clazz, ClassTree tree) { Class<?> testClass; try { testClass = Class.forName(tree.getFullyQualifiedClassname()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } if (clazz.equals(testClass)) { return; } if (clazz.getSuperclass().equals(testClass)) { ClassTree myTree = new ClassTree(clazz.getName(), isExcludeClassFromPolymorphism(clazz)); createClassTreeFromAnnotation(clazz, myTree); tree.setChildren((ClassTree[]) ArrayUtils.add(tree.getChildren(), myTree)); } else { for (ClassTree child : tree.getChildren()) { addClassToTree(clazz, child); } } } protected void createClassTreeFromAnnotation(Class<?> clazz, ClassTree myTree) { AdminPresentationClass classPresentation = clazz.getAnnotation(AdminPresentationClass.class); if (classPresentation != null) { String friendlyName = classPresentation.friendlyName(); if (!StringUtils.isEmpty(friendlyName)) { myTree.setFriendlyName(friendlyName); } } } @Override public ClassTree getClassTree(Class<?>[] polymorphicClasses) { String ceilingClass = null; for (Class<?> clazz : polymorphicClasses) { AdminPresentationClass classPresentation = clazz.getAnnotation(AdminPresentationClass.class); if (classPresentation != null) { String ceilingEntity = classPresentation.ceilingDisplayEntity(); if (!StringUtils.isEmpty(ceilingEntity)) { ceilingClass = ceilingEntity; break; } } } if (ceilingClass != null) { int pos = -1; int j = 0; for (Class<?> clazz : polymorphicClasses) { if (clazz.getName().equals(ceilingClass)) { pos = j; break; } j++; } if (pos >= 0) { Class<?>[] temp = new Class<?>[pos + 1]; System.arraycopy(polymorphicClasses, 0, temp, 0, j + 1); polymorphicClasses = temp; } } ClassTree classTree = null; if (!ArrayUtils.isEmpty(polymorphicClasses)) { Class<?> topClass = polymorphicClasses[polymorphicClasses.length-1]; classTree = new ClassTree(topClass.getName(), isExcludeClassFromPolymorphism(topClass)); createClassTreeFromAnnotation(topClass, classTree); for (int j=polymorphicClasses.length-1; j >= 0; j--) { addClassToTree(polymorphicClasses[j], classTree); } classTree.finalizeStructure(1); } return classTree; } @Override public ClassTree getClassTreeFromCeiling(Class<?> ceilingClass) { Class<?>[] sortedEntities = getAllPolymorphicEntitiesFromCeiling(ceilingClass); return getClassTree(sortedEntities); } @Override public Map<String, FieldMetadata> getSimpleMergedProperties(String entityName, PersistencePerspective persistencePerspective) { Class<?>[] entityClasses; try { entityClasses = getAllPolymorphicEntitiesFromCeiling(Class.forName(entityName)); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } if (!ArrayUtils.isEmpty(entityClasses)) { return getMergedProperties( entityName, entityClasses, (ForeignKey) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY), persistencePerspective.getAdditionalNonPersistentProperties(), persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "" ); } else { Map<String, FieldMetadata> mergedProperties = new HashMap<String, FieldMetadata>(); Class<?> targetClass; try { targetClass = Class.forName(entityName); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } Map<String, FieldMetadata> attributesMap = metadata.getFieldPresentationAttributes(null, targetClass, this, ""); for (String property : attributesMap.keySet()) { FieldMetadata presentationAttribute = attributesMap.get(property); if (!presentationAttribute.getExcluded()) { Field field = FieldManager.getSingleField(targetClass, property); if (!Modifier.isStatic(field.getModifiers())) { boolean handled = false; for (FieldMetadataProvider provider : fieldMetadataProviders) { FieldProviderResponse response = provider.addMetadataFromFieldType( new AddMetadataFromFieldTypeRequest(field, targetClass, null, new ForeignKey[]{}, MergedPropertyType.PRIMARY, null, null, "", property, null, false, 0, attributesMap, presentationAttribute, ((BasicFieldMetadata) presentationAttribute).getExplicitFieldType(), field.getType(), this), mergedProperties); if (FieldProviderResponse.NOT_HANDLED != response) { handled = true; } if (FieldProviderResponse.HANDLED_BREAK == response) { break; } } if (!handled) { //this provider is not included in the provider list on purpose - it is designed to handle basic //AdminPresentation fields, and those fields not admin presentation annotated at all defaultFieldMetadataProvider.addMetadataFromFieldType( new AddMetadataFromFieldTypeRequest(field, targetClass, null, new ForeignKey[]{}, MergedPropertyType.PRIMARY, null, null, "", property, null, false, 0, attributesMap, presentationAttribute, ((BasicFieldMetadata) presentationAttribute).getExplicitFieldType(), field.getType(), this), mergedProperties); } } } } return mergedProperties; } } @Override public Map<String, FieldMetadata> getMergedProperties(@Nonnull Class<?> cls) { Class<?>[] polymorphicTypes = getAllPolymorphicEntitiesFromCeiling(cls); return getMergedProperties( cls.getName(), polymorphicTypes, null, new String[] {}, new ForeignKey[] {}, MergedPropertyType.PRIMARY, true, new String[] {}, new String[] {}, null, "" ); } @Override public Map<String, FieldMetadata> getMergedProperties( String ceilingEntityFullyQualifiedClassname, Class<?>[] entities, ForeignKey foreignField, String[] additionalNonPersistentProperties, ForeignKey[] additionalForeignFields, MergedPropertyType mergedPropertyType, Boolean populateManyToOneFields, String[] includeFields, String[] excludeFields, String configurationKey, String prefix ) { Map<String, FieldMetadata> mergedProperties = getMergedPropertiesRecursively( ceilingEntityFullyQualifiedClassname, entities, foreignField, additionalNonPersistentProperties, additionalForeignFields, mergedPropertyType, populateManyToOneFields, includeFields, excludeFields, configurationKey, new ArrayList<Class<?>>(), prefix, false ); final List<String> removeKeys = new ArrayList<String>(); for (final String key : mergedProperties.keySet()) { if (mergedProperties.get(key).getExcluded() != null && mergedProperties.get(key).getExcluded()) { removeKeys.add(key); } } for (String removeKey : removeKeys) { mergedProperties.remove(removeKey); } // Allow field metadata providers to contribute additional fields here. These latestage handlers take place // after any cached lookups occur, and are ideal for adding in dynamic properties that are not globally cacheable // like properties gleaned from reflection typically are. Set<String> keys = new HashSet<String>(mergedProperties.keySet()); for (Class<?> targetClass : entities) { for (String key : keys) { LateStageAddMetadataRequest amr = new LateStageAddMetadataRequest(key, null, targetClass, this, ""); boolean foundOneOrMoreHandlers = false; for (FieldMetadataProvider fieldMetadataProvider : fieldMetadataProviders) { FieldProviderResponse response = fieldMetadataProvider.lateStageAddMetadata(amr, mergedProperties); if (FieldProviderResponse.NOT_HANDLED != response) { foundOneOrMoreHandlers = true; } if (FieldProviderResponse.HANDLED_BREAK == response) { break; } } if (!foundOneOrMoreHandlers) { defaultFieldMetadataProvider.lateStageAddMetadata(amr, mergedProperties); } } } return mergedProperties; } protected Map<String, FieldMetadata> getMergedPropertiesRecursively( final String ceilingEntityFullyQualifiedClassname, final Class<?>[] entities, final ForeignKey foreignField, final String[] additionalNonPersistentProperties, final ForeignKey[] additionalForeignFields, final MergedPropertyType mergedPropertyType, final Boolean populateManyToOneFields, final String[] includeFields, final String[] excludeFields, final String configurationKey, final List<Class<?>> parentClasses, final String prefix, final Boolean isParentExcluded ) { PropertyBuilder propertyBuilder = new PropertyBuilder() { @Override public Map<String, FieldMetadata> execute(Boolean overridePopulateManyToOne) { Map<String, FieldMetadata> mergedProperties = new HashMap<String, FieldMetadata>(); Boolean classAnnotatedPopulateManyToOneFields; if (overridePopulateManyToOne != null) { classAnnotatedPopulateManyToOneFields = overridePopulateManyToOne; } else { classAnnotatedPopulateManyToOneFields = populateManyToOneFields; } buildPropertiesFromPolymorphicEntities( entities, foreignField, additionalNonPersistentProperties, additionalForeignFields, mergedPropertyType, classAnnotatedPopulateManyToOneFields, includeFields, excludeFields, configurationKey, ceilingEntityFullyQualifiedClassname, mergedProperties, parentClasses, prefix, isParentExcluded ); return mergedProperties; } }; Map<String, FieldMetadata> mergedProperties = metadata.overrideMetadata(entities, propertyBuilder, prefix, isParentExcluded, ceilingEntityFullyQualifiedClassname, configurationKey, this); applyIncludesAndExcludes(includeFields, excludeFields, prefix, isParentExcluded, mergedProperties); applyForeignKeyPrecedence(foreignField, additionalForeignFields, mergedProperties); return mergedProperties; } protected void applyForeignKeyPrecedence(ForeignKey foreignField, ForeignKey[] additionalForeignFields, Map<String, FieldMetadata> mergedProperties) { for (String key : mergedProperties.keySet()) { boolean isForeign = false; if (foreignField != null) { isForeign = foreignField.getManyToField().equals(key); } if (!isForeign && !ArrayUtils.isEmpty(additionalForeignFields)) { for (ForeignKey foreignKey : additionalForeignFields) { isForeign = foreignKey.getManyToField().equals(key); if (isForeign) { break; } } } if (isForeign) { FieldMetadata metadata = mergedProperties.get(key); metadata.setExcluded(false); } } } protected void applyIncludesAndExcludes(String[] includeFields, String[] excludeFields, String prefix, Boolean isParentExcluded, Map<String, FieldMetadata> mergedProperties) { //check includes if (!ArrayUtils.isEmpty(includeFields)) { for (String include : includeFields) { for (String key : mergedProperties.keySet()) { String testKey = prefix + key; if (!(testKey.startsWith(include + ".") || testKey.equals(include))) { FieldMetadata metadata = mergedProperties.get(key); LOG.debug("applyIncludesAndExcludes:Excluding " + key + " because this field did not appear in the explicit includeFields list"); metadata.setExcluded(true); } else { FieldMetadata metadata = mergedProperties.get(key); if (!isParentExcluded) { LOG.debug("applyIncludesAndExcludes:Showing " + key + " because this field appears in the explicit includeFields list"); metadata.setExcluded(false); } } } } } else if (!ArrayUtils.isEmpty(excludeFields)) { //check excludes for (String exclude : excludeFields) { for (String key : mergedProperties.keySet()) { String testKey = prefix + key; if (testKey.startsWith(exclude + ".") || testKey.equals(exclude)) { FieldMetadata metadata = mergedProperties.get(key); LOG.debug("applyIncludesAndExcludes:Excluding " + key + " because this field appears in the explicit excludeFields list"); metadata.setExcluded(true); } else { FieldMetadata metadata = mergedProperties.get(key); if (!isParentExcluded) { LOG.debug("applyIncludesAndExcludes:Showing " + key + " because this field did not appear in the explicit excludeFields list"); metadata.setExcluded(false); } } } } } } protected String pad(String s, int length, char pad) { StringBuilder buffer = new StringBuilder(s); while (buffer.length() < length) { buffer.insert(0, pad); } return buffer.toString(); } protected String getCacheKey(ForeignKey foreignField, String[] additionalNonPersistentProperties, ForeignKey[] additionalForeignFields, MergedPropertyType mergedPropertyType, Boolean populateManyToOneFields, Class<?> clazz, String configurationKey, Boolean isParentExcluded) { StringBuilder sb = new StringBuilder(150); sb.append(clazz.hashCode()); sb.append(foreignField==null?"":foreignField.toString()); sb.append(configurationKey); sb.append(isParentExcluded); if (additionalNonPersistentProperties != null) { for (String prop : additionalNonPersistentProperties) { sb.append(prop); } } if (additionalForeignFields != null) { for (ForeignKey key : additionalForeignFields) { sb.append(key.toString()); } } sb.append(mergedPropertyType); sb.append(populateManyToOneFields); String digest; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(sb.toString().getBytes()); BigInteger number = new BigInteger(1,messageDigest); digest = number.toString(16); } catch(NoSuchAlgorithmException e) { throw new RuntimeException(e); } return pad(digest, 32, '0'); } protected void buildPropertiesFromPolymorphicEntities( Class<?>[] entities, ForeignKey foreignField, String[] additionalNonPersistentProperties, ForeignKey[] additionalForeignFields, MergedPropertyType mergedPropertyType, Boolean populateManyToOneFields, String[] includeFields, String[] excludeFields, String configurationKey, String ceilingEntityFullyQualifiedClassname, Map<String, FieldMetadata> mergedProperties, List<Class<?>> parentClasses, String prefix, Boolean isParentExcluded ) { for (Class<?> clazz : entities) { String cacheKey = getCacheKey(foreignField, additionalNonPersistentProperties, additionalForeignFields, mergedPropertyType, populateManyToOneFields, clazz, configurationKey, isParentExcluded); Map<String, FieldMetadata> cacheData = null; synchronized(DynamicDaoHelperImpl.LOCK_OBJECT) { if (useCache()) { cacheData = METADATA_CACHE.get(cacheKey); } if (cacheData == null) { Map<String, FieldMetadata> props = getPropertiesForEntityClass( clazz, foreignField, additionalNonPersistentProperties, additionalForeignFields, mergedPropertyType, populateManyToOneFields, includeFields, excludeFields, configurationKey, ceilingEntityFullyQualifiedClassname, parentClasses, prefix, isParentExcluded ); //first check all the properties currently in there to see if my entity inherits from them for (Class<?> clazz2 : entities) { if (!clazz2.getName().equals(clazz.getName())) { for (Map.Entry<String, FieldMetadata> entry : props.entrySet()) { FieldMetadata metadata = entry.getValue(); try { if (Class.forName(metadata.getInheritedFromType()).isAssignableFrom(clazz2)) { String[] both = (String[]) ArrayUtils.addAll(metadata.getAvailableToTypes(), new String[]{clazz2.getName()}); metadata.setAvailableToTypes(both); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } } METADATA_CACHE.put(cacheKey, props); cacheData = props; } } //clone the metadata before passing to the system Map<String, FieldMetadata> clonedCache = new HashMap<String, FieldMetadata>(cacheData.size()); for (Map.Entry<String, FieldMetadata> entry : cacheData.entrySet()) { clonedCache.put(entry.getKey(), entry.getValue().cloneFieldMetadata()); } mergedProperties.putAll(clonedCache); } } @Override public Field[] getAllFields(Class<?> targetClass) { Field[] allFields = new Field[]{}; boolean eof = false; Class<?> currentClass = targetClass; while (!eof) { Field[] fields = currentClass.getDeclaredFields(); allFields = (Field[]) ArrayUtils.addAll(allFields, fields); if (currentClass.getSuperclass() != null) { currentClass = currentClass.getSuperclass(); } else { eof = true; } } return allFields; } @Override public Map<String, FieldMetadata> getPropertiesForPrimitiveClass( String propertyName, String friendlyPropertyName, Class<?> targetClass, Class<?> parentClass, MergedPropertyType mergedPropertyType ) { Map<String, FieldMetadata> fields = new HashMap<String, FieldMetadata>(); BasicFieldMetadata presentationAttribute = new BasicFieldMetadata(); presentationAttribute.setFriendlyName(friendlyPropertyName); if (String.class.isAssignableFrom(targetClass)) { presentationAttribute.setExplicitFieldType(SupportedFieldType.STRING); presentationAttribute.setVisibility(VisibilityEnum.VISIBLE_ALL); fields.put(propertyName, metadata.getFieldMetadata("", propertyName, null, SupportedFieldType.STRING, null, parentClass, presentationAttribute, mergedPropertyType, this)); } else if (Boolean.class.isAssignableFrom(targetClass)) { presentationAttribute.setExplicitFieldType(SupportedFieldType.BOOLEAN); presentationAttribute.setVisibility(VisibilityEnum.VISIBLE_ALL); fields.put(propertyName, metadata.getFieldMetadata("", propertyName, null, SupportedFieldType.BOOLEAN, null, parentClass, presentationAttribute, mergedPropertyType, this)); } else if (Date.class.isAssignableFrom(targetClass)) { presentationAttribute.setExplicitFieldType(SupportedFieldType.DATE); presentationAttribute.setVisibility(VisibilityEnum.VISIBLE_ALL); fields.put(propertyName, metadata.getFieldMetadata("", propertyName, null, SupportedFieldType.DATE, null, parentClass, presentationAttribute, mergedPropertyType, this)); } else if (Money.class.isAssignableFrom(targetClass)) { presentationAttribute.setExplicitFieldType(SupportedFieldType.MONEY); presentationAttribute.setVisibility(VisibilityEnum.VISIBLE_ALL); fields.put(propertyName, metadata.getFieldMetadata("", propertyName, null, SupportedFieldType.MONEY, null, parentClass, presentationAttribute, mergedPropertyType, this)); } else if ( Byte.class.isAssignableFrom(targetClass) || Integer.class.isAssignableFrom(targetClass) || Long.class.isAssignableFrom(targetClass) || Short.class.isAssignableFrom(targetClass) ) { presentationAttribute.setExplicitFieldType(SupportedFieldType.INTEGER); presentationAttribute.setVisibility(VisibilityEnum.VISIBLE_ALL); fields.put(propertyName, metadata.getFieldMetadata("", propertyName, null, SupportedFieldType.INTEGER, null, parentClass, presentationAttribute, mergedPropertyType, this)); } else if ( Double.class.isAssignableFrom(targetClass) || BigDecimal.class.isAssignableFrom(targetClass) ) { presentationAttribute.setExplicitFieldType(SupportedFieldType.DECIMAL); presentationAttribute.setVisibility(VisibilityEnum.VISIBLE_ALL); fields.put(propertyName, metadata.getFieldMetadata("", propertyName, null, SupportedFieldType.DECIMAL, null, parentClass, presentationAttribute, mergedPropertyType, this)); } ((BasicFieldMetadata) fields.get(propertyName)).setLength(255); ((BasicFieldMetadata) fields.get(propertyName)).setForeignKeyCollection(false); ((BasicFieldMetadata) fields.get(propertyName)).setRequired(true); ((BasicFieldMetadata) fields.get(propertyName)).setUnique(true); ((BasicFieldMetadata) fields.get(propertyName)).setScale(100); ((BasicFieldMetadata) fields.get(propertyName)).setPrecision(100); return fields; } @Override public SessionFactory getSessionFactory() { return dynamicDaoHelper.getSessionFactory((HibernateEntityManager) standardEntityManager); } @Override public Map<String, Object> getIdMetadata(Class<?> entityClass) { return dynamicDaoHelper.getIdMetadata(entityClass, (HibernateEntityManager) standardEntityManager); } @Override public List<String> getPropertyNames(Class<?> entityClass) { return dynamicDaoHelper.getPropertyNames(entityClass, (HibernateEntityManager) standardEntityManager); } @Override public List<Type> getPropertyTypes(Class<?> entityClass) { return dynamicDaoHelper.getPropertyTypes(entityClass, (HibernateEntityManager) standardEntityManager); } protected Map<String, FieldMetadata> getPropertiesForEntityClass( Class<?> targetClass, ForeignKey foreignField, String[] additionalNonPersistentProperties, ForeignKey[] additionalForeignFields, MergedPropertyType mergedPropertyType, Boolean populateManyToOneFields, String[] includeFields, String[] excludeFields, String configurationKey, String ceilingEntityFullyQualifiedClassname, List<Class<?>> parentClasses, String prefix, Boolean isParentExcluded ) { Map<String, FieldMetadata> presentationAttributes = metadata.getFieldPresentationAttributes(null, targetClass, this, ""); if (isParentExcluded) { for (String key : presentationAttributes.keySet()) { LOG.debug("getPropertiesForEntityClass:Excluding " + key + " because parent is excluded."); presentationAttributes.get(key).setExcluded(true); } } Map idMetadata = getIdMetadata(targetClass); Map<String, FieldMetadata> fields = new HashMap<String, FieldMetadata>(); String idProperty = (String) idMetadata.get("name"); List<String> propertyNames = getPropertyNames(targetClass); propertyNames.add(idProperty); Type idType = (Type) idMetadata.get("type"); List<Type> propertyTypes = getPropertyTypes(targetClass); propertyTypes.add(idType); PersistentClass persistentClass = getPersistentClass(targetClass.getName()); Iterator testIter = persistentClass.getPropertyIterator(); List<Property> propertyList = new ArrayList<Property>(); //check the properties for problems while(testIter.hasNext()) { Property property = (Property) testIter.next(); if (property.getName().contains(".")) { throw new IllegalArgumentException("Properties from entities that utilize a period character ('.') in their name are incompatible with this system. The property name in question is: (" + property.getName() + ") from the class: (" + targetClass.getName() + ")"); } propertyList.add(property); } buildProperties( targetClass, foreignField, additionalForeignFields, additionalNonPersistentProperties, mergedPropertyType, presentationAttributes, propertyList, fields, propertyNames, propertyTypes, idProperty, populateManyToOneFields, includeFields, excludeFields, configurationKey, ceilingEntityFullyQualifiedClassname, parentClasses, prefix, isParentExcluded, false ); BasicFieldMetadata presentationAttribute = new BasicFieldMetadata(); presentationAttribute.setExplicitFieldType(SupportedFieldType.STRING); presentationAttribute.setVisibility(VisibilityEnum.HIDDEN_ALL); if (!ArrayUtils.isEmpty(additionalNonPersistentProperties)) { Class<?>[] entities = getAllPolymorphicEntitiesFromCeiling(targetClass); for (String additionalNonPersistentProperty : additionalNonPersistentProperties) { if (StringUtils.isEmpty(prefix) || (!StringUtils.isEmpty(prefix) && additionalNonPersistentProperty.startsWith(prefix))) { String myAdditionalNonPersistentProperty = additionalNonPersistentProperty; //get final property if this is a dot delimited property int finalDotPos = additionalNonPersistentProperty.lastIndexOf('.'); if (finalDotPos >= 0) { myAdditionalNonPersistentProperty = myAdditionalNonPersistentProperty.substring(finalDotPos + 1, myAdditionalNonPersistentProperty.length()); } //check all the polymorphic types on this target class to see if the end property exists Field testField = null; Method testMethod = null; for (Class<?> clazz : entities) { try { testMethod = clazz.getMethod(myAdditionalNonPersistentProperty); if (testMethod != null) { break; } } catch (NoSuchMethodException e) { //do nothing - method does not exist } testField = getFieldManager().getField(clazz, myAdditionalNonPersistentProperty); if (testField != null) { break; } } //if the property exists, add it to the metadata for this class if (testField != null || testMethod != null) { fields.put(additionalNonPersistentProperty, metadata.getFieldMetadata(prefix, additionalNonPersistentProperty, propertyList, SupportedFieldType.STRING, null, targetClass, presentationAttribute, mergedPropertyType, this)); } } } } return fields; } protected void buildProperties( Class<?> targetClass, ForeignKey foreignField, ForeignKey[] additionalForeignFields, String[] additionalNonPersistentProperties, MergedPropertyType mergedPropertyType, Map<String, FieldMetadata> presentationAttributes, List<Property> componentProperties, Map<String, FieldMetadata> fields, List<String> propertyNames, List<Type> propertyTypes, String idProperty, Boolean populateManyToOneFields, String[] includeFields, String[] excludeFields, String configurationKey, String ceilingEntityFullyQualifiedClassname, List<Class<?>> parentClasses, String prefix, Boolean isParentExcluded, Boolean isComponentPrefix ) { int j = 0; Comparator<String> propertyComparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { //check for property name equality and for map field properties if (o1.equals(o2) || o1.startsWith(o2 + FieldManager.MAPFIELDSEPARATOR) || o2.startsWith(o1 + FieldManager.MAPFIELDSEPARATOR)) { return 0; } return o1.compareTo(o2); } }; List<String> presentationKeyList = new ArrayList<String>(presentationAttributes.keySet()); Collections.sort(presentationKeyList); for (String propertyName : propertyNames) { final Type type = propertyTypes.get(j); boolean isPropertyForeignKey = testForeignProperty(foreignField, prefix, propertyName); int additionalForeignKeyIndexPosition = findAdditionalForeignKeyIndex(additionalForeignFields, prefix, propertyName); j++; Field myField = getFieldManager().getField(targetClass, propertyName); if (myField == null) { //try to get the field with the prefix - needed for advanced collections that appear in @Embedded classes myField = getFieldManager().getField(targetClass, prefix + propertyName); } if ( !type.isAnyType() && !type.isCollectionType() || isPropertyForeignKey || additionalForeignKeyIndexPosition >= 0 || Collections.binarySearch(presentationKeyList, propertyName, propertyComparator) >= 0 ) { if (myField != null) { boolean handled = false; for (FieldMetadataProvider provider : fieldMetadataProviders) { FieldMetadata presentationAttribute = presentationAttributes.get(propertyName); if (presentationAttribute != null) { setExcludedBasedOnShowIfProperty(presentationAttribute); } FieldProviderResponse response = provider.addMetadataFromFieldType( new AddMetadataFromFieldTypeRequest(myField, targetClass, foreignField, additionalForeignFields, mergedPropertyType, componentProperties, idProperty, prefix, propertyName, type, isPropertyForeignKey, additionalForeignKeyIndexPosition, presentationAttributes, presentationAttribute, null, type.getReturnedClass(), this), fields); if (FieldProviderResponse.NOT_HANDLED != response) { handled = true; } if (FieldProviderResponse.HANDLED_BREAK == response) { break; } } if (!handled) { buildBasicProperty(myField, targetClass, foreignField, additionalForeignFields, additionalNonPersistentProperties, mergedPropertyType, presentationAttributes, componentProperties, fields, idProperty, populateManyToOneFields, includeFields, excludeFields, configurationKey, ceilingEntityFullyQualifiedClassname, parentClasses, prefix, isParentExcluded, propertyName, type, isPropertyForeignKey, additionalForeignKeyIndexPosition, isComponentPrefix); } } } } } public Boolean testPropertyInclusion(FieldMetadata presentationAttribute) { setExcludedBasedOnShowIfProperty(presentationAttribute); return !(presentationAttribute != null && ((presentationAttribute.getExcluded() != null && presentationAttribute.getExcluded()) || (presentationAttribute.getChildrenExcluded() != null && presentationAttribute.getChildrenExcluded()))); } protected boolean setExcludedBasedOnShowIfProperty(FieldMetadata fieldMetadata) { if(fieldMetadata != null && fieldMetadata.getShowIfProperty()!=null && !fieldMetadata.getShowIfProperty().equals("") && appConfigurationRemoteService.getBooleanPropertyValue(fieldMetadata.getShowIfProperty())!=null && !appConfigurationRemoteService.getBooleanPropertyValue(fieldMetadata.getShowIfProperty()) ) { //do not include this in the display if it returns false. fieldMetadata.setExcluded(true); return false; } return true; } protected Boolean testPropertyRecursion(String prefix, List<Class<?>> parentClasses, String propertyName, Class<?> targetClass, String ceilingEntityFullyQualifiedClassname, Boolean isComponentPrefix) { Boolean includeField = true; //don't want to shun a self-referencing property in an @Embeddable boolean shouldTest = !StringUtils.isEmpty(prefix) && (!isComponentPrefix || prefix.split("\\.").length > 1); if (shouldTest) { Field testField = getFieldManager().getField(targetClass, propertyName); if (testField == null) { Class<?>[] entities; try { entities = getAllPolymorphicEntitiesFromCeiling(Class.forName(ceilingEntityFullyQualifiedClassname)); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } for (Class<?> clazz : entities) { testField = getFieldManager().getField(clazz, propertyName); if (testField != null) { break; } } String testProperty = prefix + propertyName; if (testField == null) { testField = getFieldManager().getField(targetClass, testProperty); } if (testField == null) { for (Class<?> clazz : entities) { testField = getFieldManager().getField(clazz, testProperty); if (testField != null) { break; } } } } if (testField != null) { Class<?> testType = testField.getType(); for (Class<?> parentClass : parentClasses) { if (parentClass.isAssignableFrom(testType) || testType.isAssignableFrom(parentClass)) { includeField = false; break; } } if (includeField && (targetClass.isAssignableFrom(testType) || testType.isAssignableFrom(targetClass))) { includeField = false; } } } return includeField; } protected void buildBasicProperty( Field field, Class<?> targetClass, ForeignKey foreignField, ForeignKey[] additionalForeignFields, String[] additionalNonPersistentProperties, MergedPropertyType mergedPropertyType, Map<String, FieldMetadata> presentationAttributes, List<Property> componentProperties, Map<String, FieldMetadata> fields, String idProperty, Boolean populateManyToOneFields, String[] includeFields, String[] excludeFields, String configurationKey, String ceilingEntityFullyQualifiedClassname, List<Class<?>> parentClasses, String prefix, Boolean isParentExcluded, String propertyName, Type type, boolean propertyForeignKey, int additionalForeignKeyIndexPosition, Boolean isComponentPrefix) { FieldMetadata presentationAttribute = presentationAttributes.get(propertyName); Boolean amIExcluded = isParentExcluded || !testPropertyInclusion(presentationAttribute); Boolean includeField = testPropertyRecursion(prefix, parentClasses, propertyName, targetClass, ceilingEntityFullyQualifiedClassname, isComponentPrefix); SupportedFieldType explicitType = null; if (presentationAttribute != null && presentationAttribute instanceof BasicFieldMetadata) { explicitType = ((BasicFieldMetadata) presentationAttribute).getExplicitFieldType(); } Class<?> returnedClass = type.getReturnedClass(); checkProp: { if (type.isComponentType() && includeField) { buildComponentProperties( targetClass, foreignField, additionalForeignFields, additionalNonPersistentProperties, mergedPropertyType, fields, idProperty, populateManyToOneFields, includeFields, excludeFields, configurationKey, ceilingEntityFullyQualifiedClassname, propertyName, type, returnedClass, parentClasses, amIExcluded, prefix ); break checkProp; } /* * Currently we do not support ManyToOne fields whose class type is the same * as the target type, since this forms an infinite loop and will cause a stack overflow. */ if ( type.isEntityType() && !returnedClass.isAssignableFrom(targetClass) && populateManyToOneFields && includeField ) { buildEntityProperties( fields, foreignField, additionalForeignFields, additionalNonPersistentProperties, populateManyToOneFields, includeFields, excludeFields, configurationKey, ceilingEntityFullyQualifiedClassname, propertyName, returnedClass, targetClass, parentClasses, prefix, amIExcluded ); break checkProp; } } //Don't include this property if it failed manyToOne inclusion and is not a specified foreign key if (includeField || propertyForeignKey || additionalForeignKeyIndexPosition >= 0) { defaultFieldMetadataProvider.addMetadataFromFieldType( new AddMetadataFromFieldTypeRequest(field, targetClass, foreignField, additionalForeignFields, mergedPropertyType, componentProperties, idProperty, prefix, propertyName, type, propertyForeignKey, additionalForeignKeyIndexPosition, presentationAttributes, presentationAttribute, explicitType, returnedClass, this), fields); } } protected boolean testForeignProperty(ForeignKey foreignField, String prefix, String propertyName) { boolean isPropertyForeignKey = false; if (foreignField != null) { isPropertyForeignKey = foreignField.getManyToField().equals(prefix + propertyName); } return isPropertyForeignKey; } protected int findAdditionalForeignKeyIndex(ForeignKey[] additionalForeignFields, String prefix, String propertyName) { int additionalForeignKeyIndexPosition = -1; if (additionalForeignFields != null) { additionalForeignKeyIndexPosition = Arrays.binarySearch(additionalForeignFields, new ForeignKey(prefix + propertyName, null, null), new Comparator<ForeignKey>() { @Override public int compare(ForeignKey o1, ForeignKey o2) { return o1.getManyToField().compareTo(o2.getManyToField()); } }); } return additionalForeignKeyIndexPosition; } protected void buildEntityProperties( Map<String, FieldMetadata> fields, ForeignKey foreignField, ForeignKey[] additionalForeignFields, String[] additionalNonPersistentProperties, Boolean populateManyToOneFields, String[] includeFields, String[] excludeFields, String configurationKey, String ceilingEntityFullyQualifiedClassname, String propertyName, Class<?> returnedClass, Class<?> targetClass, List<Class<?>> parentClasses, String prefix, Boolean isParentExcluded ) { Class<?>[] polymorphicEntities = getAllPolymorphicEntitiesFromCeiling(returnedClass); List<Class<?>> clonedParentClasses = new ArrayList<Class<?>>(); for (Class<?> parentClass : parentClasses) { clonedParentClasses.add(parentClass); } clonedParentClasses.add(targetClass); Map<String, FieldMetadata> newFields = getMergedPropertiesRecursively( ceilingEntityFullyQualifiedClassname, polymorphicEntities, foreignField, additionalNonPersistentProperties, additionalForeignFields, MergedPropertyType.PRIMARY, populateManyToOneFields, includeFields, excludeFields, configurationKey, clonedParentClasses, prefix + propertyName + '.', isParentExcluded ); for (FieldMetadata newMetadata : newFields.values()) { newMetadata.setInheritedFromType(targetClass.getName()); newMetadata.setAvailableToTypes(new String[]{targetClass.getName()}); } Map<String, FieldMetadata> convertedFields = new HashMap<String, FieldMetadata>(newFields.size()); for (Map.Entry<String, FieldMetadata> key : newFields.entrySet()) { convertedFields.put(propertyName + '.' + key.getKey(), key.getValue()); if (key.getValue() instanceof BasicFieldMetadata) { for (Map.Entry<String, Map<String, String>> entry : ((BasicFieldMetadata) key.getValue()).getValidationConfigurations().entrySet()) { Class<?> validatorImpl = null; try { validatorImpl = Class.forName(entry.getKey()); } catch (ClassNotFoundException e) { Object bean = applicationContext.getBean(entry.getKey()); if (bean != null) { validatorImpl = bean.getClass(); } } if (validatorImpl != null && FieldNamePropertyValidator.class.isAssignableFrom(validatorImpl)) { for (Map.Entry<String, String> configs : entry.getValue().entrySet()) { if (newFields.containsKey(configs.getValue())) { configs.setValue(propertyName + "." + configs.getValue()); } } } } } } fields.putAll(convertedFields); } protected void buildComponentProperties( Class<?> targetClass, ForeignKey foreignField, ForeignKey[] additionalForeignFields, String[] additionalNonPersistentProperties, MergedPropertyType mergedPropertyType, Map<String, FieldMetadata> fields, String idProperty, Boolean populateManyToOneFields, String[] includeFields, String[] excludeFields, String configurationKey, String ceilingEntityFullyQualifiedClassname, String propertyName, Type type, Class<?> returnedClass, List<Class<?>> parentClasses, Boolean isParentExcluded, String prefix ) { String[] componentProperties = ((ComponentType) type).getPropertyNames(); List<String> componentPropertyNames = Arrays.asList(componentProperties); Type[] componentTypes = ((ComponentType) type).getSubtypes(); List<Type> componentPropertyTypes = Arrays.asList(componentTypes); String tempPrefix = ""; int pos = prefix.indexOf("."); if (pos > 0 && pos < prefix.length()-1) { //only use part of the prefix if it's more than one layer deep tempPrefix = prefix.substring(pos + 1, prefix.length()); } Map<String, FieldMetadata> componentPresentationAttributes = metadata.getFieldPresentationAttributes(targetClass, returnedClass, this, tempPrefix + propertyName + "."); if (isParentExcluded) { for (String key : componentPresentationAttributes.keySet()) { LOG.debug("buildComponentProperties:Excluding " + key + " because the parent was excluded"); componentPresentationAttributes.get(key).setExcluded(true); } } PersistentClass persistentClass = getPersistentClass(targetClass.getName()); Property property; try { property = persistentClass.getProperty(propertyName); } catch (MappingException e) { property = persistentClass.getProperty(prefix + propertyName); } Iterator componentPropertyIterator = ((org.hibernate.mapping.Component) property.getValue()).getPropertyIterator(); List<Property> componentPropertyList = new ArrayList<Property>(); while(componentPropertyIterator.hasNext()) { componentPropertyList.add((Property) componentPropertyIterator.next()); } Map<String, FieldMetadata> newFields = new HashMap<String, FieldMetadata>(); buildProperties( targetClass, foreignField, additionalForeignFields, additionalNonPersistentProperties, mergedPropertyType, componentPresentationAttributes, componentPropertyList, newFields, componentPropertyNames, componentPropertyTypes, idProperty, populateManyToOneFields, includeFields, excludeFields, configurationKey, ceilingEntityFullyQualifiedClassname, parentClasses, propertyName + ".", isParentExcluded, true ); Map<String, FieldMetadata> convertedFields = new HashMap<String, FieldMetadata>(); for (String key : newFields.keySet()) { convertedFields.put(propertyName + "." + key, newFields.get(key)); } fields.putAll(convertedFields); } @Override public EntityManager getStandardEntityManager() { return standardEntityManager; } @Override public void setStandardEntityManager(EntityManager entityManager) { this.standardEntityManager = entityManager; } @Override public EJB3ConfigurationDao getEjb3ConfigurationDao() { return ejb3ConfigurationDao; } public void setEjb3ConfigurationDao(EJB3ConfigurationDao ejb3ConfigurationDao) { this.ejb3ConfigurationDao = ejb3ConfigurationDao; } @Override public FieldManager getFieldManager() { return new FieldManager(entityConfiguration, getStandardEntityManager()); } @Override public EntityConfiguration getEntityConfiguration() { return entityConfiguration; } @Override public void setEntityConfiguration(EntityConfiguration entityConfiguration) { this.entityConfiguration = entityConfiguration; } @Override public Metadata getMetadata() { return metadata; } @Override public void setMetadata(Metadata metadata) { this.metadata = metadata; } public List<FieldMetadataProvider> getFieldMetadataProviders() { return fieldMetadataProviders; } public void setFieldMetadataProviders(List<FieldMetadataProvider> fieldMetadataProviders) { this.fieldMetadataProviders = fieldMetadataProviders; } @Override public FieldMetadataProvider getDefaultFieldMetadataProvider() { return defaultFieldMetadataProvider; } public void setDefaultFieldMetadataProvider(FieldMetadataProvider defaultFieldMetadataProvider) { this.defaultFieldMetadataProvider = defaultFieldMetadataProvider; } protected boolean isExcludeClassFromPolymorphism(Class<?> clazz) { return dynamicDaoHelper.isExcludeClassFromPolymorphism(clazz); } @Override public DynamicDaoHelper getDynamicDaoHelper() { return dynamicDaoHelper; } public void setDynamicDaoHelper(DynamicDaoHelper dynamicDaoHelper) { this.dynamicDaoHelper = dynamicDaoHelper; } }
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2019 Guardsquare NV * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.classfile; /** * Constants used in representing a Java class file (*.class). * * @author Eric Lafortune */ public class ClassConstants { public static final String WAR_CLASS_FILE_PREFIX = "classes/"; public static final byte[] JMOD_HEADER = new byte[] { 'J', 'M', 1, 0 }; public static final String JMOD_CLASS_FILE_PREFIX = "classes/"; public static final String CLASS_FILE_EXTENSION = ".class"; public static final int MAGIC = 0xCAFEBABE; public static final int CLASS_VERSION_1_0_MAJOR = 45; public static final int CLASS_VERSION_1_0_MINOR = 3; public static final int CLASS_VERSION_1_2_MAJOR = 46; public static final int CLASS_VERSION_1_2_MINOR = 0; public static final int CLASS_VERSION_1_3_MAJOR = 47; public static final int CLASS_VERSION_1_3_MINOR = 0; public static final int CLASS_VERSION_1_4_MAJOR = 48; public static final int CLASS_VERSION_1_4_MINOR = 0; public static final int CLASS_VERSION_1_5_MAJOR = 49; public static final int CLASS_VERSION_1_5_MINOR = 0; public static final int CLASS_VERSION_1_6_MAJOR = 50; public static final int CLASS_VERSION_1_6_MINOR = 0; public static final int CLASS_VERSION_1_7_MAJOR = 51; public static final int CLASS_VERSION_1_7_MINOR = 0; public static final int CLASS_VERSION_1_8_MAJOR = 52; public static final int CLASS_VERSION_1_8_MINOR = 0; public static final int CLASS_VERSION_1_9_MAJOR = 53; public static final int CLASS_VERSION_1_9_MINOR = 0; public static final int CLASS_VERSION_10_MAJOR = 54; public static final int CLASS_VERSION_10_MINOR = 0; public static final int CLASS_VERSION_11_MAJOR = 55; public static final int CLASS_VERSION_11_MINOR = 0; public static final int CLASS_VERSION_12_MAJOR = 56; public static final int CLASS_VERSION_12_MINOR = 0; public static final int CLASS_VERSION_13_MAJOR = 57; public static final int CLASS_VERSION_13_MINOR = 0; public static final int CLASS_VERSION_1_0 = (CLASS_VERSION_1_0_MAJOR << 16) | CLASS_VERSION_1_0_MINOR; public static final int CLASS_VERSION_1_2 = (CLASS_VERSION_1_2_MAJOR << 16) | CLASS_VERSION_1_2_MINOR; public static final int CLASS_VERSION_1_3 = (CLASS_VERSION_1_3_MAJOR << 16) | CLASS_VERSION_1_3_MINOR; public static final int CLASS_VERSION_1_4 = (CLASS_VERSION_1_4_MAJOR << 16) | CLASS_VERSION_1_4_MINOR; public static final int CLASS_VERSION_1_5 = (CLASS_VERSION_1_5_MAJOR << 16) | CLASS_VERSION_1_5_MINOR; public static final int CLASS_VERSION_1_6 = (CLASS_VERSION_1_6_MAJOR << 16) | CLASS_VERSION_1_6_MINOR; public static final int CLASS_VERSION_1_7 = (CLASS_VERSION_1_7_MAJOR << 16) | CLASS_VERSION_1_7_MINOR; public static final int CLASS_VERSION_1_8 = (CLASS_VERSION_1_8_MAJOR << 16) | CLASS_VERSION_1_8_MINOR; public static final int CLASS_VERSION_1_9 = (CLASS_VERSION_1_9_MAJOR << 16) | CLASS_VERSION_1_9_MINOR; public static final int CLASS_VERSION_10 = (CLASS_VERSION_10_MAJOR << 16) | CLASS_VERSION_10_MINOR; public static final int CLASS_VERSION_11 = (CLASS_VERSION_11_MAJOR << 16) | CLASS_VERSION_11_MINOR; public static final int CLASS_VERSION_12 = (CLASS_VERSION_12_MAJOR << 16) | CLASS_VERSION_12_MINOR; public static final int CLASS_VERSION_13 = (CLASS_VERSION_13_MAJOR << 16) | CLASS_VERSION_13_MINOR; public static final int ACC_PUBLIC = 0x0001; public static final int ACC_PRIVATE = 0x0002; public static final int ACC_PROTECTED = 0x0004; public static final int ACC_STATIC = 0x0008; public static final int ACC_FINAL = 0x0010; public static final int ACC_SUPER = 0x0020; public static final int ACC_SYNCHRONIZED = 0x0020; public static final int ACC_VOLATILE = 0x0040; public static final int ACC_TRANSIENT = 0x0080; public static final int ACC_BRIDGE = 0x0040; public static final int ACC_VARARGS = 0x0080; public static final int ACC_NATIVE = 0x0100; public static final int ACC_INTERFACE = 0x0200; public static final int ACC_ABSTRACT = 0x0400; public static final int ACC_STRICT = 0x0800; public static final int ACC_SYNTHETIC = 0x1000; public static final int ACC_ANNOTATION = 0x2000; public static final int ACC_ENUM = 0x4000; public static final int ACC_MANDATED = 0x8000; public static final int ACC_MODULE = 0x8000; public static final int ACC_OPEN = 0x0020; public static final int ACC_TRANSITIVE = 0x0020; public static final int ACC_STATIC_PHASE = 0x0040; // Custom flags introduced by ProGuard public static final int ACC_RENAMED = 0x00010000; // Marks whether a class or class member has been renamed. public static final int ACC_REMOVED_METHODS = 0x00020000; // Marks whether a class has (at least one) methods removed. public static final int ACC_REMOVED_FIELDS = 0x00040000; // Marks whether a class has (at least one) fields removed. public static final int VALID_ACC_CLASS = ACC_PUBLIC | ACC_FINAL | ACC_SUPER | ACC_INTERFACE | ACC_ABSTRACT | ACC_SYNTHETIC | ACC_ANNOTATION | ACC_MODULE | ACC_ENUM; public static final int VALID_ACC_FIELD = ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL | ACC_VOLATILE | ACC_TRANSIENT | ACC_SYNTHETIC | ACC_ENUM; public static final int VALID_ACC_METHOD = ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL | ACC_SYNCHRONIZED | ACC_BRIDGE | ACC_VARARGS | ACC_NATIVE | ACC_ABSTRACT | ACC_STRICT | ACC_SYNTHETIC; public static final int VALID_ACC_PARAMETER = ACC_FINAL | ACC_SYNTHETIC | ACC_MANDATED; public static final int VALID_ACC_MODULE = ACC_OPEN | ACC_SYNTHETIC | ACC_MANDATED; public static final int VALID_ACC_REQUIRES = ACC_TRANSITIVE | ACC_STATIC_PHASE | ACC_SYNTHETIC | ACC_MANDATED; public static final int VALID_ACC_EXPORTS = ACC_SYNTHETIC | ACC_MANDATED; public static final int VALID_ACC_OPENS = ACC_SYNTHETIC | ACC_MANDATED; public static final int CONSTANT_Utf8 = 1; public static final int CONSTANT_Integer = 3; public static final int CONSTANT_Float = 4; public static final int CONSTANT_Long = 5; public static final int CONSTANT_Double = 6; public static final int CONSTANT_Class = 7; public static final int CONSTANT_String = 8; public static final int CONSTANT_Fieldref = 9; public static final int CONSTANT_Methodref = 10; public static final int CONSTANT_InterfaceMethodref = 11; public static final int CONSTANT_NameAndType = 12; public static final int CONSTANT_MethodHandle = 15; public static final int CONSTANT_MethodType = 16; public static final int CONSTANT_Dynamic = 17; public static final int CONSTANT_InvokeDynamic = 18; public static final int CONSTANT_Module = 19; public static final int CONSTANT_Package = 20; public static final int CONSTANT_PrimitiveArray = 21; public static final int REF_getField = 1; public static final int REF_getStatic = 2; public static final int REF_putField = 3; public static final int REF_putStatic = 4; public static final int REF_invokeVirtual = 5; public static final int REF_invokeStatic = 6; public static final int REF_invokeSpecial = 7; public static final int REF_newInvokeSpecial = 8; public static final int REF_invokeInterface = 9; public static final int FLAG_BRIDGES = 4; public static final int FLAG_MARKERS = 2; public static final int FLAG_SERIALIZABLE = 1; public static final String ATTR_BootstrapMethods = "BootstrapMethods"; public static final String ATTR_SourceFile = "SourceFile"; public static final String ATTR_SourceDir = "SourceDir"; public static final String ATTR_InnerClasses = "InnerClasses"; public static final String ATTR_EnclosingMethod = "EnclosingMethod"; public static final String ATTR_NestHost = "NestHost"; public static final String ATTR_NestMembers = "NestMembers"; public static final String ATTR_Deprecated = "Deprecated"; public static final String ATTR_Synthetic = "Synthetic"; public static final String ATTR_Signature = "Signature"; public static final String ATTR_ConstantValue = "ConstantValue"; public static final String ATTR_MethodParameters = "MethodParameters"; public static final String ATTR_Exceptions = "Exceptions"; public static final String ATTR_Code = "Code"; public static final String ATTR_StackMap = "StackMap"; public static final String ATTR_StackMapTable = "StackMapTable"; public static final String ATTR_LineNumberTable = "LineNumberTable"; public static final String ATTR_LocalVariableTable = "LocalVariableTable"; public static final String ATTR_LocalVariableTypeTable = "LocalVariableTypeTable"; public static final String ATTR_RuntimeVisibleAnnotations = "RuntimeVisibleAnnotations"; public static final String ATTR_RuntimeInvisibleAnnotations = "RuntimeInvisibleAnnotations"; public static final String ATTR_RuntimeVisibleParameterAnnotations = "RuntimeVisibleParameterAnnotations"; public static final String ATTR_RuntimeInvisibleParameterAnnotations = "RuntimeInvisibleParameterAnnotations"; public static final String ATTR_RuntimeVisibleTypeAnnotations = "RuntimeVisibleTypeAnnotations"; public static final String ATTR_RuntimeInvisibleTypeAnnotations = "RuntimeInvisibleTypeAnnotations"; public static final String ATTR_AnnotationDefault = "AnnotationDefault"; public static final String ATTR_Module = "Module"; public static final String ATTR_ModuleMainClass = "ModuleMainClass"; public static final String ATTR_ModulePackages = "ModulePackages"; // TODO: More attributes. public static final String ATTR_CharacterRangeTable = "CharacterRangeTable"; public static final String ATTR_CompilationID = "CompilationID"; public static final String ATTR_SourceID = "SourceID"; public static final int ANNOTATION_TARGET_ParameterGenericClass = 0x00; public static final int ANNOTATION_TARGET_ParameterGenericMethod = 0x01; public static final int ANNOTATION_TARGET_Extends = 0x10; public static final int ANNOTATION_TARGET_BoundGenericClass = 0x11; public static final int ANNOTATION_TARGET_BoundGenericMethod = 0x12; public static final int ANNOTATION_TARGET_Field = 0x13; public static final int ANNOTATION_TARGET_Return = 0x14; public static final int ANNOTATION_TARGET_Receiver = 0x15; public static final int ANNOTATION_TARGET_Parameter = 0x16; public static final int ANNOTATION_TARGET_Throws = 0x17; public static final int ANNOTATION_TARGET_LocalVariable = 0x40; public static final int ANNOTATION_TARGET_ResourceVariable = 0x41; public static final int ANNOTATION_TARGET_Catch = 0x42; public static final int ANNOTATION_TARGET_InstanceOf = 0x43; public static final int ANNOTATION_TARGET_New = 0x44; public static final int ANNOTATION_TARGET_MethodReferenceNew = 0x45; public static final int ANNOTATION_TARGET_MethodReference = 0x46; public static final int ANNOTATION_TARGET_Cast = 0x47; public static final int ANNOTATION_TARGET_ArgumentGenericMethodNew = 0x48; public static final int ANNOTATION_TARGET_ArgumentGenericMethod = 0x49; public static final int ANNOTATION_TARGET_ArgumentGenericMethodReferenceNew = 0x4a; public static final int ANNOTATION_TARGET_ArgumentGenericMethodReference = 0x4b; public static final int RESOLUTION_FLAG_DO_NOT_RESOLVE_BY_DEFAULT = 0x0001; public static final int RESOLUTION_FLAG_WARN_DEPRECATED = 0x0002; public static final int RESOLUTION_FLAG_WARN_DEPRECATED_FOR_REMOVAL = 0x0004; public static final int RESOLUTION_FLAG_WARN_INCUBATING = 0x0008; public static final char ELEMENT_VALUE_STRING_CONSTANT = 's'; public static final char ELEMENT_VALUE_ENUM_CONSTANT = 'e'; public static final char ELEMENT_VALUE_CLASS = 'c'; public static final char ELEMENT_VALUE_ANNOTATION = '@'; public static final char ELEMENT_VALUE_ARRAY = '['; public static final char PACKAGE_SEPARATOR = '/'; public static final char INNER_CLASS_SEPARATOR = '$'; public static final char SPECIAL_CLASS_CHARACTER = '-'; public static final char SPECIAL_MEMBER_SEPARATOR = '$'; public static final char METHOD_ARGUMENTS_OPEN = '('; public static final char METHOD_ARGUMENTS_CLOSE = ')'; public static final String PACKAGE_JAVA_LANG = "java/lang/"; public static final String NAME_JAVA_LANG_OBJECT = "java/lang/Object"; public static final String TYPE_JAVA_LANG_OBJECT = "Ljava/lang/Object;"; public static final String NAME_JAVA_LANG_CLONEABLE = "java/lang/Cloneable"; public static final String NAME_JAVA_LANG_THROWABLE = "java/lang/Throwable"; public static final String NAME_JAVA_LANG_EXCEPTION = "java/lang/Exception"; public static final String NAME_JAVA_LANG_NUMBER_FORMAT_EXCEPTION = "java/lang/NumberFormatException"; public static final String NAME_JAVA_LANG_CLASS = "java/lang/Class"; public static final String TYPE_JAVA_LANG_CLASS = "Ljava/lang/Class;"; public static final String NAME_JAVA_LANG_CLASS_LOADER = "java/lang/ClassLoader"; public static final String NAME_JAVA_LANG_STRING = "java/lang/String"; public static final String TYPE_JAVA_LANG_STRING = "Ljava/lang/String;"; public static final String NAME_JAVA_LANG_STRING_BUFFER = "java/lang/StringBuffer"; public static final String NAME_JAVA_LANG_STRING_BUILDER = "java/lang/StringBuilder"; public static final String NAME_JAVA_LANG_INVOKE_METHOD_HANDLE = "java/lang/invoke/MethodHandle"; public static final String NAME_JAVA_LANG_INVOKE_METHOD_TYPE = "java/lang/invoke/MethodType"; public static final String NAME_JAVA_LANG_INVOKE_STRING_CONCAT_FACTORY = "java/lang/invoke/StringConcatFactory"; public static final String NAME_JAVA_LANG_VOID = "java/lang/Void"; public static final String NAME_JAVA_LANG_BOOLEAN = "java/lang/Boolean"; public static final String TYPE_JAVA_LANG_BOOLEAN = "Ljava/lang/Boolean;"; public static final String NAME_JAVA_LANG_BYTE = "java/lang/Byte"; public static final String NAME_JAVA_LANG_SHORT = "java/lang/Short"; public static final String NAME_JAVA_LANG_CHARACTER = "java/lang/Character"; public static final String NAME_JAVA_LANG_INTEGER = "java/lang/Integer"; public static final String NAME_JAVA_LANG_LONG = "java/lang/Long"; public static final String NAME_JAVA_LANG_FLOAT = "java/lang/Float"; public static final String NAME_JAVA_LANG_DOUBLE = "java/lang/Double"; public static final String NAME_JAVA_LANG_MATH = "java/lang/Math"; public static final String NAME_JAVA_LANG_SYSTEM = "java/lang/System"; public static final String NAME_JAVA_LANG_RUNTIME = "java/lang/Runtime"; public static final String NAME_JAVA_LANG_REFLECT_ARRAY = "java/lang/reflect/Array"; public static final String NAME_JAVA_LANG_REFLECT_FIELD = "java/lang/reflect/Field"; public static final String NAME_JAVA_LANG_REFLECT_METHOD = "java/lang/reflect/Method"; public static final String NAME_JAVA_LANG_REFLECT_CONSTRUCTOR = "java/lang/reflect/Constructor"; public static final String NAME_JAVA_LANG_REFLECT_ACCESSIBLE_OBJECT = "java/lang/reflect/AccessibleObject"; public static final String NAME_JAVA_IO_SERIALIZABLE = "java/io/Serializable"; public static final String NAME_JAVA_IO_BYTE_ARRAY_INPUT_STREAM = "java/io/ByteArrayInputStream"; public static final String NAME_JAVA_IO_DATA_INPUT_STREAM = "java/io/DataInputStream"; public static final String NAME_JAVA_IO_INPUT_STREAM = "java/io/InputStream"; public static final String NAME_JAVA_UTIL_MAP = "java/util/Map"; public static final String TYPE_JAVA_UTIL_MAP = "Ljava/util/Map;"; public static final String NAME_JAVA_UTIL_HASH_MAP = "java/util/HashMap"; public static final String NAME_JAVA_UTIL_LIST = "java/util/List"; public static final String TYPE_JAVA_UTIL_LIST = "Ljava/util/List;"; public static final String NAME_JAVA_UTIL_ARRAY_LIST = "java/util/ArrayList"; public static final String NAME_ANDROID_UTIL_FLOAT_MATH = "android/util/FloatMath"; public static final String NAME_JAVA_UTIL_CONCURRENT_ATOMIC_ATOMIC_INTEGER_FIELD_UPDATER = "java/util/concurrent/atomic/AtomicIntegerFieldUpdater"; public static final String NAME_JAVA_UTIL_CONCURRENT_ATOMIC_ATOMIC_LONG_FIELD_UPDATER = "java/util/concurrent/atomic/AtomicLongFieldUpdater"; public static final String NAME_JAVA_UTIL_CONCURRENT_ATOMIC_ATOMIC_REFERENCE_FIELD_UPDATER = "java/util/concurrent/atomic/AtomicReferenceFieldUpdater"; public static final String METHOD_NAME_INIT = "<init>"; public static final String METHOD_TYPE_INIT = "()V"; public static final String METHOD_NAME_CLINIT = "<clinit>"; public static final String METHOD_TYPE_CLINIT = "()V"; public static final String METHOD_NAME_OBJECT_GET_CLASS = "getClass"; public static final String METHOD_TYPE_OBJECT_GET_CLASS = "()Ljava/lang/Class;"; public static final String METHOD_NAME_CLASS_FOR_NAME = "forName"; public static final String METHOD_TYPE_CLASS_FOR_NAME = "(Ljava/lang/String;)Ljava/lang/Class;"; public static final String METHOD_NAME_CLASS_IS_INSTANCE = "isInstance"; public static final String METHOD_TYPE_CLASS_IS_INSTANCE = "(Ljava/lang/Object;)Z"; public static final String METHOD_NAME_CLASS_GET_CLASS_LOADER = "getClassLoader"; public static final String METHOD_NAME_CLASS_GET_COMPONENT_TYPE = "getComponentType"; public static final String METHOD_TYPE_CLASS_GET_COMPONENT_TYPE = "()Ljava/lang/Class;"; public static final String METHOD_NAME_CLASS_GET_FIELD = "getField"; public static final String METHOD_TYPE_CLASS_GET_FIELD = "(Ljava/lang/String;)Ljava/lang/reflect/Field;"; public static final String METHOD_NAME_CLASS_GET_DECLARED_FIELD = "getDeclaredField"; public static final String METHOD_TYPE_CLASS_GET_DECLARED_FIELD = "(Ljava/lang/String;)Ljava/lang/reflect/Field;"; public static final String METHOD_NAME_CLASS_GET_FIELDS = "getFields"; public static final String METHOD_TYPE_CLASS_GET_FIELDS = "()[Ljava/lang/reflect/Field;"; public static final String METHOD_NAME_CLASS_GET_DECLARED_FIELDS = "getDeclaredFields"; public static final String METHOD_TYPE_CLASS_GET_DECLARED_FIELDS = "()[Ljava/lang/reflect/Field;"; public static final String METHOD_NAME_CLASS_GET_CONSTRUCTOR = "getConstructor"; public static final String METHOD_TYPE_CLASS_GET_CONSTRUCTOR = "([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;"; public static final String METHOD_NAME_CLASS_GET_DECLARED_CONSTRUCTOR = "getDeclaredConstructor"; public static final String METHOD_TYPE_CLASS_GET_DECLARED_CONSTRUCTOR = "([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;"; public static final String METHOD_NAME_CLASS_GET_CONSTRUCTORS = "getConstructors"; public static final String METHOD_TYPE_CLASS_GET_CONSTRUCTORS = "()[Ljava/lang/reflect/Constructor;"; public static final String METHOD_NAME_CLASS_GET_DECLARED_CONSTRUCTORS = "getDeclaredConstructors"; public static final String METHOD_TYPE_CLASS_GET_DECLARED_CONSTRUCTORS = "()[Ljava/lang/reflect/Constructor;"; public static final String METHOD_NAME_CLASS_GET_METHOD = "getMethod"; public static final String METHOD_TYPE_CLASS_GET_METHOD = "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;"; public static final String METHOD_NAME_CLASS_GET_DECLARED_METHOD = "getDeclaredMethod"; public static final String METHOD_TYPE_CLASS_GET_DECLARED_METHOD = "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;"; public static final String METHOD_NAME_CLASS_GET_METHODS = "getMethods"; public static final String METHOD_TYPE_CLASS_GET_METHODS = "()[Ljava/lang/reflect/Method;"; public static final String METHOD_NAME_CLASS_GET_DECLARED_METHODS = "getDeclaredMethods"; public static final String METHOD_TYPE_CLASS_GET_DECLARED_METHODS = "()[Ljava/lang/reflect/Method;"; public static final String METHOD_NAME_FIND_CLASS = "findClass"; public static final String METHOD_TYPE_FIND_CLASS = "(Ljava/lang/String;)Ljava/lang/Class;"; public static final String METHOD_NAME_LOAD_CLASS = "loadClass"; public static final String METHOD_TYPE_LOAD_CLASS = "(Ljava/lang/String;Z)Ljava/lang/Class;"; public static final String METHOD_NAME_FIND_LIBRARY = "findLibrary"; public static final String METHOD_TYPE_FIND_LIBRARY = "(Ljava/lang/String;)Ljava/lang/String;"; public static final String METHOD_NAME_LOAD_LIBRARY = "loadLibrary"; public static final String METHOD_TYPE_LOAD_LIBRARY = "(Ljava/lang/String;)V"; public static final String METHOD_NAME_LOAD = "load"; public static final String METHOD_NAME_DO_LOAD = "doLoad"; public static final String METHOD_TYPE_LOAD = "(Ljava/lang/String;)V"; public static final String METHOD_TYPE_LOAD2 = "(Ljava/lang/String;Ljava/lang/ClassLoader;)V"; public static final String METHOD_NAME_NATIVE_LOAD = "nativeLoad"; public static final String METHOD_TYPE_NATIVE_LOAD = "(Ljava/lang/String;Ljava/lang/ClassLoader;Ljava/lang/String;)Ljava/lang/String;"; public static final String METHOD_NAME_MAP_LIBRARY_NAME = "mapLibraryName"; public static final String METHOD_TYPE_MAP_LIBRARY_NAME = "(Ljava/lang/String;)Ljava/lang/String;"; public static final String METHOD_NAME_GET_RUNTIME = "getRuntime"; public static final String METHOD_TYPE_GET_RUNTIME = "()Ljava/lang/Runtime;"; public static final String METHOD_NAME_CLASS_GET_DECLARING_CLASS = "getDeclaringClass"; public static final String METHOD_NAME_CLASS_GET_ENCLOSING_CLASS = "getEnclosingClass"; public static final String METHOD_NAME_CLASS_GET_ENCLOSING_CONSTRUCTOR = "getEnclosingConstructor"; public static final String METHOD_NAME_CLASS_GET_ENCLOSING_METHOD = "getEnclosingMethod"; public static final String METHOD_NAME_GET_ANNOTATION = "getAnnotation"; public static final String METHOD_NAME_GET_ANNOTATIONS = "getAnnotations"; public static final String METHOD_NAME_GET_DECLARED_ANNOTATIONS = "getDeclaredAnnotations"; public static final String METHOD_NAME_GET_PARAMETER_ANNOTATIONS = "getParameterAnnotations"; public static final String METHOD_NAME_GET_TYPE_PREFIX = "getType"; public static final String METHOD_NAME_GET_GENERIC_PREFIX = "getGeneric"; public static final String METHOD_NAME_NEW_UPDATER = "newUpdater"; public static final String METHOD_TYPE_NEW_INTEGER_UPDATER = "(Ljava/lang/Class;Ljava/lang/String;)Ljava/util/concurrent/atomic/AtomicIntegerFieldUpdater;"; public static final String METHOD_TYPE_NEW_LONG_UPDATER = "(Ljava/lang/Class;Ljava/lang/String;)Ljava/util/concurrent/atomic/AtomicLongFieldUpdater;"; public static final String METHOD_TYPE_NEW_REFERENCE_UPDATER = "(Ljava/lang/Class;Ljava/lang/Class;Ljava/lang/String;)Ljava/util/concurrent/atomic/AtomicReferenceFieldUpdater;"; public static final String METHOD_NAME_FIELD_GET = "get"; public static final String METHOD_TYPE_FIELD_GET = "(Ljava/lang/Object;)Ljava/lang/Object;"; public static final String METHOD_NAME_FIELD_SET = "set"; public static final String METHOD_TYPE_FIELD_SET = "(Ljava/lang/Object;Ljava/lang/Object;)V"; public static final String METHOD_NAME_METHOD_INVOKE = "invoke"; public static final String METHOD_TYPE_METHOD_INVOKE = "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"; public static final String METHOD_NAME_CONSTRUCTOR_NEW_INSTANCE = "newInstance"; public static final String METHOD_TYPE_CONSTRUCTOR_NEW_INSTANCE = "([Ljava/lang/Object;)Ljava/lang/Object;"; public static final String METHOD_NAME_ARRAY_NEW_INSTANCE = "newInstance"; public static final String METHOD_TYPE_ARRAY_NEW_INSTANCE = "(Ljava/lang/Class;I)Ljava/lang/Object;"; public static final String METHOD_TYPE_ARRAY_NEW_INSTANCE2 = "(Ljava/lang/Class;[I)Ljava/lang/Object;"; public static final String METHOD_NAME_ACCESSIBLE_OBJECT_SET_ACCESSIBLE = "setAccessible"; public static final String METHOD_TYPE_ACCESSIBLE_OBJECT_SET_ACCESSIBLE = "(Z)V"; public static final String METHOD_NAME_GET_CAUSE = "getCause"; public static final String METHOD_TYPE_GET_CAUSE = "()Ljava/lang/Throwable;"; public static final String METHOD_TYPE_INIT_THROWABLE = "(Ljava/lang/Throwable;)V"; public static final String METHOD_NAME_MAKE_CONCAT = "makeConcat"; public static final String METHOD_NAME_MAKE_CONCAT_WITH_CONSTANTS = "makeConcatWithConstants"; public static final String METHOD_TYPE_INIT_COLLECTION = "(Ljava/util/Collection;)V"; public static final String METHOD_NAME_ADD = "add"; public static final String METHOD_TYPE_ADD = "(Ljava/lang/Object;)Z"; public static final String METHOD_NAME_ADD_ALL = "addAll"; public static final String METHOD_TYPE_ADD_ALL = "(Ljava/util/Collection;)Z"; public static final String METHOD_NAME_IS_EMPTY = "isEmpty"; public static final String METHOD_TYPE_IS_EMPTY = "()Z"; public static final String METHOD_NAME_MAP_PUT = "put"; public static final String METHOD_TYPE_MAP_PUT = "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"; public static final String METHOD_NAME_MAP_GET = "get"; public static final String METHOD_TYPE_MAP_GET = "(Ljava/lang/Object;)Ljava/lang/Object;"; public static final String METHOD_NAME_BOOLEAN_VALUE = "booleanValue"; public static final String METHOD_TYPE_BOOLEAN_VALUE = "()Z"; public static final String METHOD_NAME_CHAR_VALUE = "charValue"; public static final String METHOD_TYPE_CHAR_VALUE = "()C"; public static final String METHOD_NAME_SHORT_VALUE = "shortValue"; public static final String METHOD_TYPE_SHORT_VALUE = "()S"; public static final String METHOD_NAME_INT_VALUE = "intValue"; public static final String METHOD_TYPE_INT_VALUE = "()I"; public static final String METHOD_NAME_BYTE_VALUE = "byteValue"; public static final String METHOD_TYPE_BYTE_VALUE = "()B"; public static final String METHOD_NAME_LONG_VALUE = "longValue"; public static final String METHOD_TYPE_LONG_VALUE = "()J"; public static final String METHOD_NAME_FLOAT_VALUE = "floatValue"; public static final String METHOD_TYPE_FLOAT_VALUE = "()F"; public static final String METHOD_NAME_DOUBLE_VALUE = "doubleValue"; public static final String METHOD_TYPE_DOUBLE_VALUE = "()D"; // Serialization methods. public static final String METHOD_NAME_READ_OBJECT = "readObject"; public static final String METHOD_TYPE_READ_OBJECT = "(Ljava/io/ObjectInputStream;)V"; public static final String METHOD_NAME_READ_RESOLVE = "readResolve"; public static final String METHOD_TYPE_READ_RESOLVE = "()Ljava/lang/Object;"; public static final String METHOD_NAME_WRITE_OBJECT = "writeObject"; public static final String METHOD_TYPE_WRITE_OBJECT = "(Ljava/io/ObjectOutputStream;)V"; public static final String METHOD_NAME_WRITE_REPLACE = "writeReplace"; public static final String METHOD_TYPE_WRITE_REPLACE = "()Ljava/lang/Object;"; public static final String METHOD_NAME_DOT_CLASS_JAVAC = "class$"; public static final String METHOD_TYPE_DOT_CLASS_JAVAC = "(Ljava/lang/String;)Ljava/lang/Class;"; public static final String METHOD_NAME_DOT_CLASS_JIKES = "class"; public static final String METHOD_TYPE_DOT_CLASS_JIKES = "(Ljava/lang/String;Z)Ljava/lang/Class;"; public static final String METHOD_TYPE_INIT_ENUM = "(Ljava/lang/String;I)V"; public static final String METHOD_NAME_NEW_INSTANCE = "newInstance"; public static final String METHOD_TYPE_NEW_INSTANCE = "()Ljava/lang/Object;"; public static final String METHOD_NAME_VALUE_OF = "valueOf"; public static final String METHOD_TYPE_VALUE_OF_BOOLEAN = "(Z)Ljava/lang/Boolean;"; public static final String METHOD_TYPE_VALUE_OF_CHAR = "(C)Ljava/lang/Character;"; public static final String METHOD_TYPE_VALUE_OF_BYTE = "(B)Ljava/lang/Byte;"; public static final String METHOD_TYPE_VALUE_OF_SHORT = "(S)Ljava/lang/Short;"; public static final String METHOD_TYPE_VALUE_OF_INT = "(I)Ljava/lang/Integer;"; public static final String METHOD_TYPE_VALUE_OF_LONG = "(J)Ljava/lang/Long;"; public static final String METHOD_TYPE_VALUE_OF_FLOAT = "(F)Ljava/lang/Float;"; public static final String METHOD_TYPE_VALUE_OF_DOUBLE = "(D)Ljava/lang/Double;"; public static final String FIELD_NAME_TYPE = "TYPE"; public static final String FIELD_TYPE_TYPE = "Ljava/lang/Class;"; public static final String METHOD_NAME_EQUALS = "equals"; public static final String METHOD_TYPE_EQUALS = "(Ljava/lang/Object;)Z"; public static final String METHOD_NAME_LENGTH = "length"; public static final String METHOD_TYPE_LENGTH = "()I"; public static final String METHOD_NAME_VALUEOF = "valueOf"; public static final String METHOD_TYPE_VALUEOF_BOOLEAN = "(Z)Ljava/lang/String;"; public static final String METHOD_TYPE_TOSTRING_BOOLEAN = "(Z)Ljava/lang/String;"; public static final String METHOD_TYPE_VALUEOF_CHAR = "(C)Ljava/lang/String;"; public static final String METHOD_TYPE_VALUEOF_INT = "(I)Ljava/lang/String;"; public static final String METHOD_TYPE_VALUEOF_LONG = "(J)Ljava/lang/String;"; public static final String METHOD_TYPE_VALUEOF_FLOAT = "(F)Ljava/lang/String;"; public static final String METHOD_TYPE_VALUEOF_DOUBLE = "(D)Ljava/lang/String;"; public static final String METHOD_TYPE_VALUEOF_OBJECT = "(Ljava/lang/Object;)Ljava/lang/String;"; public static final String METHOD_NAME_INTERN = "intern"; public static final String METHOD_TYPE_INTERN = "()Ljava/lang/String;"; public static final String METHOD_NAME_APPEND = "append"; public static final String METHOD_TYPE_INT_VOID = "(I)V"; public static final String METHOD_TYPE_STRING_VOID = "(Ljava/lang/String;)V"; public static final String METHOD_TYPE_BYTES_VOID = "([B)V"; public static final String METHOD_TYPE_BYTES_INT_VOID = "([BI)V"; public static final String METHOD_TYPE_CHARS_VOID = "([C)V"; public static final String METHOD_TYPE_BOOLEAN_STRING_BUFFER = "(Z)Ljava/lang/StringBuffer;"; public static final String METHOD_TYPE_CHAR_STRING_BUFFER = "(C)Ljava/lang/StringBuffer;"; public static final String METHOD_TYPE_INT_STRING_BUFFER = "(I)Ljava/lang/StringBuffer;"; public static final String METHOD_TYPE_LONG_STRING_BUFFER = "(J)Ljava/lang/StringBuffer;"; public static final String METHOD_TYPE_FLOAT_STRING_BUFFER = "(F)Ljava/lang/StringBuffer;"; public static final String METHOD_TYPE_DOUBLE_STRING_BUFFER = "(D)Ljava/lang/StringBuffer;"; public static final String METHOD_TYPE_STRING_STRING_BUFFER = "(Ljava/lang/String;)Ljava/lang/StringBuffer;"; public static final String METHOD_TYPE_OBJECT_STRING_BUFFER = "(Ljava/lang/Object;)Ljava/lang/StringBuffer;"; public static final String METHOD_TYPE_BOOLEAN_STRING_BUILDER = "(Z)Ljava/lang/StringBuilder;"; public static final String METHOD_TYPE_CHAR_STRING_BUILDER = "(C)Ljava/lang/StringBuilder;"; public static final String METHOD_TYPE_INT_STRING_BUILDER = "(I)Ljava/lang/StringBuilder;"; public static final String METHOD_TYPE_LONG_STRING_BUILDER = "(J)Ljava/lang/StringBuilder;"; public static final String METHOD_TYPE_FLOAT_STRING_BUILDER = "(F)Ljava/lang/StringBuilder;"; public static final String METHOD_TYPE_DOUBLE_STRING_BUILDER = "(D)Ljava/lang/StringBuilder;"; public static final String METHOD_TYPE_STRING_STRING_BUILDER = "(Ljava/lang/String;)Ljava/lang/StringBuilder;"; public static final String METHOD_TYPE_OBJECT_STRING_BUILDER = "(Ljava/lang/Object;)Ljava/lang/StringBuilder;"; public static final String METHOD_NAME_TOSTRING = "toString"; public static final String METHOD_TYPE_TOSTRING = "()Ljava/lang/String;"; public static final String METHOD_NAME_CLONE = "clone"; public static final String METHOD_TYPE_CLONE = "()Ljava/lang/Object;"; public static final String METHOD_NAME_VALUES = "values"; public static final String METHOD_NAME_ORDINAL = "ordinal"; public static final String METHOD_TYPE_ORDINAL = "()I"; public static final char TYPE_VOID = 'V'; public static final char TYPE_BOOLEAN = 'Z'; public static final char TYPE_BYTE = 'B'; public static final char TYPE_CHAR = 'C'; public static final char TYPE_SHORT = 'S'; public static final char TYPE_INT = 'I'; public static final char TYPE_LONG = 'J'; public static final char TYPE_FLOAT = 'F'; public static final char TYPE_DOUBLE = 'D'; public static final char TYPE_CLASS_START = 'L'; public static final char TYPE_CLASS_END = ';'; public static final char TYPE_ARRAY = '['; public static final char TYPE_GENERIC_VARIABLE_START = 'T'; public static final char TYPE_GENERIC_START = '<'; public static final char TYPE_GENERIC_BOUND = ':'; public static final char TYPE_GENERIC_END = '>'; public static final int TYPICAL_CONSTANT_POOL_SIZE = 256; public static final int TYPICAL_FIELD_COUNT = 64; public static final int TYPICAL_METHOD_COUNT = 64; public static final int TYPICAL_PARAMETER_COUNT = 32; public static final int TYPICAL_CODE_LENGTH = 8096; public static final int TYPICAL_LINE_NUMBER_TABLE_LENGTH = 1024; public static final int TYPICAL_EXCEPTION_TABLE_LENGTH = 16; public static final int TYPICAL_VARIABLES_SIZE = 64; public static final int TYPICAL_STACK_SIZE = 16; public static final int TYPICAL_BOOTSTRAP_METHODS_ATTRIBUTE_SIZE = 16; public static final int MAXIMUM_BOOLEAN_AS_STRING_LENGTH = 5; // false public static final int MAXIMUM_CHAR_AS_STRING_LENGTH = 1; // any char public static final int MAXIMUM_BYTE_AS_STRING_LENGTH = 3; // 255 public static final int MAXIMUM_SHORT_AS_STRING_LENGTH = 6; // -32768 public static final int MAXIMUM_INT_AS_STRING_LENGTH = 11; //-2147483648 public static final int MAXIMUM_LONG_AS_STRING_LENGTH = 20; //-9223372036854775808 public static final int MAXIMUM_FLOAT_AS_STRING_LENGTH = 13; //-3.4028235E38 public static final int MAXIMUM_DOUBLE_AS_STRING_LENGTH = 23; //-1.7976931348623157E308 public static final int MAXIMUM_AT_HASHCODE_LENGTH = MAXIMUM_CHAR_AS_STRING_LENGTH + MAXIMUM_INT_AS_STRING_LENGTH; public static final int DEFAULT_STRINGBUILDER_INIT_SIZE = 16; }
/* * Licensed under the MIT license. * Copyright (c) 2007 David Holroyd */ package uk.co.badgersinfoil.e4x.antlr; /** * Manages the tokens of the parent tree in the most basic way possible, simply * inserting the run of tokens belonging to the child into the run of tokens * belonging to the parent and updating start/stop tokens for the parent if * required. */ public class BasicListUpdateDelegate implements TreeTokenListUpdateDelegate { // TODO: delete PLACEHOLDER tokens when they are superseded by the addition of real tokens public void addedChild(LinkedListTree parent, LinkedListTree child) { if (isPlaceholder(parent)) { if (isPlaceholder(child)) { throw new IllegalArgumentException("The parent node (" + E4XParser.tokenNames[parent.getType()] +") has only a placeholder token, so a child which also has only a placeholder token (" + E4XParser.tokenNames[child.getType()]+") can't be added yet"); } LinkedListToken placeholder = parent.getStartToken(); if (placeholder.getPrev() != null) { placeholder.getPrev().setNext(child.getStartToken()); } if (placeholder.getNext() != null) { placeholder.getNext().setPrev(child.getStopToken()); } parent.setStartToken(child.getStartToken()); parent.setStopToken(child.getStopToken()); return; } LinkedListToken stop = findTokenInsertionPointForChildWithinParent(parent, child); if (parent.getStartToken() == null) { parent.setStartToken(child.getStartToken()); } if (stop != null) { insertAfter(stop, stop.getNext(), child.getStartToken(), child.getStopToken()); } if (child.getStopToken() != null) { parent.setStopToken(child.getStopToken()); } } private boolean isPlaceholder(LinkedListTree ast) { return ast.getStartToken()==ast.getStopToken() && ast.getStartToken()!=null && ast.getStartToken().getType() == E4XParser.VIRTUAL_PLACEHOLDER && ((PlaceholderLinkedListToken)ast.getStartToken()).getHeld()==ast; } private LinkedListToken findTokenInsertionPointForChildWithinParent(LinkedListTree parent, LinkedListTree child) { // FIXME: this fails to take into account am ancestor not // having the same kind of TreeTokenListUpdateDelegate while (parent != null) { if (parent.getChildCount() == 1) { // the just-added child is the only child of 'parent' if (parent.getStopToken() != null) { return parent.getStopToken(); } if (parent.getStartToken() != null) { return parent.getStartToken(); } } int index = parent.getChildIndex(child); if (index > 0 && index < parent.getChildCount()-1) { // 'child' is not the *first* child of 'parent' LinkedListTree precedent = (LinkedListTree)parent.getChild(index-1); if (precedent.getStopToken() == null) { // TODO: loop, rather than recurse, return findTokenInsertionPointForChildWithinParent(parent, precedent); } return precedent.getStopToken(); } if (index==0 && parent.getStartToken()!=null) { return parent.getStartToken(); } if (parent.getStopToken() != null) { return parent.getStopToken(); } child = parent; parent = parent.getParent(); } return null; } public void addedChild(LinkedListTree parent, int index, LinkedListTree child) { LinkedListToken target; LinkedListToken targetNext; if (index == 0) { LinkedListTree prevFirstChild = (LinkedListTree)parent.getChild(1); targetNext = prevFirstChild.getStartToken(); target = targetNext.getPrev(); if (targetNext == parent.getStartToken()) { parent.setStartToken(child.getStartToken()); } } else { target = ((LinkedListTree)parent.getChild(index - 1)).getStopToken(); targetNext = target.getNext(); } insertAfter(target, targetNext, child.getStartToken(), child.getStopToken()); } protected static void insertAfter(LinkedListToken target, LinkedListToken targetNext, LinkedListToken start, LinkedListToken stop) { if (target == null && targetNext == null) { throw new IllegalArgumentException("At least one of target and targetNext must be non-null"); } if (start != null) { // if (start.getPrev() != null || stop.getNext() != null) { // throw new IllegalArgumentException("insertAfter("+target+", "+targetNext+", "+start+", "+stop+") : start.getPrev()="+start.getPrev()+" stop.getNext()="+stop.getNext()); // } // i.e. we're not adding an imaginary node that currently // has no real children if (target != null) { target.setNext(start); } stop.setNext(targetNext); if (targetNext != null) { targetNext.setPrev(stop); } } } public void appendToken(LinkedListTree parent, LinkedListToken append) { if (parent.getStopToken() == null) { parent.setStartToken(append); parent.setStopToken(append); } else { // TODO: can this be simplified now? append.setNext(parent.getStopToken().getNext()); parent.getStopToken().setNext(append); append.setPrev(parent.getStopToken()); parent.setStopToken(append); } } public void addToken(LinkedListTree parent, int index, LinkedListToken append) { if (isPlaceholder(parent)) { LinkedListToken placeholder = parent.getStartToken(); parent.setStartToken(append); parent.setStopToken(append); placeholder.setPrev(null); placeholder.setNext(null); } if (parent.getStopToken() == null) { parent.setStartToken(append); parent.setStopToken(append); } else { LinkedListToken target; LinkedListToken targetNext; if (index == 0) { targetNext = parent.getStartToken(); target = targetNext.getPrev(); parent.setStartToken(append); } else if (index == parent.getChildCount()) { target = parent.getStopToken(); targetNext = target.getNext(); parent.setStopToken(append); } else { LinkedListTree beforeChild = (LinkedListTree)parent.getChild(index); targetNext = beforeChild.getStartToken(); target = targetNext.getPrev(); } insertAfter(target, targetNext, append, append); } } public void deletedChild(LinkedListTree parent, int index, LinkedListTree child) { // FIXME: this should update start/stop tokens for the parent // when the first/last child is removed LinkedListToken start = child.getStartToken(); LinkedListToken stop = child.getStopToken(); LinkedListToken startPrev = start.getPrev(); LinkedListToken stopNext = stop.getNext(); // if (startPrev == null) { // throw new IllegalArgumentException("No start.prev: "+child); // } // if (stopNext == null) { // throw new IllegalArgumentException("No stop.next: "+child+" (stop="+stop+")"); // } if (parent.getChildCount() == 0 && start == parent.getStartToken() && stop == parent.getStopToken()) { // So, the child provided all the tokens that made up // the parent, and removing it will leave nothing! In // this case, we insert a 'placeholder' token just so // there's something in the token stream for the parent // to reference, and the parent remains anchored to the // appropriate location within the source code LinkedListToken placeholder = new PlaceholderLinkedListToken(parent); startPrev.setNext(placeholder); stopNext.setPrev(placeholder); } else { if (startPrev != null) { startPrev.setNext(stopNext); } else if (stopNext != null) { // so try the other way around, stopNext.setPrev(startPrev); } if (parent.getStartToken() == start) { parent.setStartToken(stopNext); } if (parent.getStopToken() == stop) { parent.setStopToken(startPrev); } } // just to save possible confusion, break links out from the // removed token list too, start.setPrev(null); stop.setNext(null); } public void replacedChild(LinkedListTree tree, int index, LinkedListTree child, LinkedListTree oldChild) { // defensive assertions to catch bugs, if (child.getStartToken() == null) { throw new IllegalArgumentException("No startToken: "+child); } if (child.getStopToken() == null) { throw new IllegalArgumentException("No stopToken: "+child); } // link the new child's tokens in place of the old, LinkedListToken oldBefore = findOldBeforeToken(tree, index, child, oldChild); LinkedListToken oldAfter = findOldAfterToken(tree, index, child, oldChild); if (oldBefore != null) { oldBefore.setNext(child.getStartToken()); } if (oldAfter != null) { oldAfter.setPrev(child.getStopToken()); } // just to save possible confusion, break links out from the // removed token list too, oldChild.getStartToken().setPrev(null); oldChild.getStopToken().setNext(null); if (tree.getStartToken() == oldChild.getStartToken()) { tree.setStartToken(child.getStartToken()); } if (tree.getStopToken() == oldChild.getStopToken()) { tree.setStopToken(child.getStopToken()); } } private LinkedListToken findOldBeforeToken(LinkedListTree tree, int index, LinkedListTree child, LinkedListTree oldChild) { LinkedListToken oldStart = oldChild.getStartToken(); if (oldStart == null) { throw new IllegalStateException("<"+oldChild+">, child "+index+" of <"+tree+">, had no startToken"); } return oldStart.getPrev(); } private LinkedListToken findOldAfterToken(LinkedListTree tree, int index, LinkedListTree child, LinkedListTree oldChild) { LinkedListToken oldStop = oldChild.getStopToken(); if (oldStop == null) { throw new IllegalStateException("<"+oldChild+">, child "+index+" of <"+tree+">, had no stopToken"); } return oldStop.getNext(); } }
/** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI licenses this file to you 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 org.openengsb.core.common.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Dictionary; import java.util.Hashtable; import java.util.Iterator; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.ObjectUtils; import org.openengsb.core.api.ConnectorInstanceFactory; import org.openengsb.core.api.ConnectorProvider; import org.openengsb.core.api.DomainProvider; import org.openengsb.core.api.VirtualConnectorProvider; import org.openengsb.core.util.FilterUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.Filter; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.common.collect.Sets; /** * This class is used to automatically register {@link ConnectorProvider}s for Virtual connectors. With every * {@link VirtualConnectorProvider} or {@link DomainProvider} registered or removed the {@link ConnectorProvider}s for * the virtual connectors are managed accordingly. */ public class VirtualConnectorManager { private static class Registration { protected Registration(VirtualConnectorProvider virtualConnector, DomainProvider domainProvider, ServiceRegistration factoryService, ServiceRegistration connectorProvider) { this.virtualConnector = virtualConnector; this.domainProvider = domainProvider; this.factoryService = factoryService; this.connectorProvider = connectorProvider; } private VirtualConnectorProvider virtualConnector; private DomainProvider domainProvider; private ServiceRegistration factoryService; private ServiceRegistration connectorProvider; } private Collection<Registration> registeredFactories = Sets.newHashSet(); private ServiceTracker virtualConnectorProviderTracker; private ServiceTracker domainProviderTracker; private final BundleContext bundleContext; public VirtualConnectorManager(BundleContext bundleContext) { this.bundleContext = bundleContext; init(); } private void init() { Filter virtualConnectorFilter = FilterUtils.makeFilterForClass(VirtualConnectorProvider.class); virtualConnectorProviderTracker = new ServiceTracker(bundleContext, virtualConnectorFilter, new ServiceTrackerCustomizer() { @Override public void removedService(ServiceReference reference, Object service) { VirtualConnectorProvider provider = (VirtualConnectorProvider) service; Iterator<Registration> factoryServices = getFactoriesForVirtualConnectorForRemoval(provider); unregisterAllRegistrations(factoryServices); } @Override public void modifiedService(ServiceReference reference, Object service) { // do nothing } @Override public Object addingService(ServiceReference reference) { createNewFactoryForVirtualConnectorProvider(reference); return bundleContext.getService(reference); } }); Filter domainProviderFilter = FilterUtils.makeFilterForClass(DomainProvider.class); domainProviderTracker = new ServiceTracker(bundleContext, domainProviderFilter, new ServiceTrackerCustomizer() { @Override public void removedService(ServiceReference reference, Object service) { Iterator<Registration> factoryServices = getFactoriesForDomainProviderForRemoval((DomainProvider) service); unregisterAllRegistrations(factoryServices); } @Override public void modifiedService(ServiceReference reference, Object service) { // do nothing } @Override public Object addingService(ServiceReference reference) { DomainProvider newProvider = (DomainProvider) bundleContext.getService(reference); createNewFactoryForDomainProvider(newProvider); return newProvider; } }); } public void start() { virtualConnectorProviderTracker.open(); domainProviderTracker.open(); Object[] services = domainProviderTracker.getServices(); if (services != null) { for (Object service : services) { createNewFactoryForDomainProvider((DomainProvider) service); } } } public void stop() { virtualConnectorProviderTracker.close(); domainProviderTracker.close(); } protected static <T> Collection<T> getServicesFromTracker(ServiceTracker tracker, Class<T> serviceClass) { Collection<T> result = new ArrayList<T>(); if (tracker == null) { return result; } Object[] services = tracker.getServices(); if (services != null) { CollectionUtils.addAll(result, services); } return result; } private Iterator<Registration> getFactoriesForVirtualConnectorForRemoval(final VirtualConnectorProvider provider) { Iterator<Registration> consumingIterator = Iterators.consumingIterator(registeredFactories.iterator()); return Iterators.filter(consumingIterator, new Predicate<Registration>() { @Override public boolean apply(Registration input) { return ObjectUtils.equals(input.virtualConnector, provider); } }); } private Iterator<Registration> getFactoriesForDomainProviderForRemoval(final DomainProvider provider) { Iterator<Registration> consumingIterator = Iterators.consumingIterator(registeredFactories.iterator()); return Iterators.filter(consumingIterator, new Predicate<Registration>() { @Override public boolean apply(Registration input) { return ObjectUtils.equals(input.domainProvider, provider); } }); } private void createNewFactoryForVirtualConnectorProvider(ServiceReference reference) { VirtualConnectorProvider virtualConnectorProvider = (VirtualConnectorProvider) bundleContext.getService(reference); for (DomainProvider p : getServicesFromTracker(domainProviderTracker, DomainProvider.class)) { ServiceRegistration factoryService = registerConnectorFactoryService(virtualConnectorProvider, p); ServiceRegistration providerService = registerConnectorProviderService(virtualConnectorProvider, p); registeredFactories.add(new Registration(virtualConnectorProvider, p, factoryService, providerService)); } } private ServiceRegistration registerConnectorProviderService(VirtualConnectorProvider virtualConnectorProvider, DomainProvider p) { Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put(org.openengsb.core.api.Constants.DOMAIN_KEY, p.getId()); properties.put(org.openengsb.core.api.Constants.CONNECTOR_KEY, virtualConnectorProvider.getId()); return bundleContext.registerService(ConnectorProvider.class.getCanonicalName(), virtualConnectorProvider, properties); } private void createNewFactoryForDomainProvider(DomainProvider newProvider) { Collection<VirtualConnectorProvider> virtualProviders = getServicesFromTracker(virtualConnectorProviderTracker, VirtualConnectorProvider.class); for (VirtualConnectorProvider p : virtualProviders) { registerConnectorFactoryService(p, newProvider); ServiceRegistration factoryService = registerConnectorFactoryService(p, newProvider); ServiceRegistration providerService = registerConnectorProviderService(p, newProvider); registeredFactories.add(new Registration(p, newProvider, factoryService, providerService)); } } protected ServiceRegistration registerConnectorFactoryService(VirtualConnectorProvider virtualConnectorProvider, DomainProvider p) { ConnectorInstanceFactory factory = virtualConnectorProvider.createFactory(p); Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put(org.openengsb.core.api.Constants.DOMAIN_KEY, p.getId()); properties.put(org.openengsb.core.api.Constants.CONNECTOR_KEY, virtualConnectorProvider.getId()); return bundleContext.registerService(ConnectorInstanceFactory.class.getName(), factory, properties); } private void unregisterAllRegistrations(Iterator<Registration> factoryServices) { while (factoryServices.hasNext()) { Registration r = factoryServices.next(); r.factoryService.unregister(); r.connectorProvider.unregister(); } } }
/* * MultipartEntity * * 0.1 * * 2014/07/18 * * (The MIT License) * * Copyright (c) R2B Apps <r2b.apps@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package r2b.apps.utils.logger; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import r2b.apps.utils.Cons; import android.util.Log; /** * MultipartEntity utility class for sending multipart HTTP * POST requests to a web server. */ public class MultipartEntity { /** * Default charset. */ private static final String DEFAULT_CHARSET = "UTF-8"; private static final String LINE_FEED = "\r\n"; private final String boundary; private HttpURLConnection httpConn; private OutputStream outputStream; private PrintWriter writer; /** * This constructor initializes a new HTTP POST request with content type is * set to multipart/form-data * * @param requestURL * @param charset * @throws IOException */ public MultipartEntity(String requestURL) throws IOException { // creates a unique boundary based on time stamp boundary = "===" + System.currentTimeMillis() + "==="; URL url = new URL(requestURL); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = httpConn.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(outputStream, DEFAULT_CHARSET), true); } /** * Adds a form field to the request * * @param name * field name * @param value * field value */ public void addFormField(String name, String value) { writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + name + "\"") .append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + DEFAULT_CHARSET) .append(LINE_FEED); writer.append(LINE_FEED); writer.append(value).append(LINE_FEED); writer.flush(); } /** * Adds a upload file section to the request * * @param fieldName * name attribute in <input type="file" name="..." /> * @param uploadFile * a File to be uploaded * @throws IOException */ public void addFilePart(String fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); writer.append("--" + boundary).append(LINE_FEED); writer.append( "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"") .append(LINE_FEED); writer.append( "Content-Type: " + URLConnection.guessContentTypeFromName(fileName)) .append(LINE_FEED); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); writer.flush(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); } /** * Adds a header field to the request. * * @param name * - name of the header field * @param value * - value of the header field */ public void addHeaderField(String name, String value) { writer.append(name + ": " + value).append(LINE_FEED); writer.flush(); } /** * Completes the request and receives response from the server. * * @return a list of Strings as response in case the server returned status * OK, otherwise nothing do. */ public List<String> finish() throws IOException { List<String> response = new ArrayList<String>(); writer.append(LINE_FEED).flush(); writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); // checks server's status code first int status = httpConn.getResponseCode(); if(Cons.DEBUG) { if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader( httpConn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { response.add(line); } reader.close(); httpConn.disconnect(); } else { Log.e(this.getClass().getSimpleName(), "Server returned non-OK status: " + status); } } else { if (status == HttpURLConnection.HTTP_OK) { httpConn.disconnect(); } else { Log.e(this.getClass().getSimpleName(), "Server returned non-OK status: " + status); } } return response; } }
package com.mkl.eu.client.service.vo.military; import com.mkl.eu.client.service.vo.AbstractWithLoss; /** * Modifiers of each side in battle. * * @author MKL. */ public class BattleSide { /** Flag saying that the side has selected its forces. */ private Boolean forces; /** Flag saying that the side has selected its losses. */ private Boolean lossesSelected; /** Flag saying that the side has selected its retreat. */ private Boolean retreatSelected; /** Code of the leader commanding the side. */ private String leader; /** Country commanding the side. */ private String country; /** Size of the side. */ private Double size; /** Technology of the side. */ private String tech; /** Fire column of the side. */ private String fireColumn; /** Shock column of the side. */ private String shockColumn; /** Moral of the side. */ private Integer moral; /** First day modifiers. */ private BattleDay firstDay = new BattleDay(); /** Second day modifiers. */ private BattleDay secondDay = new BattleDay(); /** Modifier for the pursuit phase. */ private int pursuitMod; /** Unmodified die roll for the pursuit phase. */ private Integer pursuit; /** Losses. */ private AbstractWithLoss losses = new AbstractWithLoss(); /** Size diff. */ private Integer sizeDiff; /** Unmodified die roll for the retreat. */ private Integer retreat; /** @return the forces. */ public Boolean isForces() { return forces; } /** @param forces the forces to set. */ public void setForces(Boolean forces) { this.forces = forces; } /** @return the leader. */ public String getLeader() { return leader; } /** @param leader the leader to set. */ public void setLeader(String leader) { this.leader = leader; } /** @return the country. */ public String getCountry() { return country; } /** @param country the country to set. */ public void setCountry(String country) { this.country = country; } /** @return the size. */ public Double getSize() { return size; } /** @param size the size to set. */ public void setSize(Double size) { this.size = size; } /** @return the tech. */ public String getTech() { return tech; } /** @param tech the tech to set. */ public void setTech(String tech) { this.tech = tech; } /** @return the fireColumn. */ public String getFireColumn() { return fireColumn; } /** @param fireColumn the fireColumn to set. */ public void setFireColumn(String fireColumn) { this.fireColumn = fireColumn; } /** @return the shockColumn. */ public String getShockColumn() { return shockColumn; } /** @param shockColumn the shockColumn to set. */ public void setShockColumn(String shockColumn) { this.shockColumn = shockColumn; } /** @return the moral. */ public Integer getMoral() { return moral; } /** @param moral the moral to set. */ public void setMoral(Integer moral) { this.moral = moral; } /** @return the firstDay. */ public BattleDay getFirstDay() { return firstDay; } /** @param firstDay the firstDay to set. */ public void setFirstDay(BattleDay firstDay) { this.firstDay = firstDay; } /** @return the secondDay. */ public BattleDay getSecondDay() { return secondDay; } /** @param secondDay the secondDay to set. */ public void setSecondDay(BattleDay secondDay) { this.secondDay = secondDay; } /** @return the pursuitMod. */ public int getPursuitMod() { return pursuitMod; } /** @param pursuitMod the pursuitMod to set. */ public void setPursuitMod(int pursuitMod) { this.pursuitMod = pursuitMod; } /** * Add the pursuit modifier to the current one. * * @param pursuit the pursuit modifier to add. */ public void addPursuit(int pursuit) { this.pursuitMod += pursuit; } /** @return the pursuit. */ public Integer getPursuit() { return pursuit; } /** @param pursuit the pursuit to set. */ public void setPursuit(Integer pursuit) { this.pursuit = pursuit; } /** @return the losses. */ public AbstractWithLoss getLosses() { return losses; } /** @param losses the losses to set. */ public void setLosses(AbstractWithLoss losses) { this.losses = losses; } /** @return the sizeDiff. */ public Integer getSizeDiff() { return sizeDiff; } /** @param sizeDiff the sizeDiff to set. */ public void setSizeDiff(Integer sizeDiff) { this.sizeDiff = sizeDiff; } /** @return the retreat. */ public Integer getRetreat() { return retreat; } /** @param retreat the retreat to set. */ public void setRetreat(Integer retreat) { this.retreat = retreat; } /** @return the lossesSelected. */ public Boolean isLossesSelected() { return lossesSelected; } /** @param lossesSelected the lossesSelected to set. */ public void setLossesSelected(Boolean lossesSelected) { this.lossesSelected = lossesSelected; } /** @return the retreatSelected. */ public Boolean isRetreatSelected() { return retreatSelected; } /** @param retreatSelected the retreatSelected to set. */ public void setRetreatSelected(Boolean retreatSelected) { this.retreatSelected = retreatSelected; } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 org.apache.edgent.test.connectors.jdbc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.sql.DataSource; import org.apache.edgent.connectors.jdbc.JdbcStreams; import org.apache.edgent.function.Predicate; import org.apache.edgent.test.connectors.common.ConnectorTestBase; import org.apache.edgent.topology.TSink; import org.apache.edgent.topology.TStream; import org.apache.edgent.topology.Topology; import org.apache.edgent.topology.plumbing.PlumbingStreams; import org.apache.edgent.topology.tester.Condition; import org.junit.Test; /** * JdbcStreams connector tests. * <p> * The tests use Apache Embedded Derby as the backing dbms. * The connectors/jdbc/pom.xml includes a "test" dependency on derby * so execution of the test via maven automatially retrieves and adds * the derby jar to the classpath. * The pom also defines jdbcStreamsTest.tmpdir and redirects the derby.log location. * <p> * If running the test from Eclipse you may have to manually add derby.jar * to the test's classpath. * The Oracle JDK includes Derby in $JAVA_HOME/db/lib/derby.jar. * <p> * The tests are "skipped" if the dbms's jdbc driver can't be found. */ public class JdbcStreamsTest extends ConnectorTestBase { private static final int SEC_TIMEOUT = 10; private final static String TMPDIR_PROPERTY_NAME = "jdbcStreamsTest.tmpdir"; private final static String TMPDIR = System.getProperty(TMPDIR_PROPERTY_NAME, ""); static { if (TMPDIR.equals("")) { throw new RuntimeException("System property \""+TMPDIR_PROPERTY_NAME+"\" is not set."); } } private final static String DB_NAME = TMPDIR + "/JdbcStreamsTestDb"; private final static String USERNAME = "test"; // can't contain "." private final static String PW = "none"; private static final List<Person> personList = new ArrayList<>(); static { personList.add(new Person(1, "John", "Doe", "male", 35)); personList.add(new Person(2, "Jane", "Doe", "female", 29)); personList.add(new Person(3, "Billy", "McDoe", "male", 3)); } private static final List<PersonId> personIdList = new ArrayList<>(); static { for(Person p : personList) { personIdList.add(new PersonId(p.id)); } } static class Person { int id; String firstName; String lastName; String gender; int age; Person(int id, String first, String last, String gender, int age) { this.id = id; this.firstName = first; this.lastName = last; this.gender = gender; this.age = age; } public String toString() { return String.format("id=%d first=%s last=%s gender=%s age=%d", id, firstName, lastName, gender, age); } } static class PersonId { int id; PersonId(int id) { this.id = id; } public String toString() { return String.format("id=%d", id); } } public List<Person> getPersonList() { return personList; } public List<PersonId> getPersonIdList() { return personIdList; } DataSource getDerbyEmbeddedDataSource(String database) throws Exception { // Avoid a compile-time dependency to the jdbc driver. // At runtime, require that the classpath can find it. // e.g., pom.xml adds derby.jar to the test classpath String DERBY_DATA_SOURCE = "org.apache.derby.jdbc.EmbeddedDataSource"; Class<?> nsDataSource = null; try { nsDataSource = Class.forName(DERBY_DATA_SOURCE); } catch (ClassNotFoundException e) { String msg = "Fix the test classpath. "; msg += "Class not found: "+e.getLocalizedMessage(); System.err.println(msg); assumeTrue(false); } DataSource ds = (DataSource) nsDataSource.newInstance(); @SuppressWarnings("rawtypes") Class[] methodParams = new Class[] {String.class}; Method dbname = nsDataSource.getMethod("setDatabaseName", methodParams); Object[] args = new Object[] {database}; dbname.invoke(ds, args); // create the db if necessary Method create = nsDataSource.getMethod("setCreateDatabase", methodParams); args = new Object[] {"create"}; create.invoke(ds, args); return ds; } private DataSource getDataSource(String logicalDbName) throws Exception { return getDerbyEmbeddedDataSource(logicalDbName); } private Connection connect(DataSource ds) throws Exception { return ds.getConnection(USERNAME, PW); } private void createPersonsTable() throws Exception { DataSource ds = getDataSource(DB_NAME); try(Connection cn = connect(ds)) { Statement stmt = cn.createStatement(); try { stmt.execute("CREATE TABLE persons " + "(" + "id INTEGER NOT NULL," + "firstname VARCHAR(40) NOT NULL," + "lastname VARCHAR(40) NOT NULL," + "gender VARCHAR(6)," + "age INTEGER," + "PRIMARY KEY (id)" + ")" ); } catch (SQLException e) { if (e.getLocalizedMessage().contains("already exists")) return; else throw e; } } } private void truncatePersonsTable() throws Exception { createPersonsTable(); DataSource ds = getDataSource(DB_NAME); try(Connection cn = connect(ds)) { Statement stmt = cn.createStatement(); stmt.executeUpdate("DELETE FROM persons"); } } private void populatePersonsTable(List<Person> personList) throws Exception { truncatePersonsTable(); DataSource ds = getDataSource(DB_NAME); try(Connection cn = connect(ds)) { Statement stmt = cn.createStatement(); for(Person p : personList) { stmt.execute(String.format( "INSERT INTO persons VALUES(%d,'%s','%s','%s',%d)", p.id, p.firstName, p.lastName, p.gender, p.age)); } } } private TStream<Person> readPersonsTable(Topology t, JdbcStreams db, List<PersonId> personIdList, int delayMsec) { // Create a stream of Person from a stream of ids TStream<PersonId> personIds = t.collection(personIdList); if (delayMsec!=0) { personIds = PlumbingStreams.blockingOneShotDelay(personIds, delayMsec, TimeUnit.MILLISECONDS); } TStream<Person> rcvdPerson = db.executeStatement(personIds, () -> "SELECT id, firstname, lastname, gender, age" + " FROM persons WHERE id = ?", (tuple,stmt) -> stmt.setInt(1, tuple.id), (tuple,resultSet,exc,stream) -> { resultSet.next(); int id = resultSet.getInt("id"); String firstName = resultSet.getString("firstname"); String lastName = resultSet.getString("lastname"); String gender = resultSet.getString("gender"); int age = resultSet.getInt("age"); stream.accept(new Person(id, firstName, lastName, gender, age)); } ); return rcvdPerson; } private static Predicate<Person> newOddIdPredicate() { return (person) -> person.id % 2 != 0; } private List<String> expectedPersons(Predicate<Person> predicate, List<Person> persons) { List<String> expPersons = new ArrayList<>(); for (Person p : persons) { if (predicate.test(p)) { expPersons.add(p.toString()); } } return expPersons; } @Test public void testBasicRead() throws Exception { Topology t = this.newTopology("testBasicRead"); populatePersonsTable(getPersonList()); List<String> expected = expectedPersons(person->true, getPersonList()); JdbcStreams db = new JdbcStreams(t, () -> getDataSource(DB_NAME), dataSource -> connect(dataSource)); // Create a stream of Person from a stream of ids TStream<Person> rcvdPerson = readPersonsTable(t, db, getPersonIdList(), 0/*msec*/); TStream<String> rcvd = rcvdPerson.map(person -> person.toString()); rcvd.sink(tuple -> System.out.println( String.format("%s rcvd: %s", t.getName(), tuple))); completeAndValidate("", t, rcvd, SEC_TIMEOUT, expected.toArray(new String[0])); } @Test public void testBasicRead2() throws Exception { Topology t = newTopology("testBasicRead2"); // same as testBasic but use the explicit PreparedStatement forms // of executeStatement(). populatePersonsTable(getPersonList()); List<String> expected = expectedPersons(person->true, getPersonList()); JdbcStreams db = new JdbcStreams(t, () -> getDataSource(DB_NAME), dataSource -> connect(dataSource)); // Create a stream of Person from a stream of ids // Delay so this runs after populating the db above TStream<PersonId> personIds = PlumbingStreams.blockingOneShotDelay( t.collection(getPersonIdList()), 3, TimeUnit.SECONDS); TStream<Person> rcvdPerson = db.executeStatement(personIds, (cn) -> cn.prepareStatement("SELECT id, firstname, lastname, gender, age" + " FROM persons WHERE id = ?"), (tuple,stmt) -> stmt.setInt(1, tuple.id), (tuple,resultSet,exc,stream) -> { resultSet.next(); int id = resultSet.getInt("id"); String firstName = resultSet.getString("firstname"); String lastName = resultSet.getString("lastname"); String gender = resultSet.getString("gender"); int age = resultSet.getInt("age"); stream.accept(new Person(id, firstName, lastName, gender, age)); } ); TStream<String> rcvd = rcvdPerson.map(person -> person.toString()); rcvd.sink(tuple -> System.out.println( String.format("%s rcvd: %s", t.getName(), tuple))); completeAndValidate("", t, rcvd, SEC_TIMEOUT, expected.toArray(new String[0])); } @Test public void testBasicWrite() throws Exception { Topology t = newTopology("testBasicWrite"); truncatePersonsTable(); List<String> expected = expectedPersons(person->true, getPersonList()); JdbcStreams db = new JdbcStreams(t, () -> getDataSource(DB_NAME), dataSource -> connect(dataSource)); // Add stream of Person to the db TStream<Person> s = t.collection(getPersonList()); TSink<Person> sink = db.executeStatement(s, () -> "INSERT INTO persons VALUES(?,?,?,?,?)", (tuple,stmt) -> { stmt.setInt(1, tuple.id); stmt.setString(2, tuple.firstName); stmt.setString(3, tuple.lastName); stmt.setString(4, tuple.gender); stmt.setInt(5, tuple.age); } ); assertNotNull(sink); // Use the same code as testBasicRead to verify the write worked. TStream<Person> rcvdPerson = readPersonsTable(t, db, getPersonIdList(), 3000/*msec*/); TStream<String> rcvd = rcvdPerson.map(person -> person.toString()); rcvd.sink(tuple -> System.out.println( String.format("%s rcvd: %s", t.getName(), tuple))); completeAndValidate("", t, rcvd, SEC_TIMEOUT, expected.toArray(new String[0])); } @Test public void testBasicWrite2() throws Exception { Topology t = newTopology("testBasicWrite2"); // same as testBasic but use the explicit PreparedStatement forms // of executeStatement(). truncatePersonsTable(); List<String> expected = expectedPersons(person->true, getPersonList()); JdbcStreams db = new JdbcStreams(t, () -> getDataSource(DB_NAME), dataSource -> connect(dataSource)); // Add stream of Person to the db TStream<Person> s = t.collection(getPersonList()); TSink<Person> sink = db.executeStatement(s, (cn) -> cn.prepareStatement("INSERT into PERSONS values(?,?,?,?,?)"), (tuple,stmt) -> { stmt.setInt(1, tuple.id); stmt.setString(2, tuple.firstName); stmt.setString(3, tuple.lastName); stmt.setString(4, tuple.gender); stmt.setInt(5, tuple.age); } ); assertNotNull(sink); // Use the same code as testBasicRead to verify the write worked. TStream<Person> rcvdPerson = readPersonsTable(t, db, getPersonIdList(), 3000/*msec*/); TStream<String> rcvd = rcvdPerson.map(person -> person.toString()); rcvd.sink(tuple -> System.out.println( String.format("%s rcvd: %s", t.getName(), tuple))); completeAndValidate("", t, rcvd, SEC_TIMEOUT, expected.toArray(new String[0])); } @Test public void testBadConnectFn() throws Exception { Topology t = newTopology("testBadConnectFn"); // connFn is only called for initial connect or reconnect // following certain failures. // Hence, to exercise transient connFn failures, we need to start // off with a failure. // TODO for transient connection failure cases, simulate a failure // as part of preparedStatement.execute() failing (e.g., force cn-close // right before it?), so that we can verify the conn is closed and // then reconnected populatePersonsTable(getPersonList()); List<String> expected = expectedPersons(p->true, getPersonList().subList(1, getPersonList().size())); int expectedExcCnt = getPersonList().size() - expected.size(); AtomicInteger connFnCnt = new AtomicInteger(); JdbcStreams db = new JdbcStreams(t, () -> getDataSource(DB_NAME), dataSource -> { if (connFnCnt.incrementAndGet() == 1) throw new SQLException("FAKE-CONNECT-FN-FAILURE"); else return connect(dataSource); }); // Create a stream of Person from a stream of ids AtomicInteger executionExcCnt = new AtomicInteger(); TStream<PersonId> personIds = t.collection(getPersonIdList()); TStream<Person> rcvdPerson = db.executeStatement(personIds, () -> "SELECT id, firstname, lastname, gender, age" + " FROM persons WHERE id = ?", (tuple,stmt) -> stmt.setInt(1, tuple.id), (tuple,resultSet,exc,stream) -> { System.out.println(t.getName()+" resultHandler called tuple="+tuple+" exc="+exc); if (exc!=null) { executionExcCnt.incrementAndGet(); return; } resultSet.next(); int id = resultSet.getInt("id"); String firstName = resultSet.getString("firstname"); String lastName = resultSet.getString("lastname"); String gender = resultSet.getString("gender"); int age = resultSet.getInt("age"); stream.accept(new Person(id, firstName, lastName, gender, age)); } ); TStream<String> rcvd = rcvdPerson.map(person -> person.toString()); rcvd.sink(tuple -> System.out.println( String.format("%s rcvd: %s", t.getName(), tuple))); completeAndValidate("", t, rcvd, SEC_TIMEOUT, expected.toArray(new String[0])); assertEquals("executionExcCnt", expectedExcCnt, executionExcCnt.get()); } @Test public void testBadSQL() throws Exception { Topology t = newTopology("testBadSQL"); // the statement is nominally "retrieved" only once, not per-tuple. // hence, there's not much sense in trying to simulate it // getting called unsuccessfully, then successfully, etc. // however, verify the result handler gets called appropriately. populatePersonsTable(getPersonList()); List<String> expected = Collections.emptyList(); int expectedExcCnt = getPersonList().size() - expected.size(); JdbcStreams db = new JdbcStreams(t, () -> getDataSource(DB_NAME), dataSource -> connect(dataSource)); // Create a stream of Person from a stream of ids AtomicInteger executionExcCnt = new AtomicInteger(); TStream<PersonId> personIds = t.collection(getPersonIdList()); TStream<Person> rcvdPerson = db.executeStatement(personIds, () -> "SELECT id, firstname, lastname, gender, age" + " FROM persons WHERE BOGUS_XYZZY id = ?", (tuple,stmt) -> stmt.setInt(1, tuple.id), (tuple,resultSet,exc,stream) -> { System.out.println(t.getName()+" resultHandler called tuple="+tuple+" exc="+exc); if (exc!=null) { executionExcCnt.incrementAndGet(); return; } // don't ever expect to get here in this case resultSet.next(); int id = resultSet.getInt("id"); String firstName = resultSet.getString("firstname"); String lastName = resultSet.getString("lastname"); String gender = resultSet.getString("gender"); int age = resultSet.getInt("age"); stream.accept(new Person(id, firstName, lastName, gender, age)); } ); TStream<String> rcvd = rcvdPerson.map(person -> person.toString()); // Await completion on having received the correct number of exception. // Then also verify that no non-exceptional results were received. Condition<Object> tc = new Condition<Object>() { public boolean valid() { return executionExcCnt.get() == expectedExcCnt; } public Object getResult() { return executionExcCnt.get(); } }; Condition<List<String>> rcvdContents = t.getTester().streamContents(rcvd, expected.toArray(new String[0])); rcvd.sink(tuple -> System.out.println( String.format("%s rcvd: %s", t.getName(), tuple))); complete(t, tc, SEC_TIMEOUT, TimeUnit.SECONDS); assertEquals("executionExcCnt", expectedExcCnt, executionExcCnt.get()); assertTrue("rcvd: "+rcvdContents.getResult(), rcvdContents.valid()); } @Test public void testBadSetParams() throws Exception { Topology t = newTopology("testBadSetParams"); // exercise and validate behavior with transient parameter setter failures populatePersonsTable(getPersonList()); List<String> expected = expectedPersons(newOddIdPredicate(), getPersonList()); int expectedExcCnt = getPersonList().size() - expected.size(); JdbcStreams db = new JdbcStreams(t, () -> getDataSource(DB_NAME), dataSource -> connect(dataSource)); // Create a stream of Person from a stream of ids AtomicInteger executionExcCnt = new AtomicInteger(); TStream<PersonId> personIds = t.collection(getPersonIdList()); TStream<Person> rcvdPerson = db.executeStatement(personIds, () -> "SELECT id, firstname, lastname, gender, age" + " FROM persons WHERE id = ?", (tuple,stmt) -> { if (tuple.id % 2 != 0) stmt.setInt(1, tuple.id); else stmt.setString(1, "THIS-IS-BOGUS"); }, (tuple,resultSet,exc,stream) -> { System.out.println(t.getName()+" resultHandler called tuple="+tuple+" exc="+exc); if (exc!=null) { executionExcCnt.incrementAndGet(); return; } resultSet.next(); int id = resultSet.getInt("id"); String firstName = resultSet.getString("firstname"); String lastName = resultSet.getString("lastname"); String gender = resultSet.getString("gender"); int age = resultSet.getInt("age"); stream.accept(new Person(id, firstName, lastName, gender, age)); } ); TStream<String> rcvd = rcvdPerson.map(person -> person.toString()); rcvd.sink(tuple -> System.out.println( String.format("%s rcvd: %s", t.getName(), tuple))); completeAndValidate("", t, rcvd, SEC_TIMEOUT, expected.toArray(new String[0])); assertEquals("executionExcCnt", expectedExcCnt, executionExcCnt.get()); } @Test public void testBadResultHandler() throws Exception { Topology t = newTopology("testBadResultHandler"); // exercise and validate behavior with transient result handler failures populatePersonsTable(getPersonList()); List<String> expected = expectedPersons(newOddIdPredicate(), getPersonList()); int expectedExcCnt = getPersonList().size() - expected.size(); JdbcStreams db = new JdbcStreams(t, () -> getDataSource(DB_NAME), dataSource -> connect(dataSource)); // Create a stream of Person from a stream of ids AtomicInteger executionExcCnt = new AtomicInteger(); TStream<PersonId> personIds = t.collection(getPersonIdList()); TStream<Person> rcvdPerson = db.executeStatement(personIds, () -> "SELECT id, firstname, lastname, gender, age" + " FROM persons WHERE id = ?", (tuple,stmt) -> stmt.setInt(1, tuple.id), (tuple,resultSet,exc,stream) -> { System.out.println(t.getName()+" resultHandler called tuple="+tuple+" exc="+exc); if (exc!=null) { executionExcCnt.incrementAndGet(); return; } resultSet.next(); int id = resultSet.getInt(tuple.id % 2 == 0 ? "ID-THIS-IS-BOGUS" : "id"); String firstName = resultSet.getString("firstname"); String lastName = resultSet.getString("lastname"); String gender = resultSet.getString("gender"); int age = resultSet.getInt("age"); stream.accept(new Person(id, firstName, lastName, gender, age)); } ); TStream<String> rcvd = rcvdPerson.map(person -> person.toString()); rcvd.sink(tuple -> System.out.println( String.format("%s rcvd: %s", t.getName(), tuple))); completeAndValidate("", t, rcvd, SEC_TIMEOUT, expected.toArray(new String[0])); assertEquals("executionExcCnt", expectedExcCnt, executionExcCnt.get()); } @Test public void testNonResultSetStmt() throws Exception { Topology t = newTopology("testNonResultSetStmt"); // exercise and validate use of non-ResultSet SQL statement // wrt proper resultHandler behavior - e.g., receive exception, // can generate tuples List<String> expected = Arrays.asList("once"); // throw if can't create DataSource - e.g., can't locate derby getDataSource(DB_NAME); JdbcStreams db = new JdbcStreams(t, () -> getDataSource(DB_NAME), dataSource -> connect(dataSource)); // Add stream of Person to the db TStream<String> trigger = t.collection(expected); TStream<String> dropTableStep = db.executeStatement(trigger, () -> "DROP TABLE swill", (tuple,stmt) -> { /* no params */ }, (tuple,rs,exc,consumer) -> { // ok if fails System.out.println(t.getName()+" resultHandler drop table exc="+exc); if (rs!=null) throw new IllegalStateException("rs!=null"); consumer.accept(tuple); } ); TStream<String> createTableStep = db.executeStatement(dropTableStep, () -> "CREATE TABLE swill (id INTEGER NOT NULL)", (tuple,stmt) -> { /* no params */ }, (tuple,rs,exc,consumer) -> { System.out.println(t.getName()+" resultHandler create table exc="+exc); if (rs!=null) throw new IllegalStateException("rs!=null"); consumer.accept(tuple); } ); TStream<String> failDropTable = db.executeStatement(createTableStep, () -> "DROP TABLE no_such_table", (tuple,stmt) -> { /* no params */ }, (tuple,rs,exc,consumer) -> { System.out.println(t.getName()+" resultHandler fail drop table exc="+exc); if (exc==null) throw new IllegalStateException("exc==null"); if (rs!=null) throw new IllegalStateException("rs!=null"); consumer.accept(tuple); } ); TStream<String> selectStep = db.executeStatement(failDropTable, () -> "SELECT * FROM swill", (tuple,stmt) -> { /* no params */ }, (tuple,rs,exc,consumer) -> { System.out.println(t.getName()+" resultHandler select exc="+exc); if (rs==null) throw new IllegalStateException("rs==null"); consumer.accept(tuple); } ); TStream<String> rcvd = selectStep; completeAndValidate("", t, rcvd, SEC_TIMEOUT, expected.toArray(new String[0])); } }
/******************************************************************************* * * Copyright (c) 2012 GigaSpaces Technologies Ltd. All rights reserved * * 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 org.openspaces.admin.internal.alert.bean; import java.util.List; import java.util.Map; import org.openspaces.admin.Admin; import org.openspaces.admin.alert.Alert; import org.openspaces.admin.alert.AlertFactory; import org.openspaces.admin.alert.AlertSeverity; import org.openspaces.admin.alert.AlertStatus; import org.openspaces.admin.alert.alerts.MirrorPersistenceFailureAlert; import org.openspaces.admin.alert.config.MirrorPersistenceFailureAlertConfiguration; import org.openspaces.admin.internal.alert.InternalAlertManager; import org.openspaces.admin.internal.alert.bean.util.AlertBeanUtils; import org.openspaces.admin.space.ReplicationStatus; import org.openspaces.admin.space.ReplicationTarget; import org.openspaces.admin.space.SpaceInstance; import org.openspaces.admin.space.events.SpaceInstanceRemovedEventListener; import org.openspaces.admin.space.events.SpaceInstanceStatisticsChangedEvent; import org.openspaces.admin.space.events.SpaceInstanceStatisticsChangedEventListener; import com.gigaspaces.cluster.activeelection.SpaceMode; import com.gigaspaces.cluster.replication.async.mirror.MirrorStatistics; import com.j_spaces.core.filters.ReplicationStatistics; import com.j_spaces.core.filters.ReplicationStatistics.OutgoingChannel; import com.j_spaces.core.filters.ReplicationStatistics.ReplicationMode; public class MirrorPersistenceFailureAlertBean implements AlertBean, SpaceInstanceRemovedEventListener, SpaceInstanceStatisticsChangedEventListener { public static final String beanUID = "aafb1222-f271090d-157b-4aa7-bc99-f5baec11296a"; public static final String ALERT_NAME = "Mirror Persistence Failure"; private final MirrorPersistenceFailureAlertConfiguration config = new MirrorPersistenceFailureAlertConfiguration(); private Admin admin; public MirrorPersistenceFailureAlertBean() { } @Override public void afterPropertiesSet() throws Exception { validateProperties(); admin.getSpaces().getSpaceInstanceRemoved().add(this); admin.getSpaces().getSpaceInstanceStatisticsChanged().add(this); admin.getSpaces().startStatisticsMonitor(); } @Override public void destroy() throws Exception { admin.getSpaces().getSpaceInstanceRemoved().remove(this); admin.getSpaces().getSpaceInstanceStatisticsChanged().remove(this); admin.getSpaces().stopStatisticsMonitor(); } @Override public Map<String, String> getProperties() { return config.getProperties(); } @Override public void setAdmin(Admin admin) { this.admin = admin; } @Override public void setProperties(Map<String, String> properties) { config.setProperties(properties); } private void validateProperties() { } @Override public void spaceInstanceRemoved(SpaceInstance spaceInstance) { if (!spaceInstance.getSpaceUrl().getSchema().equals("mirror")) { return; //not a mirror } final String groupUid = generateGroupUid(spaceInstance.getUid()); Alert[] alertsByGroupUid = ((InternalAlertManager)admin.getAlertManager()).getAlertRepository().getAlertsByGroupUid(groupUid); if (alertsByGroupUid.length != 0 && !alertsByGroupUid[0].getStatus().isResolved()) { AlertFactory factory = new AlertFactory(); factory.name(ALERT_NAME); factory.groupUid(groupUid); factory.description("Mirror space " + getSpaceName(spaceInstance) + " is unavailable."); factory.severity(AlertSeverity.SEVERE); factory.status(AlertStatus.NA); factory.componentUid(spaceInstance.getUid()); factory.componentDescription(AlertBeanUtils.getSpaceInstanceDescription(spaceInstance)); factory.config(config.getProperties()); factory.putProperty(MirrorPersistenceFailureAlert.HOST_NAME, spaceInstance.getMachine().getHostName()); factory.putProperty(MirrorPersistenceFailureAlert.HOST_ADDRESS, spaceInstance.getMachine().getHostAddress()); factory.putProperty(MirrorPersistenceFailureAlert.VIRTUAL_MACHINE_UID, spaceInstance.getVirtualMachine().getUid()); Alert alert = factory.toAlert(); admin.getAlertManager().triggerAlert( new MirrorPersistenceFailureAlert(alert)); } } @Override public void spaceInstanceStatisticsChanged(SpaceInstanceStatisticsChangedEvent event) { final SpaceInstance source = event.getSpaceInstance(); final ReplicationStatistics replicationStatistics = event.getStatistics().getReplicationStatistics(); if (replicationStatistics == null) return; Boolean mirrorChannelIsInconsistent = null; String reason = null; long redoLogRetainedSize = -1; SpaceInstance mirrorInstance = null; List<OutgoingChannel> channels = replicationStatistics.getOutgoingReplication().getChannels(); for (OutgoingChannel channel : channels) { if (ReplicationMode.MIRROR.equals(channel.getReplicationMode())) { //find matching mirror instance for (ReplicationTarget replicationTarget : source.getReplicationTargets()) { if (replicationTarget.getMemberName().equals(channel.getTargetMemberName())) { mirrorInstance = replicationTarget.getSpaceInstance(); } } //extract info from channel mirrorChannelIsInconsistent = Boolean.valueOf(channel.isInconsistent()); if (mirrorChannelIsInconsistent) { reason = channel.getInconsistencyReason(); redoLogRetainedSize = channel.getRedologRetainedSize(); break; } } } //no mirror channel found if (mirrorChannelIsInconsistent == null || mirrorInstance == null) return; if (mirrorChannelIsInconsistent && reason != null) { final String groupUid = generateGroupUid(mirrorInstance.getUid()); AlertFactory factory = new AlertFactory(); factory.name(ALERT_NAME); factory.groupUid(groupUid); factory.description("Mirror failed to persist data sent from " + getSpaceName(source) + " - " + getRootCauseMessage(reason)); factory.severity(AlertSeverity.SEVERE); factory.status(AlertStatus.RAISED); factory.componentUid(mirrorInstance.getUid()); factory.componentDescription(AlertBeanUtils.getSpaceInstanceDescription(mirrorInstance)); factory.config(config.getProperties()); factory.putProperty(MirrorPersistenceFailureAlert.HOST_NAME, mirrorInstance.getMachine().getHostName()); factory.putProperty(MirrorPersistenceFailureAlert.HOST_ADDRESS, mirrorInstance.getMachine().getHostAddress()); factory.putProperty(MirrorPersistenceFailureAlert.VIRTUAL_MACHINE_UID, mirrorInstance.getVirtualMachine().getUid()); factory.putProperty(MirrorPersistenceFailureAlert.INCONSISTENCY_REASON, reason); factory.putProperty(MirrorPersistenceFailureAlert.ROOT_CAUSE_MESSAGE, getRootCauseMessage(reason)); factory.putProperty(MirrorPersistenceFailureAlert.ROOT_CAUSE_TRACE, getRootCauseTrace(reason)); factory.putProperty(MirrorPersistenceFailureAlert.REPLICATION_STATUS, getReplicationStatus(source)); factory.putProperty(MirrorPersistenceFailureAlert.REDO_LOG_SIZE, String.valueOf(replicationStatistics.getOutgoingReplication().getRedoLogSize())); factory.putProperty(MirrorPersistenceFailureAlert.REDO_LOG_RETAINED_SIZE, String.valueOf(redoLogRetainedSize)); MirrorStatistics mirrorStatistics = source.getStatistics().getMirrorStatistics(); if (mirrorStatistics != null) { factory.putProperty(MirrorPersistenceFailureAlert.FAILED_OPERATION_COUNT, String.valueOf(mirrorStatistics.getFailedOperationCount())); factory.putProperty(MirrorPersistenceFailureAlert.IN_PROGRESS_OPERATION_COUNT, String.valueOf(mirrorStatistics.getInProgressOperationCount())); factory.putProperty(MirrorPersistenceFailureAlert.DISCARDED_OPERATION_COUNT, String.valueOf(mirrorStatistics.getDiscardedOperationCount())); } Alert alert = factory.toAlert(); admin.getAlertManager().triggerAlert( new MirrorPersistenceFailureAlert(alert)); } else if (!mirrorChannelIsInconsistent) { final String groupUid = generateGroupUid(mirrorInstance.getUid()); Alert[] alertsByGroupUid = ((InternalAlertManager)admin.getAlertManager()).getAlertRepository().getAlertsByGroupUid(groupUid); if (alertsByGroupUid.length != 0 && !alertsByGroupUid[0].getStatus().isResolved()) { AlertFactory factory = new AlertFactory(); factory.name(ALERT_NAME); factory.groupUid(groupUid); factory.description("Mirror managed to persist data sent from " + getSpaceName(source)); factory.severity(AlertSeverity.SEVERE); factory.status(AlertStatus.RESOLVED); factory.componentUid(mirrorInstance.getUid()); factory.componentDescription(AlertBeanUtils.getSpaceInstanceDescription(mirrorInstance)); factory.config(config.getProperties()); factory.putProperty(MirrorPersistenceFailureAlert.HOST_NAME, mirrorInstance.getMachine().getHostName()); factory.putProperty(MirrorPersistenceFailureAlert.HOST_ADDRESS, mirrorInstance.getMachine().getHostAddress()); factory.putProperty(MirrorPersistenceFailureAlert.VIRTUAL_MACHINE_UID, mirrorInstance.getVirtualMachine().getUid()); factory.putProperty(MirrorPersistenceFailureAlert.REPLICATION_STATUS, getReplicationStatus(source)); factory.putProperty(MirrorPersistenceFailureAlert.REDO_LOG_SIZE, String.valueOf(replicationStatistics.getOutgoingReplication().getRedoLogSize())); factory.putProperty(MirrorPersistenceFailureAlert.REDO_LOG_RETAINED_SIZE, String.valueOf(redoLogRetainedSize)); MirrorStatistics mirrorStatistics = source.getStatistics().getMirrorStatistics(); if (mirrorStatistics != null) { factory.putProperty(MirrorPersistenceFailureAlert.FAILED_OPERATION_COUNT, String.valueOf(mirrorStatistics.getFailedOperationCount())); factory.putProperty(MirrorPersistenceFailureAlert.IN_PROGRESS_OPERATION_COUNT, String.valueOf(mirrorStatistics.getInProgressOperationCount())); factory.putProperty(MirrorPersistenceFailureAlert.DISCARDED_OPERATION_COUNT, String.valueOf(mirrorStatistics.getDiscardedOperationCount())); } Alert alert = factory.toAlert(); admin.getAlertManager().triggerAlert(new MirrorPersistenceFailureAlert(alert)); } } } private String getRootCauseMessage(String reason) { int lastIndexOfCausedBy = reason.lastIndexOf("Caused by: "); if (lastIndexOfCausedBy == -1) { lastIndexOfCausedBy = 0; } int endOfLineIndex = reason.indexOf("\n", lastIndexOfCausedBy); if (endOfLineIndex == -1) { return reason.substring(0, Math.min(20, reason.length()))+"..."; } String cause = reason.substring(lastIndexOfCausedBy, endOfLineIndex); return cause; } private String getRootCauseTrace(String reason) { int lastIndexOfCausedBy = reason.lastIndexOf("Caused by: "); if (lastIndexOfCausedBy == -1) { lastIndexOfCausedBy = 0; } int lastIndexOfAt = reason.lastIndexOf("\tat", reason.length()); if (lastIndexOfAt == -1) { return reason.substring(0, Math.min(20, reason.length()))+"..."; } String cause = reason.substring(lastIndexOfCausedBy, lastIndexOfAt); return cause; } private String getReplicationStatus(SpaceInstance source) { for (ReplicationTarget target : source.getReplicationTargets()) { if (!ReplicationStatus.ACTIVE.equals(target.getReplicationStatus())) { return target.getReplicationStatus().name(); } } return ReplicationStatus.ACTIVE.name(); } private String getSpaceName(SpaceInstance source) { StringBuilder sb = new StringBuilder(); SpaceMode sourceSpaceMode = source.getMode(); sb.append(sourceSpaceMode.toString().toLowerCase()).append(" Space "); sb.append(source.getSpace().getName() + "." + source.getInstanceId() + " ["+(source.getBackupId()+1)+"]"); return sb.toString(); } private String generateGroupUid(String uid) { return beanUID.concat("-").concat(uid); } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.iot.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The criteria that determines how many retries are allowed for each failure type for a job. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RetryCriteria implements Serializable, Cloneable, StructuredPojo { /** * <p> * The type of job execution failures that can initiate a job retry. * </p> */ private String failureType; /** * <p> * The number of retries allowed for a failure type for the job. * </p> */ private Integer numberOfRetries; /** * <p> * The type of job execution failures that can initiate a job retry. * </p> * * @param failureType * The type of job execution failures that can initiate a job retry. * @see RetryableFailureType */ public void setFailureType(String failureType) { this.failureType = failureType; } /** * <p> * The type of job execution failures that can initiate a job retry. * </p> * * @return The type of job execution failures that can initiate a job retry. * @see RetryableFailureType */ public String getFailureType() { return this.failureType; } /** * <p> * The type of job execution failures that can initiate a job retry. * </p> * * @param failureType * The type of job execution failures that can initiate a job retry. * @return Returns a reference to this object so that method calls can be chained together. * @see RetryableFailureType */ public RetryCriteria withFailureType(String failureType) { setFailureType(failureType); return this; } /** * <p> * The type of job execution failures that can initiate a job retry. * </p> * * @param failureType * The type of job execution failures that can initiate a job retry. * @return Returns a reference to this object so that method calls can be chained together. * @see RetryableFailureType */ public RetryCriteria withFailureType(RetryableFailureType failureType) { this.failureType = failureType.toString(); return this; } /** * <p> * The number of retries allowed for a failure type for the job. * </p> * * @param numberOfRetries * The number of retries allowed for a failure type for the job. */ public void setNumberOfRetries(Integer numberOfRetries) { this.numberOfRetries = numberOfRetries; } /** * <p> * The number of retries allowed for a failure type for the job. * </p> * * @return The number of retries allowed for a failure type for the job. */ public Integer getNumberOfRetries() { return this.numberOfRetries; } /** * <p> * The number of retries allowed for a failure type for the job. * </p> * * @param numberOfRetries * The number of retries allowed for a failure type for the job. * @return Returns a reference to this object so that method calls can be chained together. */ public RetryCriteria withNumberOfRetries(Integer numberOfRetries) { setNumberOfRetries(numberOfRetries); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFailureType() != null) sb.append("FailureType: ").append(getFailureType()).append(","); if (getNumberOfRetries() != null) sb.append("NumberOfRetries: ").append(getNumberOfRetries()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RetryCriteria == false) return false; RetryCriteria other = (RetryCriteria) obj; if (other.getFailureType() == null ^ this.getFailureType() == null) return false; if (other.getFailureType() != null && other.getFailureType().equals(this.getFailureType()) == false) return false; if (other.getNumberOfRetries() == null ^ this.getNumberOfRetries() == null) return false; if (other.getNumberOfRetries() != null && other.getNumberOfRetries().equals(this.getNumberOfRetries()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFailureType() == null) ? 0 : getFailureType().hashCode()); hashCode = prime * hashCode + ((getNumberOfRetries() == null) ? 0 : getNumberOfRetries().hashCode()); return hashCode; } @Override public RetryCriteria clone() { try { return (RetryCriteria) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.iot.model.transform.RetryCriteriaMarshaller.getInstance().marshall(this, protocolMarshaller); } }