gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * Copyright 2010-2011 Nabeel Mukhtar * * 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.code.linkedinapi.schema.xpp; import java.io.IOException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; import com.google.code.linkedinapi.schema.Company; import com.google.code.linkedinapi.schema.CompanyJobUpdate; import com.google.code.linkedinapi.schema.CompanyPersonUpdate; import com.google.code.linkedinapi.schema.CompanyProfileUpdate; import com.google.code.linkedinapi.schema.CompanyStatusUpdate; import com.google.code.linkedinapi.schema.Job; import com.google.code.linkedinapi.schema.Person; import com.google.code.linkedinapi.schema.Question; import com.google.code.linkedinapi.schema.UpdateAction; import com.google.code.linkedinapi.schema.UpdateContent; public class UpdateContentImpl extends BaseSchemaEntity implements UpdateContent { /** * */ private static final long serialVersionUID = 8557807037014197165L; protected PersonImpl person; protected UpdateActionImpl updateAction; protected JobImpl job; protected QuestionImpl question; protected CompanyImpl company; protected CompanyJobUpdateImpl companyJobUpdate; protected CompanyPersonUpdateImpl companyPersonUpdate; protected CompanyProfileUpdateImpl companyProfileUpdate; protected CompanyStatusUpdateImpl companyStatusUpdate; public Person getPerson() { return person; } public void setPerson(Person value) { this.person = ((PersonImpl) value); } public UpdateAction getUpdateAction() { return updateAction; } public void setUpdateAction(UpdateAction value) { this.updateAction = ((UpdateActionImpl) value); } public Question getQuestion() { return question; } public void setQuestion(Question value) { this.question = ((QuestionImpl) value); } public Job getJob() { return job; } public void setJob(Job value) { this.job = ((JobImpl) value); } public Company getCompany() { return company; } public void setCompany(Company value) { this.company = ((CompanyImpl) value); } public CompanyJobUpdate getCompanyJobUpdate() { return companyJobUpdate; } public void setCompanyJobUpdate(CompanyJobUpdate value) { this.companyJobUpdate = ((CompanyJobUpdateImpl) value); } public CompanyPersonUpdate getCompanyPersonUpdate() { return companyPersonUpdate; } public void setCompanyPersonUpdate(CompanyPersonUpdate value) { this.companyPersonUpdate = ((CompanyPersonUpdateImpl) value); } public CompanyProfileUpdate getCompanyProfileUpdate() { return companyProfileUpdate; } public void setCompanyProfileUpdate(CompanyProfileUpdate value) { this.companyProfileUpdate = ((CompanyProfileUpdateImpl) value); } public CompanyStatusUpdate getCompanyStatusUpdate() { return companyStatusUpdate; } public void setCompanyStatusUpdate(CompanyStatusUpdate value) { this.companyStatusUpdate = ((CompanyStatusUpdateImpl) value); } @Override public void init(XmlPullParser parser) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, null, null); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("person")) { PersonImpl personImpl = new PersonImpl(); personImpl.init(parser); setPerson(personImpl); } else if (name.equals("job")) { JobImpl jobImpl = new JobImpl(); jobImpl.init(parser); setJob(jobImpl); } else if (name.equals("update-action")) { UpdateActionImpl updateActionImpl = new UpdateActionImpl(); updateActionImpl.init(parser); setUpdateAction(updateActionImpl); } else if (name.equals("question")) { QuestionImpl questionImpl = new QuestionImpl(); questionImpl.init(parser); setQuestion(questionImpl); } else if (name.equals("company")) { CompanyImpl companyImpl = new CompanyImpl(); companyImpl.init(parser); setCompany(companyImpl); } else if (name.equals("company-job-update")) { CompanyJobUpdateImpl companyJobUpdate = new CompanyJobUpdateImpl(); companyJobUpdate.init(parser); setCompanyJobUpdate(companyJobUpdate); } else if (name.equals("company-person-update")) { CompanyPersonUpdateImpl companyPersonUpdate = new CompanyPersonUpdateImpl(); companyPersonUpdate.init(parser); setCompanyPersonUpdate(companyPersonUpdate); } else if (name.equals("company-profile-update")) { CompanyProfileUpdateImpl companyProfileUpdate = new CompanyProfileUpdateImpl(); companyProfileUpdate.init(parser); setCompanyProfileUpdate(companyProfileUpdate); } else if (name.equals("company-status-update")) { CompanyStatusUpdateImpl companyStatusUpdate = new CompanyStatusUpdateImpl(); companyStatusUpdate.init(parser); setCompanyStatusUpdate(companyStatusUpdate); } else { // Consume something we don't understand. LOG.warning("Found tag that we don't recognize: " + name); XppUtils.skipSubTree(parser); } } } @Override public void toXml(XmlSerializer serializer) throws IOException { XmlSerializer element = serializer.startTag(null, "update-content"); if (getPerson() != null) { ((PersonImpl) getPerson()).toXml(element); } if (getJob() != null) { ((JobImpl) getJob()).toXml(element); } if (getUpdateAction() != null) { ((UpdateActionImpl) getUpdateAction()).toXml(element); } if (getQuestion() != null) { ((QuestionImpl) getQuestion()).toXml(element); } if (getCompany() != null) { ((CompanyImpl) getCompany()).toXml(element); } if (getCompanyJobUpdate() != null) { ((CompanyJobUpdateImpl) getCompanyJobUpdate()).toXml(element); } if (getCompanyPersonUpdate() != null) { ((CompanyPersonUpdateImpl) getCompanyPersonUpdate()).toXml(element); } if (getCompanyProfileUpdate() != null) { ((CompanyProfileUpdateImpl) getCompanyProfileUpdate()).toXml(element); } if (getCompanyStatusUpdate() != null) { ((CompanyStatusUpdateImpl) getCompanyStatusUpdate()).toXml(element); } serializer.endTag(null, "update-content"); } }
/* * 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.sling.installer.it; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.provision; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.when; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Dictionary; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import javax.inject.Inject; import org.apache.sling.installer.api.InstallableResource; import org.apache.sling.installer.api.OsgiInstaller; import org.junit.Before; import org.ops4j.pax.exam.Option; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.osgi.framework.ServiceReference; import org.osgi.framework.SynchronousBundleListener; import org.osgi.framework.Version; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleWiring; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.log.LogService; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.util.tracker.ServiceTracker; /** Base class for OsgiInstaller testing */ public class OsgiInstallerTestBase implements FrameworkListener { private final static String POM_VERSION = System.getProperty("osgi.installer.pom.version", "POM_VERSION_NOT_SET"); private final static String CONFIG_VERSION = System.getProperty("installer.configuration.version", "INSTALLER_VERSION_NOT_SET"); public final static String JAR_EXT = ".jar"; private int packageRefreshEventsCount; private ServiceTracker configAdminTracker; protected OsgiInstaller installer; public static final long WAIT_FOR_ACTION_TIMEOUT_MSEC = 6000; public static final String BUNDLE_BASE_NAME = "org.apache.sling.installer.it-" + POM_VERSION; @Inject protected BundleContext bundleContext; public static final String URL_SCHEME = "OsgiInstallerTest"; static abstract class Condition { abstract boolean isTrue() throws Exception; String additionalInfo() { return null; } void onFailure() { } long getMsecBetweenEvaluations() { return 100L; } } /** * Helper method to get a service of the given type */ @SuppressWarnings("unchecked") protected <T> T getService(Class<T> clazz) { final ServiceReference ref = bundleContext.getServiceReference(clazz.getName()); assertNotNull("getService(" + clazz.getName() + ") must find ServiceReference", ref); final T result = (T)(bundleContext.getService(ref)); assertNotNull("getService(" + clazz.getName() + ") must find service", result); return result; } /** Set up the installer service. */ protected void setupInstaller() { installer = getService(OsgiInstaller.class); } @Before public void setup() { configAdminTracker = new ServiceTracker(bundleContext, ConfigurationAdmin.class.getName(), null); configAdminTracker.open(); } /** Tear down everything. */ public void tearDown() { synchronized (this) { if (configAdminTracker != null) { configAdminTracker.close(); configAdminTracker = null; } } } /** * Restart the installer. */ protected void restartInstaller() throws BundleException { final String symbolicName = "org.apache.sling.installer.core"; final Bundle b = findBundle(symbolicName); if (b == null) { fail("Bundle " + symbolicName + " not found"); } log(LogService.LOG_INFO, "Restarting " + symbolicName + " bundle"); b.stop(); b.start(); setupInstaller(); } protected void generateBundleEvent() throws Exception { // install a bundle manually to generate a bundle event final File f = getTestBundle("org.apache.sling.installer.it-" + POM_VERSION + "-testbundle-1.0.jar"); final InputStream is = new FileInputStream(f); Bundle b = null; try { b = bundleContext.installBundle(getClass().getName(), is); b.start(); final long timeout = System.currentTimeMillis() + 2000L; while(b.getState() != Bundle.ACTIVE && System.currentTimeMillis() < timeout) { sleep(10L); } } finally { is.close(); if (b != null) { b.uninstall(); } } } /** * @see org.osgi.framework.FrameworkListener#frameworkEvent(org.osgi.framework.FrameworkEvent) */ public void frameworkEvent(FrameworkEvent event) { if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) { packageRefreshEventsCount++; } } protected void refreshPackages() { bundleContext.addFrameworkListener(this); final int MAX_REFRESH_PACKAGES_WAIT_SECONDS = 5; final int targetEventCount = packageRefreshEventsCount + 1; final long timeout = System.currentTimeMillis() + MAX_REFRESH_PACKAGES_WAIT_SECONDS * 1000L; final PackageAdmin pa = getService(PackageAdmin.class); pa.refreshPackages(null); try { while(true) { if(System.currentTimeMillis() > timeout) { break; } if(packageRefreshEventsCount >= targetEventCount) { break; } sleep(250L); } } finally { bundleContext.removeFrameworkListener(this); } } protected Configuration findConfiguration(String pid) throws Exception { final ConfigurationAdmin ca = this.waitForConfigAdmin(true); if (ca != null) { final Configuration[] cfgs = ca.listConfigurations(null); if (cfgs != null) { for(Configuration cfg : cfgs) { try { if(cfg.getPid().equals(pid)) { return cfg; } } catch (IllegalStateException e) {} } } } return null; } protected void waitForCondition(String info, long timeoutMsec, Condition c) throws Exception { final long end = System.currentTimeMillis() + timeoutMsec; do { if(c.isTrue()) { return; } sleep(c.getMsecBetweenEvaluations()); } while(System.currentTimeMillis() < end); if(c.additionalInfo() != null) { info += " " + c.additionalInfo(); } c.onFailure(); fail("WaitForCondition failed: " + info); } protected void waitForConfigValue(String info, String pid, long timeoutMsec, String key, String value) throws Exception { final long end = System.currentTimeMillis() + timeoutMsec; do { final Configuration c = waitForConfiguration(info, pid, timeoutMsec, true); if(value.equals(c.getProperties().get(key))) { return; } sleep(100L); } while(System.currentTimeMillis() < end); fail("Did not get " + key + "=" + value + " for config " + pid); } protected Configuration waitForConfiguration(String info, String pid, long timeoutMsec, boolean shouldBePresent) throws Exception { if (info == null) { info = ""; } else { info += ": "; } Configuration result = null; final long start = System.currentTimeMillis(); final long end = start + timeoutMsec; log(LogService.LOG_DEBUG, "Starting config check at " + start + "; ending by " + end); do { result = findConfiguration(pid); if ((shouldBePresent && result != null) || (!shouldBePresent && result == null)) { break; } log(LogService.LOG_DEBUG, "Config check failed at " + System.currentTimeMillis() + "; sleeping"); sleep(25); } while(System.currentTimeMillis() < end); if (shouldBePresent && result == null) { fail(info + "Configuration not found (" + pid + ")"); } else if (!shouldBePresent && result != null) { fail(info + "Configuration is still present (" + pid + ")"); } return result; } protected Bundle findBundle(String symbolicName) { for(Bundle b : bundleContext.getBundles()) { if (symbolicName.equals(b.getSymbolicName())) { return b; } } return null; } protected Bundle assertBundle(String info, String symbolicName, String version, int state) { final Bundle b = findBundle(symbolicName); if(info == null) { info = ""; } else { info += ": "; } assertNotNull(info + "Expected bundle " + symbolicName + " to be installed", b); if(version != null) { assertEquals(info + "Expected bundle " + symbolicName + " to be version " + version, version, b.getHeaders().get(Constants.BUNDLE_VERSION)); } if(state >= 0) { assertEquals(info + "Expected bundle " + symbolicName + " to be in state " + state, state, b.getState()); } return b; } protected File getTestBundle(String bundleName) { return new File(System.getProperty("osgi.installer.base.dir"), bundleName); } protected InstallableResource[] getInstallableResource(File testBundle) throws IOException { return getInstallableResource(testBundle, null); } protected String[] getNonInstallableResourceUrl(File testBundle) throws IOException { return new String[] {testBundle.getAbsolutePath()}; } protected InstallableResource[] getInstallableResource(File testBundle, String digest) throws IOException { return getInstallableResource(testBundle, digest, InstallableResource.DEFAULT_PRIORITY); } protected InstallableResource[] getInstallableResource(File testBundle, String digest, int priority) throws IOException { final String url = testBundle.getAbsolutePath(); if (digest == null) { digest = String.valueOf(testBundle.lastModified()); } final InstallableResource result = new MockInstallableResource(url, new FileInputStream(testBundle), digest, null, priority); return new InstallableResource[] {result}; } protected InstallableResource[] getInstallableResource(String configPid, Dictionary<String, Object> data) { return getInstallableResource(configPid, copy(data), InstallableResource.DEFAULT_PRIORITY); } protected InstallableResource[] getInstallableResource(String configPid, Dictionary<String, Object> data, int priority) { final InstallableResource result = new MockInstallableResource("/" + configPid, copy(data), null, null, priority); return new InstallableResource[] {result}; } protected Dictionary<String, Object> copy(Dictionary<String, Object> data) { final Dictionary<String, Object> copy = new Hashtable<String, Object>(); final Enumeration<String> keys = data.keys(); while(keys.hasMoreElements()) { final String key = keys.nextElement(); copy.put(key, data.get(key)); } return copy; } protected ConfigurationAdmin waitForConfigAdmin(final boolean shouldBePresent) { ConfigurationAdmin result = null; final int timeout = 5; final long waitUntil = System.currentTimeMillis() + (timeout * 1000L); boolean isPresent; do { result = (ConfigurationAdmin)configAdminTracker.getService(); isPresent = result != null; if ( shouldBePresent == isPresent ) { return result; } } while(System.currentTimeMillis() < waitUntil); assertEquals("Expected ConfigurationAdmin to be " + (shouldBePresent ? "present" : "absent"), shouldBePresent, isPresent); return result; } protected Bundle getConfigAdminBundle() { this.waitForConfigAdmin(true); return this.configAdminTracker.getServiceReference().getBundle(); } /** * Helper method for sleeping. */ protected void sleep(long msec) { try { Thread.sleep(msec); } catch(InterruptedException ignored) { } } protected void log(int level, String msg) { final LogService log = getService(LogService.class); log.log(level, msg); } protected Option[] defaultConfiguration() { String vmOpt = "-Dosgi.installer.testing"; // This runs in the VM that runs the build, but the tests run in another one. // Make all osgi.installer.* system properties available to OSGi framework VM for(Object o : System.getProperties().keySet()) { final String key = (String)o; if(key.startsWith("osgi.installer.")) { vmOpt += " -D" + key + "=" + System.getProperty(key); } } // optional debugging final String paxDebugLevel = System.getProperty("pax.exam.log.level", "INFO"); final String paxDebugPort = System.getProperty("pax.exam.debug.port"); if(paxDebugPort != null && paxDebugPort.length() > 0) { vmOpt += " -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=" + paxDebugPort; } String localRepo = System.getProperty("maven.repo.local", ""); return options( junitBundles(), when( localRepo.length() > 0 ).useOptions( systemProperty("org.ops4j.pax.url.mvn.localRepository").value(localRepo) ), systemProperty( "org.ops4j.pax.logging.DefaultServiceLog.level" ).value(paxDebugLevel), provision( mavenBundle("org.apache.sling", "org.apache.sling.commons.log", "3.0.0"), mavenBundle("org.apache.sling", "org.apache.sling.commons.logservice", "1.0.2"), mavenBundle("org.slf4j", "slf4j-api", "1.6.4"), mavenBundle("org.slf4j", "jcl-over-slf4j", "1.6.4"), mavenBundle("org.slf4j", "log4j-over-slf4j", "1.6.4"), mavenBundle("org.apache.felix", "org.apache.felix.scr", "1.8.0"), mavenBundle("org.apache.felix", "org.apache.felix.configadmin", "1.2.8"), mavenBundle("org.apache.felix", "org.apache.felix.metatype", "1.0.2"), mavenBundle("org.apache.sling", "org.apache.sling.installer.core", POM_VERSION), mavenBundle("org.apache.sling", "org.apache.sling.installer.factory.configuration", CONFIG_VERSION) ) ); } protected Object startObservingBundleEvents() { final BundleEventListener listener = new BundleEventListener(); this.bundleContext.addBundleListener(listener); return listener; } public static final class BundleEvent { public final String symbolicName; public final Version version; public final int state; public BundleEvent(final String sn, final String v, final int s) { this.symbolicName = sn; this.version = (v == null ? null : Version.parseVersion(v)); this.state = s; } public BundleEvent(final String sn, final int s) { this(sn, null, s); } @Override public String toString() { return "BundleEvent " + symbolicName + ", version=" + version + ", state="+state; } } protected void waitForBundleEvents(final String msg, final Object l, BundleEvent... events) throws Exception { final BundleEventListener listener = (BundleEventListener)l; try { listener.wait(msg, events, WAIT_FOR_ACTION_TIMEOUT_MSEC); } finally { this.bundleContext.removeBundleListener(listener); } } protected void waitForBundleEvents(final String msg, final Object l, long timeout, BundleEvent... events) throws Exception { final BundleEventListener listener = (BundleEventListener)l; try { listener.wait(msg, events, timeout); } finally { this.bundleContext.removeBundleListener(listener); } } protected void assertNoBundleEvents(final String msg, final Object l, final String symbolicName) { final BundleEventListener listener = (BundleEventListener)l; try { listener.assertNoBundleEvents(msg, symbolicName); } finally { this.bundleContext.removeBundleListener(listener); } } protected boolean isPackageExported(Bundle b, String packageName) { final BundleWiring wiring = b.adapt(BundleWiring.class); assertNotNull("Expecting non-null BundleWiring for bundle " + b, wiring); for(BundleCapability c : wiring.getCapabilities(PackageNamespace.PACKAGE_NAMESPACE)) { if(packageName.equals(c.getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE))) { return true; } } return false; } public void logInstalledBundles() { for(Bundle b : bundleContext.getBundles()) { log(LogService.LOG_DEBUG, "Installed bundle: " + b.getSymbolicName()); } } private final class BundleEventListener implements SynchronousBundleListener { private final List<BundleEvent> events = new ArrayList<BundleEvent>(); public void bundleChanged(org.osgi.framework.BundleEvent event) { synchronized ( this ) { events.add(new BundleEvent(event.getBundle().getSymbolicName(), event.getBundle().getVersion().toString(), event.getType())); } } public void wait(final String msg, final BundleEvent[] checkEvents, final long timeoutMsec) throws Exception { if ( checkEvents == null || checkEvents.length == 0 ) { return; } final long start = System.currentTimeMillis(); final long end = start + timeoutMsec; log(LogService.LOG_DEBUG, "Starting event check at " + start + "; ending by " + end); while ( System.currentTimeMillis() < end ) { synchronized ( this) { if ( this.events.size() >= checkEvents.length ) { int found = 0; for(final BundleEvent e : checkEvents ) { int startIndex = 0; final int oldFound = found; while ( oldFound == found && startIndex < this.events.size() ) { final BundleEvent bundleEvent = this.events.get(startIndex); // first check symbolic name if ( e.symbolicName == null || e.symbolicName.equals(bundleEvent.symbolicName) ) { if ( e.version == null || e.version.equals(bundleEvent.version) ) { if ( e.state == bundleEvent.state ) { found++; } } } if ( oldFound == found ) { startIndex++; } } } if ( found == checkEvents.length ) { return; } } } sleep(100); } logInstalledBundles(); final StringBuilder sb = new StringBuilder(); sb.append(msg); sb.append(" : Expected events=[\n"); for(final BundleEvent be : checkEvents) { sb.append(be); sb.append("\n"); } sb.append("]\nreceived events=[\n"); for(final BundleEvent be : this.events) { sb.append(be); sb.append("\n"); } sb.append("]\n"); fail(sb.toString()); } public void assertNoBundleEvents(final String msg, final String symbolicName) { boolean found = false; synchronized ( this ) { if ( symbolicName == null ) { found = this.events.size() > 0; } else { for(BundleEvent e : this.events ) { if ( symbolicName.equals(e.symbolicName) ) { found = true; break; } } } } if ( found ) { fail(msg + " : Expected to receive no bundle events for bundle " + symbolicName); } } } }
package com.atlassian.maven.plugins.amps.product; import java.io.File; import java.io.IOException; import java.util.ArrayList; 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 com.atlassian.maven.plugins.amps.AbstractProductHandlerMojo; import com.atlassian.maven.plugins.amps.MavenContext; import com.atlassian.maven.plugins.amps.MavenGoals; import com.atlassian.maven.plugins.amps.Product; import com.atlassian.maven.plugins.amps.ProductArtifact; import com.atlassian.maven.plugins.amps.util.ConfigFileUtils; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import org.apache.commons.lang.StringUtils; import org.apache.maven.plugin.MojoExecutionException; import static com.atlassian.maven.plugins.amps.util.FileUtils.doesFileNameMatchArtifact; import static com.atlassian.maven.plugins.amps.util.ZipUtils.unzip; import static org.apache.commons.io.FileUtils.copyDirectory; import static org.apache.commons.io.FileUtils.copyFile; import static org.apache.commons.io.FileUtils.iterateFiles; import static org.apache.commons.io.FileUtils.moveDirectory; import static org.apache.commons.io.FileUtils.readFileToString; import static com.atlassian.maven.plugins.amps.util.ProjectUtils.createDirectory; public abstract class AbstractProductHandler extends AmpsProductHandler { private final PluginProvider pluginProvider; protected AbstractProductHandler(MavenContext context, MavenGoals goals, PluginProvider pluginProvider) { super(context, goals); this.pluginProvider = pluginProvider; } /** * Extracts the product and its home, prepares both and starts the product * @return the port */ public final int start(final Product ctx) throws MojoExecutionException { final File homeDir = extractAndProcessHomeDirectory(ctx); final File extractedApp = extractApplication(ctx, homeDir); final File finalApp = addArtifactsAndOverrides(ctx, homeDir, extractedApp); // Ask for the system properties (from the ProductHandler and from the pom.xml) Map<String, String> systemProperties = mergeSystemProperties(ctx); return startApplication(ctx, finalApp, homeDir, systemProperties); } protected final File extractAndProcessHomeDirectory(final Product ctx) throws MojoExecutionException { final File homeDir = getHomeDirectory(ctx); // Check if home directory was provided by the user if (StringUtils.isNotBlank(ctx.getDataHome())) { // Don't modify the home. Just use it. return homeDir; } // Create a home dir for the product in target final File productHomeData = getProductHomeData(ctx); if (productHomeData != null) { // Only create the home dir if it doesn't exist if (!homeDir.exists()) { extractProductHomeData(productHomeData, homeDir, ctx); // just in case homeDir.mkdir(); processHomeDirectory(ctx, homeDir); } // Always override files regardless of home directory existing or not overrideAndPatchHomeDir(homeDir, ctx); } return homeDir; } protected void extractProductHomeData(File productHomeData, File homeDir, Product ctx) throws MojoExecutionException { final File tmpDir = new File(getBaseDirectory(ctx), "tmp-resources"); tmpDir.mkdir(); try { if (productHomeData.isFile()) { File tmp = new File(getBaseDirectory(ctx), ctx.getId() + "-home"); unzip(productHomeData, tmpDir.getPath()); File[] topLevelFiles = tmpDir.listFiles(); if (topLevelFiles.length != 1) { Iterable<String> filenames = Iterables.transform(Arrays.asList(topLevelFiles), new Function<File, String>(){ @Override public String apply(File from) { return from.getName(); } }); throw new MojoExecutionException("Expected a single top-level directory in test resources. Got: " + Joiner.on(", ").join(filenames)); } copyDirectory(topLevelFiles[0], getBaseDirectory(ctx), true); moveDirectory(tmp, homeDir); } else if (productHomeData.isDirectory()) { copyDirectory(productHomeData, homeDir); } } catch (final IOException ex) { throw new MojoExecutionException("Unable to copy home directory", ex); } } /** * Takes 'app' (the file of the application - either .war or the exploded directory), * adds the artifacts, then returns the 'app'. * @return if {@code app} was a dir, returns a dir; if {@code app} was a war, returns a war. */ private final File addArtifactsAndOverrides(final Product ctx, final File homeDir, final File app) throws MojoExecutionException { try { final File appDir; if (app.isFile()) { appDir = new File(getBaseDirectory(ctx), "webapp"); if (!appDir.exists()) { unzip(app, appDir.getAbsolutePath()); } } else { appDir = app; } addArtifacts(ctx, homeDir, appDir); // override war files try { addOverrides(appDir, ctx); customiseInstance(ctx, homeDir, appDir); } catch (IOException e) { throw new MojoExecutionException("Unable to override WAR files using src/test/resources/" + ctx.getInstanceId() + "-app", e); } if (app.isFile()) { final File warFile = new File(app.getParentFile(), getId() + ".war"); com.atlassian.core.util.FileUtils.createZipFile(appDir, warFile); return warFile; } else { return appDir; } } catch (final Exception e) { throw new MojoExecutionException(e.getMessage(), e); } } /** * Each product handler can add specific operations on the application's home and war. * By default no operation is performed in this hook. * * <p>Example: StudioXXXProductHandlers can change the webapp to be studio-ready.</p> * @param ctx the product's details * @param homeDir the home directory * @param explodedWarDir the directory containing the exploded WAR of the application * @throws MojoExecutionException */ protected void customiseInstance(Product ctx, File homeDir, File explodedWarDir) throws MojoExecutionException { // No operation by default } private void addArtifacts(final Product ctx, final File homeDir, final File appDir) throws IOException, MojoExecutionException, Exception { File pluginsDir = getUserInstalledPluginsDirectory(appDir, homeDir); final File bundledPluginsDir = new File(getBaseDirectory(ctx), "bundled-plugins"); bundledPluginsDir.mkdir(); // add bundled plugins final File bundledPluginsZip = new File(appDir, getBundledPluginPath(ctx)); if (bundledPluginsZip.exists()) { unzip(bundledPluginsZip, bundledPluginsDir.getPath()); } if (isStaticPlugin()) { if (!supportsStaticPlugins()) { throw new MojoExecutionException("According to your atlassian-plugin.xml file, this plugin is not " + "atlassian-plugins version 2. This app currently only supports atlassian-plugins " + "version 2."); } pluginsDir = new File(appDir, "WEB-INF/lib"); } if (pluginsDir == null) { pluginsDir = bundledPluginsDir; } createDirectory(pluginsDir); // add this plugin itself if enabled if (ctx.isInstallPlugin()) { addThisPluginToDirectory(pluginsDir); addTestPluginToDirectory(pluginsDir); } // add plugins2 plugins if necessary if (!isStaticPlugin()) { addArtifactsToDirectory(pluginProvider.provide(ctx), pluginsDir); } // add plugins1 plugins List<ProductArtifact> artifacts = new ArrayList<ProductArtifact>(); artifacts.addAll(getDefaultLibPlugins()); artifacts.addAll(ctx.getLibArtifacts()); addArtifactsToDirectory(artifacts, new File(appDir, "WEB-INF/lib")); artifacts = new ArrayList<ProductArtifact>(); artifacts.addAll(getDefaultBundledPlugins()); artifacts.addAll(ctx.getBundledArtifacts()); addArtifactsToDirectory(artifacts, bundledPluginsDir); if (bundledPluginsDir.list().length > 0) { com.atlassian.core.util.FileUtils.createZipFile(bundledPluginsDir, bundledPluginsZip); } if (ctx.getLog4jProperties() != null && getLog4jPropertiesPath() != null) { copyFile(ctx.getLog4jProperties(), new File(appDir, getLog4jPropertiesPath())); } } /** * Processes standard replacement of configuration placeholders in the home directory. */ protected void processHomeDirectory(Product ctx, File snapshotDir) throws MojoExecutionException { ConfigFileUtils.replace(getConfigFiles(ctx, snapshotDir), getReplacements(ctx), false, log); } abstract protected File extractApplication(Product ctx, File homeDir) throws MojoExecutionException; abstract protected int startApplication(Product ctx, File app, File homeDir, Map<String, String> properties) throws MojoExecutionException; abstract protected boolean supportsStaticPlugins(); abstract protected Collection<? extends ProductArtifact> getDefaultBundledPlugins(); abstract protected Collection<? extends ProductArtifact> getDefaultLibPlugins(); abstract protected String getBundledPluginPath(Product ctx); abstract protected File getUserInstalledPluginsDirectory(File webappDir, File homeDir); protected String getLog4jPropertiesPath() { return null; } protected boolean isStaticPlugin() throws IOException { final File atlassianPluginXml = new File(project.getBasedir(), "src/main/resources/atlassian-plugin.xml"); if (atlassianPluginXml.exists()) { String text = readFileToString(atlassianPluginXml); return !text.contains("pluginsVersion=\"2\"") && !text.contains("plugins-version=\"2\""); } else { // probably an osgi bundle return false; } } protected final void addThisPluginToDirectory(final File targetDir) throws IOException { final File thisPlugin = getPluginFile(); if (thisPlugin.exists()) { // remove any existing version for (final Iterator<?> iterateFiles = iterateFiles(targetDir, null, false); iterateFiles.hasNext();) { final File file = (File) iterateFiles.next(); if (doesFileNameMatchArtifact(file.getName(), project.getArtifactId())) { file.delete(); } } // add the plugin jar to the directory copyFile(thisPlugin, new File(targetDir, thisPlugin.getName())); } else { log.info("No plugin in the current project - " + thisPlugin.getAbsolutePath()); } } protected void addTestPluginToDirectory(final File targetDir) throws IOException { final File testPluginFile = getTestPluginFile(); if (testPluginFile.exists()) { // add the test plugin jar to the directory copyFile(testPluginFile, new File(targetDir, testPluginFile.getName())); } } protected final File getPluginFile() { return new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".jar"); } protected File getTestPluginFile() { return new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + "-tests.jar"); } protected final void addArtifactsToDirectory(final List<ProductArtifact> artifacts, final File pluginsDir) throws MojoExecutionException { // copy the all the plugins we want in the webapp if (!artifacts.isEmpty()) { // first remove plugins from the webapp that we want to update if (pluginsDir.isDirectory() && pluginsDir.exists()) { for (final Iterator<?> iterateFiles = iterateFiles(pluginsDir, null, false); iterateFiles.hasNext();) { final File file = (File) iterateFiles.next(); for (final ProductArtifact webappArtifact : artifacts) { if (!file.isDirectory() && doesFileNameMatchArtifact(file.getName(), webappArtifact.getArtifactId())) { file.delete(); } } } } goals.copyPlugins(pluginsDir, artifacts); } } protected final void addOverrides(File appDir, final Product ctx) throws IOException { final File srcDir = new File(project.getBasedir(), "src/test/resources/" + ctx.getInstanceId() + "-app"); if (srcDir.exists() && appDir.exists()) { copyDirectory(srcDir, appDir); } } /** * Merges the properties: pom.xml overrides {@link AbstractProductHandlerMojo#setDefaultValues} overrides the Product Handler. * @param ctx the Product * @return the complete list of system properties */ protected final Map<String, String> mergeSystemProperties(Product ctx) { final Map<String, String> properties = new HashMap<String, String>(); properties.putAll(getSystemProperties(ctx)); for (Map.Entry<String, Object> entry : ctx.getSystemPropertyVariables().entrySet()) { properties.put(entry.getKey(), (String) entry.getValue()); } return properties; } /** * System properties which are specific to the Product Handler */ protected abstract Map<String, String> getSystemProperties(Product ctx); /** * The artifact of the product (a war, a jar, a binary...) */ protected abstract ProductArtifact getArtifact(); }
/* * Copyright (C) 2015 Brian Wernick * * 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.devbrackets.android.exomedia; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Build; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.view.View; import android.widget.RemoteViews; /** * A class to help simplify notification creation and modification for * media playback applications. */ public class EMNotification { private Context context; private NotificationManager notificationManager; private NotificationInfo notificationInfo = new NotificationInfo(); private Class<? extends Service> mediaServiceClass; private RemoteViews customNotification; private RemoteViews bigContent; public EMNotification(Context context) { this.context = context; notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); } /** * Dismisses the current active notification */ public void dismiss() { if (notificationManager != null && notificationInfo != null) { notificationManager.cancel(notificationInfo.getNotificationId()); } } /** * Sets weather notifications are shown when audio is playing or * ready for playback (e.g. paused). The notification information * will need to be updated by calling {@link #setNotificationBaseInformation(int, int)} * and {@link #updateNotificationInformation(String, String, Bitmap, Bitmap)} and can be retrieved * with {@link #getNotification(android.app.PendingIntent)} * * @param enabled True if notifications should be shown */ public void setNotificationsEnabled(boolean enabled) { if (enabled == notificationInfo.getShowNotifications()) { return; } notificationInfo.setShowNotifications(enabled); //Remove the notification when disabling if (!enabled) { notificationManager.cancel(notificationInfo.getNotificationId()); } } /** * Sets the basic information for the notification that doesn't need to be updated. To enable the big * notification you will need to use {@link #setNotificationBaseInformation(int, int, Class)} instead * * @param notificationId The ID to specify this notification * @param appIcon The applications icon resource */ public void setNotificationBaseInformation(int notificationId, @DrawableRes int appIcon) { setNotificationBaseInformation(notificationId, appIcon, null); } /** * Sets the basic information for the notification that doesn't need to be updated. Additionally, when * the mediaServiceClass is set the big notification will send intents to that service to notify of * button clicks. These intents will have an action from * <ul> * <li>{@link EMRemoteActions#ACTION_STOP}</li> * <li>{@link EMRemoteActions#ACTION_PLAY_PAUSE}</li> * <li>{@link EMRemoteActions#ACTION_PREVIOUS}</li> * <li>{@link EMRemoteActions#ACTION_NEXT}</li> * </ul> * * @param notificationId The ID to specify this notification * @param appIcon The applications icon resource * @param mediaServiceClass The class for the service to notify of big notification actions */ public void setNotificationBaseInformation(int notificationId, @DrawableRes int appIcon, @Nullable Class<? extends Service> mediaServiceClass) { notificationInfo.setNotificationId(notificationId); notificationInfo.setAppIcon(appIcon); this.mediaServiceClass = mediaServiceClass; } /** * Sets the volatile information for the notification. This information is expected to * change frequently. * * @param title The title to display for the notification (e.g. A song name) * @param content A short description or additional information for the notification (e.g. An artists name) * @param notificationImage An image to display on the notification (e.g. Album artwork) * @param secondaryNotificationImage An image to display on the notification should be used to indicate playback type (e.g. Chromecast) */ public void updateNotificationInformation(String title, String content, @Nullable Bitmap notificationImage, @Nullable Bitmap secondaryNotificationImage) { updateNotificationInformation(title, content, notificationImage, secondaryNotificationImage, null); } /** * Sets the {@link PendingIntent} to call when the notification is clicked. * * @param pendingIntent The pending intent to use when the notification itself is clicked */ public void setClickPendingIntent(@Nullable PendingIntent pendingIntent) { notificationInfo.setPendingIntent(pendingIntent); } /** * Sets the volatile information for the notification. This information is expected to * change frequently. * * @param title The title to display for the notification (e.g. A song name) * @param content A short description or additional information for the notification (e.g. An artists name) * @param notificationImage An image to display on the notification (e.g. Album artwork) * @param secondaryNotificationImage An image to display on the notification should be used to indicate playback type (e.g. Chromecast) * @param notificationMediaState The current media state for the expanded (big) notification */ public void updateNotificationInformation(String title, String content, @Nullable Bitmap notificationImage, @Nullable Bitmap secondaryNotificationImage, @Nullable NotificationMediaState notificationMediaState) { notificationInfo.setTitle(title); notificationInfo.setContent(content); notificationInfo.setLargeImage(notificationImage); notificationInfo.setSecondaryImage(secondaryNotificationImage); notificationInfo.setMediaState(notificationMediaState); if (notificationInfo.getShowNotifications()) { notificationManager.notify(notificationInfo.getNotificationId(), getNotification(notificationInfo.getPendingIntent())); } } /** * Returns a fully constructed notification to use when moving a service to the * foreground. This should be called after the notification information is set with * {@link #setNotificationBaseInformation(int, int)} and {@link #updateNotificationInformation(String, String, Bitmap, Bitmap)}. * * @param pendingIntent The pending intent to use when the notification itself is clicked * @return The constructed notification */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public Notification getNotification(@Nullable PendingIntent pendingIntent) { setClickPendingIntent(pendingIntent); RemoteViews customNotificationViews = getCustomNotification(); boolean allowSwipe = notificationInfo.getMediaState() == null || !notificationInfo.getMediaState().isPlaying(); NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setContent(customNotificationViews); builder.setContentIntent(pendingIntent); builder.setDeleteIntent(createPendingIntent(EMRemoteActions.ACTION_STOP, mediaServiceClass)); builder.setSmallIcon(notificationInfo.getAppIcon()); builder.setAutoCancel(allowSwipe); builder.setOngoing(!allowSwipe); if (pendingIntent != null) { customNotificationViews.setOnClickPendingIntent(R.id.exomedia_notification_touch_area, pendingIntent); } //Set the notification category on lollipop if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setCategory(Notification.CATEGORY_STATUS); builder.setVisibility(Notification.VISIBILITY_PUBLIC); } //Build the notification and set the expanded content view if there is a service to inform of clicks Notification notification = builder.build(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && mediaServiceClass != null) { notification.bigContentView = getBigNotification(); notification.bigContentView.setOnClickPendingIntent(R.id.exomedia_big_notification_touch_area, pendingIntent); } return notification; } /** * Creates the RemoteViews used for the custom (standard) notification * * @return The resulting RemoteViews */ private RemoteViews getCustomNotification() { if (customNotification == null) { customNotification = new RemoteViews(context.getPackageName(), R.layout.exomedia_notification_content); customNotification.setOnClickPendingIntent(R.id.exomedia_notification_playpause, createPendingIntent(EMRemoteActions.ACTION_PLAY_PAUSE, mediaServiceClass)); customNotification.setOnClickPendingIntent(R.id.exomedia_notification_next, createPendingIntent(EMRemoteActions.ACTION_NEXT, mediaServiceClass)); customNotification.setOnClickPendingIntent(R.id.exomedia_notification_prev, createPendingIntent(EMRemoteActions.ACTION_PREVIOUS, mediaServiceClass)); } customNotification.setTextViewText(R.id.exomedia_notification_title, notificationInfo.getTitle()); customNotification.setTextViewText(R.id.exomedia_notification_content_text, notificationInfo.getContent()); customNotification.setBitmap(R.id.exomedia_notification_large_image, "setImageBitmap", notificationInfo.getLargeImage()); if (notificationInfo.getMediaState() != null) { updateCustomNotificationMediaState(customNotification); } return customNotification; } /** * Creates the RemoteViews used for the expanded (big) notification * * @return The resulting RemoteViews */ private RemoteViews getBigNotification() { if (bigContent == null) { bigContent = new RemoteViews(context.getPackageName(), R.layout.exomedia_big_notification_content); bigContent.setOnClickPendingIntent(R.id.exomedia_big_notification_close, createPendingIntent(EMRemoteActions.ACTION_STOP, mediaServiceClass)); bigContent.setOnClickPendingIntent(R.id.exomedia_big_notification_playpause, createPendingIntent(EMRemoteActions.ACTION_PLAY_PAUSE, mediaServiceClass)); bigContent.setOnClickPendingIntent(R.id.exomedia_big_notification_next, createPendingIntent(EMRemoteActions.ACTION_NEXT, mediaServiceClass)); bigContent.setOnClickPendingIntent(R.id.exomedia_big_notification_prev, createPendingIntent(EMRemoteActions.ACTION_PREVIOUS, mediaServiceClass)); } bigContent.setTextViewText(R.id.exomedia_big_notification_title, notificationInfo.getTitle()); bigContent.setTextViewText(R.id.exomedia_big_notification_content_text, notificationInfo.getContent()); bigContent.setBitmap(R.id.exomedia_big_notification_large_image, "setImageBitmap", notificationInfo.getLargeImage()); bigContent.setBitmap(R.id.exomedia_big_notification_secondary_image, "setImageBitmap", notificationInfo.getSecondaryImage()); //Makes sure the play/pause, next, and previous are displayed correctly if (notificationInfo.getMediaState() != null) { updateBigNotificationMediaState(bigContent); } return bigContent; } /** * Updates the images for the play/pause button so that only valid ones are * displayed with the correct state. * * @param customNotification The RemoteViews to use to modify the state */ private void updateCustomNotificationMediaState(RemoteViews customNotification) { NotificationMediaState state = notificationInfo.getMediaState(); if (customNotification == null || state == null) { return; } customNotification.setImageViewResource(R.id.exomedia_notification_playpause, state.isPlaying() ? R.drawable.exomedia_notification_pause : R.drawable.exomedia_notification_play); customNotification.setInt(R.id.exomedia_notification_prev, "setVisibility", state.isPreviousEnabled() ? View.VISIBLE : View.GONE); customNotification.setInt(R.id.exomedia_notification_next, "setVisibility", state.isNextEnabled() ? View.VISIBLE : View.GONE); } /** * Updates the images for the play/pause, next, and previous buttons so that only valid ones are * displayed with the correct state. * * @param bigContent The RemoteViews to use to modify the state */ private void updateBigNotificationMediaState(RemoteViews bigContent) { NotificationMediaState state = notificationInfo.getMediaState(); if (bigContent == null || state == null) { return; } bigContent.setImageViewResource(R.id.exomedia_big_notification_playpause, state.isPlaying() ? R.drawable.exomedia_notification_pause : R.drawable.exomedia_notification_play); bigContent.setInt(R.id.exomedia_big_notification_prev, "setVisibility", state.isPreviousEnabled() ? View.VISIBLE : View.INVISIBLE); bigContent.setInt(R.id.exomedia_big_notification_next, "setVisibility", state.isNextEnabled() ? View.VISIBLE : View.INVISIBLE); } /** * Creates a PendingIntent for the given action to the specified service * * @param action The action to use * @param serviceClass The service class to notify of intents * @return The resulting PendingIntent */ private PendingIntent createPendingIntent(String action, Class<? extends Service> serviceClass) { Intent intent = new Intent(context, serviceClass); intent.setAction(action); return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } public static class NotificationMediaState { private boolean isPlaying; private boolean isPreviousEnabled; private boolean isNextEnabled; public boolean isPlaying() { return isPlaying; } public boolean isPreviousEnabled() { return isPreviousEnabled; } public boolean isNextEnabled() { return isNextEnabled; } public void setPlaying(boolean isPlaying) { this.isPlaying = isPlaying; } public void setPreviousEnabled(boolean isPreviousEnabled) { this.isPreviousEnabled = isPreviousEnabled; } public void setNextEnabled(boolean isNextEnabled) { this.isNextEnabled = isNextEnabled; } } }
/* * Copyright 2003 - 2016 The eFaps Team * * 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.efaps.esjp.sales; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import org.efaps.admin.datamodel.Status; import org.efaps.admin.event.Parameter; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.db.CachedInstanceQuery; import org.efaps.db.CachedMultiPrintQuery; import org.efaps.db.CachedPrintQuery; import org.efaps.db.Instance; import org.efaps.db.PrintQuery; import org.efaps.db.QueryBuilder; import org.efaps.db.SelectBuilder; import org.efaps.esjp.ci.CIERP; import org.efaps.esjp.ci.CISales; import org.efaps.esjp.db.InstanceUtils; import org.efaps.esjp.erp.Currency; import org.efaps.esjp.erp.RateInfo; import org.efaps.esjp.products.Cost; import org.efaps.util.EFapsException; import org.joda.time.DateTime; /** * Contains method to calculate the costs for products. * * @author The eFaps Team * */ @EFapsUUID("586c03e5-1e3e-41ec-852d-6bca23559f2d") @EFapsApplication("eFapsApp-Sales") public abstract class Costs_Base extends Cost { /** * Eval acquisition cost. * * @param _parameter Parameter as passed by the eFaps API * @param _productInstance the product instance * @param _docInst the doc inst * @param _currenyInst the curreny inst * @return the big decimal * @throws EFapsException on error */ protected BigDecimal evalAcquisitionCost(final Parameter _parameter, final Instance _productInstance, final Instance _docInst, final Instance _currenyInst, final DateTime _date) throws EFapsException { final List<Instance> reTickInsts = getRecievingTicketInsts(_parameter, _productInstance, _docInst, _date); final List<CostBean> costs = new ArrayList<>(); for (final Instance reTickInst : reTickInsts) { final List<CostBean> tmpCosts = eval4Costing(_parameter, reTickInst, _productInstance); if (tmpCosts.isEmpty()) { costs.addAll(eval4Invoice(_parameter, reTickInst, _productInstance)); } else { costs.addAll(tmpCosts); } } return getCost(_parameter, costs, _currenyInst); } /** * Gets the cost. * * @param _parameter Parameter as passed by the eFaps API * @param _costs the costs * @param _currenyInst the curreny inst * @return the cost * @throws EFapsException on error */ protected BigDecimal getCost(final Parameter _parameter, final List<CostBean> _costs, final Instance _currenyInst) throws EFapsException { BigDecimal ret = BigDecimal.ZERO; // first priority have costing informations final List<CostBean> costings = _costs.stream().filter(_bean -> _bean.isCosting()).collect(Collectors.toList()); final Iterator<CostBean> iter; if (costings.isEmpty()) { iter = _costs.iterator(); } else { iter = costings.iterator(); } BigDecimal quantity = BigDecimal.ZERO; while (iter.hasNext()) { final CostBean bean = iter.next(); final BigDecimal currentCost = getCost4Curreny(_parameter, bean, _currenyInst); if (quantity.compareTo(BigDecimal.ZERO) == 0) { ret = currentCost; quantity = bean.getQuantity(); } else { ret = quantity.multiply(ret).add(bean.getQuantity().multiply(currentCost)).divide(quantity.add(bean .getQuantity()), 8, RoundingMode.HALF_UP); quantity = quantity.add(bean.getQuantity()); } } return ret; } /** * Gets the cost for curreny. * * @param _parameter Parameter as passed by the eFaps API * @param _costBean the cost bean * @param _currenyInst the curreny inst * @return the cost for curreny * @throws EFapsException on error */ protected BigDecimal getCost4Curreny(final Parameter _parameter, final CostBean _costBean, final Instance _currenyInst) throws EFapsException { final BigDecimal ret; if (_costBean.getRateCurInst().equals(_currenyInst)) { ret = _costBean.getRateNetUnitPrice(); } else if (_costBean.getCurInst().equals(_currenyInst)) { ret = _costBean.getNetUnitPrice(); } else { final RateInfo rateInfo = new Currency().evaluateRateInfo(_parameter, _costBean.getDate(), _currenyInst); final BigDecimal rate = RateInfo.getRate(_parameter, rateInfo, CISales.RecievingTicket.getType().getName()); ret = _costBean.getNetUnitPrice().multiply(rate); } return ret; } /** * Eval for costing. * * @param _parameter Parameter as passed by the eFaps API * @param _reTickInst the re tick inst * @param _productInstance the product instance * @return the list< cost bean> * @throws EFapsException on error */ protected List<CostBean> eval4Costing(final Parameter _parameter, final Instance _reTickInst, final Instance _productInstance) throws EFapsException { final List<CostBean> ret = new ArrayList<>(); final QueryBuilder docAttrQueryBldr = new QueryBuilder(CISales.AcquisitionCosting); docAttrQueryBldr.addWhereAttrNotEqValue(CISales.AcquisitionCosting.Status, Status.find(CISales.AcquisitionCostingStatus.Canceled)); final QueryBuilder relAttrQueryBldr = new QueryBuilder(CISales.AcquisitionCosting2RecievingTicket); relAttrQueryBldr.addWhereAttrEqValue(CISales.AcquisitionCosting2RecievingTicket.ToLink, _reTickInst); relAttrQueryBldr.addWhereAttrInQuery(CISales.AcquisitionCosting2RecievingTicket.FromLink, docAttrQueryBldr.getAttributeQuery(CISales.AcquisitionCosting.ID)); final QueryBuilder posQueryBldr = new QueryBuilder(CISales.AcquisitionCostingPosition); posQueryBldr.addWhereAttrEqValue(CISales.AcquisitionCostingPosition.Product, _productInstance); posQueryBldr.addWhereAttrInQuery(CISales.AcquisitionCostingPosition.AcquisitionCostingLink, relAttrQueryBldr .getAttributeQuery(CISales.AcquisitionCosting2RecievingTicket.FromLink)); final CachedMultiPrintQuery multi = posQueryBldr.getCachedPrint4Request(); final SelectBuilder selDate = SelectBuilder.get() .linkto(CISales.AcquisitionCostingPosition.AcquisitionCostingLink) .attribute(CISales.AcquisitionCosting.Date); final SelectBuilder selCurInst = SelectBuilder.get().linkto(CISales.AcquisitionCostingPosition.CurrencyId) .instance(); final SelectBuilder selRateCurInst = SelectBuilder.get() .linkto(CISales.AcquisitionCostingPosition.RateCurrencyId) .instance(); multi.addSelect(selDate, selCurInst, selRateCurInst); multi.addAttribute(CISales.AcquisitionCostingPosition.NetUnitPrice, CISales.AcquisitionCostingPosition.RateNetUnitPrice, CISales.AcquisitionCostingPosition.Quantity); multi.execute(); while (multi.next()) { ret.add(new CostBean() .setCosting(true) .setDate(multi.getSelect(selDate)) .setCurInst(multi.getSelect(selCurInst)) .setRateCurInst(multi.getSelect(selRateCurInst)) .setQuantity(multi.getAttribute(CISales.AcquisitionCostingPosition.Quantity)) .setNetUnitPrice(multi.getAttribute(CISales.AcquisitionCostingPosition.NetUnitPrice)) .setRateNetUnitPrice( multi.getAttribute(CISales.AcquisitionCostingPosition.RateNetUnitPrice))); } return ret; } /** * Eval for invoice. * * @param _parameter Parameter as passed by the eFaps API * @param _reTickInst the re tick inst * @param _productInstance the product instance * @return the list< cost bean> * @throws EFapsException on error */ protected List<CostBean> eval4Invoice(final Parameter _parameter, final Instance _reTickInst, final Instance _productInstance) throws EFapsException { final List<CostBean> ret = new ArrayList<>(); final QueryBuilder docAttrQueryBldr = new QueryBuilder(CISales.IncomingInvoice); docAttrQueryBldr.addWhereAttrNotEqValue(CISales.IncomingInvoice.Status, Status.find(CISales.IncomingInvoiceStatus.Replaced)); final QueryBuilder relAttrQueryBldr = new QueryBuilder(CISales.IncomingInvoice2RecievingTicket); relAttrQueryBldr.addWhereAttrEqValue(CISales.IncomingInvoice2RecievingTicket.ToLink, _reTickInst); relAttrQueryBldr.addWhereAttrInQuery(CISales.IncomingInvoice2RecievingTicket.FromLink, docAttrQueryBldr.getAttributeQuery(CISales.IncomingInvoice.ID)); final QueryBuilder posQueryBldr = new QueryBuilder(CISales.IncomingInvoicePosition); posQueryBldr.addWhereAttrEqValue(CISales.IncomingInvoicePosition.Product, _productInstance); posQueryBldr.addWhereAttrInQuery(CISales.IncomingInvoicePosition.IncomingInvoice, relAttrQueryBldr .getAttributeQuery(CISales.IncomingInvoice2RecievingTicket.FromLink)); final CachedMultiPrintQuery multi = posQueryBldr.getCachedPrint4Request(); final SelectBuilder selDate = SelectBuilder.get().linkto(CISales.IncomingInvoicePosition.IncomingInvoice) .attribute(CISales.IncomingInvoice.Date); final SelectBuilder selCurInst = SelectBuilder.get().linkto(CISales.IncomingInvoicePosition.CurrencyId) .instance(); final SelectBuilder selRateCurInst = SelectBuilder.get().linkto(CISales.IncomingInvoicePosition.RateCurrencyId) .instance(); multi.addSelect(selDate, selCurInst, selRateCurInst); multi.addAttribute(CISales.IncomingInvoicePosition.NetUnitPrice, CISales.IncomingInvoicePosition.RateNetUnitPrice, CISales.IncomingInvoicePosition.Quantity); multi.execute(); while (multi.next()) { ret.add(new CostBean() .setDate(multi.getSelect(selDate)) .setCurInst(multi.getSelect(selCurInst)) .setRateCurInst(multi.getSelect(selRateCurInst)) .setQuantity(multi.getAttribute(CISales.IncomingInvoicePosition.Quantity)) .setNetUnitPrice(multi.getAttribute(CISales.IncomingInvoicePosition.NetUnitPrice)) .setRateNetUnitPrice(multi.getAttribute(CISales.IncomingInvoicePosition.RateNetUnitPrice))); } return ret; } /** * Gets the recieving ticket insts. * * @param _parameter Parameter as passed by the eFaps API * @param _productInstance the product instance * @param _docInst the doc inst * @param _date the date * @return the recieving ticket insts * @throws EFapsException on error */ protected List<Instance> getRecievingTicketInsts(final Parameter _parameter, final Instance _productInstance, final Instance _docInst, final DateTime _date) throws EFapsException { final List<Instance> ret = new ArrayList<>(); // if the start doc is a recievingticket, verify it if (InstanceUtils.isType(_docInst, CISales.RecievingTicket)) { final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.IncomingInvoice); attrQueryBldr.addWhereAttrNotEqValue(CISales.IncomingInvoice.Status, Status.find( CISales.IncomingInvoiceStatus.Replaced)); final QueryBuilder queryBldr = new QueryBuilder(CISales.IncomingInvoice2RecievingTicket); queryBldr.addWhereAttrEqValue(CISales.IncomingInvoice2RecievingTicket.ToLink, _docInst); queryBldr.addWhereAttrInQuery(CISales.IncomingInvoice2RecievingTicket.FromLink, attrQueryBldr .getAttributeQuery(CISales.IncomingInvoice.ID)); final CachedInstanceQuery query = queryBldr.getCachedQuery4Request(); query.executeWithoutAccessCheck(); if (query.next()) { ret.add(_docInst); } } if (ret.isEmpty()) { final DateTime date; if (InstanceUtils.isKindOf(_docInst, CIERP.DocumentAbstract)) { final PrintQuery print = CachedPrintQuery.get4Request(_docInst); print.addAttribute(CIERP.DocumentAbstract.Date); print.executeWithoutAccessCheck(); date = print.getAttribute(CIERP.DocumentAbstract.Date); } else { date = _date; } // must have a valid invoice or valid costing final QueryBuilder invAttrQueryBldr = new QueryBuilder(CISales.IncomingInvoice); invAttrQueryBldr.addWhereAttrNotEqValue(CISales.IncomingInvoice.Status, Status.find( CISales.IncomingInvoiceStatus.Replaced)); final QueryBuilder costAttrQueryBldr = new QueryBuilder(CISales.AcquisitionCosting); costAttrQueryBldr.addWhereAttrNotEqValue(CISales.AcquisitionCosting.Status, Status.find( CISales.AcquisitionCostingStatus.Canceled)); // must be related to an invoice final QueryBuilder relAttrQueryBldr = new QueryBuilder(CISales.AcquisitionCosting2RecievingTicket); relAttrQueryBldr.addType(CISales.IncomingInvoice2RecievingTicket); relAttrQueryBldr.setOr(true); relAttrQueryBldr.addWhereAttrInQuery(CISales.Document2DocumentAbstract.FromAbstractLink, invAttrQueryBldr .getAttributeQuery(CISales.IncomingInvoice.ID)); relAttrQueryBldr.addWhereAttrInQuery(CISales.Document2DocumentAbstract.FromAbstractLink, costAttrQueryBldr .getAttributeQuery(CISales.AcquisitionCosting.ID)); // must have a position with the given product final QueryBuilder posAttrQueryBldr = new QueryBuilder(CISales.RecievingTicketPosition); posAttrQueryBldr.addWhereAttrEqValue(CISales.RecievingTicketPosition.Product, _productInstance); // valid RecievingTicket with the same date or earlier, for the same // day (max 10 are evaluated) final QueryBuilder queryBldr = new QueryBuilder(CISales.RecievingTicket); queryBldr.addWhereAttrNotEqValue(CISales.RecievingTicket.Status, Status.find( CISales.RecievingTicketStatus.Canceled)); queryBldr.addWhereAttrLessValue(CISales.RecievingTicket.Date, date.withTimeAtStartOfDay().plusDays(1)); queryBldr.addWhereAttrInQuery(CISales.RecievingTicket.ID, relAttrQueryBldr.getAttributeQuery( CISales.Document2DocumentAbstract.ToAbstractLink)); queryBldr.addWhereAttrInQuery(CISales.RecievingTicket.ID, posAttrQueryBldr.getAttributeQuery( CISales.RecievingTicketPosition.RecievingTicket)); queryBldr.addOrderByAttributeDesc(CISales.RecievingTicket.Date); queryBldr.setLimit(10); final CachedMultiPrintQuery multi = queryBldr.getCachedPrint4Request(); multi.setEnforceSorted(true); multi.addAttribute(CISales.RecievingTicket.Date); multi.executeWithoutAccessCheck(); DateTime current = null; while (multi.next()) { if (current == null) { current = multi.<DateTime>getAttribute(CISales.RecievingTicket.Date).withTimeAtStartOfDay(); ret.add(multi.getCurrentInstance()); } else { final boolean invalid = current.isAfter(multi.<DateTime>getAttribute(CISales.RecievingTicket.Date) .withTimeAtStartOfDay()); if (invalid) { break; } else { ret.add(multi.getCurrentInstance()); } } } } return ret; } /** * Gets the acquisition cost. * * @param _parameter Parameter as passed by the eFaps API * @param _productInstance the product instance * @param _docInst the doc inst * @param _currenyInst the curreny inst * @return the acquisition cost * @throws EFapsException on error */ protected static BigDecimal getAcquisitionCost(final Parameter _parameter, final Instance _productInstance, final Instance _docInst, final Instance _currenyInst) throws EFapsException { return new Costs().evalAcquisitionCost(_parameter, _productInstance, _docInst, _currenyInst, null); } /** * Gets the acquisition cost for date. * * @param _parameter Parameter as passed by the eFaps API * @param _productInstance the product instance * @param _currenyInst the curreny inst * @param _date the date * @return the acquisition cost for date * @throws EFapsException on error */ protected static BigDecimal getAcquisitionCost4Date(final Parameter _parameter, final Instance _productInstance, final Instance _currenyInst, final DateTime _date) throws EFapsException { return new Costs().evalAcquisitionCost(_parameter, _productInstance, null, _currenyInst, _date); } /** * CostBean. */ public static class CostBean { /** The costing. */ private boolean costing; /** The date. */ private DateTime date; /** The cur inst. */ private Instance curInst; /** The rate cur inst. */ private Instance rateCurInst; /** The quantity. */ private BigDecimal quantity; /** The net unit price. */ private BigDecimal netUnitPrice; /** The rate net unit price. */ private BigDecimal rateNetUnitPrice; /** * Getter method for the instance variable {@link #curInst}. * * @return value of instance variable {@link #curInst} */ public Instance getCurInst() { return this.curInst; } /** * Setter method for instance variable {@link #curInst}. * * @param _curInst value for instance variable {@link #curInst} * @return the cost bean */ public CostBean setCurInst(final Instance _curInst) { this.curInst = _curInst; return this; } /** * Getter method for the instance variable {@link #rateCurInst}. * * @return value of instance variable {@link #rateCurInst} */ public Instance getRateCurInst() { return this.rateCurInst; } /** * Setter method for instance variable {@link #rateCurInst}. * * @param _rateCurInst value for instance variable {@link #rateCurInst} * @return the cost bean */ public CostBean setRateCurInst(final Instance _rateCurInst) { this.rateCurInst = _rateCurInst; return this; } /** * Getter method for the instance variable {@link #quantity}. * * @return value of instance variable {@link #quantity} */ public BigDecimal getQuantity() { return this.quantity; } /** * Setter method for instance variable {@link #quantity}. * * @param _quantity value for instance variable {@link #quantity} * @return the cost bean */ public CostBean setQuantity(final BigDecimal _quantity) { this.quantity = _quantity; return this; } /** * Getter method for the instance variable {@link #netUnitPrice}. * * @return value of instance variable {@link #netUnitPrice} */ public BigDecimal getNetUnitPrice() { return this.netUnitPrice; } /** * Setter method for instance variable {@link #netUnitPrice}. * * @param _netUnitPrice value for instance variable {@link #netUnitPrice} * @return the cost bean */ public CostBean setNetUnitPrice(final BigDecimal _netUnitPrice) { this.netUnitPrice = _netUnitPrice; return this; } /** * Getter method for the instance variable {@link #rateNetUnitPrice}. * * @return value of instance variable {@link #rateNetUnitPrice} */ public BigDecimal getRateNetUnitPrice() { return this.rateNetUnitPrice; } /** * Setter method for instance variable {@link #rateNetUnitPrice}. * * @param _rateNetUnitPrice value for instance variable {@link #rateNetUnitPrice} * @return the cost bean */ public CostBean setRateNetUnitPrice(final BigDecimal _rateNetUnitPrice) { this.rateNetUnitPrice = _rateNetUnitPrice; return this; } /** * Checks if is costing. * * @return true, if is costing */ public boolean isCosting() { return this.costing; } /** * Sets the costing. * * @param _costing the costing * @return the cost bean */ public CostBean setCosting(final boolean _costing) { this.costing = _costing; return this; } /** * Getter method for the instance variable {@link #date}. * * @return value of instance variable {@link #date} */ public DateTime getDate() { return this.date; } /** * Setter method for instance variable {@link #date}. * * @param _date value for instance variable {@link #date} * @return the cost bean */ public CostBean setDate(final DateTime _date) { this.date = _date; return this; } } }
/** * 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. */ package com.microsoft.azure.management.network.v2019_07_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.arm.resources.models.Resource; import com.microsoft.azure.arm.resources.models.GroupableResourceCore; import com.microsoft.azure.arm.resources.models.HasResourceGroup; import com.microsoft.azure.arm.model.Refreshable; import com.microsoft.azure.arm.model.Updatable; import com.microsoft.azure.arm.model.Appliable; import com.microsoft.azure.arm.model.Creatable; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.network.v2019_07_01.implementation.NetworkManager; import java.util.List; import com.microsoft.azure.management.network.v2019_07_01.implementation.SubnetInner; import com.microsoft.azure.management.network.v2019_07_01.implementation.PrivateEndpointInner; /** * Type representing PrivateEndpoint. */ public interface PrivateEndpoint extends HasInner<PrivateEndpointInner>, Resource, GroupableResourceCore<NetworkManager, PrivateEndpointInner>, HasResourceGroup, Refreshable<PrivateEndpoint>, Updatable<PrivateEndpoint.Update>, HasManager<NetworkManager> { /** * @return the etag value. */ String etag(); /** * @return the manualPrivateLinkServiceConnections value. */ List<PrivateLinkServiceConnection> manualPrivateLinkServiceConnections(); /** * @return the networkInterfaces value. */ List<NetworkInterface> networkInterfaces(); /** * @return the privateLinkServiceConnections value. */ List<PrivateLinkServiceConnection> privateLinkServiceConnections(); /** * @return the provisioningState value. */ ProvisioningState provisioningState(); /** * @return the subnet value. */ Subnet subnet(); /** * The entirety of the PrivateEndpoint definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate { } /** * Grouping of PrivateEndpoint definition stages. */ interface DefinitionStages { /** * The first stage of a PrivateEndpoint definition. */ interface Blank extends GroupableResourceCore.DefinitionWithRegion<WithGroup> { } /** * The stage of the PrivateEndpoint definition allowing to specify the resource group. */ interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup<WithCreate> { } /** * The stage of the privateendpoint definition allowing to specify Etag. */ interface WithEtag { /** * Specifies etag. * @param etag A unique read-only string that changes whenever the resource is updated * @return the next definition stage */ WithCreate withEtag(String etag); } /** * The stage of the privateendpoint definition allowing to specify ManualPrivateLinkServiceConnections. */ interface WithManualPrivateLinkServiceConnections { /** * Specifies manualPrivateLinkServiceConnections. * @param manualPrivateLinkServiceConnections A grouping of information about the connection to the remote resource. Used when the network admin does not have access to approve connections to the remote resource * @return the next definition stage */ WithCreate withManualPrivateLinkServiceConnections(List<PrivateLinkServiceConnection> manualPrivateLinkServiceConnections); } /** * The stage of the privateendpoint definition allowing to specify PrivateLinkServiceConnections. */ interface WithPrivateLinkServiceConnections { /** * Specifies privateLinkServiceConnections. * @param privateLinkServiceConnections A grouping of information about the connection to the remote resource * @return the next definition stage */ WithCreate withPrivateLinkServiceConnections(List<PrivateLinkServiceConnection> privateLinkServiceConnections); } /** * The stage of the privateendpoint definition allowing to specify ProvisioningState. */ interface WithProvisioningState { /** * Specifies provisioningState. * @param provisioningState The provisioning state of the private endpoint resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' * @return the next definition stage */ WithCreate withProvisioningState(ProvisioningState provisioningState); } /** * The stage of the privateendpoint definition allowing to specify Subnet. */ interface WithSubnet { /** * Specifies subnet. * @param subnet The ID of the subnet from which the private IP will be allocated * @return the next definition stage */ WithCreate withSubnet(SubnetInner subnet); } /** * The stage of the definition which contains all the minimum required inputs for * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ interface WithCreate extends Creatable<PrivateEndpoint>, Resource.DefinitionWithTags<WithCreate>, DefinitionStages.WithEtag, DefinitionStages.WithManualPrivateLinkServiceConnections, DefinitionStages.WithPrivateLinkServiceConnections, DefinitionStages.WithProvisioningState, DefinitionStages.WithSubnet { } } /** * The template for a PrivateEndpoint update operation, containing all the settings that can be modified. */ interface Update extends Appliable<PrivateEndpoint>, Resource.UpdateWithTags<Update>, UpdateStages.WithEtag, UpdateStages.WithManualPrivateLinkServiceConnections, UpdateStages.WithPrivateLinkServiceConnections, UpdateStages.WithProvisioningState, UpdateStages.WithSubnet { } /** * Grouping of PrivateEndpoint update stages. */ interface UpdateStages { /** * The stage of the privateendpoint update allowing to specify Etag. */ interface WithEtag { /** * Specifies etag. * @param etag A unique read-only string that changes whenever the resource is updated * @return the next update stage */ Update withEtag(String etag); } /** * The stage of the privateendpoint update allowing to specify ManualPrivateLinkServiceConnections. */ interface WithManualPrivateLinkServiceConnections { /** * Specifies manualPrivateLinkServiceConnections. * @param manualPrivateLinkServiceConnections A grouping of information about the connection to the remote resource. Used when the network admin does not have access to approve connections to the remote resource * @return the next update stage */ Update withManualPrivateLinkServiceConnections(List<PrivateLinkServiceConnection> manualPrivateLinkServiceConnections); } /** * The stage of the privateendpoint update allowing to specify PrivateLinkServiceConnections. */ interface WithPrivateLinkServiceConnections { /** * Specifies privateLinkServiceConnections. * @param privateLinkServiceConnections A grouping of information about the connection to the remote resource * @return the next update stage */ Update withPrivateLinkServiceConnections(List<PrivateLinkServiceConnection> privateLinkServiceConnections); } /** * The stage of the privateendpoint update allowing to specify ProvisioningState. */ interface WithProvisioningState { /** * Specifies provisioningState. * @param provisioningState The provisioning state of the private endpoint resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed' * @return the next update stage */ Update withProvisioningState(ProvisioningState provisioningState); } /** * The stage of the privateendpoint update allowing to specify Subnet. */ interface WithSubnet { /** * Specifies subnet. * @param subnet The ID of the subnet from which the private IP will be allocated * @return the next update stage */ Update withSubnet(SubnetInner subnet); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/services/conversion_custom_variable_service.proto package com.google.ads.googleads.v10.services; /** * <pre> * The result for the conversion custom variable mutate. * </pre> * * Protobuf type {@code google.ads.googleads.v10.services.MutateConversionCustomVariableResult} */ public final class MutateConversionCustomVariableResult extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v10.services.MutateConversionCustomVariableResult) MutateConversionCustomVariableResultOrBuilder { private static final long serialVersionUID = 0L; // Use MutateConversionCustomVariableResult.newBuilder() to construct. private MutateConversionCustomVariableResult(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MutateConversionCustomVariableResult() { resourceName_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MutateConversionCustomVariableResult(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MutateConversionCustomVariableResult( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); resourceName_ = s; break; } case 18: { com.google.ads.googleads.v10.resources.ConversionCustomVariable.Builder subBuilder = null; if (conversionCustomVariable_ != null) { subBuilder = conversionCustomVariable_.toBuilder(); } conversionCustomVariable_ = input.readMessage(com.google.ads.googleads.v10.resources.ConversionCustomVariable.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(conversionCustomVariable_); conversionCustomVariable_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.services.ConversionCustomVariableServiceProto.internal_static_google_ads_googleads_v10_services_MutateConversionCustomVariableResult_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.services.ConversionCustomVariableServiceProto.internal_static_google_ads_googleads_v10_services_MutateConversionCustomVariableResult_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult.class, com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult.Builder.class); } public static final int RESOURCE_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object resourceName_; /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1 [(.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } } /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1 [(.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONVERSION_CUSTOM_VARIABLE_FIELD_NUMBER = 2; private com.google.ads.googleads.v10.resources.ConversionCustomVariable conversionCustomVariable_; /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> * @return Whether the conversionCustomVariable field is set. */ @java.lang.Override public boolean hasConversionCustomVariable() { return conversionCustomVariable_ != null; } /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> * @return The conversionCustomVariable. */ @java.lang.Override public com.google.ads.googleads.v10.resources.ConversionCustomVariable getConversionCustomVariable() { return conversionCustomVariable_ == null ? com.google.ads.googleads.v10.resources.ConversionCustomVariable.getDefaultInstance() : conversionCustomVariable_; } /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v10.resources.ConversionCustomVariableOrBuilder getConversionCustomVariableOrBuilder() { return getConversionCustomVariable(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (conversionCustomVariable_ != null) { output.writeMessage(2, getConversionCustomVariable()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (conversionCustomVariable_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getConversionCustomVariable()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult)) { return super.equals(obj); } com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult other = (com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (hasConversionCustomVariable() != other.hasConversionCustomVariable()) return false; if (hasConversionCustomVariable()) { if (!getConversionCustomVariable() .equals(other.getConversionCustomVariable())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); if (hasConversionCustomVariable()) { hash = (37 * hash) + CONVERSION_CUSTOM_VARIABLE_FIELD_NUMBER; hash = (53 * hash) + getConversionCustomVariable().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * The result for the conversion custom variable mutate. * </pre> * * Protobuf type {@code google.ads.googleads.v10.services.MutateConversionCustomVariableResult} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.services.MutateConversionCustomVariableResult) com.google.ads.googleads.v10.services.MutateConversionCustomVariableResultOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.services.ConversionCustomVariableServiceProto.internal_static_google_ads_googleads_v10_services_MutateConversionCustomVariableResult_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.services.ConversionCustomVariableServiceProto.internal_static_google_ads_googleads_v10_services_MutateConversionCustomVariableResult_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult.class, com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult.Builder.class); } // Construct using com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); resourceName_ = ""; if (conversionCustomVariableBuilder_ == null) { conversionCustomVariable_ = null; } else { conversionCustomVariable_ = null; conversionCustomVariableBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v10.services.ConversionCustomVariableServiceProto.internal_static_google_ads_googleads_v10_services_MutateConversionCustomVariableResult_descriptor; } @java.lang.Override public com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult getDefaultInstanceForType() { return com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult build() { com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult buildPartial() { com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult result = new com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult(this); result.resourceName_ = resourceName_; if (conversionCustomVariableBuilder_ == null) { result.conversionCustomVariable_ = conversionCustomVariable_; } else { result.conversionCustomVariable_ = conversionCustomVariableBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult) { return mergeFrom((com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult other) { if (other == com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; onChanged(); } if (other.hasConversionCustomVariable()) { mergeConversionCustomVariable(other.getConversionCustomVariable()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object resourceName_ = ""; /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1 [(.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1 [(.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1 [(.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; onChanged(); return this; } /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1 [(.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); onChanged(); return this; } /** * <pre> * Returned for successful operations. * </pre> * * <code>string resource_name = 1 [(.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; onChanged(); return this; } private com.google.ads.googleads.v10.resources.ConversionCustomVariable conversionCustomVariable_; private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v10.resources.ConversionCustomVariable, com.google.ads.googleads.v10.resources.ConversionCustomVariable.Builder, com.google.ads.googleads.v10.resources.ConversionCustomVariableOrBuilder> conversionCustomVariableBuilder_; /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> * @return Whether the conversionCustomVariable field is set. */ public boolean hasConversionCustomVariable() { return conversionCustomVariableBuilder_ != null || conversionCustomVariable_ != null; } /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> * @return The conversionCustomVariable. */ public com.google.ads.googleads.v10.resources.ConversionCustomVariable getConversionCustomVariable() { if (conversionCustomVariableBuilder_ == null) { return conversionCustomVariable_ == null ? com.google.ads.googleads.v10.resources.ConversionCustomVariable.getDefaultInstance() : conversionCustomVariable_; } else { return conversionCustomVariableBuilder_.getMessage(); } } /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> */ public Builder setConversionCustomVariable(com.google.ads.googleads.v10.resources.ConversionCustomVariable value) { if (conversionCustomVariableBuilder_ == null) { if (value == null) { throw new NullPointerException(); } conversionCustomVariable_ = value; onChanged(); } else { conversionCustomVariableBuilder_.setMessage(value); } return this; } /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> */ public Builder setConversionCustomVariable( com.google.ads.googleads.v10.resources.ConversionCustomVariable.Builder builderForValue) { if (conversionCustomVariableBuilder_ == null) { conversionCustomVariable_ = builderForValue.build(); onChanged(); } else { conversionCustomVariableBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> */ public Builder mergeConversionCustomVariable(com.google.ads.googleads.v10.resources.ConversionCustomVariable value) { if (conversionCustomVariableBuilder_ == null) { if (conversionCustomVariable_ != null) { conversionCustomVariable_ = com.google.ads.googleads.v10.resources.ConversionCustomVariable.newBuilder(conversionCustomVariable_).mergeFrom(value).buildPartial(); } else { conversionCustomVariable_ = value; } onChanged(); } else { conversionCustomVariableBuilder_.mergeFrom(value); } return this; } /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> */ public Builder clearConversionCustomVariable() { if (conversionCustomVariableBuilder_ == null) { conversionCustomVariable_ = null; onChanged(); } else { conversionCustomVariable_ = null; conversionCustomVariableBuilder_ = null; } return this; } /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> */ public com.google.ads.googleads.v10.resources.ConversionCustomVariable.Builder getConversionCustomVariableBuilder() { onChanged(); return getConversionCustomVariableFieldBuilder().getBuilder(); } /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> */ public com.google.ads.googleads.v10.resources.ConversionCustomVariableOrBuilder getConversionCustomVariableOrBuilder() { if (conversionCustomVariableBuilder_ != null) { return conversionCustomVariableBuilder_.getMessageOrBuilder(); } else { return conversionCustomVariable_ == null ? com.google.ads.googleads.v10.resources.ConversionCustomVariable.getDefaultInstance() : conversionCustomVariable_; } } /** * <pre> * The mutated conversion custom variable with only mutable fields after * mutate. The field will only be returned when response_content_type is set * to "MUTABLE_RESOURCE". * </pre> * * <code>.google.ads.googleads.v10.resources.ConversionCustomVariable conversion_custom_variable = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v10.resources.ConversionCustomVariable, com.google.ads.googleads.v10.resources.ConversionCustomVariable.Builder, com.google.ads.googleads.v10.resources.ConversionCustomVariableOrBuilder> getConversionCustomVariableFieldBuilder() { if (conversionCustomVariableBuilder_ == null) { conversionCustomVariableBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v10.resources.ConversionCustomVariable, com.google.ads.googleads.v10.resources.ConversionCustomVariable.Builder, com.google.ads.googleads.v10.resources.ConversionCustomVariableOrBuilder>( getConversionCustomVariable(), getParentForChildren(), isClean()); conversionCustomVariable_ = null; } return conversionCustomVariableBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.services.MutateConversionCustomVariableResult) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v10.services.MutateConversionCustomVariableResult) private static final com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult(); } public static com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MutateConversionCustomVariableResult> PARSER = new com.google.protobuf.AbstractParser<MutateConversionCustomVariableResult>() { @java.lang.Override public MutateConversionCustomVariableResult parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MutateConversionCustomVariableResult(input, extensionRegistry); } }; public static com.google.protobuf.Parser<MutateConversionCustomVariableResult> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MutateConversionCustomVariableResult> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v10.services.MutateConversionCustomVariableResult getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.impl.auxiliary.modifiers; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.impl.compiled.ClsClassImpl; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.AnnotatedElementsSearch; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationMemberValue; import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightAnnotation; import org.jetbrains.plugins.groovy.transformations.immutable.GrImmutableUtils; import java.util.*; import static java.util.Collections.singletonMap; import static org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.*; import static org.jetbrains.plugins.groovy.lang.resolve.imports.GroovyImports.getAliasedShortNames; public final class GrAnnotationCollector { public static GrAnnotation @NotNull [] getResolvedAnnotations(@NotNull GrModifierList modifierList) { final GrAnnotation[] rawAnnotations = modifierList.getRawAnnotations(); if (!mayHaveAnnotationCollector(rawAnnotations)) return rawAnnotations; final List<GrAnnotation> result = new ArrayList<>(); for (GrAnnotation annotation : rawAnnotations) { final PsiAnnotation annotationCollector = findAnnotationCollector(annotation); if (annotationCollector != null) { if (!collectCompileDynamic(result, annotation)) { collectAnnotations(result, annotation, annotationCollector); } } else if (!collectHardcoded(result, annotation)) { result.add(annotation); } } return result.toArray(GrAnnotation.EMPTY_ARRAY); } /** * * @param list resulting collection of aliased annotations * @param alias alias annotation * @param annotationCollector @AnnotationCollector annotation used in alias declaration * @return set of used arguments of alias annotation */ @NotNull public static Set<String> collectAnnotations(@NotNull List<? super GrAnnotation> list, @NotNull GrAnnotation alias, @NotNull PsiAnnotation annotationCollector) { final PsiModifierList modifierList = (PsiModifierList)annotationCollector.getParent(); Map<String, Map<String, PsiNameValuePair>> annotations = new LinkedHashMap<>(); collectAliasedAnnotationsFromAnnotationCollectorValueAttribute(annotationCollector, annotations); collectAliasedAnnotationsFromAnnotationCollectorAnnotations(modifierList, annotations); final PsiManager manager = alias.getManager(); final GrAnnotationNameValuePair[] attributes = alias.getParameterList().getAttributes(); Set<String> allUsedAttrs = new LinkedHashSet<>(); for (Map.Entry<String, Map<String, PsiNameValuePair>> entry : annotations.entrySet()) { final String qname = entry.getKey(); if (qname.equals(alias.getQualifiedName())) { continue; } final PsiClass resolved = JavaPsiFacade.getInstance(alias.getProject()).findClass(qname, alias.getResolveScope()); if (resolved == null) continue; final GrLightAnnotation annotation = new GrLightAnnotation(manager, alias.getLanguage(), qname, (PsiModifierList)alias.getParent()); Set<String> usedAttrs = new LinkedHashSet<>(); for (GrAnnotationNameValuePair attr : attributes) { final String name = attr.getName() != null ? attr.getName() : "value"; if (resolved.findMethodsByName(name, false).length > 0) { annotation.addAttribute(attr); allUsedAttrs.add(name); usedAttrs.add(name); } } final Map<String, PsiNameValuePair> defaults = entry.getValue(); for (Map.Entry<String, PsiNameValuePair> defa : defaults.entrySet()) { if (!usedAttrs.contains(defa.getKey())) { annotation.addAttribute(defa.getValue()); } } list.add(annotation); } return allUsedAttrs; } private static void collectAliasedAnnotationsFromAnnotationCollectorAnnotations(@NotNull PsiModifierList modifierList, @NotNull Map<String, Map<String, PsiNameValuePair>> annotations) { PsiAnnotation[] rawAnnotations = modifierList instanceof GrModifierList ? ((GrModifierList)modifierList).getRawAnnotations() : modifierList.getAnnotations(); for (PsiAnnotation annotation : rawAnnotations) { final String qname = annotation.getQualifiedName(); if (qname == null || qname.equals(GROOVY_TRANSFORM_ANNOTATION_COLLECTOR) || qname.startsWith("java.lang.annotation")) continue; final PsiNameValuePair[] attributes = annotation.getParameterList().getAttributes(); for (PsiNameValuePair pair : attributes) { Map<String, PsiNameValuePair> map = annotations.get(qname); if (map == null) { map = new LinkedHashMap<>(); annotations.put(qname, map); } map.put(pair.getName() != null ? pair.getName() : "value", pair); } if (attributes.length == 0 && !annotations.containsKey(qname)) { annotations.put(qname, new LinkedHashMap<>()); } } } private static void collectAliasedAnnotationsFromAnnotationCollectorValueAttribute(@NotNull PsiAnnotation annotationCollector, @NotNull Map<String, Map<String, PsiNameValuePair>> annotations) { final PsiAnnotationMemberValue annotationsFromValue = annotationCollector.findAttributeValue("value"); if (annotationsFromValue instanceof GrAnnotationArrayInitializer) { for (GrAnnotationMemberValue member : ((GrAnnotationArrayInitializer)annotationsFromValue).getInitializers()) { if (member instanceof GrReferenceExpression) { final PsiElement resolved = ((GrReferenceExpression)member).resolve(); if (resolved instanceof PsiClass && ((PsiClass)resolved).isAnnotationType()) { annotations.put(((PsiClass)resolved).getQualifiedName(), new LinkedHashMap<>()); } } } } } @Nullable public static PsiAnnotation findAnnotationCollector(@Nullable PsiClass clazz) { if (clazz != null) { final PsiModifierList modifierList = clazz.getModifierList(); if (modifierList != null) { PsiAnnotation[] annotations = modifierList instanceof GrModifierList ? ((GrModifierList)modifierList).getRawAnnotations() : modifierList.getAnnotations(); for (PsiAnnotation annotation : annotations) { if (GROOVY_TRANSFORM_ANNOTATION_COLLECTOR.equals(annotation.getQualifiedName())) { return annotation; } } } } return null; } @Nullable public static PsiAnnotation findAnnotationCollector(@NotNull GrAnnotation annotation) { if (!mayHaveAnnotationCollector(annotation)) { return null; } PsiElement resolved = annotation.getClassReference().resolve(); if (resolved instanceof ClsClassImpl) { return findAnnotationCollector(((ClsClassImpl)resolved).getSourceMirrorClass()); } else if (resolved instanceof PsiClass) { return findAnnotationCollector((PsiClass)resolved); } else { return null; } } private static boolean mayHaveAnnotationCollector(GrAnnotation @NotNull [] rawAnnotations) { for (GrAnnotation annotation : rawAnnotations) { if (mayHaveAnnotationCollector(annotation)) { return true; } } return false; } private static boolean mayHaveAnnotationCollector(@NotNull GrAnnotation annotation) { String shortName = annotation.getShortName(); Set<String> allNames = allCollectorNames(annotation.getProject()); return allNames.contains(shortName) || ContainerUtil.exists(getAliasedShortNames(annotation, shortName), allNames::contains); } private static Set<String> allCollectorNames(@NotNull Project project) { return CachedValuesManager.getManager(project).getCachedValue(project, () -> { Set<String> result = new HashSet<>(); GlobalSearchScope scope = GlobalSearchScope.allScope(project); for (PsiClass collector : JavaPsiFacade.getInstance(project).findClasses(GROOVY_TRANSFORM_ANNOTATION_COLLECTOR, scope)) { AnnotatedElementsSearch.searchPsiClasses(collector, scope).forEach(aClass -> { ContainerUtil.addIfNotNull(result, aClass.getName()); return true; }); } return CachedValueProvider.Result.create(result, PsiModificationTracker.MODIFICATION_COUNT); }); } private static boolean collectHardcoded(@NotNull List<? super GrAnnotation> list, @NotNull GrAnnotation alias) { String fqn = alias.getQualifiedName(); if (GROOVY_TRANSFORM_IMMUTABLE.equals(fqn)) { GrImmutableUtils.collectImmutableAnnotations(alias, list); return true; } return collectCompileDynamic(list, alias); } private static boolean collectCompileDynamic(@NotNull List<? super GrAnnotation> list, @NotNull GrAnnotation alias) { if (GROOVY_TRANSFORM_COMPILE_DYNAMIC.equals(alias.getQualifiedName())) { PsiAnnotationOwner owner = alias.getOwner(); if (owner != null) { GrLightAnnotation annotation = new GrLightAnnotation( owner, alias, GROOVY_TRANSFORM_COMPILE_STATIC, singletonMap("value", "TypeCheckingMode.SKIP") ); list.add(annotation); } return true; } return false; } }
package recube.cobalt; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import android.content.Context; public class FileProc { GameView gameView; String fileName; FileInputStream fis; ObjectInputStream ois; FileOutputStream fos; ObjectOutputStream oos; public FileProc(GameView _gameView, String name) { gameView = _gameView; fileName = name; } public boolean InitInput() { try { fis = gameView.getContext().openFileInput(fileName); ois = new ObjectInputStream(fis); } catch (Exception e) { e.printStackTrace(); return false; } return true; } public boolean InitOutput() { try { fos = gameView.getContext().openFileOutput(fileName, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); } catch (Exception e) { e.printStackTrace(); return false; } return true; } public void DestInput() { if(fis != null) { try { ois.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } ois = null; fis = null; } } public void DestOutput() { if(fos != null) { try { oos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } oos = null; fos = null; } } public void WriteByte(byte d) { try { oos.writeByte(d); } catch (IOException e) { e.printStackTrace(); } } public void WriteChar(char d) { try { oos.writeChar(d); } catch (IOException e) { e.printStackTrace(); } } public void WriteShort(short d) { try { oos.writeShort(d); } catch (IOException e) { e.printStackTrace(); } } public void WriteInteger(int d) { try { oos.writeInt(d); } catch (IOException e) { e.printStackTrace(); } } public void WriteLong(long d) { try { oos.writeLong(d); } catch (IOException e) { e.printStackTrace(); } } public void WriteSingle(float d) { try { oos.writeFloat(d); } catch (IOException e) { e.printStackTrace(); } } public void WriteDouble(double d) { try { oos.writeDouble(d); } catch (IOException e) { e.printStackTrace(); } } public void WriteString(String d) { try { oos.writeChars(d); } catch (IOException e) { e.printStackTrace(); } } public void WriteUnicodeString(String d) { try { oos.writeUTF(d); } catch (IOException e) { e.printStackTrace(); } } public void WriteBoolean(boolean d) { try { oos.writeBoolean(d); } catch (IOException e) { e.printStackTrace(); } } public void Write(Object d) { try { oos.writeObject(d); } catch (IOException e) { e.printStackTrace(); } } public byte ReadByte() throws IOException { return ois.readByte(); } public char ReadChar() throws IOException { return ois.readChar(); } public short ReadShort() throws IOException { return ois.readShort(); } public int ReadInteger() throws IOException { return ois.readInt(); } public long ReadLong() throws IOException { return ois.readLong(); } public float ReadSingle() throws IOException { return ois.readFloat(); } public double ReadDouble() throws IOException { return ois.readDouble(); } public String ReadString() throws IOException { return ois.readLine(); } public String ReadUTF() throws IOException { return ois.readUTF(); } public boolean ReadBoolean() throws IOException { return ois.readBoolean(); } public Object Read() throws IOException, ClassNotFoundException { return ois.readObject(); } }
/* * 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 io.airlift.log; import io.airlift.units.DataSize; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.Objects; import java.util.Optional; import java.util.PriorityQueue; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static io.airlift.log.LogFileName.parseHistoryLogFileName; import static java.util.Objects.requireNonNull; @ThreadSafe final class LogHistoryManager { private final Path masterLogFile; private final long maxTotalSize; @GuardedBy("this") private long totalSize; @GuardedBy("this") private final PriorityQueue<LogFile> files = new PriorityQueue<>(); public LogHistoryManager(Path masterLogFile, DataSize maxTotalSize) { requireNonNull(masterLogFile, "masterLogFile is null"); requireNonNull(maxTotalSize, "maxTotalSize is null"); this.masterLogFile = masterLogFile; this.maxTotalSize = maxTotalSize.toBytes(); // list existing logs try { Files.list(masterLogFile.getParent()) .map(this::createLogFile) .filter(Optional::isPresent) .map(Optional::get) .forEach(files::add); totalSize = files.stream() .mapToLong(LogFile::getSize) .sum(); } catch (IOException e) { throw new UncheckedIOException("Unable to list existing history log files for " + masterLogFile, e); } pruneLogFilesIfNecessary(0); } public synchronized long getTotalSize() { return totalSize; } public synchronized Set<LogFileName> getFiles() { return files.stream() .map(LogFile::getLogFileName) .collect(toImmutableSet()); } public synchronized void pruneLogFilesIfNecessary(long otherDataSize) { while (totalSize + otherDataSize > maxTotalSize) { LogFile logFile = files.poll(); if (logFile == null) { break; } // always reduce the cached total file size as we will either delete the file or stop tracking it totalSize -= logFile.getSize(); // attempt to delete the file which may fail, because the file was already deleted or is not deletable // failure is ok as this is a best effort system try { Files.deleteIfExists(logFile.getPath()); } catch (IOException ignored) { } } } private Optional<LogFile> createLogFile(Path path) { Optional<LogFileName> logFileName = parseHistoryLogFileName(masterLogFile.getFileName().toString(), path.getFileName().toString()); if (!logFileName.isPresent()) { return Optional.empty(); } BasicFileAttributes fileAttributes; try { fileAttributes = Files.readAttributes(path, BasicFileAttributes.class); } catch (IOException e) { return Optional.empty(); } return Optional.of(new LogFile(path, logFileName.get(), fileAttributes.size())); } public synchronized void addFile(Path file, LogFileName fileName, long size) { files.add(new LogFile(file, fileName, size)); totalSize += size; } public synchronized boolean removeFile(Path path) { return files.stream() .filter(file -> file.getPath().equals(path)) .findFirst() .map(this::removeFile) .orElse(false); } private synchronized boolean removeFile(LogFile file) { if (!files.remove(file)) { return false; } totalSize -= file.getSize(); return true; } private static class LogFile implements Comparable<LogFile> { private final Path path; private final LogFileName logFileName; private final long size; public LogFile(Path path, LogFileName logFileName, long size) { this.path = requireNonNull(path, "path is null"); this.logFileName = requireNonNull(logFileName, "logFileName is null"); checkArgument(size >= 0, "size is negative"); this.size = size; } public Path getPath() { return path; } public LogFileName getLogFileName() { return logFileName; } public long getSize() { return size; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LogFile logFile = (LogFile) o; return logFileName.equals(logFile.logFileName); } @Override public int hashCode() { return Objects.hash(logFileName); } @Override public int compareTo(LogFile o) { return logFileName.compareTo(o.logFileName); } @Override public String toString() { return logFileName.toString(); } } }
package org.opencb.opencga.storage.core.variant.search; import com.google.common.collect.Iterators; import org.apache.commons.lang3.time.StopWatch; import org.opencb.biodata.models.variant.Variant; import org.opencb.commons.datastore.core.DataResult; import org.opencb.commons.datastore.core.ObjectMap; import org.opencb.commons.datastore.core.Query; import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.opencga.core.config.storage.StorageConfiguration; import org.opencb.opencga.core.response.VariantQueryResult; import org.opencb.opencga.storage.core.exceptions.StorageEngineException; import org.opencb.opencga.storage.core.exceptions.VariantSearchException; import org.opencb.opencga.storage.core.variant.VariantStorageEngine; import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor; import org.opencb.opencga.storage.core.variant.adaptors.VariantField; import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryException; import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam; import org.opencb.opencga.storage.core.variant.query.VariantQueryUtils; import org.opencb.opencga.storage.core.variant.search.solr.SolrNativeIterator; import org.opencb.opencga.storage.core.variant.search.solr.VariantSearchManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import static org.opencb.opencga.storage.core.variant.VariantStorageOptions.*; import static org.opencb.opencga.storage.core.variant.query.VariantQueryUtils.MODIFIER_QUERY_PARAMS; import static org.opencb.opencga.storage.core.variant.search.VariantSearchUtils.*; import static org.opencb.opencga.storage.core.variant.search.solr.VariantSearchManager.SEARCH_ENGINE_ID; /** * Query executor that joins results from {@link VariantSearchManager} and the underlying {@link VariantDBAdaptor}. * * Created on 01/04/19. * * @author Jacobo Coll &lt;jacobo167@gmail.com&gt; */ public class SearchIndexVariantQueryExecutor extends AbstractSearchIndexVariantQueryExecutor { private Logger logger = LoggerFactory.getLogger(SearchIndexVariantQueryExecutor.class); private boolean intersectActive; private boolean intersectAlways; private int intersectParamsThreshold; public SearchIndexVariantQueryExecutor(VariantDBAdaptor dbAdaptor, VariantSearchManager searchManager, String storageEngineId, String dbName, StorageConfiguration configuration, ObjectMap options) { super(dbAdaptor, searchManager, storageEngineId, dbName, configuration, options); intersectActive = getOptions().getBoolean(INTERSECT_ACTIVE.key(), INTERSECT_ACTIVE.defaultValue()); intersectAlways = getOptions().getBoolean(INTERSECT_ALWAYS.key(), INTERSECT_ALWAYS.defaultValue()); intersectParamsThreshold = getOptions().getInt(INTERSECT_PARAMS_THRESHOLD.key(), INTERSECT_PARAMS_THRESHOLD.defaultValue()); } public SearchIndexVariantQueryExecutor setIntersectActive(boolean intersectActive) { this.intersectActive = intersectActive; return this; } public SearchIndexVariantQueryExecutor setIntersectAlways(boolean intersectAlways) { this.intersectAlways = intersectAlways; return this; } public SearchIndexVariantQueryExecutor setIntersectParamsThreshold(int intersectParamsThreshold) { this.intersectParamsThreshold = intersectParamsThreshold; return this; } @Override public boolean canUseThisExecutor(Query query, QueryOptions options) throws StorageEngineException { return doQuerySearchManager(query, options) || doIntersectWithSearch(query, options); } @Override public DataResult<Long> count(Query query) { try { StopWatch watch = StopWatch.createStarted(); long count = searchManager.count(dbName, query); int time = (int) watch.getTime(TimeUnit.MILLISECONDS); return new DataResult<>(time, Collections.emptyList(), 1, Collections.singletonList(count), 1); } catch (IOException | VariantSearchException e) { throw new VariantQueryException("Error querying Solr", e); } } @Override protected Object getOrIterator(Query query, QueryOptions options, boolean iterator) { if (options == null) { options = QueryOptions.empty(); } if (doQuerySearchManager(query, options)) { try { if (iterator) { return searchManager.iterator(dbName, query, options); } else { return searchManager.query(dbName, query, options); } } catch (IOException | VariantSearchException e) { throw new VariantQueryException("Error querying Solr", e); } } else { // Intersect Solr+Engine int limit = options.getInt(QueryOptions.LIMIT, Integer.MAX_VALUE); int skip = options.getInt(QueryOptions.SKIP, 0); boolean pagination = !iterator || skip > 0; Iterator<?> variantsIterator; Number numTotalResults = null; AtomicLong searchCount = null; Boolean approxCount = null; Integer approxCountSamplingSize = null; Query searchEngineQuery = getSearchEngineQuery(query); Query engineQuery = getEngineQuery(query, options, getMetadataManager()); // Do not count for iterator if (!iterator) { if (isQueryCovered(query)) { // If the query is fully covered, the numTotalResults from solr is correct. searchCount = new AtomicLong(); numTotalResults = searchCount; // Skip count in storage. We already know the numTotalResults options.put(QueryOptions.COUNT, false); approxCount = false; } else if (options.getBoolean(APPROXIMATE_COUNT.key()) || options.getBoolean(QueryOptions.COUNT)) { options.put(QueryOptions.COUNT, false); VariantQueryResult<Long> result = approximateCount(query, options); numTotalResults = result.first(); approxCount = result.getApproximateCount(); approxCountSamplingSize = result.getApproximateCountSamplingSize(); } } if (pagination) { if (isQueryCovered(query)) { // We can use limit+skip directly in solr variantsIterator = variantIdIteratorFromSearch(searchEngineQuery, limit, skip, searchCount); // Remove limit and skip from Options for storage. The Search Engine already knows the pagination. options = new QueryOptions(options); options.remove(QueryOptions.LIMIT); options.remove(QueryOptions.SKIP); } else { logger.debug("Client side pagination. limit : {} , skip : {}", limit, skip); // Can't limit+skip only from solr. Need to limit+skip also in client side variantsIterator = variantIdIteratorFromSearch(searchEngineQuery); } } else { variantsIterator = variantIdIteratorFromSearch(searchEngineQuery, Integer.MAX_VALUE, 0, searchCount); } logger.debug("Intersect query " + engineQuery.toJson() + " options " + options.toJson()); if (iterator) { return dbAdaptor.iterator(variantsIterator, engineQuery, options); } else { setDefaultTimeout(options); VariantQueryResult<Variant> queryResult = dbAdaptor.get(variantsIterator, engineQuery, options); if (numTotalResults != null) { queryResult.setApproximateCount(approxCount); queryResult.setApproximateCountSamplingSize(approxCountSamplingSize); queryResult.setNumMatches(numTotalResults.longValue()); } queryResult.setSource(SEARCH_ENGINE_ID + '+' + getStorageEngineId()); return queryResult; } } } public VariantQueryResult<Long> approximateCount(Query query, QueryOptions options) { long count; boolean approxCount = true; int sampling = 0; StopWatch watch = StopWatch.createStarted(); try { if (doQuerySearchManager(query, new QueryOptions(QueryOptions.COUNT, true))) { approxCount = false; count = searchManager.count(dbName, query); } else { sampling = options.getInt(APPROXIMATE_COUNT_SAMPLING_SIZE.key(), getOptions().getInt(APPROXIMATE_COUNT_SAMPLING_SIZE.key(), APPROXIMATE_COUNT_SAMPLING_SIZE.defaultValue())); QueryOptions queryOptions = new QueryOptions(QueryOptions.INCLUDE, VariantField.ID).append(QueryOptions.LIMIT, sampling); Query searchEngineQuery = getSearchEngineQuery(query); Query engineQuery = getEngineQuery(query, options, getMetadataManager()); VariantQueryResult<VariantSearchModel> nativeResult = searchManager .nativeQuery(dbName, searchEngineQuery, queryOptions); List<String> variantIds = nativeResult.getResults().stream().map(VariantSearchModel::getId).collect(Collectors.toList()); // Adjust numSamples if the results from SearchManager is smaller than numSamples // If this happens, the count is not approximated if (variantIds.size() < sampling) { approxCount = false; sampling = variantIds.size(); } long numSearchResults = nativeResult.getNumTotalResults(); long numResults; if (variantIds.isEmpty()) { // Do not count if empty. It will not apply the filter and count through the whole database. numResults = 0; } else { engineQuery.put(VariantQueryUtils.ID_INTERSECT.key(), variantIds); numResults = dbAdaptor.count(engineQuery).first(); } logger.debug("NumResults: {}, NumSearchResults: {}, NumSamples: {}", numResults, numSearchResults, sampling); if (approxCount) { count = (long) ((numResults / (float) sampling) * numSearchResults); } else { count = numResults; } } } catch (IOException | VariantSearchException e) { throw new VariantQueryException("Error querying Solr", e); } int time = (int) watch.getTime(TimeUnit.MILLISECONDS); return new VariantQueryResult<>(time, 1, 1, Collections.emptyList(), Collections.singletonList(count), null, SEARCH_ENGINE_ID + '+' + getStorageEngineId(), approxCount, approxCount ? sampling : null, null); } /** * Decide if a query should be resolved using SearchManager or not. * * @param query Query * @param options QueryOptions * @return true if should resolve only with SearchManager */ public boolean doQuerySearchManager(Query query, QueryOptions options) { if (VariantStorageEngine.UseSearchIndex.from(options).equals(VariantStorageEngine.UseSearchIndex.NO)) { return false; } // else, YES or AUTO if (isQueryCovered(query) && isIncludeCovered(options)) { if (searchActiveAndAlive()) { return true; } } return false; } /** * Decide if a query should be resolved intersecting with SearchManager or not. * * @param query Query * @param options QueryOptions * @return true if should intersect */ public boolean doIntersectWithSearch(Query query, QueryOptions options) { VariantStorageEngine.UseSearchIndex useSearchIndex = VariantStorageEngine.UseSearchIndex.from(options); final boolean intersect; boolean active = searchActiveAndAlive(); if (useSearchIndex.equals(VariantStorageEngine.UseSearchIndex.NO)) { // useSearchIndex = NO intersect = false; } else if (!intersectActive) { // If intersect is not active, do not intersect. intersect = false; } else if (intersectAlways) { // If always intersect, intersect if available intersect = active; } else if (!active) { intersect = false; } else if (useSearchIndex.equals(VariantStorageEngine.UseSearchIndex.YES) || VariantQueryUtils.isValidParam(query, VariantQueryParam.ANNOT_TRAIT)) { intersect = true; } else { if (options.getBoolean(QueryOptions.COUNT)) { intersect = true; } else { // TODO: Improve this heuristic // Count only real params Collection<VariantQueryParam> coveredParams = coveredParams(query); coveredParams.removeAll(MODIFIER_QUERY_PARAMS); intersect = coveredParams.size() >= intersectParamsThreshold; } } if (!intersect) { if (useSearchIndex.equals(VariantStorageEngine.UseSearchIndex.YES)) { throw new VariantQueryException("Unable to use search index. SearchEngine is not available"); } else if (VariantQueryUtils.isValidParam(query, VariantQueryParam.ANNOT_TRAIT)) { throw VariantQueryException.unsupportedVariantQueryFilter(VariantQueryParam.ANNOT_TRAIT, getStorageEngineId(), "Search engine is required."); } } return intersect; } protected Iterator<String> variantIdIteratorFromSearch(Query query) { return variantIdIteratorFromSearch(query, Integer.MAX_VALUE, 0, null); } protected Iterator<String> variantIdIteratorFromSearch(Query query, int limit, int skip, AtomicLong numTotalResults) { Iterator<String> variantsIterator; QueryOptions queryOptions = new QueryOptions() .append(QueryOptions.LIMIT, limit) .append(QueryOptions.SKIP, skip) .append(QueryOptions.INCLUDE, VariantField.ID.fieldName()); try { // Do not iterate for small queries if (limit < 10000) { VariantQueryResult<VariantSearchModel> nativeResult = searchManager.nativeQuery(dbName, query, queryOptions); if (numTotalResults != null) { numTotalResults.set(nativeResult.getNumMatches()); } variantsIterator = nativeResult.getResults() .stream() .map(VariantSearchModel::getId) .iterator(); } else { SolrNativeIterator nativeIterator = searchManager.nativeIterator(dbName, query, queryOptions); if (numTotalResults != null) { numTotalResults.set(nativeIterator.getNumFound()); } variantsIterator = Iterators.transform(nativeIterator, VariantSearchModel::getId); } } catch (VariantSearchException | IOException e) { throw new VariantQueryException("Error querying " + VariantSearchManager.SEARCH_ENGINE_ID, e); } return variantsIterator; } }
/* * 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 io.trino.plugin.raptor.legacy.storage; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import io.airlift.units.Duration; import io.trino.client.NodeVersion; import io.trino.metadata.InternalNode; import io.trino.plugin.raptor.legacy.backup.BackupStore; import io.trino.plugin.raptor.legacy.metadata.ColumnInfo; import io.trino.plugin.raptor.legacy.metadata.MetadataDao; import io.trino.plugin.raptor.legacy.metadata.ShardInfo; import io.trino.plugin.raptor.legacy.metadata.ShardManager; import io.trino.plugin.raptor.legacy.metadata.ShardMetadata; import io.trino.spi.Node; import io.trino.spi.NodeManager; import io.trino.spi.predicate.TupleDomain; import io.trino.testing.TestingNodeManager; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.Jdbi; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.net.URI; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.Set; import java.util.UUID; import static com.google.common.io.Files.createTempDir; import static com.google.common.io.MoreFiles.deleteRecursively; import static com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE; import static io.trino.plugin.raptor.legacy.DatabaseTesting.createTestingJdbi; import static io.trino.plugin.raptor.legacy.metadata.SchemaDaoUtil.createTablesWithRetry; import static io.trino.plugin.raptor.legacy.metadata.TestDatabaseShardManager.createShardManager; import static io.trino.spi.type.BigintType.BIGINT; import static java.util.UUID.randomUUID; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.stream.Collectors.toSet; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestShardEjector { private Jdbi dbi; private Handle dummyHandle; private ShardManager shardManager; private File dataDir; private StorageService storageService; @BeforeMethod public void setup() { dbi = createTestingJdbi(); dummyHandle = dbi.open(); createTablesWithRetry(dbi); shardManager = createShardManager(dbi); dataDir = createTempDir(); storageService = new FileStorageService(dataDir); storageService.start(); } @AfterMethod(alwaysRun = true) public void teardown() throws Exception { if (dummyHandle != null) { dummyHandle.close(); } if (dataDir != null) { deleteRecursively(dataDir.toPath(), ALLOW_INSECURE); } } @Test(invocationCount = 20) public void testEjector() throws Exception { NodeManager nodeManager = createNodeManager("node1", "node2", "node3", "node4", "node5"); ShardEjector ejector = new ShardEjector( nodeManager.getCurrentNode().getNodeIdentifier(), nodeManager::getWorkerNodes, shardManager, storageService, new Duration(1, HOURS), Optional.of(new TestingBackupStore()), "test"); List<ShardInfo> shards = ImmutableList.<ShardInfo>builder() .add(shardInfo("node1", 14)) .add(shardInfo("node1", 13)) .add(shardInfo("node1", 12)) .add(shardInfo("node1", 11)) .add(shardInfo("node1", 10)) .add(shardInfo("node1", 10)) .add(shardInfo("node1", 10)) .add(shardInfo("node1", 10)) .add(shardInfo("node2", 5)) .add(shardInfo("node2", 5)) .add(shardInfo("node3", 10)) .add(shardInfo("node4", 10)) .add(shardInfo("node5", 10)) .add(shardInfo("node6", 200)) .build(); long tableId = createTable("test"); List<ColumnInfo> columns = ImmutableList.of(new ColumnInfo(1, BIGINT)); shardManager.createTable(tableId, columns, false, OptionalLong.empty()); long transactionId = shardManager.beginTransaction(); shardManager.commitShards(transactionId, tableId, columns, shards, Optional.empty(), 0); for (ShardInfo shard : shards.subList(0, 8)) { File file = storageService.getStorageFile(shard.getShardUuid()); storageService.createParents(file); assertTrue(file.createNewFile()); } ejector.process(); shardManager.getShardNodes(tableId, TupleDomain.all()); Set<UUID> ejectedShards = shards.subList(0, 4).stream() .map(ShardInfo::getShardUuid) .collect(toSet()); Set<UUID> keptShards = shards.subList(4, 8).stream() .map(ShardInfo::getShardUuid) .collect(toSet()); Set<UUID> remaining = uuids(shardManager.getNodeShards("node1")); for (UUID uuid : ejectedShards) { assertFalse(remaining.contains(uuid)); assertFalse(storageService.getStorageFile(uuid).exists()); } assertEquals(remaining, keptShards); for (UUID uuid : keptShards) { assertTrue(storageService.getStorageFile(uuid).exists()); } Set<UUID> others = ImmutableSet.<UUID>builder() .addAll(uuids(shardManager.getNodeShards("node2"))) .addAll(uuids(shardManager.getNodeShards("node3"))) .addAll(uuids(shardManager.getNodeShards("node4"))) .addAll(uuids(shardManager.getNodeShards("node5"))) .build(); assertTrue(others.containsAll(ejectedShards)); } private long createTable(String name) { return dbi.onDemand(MetadataDao.class).insertTable("test", name, false, false, null, 0); } private static Set<UUID> uuids(Set<ShardMetadata> metadata) { return metadata.stream() .map(ShardMetadata::getShardUuid) .collect(toSet()); } private static ShardInfo shardInfo(String node, long size) { return new ShardInfo(randomUUID(), OptionalInt.empty(), ImmutableSet.of(node), ImmutableList.of(), 1, size, size * 2, 0); } private static NodeManager createNodeManager(String current, String... others) { Node currentNode = createTestingNode(current); TestingNodeManager nodeManager = new TestingNodeManager(currentNode); for (String other : others) { nodeManager.addNode(createTestingNode(other)); } return nodeManager; } private static Node createTestingNode(String identifier) { return new InternalNode(identifier, URI.create("http://test"), NodeVersion.UNKNOWN, false); } private static class TestingBackupStore implements BackupStore { @Override public void backupShard(UUID uuid, File source) { throw new UnsupportedOperationException(); } @Override public void restoreShard(UUID uuid, File target) { throw new UnsupportedOperationException(); } @Override public boolean deleteShard(UUID uuid) { throw new UnsupportedOperationException(); } @Override public boolean shardExists(UUID uuid) { return true; } } }
// Copyright 2013 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.api.ads.adwords.awreporting.model.persistence.sql; import com.google.api.ads.adwords.awreporting.model.entities.AuthMcc; import com.google.api.ads.adwords.awreporting.model.entities.Report; import com.google.api.ads.adwords.awreporting.model.entities.ReportBase; import com.google.api.ads.adwords.awreporting.model.persistence.EntityPersister; import com.google.common.collect.Maps; import org.hibernate.Criteria; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.lang.reflect.Field; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.persistence.Column; import javax.persistence.Table; /** * This is the basic implementation of the persistence layer to communicate with a SQL data base. * * The communication is done using a generic {@link SessionFactory}, which allows this * implementation to talk to other data bases easily, but the intention is to specialize this class * to communicate in the best way possible to a SQL data base, so don't count in the use of the * {@code SessionFactory} when implementing your client class. * * @author gustavomoreira@google.com (Gustavo Moreira) */ @Component @Qualifier("sqlEntitiesPersister") public class SqlReportEntitiesPersister implements EntityPersister { private static final int BATCH_SIZE = 50; private SessionFactory sessionFactory; /** * C'tor * * @param sessionFactory the session factory to communicate with the DB */ @Autowired public SqlReportEntitiesPersister(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * Persists all the given entities into the DB configured in the {@code SessionFactory} */ @Override @Transactional public void persistReportEntities(List<? extends Report> reportEntities) { int batchFlush = 0; Session session = this.sessionFactory.getCurrentSession(); for (Report report : reportEntities) { report.setId(); session.saveOrUpdate(report); batchFlush++; if (batchFlush % BATCH_SIZE == 0) { session.flush(); session.clear(); } } } /** * Lists all the report entities persisted so far. * * Note that there is no pagination, so be careful when invoking this method. */ @Override @Transactional @SuppressWarnings("unchecked") public <T extends Report> List<T> listReports(Class<T> classT) { Criteria criteria = createCriteria(classT); return criteria.list(); } /** * Creates a new criteria for the current session * * @param classT the class of the entity * @return the criteria for the current session */ private <T> Criteria createCriteria(Class<T> classT) { Session session = this.sessionFactory.getCurrentSession(); return session.createCriteria(classT); } /** * Remove all the entities given in the {@code Collection}, that will be found in the DB. */ @Override @Transactional public void removeReportEntities(Collection<? extends Report> reportEntities) { Session session = this.sessionFactory.getCurrentSession(); for (Report report : reportEntities) { session.delete(report); } } /** * Create a paginated query * * @param classT the entity class * @param numToSkip the first result * @param limit the max number of results * @return the list of results */ private <T> Criteria createPaginatedCriteria(Class<T> classT, int numToSkip, int limit) { Criteria criteria = this.createCriteria(classT); criteria.setFirstResult(numToSkip); criteria.setMaxResults(limit); return criteria; } /** * Gets the entity list for the given report class. */ @Override @Transactional(readOnly = true) @SuppressWarnings("unchecked") public <T> List<T> get(Class<T> classT) { Criteria criteria = this.createCriteria(classT); return criteria.list(); } /** * Gets the entity list for the given report class. * * @param classT the report class * @param numToSkip the number to begin pagination * @param limit the number to limit the pagination */ @Override @Transactional(readOnly = true) @SuppressWarnings("unchecked") public <T> List<T> get(Class<T> classT, int numToSkip, int limit) { Criteria criteria = this.createPaginatedCriteria(classT, numToSkip, limit); return criteria.list(); } /** * Gets the entity list for the given report class and with the given value. */ @Override @Transactional(readOnly = true) @SuppressWarnings("unchecked") public <T, V> List<T> get(Class<T> classT, String key, V value) { Criteria criteria = this.createCriteria(classT); criteria.add(Restrictions.eq(key, value)); return criteria.list(); } /** * Gets the entity list for the given report class, with a key in those values * * @param classT the report class * @param key the name of the property * @param values the values that meet key */ @Override @Transactional(readOnly = true) @SuppressWarnings("unchecked") public <T, V> List<T> get(Class<T> classT, String key, List<V> values) { Criteria criteria = this.createCriteria(classT); if (key != null) { criteria.add(Restrictions.in(key, values)); } return criteria.list(); } /** * Gets the entity list for the given report class and with the given value. * * @param classT the report class * @param key the name of the property * @param value the value for the property * @param numToSkip the number to begin pagination * @param limit the number to be paginated */ @Override @Transactional(readOnly = true) @SuppressWarnings("unchecked") public <T, V> List<T> get(Class<T> classT, String key, V value, int numToSkip, int limit) { Criteria criteria = this.createPaginatedCriteria(classT, numToSkip, limit); criteria.add(Restrictions.eq(key, value)); return criteria.list(); } /** * Gets the entity list for the given report class and with the given date range. */ @Override @Transactional(readOnly = true) @SuppressWarnings("unchecked") public <T> List<T> get(Class<T> classT, String key, Object value, String dateKey, Date dateStart, Date dateEnd) { Criteria criteria = this.createCriteria(classT); if (key != null) { criteria.add(Restrictions.eq(key, value)); } criteria.add(Restrictions.ge(dateKey, dateStart)); criteria.add(Restrictions.le(dateKey, dateEnd)); return criteria.list(); } /** * Gets the entity list for the given report class and key the given range. */ @Override @Transactional(readOnly = true) @SuppressWarnings("unchecked") public <T> List<T> get(Class<T> classT, String key, Object value, String dateKey, String dateStart, String dateEnd) { Criteria criteria = this.createCriteria(classT); if (key != null) { criteria.add(Restrictions.eq(key, value)); } criteria.add(Restrictions.ge(dateKey, dateStart)); criteria.add(Restrictions.le(dateKey, dateEnd)); return criteria.list(); } /** * Gets the entity list for the given report class and with the given date range. */ @Override @Transactional(readOnly = true) @SuppressWarnings("unchecked") public <T> List<T> get(Class<T> classT, String key, Object value, String dateKey, Date dateStart, Date dateEnd, int numToSkip, int limit) { Criteria criteria = this.createPaginatedCriteria(classT, numToSkip, limit); criteria.add(Restrictions.eq(key, value)); criteria.add(Restrictions.ge(dateKey, dateStart)); criteria.add(Restrictions.le(dateKey, dateEnd)); return criteria.list(); } /** * Gets the entity list for the given report class and with the given map of values. */ @Override @Transactional(readOnly = true) @SuppressWarnings("unchecked") public <T, V> List<T> get(Class<T> classT, Map<String, V> keyValueList) { Criteria criteria = this.createCriteria(classT); for (Entry<String, V> entry : keyValueList.entrySet()) { criteria.add(Restrictions.eq(entry.getKey(), entry.getValue())); } return criteria.list(); } /** * Gets the entity list for the given report class and with the given map of values. */ @Override @Transactional(readOnly = true) @SuppressWarnings("unchecked") public <T, V> List<T> get(Class<T> classT, Map<String, V> keyValueList, int numToSkip, int limit) { Criteria criteria = this.createPaginatedCriteria(classT, numToSkip, limit); for (Entry<String, V> entry : keyValueList.entrySet()) { criteria.add(Restrictions.eq(entry.getKey(), entry.getValue())); } return criteria.list(); } /** * Removes the report entity. */ @Override @Transactional public <T> void remove(T t) { Session session = this.sessionFactory.getCurrentSession(); session.delete(t); } /** * Removes the report entity list. */ @Override @Transactional public <T> void remove(Collection<T> listT) { Session session = this.sessionFactory.getCurrentSession(); for (T t : listT) { session.delete(t); } } private <T> Field getField(Class<T> classT, String fieldName) throws NoSuchFieldException { try { return classT.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { Class<? super T> superClass = classT.getSuperclass(); if (superClass == null) { throw e; } else { return getField(superClass, fieldName); } } } /** * Removes the collection of entities by key,value * * @param classT the entity T class * @param key the property name * @param value the property value */ @Override @Transactional public <T, V> void remove(Class<T> classT, String key, V value) { remove(get(classT, key, value)); } /** * Removes the collection of entities by key,values * * @param classT the entity T class * @param key the property name * @param a list of values */ @Override @Transactional public <T, V> void remove(Class<T> classT, String key, List<V> values) { remove(get(classT, key, values)); } /** * Create a new Index on the "key" column */ @Override @Transactional public <T> void createIndex(Class<T> t, String key) { try { Table table = t.getAnnotation(Table.class); String tableName = table.name(); Field property = getField(t, key); Column column = property.getAnnotation(Column.class); String columnName = column.name(); String checkIndex = "SELECT COUNT(1) IndexIsThere FROM INFORMATION_SCHEMA.STATISTICS WHERE " + "Table_name='" + tableName + "' AND index_name='AW_INDEX_" + columnName + "'"; String newIndex = "ALTER TABLE " + tableName + " ADD INDEX " + "AW_INDEX_" + columnName + " ( " + columnName + " )" ; Session session = this.sessionFactory.getCurrentSession(); List<?> list = session.createSQLQuery(checkIndex).list(); if (String.valueOf(list.get(0)).equals("0")) { System.out.println( "Creating Index AW_INDEX_" + columnName +" ON " + tableName ); SQLQuery sqlQuery = session.createSQLQuery(newIndex); sqlQuery.executeUpdate(); } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } /** * Create a new composed Index with the the "keys" columns */ @Override @Transactional public <T> void createIndex(Class<T> t, List<String> keys) { try { Table table = t.getAnnotation(Table.class); String tableName = table.name(); String columnNames = ""; String columnIndexName = ""; int position = 0; for (String key : keys) { Field property = getField(t, key); Column column = property.getAnnotation(Column.class); if (position++ == 0) { columnNames += column.name(); columnIndexName += column.name(); } else { columnNames += "," + column.name(); columnIndexName += "_" + column.name(); } } String checkIndex = "SELECT COUNT(1) IndexIsThere FROM INFORMATION_SCHEMA.STATISTICS WHERE " + "Table_name='" + tableName + "' AND index_name='AW_INDEX_" + columnIndexName + "'"; String newIndex = "ALTER TABLE " + tableName + " ADD INDEX " + "AW_INDEX_" + columnIndexName + " ( " + columnNames + " )" ; Session session = this.sessionFactory.getCurrentSession(); List<?> list = session.createSQLQuery(checkIndex).list(); if (String.valueOf(list.get(0)).equals("0")) { System.out.println( "Creating Index AW_INDEX_" + columnIndexName +" ON " + tableName ); SQLQuery sqlQuery = session.createSQLQuery(newIndex); sqlQuery.executeUpdate(); } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } /** * @see com.google.api.ads.adwords.awreporting.model.persistence.EntityPersister * #save(com.google.api.ads.adwords.awreporting.model.entities.Report) */ @Override @Transactional public <T> T save(T t) { Session session = this.sessionFactory.getCurrentSession(); session.saveOrUpdate(t); return t; } /** * @see com.google.api.ads.adwords.awreporting.model.persistence.EntityPersister * #save(java.util.List) */ @Override @Transactional public <T> void save(List<T> reports) { Session session = this.sessionFactory.getCurrentSession(); for (T report : reports) { session.saveOrUpdate(report); } } /** * @see com.google.api.ads.adwords.awreporting.model.persistence.EntityPersister * #listMonthReports(Class, long, DateTime, DateTime) */ @Override @Transactional public <T extends Report> List<T> listMonthReports( Class<T> classT, long accountId, DateTime startDate, DateTime endDate) { Criteria criteria = this.createCriteria(classT); return this.listMonthReportsForCriteria(accountId, startDate, endDate, criteria); } /** * @see com.google.api.ads.adwords.awreporting.model.persistence. * EntityPersister#listMonthReports(Class, long, DateTime, DateTime, int, int) */ @Override @Transactional public <T extends Report> List<T> listMonthReports(Class<T> classT, long accountId, DateTime startDate, DateTime endDate, int page, int amount) { Criteria criteria = this.createPaginatedCriteria(classT, page, amount); return this.listMonthReportsForCriteria(accountId, startDate, endDate, criteria); } /** * @param startDate the start date * @param endDate the end date * @param criteria the criteria * @return the list of reports grouped by month */ @SuppressWarnings("unchecked") private <T extends Report> List<T> listMonthReportsForCriteria( long accountId, DateTime startDate, DateTime endDate, Criteria criteria) { criteria.add(Restrictions.isNull(ReportBase.DAY)); criteria.add(Restrictions.isNotNull(ReportBase.MONTH)); criteria.add(Restrictions.eq(ReportBase.ACCOUNT_ID, accountId)); criteria.addOrder(Order.asc(ReportBase.MONTH)); if (startDate != null) { criteria.add(Restrictions.ge(ReportBase.MONTH, startDate.toDate())); } if (endDate != null) { criteria.add(Restrictions.le(ReportBase.MONTH, endDate.toDate())); } return criteria.list(); } @Override @Transactional public <T extends ReportBase> Map<String, Object> getReportDataAvailableByDate(Class<T> classT, long topAccountId, String dateKey) { Map<String, Object> map = Maps.newHashMap(); if (!accountExists(topAccountId)) { map.put("error", "invalid_params"); map.put("message", "The requested MCC does not exist in the database."); } else { T tMin = getMinByDateKey(classT, topAccountId, dateKey); T tMax = getMaxByDateKey(classT, topAccountId, dateKey); if (tMax != null && tMin != null) { map.put("ReportType", classT.getSimpleName()); if (dateKey.equalsIgnoreCase(ReportBase.MONTH)) { map.put("startMonth", tMin.getMonth()); map.put("endMonth", tMax.getMonth()); } if (dateKey.equalsIgnoreCase(ReportBase.DAY)) { map.put("startDay", tMin.getDay()); map.put("endDay", tMax.getDay()); } } } return map; } @SuppressWarnings("unchecked") @Transactional public <T> T getMinByDateKey(Class<T> classT, long topAccountId, String dateKey) { if (!accountExists(topAccountId)) { return null; } else { Criteria criteriaMin = this.createCriteria(classT); criteriaMin.add(Restrictions.eq(Report.TOP_ACCOUNT_ID, topAccountId)); criteriaMin.add(Restrictions.isNotNull(dateKey)); criteriaMin.addOrder(Order.asc(dateKey)); criteriaMin.setFirstResult(0); criteriaMin.setMaxResults(1); return (T) criteriaMin.uniqueResult(); } } @SuppressWarnings("unchecked") @Transactional public <T> T getMaxByDateKey(Class<T> classT, long topAccountId, String dateKey) { if (!accountExists(topAccountId)) { return null; } else { Criteria criteriaMin = this.createCriteria(classT); criteriaMin.add(Restrictions.eq(Report.TOP_ACCOUNT_ID, topAccountId)); criteriaMin.add(Restrictions.isNotNull(dateKey)); criteriaMin.addOrder(Order.desc(dateKey)); criteriaMin.setFirstResult(0); criteriaMin.setMaxResults(1); return (T) criteriaMin.uniqueResult(); } } /** * Checks if the account exists in the datastore. This method does NOT validate an CID against AdWords. * @param topAccountId * @return true if account exists in datastore */ private boolean accountExists(long topAccountId) { List<AuthMcc> list = get(AuthMcc.class, AuthMcc.TOP_ACCOUNT_ID, String.valueOf(topAccountId)); if(list != null && !list.isEmpty()) { return true; } else { return false; } } }
package org.apache.maven.plugins.javadoc; /* * 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.util.Collection; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import org.apache.maven.doxia.siterenderer.RenderingContext; import org.apache.maven.doxia.siterenderer.sink.SiteRendererSink; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.reporting.MavenReport; import org.apache.maven.reporting.MavenReportException; import org.codehaus.doxia.sink.Sink; import org.codehaus.plexus.util.StringUtils; /** * Generates documentation for the <code>Java code</code> in an <b>NON aggregator</b> project using the standard * <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/javadoc/">Javadoc Tool</a>. * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> * @author <a href="mailto:vincent.siveton@gmail.com">Vincent Siveton</a> * @version $Id: JavadocReport.java 1800564 2017-07-02 14:08:18Z michaelo $ * @since 2.0 * @see <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/javadoc/">Javadoc Tool</a> * @see <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#options">Javadoc Options</a> */ @Mojo( name = "javadoc", requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true ) @Execute( phase = LifecyclePhase.GENERATE_SOURCES ) public class JavadocReport extends AbstractJavadocMojo implements MavenReport { // ---------------------------------------------------------------------- // Report Mojo Parameters // ---------------------------------------------------------------------- /** * Specifies the destination directory where javadoc saves the generated HTML files. */ @Parameter( property = "reportOutputDirectory", defaultValue = "${project.reporting.outputDirectory}/apidocs", required = true ) private File reportOutputDirectory; /** * The name of the destination directory. * <br/> * * @since 2.1 */ @Parameter( property = "destDir", defaultValue = "apidocs" ) private String destDir; /** * The name of the Javadoc report to be displayed in the Maven Generated Reports page * (i.e. <code>project-reports.html</code>). * * @since 2.1 */ @Parameter( property = "name" ) private String name; /** * The description of the Javadoc report to be displayed in the Maven Generated Reports page * (i.e. <code>project-reports.html</code>). * * @since 2.1 */ @Parameter( property = "description" ) private String description; // ---------------------------------------------------------------------- // Report public methods // ---------------------------------------------------------------------- /** {@inheritDoc} */ @Override public String getName( Locale locale ) { if ( StringUtils.isEmpty( name ) ) { return getBundle( locale ).getString( "report.javadoc.name" ); } return name; } /** {@inheritDoc} */ @Override public String getDescription( Locale locale ) { if ( StringUtils.isEmpty( description ) ) { return getBundle( locale ).getString( "report.javadoc.description" ); } return description; } /** {@inheritDoc} */ @Override public void generate( Sink sink, Locale locale ) throws MavenReportException { outputDirectory = getReportOutputDirectory(); try { executeReport( locale ); } catch ( MavenReportException e ) { if ( failOnError ) { throw e; } getLog().error( "Error while creating javadoc report: " + e.getMessage(), e ); } catch ( RuntimeException e ) { if ( failOnError ) { throw e; } getLog().error( "Error while creating javadoc report: " + e.getMessage(), e ); } } /** {@inheritDoc} */ @Override public String getOutputName() { return destDir + "/index"; } /** {@inheritDoc} */ @Override public boolean isExternalReport() { return true; } /** * {@inheritDoc} * * <br/> * The logic is the following: * <table> * <tbody> * <tr> * <th> isAggregator </th> * <th> hasSourceFiles </th> * <th> isRootProject </th> * <th> Generate Report </th> * </tr> * <tr> * <td>True</td> * <td>True</td> * <td>True</td> * <td>True</td> * </tr> * <tr> * <td>True</td> * <td>True</td> * <td>False</td> * <td>False</td> * </tr> * <tr> * <td>True</td> * <td>False</td> * <td>True</td> * <td>False</td> * </tr> * <tr> * <td>True</td> * <td>False</td> * <td>False</td> * <td>False</td> * </tr> * <tr> * <td>False</td> * <td>True</td> * <td>True</td> * <td>True</td> * </tr> * <tr> * <td>False</td> * <td>True</td> * <td>False</td> * <td>True</td> * </tr> * <tr> * <td>False</td> * <td>False</td> * <td>True</td> * <td>False</td> * </tr> * <tr> * <td>False</td> * <td>False</td> * <td>False</td> * <td>False</td> * </tr> * </tbody> * </table> */ @Override public boolean canGenerateReport() { boolean canGenerate = false; if ( !this.isAggregator() || ( this.isAggregator() && this.project.isExecutionRoot() ) ) { Collection<String> sourcePaths; List<String> files; try { sourcePaths = collect( getSourcePaths().values() ); files = getFiles( sourcePaths ); } catch ( MavenReportException e ) { getLog().error( e.getMessage(), e ); return false; } canGenerate = canGenerateReport( files ); } if ( getLog().isDebugEnabled() ) { getLog().debug( " canGenerateReport = " + canGenerate + " for project " + this.project ); } return canGenerate; } /** {@inheritDoc} */ @Override public String getCategoryName() { return CATEGORY_PROJECT_REPORTS; } /** {@inheritDoc} */ @Override public File getReportOutputDirectory() { if ( reportOutputDirectory == null ) { return outputDirectory; } return reportOutputDirectory; } /** * Method to set the directory where the generated reports will be put * * @param reportOutputDirectory the directory file to be set */ @Override public void setReportOutputDirectory( File reportOutputDirectory ) { updateReportOutputDirectory( reportOutputDirectory, destDir ); } /** * @param theDestDir The destiation directory. */ public void setDestDir( String theDestDir ) { this.destDir = theDestDir; updateReportOutputDirectory( reportOutputDirectory, theDestDir ); } private void updateReportOutputDirectory( File reportOutputDirectory, String destDir ) { if ( reportOutputDirectory != null && destDir != null && !reportOutputDirectory.getAbsolutePath().endsWith( destDir ) ) { this.reportOutputDirectory = new File( reportOutputDirectory, destDir ); } else { this.reportOutputDirectory = reportOutputDirectory; } } /** {@inheritDoc} */ @Override public void doExecute() throws MojoExecutionException, MojoFailureException { if ( skip ) { getLog().info( "Skipping javadoc generation" ); return; } try { RenderingContext context = new RenderingContext( outputDirectory, getOutputName() + ".html" ); SiteRendererSink sink = new SiteRendererSink( context ); Locale locale = Locale.getDefault(); generate( sink, locale ); } catch ( MavenReportException e ) { failOnError( "An error has occurred in " + getName( Locale.ENGLISH ) + " report generation", e ); } catch ( RuntimeException e ) { failOnError( "An error has occurred in " + getName( Locale.ENGLISH ) + " report generation", e ); } } /** * Gets the resource bundle for the specified locale. * * @param locale The locale of the currently generated report. * @return The resource bundle for the requested locale. */ private ResourceBundle getBundle( Locale locale ) { return ResourceBundle.getBundle( "javadoc-report", locale, getClass().getClassLoader() ); } }
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.matrix; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; import javax.annotation.Nonnull; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.io.file.FileHelper; import com.helger.commons.io.file.FileOperations; import com.helger.commons.string.StringHelper; /** * TestMatrix tests the functionality of the Jama MatrixInt class and associated * decompositions. * <P> * Run the test from the command line using <BLOCKQUOTE> * * <PRE> * <CODE> * java Jama.test.TestMatrix * </CODE> * </PRE> * * </BLOCKQUOTE> Detailed output is provided indicating the functionality being * tested and whether the functionality is correctly implemented. Exception * handling is also tested. * <P> * The test is designed to run to completion and give a summary of any * implementation errors encountered. The final output should be: <BLOCKQUOTE> * * <PRE> * <CODE> * TestMatrix completed. * Total errors reported: n1 * Total warning reported: n2 * </CODE> * </PRE> * * </BLOCKQUOTE> If the test does not run to completion, this indicates that * there is a substantial problem within the implementation that was not * anticipated in the test design. The stopping point should give an indication * of where the problem exists. **/ public final class MatrixIntTest { private static final Logger LOGGER = LoggerFactory.getLogger (MatrixIntTest.class); private static final File FILE_JAMA_TEST_MATRIX_OUT = new File ("Jamaout"); private static final double EPSILON = Math.pow (2.0, -52.0); private static final DecimalFormatSymbols DFS = DecimalFormatSymbols.getInstance (Locale.US); @Test public void testMain () { // Uncomment this to test IO in a different locale. // Locale.setDefault(Locale.GERMAN); int warningCount = 0; int tmp; final int [] columnwise = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; final int [] rowwise = { 1, 4, 7, 10, 2, 5, 8, 11, 3, 6, 9, 12 }; final int [] [] avals = { { 1, 4, 7, 10 }, { 2, 5, 8, 11 }, { 3, 6, 9, 12 } }; final int [] [] tvals = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } }; final int [] [] subavals = { { 5, 8, 11 }, { 6, 9, 12 } }; final int [] [] rvals = { { 1, 4, 7 }, { 2, 5, 8, 11 }, { 3, 6, 9, 12 } }; final int [] [] ivals = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 } }; final int [] [] square = { { 166, 188, 210 }, { 188, 214, 240 }, { 210, 240, 270 } }; final int rows = 3; final int cols = 4; /* * should trigger bad shape for construction with val */ final int invalidld = 5; /* * (raggedr,raggedc) should be out of bounds in ragged array */ final int raggedr = 0; final int raggedc = 4; /* leading dimension of intended test Matrices */ final int validld = 3; /* * leading dimension which is valid, but nonconforming */ final int nonconformld = 4; /* index ranges for sub MatrixInt */ final int ib = 1; final int ie = 2; final int jb = 1; final int je = 3; final int [] rowindexset = { 1, 2 }; final int [] badrowindexset = { 1, 3 }; final int [] columnindexset = { 1, 2, 3 }; final int [] badcolumnindexset = { 1, 2, 4 }; final int columnsummax = 33; final int rowsummax = 30; final int sumofdiagonals = 15; final int sumofsquares = 650; /** * Constructors and constructor-like methods: double[], int double[][] int, * int int, int, double int, int, double[][] constructWithCopy(double[][]) * random(int,int) identity(int) **/ _print ("\nTesting constructors and constructor-like methods...\n"); try { /** * _check that exception is thrown in packed constructor with invalid * length **/ new MatrixInt (columnwise, invalidld); fail ("exception not thrown for invalid input"); } catch (final IllegalArgumentException e) { _try_success ("Catch invalid length in packed constructor... ", e.getMessage ()); } try { /** * _check that exception is thrown in default constructor if input array * is 'ragged' **/ final MatrixInt a = new MatrixInt (rvals); tmp = a.get (raggedr, raggedc); } catch (final IllegalArgumentException e) { _try_success ("Catch ragged input to default constructor... ", e.getMessage ()); } catch (final ArrayIndexOutOfBoundsException e) { fail ("exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } try { /** * _check that exception is thrown in constructWithCopy if input array is * 'ragged' **/ final MatrixInt a = MatrixInt.constructWithCopy (rvals); tmp = a.get (raggedr, raggedc); } catch (final IllegalArgumentException e) { _try_success ("Catch ragged input to constructWithCopy... ", e.getMessage ()); } catch (final ArrayIndexOutOfBoundsException e) { fail ("exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } MatrixInt a = new MatrixInt (columnwise, validld); MatrixInt b = new MatrixInt (avals); tmp = b.get (0, 0); avals[0][0] = 0; MatrixInt C = b.minus (a); avals[0][0] = tmp; b = MatrixInt.constructWithCopy (avals); tmp = b.get (0, 0); avals[0][0] = 0; if ((tmp - b.get (0, 0)) != 0.0) { /** _check that constructWithCopy behaves properly **/ fail ("copy not effected... data visible outside"); } else { _try_success ("constructWithCopy... ", ""); } avals[0][0] = columnwise[0]; final MatrixInt I = new MatrixInt (ivals); try { _check (I, MatrixInt.identity (3, 4)); _try_success ("identity... ", ""); } catch (final RuntimeException e) { fail ("identity MatrixInt not successfully created"); } /** * Access Methods: getColumnDimension() getRowDimension() getArray() * getArrayCopy() getColumnPackedCopy() getRowPackedCopy() get(int,int) * getMatrix(int,int,int,int) getMatrix(int,int,int[]) * getMatrix(int[],int,int) getMatrix(int[],int[]) set(int,int,double) * setMatrix(int,int,int,int,MatrixInt) setMatrix(int,int,int[],MatrixInt) * setMatrix(int[],int,int,MatrixInt) setMatrix(int[],int[],MatrixInt) **/ _print ("\nTesting access methods...\n"); /** * Various get methods: **/ b = new MatrixInt (avals); if (b.getRowDimension () != rows) { fail (); } else { _try_success ("getRowDimension... ", ""); } if (b.getColumnDimension () != cols) { fail (); } else { _try_success ("getColumnDimension... ", ""); } b = new MatrixInt (avals); int [] [] barray = b.internalGetArray (); if (barray != avals) { fail (); } else { _try_success ("getArray... ", ""); } barray = b.getArrayCopy (); if (barray == avals) { fail ("data not (deep) copied"); } try { _check (barray, avals); _try_success ("getArrayCopy... ", ""); } catch (final RuntimeException e) { fail ("data not successfully (deep) copied"); } int [] bpacked = b.getColumnPackedCopy (); try { _check (bpacked, columnwise); _try_success ("getColumnPackedCopy... ", ""); } catch (final RuntimeException e) { fail ("data not successfully (deep) copied by columns"); } bpacked = b.getRowPackedCopy (); try { _check (bpacked, rowwise); _try_success ("getRowPackedCopy... ", ""); } catch (final RuntimeException e) { fail ("data not successfully (deep) copied by rows"); } try { tmp = b.get (b.getRowDimension (), b.getColumnDimension () - 1); fail ("OutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e) { try { tmp = b.get (b.getRowDimension () - 1, b.getColumnDimension ()); fail ("OutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e1) { _try_success ("get(int,int)... OutofBoundsException... ", ""); } } catch (final IllegalArgumentException e1) { fail ("OutOfBoundsException expected but not thrown"); } try { if (b.get (b.getRowDimension () - 1, b.getColumnDimension () - 1) != avals[b.getRowDimension () - 1][b.getColumnDimension () - 1]) { fail ("MatrixInt entry (i,j) not successfully retreived"); } else { _try_success ("get(int,int)... ", ""); } } catch (final ArrayIndexOutOfBoundsException e) { fail ("Unexpected ArrayIndexOutOfBoundsException"); } final MatrixInt SUB = new MatrixInt (subavals); MatrixInt M; try { M = b.getMatrix (ib, ie + b.getRowDimension () + 1, jb, je); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e) { try { M = b.getMatrix (ib, ie, jb, je + b.getColumnDimension () + 1); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e1) { _try_success ("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (final IllegalArgumentException e1) { fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = b.getMatrix (ib, ie, jb, je); try { _check (SUB, M); _try_success ("getMatrix(int,int,int,int)... ", ""); } catch (final RuntimeException e) { fail ("submatrix not successfully retreived"); } } catch (final ArrayIndexOutOfBoundsException e) { fail ("Unexpected ArrayIndexOutOfBoundsException"); } try { M = b.getMatrix (ib, ie, badcolumnindexset); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e) { try { M = b.getMatrix (ib, ie + b.getRowDimension () + 1, columnindexset); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e1) { _try_success ("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (final IllegalArgumentException e1) { fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = b.getMatrix (ib, ie, columnindexset); try { _check (SUB, M); _try_success ("getMatrix(int,int,int[])... ", ""); } catch (final RuntimeException e) { fail ("submatrix not successfully retreived"); } } catch (final ArrayIndexOutOfBoundsException e) { fail ("Unexpected ArrayIndexOutOfBoundsException"); } try { M = b.getMatrix (badrowindexset, jb, je); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e) { try { M = b.getMatrix (rowindexset, jb, je + b.getColumnDimension () + 1); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e1) { _try_success ("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (final IllegalArgumentException e1) { fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = b.getMatrix (rowindexset, jb, je); try { _check (SUB, M); _try_success ("getMatrix(int[],int,int)... ", ""); } catch (final RuntimeException e) { fail ("submatrix not successfully retreived"); } } catch (final ArrayIndexOutOfBoundsException e) { fail ("Unexpected ArrayIndexOutOfBoundsException"); } try { M = b.getMatrix (badrowindexset, columnindexset); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e) { try { M = b.getMatrix (rowindexset, badcolumnindexset); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e1) { _try_success ("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (final IllegalArgumentException e1) { fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = b.getMatrix (rowindexset, columnindexset); try { _check (SUB, M); _try_success ("getMatrix(int[],int[])... ", ""); } catch (final RuntimeException e) { fail ("submatrix not successfully retreived"); } } catch (final ArrayIndexOutOfBoundsException e) { fail ("Unexpected ArrayIndexOutOfBoundsException"); } /** * Various set methods: **/ try { b.set (b.getRowDimension (), b.getColumnDimension () - 1, 0); fail ("OutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e) { try { b.set (b.getRowDimension () - 1, b.getColumnDimension (), 0); fail ("OutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e1) { _try_success ("set(int,int,double)... OutofBoundsException... ", ""); } } catch (final IllegalArgumentException e1) { fail ("OutOfBoundsException expected but not thrown"); } try { b.set (ib, jb, 0); tmp = b.get (ib, jb); try { _check (tmp, 0); _try_success ("set(int,int,double)... ", ""); } catch (final RuntimeException e) { fail ("MatrixInt element not successfully set"); } } catch (final ArrayIndexOutOfBoundsException e1) { fail ("Unexpected ArrayIndexOutOfBoundsException"); } M = new MatrixInt (2, 3, 0); try { b.setMatrix (ib, ie + b.getRowDimension () + 1, jb, je, M); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e) { try { b.setMatrix (ib, ie, jb, je + b.getColumnDimension () + 1, M); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e1) { _try_success ("setMatrix(int,int,int,int,MatrixInt)... ArrayIndexOutOfBoundsException... ", ""); } } catch (final IllegalArgumentException e1) { fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } try { b.setMatrix (ib, ie, jb, je, M); try { _check (M.minus (b.getMatrix (ib, ie, jb, je)), M); _try_success ("setMatrix(int,int,int,int,MatrixInt)... ", ""); } catch (final RuntimeException e) { fail ("submatrix not successfully set"); } b.setMatrix (ib, ie, jb, je, SUB); } catch (final ArrayIndexOutOfBoundsException e1) { fail ("Unexpected ArrayIndexOutOfBoundsException"); } try { b.setMatrix (ib, ie + b.getRowDimension () + 1, columnindexset, M); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e) { try { b.setMatrix (ib, ie, badcolumnindexset, M); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e1) { _try_success ("setMatrix(int,int,int[],MatrixInt)... ArrayIndexOutOfBoundsException... ", ""); } } catch (final IllegalArgumentException e1) { fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } try { b.setMatrix (ib, ie, columnindexset, M); try { _check (M.minus (b.getMatrix (ib, ie, columnindexset)), M); _try_success ("setMatrix(int,int,int[],MatrixInt)... ", ""); } catch (final RuntimeException e) { fail ("submatrix not successfully set"); } b.setMatrix (ib, ie, jb, je, SUB); } catch (final ArrayIndexOutOfBoundsException e1) { fail ("Unexpected ArrayIndexOutOfBoundsException"); } try { b.setMatrix (rowindexset, jb, je + b.getColumnDimension () + 1, M); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e) { try { b.setMatrix (badrowindexset, jb, je, M); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e1) { _try_success ("setMatrix(int[],int,int,MatrixInt)... ArrayIndexOutOfBoundsException... ", ""); } } catch (final IllegalArgumentException e1) { fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } try { b.setMatrix (rowindexset, jb, je, M); try { _check (M.minus (b.getMatrix (rowindexset, jb, je)), M); _try_success ("setMatrix(int[],int,int,MatrixInt)... ", ""); } catch (final RuntimeException e) { fail ("submatrix not successfully set"); } b.setMatrix (ib, ie, jb, je, SUB); } catch (final ArrayIndexOutOfBoundsException e1) { fail ("Unexpected ArrayIndexOutOfBoundsException"); } try { b.setMatrix (rowindexset, badcolumnindexset, M); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e) { try { b.setMatrix (badrowindexset, columnindexset, M); fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } catch (final ArrayIndexOutOfBoundsException e1) { _try_success ("setMatrix(int[],int[],MatrixInt)... ArrayIndexOutOfBoundsException... ", ""); } } catch (final IllegalArgumentException e1) { fail ("ArrayIndexOutOfBoundsException expected but not thrown"); } try { b.setMatrix (rowindexset, columnindexset, M); try { _check (M.minus (b.getMatrix (rowindexset, columnindexset)), M); _try_success ("setMatrix(int[],int[],MatrixInt)... ", ""); } catch (final RuntimeException e) { fail ("submatrix not successfully set"); } } catch (final ArrayIndexOutOfBoundsException e1) { fail ("Unexpected ArrayIndexOutOfBoundsException"); } /** * Array-like methods: minus minusEquals plus plusEquals arrayLeftDivide * arrayLeftDivideEquals arrayRightDivide arrayRightDivideEquals arrayTimes * arrayTimesEquals uminus **/ _print ("\nTesting array-like methods...\n"); MatrixInt S = new MatrixInt (columnwise, nonconformld); MatrixInt r = MatrixInt.random (a.getRowDimension (), a.getColumnDimension ()); a = r; try { S = a.minus (S); fail ("nonconformance not raised"); } catch (final IllegalArgumentException e) { _try_success ("minus conformance _check... ", ""); } if (a.minus (r).norm1 () != 0) { fail ("(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { _try_success ("minus... ", ""); } a = r.getClone (); a.minusEquals (r); final MatrixInt Z = new MatrixInt (a.getRowDimension (), a.getColumnDimension ()); try { a.minusEquals (S); fail ("nonconformance not raised"); } catch (final IllegalArgumentException e) { _try_success ("minusEquals conformance _check... ", ""); } if (a.minus (Z).norm1 () != 0) { fail ("(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { _try_success ("minusEquals... ", ""); } a = r.getClone (); b = MatrixInt.random (a.getRowDimension (), a.getColumnDimension ()); C = a.minus (b); try { S = a.plus (S); fail ("nonconformance not raised"); } catch (final IllegalArgumentException e) { _try_success ("plus conformance _check... ", ""); } try { _check (C.plus (b), a); _try_success ("plus... ", ""); } catch (final RuntimeException e) { fail ("(C = a - b, but C + b != a)"); } C = a.minus (b); C.plusEquals (b); try { a.plusEquals (S); fail ("nonconformance not raised"); } catch (final IllegalArgumentException e) { _try_success ("plusEquals conformance _check... ", ""); } try { _check (C, a); _try_success ("plusEquals... ", ""); } catch (final RuntimeException e) { fail ("(C = a - b, but C = C + b != a)"); } a = r.uminus (); try { _check (a.plus (r), Z); _try_success ("uminus... ", ""); } catch (final RuntimeException e) { fail ("(-a + a != zeros)"); } a = r.getClone (); final MatrixInt O = new MatrixInt (a.getRowDimension (), a.getColumnDimension (), 1); C = a.arrayLeftDivide (r); try { S = a.arrayLeftDivide (S); fail ("nonconformance not raised"); } catch (final IllegalArgumentException e) { _try_success ("arrayLeftDivide conformance _check... ", ""); } try { _check (C, O); _try_success ("arrayLeftDivide... ", ""); } catch (final RuntimeException e) { fail ("(M.\\M != ones)"); } try { a.arrayLeftDivideEquals (S); fail ("nonconformance not raised"); } catch (final IllegalArgumentException e) { _try_success ("arrayLeftDivideEquals conformance _check... ", ""); } a.arrayLeftDivideEquals (r); try { _check (a, O); _try_success ("arrayLeftDivideEquals... ", ""); } catch (final RuntimeException e) { fail ("(M.\\M != ones)"); } a = r.getClone (); try { a.arrayRightDivide (S); fail ("nonconformance not raised"); } catch (final IllegalArgumentException e) { _try_success ("arrayRightDivide conformance _check... ", ""); } C = a.arrayRightDivide (r); try { _check (C, O); _try_success ("arrayRightDivide... ", ""); } catch (final RuntimeException e) { fail ("(M./M != ones)"); } try { a.arrayRightDivideEquals (S); fail ("nonconformance not raised"); } catch (final IllegalArgumentException e) { _try_success ("arrayRightDivideEquals conformance _check... ", ""); } a.arrayRightDivideEquals (r); try { _check (a, O); _try_success ("arrayRightDivideEquals... ", ""); } catch (final RuntimeException e) { fail ("(M./M != ones)"); } a = r.getClone (); b = MatrixInt.random (a.getRowDimension (), a.getColumnDimension ()); try { S = a.arrayTimes (S); fail ("nonconformance not raised"); } catch (final IllegalArgumentException e) { _try_success ("arrayTimes conformance _check... ", ""); } C = a.arrayTimes (b); try { _check (C.arrayRightDivideEquals (b), a); _try_success ("arrayTimes... ", ""); } catch (final RuntimeException e) { fail ("(a = r, C = a.*b, but C./b != a)"); } try { a.arrayTimesEquals (S); fail ("nonconformance not raised"); } catch (final IllegalArgumentException e) { _try_success ("arrayTimesEquals conformance _check... ", ""); } a.arrayTimesEquals (b); try { _check (a.arrayRightDivideEquals (b), r); _try_success ("arrayTimesEquals... ", ""); } catch (final RuntimeException e) { fail ("(a = r, a = a.*b, but a./b != r)"); } /** * I/O methods: read print serializable: writeObject readObject **/ _print ("\nTesting I/O methods...\n"); try { final DecimalFormat fmt = new DecimalFormat ("0", DFS); try (final PrintWriter aPW = FileHelper.getPrintWriter (FILE_JAMA_TEST_MATRIX_OUT, StandardCharsets.UTF_8)) { a.print (aPW, fmt, 10); } try (final Reader aReader = FileHelper.getReader (FILE_JAMA_TEST_MATRIX_OUT, StandardCharsets.UTF_8)) { r = MatrixInt.read (aReader); } if (a.minus (r).norm1 () < .001) { _try_success ("print()/read()...", ""); } else { fail ("MatrixInt read from file does not match MatrixInt printed to file"); } } catch (final IOException ioe) { warningCount = _try_warning (warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; _check write permission in current directory and retry"); } catch (final Exception e) { try { LOGGER.error ("oops", e); warningCount = _try_warning (warningCount, "print()/read()...", "Formatting error... will try JDK1.1 reformulation..."); final DecimalFormat fmt = new DecimalFormat ("0", DFS); try (final PrintWriter aPW = FileHelper.getPrintWriter (FILE_JAMA_TEST_MATRIX_OUT, StandardCharsets.UTF_8)) { a.print (aPW, fmt, 10); } try (final Reader aReader = FileHelper.getBufferedReader (FILE_JAMA_TEST_MATRIX_OUT, StandardCharsets.UTF_8)) { r = MatrixInt.read (aReader); } if (a.minus (r).norm1 () < .001) { _try_success ("print()/read()...", ""); } else { fail ("MatrixInt read from file does not match MatrixInt printed to file"); } } catch (final IOException ioe) { warningCount = _try_warning (warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; _check write permission in current directory and retry"); } } finally { FileOperations.deleteFile (FILE_JAMA_TEST_MATRIX_OUT); } r = MatrixInt.random (a.getRowDimension (), a.getColumnDimension ()); final String tmpname = "TMPMATRIX.serial"; try { try (final ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream (tmpname))) { out.writeObject (r); } try (final ObjectInputStream sin = new ObjectInputStream (new FileInputStream (tmpname))) { a = (MatrixInt) sin.readObject (); } try { _check (a, r); _try_success ("writeObject(MatrixInt)/readObject(MatrixInt)...", ""); } catch (final RuntimeException e) { fail ("MatrixInt not serialized correctly"); } } catch (final IOException ioe) { warningCount = _try_warning (warningCount, "writeObject()/readObject()...", "unexpected I/O error, unable to run serialization test; _check write permission in current directory and retry"); } catch (final Exception e) { fail ("unexpected error in serialization test"); } finally { FileOperations.deleteFile (new File (tmpname)); } /** * LA methods: transpose times cond rank det trace norm1 norm2 normF normInf * solve solveTranspose inverse chol eig lu qr svd **/ _print ("\nTesting linear algebra methods...\n"); a = new MatrixInt (columnwise, 3); MatrixInt T = new MatrixInt (tvals); T = a.transpose (); try { _check (a.transpose (), T); _try_success ("transpose...", ""); } catch (final RuntimeException e) { fail ("transpose unsuccessful"); } assertNotNull (a.transpose ()); try { _check (a.norm1 (), columnsummax); _try_success ("norm1...", ""); } catch (final RuntimeException e) { fail ("incorrect norm calculation"); } try { _check (a.normInf (), rowsummax); _try_success ("normInf()...", ""); } catch (final RuntimeException e) { fail ("incorrect norm calculation"); } try { _check (a.normF (), Math.sqrt (sumofsquares)); _try_success ("normF...", ""); } catch (final RuntimeException e) { fail ("incorrect norm calculation"); } try { _check (a.trace (), sumofdiagonals); _try_success ("trace()...", ""); } catch (final RuntimeException e) { fail ("incorrect trace calculation"); } final MatrixInt SQ = new MatrixInt (square); try { _check (a.times (a.transpose ()), SQ); _try_success ("times(MatrixInt)...", ""); } catch (final RuntimeException e) { fail ("incorrect MatrixInt-MatrixInt product calculation"); } try { _check (a.times (0), Z); _try_success ("times(double)...", ""); } catch (final RuntimeException e) { fail ("incorrect MatrixInt-scalar product calculation"); } a = new MatrixInt (columnwise, 4); assertNotNull (a); assertEquals (0, warningCount); } /** private utility routines **/ /** Check magnitude of difference of scalars. **/ private static void _check (final double x, final double y) { if (x == 0 && Math.abs (y) < 10 * EPSILON) return; if (y == 0 && Math.abs (x) < 10 * EPSILON) return; if (Math.abs (x - y) > 10 * EPSILON * Math.max (Math.abs (x), Math.abs (y))) { throw new IllegalArgumentException ("The difference x-y is too large: x = " + Double.toString (x) + " y = " + Double.toString (y)); } } private static void _check (final int x, final int y) { if (x != y) throw new IllegalArgumentException ("The difference x-y is !=0: x = " + x + " y = " + y); } /** Check norm of difference of "vectors". **/ private static void _check (final int [] x, final int [] y) { if (x.length == y.length) { for (int i = 0; i < x.length; i++) _check (x[i], y[i]); } else { throw new IllegalArgumentException ("Attempt to compare vectors of different lengths"); } } /** Check norm of difference of arrays. **/ private static void _check (@Nonnull final int [] [] x, @Nonnull final int [] [] y) { final MatrixInt a = new MatrixInt (x); final MatrixInt b = new MatrixInt (y); _check (a, b); } /** Check norm of difference of Matrices. **/ private static void _check (@Nonnull final MatrixInt x, @Nonnull final MatrixInt y) { if (x.norm1 () == 0. && y.norm1 () < 10 * EPSILON) return; if (y.norm1 () == 0. && x.norm1 () < 10 * EPSILON) return; if (x.minus (y).norm1 () > 1000 * EPSILON * Math.max (x.norm1 (), y.norm1 ())) throw new IllegalArgumentException ("The norm of (x-y) is too large: " + Double.toString (x.minus (y).norm1 ())); } /** Shorten spelling of print. **/ private static void _print (final String s) { LOGGER.info (StringHelper.trimEnd (s, '\n')); } /** Print appropriate messages for successful outcome try **/ private static void _try_success (final String s, final String e) { _print ("> " + s + "success\n"); if (StringHelper.hasText (e)) _print ("> Message: " + e + "\n"); } /** Print appropriate messages for unsuccessful outcome try **/ private static int _try_warning (final int count, final String s, final String e) { _print ("> " + s + "*** warning ***\n> Message: " + e + "\n"); return count + 1; } }
// Copyright 2015 The Chromium Authors. 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.chromium.chrome.browser.ntp; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Build; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnLayoutChangeListener; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import org.chromium.base.CommandLine; import org.chromium.base.FieldTrialList; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.R; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.favicon.FaviconHelper.FaviconAvailabilityCallback; import org.chromium.chrome.browser.favicon.FaviconHelper.FaviconImageCallback; import org.chromium.chrome.browser.favicon.LargeIconBridge.LargeIconCallback; import org.chromium.chrome.browser.ntp.LogoBridge.Logo; import org.chromium.chrome.browser.ntp.LogoBridge.LogoObserver; import org.chromium.chrome.browser.ntp.MostVisitedItem.MostVisitedItemManager; import org.chromium.chrome.browser.ntp.NewTabPage.OnSearchBoxScrollListener; import org.chromium.chrome.browser.profiles.MostVisitedSites.MostVisitedURLsObserver; import org.chromium.chrome.browser.profiles.MostVisitedSites.ThumbnailCallback; import org.chromium.chrome.browser.util.ViewUtils; import org.chromium.chrome.browser.widget.RoundedIconGenerator; import org.chromium.ui.text.SpanApplier; import org.chromium.ui.text.SpanApplier.SpanInfo; import java.util.Locale; /** * The native new tab page, represented by some basic data such as title and url, and an Android * View that displays the page. */ public class NewTabPageView extends FrameLayout implements MostVisitedURLsObserver, OnLayoutChangeListener { static final int MAX_MOST_VISITED_SITES = 12; private static final int SHADOW_COLOR = 0x11000000; private static final long SNAP_SCROLL_DELAY_MS = 30; private static final String ICON_NTP_FIELD_TRIAL_NAME = "IconNTP"; private static final String ICON_NTP_ENABLED_GROUP = "Enabled"; // Taken from https://support.google.com/googleplay/answer/1727131?hl=en-GB private static final String[] SUPPORTED_SAMSUNG_DEVICES = { "sm-g920", // Galaxy S6 "sm-g925", // Galaxy S6 Edge "404sc", // Galaxy S6 Edge "scv31", // Galaxy S6 Edge "sm-g890", // Galaxy S6 Active "sm-g800", // Galaxy S5 mini "sm-g860", // Galaxy S5 K Sport "sm-g870", // Galaxy S5 Active "sm-g900", // Galaxy S5 "sm-g901", // Galaxy S5 LTE-A "sm-g906", // Galaxy S5 "scl23", // Galaxy S5 "sm-n915", // Galaxy Note Edge "scl24", // Galaxy Note Edge "sm-n916", // Galaxy Note 4 "sm-n910", // Galaxy Note 4 "sm-g850", // Galaxy Alpha }; private ViewGroup mContentView; private NewTabScrollView mScrollView; private LogoView mSearchProviderLogoView; private View mSearchBoxView; private TextView mSearchBoxTextView; private ImageView mVoiceSearchButton; private ViewGroup mMostVisitedLayout; private View mMostVisitedPlaceholder; private View mOptOutView; private View mNoSearchLogoSpacer; private OnSearchBoxScrollListener mSearchBoxScrollListener; private NewTabPageManager mManager; private MostVisitedDesign mMostVisitedDesign; private MostVisitedItem[] mMostVisitedItems; private boolean mFirstShow = true; private boolean mSearchProviderHasLogo = true; private boolean mHasReceivedMostVisitedSites; private boolean mPendingSnapScroll; /** * The number of asynchronous tasks that need to complete before the page is done loading. * This starts at one to track when the view is finished attaching to the window. */ private int mPendingLoadTasks = 1; private boolean mLoadHasCompleted; private float mUrlFocusChangePercent; private boolean mDisableUrlFocusChangeAnimations; private boolean mSnapshotMostVisitedChanged; private int mSnapshotWidth; private int mSnapshotHeight; private int mSnapshotScrollY; /** * Manages the view interaction with the rest of the system. */ public interface NewTabPageManager extends MostVisitedItemManager { /** @return Whether the location bar is shown in the NTP. */ boolean isLocationBarShownInNTP(); /** @return Whether voice search is enabled and the microphone should be shown. */ boolean isVoiceSearchEnabled(); /** @return Whether the document mode opt out promo should be shown. */ boolean shouldShowOptOutPromo(); /** Called when the document mode opt out promo is shown. */ void optOutPromoShown(); /** Called when the user clicks "settings" or "ok, got it" on the opt out promo. */ void optOutPromoClicked(boolean settingsClicked); /** Opens the bookmarks page in the current tab. */ void navigateToBookmarks(); /** Opens the recent tabs page in the current tab. */ void navigateToRecentTabs(); /** * Animates the search box up into the omnibox and bring up the keyboard. * @param beginVoiceSearch Whether to begin a voice search. * @param pastedText Text to paste in the omnibox after it's been focused. May be null. */ void focusSearchBox(boolean beginVoiceSearch, String pastedText); /** * Gets the list of most visited sites. * @param observer The observer to be notified with the list of sites. * @param numResults The maximum number of sites to retrieve. */ void setMostVisitedURLsObserver(MostVisitedURLsObserver observer, int numResults); /** * Gets a cached thumbnail of a URL. * @param url The URL whose thumbnail is being retrieved. * @param thumbnailCallback The callback to be notified when the thumbnail is available. */ void getURLThumbnail(String url, ThumbnailCallback thumbnailCallback); /** * Gets the favicon image for a given URL. * @param url The URL of the site whose favicon is being requested. * @param size The desired size of the favicon in pixels. * @param faviconCallback The callback to be notified when the favicon is available. */ void getLocalFaviconImageForURL( String url, int size, FaviconImageCallback faviconCallback); /** * Gets the large icon (e.g. favicon or touch icon) for a given URL. * @param url The URL of the site whose icon is being requested. * @param size The desired size of the icon in pixels. * @param callback The callback to be notified when the icon is available. */ void getLargeIconForUrl(String url, int size, LargeIconCallback callback); /** * Checks if a favicon with the given faviconUrl is available. If not, * downloads it and stores it as a favicon for the given pageUrl. * @param pageUrl The URL of the site whose icon is being requested. * @param faviconUrl The URL of the favicon. * @param callback The callback to be notified when the favicon has been checked. */ void ensureFaviconIsAvailable(String pageUrl, String faviconUrl, FaviconAvailabilityCallback callback); /** * Navigates to a URL chosen by the search provider when the user clicks on the logo. */ void openLogoLink(); /** * Gets the default search provider's logo and calls logoObserver with the result. * @param logoObserver The callback to notify when the logo is available. */ void getSearchProviderLogo(LogoObserver logoObserver); /** * Called when the NTP has completely finished loading (all views will be inflated * and any dependent resources will have been loaded). */ void onLoadingComplete(); } /** * Returns a title suitable for display for a link (e.g. a most visited item). If |title| is * non-empty, this simply returns it. Otherwise, returns a shortened form of the URL. */ static String getTitleForDisplay(String title, String url) { if (TextUtils.isEmpty(title) && url != null) { Uri uri = Uri.parse(url); String host = uri.getHost(); String path = uri.getPath(); if (host == null) host = ""; if (TextUtils.isEmpty(path) || path.equals("/")) path = ""; title = host + path; } return title; } /** * Default constructor required for XML inflation. */ public NewTabPageView(Context context, AttributeSet attrs) { super(context, attrs); } private boolean isIconNtpEnabled() { // Query the field trial state first, to ensure that UMA reports the correct group. String fieldTrialGroup = FieldTrialList.findFullName(ICON_NTP_FIELD_TRIAL_NAME); CommandLine commandLine = CommandLine.getInstance(); if (commandLine.hasSwitch(ChromeSwitches.DISABLE_ICON_NTP)) return false; if (commandLine.hasSwitch(ChromeSwitches.ENABLE_ICON_NTP)) return true; return fieldTrialGroup.equals(ICON_NTP_ENABLED_GROUP); } /** * Initializes the NTP. This must be called immediately after inflation, before this object is * used in any other way. * * @param manager NewTabPageManager used to perform various actions when the user interacts * with the page. * @param isSingleUrlBarMode Whether the NTP is in single URL bar mode. * @param searchProviderHasLogo Whether the search provider has a logo. */ public void initialize(NewTabPageManager manager, boolean isSingleUrlBarMode, boolean searchProviderHasLogo) { mManager = manager; mScrollView = (NewTabScrollView) findViewById(R.id.ntp_scrollview); mScrollView.enableBottomShadow(SHADOW_COLOR); mContentView = (ViewGroup) findViewById(R.id.ntp_content); mMostVisitedDesign = isIconNtpEnabled() ? new IconMostVisitedDesign(getContext()) : new ThumbnailMostVisitedDesign(getContext()); ViewStub mostVisitedLayoutStub = (ViewStub) findViewById(R.id.most_visited_layout_stub); mostVisitedLayoutStub.setLayoutResource(mMostVisitedDesign.getMostVisitedLayoutId()); mMostVisitedLayout = (ViewGroup) mostVisitedLayoutStub.inflate(); mMostVisitedDesign.initMostVisitedLayout(mMostVisitedLayout, searchProviderHasLogo); mSearchProviderLogoView = (LogoView) findViewById(R.id.search_provider_logo); mSearchBoxView = findViewById(R.id.search_box); mNoSearchLogoSpacer = findViewById(R.id.no_search_logo_spacer); mSearchBoxTextView = (TextView) mSearchBoxView.findViewById(R.id.search_box_text); String hintText = getResources().getString(R.string.search_or_type_url); if (isSingleUrlBarMode) { mSearchBoxTextView.setHint(hintText); } else { mSearchBoxTextView.setContentDescription(hintText); } mSearchBoxTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mManager.focusSearchBox(false, null); } }); mSearchBoxTextView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.length() == 0) return; mManager.focusSearchBox(false, s.toString()); mSearchBoxTextView.setText(""); } }); mVoiceSearchButton = (ImageView) findViewById(R.id.voice_search_button); mVoiceSearchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mManager.focusSearchBox(true, null); } }); NewTabPageToolbar toolbar = (NewTabPageToolbar) findViewById(R.id.ntp_toolbar); toolbar.getRecentTabsButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mManager.navigateToRecentTabs(); } }); toolbar.getBookmarksButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mManager.navigateToBookmarks(); } }); initializeSearchBoxScrollHandling(); addOnLayoutChangeListener(this); setSearchProviderHasLogo(searchProviderHasLogo); mPendingLoadTasks++; mManager.setMostVisitedURLsObserver(this, mMostVisitedDesign.getNumberOfTiles(searchProviderHasLogo)); if (mManager.shouldShowOptOutPromo()) showOptOutPromo(); } private int getTabsMovedIllustration() { switch (Build.MANUFACTURER.toLowerCase(Locale.US)) { case "samsung": String model = Build.MODEL.toLowerCase(Locale.US); for (String supportedModel : SUPPORTED_SAMSUNG_DEVICES) { if (model.contains(supportedModel)) { return R.drawable.tabs_moved_samsung; } } return 0; case "htc": return R.drawable.tabs_moved_htc; default: return R.drawable.tabs_moved_nexus; } } private void showOptOutPromo() { ViewStub optOutPromoStub = (ViewStub) findViewById(R.id.opt_out_promo_stub); mOptOutView = optOutPromoStub.inflate(); // Fill in opt-out text with Settings link TextView optOutText = (TextView) mOptOutView.findViewById(R.id.opt_out_text); ClickableSpan settingsLink = new ClickableSpan() { @Override public void onClick(View view) { mManager.optOutPromoClicked(true); } // Disable underline on the link text. @Override public void updateDrawState(android.text.TextPaint textPaint) { super.updateDrawState(textPaint); textPaint.setUnderlineText(false); } }; optOutText.setText(SpanApplier.applySpans( getContext().getString(R.string.tabs_and_apps_opt_out_text), new SpanInfo("<link>", "</link>", settingsLink))); optOutText.setMovementMethod(LinkMovementMethod.getInstance()); ImageView illustration = (ImageView) mOptOutView.findViewById(R.id.tabs_moved_illustration); illustration.setImageResource(getTabsMovedIllustration()); mOptOutView.setVisibility(View.VISIBLE); mMostVisitedLayout.setVisibility(View.GONE); Button gotItButton = (Button) mOptOutView.findViewById(R.id.got_it_button); gotItButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mOptOutView.setVisibility(View.GONE); mMostVisitedLayout.setVisibility(View.VISIBLE); mManager.optOutPromoClicked(false); updateMostVisitedPlaceholderVisibility(); } }); mManager.optOutPromoShown(); } private void updateSearchBoxOnScroll() { if (mDisableUrlFocusChangeAnimations) return; float percentage = 0; // During startup the view may not be fully initialized, so we only calculate the current // percentage if some basic view properties are sane. if (mScrollView.getHeight() != 0 && mSearchBoxView.getTop() != 0) { int scrollY = mScrollView.getScrollY(); percentage = Math.max( 0f, Math.min(1f, scrollY / (float) mSearchBoxView.getTop())); } updateVisualsForToolbarTransition(percentage); if (mSearchBoxScrollListener != null) { mSearchBoxScrollListener.onScrollChanged(percentage); } } private void initializeSearchBoxScrollHandling() { final Runnable mSnapScrollRunnable = new Runnable() { @Override public void run() { if (!mPendingSnapScroll) return; int scrollY = mScrollView.getScrollY(); int dividerTop = mMostVisitedLayout.getTop() - mContentView.getPaddingTop(); if (scrollY > 0 && scrollY < dividerTop) { mScrollView.smoothScrollTo(0, scrollY < (dividerTop / 2) ? 0 : dividerTop); } mPendingSnapScroll = false; } }; mScrollView.setOnScrollListener(new NewTabScrollView.OnScrollListener() { @Override public void onScrollChanged(int l, int t, int oldl, int oldt) { if (mPendingSnapScroll) { mScrollView.removeCallbacks(mSnapScrollRunnable); mScrollView.postDelayed(mSnapScrollRunnable, SNAP_SCROLL_DELAY_MS); } updateSearchBoxOnScroll(); } }); mScrollView.setOnTouchListener(new OnTouchListener() { @Override @SuppressLint("ClickableViewAccessibility") public boolean onTouch(View v, MotionEvent event) { if (mScrollView.getHandler() == null) return false; mScrollView.removeCallbacks(mSnapScrollRunnable); if (event.getActionMasked() == MotionEvent.ACTION_CANCEL || event.getActionMasked() == MotionEvent.ACTION_UP) { mPendingSnapScroll = true; mScrollView.postDelayed(mSnapScrollRunnable, SNAP_SCROLL_DELAY_MS); } else { mPendingSnapScroll = false; } return false; } }); } /** * Decrements the count of pending load tasks and notifies the manager when the page load * is complete. */ private void loadTaskCompleted() { assert mPendingLoadTasks > 0; mPendingLoadTasks--; if (mPendingLoadTasks == 0) { if (mLoadHasCompleted) { assert false; } else { mLoadHasCompleted = true; mManager.onLoadingComplete(); mMostVisitedDesign.onLoadingComplete(); // Load the logo after everything else is finished, since it's lower priority. loadSearchProviderLogo(); } } } /** * Loads the search provider logo (e.g. Google doodle), if any. */ private void loadSearchProviderLogo() { mManager.getSearchProviderLogo(new LogoObserver() { @Override public void onLogoAvailable(Logo logo, boolean fromCache) { if (logo == null && fromCache) return; mSearchProviderLogoView.setMananger(mManager); mSearchProviderLogoView.updateLogo(logo); mSnapshotMostVisitedChanged = true; } }); } /** * Changes the layout depending on whether the selected search provider (e.g. Google, Bing) * has a logo. * @param hasLogo Whether the search provider has a logo. */ public void setSearchProviderHasLogo(boolean hasLogo) { if (hasLogo == mSearchProviderHasLogo) return; mSearchProviderHasLogo = hasLogo; mMostVisitedDesign.setSearchProviderHasLogo(mMostVisitedLayout, hasLogo); if (!hasLogo) setUrlFocusChangeAnimationPercentInternal(0); // Hide or show all the views above the Most Visited items. int visibility = hasLogo ? View.VISIBLE : View.GONE; int childCount = mContentView.getChildCount(); for (int i = 0; i < childCount; i++) { View child = mContentView.getChildAt(i); if (child == mMostVisitedLayout) break; // Don't change the visibility of a ViewStub as that will automagically inflate it. if (child instanceof ViewStub) continue; child.setVisibility(visibility); } updateMostVisitedPlaceholderVisibility(); if (hasLogo) setUrlFocusChangeAnimationPercent(mUrlFocusChangePercent); mSnapshotMostVisitedChanged = true; } /** * Updates whether the NewTabPage should animate on URL focus changes. * @param disable Whether to disable the animations. */ void setUrlFocusAnimationsDisabled(boolean disable) { if (disable == mDisableUrlFocusChangeAnimations) return; mDisableUrlFocusChangeAnimations = disable; if (!disable) setUrlFocusChangeAnimationPercent(mUrlFocusChangePercent); } /** * @return Whether URL focus animations are currently disabled. */ boolean urlFocusAnimationsDisabled() { return mDisableUrlFocusChangeAnimations; } /** * Specifies the percentage the URL is focused during an animation. 1.0 specifies that the URL * bar has focus and has completed the focus animation. 0 is when the URL bar is does not have * any focus. * * @param percent The percentage of the URL bar focus animation. */ void setUrlFocusChangeAnimationPercent(float percent) { mUrlFocusChangePercent = percent; if (!mDisableUrlFocusChangeAnimations && mSearchProviderHasLogo) { setUrlFocusChangeAnimationPercentInternal(percent); } } /** * @return The percentage that the URL bar is focused during an animation. */ @VisibleForTesting float getUrlFocusChangeAnimationPercent() { return mUrlFocusChangePercent; } /** * Unconditionally sets the percentage the URL is focused during an animation, without updating * mUrlFocusChangePercent. * @see #setUrlFocusChangeAnimationPercent */ private void setUrlFocusChangeAnimationPercentInternal(float percent) { mContentView.setTranslationY(percent * (-mMostVisitedLayout.getTop() + mScrollView.getScrollY() + mContentView.getPaddingTop())); updateVisualsForToolbarTransition(percent); } private void updateVisualsForToolbarTransition(float transitionPercentage) { // Complete the full alpha transition in the first 40% of the animation. float searchUiAlpha = transitionPercentage >= 0.4f ? 0f : (0.4f - transitionPercentage) * 2.5f; // Ensure there are no rounding issues when the animation percent is 0. if (transitionPercentage == 0f) searchUiAlpha = 1f; mSearchProviderLogoView.setAlpha(searchUiAlpha); mSearchBoxView.setAlpha(searchUiAlpha); } /** * Get the bounds of the search box in relation to the top level NewTabPage view. * * @param originalBounds The bounding region of the search box without external transforms * applied. The delta between this and the transformed bounds determines * the amount of scroll applied to this view. * @param transformedBounds The bounding region of the search box including any transforms * applied by the parent view hierarchy up to the NewTabPage view. * This more accurately reflects the current drawing location of the * search box. */ void getSearchBoxBounds(Rect originalBounds, Rect transformedBounds) { int searchBoxX = (int) mSearchBoxView.getX(); int searchBoxY = (int) mSearchBoxView.getY(); originalBounds.set( searchBoxX + mSearchBoxView.getPaddingLeft(), searchBoxY + mSearchBoxView.getPaddingTop(), searchBoxX + mSearchBoxView.getWidth() - mSearchBoxView.getPaddingRight(), searchBoxY + mSearchBoxView.getHeight() - mSearchBoxView.getPaddingBottom()); transformedBounds.set(originalBounds); View view = (View) mSearchBoxView.getParent(); while (view != null) { transformedBounds.offset(-view.getScrollX(), -view.getScrollY()); if (view == this) break; transformedBounds.offset((int) view.getX(), (int) view.getY()); view = (View) view.getParent(); } } /** * Sets the listener for search box scroll changes. * @param listener The listener to be notified on changes. */ void setSearchBoxScrollListener(OnSearchBoxScrollListener listener) { mSearchBoxScrollListener = listener; if (mSearchBoxScrollListener != null) updateSearchBoxOnScroll(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); assert mManager != null; if (mFirstShow) { loadTaskCompleted(); mFirstShow = false; } else { // Trigger a scroll update when reattaching the window to signal the toolbar that // it needs to reset the NTP state. if (mManager.isLocationBarShownInNTP()) updateSearchBoxOnScroll(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); setUrlFocusChangeAnimationPercent(0f); } /** * Update the visibility of the voice search button based on whether the feature is currently * enabled. */ void updateVoiceSearchButtonVisibility() { mVoiceSearchButton.setVisibility(mManager.isVoiceSearchEnabled() ? VISIBLE : GONE); } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); if (visibility == VISIBLE) { updateVoiceSearchButtonVisibility(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Make the search box and logo the same width as the most visited tiles. if (mMostVisitedLayout.getVisibility() != GONE) { int mostVisitedWidth = MeasureSpec.makeMeasureSpec(mMostVisitedLayout.getMeasuredWidth() - mMostVisitedDesign.getMostVisitedLayoutBleed(), MeasureSpec.EXACTLY); int searchBoxHeight = MeasureSpec.makeMeasureSpec( mSearchBoxView.getMeasuredHeight(), MeasureSpec.EXACTLY); int logoHeight = MeasureSpec.makeMeasureSpec( mSearchProviderLogoView.getMeasuredHeight(), MeasureSpec.EXACTLY); mSearchBoxView.measure(mostVisitedWidth, searchBoxHeight); mSearchProviderLogoView.measure(mostVisitedWidth, logoHeight); } } /** * @see org.chromium.chrome.browser.compositor.layouts.content. * InvalidationAwareThumbnailProvider#shouldCaptureThumbnail() */ boolean shouldCaptureThumbnail() { if (getWidth() == 0 || getHeight() == 0) return false; return mSnapshotMostVisitedChanged || getWidth() != mSnapshotWidth || getHeight() != mSnapshotHeight || mScrollView.getScrollY() != mSnapshotScrollY; } /** * @see org.chromium.chrome.browser.compositor.layouts.content. * InvalidationAwareThumbnailProvider#captureThumbnail(Canvas) */ void captureThumbnail(Canvas canvas) { mSearchProviderLogoView.endAnimation(); ViewUtils.captureBitmap(this, canvas); mSnapshotWidth = getWidth(); mSnapshotHeight = getHeight(); mSnapshotScrollY = mScrollView.getScrollY(); mSnapshotMostVisitedChanged = false; } // OnLayoutChangeListener overrides @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { int oldWidth = oldRight - oldLeft; int newWidth = right - left; if (oldWidth == newWidth) return; // Re-apply the url focus change amount after a rotation to ensure the views are correctly // placed with their new layout configurations. setUrlFocusChangeAnimationPercent(mUrlFocusChangePercent); } // MostVisitedURLsObserver implementation @Override public void onMostVisitedURLsAvailable(String[] titles, String[] urls) { mMostVisitedLayout.removeAllViews(); MostVisitedItem[] oldItems = mMostVisitedItems; int oldItemCount = oldItems == null ? 0 : oldItems.length; mMostVisitedItems = new MostVisitedItem[titles.length]; final boolean isInitialLoad = !mHasReceivedMostVisitedSites; LayoutInflater inflater = LayoutInflater.from(getContext()); // Add the most visited items to the page. for (int i = 0; i < titles.length; i++) { final String url = urls[i]; final String title = titles[i]; // Look for an existing item to reuse. MostVisitedItem item = null; for (int j = 0; j < oldItemCount; j++) { MostVisitedItem oldItem = oldItems[j]; if (oldItem != null && TextUtils.equals(url, oldItem.getUrl()) && TextUtils.equals(title, oldItem.getTitle())) { item = oldItem; item.setIndex(i); oldItems[j] = null; break; } } // If nothing can be reused, create a new item. if (item == null) { String displayTitle = getTitleForDisplay(title, url); View view = mMostVisitedDesign.createMostVisitedItemView(inflater, url, title, displayTitle, i, isInitialLoad); item = new MostVisitedItem(mManager, title, url, i, view); } mMostVisitedItems[i] = item; mMostVisitedLayout.addView(item.getView()); } mHasReceivedMostVisitedSites = true; updateMostVisitedPlaceholderVisibility(); if (isInitialLoad) { loadTaskCompleted(); // The page contents are initially hidden; otherwise they'll be drawn centered on the // page before the most visited sites are available and then jump upwards to make space // once the most visited sites are available. mContentView.setVisibility(View.VISIBLE); } mSnapshotMostVisitedChanged = true; } @Override public void onPopularURLsAvailable(String[] urls, String[] faviconUrls) { for (int i = 0; i < urls.length; i++) { final String url = urls[i]; final String faviconUrl = faviconUrls[i]; if (faviconUrl.isEmpty()) continue; FaviconAvailabilityCallback callback = new FaviconAvailabilityCallback() { @Override public void onFaviconAvailabilityChecked(boolean newlyAvailable) { if (newlyAvailable) { mMostVisitedDesign.onFaviconUpdated(url); } } }; mManager.ensureFaviconIsAvailable(url, faviconUrl, callback); } } /** * Shows the most visited placeholder ("Nothing to see here") if there are no most visited * items and there is no search provider logo. */ private void updateMostVisitedPlaceholderVisibility() { boolean showPlaceholder = mHasReceivedMostVisitedSites && !mManager.shouldShowOptOutPromo() && mMostVisitedLayout.getChildCount() == 0 && !mSearchProviderHasLogo; mNoSearchLogoSpacer.setVisibility( (mSearchProviderHasLogo || showPlaceholder) ? View.GONE : View.INVISIBLE); if (showPlaceholder) { if (mMostVisitedPlaceholder == null) { ViewStub mostVisitedPlaceholderStub = (ViewStub) findViewById( R.id.most_visited_placeholder_stub); mMostVisitedPlaceholder = mostVisitedPlaceholderStub.inflate(); } mMostVisitedLayout.setVisibility(GONE); mMostVisitedPlaceholder.setVisibility(VISIBLE); return; } else if (mMostVisitedPlaceholder != null) { mMostVisitedLayout.setVisibility(VISIBLE); mMostVisitedPlaceholder.setVisibility(GONE); } } /** * Interface for creating the most visited layout and tiles. * TODO(newt): delete this once a single design has been chosen. */ private interface MostVisitedDesign { int getNumberOfTiles(boolean searchProviderHasLogo); int getMostVisitedLayoutId(); int getMostVisitedLayoutBleed(); void initMostVisitedLayout(ViewGroup mostVisitedLayout, boolean searchProviderHasLogo); void setSearchProviderHasLogo(View mostVisitedLayout, boolean hasLogo); View createMostVisitedItemView(LayoutInflater inflater, String url, String title, String displayTitle, int index, boolean isInitialLoad); void onFaviconUpdated(String url); void onLoadingComplete(); } /** * The old most visited design, where each tile shows a thumbnail of the page, a small favicon, * and the title. */ private class ThumbnailMostVisitedDesign implements MostVisitedDesign { private static final int NUM_TILES = 6; private static final int FAVICON_CORNER_RADIUS_DP = 2; private static final int FAVICON_TEXT_SIZE_DP = 10; private static final int FAVICON_BACKGROUND_COLOR = 0xff969696; private int mDesiredFaviconSize; private RoundedIconGenerator mFaviconGenerator; ThumbnailMostVisitedDesign(Context context) { Resources res = context.getResources(); mDesiredFaviconSize = res.getDimensionPixelSize(R.dimen.most_visited_favicon_size); int desiredFaviconSizeDp = Math.round( mDesiredFaviconSize / res.getDisplayMetrics().density); mFaviconGenerator = new RoundedIconGenerator( context, desiredFaviconSizeDp, desiredFaviconSizeDp, FAVICON_CORNER_RADIUS_DP, FAVICON_BACKGROUND_COLOR, FAVICON_TEXT_SIZE_DP); } @Override public int getNumberOfTiles(boolean searchProviderHasLogo) { return NUM_TILES; } @Override public int getMostVisitedLayoutId() { return R.layout.most_visited_layout; } @Override public int getMostVisitedLayoutBleed() { return 0; } @Override public void initMostVisitedLayout(ViewGroup mostVisitedLayout, boolean searchProviderHasLogo) { } @Override public void setSearchProviderHasLogo(View mostVisitedLayout, boolean hasLogo) {} @Override public View createMostVisitedItemView(LayoutInflater inflater, final String url, String title, String displayTitle, int index, final boolean isInitialLoad) { final MostVisitedItemView view = (MostVisitedItemView) inflater.inflate( R.layout.most_visited_item, mMostVisitedLayout, false); view.init(displayTitle); ThumbnailCallback thumbnailCallback = new ThumbnailCallback() { @Override public void onMostVisitedURLsThumbnailAvailable(Bitmap thumbnail) { view.setThumbnail(thumbnail); mSnapshotMostVisitedChanged = true; if (isInitialLoad) loadTaskCompleted(); } }; if (isInitialLoad) mPendingLoadTasks++; mManager.getURLThumbnail(url, thumbnailCallback); FaviconImageCallback faviconCallback = new FaviconImageCallback() { @Override public void onFaviconAvailable(Bitmap image, String iconUrl) { if (image == null) { image = mFaviconGenerator.generateIconForUrl(url); } view.setFavicon(image); mSnapshotMostVisitedChanged = true; if (isInitialLoad) loadTaskCompleted(); } }; if (isInitialLoad) mPendingLoadTasks++; mManager.getLocalFaviconImageForURL(url, mDesiredFaviconSize, faviconCallback); return view; } @Override public void onFaviconUpdated(final String url) { // Find a matching most visited item. for (MostVisitedItem item : mMostVisitedItems) { if (!item.getUrl().equals(url)) continue; final MostVisitedItemView view = (MostVisitedItemView) item.getView(); FaviconImageCallback faviconCallback = new FaviconImageCallback() { @Override public void onFaviconAvailable(Bitmap image, String iconUrl) { if (image == null) { image = mFaviconGenerator.generateIconForUrl(url); } view.setFavicon(image); mSnapshotMostVisitedChanged = true; } }; mManager.getLocalFaviconImageForURL(url, mDesiredFaviconSize, faviconCallback); break; } } @Override public void onLoadingComplete() {} } /** * The new-fangled design for most visited tiles, where each tile shows a large icon and title. */ private class IconMostVisitedDesign implements MostVisitedDesign { private static final int NUM_TILES = 8; private static final int NUM_TILES_NO_LOGO = 12; private static final int MAX_ROWS = 2; private static final int MAX_ROWS_NO_LOGO = 3; private static final int ICON_CORNER_RADIUS_DP = 4; private static final int ICON_TEXT_SIZE_DP = 20; private static final int ICON_BACKGROUND_COLOR = 0xff787878; private static final int ICON_MIN_SIZE_PX = 48; private int mMostVisitedLayoutBleed; private int mMinIconSize; private int mDesiredIconSize; private RoundedIconGenerator mIconGenerator; private int mNumGrayIcons; private int mNumColorIcons; private int mNumRealIcons; IconMostVisitedDesign(Context context) { Resources res = context.getResources(); mMostVisitedLayoutBleed = res.getDimensionPixelSize( R.dimen.icon_most_visited_layout_bleed); mDesiredIconSize = res.getDimensionPixelSize(R.dimen.icon_most_visited_icon_size); // On ldpi devices, mDesiredIconSize could be even smaller than ICON_MIN_SIZE_PX. mMinIconSize = Math.min(mDesiredIconSize, ICON_MIN_SIZE_PX); int desiredIconSizeDp = Math.round( mDesiredIconSize / res.getDisplayMetrics().density); mIconGenerator = new RoundedIconGenerator( context, desiredIconSizeDp, desiredIconSizeDp, ICON_CORNER_RADIUS_DP, ICON_BACKGROUND_COLOR, ICON_TEXT_SIZE_DP); } @Override public int getNumberOfTiles(boolean searchProviderHasLogo) { return searchProviderHasLogo ? NUM_TILES : NUM_TILES_NO_LOGO; } @Override public int getMostVisitedLayoutId() { return R.layout.icon_most_visited_layout; } @Override public int getMostVisitedLayoutBleed() { return mMostVisitedLayoutBleed; } @Override public void initMostVisitedLayout(ViewGroup mostVisitedLayout, boolean searchProviderHasLogo) { ((IconMostVisitedLayout) mostVisitedLayout).setMaxRows( searchProviderHasLogo ? MAX_ROWS : MAX_ROWS_NO_LOGO); } @Override public void setSearchProviderHasLogo(View mostVisitedLayout, boolean hasLogo) { int paddingTop = getResources().getDimensionPixelSize(hasLogo ? R.dimen.icon_most_visited_layout_padding_top : R.dimen.icon_most_visited_layout_no_logo_padding_top); mostVisitedLayout.setPadding(0, paddingTop, 0, 0); } class LargeIconCallbackImpl implements LargeIconCallback { private String mUrl; private IconMostVisitedItemView mView; private boolean mIsInitialLoad; public LargeIconCallbackImpl(String url, IconMostVisitedItemView view, boolean isInitialLoad) { mUrl = url; mView = view; mIsInitialLoad = isInitialLoad; } @Override public void onLargeIconAvailable(Bitmap icon, int fallbackColor) { if (icon == null) { mIconGenerator.setBackgroundColor(fallbackColor); icon = mIconGenerator.generateIconForUrl(mUrl); mView.setIcon(new BitmapDrawable(getResources(), icon)); if (mIsInitialLoad) { if (fallbackColor == ICON_BACKGROUND_COLOR) { mNumGrayIcons++; } else { mNumColorIcons++; } } } else { RoundedBitmapDrawable roundedIcon = RoundedBitmapDrawableFactory.create( getResources(), icon); int cornerRadius = Math.round(ICON_CORNER_RADIUS_DP * getResources().getDisplayMetrics().density * icon.getWidth() / mDesiredIconSize); roundedIcon.setCornerRadius(cornerRadius); roundedIcon.setAntiAlias(true); roundedIcon.setFilterBitmap(true); mView.setIcon(roundedIcon); if (mIsInitialLoad) mNumRealIcons++; } mSnapshotMostVisitedChanged = true; if (mIsInitialLoad) loadTaskCompleted(); } }; @Override public View createMostVisitedItemView(LayoutInflater inflater, final String url, String title, String displayTitle, int index, final boolean isInitialLoad) { final IconMostVisitedItemView view = (IconMostVisitedItemView) inflater.inflate( R.layout.icon_most_visited_item, mMostVisitedLayout, false); view.setTitle(displayTitle); LargeIconCallback iconCallback = new LargeIconCallbackImpl(url, view, isInitialLoad); if (isInitialLoad) mPendingLoadTasks++; mManager.getLargeIconForUrl(url, mMinIconSize, iconCallback); return view; } @Override public void onFaviconUpdated(final String url) { // Find a matching most visited item. for (MostVisitedItem item : mMostVisitedItems) { if (!item.getUrl().equals(url)) continue; final IconMostVisitedItemView view = (IconMostVisitedItemView) item.getView(); LargeIconCallback iconCallback = new LargeIconCallbackImpl(url, view, false); mManager.getLargeIconForUrl(url, mMinIconSize, iconCallback); break; } } @Override public void onLoadingComplete() { RecordHistogram.recordCount100Histogram("NewTabPage.IconsGray", mNumGrayIcons); RecordHistogram.recordCount100Histogram("NewTabPage.IconsColor", mNumColorIcons); RecordHistogram.recordCount100Histogram("NewTabPage.IconsReal", mNumRealIcons); } } }
/** * Copyright 2011-2013 BBe Consulting GmbH * * 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 de.bbe_consulting.mavento; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Properties; import org.apache.maven.archetype.ArchetypeGenerationRequest; import org.apache.maven.archetype.ArchetypeGenerationResult; import org.codehaus.plexus.util.StringUtils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import de.bbe_consulting.mavento.helper.FileUtil; import de.bbe_consulting.mavento.helper.MagentoUtil; /** * Create Magento boiler code from snippets. Can only be executed in projects * with packaging type php. * * @goal snippet * @requiresDependencyResolution runtime * @author Erik Dannenberg */ public class MagentoSnippetMojo extends AbstractArchetypeMojo { /** * @parameter default-value="${project}" * @required * @readonly */ protected MavenProject project; @Override public void execute() throws MojoExecutionException, MojoFailureException { // check for existing pom in current dir, if yes try to set some // defaults final File p = new File("pom.xml"); String defaultGroupdId = "de.bbe-consulting.magento"; if (p.exists()) { SAXReader reader = new SAXReader(); Document document; try { document = reader.read(p); } catch (DocumentException e) { throw new MojoExecutionException("Error reading pom.xml " + e.getMessage(), e); } final String packagingType = getXmlNodeValueFromPom("/x:project/x:packaging", document); if (!"php".equals(packagingType)) { throw new MojoExecutionException("This mojo can only be run from a php project."); } final String parentArtifactId = getXmlNodeValueFromPom("/x:project/x:artifactId", document); defaultGroupdId = getXmlNodeValueFromPom("/x:project/x:groupId", document) + "." + parentArtifactId; } else { throw new MojoExecutionException("This mojo can only be run from a maven project root."); } final Properties executionProperties = session.getUserProperties(); final ArchetypeGenerationRequest request = new ArchetypeGenerationRequest() .setArchetypeGroupId(archetypeGroupId) .setArchetypeArtifactId(archetypeArtifactId) .setArchetypeVersion(archetypeVersion) .setOutputDirectory(basedir.getAbsolutePath()) .setLocalRepository(localRepository) .setArchetypeRepository(archetypeRepository) .setRemoteArtifactRepositories(remoteArtifactRepositories); try { if (interactiveMode.booleanValue()) { getLog().info("Generating project in Interactive mode"); } else { getLog().info("Generating project in Batch mode"); } final Properties rp = new Properties(); rp.setProperty("magentoArchetypeIdentifier", "snippet"); request.setProperties(rp); selector.selectArchetype(request, interactiveMode, archetypeCatalog); final List<String> requiredProperties = getRequiredArchetypeProperties(request, executionProperties); // not needed in partial mode as we don't touch any poms anyways executionProperties.put("groupId", defaultGroupdId); executionProperties.put("artifactId", "foobar"); executionProperties.put("version", "1.0-SNAPSHOT"); final Path srcPath = Paths.get(project.getBuild().getSourceDirectory()); String defaultMagentoModuleName = null; String defaultMagentoModuleNameSpace = null; String defaultMagentoModuleType = null; // try to auto guess some defaults if (Files.exists(srcPath)) { final List<Path> modulePaths = MagentoUtil.getMagentoModuleNames(srcPath); if (!modulePaths.isEmpty()) { final Path m = modulePaths.get(0); defaultMagentoModuleName = m.getFileName().toString(); defaultMagentoModuleNameSpace = m.getParent().getFileName().toString(); defaultMagentoModuleType = m.getParent().getParent().getFileName().toString(); } } if (requiredProperties.contains("magentoModuleName")) { String reqMagentoModuleName = queryer.getPropertyValue( "magentoModuleName", defaultMagentoModuleName); executionProperties.put("magentoModuleName", reqMagentoModuleName); executionProperties.put("magentoModuleNameLowerCase", reqMagentoModuleName.toLowerCase()); } if (requiredProperties.contains("magentoNameSpace")) { final String reqMagentoNamespace = queryer.getPropertyValue("magentoNamespace", defaultMagentoModuleNameSpace); executionProperties.put("magentoNameSpace", reqMagentoNamespace); } if (requiredProperties.contains("magentoModuleType")) { String reqMagentoNamespace = queryer.getPropertyValue("magentoModuleType", defaultMagentoModuleType); executionProperties.put("magentoModuleType", reqMagentoNamespace); } // query any custom required properties and fill LowerCase/LowerCamel version for (String property : requiredProperties) { if (!property.equals("artifactId") && !property.equals("groupId") && !property.equals("version") && !property.equals("package")) { if (!property.startsWith("magento") && !property.endsWith("LowerCase") && !property.endsWith("LowerCamel")) { final String propertyValue = queryer.getPropertyValue(property, null); if (propertyValue != null && !propertyValue.isEmpty()) { executionProperties.put(property, propertyValue); executionProperties.put(property + "LowerCase", propertyValue.toLowerCase()); String lowerCamel = propertyValue.substring(0, 1).toLowerCase() + propertyValue.substring(1); executionProperties.put(property + "LowerCamel", lowerCamel); } } } } configurator.configureArchetype(request, false, executionProperties); final ArchetypeGenerationResult generationResult = archetype.generateProjectFromArchetype(request); if (generationResult.getCause() != null) { throw new MojoFailureException(generationResult.getCause(), generationResult.getCause().getMessage(), generationResult.getCause().getMessage()); } } catch (Exception ex) { throw (MojoFailureException) new MojoFailureException(ex.getMessage()).initCause(ex); } final String artifactId = request.getArtifactId(); String postArchetypeGenerationGoals = request.getArchetypeGoals(); if (StringUtils.isEmpty(postArchetypeGenerationGoals)) { postArchetypeGenerationGoals = goals; } if (StringUtils.isNotEmpty(postArchetypeGenerationGoals)) { invokePostArchetypeGenerationGoals(postArchetypeGenerationGoals, artifactId); } // show post install message final Path postMessagePath = Paths.get("_post_install_msg.txt"); if (Files.exists(postMessagePath)) { try { FileUtil.logFileContents(postMessagePath.toString(), getLog()); Files.delete(postMessagePath); } catch (IOException e) { throw new MojoExecutionException("Error handling _post_install_msg.txt " + e.getMessage(), e); } } } }
/* * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. * * 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.switchyard.component.soap.composer; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.wsdl.Operation; import javax.wsdl.Part; import javax.wsdl.Port; import javax.xml.XMLConstants; import javax.xml.soap.AttachmentPart; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFault; import javax.xml.soap.SOAPMessage; import org.jboss.logging.Logger; import org.switchyard.Exchange; import org.switchyard.ExchangeState; import org.switchyard.Message; import org.switchyard.component.common.composer.BaseMessageComposer; import org.switchyard.component.soap.SOAPMessages; import org.switchyard.component.soap.util.SOAPUtil; import org.switchyard.component.soap.util.WSDLUtil; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * The SOAP implementation of MessageComposer simply copies the SOAP body into * the Message and SOAP headers into the Message's context, and vice-versa. * * @author Magesh Kumar B <mageshbk@jboss.com> (C) 2011 Red Hat Inc. */ public class SOAPMessageComposer extends BaseMessageComposer<SOAPBindingData> { // Constant suffix used for the reply wrapper when the composer is configured to // wrap response messages with operation name. private static final String DOC_LIT_WRAPPED_REPLY_SUFFIX = "Response"; private static final String CONTENT_DISPOSITION = "Content-Disposition"; private static final String CONTENT_ID = "Content-ID"; private static final String CONTENT_ID_START = "<"; private static final String CONTENT_DISPOSITION_NAME = "name="; private static final String CONTENT_DISPOSITION_QUOTE = "\""; private static final String TEMP_FILE_EXTENSION = ".tmp"; private static Logger _log = Logger.getLogger(SOAPMessageComposer.class); private Port _wsdlPort; private Boolean _documentStyle = false; private Boolean _mtomEnabled = false; private Boolean _xopExpand = false; private Boolean _unwrapped = false; private Boolean _copyNamespaces = false; /** * {@inheritDoc} */ @Override public Message compose(SOAPBindingData source, Exchange exchange) throws Exception { final SOAPMessage soapMessage = source.getSOAPMessage(); final Message message = exchange.createMessage(); getContextMapper().mapFrom(source, exchange.getContext(message)); final SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope(); if (envelope == null) { return message; } final SOAPBody soapBody = envelope.getBody(); if (soapBody == null) { throw SOAPMessages.MESSAGES.missingSOAPBodyFromRequest(); } try { if (soapBody.hasFault()) { // peel off the Fault element SOAPFault fault = soapBody.getFault(); if (_copyNamespaces) { Iterator i = fault.getVisibleNamespacePrefixes(); while (i.hasNext()) { String prefix = i.next().toString(); fault.addNamespaceDeclaration(prefix, fault.getNamespaceURI(prefix)); } } Node faultNode = fault.getParentNode().removeChild(fault); message.setContent(faultNode); return message; } List<Element> bodyChildren = getChildElements(soapBody); if (bodyChildren.size() > 1) { throw SOAPMessages.MESSAGES.foundMultipleSOAPElementsInSOAPBody(); } else if (bodyChildren.size() == 0 || bodyChildren.get(0) == null) { throw SOAPMessages.MESSAGES.couldNotFindSOAPElementInSOAPBody(); } Node bodyNode = bodyChildren.get(0); if (_documentStyle) { if (_unwrapped) { String opName = exchange.getContract().getConsumerOperation().getName(); // peel off the operation wrapper, if present if (opName != null && opName.equals(bodyNode.getLocalName())) { List<Element> subChildren = getChildElements(bodyNode); if (subChildren.size() == 0 || subChildren.size() > 1) { _log.debug("Unable to unwrap element: " + bodyNode.getLocalName() + ". A single child element is required."); } else { bodyNode = subChildren.get(0); } } } } if (_copyNamespaces) { Iterator i = soapBody.getVisibleNamespacePrefixes(); while (i.hasNext()) { String prefix = i.next().toString(); ((Element)bodyNode).setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + prefix, soapBody.getNamespaceURI(prefix)); } } bodyNode = bodyNode.getParentNode().removeChild(bodyNode); // SOAP Attachments Map<String, DataSource> attachments = new HashMap<String, DataSource>(); Iterator<AttachmentPart> aparts = (Iterator<AttachmentPart>) soapMessage.getAttachments(); while (aparts.hasNext()) { AttachmentPart apRequest = aparts.next(); String[] contentId = apRequest.getMimeHeader(CONTENT_ID); String name = null; if (_mtomEnabled) { if (contentId == null) { throw SOAPMessages.MESSAGES.contentIDHeaderMissingForAttachmentPart(); } name = contentId[0]; } else { name = apRequest.getDataHandler().getDataSource().getName(); if ((name == null) || (name.length() == 0)) { String[] disposition = apRequest.getMimeHeader(CONTENT_DISPOSITION); name = (contentId != null) ? contentId[0] : null; if ((name == null) && (disposition != null)) { int start = disposition[0].indexOf(CONTENT_DISPOSITION_NAME); String namePart = disposition[0].substring(start + CONTENT_DISPOSITION_NAME.length() + 1); int end = namePart.indexOf(CONTENT_DISPOSITION_QUOTE); name = namePart.substring(0, end); } else if (name == null) { // TODO: Identify the extension using content-type name = UUID.randomUUID() + TEMP_FILE_EXTENSION; } } } if (name.startsWith(CONTENT_ID_START)) { name = name.substring(1, name.length() - 1); } if (_mtomEnabled && _xopExpand) { // Using a different map because Camel throws java.lang.StackOverflowError // when we do message.removeAttachment(cid); attachments.put(name, apRequest.getDataHandler().getDataSource()); } else { message.addAttachment(name, apRequest.getDataHandler().getDataSource()); } } if (_mtomEnabled && _xopExpand) { // Expand xop message by inlining Base64 content bodyNode = SOAPUtil.expandXop((Element)bodyNode, attachments); } message.setContent(bodyNode); } catch (Exception ex) { if (ex instanceof SOAPException) { throw (SOAPException) ex; } throw new SOAPException(ex); } return message; } /** * {@inheritDoc} */ @Override public SOAPBindingData decompose(Exchange exchange, SOAPBindingData target) throws Exception { final SOAPMessage soapMessage = target.getSOAPMessage(); final Message message = exchange.getMessage(); final Boolean input = exchange.getPhase() == null; if (message != null) { // check to see if the payload is null or it's a full SOAP Message if (message.getContent() == null) { throw SOAPMessages.MESSAGES.unableToCreateSOAPBodyDueToNullMessageContent(); } if (message.getContent() instanceof SOAPMessage) { return new SOAPBindingData((SOAPMessage)message.getContent()); } try { // convert the message content to a form we can work with Node messageNode = message.getContent(Node.class); if (messageNode != null) { Node messageNodeImport = soapMessage.getSOAPBody().getOwnerDocument().importNode(messageNode, true); if (exchange.getState() != ExchangeState.FAULT || isSOAPFaultPayload(messageNode)) { if (_documentStyle) { String opName = exchange.getContract().getProviderOperation().getName(); if (_unwrapped) { String ns = getWrapperNamespace(opName, input); // Don't wrap if it's already wrapped if (!messageNodeImport.getLocalName().equals(opName + DOC_LIT_WRAPPED_REPLY_SUFFIX)) { Element wrapper = messageNodeImport.getOwnerDocument().createElementNS( ns, opName + DOC_LIT_WRAPPED_REPLY_SUFFIX); wrapper.appendChild(messageNodeImport); messageNodeImport = wrapper; } } } soapMessage.getSOAPBody().appendChild(messageNodeImport); // SOAP Attachments for (String name : message.getAttachmentMap().keySet()) { AttachmentPart apResponse = soapMessage.createAttachmentPart(); apResponse.setDataHandler(new DataHandler(message.getAttachment(name))); apResponse.setContentId("<" + name + ">"); soapMessage.addAttachmentPart(apResponse); } } else { // convert to SOAP Fault since ExchangeState is FAULT but the message is not SOAP Fault SOAPUtil.addFault(soapMessage).addDetail().appendChild(messageNodeImport); } } } catch (Exception e) { // Account for exception as payload in case of fault if (exchange.getState().equals(ExchangeState.FAULT) && exchange.getMessage().getContent() instanceof Exception) { // Throw the Exception and let JAX-WS format the fault. throw exchange.getMessage().getContent(Exception.class); } throw SOAPMessages.MESSAGES.unableToParseSOAPMessage(e); } } try { getContextMapper().mapTo(exchange.getContext(), target); } catch (Exception ex) { throw SOAPMessages.MESSAGES.failedToMapContextPropertiesToSOAPMessage(ex); } return target; } private boolean isSOAPFaultPayload(org.w3c.dom.Node messageNode) { String rootName = messageNode.getLocalName().toLowerCase(); if (rootName.equals("fault")) { String nsURI = messageNode.getNamespaceURI(); if (nsURI.equals(SOAPUtil.SOAP12_URI) || nsURI.equals(SOAPUtil.SOAP11_URI)) { return true; } } return false; } // Retrieves the immediate child of the specified parent element private List<Element> getChildElements(Node parent) { List<Element> children = new ArrayList<Element>(); NodeList nodes = parent.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) { children.add((Element)nodes.item(i)); } } return children; } private String getWrapperNamespace(String operationName, boolean input) { String ns = null; if (_wsdlPort != null) { Operation operation = WSDLUtil.getOperationByName(_wsdlPort, operationName); if (!_documentStyle) { ns = input ? operation.getInput().getMessage().getQName().getNamespaceURI() : operation.getOutput().getMessage().getQName().getNamespaceURI(); } else { // Note: WS-I Profile allows only one child under SOAPBody. Part part = input ? (Part)operation.getInput().getMessage().getParts().values().iterator().next() : (Part)operation.getOutput().getMessage().getParts().values().iterator().next(); if (part.getElementName() != null) { ns = part.getElementName().getNamespaceURI(); } else if (part.getTypeName() != null) { ns = part.getTypeName().getNamespaceURI(); } } } return ns; } /** * Get the WSDL Port used by this message composer. * @return the wsdlPort */ public Port getWsdlPort() { return _wsdlPort; } /** * Set the WSDL Port used by this message composer. * @param wsdlPort WSDL port */ public void setWsdlPort(Port wsdlPort) { _wsdlPort = wsdlPort; } /** * Check if the WSDL used is of 'document' style. * @return true if 'document' style, false otherwise */ public Boolean isDocumentStyle() { return _documentStyle; } /** * Set that the WSDL used is of 'document' style. * @param style true or false */ public void setDocumentStyle(Boolean style) { _documentStyle = style; } /** * Check if MTOM is enabled. * @return true if enabled, false otherwise */ public Boolean isMtomEnabled() { return _mtomEnabled; } /** * Set MTOM enabled/disabled. * @param enabled true or false */ public void setMtomEnabled(Boolean enabled) { _mtomEnabled = enabled; } /** * Check if XOP message should expanded. * @return true if expandable, false otherwise */ public Boolean isXopExpand() { return _xopExpand; } /** * Set XOP expansion. * @param expand true or false */ public void setXopExpand(Boolean expand) { _xopExpand = expand; } /** * Check if composer has set unwrap. * @return true if expandable, false otherwise */ public Boolean isUnwrapped() { return _unwrapped; } /** * Set unwrap flag. * @param unwrapped true or false */ public void setUnwrapped(Boolean unwrapped) { _unwrapped = unwrapped; } /** * Check if composer has set copyNamespaces. * @return true if copyNamespaces, false otherwise */ public Boolean isCopyNamespaces() { return _copyNamespaces; } /** * Set copyNamespaces flag. * @param copyNamespaces true or false */ public void setCopyNamespaces(Boolean copyNamespaces) { _copyNamespaces = copyNamespaces; } }
/* * Copyright (C) 2013 salesforce.com, 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.auraframework.util.date; import java.text.DateFormat; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; import org.auraframework.util.test.annotation.UnAdaptableTest; import org.auraframework.util.test.util.UnitTestCase; /** * @since: 224 */ public class DateServiceTest extends UnitTestCase { private StringBuilder sb; @SuppressWarnings("serial") private static class DebugDate extends Date { private final String debugInfo; DebugDate(long time, String debugInfo) { super(time); this.debugInfo = debugInfo; } /* * } */ DebugDate(long time) { this(time, "Date(" + time + ")"); } @Override public String toString() { return debugInfo; } } @Override public void setUp() throws Exception{ super.setUp(); sb = new StringBuilder(); } /** * Test Data */ final Date[] DATE_TIME = { new DebugDate(1), // now new DebugDate(1000L), // 12:00:01 AM GMT new DebugDate(1333322872649L), // 4:27:52.649 PM PDT (GMT-7) new DebugDate(0) // 00:00:00.000 GMT }; public static final int[] DATE_TIME_STYLES = { DateFormat.SHORT, DateFormat.MEDIUM, DateFormat.LONG, DateFormat.FULL, -1 }; public static final String[] SIMPLE_DATE_FORMAT_PATTERNS = { "yyyy.MM.dd G 'at' HH:mm:ss z", "eee, MMM d, yyyy", "h:mm a", "hh 'o''clock' a, zzzz", "K:mm a, z", "yyyyy.MMMMM.dd GGG hh:mm a", "eee, d MMM yyyy HH:mm:ss Z", "yyMMddHHmmssZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZ" }; public List<LocaleConfig> getConfigs() { List<LocaleConfig> configs = new ArrayList<>(); configs.add(new LocaleConfig(Locale.TRADITIONAL_CHINESE, TimeZone.getTimeZone("GMT+8"))); configs.add(new LocaleConfig(Locale.US, TimeZone.getTimeZone("EST"))); configs.add(new LocaleConfig(new Locale("en", "US"), TimeZone.getTimeZone("PDT"))); return configs; } public static class LocaleConfig { private Locale locale = null; private TimeZone timeZone = null; public LocaleConfig(Locale locale) { setLocale(locale); setTimeZone(TimeZone.getDefault()); } public LocaleConfig(Locale locale, TimeZone timeZone) { setLocale(locale); setTimeZone(timeZone); } public Locale getLocale() { return this.locale; } public void setLocale(Locale locale) { this.locale = locale; } public TimeZone getTimeZone() { return this.timeZone; } public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; } } /** * NOTE: api's converter.format(date) and converter.parse(date) will rely on * the TimeZone.getDefault() value to do their job. Thus, tests for these * will return different results based on default TimeZone that is set. */ /** * Tests for different converters including parsing and formatting */ public void testGetDateTimeISO8601Converter() throws Exception { DateConverter converter = null; converter = DateServiceImpl.get().getDateTimeISO8601Converter(); for (LocaleConfig c : getConfigs()) { TimeZone tz = c.getTimeZone(); for (Date d : DATE_TIME) { // formatting String formattedDate = converter.format(d, tz); // parsing Date parsedDate = converter.parse(formattedDate, tz); String text = "Input date:" + d.toString() + "\t\tFormatted date:" + formattedDate + "\t\tParsed date:" + parsedDate.getTime() + "\t\tTimezone:" + tz.getID() + "\n"; sb.append(text); } } goldFileText("Test:testGetDateTimeISO8601Converter\n" + sb.toString()); } public void testGetDateISO8601Converter() throws Exception { DateConverter converter = null; converter = DateServiceImpl.get().getDateISO8601Converter(); for (LocaleConfig c : getConfigs()) { TimeZone tz = c.getTimeZone(); for (Date d : DATE_TIME) { // formatting String formattedDate = converter.format(d, tz); // parsing Date parsedDate = converter.parse(formattedDate, tz); String text = "Input date:" + d.toString() + "\t\tFormatted date:" + formattedDate + "\t\tParsed date:" + parsedDate.getTime() + "\t\tTimezone:" + tz.getID() + "\n"; sb.append(text); } } goldFileText("Test:testGetDateISO8601Converter\n" + sb.toString()); } public void testGetGenericISO8601Converter() throws Exception { String text = null; DateConverter converter = DateServiceImpl.get().getGenericISO8601Converter(); ; // date time for (LocaleConfig c : getConfigs()) { TimeZone tz = c.getTimeZone(); for (Date d : DATE_TIME) { // formatting String formattedDate = converter.format(d, tz); // parsing Date parsedDate = converter.parse(formattedDate, tz); text = "Input date:" + d.toString() + "\t\tFormatted date:" + formattedDate + "\t\tParsed date:" + parsedDate.getTime() + "\t\tTimezone:" + tz.getID() + "\n"; sb.append(text); } } // datetime no seconds String DATETIME_NOSECONDS[] = { "2012-06-05T13:12Z" }; for (LocaleConfig c : getConfigs()) { TimeZone tz = c.getTimeZone(); for (String d : DATETIME_NOSECONDS) { try { // parsing Date parsedDate = converter.parse(d, tz); // formatting String formattedDate = converter.format(parsedDate, tz); text = "Input date:" + d.toString() + "\t\tFormatted date:" + formattedDate + "\t\tParsed date:" + parsedDate.getTime() + "\n"; sb.append(text); } catch (IllegalArgumentException e) { sb.append(e.getMessage() + "\n"); } } } goldFileText("Test:testGetGenericISO8601Converter\n" + sb.toString()); } @UnAdaptableTest("Date format on SFDC handles differently than standalone Aura, need to investigate") public void testGetDateStyleConverter_locale_dateStyle() throws Exception { DateConverter converter = null; String text = null; for (LocaleConfig c : getConfigs()) { Locale l = c.getLocale(); TimeZone tz = c.getTimeZone(); for (Date d : DATE_TIME) { for (int ds : DATE_TIME_STYLES) { if (ds > -1) { converter = DateServiceImpl.get().getDateStyleConverter(l, ds); // formatting String formattedDate = converter.format(d, tz); // parsing try { Date parsedDate = converter.parse(formattedDate, tz); text = "Input date:" + d.toString() + "\t\tFormatted date:" + formattedDate + "\t\tParsed date:" + parsedDate.getTime() + "\t\tLocale:" + l.getDisplayName() + "\t\tTimeZone: " + tz.getID() + "\t\tDate style: " + ds + "\n"; sb.append(text); } catch (IllegalArgumentException e) { sb.append(e.getMessage() + "\n"); } } } } } goldFileText("Test:testGetDateStyleConverter_locale_dateStyle\n" + sb.toString()); } @UnAdaptableTest("Date format on SFDC handles differently than standalone Aura, need to investigate") public void testGetTimeStyleConverter_locale_timeStyle() throws Exception { DateConverter converter = null; String text = null; for (LocaleConfig c : getConfigs()) { Locale l = c.getLocale(); TimeZone tz = c.getTimeZone(); for (Date d : DATE_TIME) { for (int ts : DATE_TIME_STYLES) { if (ts > -1) { converter = DateServiceImpl.get().getTimeStyleConverter(l, ts); // formatting String formattedDate = converter.format(d, tz); // parsing try { Date parsedDate = converter.parse(formattedDate, tz); text = "Input date:" + d.toString() + "\t\tFormatted date:" + formattedDate + "\t\tParsed date:" + parsedDate.getTime() + "\t\tLocale:" + l.getDisplayName() + "\t\tTimeZone: " + tz.getID() + "\t\tTime style: " + ts + "\n"; sb.append(text); } catch (IllegalArgumentException e) { sb.append(e.getMessage() + "\n"); } } } } } goldFileText("Test:testGetTimeStyleConverter_locale_timeStyle\n" + sb.toString()); } @UnAdaptableTest("Date format on SFDC handles differently than standalone Aura, need to investigate") public void testGetDateTimeStyleConverter_locale_dateStyle_timeStyle() throws Exception { DateConverter converter = null; String text = null; for (LocaleConfig c : getConfigs()) { Locale l = c.getLocale(); TimeZone tz = c.getTimeZone(); for (Date d : DATE_TIME) { for (int ds : DATE_TIME_STYLES) { for (int ts : DATE_TIME_STYLES) { if ((ds + ts) > 0) { converter = DateServiceImpl.get().getDateTimeStyleConverter(l, ds, ts); // formatting String formattedDate = converter.format(d, tz); // parsing try { Date parsedDate = converter.parse(formattedDate, tz); text = "Input date:" + d.toString() + "\t\tFormatted date:" + formattedDate + "\t\tParsed date:" + parsedDate.getTime() + "\t\tLocale:" + l.getDisplayName() + "\t\tTimeZone: " + tz.getID() + "\t\tDate style: " + ds + "\t\tTime style: " + ts + "\n"; sb.append(text); } catch (IllegalArgumentException e) { sb.append(e.getMessage() + "\n"); } } } } } } goldFileText("Test:testGetDateTimeStyleConverter_locale_dateStyle_timeStyle\n" + sb.toString()); } @UnAdaptableTest("Date format on SFDC handles differently than standalone Aura, need to investigate") public void testGetPatternConverter_locale_pattern() throws Exception { DateConverter converter = null; String text = null; // format/parse(date, timezone) // SimpleDateFormat style for (LocaleConfig c : getConfigs()) { Locale l = c.getLocale(); TimeZone tz = c.getTimeZone(); for (Date d : DATE_TIME) { for (String pattern : SIMPLE_DATE_FORMAT_PATTERNS) { converter = DateServiceImpl.get().getPatternConverter(l, pattern); // formatting String formattedDate = converter.format(d, tz); // parsing try { Date parsedDate = converter.parse(formattedDate, tz); text = "Input date:" + d.toString() + "\t\tFormatted date:" + formattedDate + "\t\tParsed date:" + parsedDate.getTime() + "\t\tLocale:" + l.getDisplayName() + "\t\tTimeZone:" + tz.getID() + "\t\tSimpleDateFormat pattern:" + pattern + "\n"; sb.append(text); } catch (IllegalArgumentException | DateTimeParseException e) { sb.append(e.getMessage() + "\n"); } } } } goldFileText("Test:testGetPatternConverter_locale_pattern\n" + sb.toString()); } public void testGetStyle() { String[] styles = { "full", "long", "medium", "short" }; int i = -1; for (String s : styles) { i++; int dateFormatStyleInteger = DateServiceImpl.get().getStyle(s); assertEquals("# date format style integer does not match for style " + s, dateFormatStyleInteger, i); } } public void testDateTimeNoneConverter() { try { DateServiceImpl.get().getDateTimeStyleConverter(Locale.US, -1, -1); } catch (IllegalArgumentException e) { assertEquals("# Incorrect exception message for api getDateTimeStyleConverter(Locale.US, -1, -1)", "Both date style and time style cannot be none", e.getMessage()); } try { DateServiceImpl.get().getDateStyleConverter(Locale.US, -1); } catch (IllegalArgumentException e) { assertEquals("# Incorrect exception message for api getDateStyleConverter(Locale.US, -1)", "Both date style and time style cannot be none", e.getMessage()); } try { DateServiceImpl.get().getTimeStyleConverter(Locale.US, -1); } catch (IllegalArgumentException e) { assertEquals("# Incorrect exception message for api getTimeStyleConverter(Locale.US, -1)", "Both date style and time style cannot be none", e.getMessage()); } } public void testNullDataForConverters() { try { DateServiceImpl.get().getDateTimeStyleConverter(null, -0, -0); } catch (IllegalArgumentException e) { assertEquals("# Incorrect exception message for api getDateTimeStyleConverter(null, -0, -0)", "Locale must be provided", e.getMessage()); } try { DateServiceImpl.get().getPatternConverter(Locale.US, null); } catch (IllegalArgumentException e) { assertEquals("# Incorrect exception message for api getPatternConverter(null, null)", "Pattern must be provided", e.getMessage()); } try { DateServiceImpl.get().getStyle(null); } catch (IllegalArgumentException e) { assertEquals("# Incorrect exception message for api getStyle(null)", "Style is null", e.getMessage()); } } public void testNullDataForFormatAndParse() { try { DateServiceImpl.get().getDateTimeISO8601Converter().format(null); } catch (IllegalArgumentException e) { assertEquals("# Incorrect exception message for api getDateTimeISO8601Converter().format(null)", "Date can not be null", e.getMessage()); } try { DateServiceImpl.get().getDateTimeISO8601Converter().format(null, null); } catch (IllegalArgumentException e) { assertEquals("# Incorrect exception message for api getDateTimeISO8601Converter().format(null, null)", "Date can not be null", e.getMessage()); } try { DateServiceImpl.get().getDateTimeISO8601Converter().parse(null); } catch (IllegalArgumentException e) { assertEquals("# Incorrect exception message for api getDateTimeISO8601Converter().parse(null)", "Date can not be null", e.getMessage()); } try { DateServiceImpl.get().getDateTimeISO8601Converter().parse(null, null); } catch (IllegalArgumentException e) { assertEquals("# Incorrect exception message for api getDateTimeISO8601Converter().parse(null, null)", "Date can not be null", e.getMessage()); } } public void testFormatWithTimeZone() { // this is equivalent to 1970-01-01 5pm EST long offsetEST = 5 * 60 * 60 * 1000; Date testDate = new Date(offsetEST); DateConverter converter = DateServiceImpl.get().getDateISO8601Converter(); // gmt-8 here is the equivalent of using the default JDK timezone // hardcoded so the test works wherever it is run String result = converter.format(testDate, TimeZone.getTimeZone("GMT-8")); // 1970-01-01 midnight EST is 1969-12-31 9pm PST assertEquals("1969-12-31", result); // 1970-01-01 midnight EST should match EST, right? result = converter.format(testDate, TimeZone.getTimeZone("GMT-5")); assertEquals("1970-01-01", result); // switch to datetime converter converter = DateServiceImpl.get().getDateTimeISO8601Converter(); // gmt-8 here is the equivalent of using the default JDK timezone // hardcoded so the test works wherever it is run result = converter.format(testDate, TimeZone.getTimeZone("GMT-8")); // 9PM PST = midnight EST, right? note the 21:00 and -08:00 assertEquals("1969-12-31T21:00:00.000-08:00", result); // and a quick reverse check to verify assertEquals(offsetEST, converter.parse(result).getTime()); // 1970-01-01 midnight EST should match EST result = converter.format(testDate, TimeZone.getTimeZone("GMT-5")); assertEquals("1970-01-01T00:00:00.000-05:00", result); } public void testParseWithTimeZone() { // if someone types in 1970-01-01, and they're in GMT - that's date=0L String testDate = "1970-01-01"; long offsetEST = 5 * 60 * 60 * 1000; long offsetGMT8 = -(8 * 60 * 60 * 1000); DateConverter converter = DateServiceImpl.get().getDateISO8601Converter(); // 1970-01-01, and they're in EST, that's 5 hours behind. // but when they hit 1970-01-01, they're 5 hours later than when GMT // folks hit it // date=0 PLUS (5x60x60x1000) Date resultDate = converter.parse(testDate, TimeZone.getTimeZone("EST")); assertEquals(offsetEST, resultDate.getTime()); // 1970-01-01, and they're in China, that's 8 hours ahead of GMT. // but when they hit 1970-01-01, they're 8 hours earlier than when GMT // folks hit it // date=0 MINUS (8x60x60x1000) resultDate = converter.parse(testDate, TimeZone.getTimeZone("GMT+8")); assertEquals(offsetGMT8, resultDate.getTime()); // If parse, without timezone is called, the ISO8601's default // timezone should be used ("GMT"). resultDate = converter.parse(testDate); assertEquals(-TimeZone.getTimeZone("GMT").getRawOffset(), resultDate.getTime()); // switch to dateTime converter converter = DateServiceImpl.get().getDateTimeISO8601Converter(); // timezone is in this date - EST again - so we should get the same as // above testDate = "1970-01-01T00:00:00.000-05:00"; resultDate = converter.parse(testDate); assertEquals(offsetEST, resultDate.getTime()); // specifying a timezone shouldn't change a thing resultDate = converter.parse(testDate, TimeZone.getTimeZone("GMT+8")); assertEquals(offsetEST, resultDate.getTime()); } }
/* * 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.cassandra.cql3; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import com.google.common.base.Joiner; import org.apache.cassandra.db.ColumnFamily; import org.apache.cassandra.db.marshal.CollectionType; import org.apache.cassandra.db.marshal.MapType; import org.apache.cassandra.db.marshal.SetType; import org.apache.cassandra.exceptions.InvalidRequestException; import org.apache.cassandra.serializers.MarshalException; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; /** * Static helper methods and classes for sets. */ public abstract class Sets { private Sets() {} public static ColumnSpecification valueSpecOf(ColumnSpecification column) { return new ColumnSpecification(column.ksName, column.cfName, new ColumnIdentifier("value(" + column.name + ")", true), ((SetType)column.type).elements); } public static class Literal implements Term.Raw { private final List<Term.Raw> elements; public Literal(List<Term.Raw> elements) { this.elements = elements; } public Term prepare(ColumnSpecification receiver) throws InvalidRequestException { validateAssignableTo(receiver); // We've parsed empty maps as a set literal to break the ambiguity so // handle that case now if (receiver.type instanceof MapType && elements.isEmpty()) return new Maps.Value(Collections.<ByteBuffer, ByteBuffer>emptyMap()); ColumnSpecification valueSpec = Sets.valueSpecOf(receiver); Set<Term> values = new HashSet<Term>(elements.size()); boolean allTerminal = true; for (Term.Raw rt : elements) { Term t = rt.prepare(valueSpec); if (t.containsBindMarker()) throw new InvalidRequestException(String.format("Invalid set literal for %s: bind variables are not supported inside collection literals", receiver)); if (t instanceof Term.NonTerminal) allTerminal = false; values.add(t); } DelayedValue value = new DelayedValue(((SetType)receiver.type).elements, values); return allTerminal ? value.bind(Collections.<ByteBuffer>emptyList()) : value; } private void validateAssignableTo(ColumnSpecification receiver) throws InvalidRequestException { if (!(receiver.type instanceof SetType)) { // We've parsed empty maps as a set literal to break the ambiguity so // handle that case now if (receiver.type instanceof MapType && elements.isEmpty()) return; throw new InvalidRequestException(String.format("Invalid set literal for %s of type %s", receiver, receiver.type.asCQL3Type())); } ColumnSpecification valueSpec = Sets.valueSpecOf(receiver); for (Term.Raw rt : elements) { if (!rt.isAssignableTo(valueSpec)) throw new InvalidRequestException(String.format("Invalid set literal for %s: value %s is not of type %s", receiver, rt, valueSpec.type.asCQL3Type())); } } public boolean isAssignableTo(ColumnSpecification receiver) { try { validateAssignableTo(receiver); return true; } catch (InvalidRequestException e) { return false; } } @Override public String toString() { return "{" + Joiner.on(", ").join(elements) + "}"; } } public static class Value extends Term.Terminal { public final Set<ByteBuffer> elements; public Value(Set<ByteBuffer> elements) { this.elements = elements; } public static Value fromSerialized(ByteBuffer value, SetType type) throws InvalidRequestException { try { // Collections have this small hack that validate cannot be called on a serialized object, // but compose does the validation (so we're fine). Set<?> s = (Set<?>)type.compose(value); Set<ByteBuffer> elements = new LinkedHashSet<ByteBuffer>(s.size()); for (Object element : s) elements.add(type.elements.decompose(element)); return new Value(elements); } catch (MarshalException e) { throw new InvalidRequestException(e.getMessage()); } } public ByteBuffer get() { return CollectionType.pack(new ArrayList<ByteBuffer>(elements), elements.size()); } } // See Lists.DelayedValue public static class DelayedValue extends Term.NonTerminal { private final Comparator<ByteBuffer> comparator; private final Set<Term> elements; public DelayedValue(Comparator<ByteBuffer> comparator, Set<Term> elements) { this.comparator = comparator; this.elements = elements; } public boolean containsBindMarker() { // False since we don't support them in collection return false; } public void collectMarkerSpecification(VariableSpecifications boundNames) { } public Value bind(List<ByteBuffer> values) throws InvalidRequestException { Set<ByteBuffer> buffers = new TreeSet<ByteBuffer>(comparator); for (Term t : elements) { ByteBuffer bytes = t.bindAndGet(values); if (bytes == null) throw new InvalidRequestException("null is not supported inside collections"); // We don't support value > 64K because the serialization format encode the length as an unsigned short. if (bytes.remaining() > FBUtilities.MAX_UNSIGNED_SHORT) throw new InvalidRequestException(String.format("Set value is too long. Set values are limited to %d bytes but %d bytes value provided", FBUtilities.MAX_UNSIGNED_SHORT, bytes.remaining())); buffers.add(bytes); } return new Value(buffers); } } public static class Marker extends AbstractMarker { protected Marker(int bindIndex, ColumnSpecification receiver) { super(bindIndex, receiver); assert receiver.type instanceof SetType; } public Value bind(List<ByteBuffer> values) throws InvalidRequestException { ByteBuffer value = values.get(bindIndex); return value == null ? null : Value.fromSerialized(value, (SetType)receiver.type); } } public static class Setter extends Operation { public Setter(ColumnIdentifier column, Term t) { super(column, t); } public void execute(ByteBuffer rowKey, ColumnFamily cf, ColumnNameBuilder prefix, UpdateParameters params) throws InvalidRequestException { // delete + add ColumnNameBuilder column = prefix.add(columnName.key); cf.addAtom(params.makeTombstoneForOverwrite(column.build(), column.buildAsEndOfRange())); Adder.doAdd(t, cf, column, params); } } public static class Adder extends Operation { public Adder(ColumnIdentifier column, Term t) { super(column, t); } public void execute(ByteBuffer rowKey, ColumnFamily cf, ColumnNameBuilder prefix, UpdateParameters params) throws InvalidRequestException { doAdd(t, cf, prefix.add(columnName.key), params); } static void doAdd(Term t, ColumnFamily cf, ColumnNameBuilder columnName, UpdateParameters params) throws InvalidRequestException { Term.Terminal value = t.bind(params.variables); if (value == null) return; assert value instanceof Sets.Value : value; Set<ByteBuffer> toAdd = ((Sets.Value)value).elements; for (ByteBuffer bb : toAdd) { ByteBuffer cellName = columnName.copy().add(bb).build(); cf.addColumn(params.makeColumn(cellName, ByteBufferUtil.EMPTY_BYTE_BUFFER)); } } } public static class Discarder extends Operation { public Discarder(ColumnIdentifier column, Term t) { super(column, t); } public void execute(ByteBuffer rowKey, ColumnFamily cf, ColumnNameBuilder prefix, UpdateParameters params) throws InvalidRequestException { Term.Terminal value = t.bind(params.variables); if (value == null) return; // This can be either a set or a single element Set<ByteBuffer> toDiscard = value instanceof Constants.Value ? Collections.singleton(((Constants.Value)value).bytes) : ((Sets.Value)value).elements; ColumnNameBuilder column = prefix.add(columnName.key); for (ByteBuffer bb : toDiscard) { ByteBuffer cellName = column.copy().add(bb).build(); cf.addColumn(params.makeTombstone(cellName)); } } } }
package be.normegil.librarium.model.data; import be.normegil.librarium.WarningTypes; import be.normegil.librarium.model.data.fake.FakeMedia; import be.normegil.librarium.tool.DataFactory; import be.normegil.librarium.tool.FactoryRepository; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.time.LocalDate; import java.util.*; import static org.junit.Assert.assertEquals; public class UTMedia { @SuppressWarnings(WarningTypes.UNCHECKED_CAST) private static final DataFactory<Media> FACTORY = FactoryRepository.get(Media.class); @SuppressWarnings(WarningTypes.UNCHECKED_CAST) private static final DataFactory<Universe> UNIVERSE_FACTORY = FactoryRepository.get(Universe.class); @SuppressWarnings(WarningTypes.UNCHECKED_CAST) private static final DataFactory<Support> SUPPORT_FACTORY = FactoryRepository.get(Support.class); private Media entity; private Collection<Universe> universes = new ArrayList<>(); private Collection<Support> supports = new ArrayList<>(); private Map<Support, LocalDate> releaseDates = new HashMap<>(); @Before public void setUp() throws Exception { entity = FACTORY.getNew(); universes = entity.getUniverses(); supports = entity.getSupports(); releaseDates = entity.getReleaseDates(); } @After public void tearDown() throws Exception { releaseDates = null; supports = null; universes = null; entity = null; } @Test public void testCopyConstructor() throws Exception { Media copy = new FakeMedia(entity); assertEquals(entity, copy); } @Test public void testAddAllUniverses() throws Exception { Collection<Universe> toAdd = new HashSet<>(); toAdd.add(UNIVERSE_FACTORY.getNext()); toAdd.add(UNIVERSE_FACTORY.getNext()); toAdd.add(UNIVERSE_FACTORY.getNext()); universes.addAll(toAdd); entity.addAllUniverses(toAdd); assertEquals(universes, entity.getUniverses()); } @Test public void testAddUniverse() throws Exception { Universe toAdd = UNIVERSE_FACTORY.getNext(); universes.add(toAdd); entity.addUniverse(toAdd); assertEquals(universes, entity.getUniverses()); } @Test public void testRemoveAllUniverses() throws Exception { Universe base = UNIVERSE_FACTORY.getNext(); Universe second = UNIVERSE_FACTORY.getNext(); Universe third = UNIVERSE_FACTORY.getNext(); Collection<Universe> toAdd = new HashSet<>(); toAdd.add(base); toAdd.add(second); toAdd.add(third); Collection<Universe> toRemove = new HashSet<>(); toRemove.add(second); toRemove.add(third); universes.addAll(toAdd); entity.addAllUniverses(toAdd); universes.removeAll(toRemove); entity.removeAllUniverses(toRemove); assertEquals(universes, entity.getUniverses()); } @Test public void testRemoveUniverse() throws Exception { Universe toRemove = entity.getUniverses().iterator().next(); universes.remove(toRemove); entity.removeUniverse(toRemove); assertEquals(universes, entity.getUniverses()); } @Test public void testAddAllSupports() throws Exception { Collection<Support> toAdd = new HashSet<>(); toAdd.add(SUPPORT_FACTORY.getNext()); toAdd.add(SUPPORT_FACTORY.getNext()); toAdd.add(SUPPORT_FACTORY.getNext()); supports.addAll(toAdd); entity.addAllSupports(toAdd); assertEquals(supports, entity.getSupports()); } @Test public void testAddSupport() throws Exception { Support toAdd = SUPPORT_FACTORY.getNext(); supports.add(toAdd); entity.addSupport(toAdd); assertEquals(supports, entity.getSupports()); } @Test public void testRemoveAllSupports() throws Exception { Support base = SUPPORT_FACTORY.getNext(); Support second = SUPPORT_FACTORY.getNext(); Support third = SUPPORT_FACTORY.getNext(); Collection<Support> toAdd = new HashSet<>(); toAdd.add(base); toAdd.add(second); toAdd.add(third); Collection<Support> toRemove = new HashSet<>(); toRemove.add(second); toRemove.add(third); supports.addAll(toAdd); entity.addAllSupports(toAdd); supports.removeAll(toRemove); entity.removeAllSupports(toRemove); assertEquals(supports, entity.getSupports()); } @Test public void testRemoveSupport() throws Exception { Support toRemove = entity.getSupports().iterator().next(); supports.remove(toRemove); entity.removeSupport(toRemove); assertEquals(supports, entity.getSupports()); } @Test public void testGetReleaseDate() throws Exception { Support support = SUPPORT_FACTORY.getNext(); LocalDate date = LocalDate.of(1990, 01, 01); entity.addReleaseDate(support, date); assertEquals(date, entity.getReleaseDate(support)); } @Test public void testAddAllReleaseDates() throws Exception { Map<Support, LocalDate> toAdd = new HashMap<>(); toAdd.put(SUPPORT_FACTORY.getNext(), LocalDate.now()); toAdd.put(SUPPORT_FACTORY.getNext(), LocalDate.now()); toAdd.put(SUPPORT_FACTORY.getNext(), LocalDate.now()); releaseDates.putAll(toAdd); entity.addAllReleaseDates(toAdd); assertEquals(releaseDates, entity.getReleaseDates()); } @Test public void testAddReleaseDate() throws Exception { Support toAddSupport = SUPPORT_FACTORY.getNext(); LocalDate toAddDate = LocalDate.now(); releaseDates.put(toAddSupport, toAddDate); entity.addReleaseDate(toAddSupport, toAddDate); assertEquals(releaseDates, entity.getReleaseDates()); } @Test public void testRemoveAllReleaseDates() throws Exception { Support base = SUPPORT_FACTORY.getNext(); Support second = SUPPORT_FACTORY.getNext(); Support third = SUPPORT_FACTORY.getNext(); LocalDate date = LocalDate.now(); Map<Support, LocalDate> toAdd = new HashMap<>(); toAdd.put(base, date); toAdd.put(second, date); toAdd.put(third, date); Collection<Support> toRemove = new HashSet<>(); toRemove.add(second); toRemove.add(third); releaseDates.putAll(toAdd); entity.addAllReleaseDates(toAdd); for (Support support : toRemove) { releaseDates.remove(support); } entity.removeAllReleaseDates(toRemove); assertEquals(releaseDates, entity.getReleaseDates()); } @Test public void testRemoveReleaseDate() throws Exception { Support support = entity.getReleaseDates().keySet().iterator().next(); releaseDates.remove(support); entity.removeReleaseDate(support); assertEquals(releaseDates, entity.getReleaseDates()); } }
/* * Copyright 2016 - 2021 Acosix GmbH * * 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 de.acosix.alfresco.utility.repo.batch; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import org.alfresco.repo.batch.BatchProcessWorkProvider; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.service.cmr.dictionary.DataTypeDefinition; import org.alfresco.service.cmr.dictionary.DictionaryService; import org.alfresco.service.cmr.dictionary.PropertyDefinition; import org.alfresco.service.cmr.dictionary.TypeDefinition; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.search.LimitBy; import org.alfresco.service.cmr.search.ResultSet; import org.alfresco.service.cmr.search.SearchParameters; import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.namespace.NamespaceService; import org.alfresco.service.namespace.QName; import org.alfresco.util.PropertyCheck; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; /** * This class provides a generic work provider for batch operations that process generic {@link NodeRef NodeRefs} as units of work, querying * with transactional metadata query-compatible CMIS queries and avoiding problematic preloading of node data, which can delay batch * processing and in the worst case overwhelm transactional caches. The queries make use of pagination using a configured textual property * as from/to restrictions. * * @author Axel Faust */ public class PropertyOrderedTransactionalNodeBatchWorkProvider implements BatchProcessWorkProvider<NodeRef>, InitializingBean { private static final Logger LOGGER = LoggerFactory.getLogger(PropertyOrderedTransactionalNodeBatchWorkProvider.class); protected NamespaceService namespaceService; protected DictionaryService dictionaryService; protected SearchService searchService; protected String typeName; protected String propertyName; protected String runAsUser = AuthenticationUtil.getSystemUserName(); protected QName typeQName; protected QName propertyQName; protected char maxCharacter = '\0'; protected boolean done; protected boolean useCharacterUpperBound = true; protected final Set<NodeRef> retrievedNodes = new HashSet<>(); /** * * {@inheritDoc} */ @Override public void afterPropertiesSet() { PropertyCheck.mandatory(this, "namespaceService", this.namespaceService); PropertyCheck.mandatory(this, "searchService", this.searchService); if (this.typeQName == null) { PropertyCheck.mandatory(this, "dictionaryService", this.dictionaryService); PropertyCheck.mandatory(this, "typeName", this.typeName); this.typeQName = QName.resolveToQName(this.namespaceService, this.typeName); if (this.typeQName == null) { throw new IllegalStateException("Type name " + this.typeName + " cannot be resolved to a QName"); } final TypeDefinition typeDef = this.dictionaryService.getType(this.typeQName); if (typeDef == null) { throw new IllegalStateException("The type " + this.typeName + " is not defined in the data model"); } } if (this.propertyQName == null) { PropertyCheck.mandatory(this, "dictionaryService", this.dictionaryService); PropertyCheck.mandatory(this, "propertyName", this.propertyName); this.propertyQName = QName.resolveToQName(this.namespaceService, this.propertyName); if (this.propertyQName == null) { throw new IllegalStateException("Property name " + this.propertyName + " cannot be resolved to a QName"); } final PropertyDefinition propertyDef = this.dictionaryService.getProperty(this.propertyQName); if (propertyDef == null) { throw new IllegalStateException("The property " + this.propertyName + " is not defined in the data model"); } if (!DataTypeDefinition.TEXT.equals(propertyDef.getDataType().getName())) { throw new IllegalStateException("The property " + this.propertyName + " is not defined as a d:text property"); } } } /** * @param namespaceService * the namespaceService to set */ public void setNamespaceService(final NamespaceService namespaceService) { this.namespaceService = namespaceService; } /** * @param dictionaryService * the dictionaryService to set */ public void setDictionaryService(final DictionaryService dictionaryService) { this.dictionaryService = dictionaryService; } /** * @param searchService * the searchService to set */ public void setSearchService(final SearchService searchService) { this.searchService = searchService; } /** * @param typeName * the typeName to set */ public void setTypeName(final String typeName) { this.typeName = typeName; } /** * @param propertyName * the propertyName to set */ public void setPropertyName(final String propertyName) { this.propertyName = propertyName; } /** * @param runAsUser * the runAsUser to set */ public void setRunAsUser(final String runAsUser) { this.runAsUser = runAsUser; } /** * * {@inheritDoc} */ @Override public int getTotalEstimatedWorkSize() { // can't efficiently determine number of affected nodes without doing an actual (expensive) query return 0; } /** * * {@inheritDoc} */ @Override public Collection<NodeRef> getNextWork() { final List<NodeRef> nextWork = new ArrayList<>(); AuthenticationUtil.runAs(() -> { while (!this.done && nextWork.isEmpty()) { final char lastMaxCharacter = this.maxCharacter; // check the last limit character (for name-based pagination to keep DB query highly selective) switch (this.maxCharacter) { case '\0': this.maxCharacter = '0'; break; case '9': this.maxCharacter = 'A'; break; case 'Z': this.maxCharacter = 'a'; break; case 'z': this.useCharacterUpperBound = false; break; default: this.maxCharacter += 1; } final SearchParameters sp = new SearchParameters(); sp.setLanguage(SearchService.LANGUAGE_CMIS_ALFRESCO); sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE); final String query; if (this.useCharacterUpperBound) { // query with upper bound as long as we are in a sensible ASCII range final MessageFormat mf = new MessageFormat( lastMaxCharacter != '\0' ? "SELECT * FROM {0} P WHERE P.{1} <= ''{2}'' AND P.{1} > ''{3}''" : "SELECT * FROM {0} P WHERE P.{1} <= ''{2}''", Locale.ENGLISH); query = mf.format(new Object[] { this.typeQName.toPrefixString(this.namespaceService), this.propertyQName.toPrefixString(this.namespaceService), String.valueOf(this.maxCharacter), String.valueOf(lastMaxCharacter) }); } else { // for user names in unicode and beyond ASCII range we can't really do name-based pagination anymore final MessageFormat mf = new MessageFormat( lastMaxCharacter != '\0' ? "SELECT * FROM {0} P WHERE P.{1} > ''{2}''" : "SELECT * FROM {0}", Locale.ENGLISH); query = mf.format(new Object[] { this.typeQName.toPrefixString(this.namespaceService), this.propertyQName.toPrefixString(this.namespaceService), String.valueOf(lastMaxCharacter) }); } LOGGER.debug("Generated query: {}", query); sp.setQuery(query); sp.setBulkFetchEnabled(false); // since we can't sort by cm:userName (default model lacks tokenise false/both, so CMIS rejects ORDER BY) we have to fetch // all results per iteration in one go sp.setLimitBy(LimitBy.UNLIMITED); sp.setMaxPermissionChecks(Integer.MAX_VALUE); sp.setMaxPermissionCheckTimeMillis(Long.MAX_VALUE); final ResultSet results = this.searchService.query(sp); try { final List<NodeRef> resultNodes = results.getNodeRefs(); nextWork.addAll(resultNodes); } finally { results.close(); } // depending on DB collation (case sensitive or insensitive) we may get duplicates when we query for lower/upper case // initial characters nextWork.removeAll(this.retrievedNodes); LOGGER.debug("Determined unique, unprocessed nodes {}", nextWork); this.retrievedNodes.addAll(nextWork); // if we did a query without an upper bound we are done now this.done = !this.useCharacterUpperBound && nextWork.isEmpty(); if (this.done) { LOGGER.debug("Done loading work items"); } } return null; }, this.runAsUser); return nextWork; } }
/* * Copyright 2008-2009 LinkedIn, 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 voldemort.common.service; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.management.MBeanOperationInfo; import org.apache.log4j.Logger; import voldemort.VoldemortException; import voldemort.annotations.jmx.JmxGetter; import voldemort.annotations.jmx.JmxManaged; import voldemort.annotations.jmx.JmxOperation; import voldemort.utils.Time; import com.google.common.collect.Lists; /** * The voldemort scheduler * * */ @SuppressWarnings("unchecked") @JmxManaged(description = "A service that runs scheduled jobs.") public class SchedulerService extends AbstractService { private static final Logger logger = Logger.getLogger(SchedulerService.class); private boolean mayInterrupt; private static final String THREAD_NAME_PREFIX = "voldemort-scheduler-service"; private static final AtomicInteger schedulerServiceCount = new AtomicInteger(0); private final String schedulerName = THREAD_NAME_PREFIX + schedulerServiceCount.incrementAndGet(); private class ScheduledRunnable { private Runnable runnable; private Date delayDate; private long intervalMs; ScheduledRunnable(Runnable runnable, Date delayDate, long intervalMs) { this.runnable = runnable; this.delayDate = delayDate; this.intervalMs = intervalMs; } ScheduledRunnable(Runnable runnable, Date delayDate) { this(runnable, delayDate, 0); } Runnable getRunnable() { return this.runnable; } Date getDelayDate() { return this.delayDate; } long getIntervalMs() { return this.intervalMs; } } private final ScheduledThreadPoolExecutor scheduler; private final Time time; private final Map<String, ScheduledFuture> scheduledJobResults; private final Map<String, ScheduledRunnable> allJobs; public SchedulerService(int schedulerThreads, Time time) { this(schedulerThreads, time, true); } public SchedulerService(int schedulerThreads, Time time, boolean mayInterrupt) { super(ServiceType.SCHEDULER); this.time = time; this.scheduler = new SchedulerThreadPool(schedulerThreads, schedulerName); this.scheduledJobResults = new ConcurrentHashMap<String, ScheduledFuture>(); this.allJobs = new ConcurrentHashMap<String, ScheduledRunnable>(); this.mayInterrupt = mayInterrupt; } @Override public void startInner() { // TODO note that most code does not do this. so scheduler.isStarted() // returns false even after you have submitted some tasks and they are // running fine. } @Override public void stopInner() { this.scheduler.shutdownNow(); try { this.scheduler.awaitTermination(5, TimeUnit.SECONDS); } catch(Exception e) { logger.info("Error waiting for termination of scheduler service", e); } } @JmxOperation(description = "Disable a particular scheduled job", impact = MBeanOperationInfo.ACTION) public void disable(String id) { if(allJobs.containsKey(id) && scheduledJobResults.containsKey(id)) { ScheduledFuture<?> future = scheduledJobResults.get(id); boolean cancelled = future.cancel(false); if(cancelled == true) { logger.info("Removed '" + id + "' from list of scheduled jobs"); scheduledJobResults.remove(id); } } } @JmxOperation(description = "Terminate a particular scheduled job", impact = MBeanOperationInfo.ACTION) public void terminate(String id) { if(allJobs.containsKey(id) && scheduledJobResults.containsKey(id)) { ScheduledFuture<?> future = scheduledJobResults.get(id); boolean cancelled = future.cancel(this.mayInterrupt); if(cancelled == true) { logger.info("Removed '" + id + "' from list of scheduled jobs"); scheduledJobResults.remove(id); } } } @JmxOperation(description = "Enable a particular scheduled job", impact = MBeanOperationInfo.ACTION) public void enable(String id) { if(allJobs.containsKey(id) && !scheduledJobResults.containsKey(id)) { ScheduledRunnable scheduledRunnable = allJobs.get(id); logger.info("Adding '" + id + "' to list of scheduled jobs"); if(scheduledRunnable.getIntervalMs() > 0) { schedule(id, scheduledRunnable.getRunnable(), scheduledRunnable.getDelayDate(), scheduledRunnable.getIntervalMs()); } else { schedule(id, scheduledRunnable.getRunnable(), scheduledRunnable.getDelayDate()); } } } @JmxGetter(name = "getScheduledJobs", description = "Returns names of jobs in the scheduler") public List<String> getScheduledJobs() { return Lists.newArrayList(scheduledJobResults.keySet()); } public List<String> getAllJobs() { return Lists.newArrayList(allJobs.keySet()); } public boolean getJobEnabled(String id) { if(allJobs.containsKey(id)) { return scheduledJobResults.containsKey(id); } else { throw new VoldemortException("Job id "+id + " does not exist."); } } public void scheduleNow(Runnable runnable) { scheduler.execute(runnable); } public void schedule(String id, Runnable runnable, Date timeToRun) { ScheduledFuture<?> future = scheduler.schedule(runnable, delayMs(timeToRun), TimeUnit.MILLISECONDS); if(!allJobs.containsKey(id)) { allJobs.put(id, new ScheduledRunnable(runnable, timeToRun)); } scheduledJobResults.put(id, future); } public void schedule(String id, Runnable runnable, Date nextRun, long periodMs) { schedule(id, runnable, nextRun, periodMs, false); } public void schedule(String id, Runnable runnable, Date nextRun, long periodMs, boolean scheduleAtFixedRate) { ScheduledFuture<?> future = null; if(scheduleAtFixedRate) future = scheduler.scheduleAtFixedRate(runnable, delayMs(nextRun), periodMs, TimeUnit.MILLISECONDS); else future = scheduler.scheduleWithFixedDelay(runnable, delayMs(nextRun), periodMs, TimeUnit.MILLISECONDS); if(!allJobs.containsKey(id)) { allJobs.put(id, new ScheduledRunnable(runnable, nextRun, periodMs)); } scheduledJobResults.put(id, future); } private long delayMs(Date runDate) { return Math.max(0, runDate.getTime() - time.getMilliseconds()); } /** * A scheduled thread pool that fixes some default behaviors */ private static class SchedulerThreadPool extends ScheduledThreadPoolExecutor { public SchedulerThreadPool(int numThreads, final String schedulerName) { super(numThreads, new ThreadFactory() { private AtomicInteger threadCount = new AtomicInteger(0); /** * This function is overridden in order to activate the daemon mode as well as * to give a human readable name to threads used by the {@link SchedulerService}. * * Previously, this function would set the thread's name to the value of the passed-in * {@link Runnable}'s class name, but this is useless since it always ends up being a * java.util.concurrent.ThreadPoolExecutor$Worker * * Instead, a generic name is now used, and the thread's name can be set more * precisely during {@link voldemort.server.protocol.admin.AsyncOperation#run()}. * * @param r {@link Runnable} to execute * @return a new {@link Thread} appropriate for use within the {@link SchedulerService}. */ public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); thread.setName(schedulerName + "-t" + threadCount.incrementAndGet()); return thread; } }); } } }
/* ========================================================= * UIApplicationSettings.java * * Author: kmchugh * Created: 26 November 2007, 15:33 * * Description * -------------------------------------------------------- * Controls the application behaviours for a regular UI application * * Change Log * -------------------------------------------------------- * Init.Date Ref. Description * -------------------------------------------------------- * * =======================================================*/ package Goliath.Applications; import Goliath.Collections.HashTable; import Goliath.Delegate; import Goliath.Event; import Goliath.Interfaces.Applications.IApplicationController; import Goliath.Interfaces.Applications.IUIApplicationSettings; import Goliath.Interfaces.ISession; import Goliath.Interfaces.UI.Controls.IApplicationWindow; import Goliath.LibraryVersion; import Goliath.Session; import Goliath.UI.Controls.ControlImplementationType; import Goliath.UI.Controls.Menu; import Goliath.UI.Controls.MenuItem; import Goliath.Utilities; import java.awt.AWTException; import java.awt.Image; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.Toolkit; import java.awt.TrayIcon; import java.util.TimerTask; /** * Controls the application behaviours for a regular web application * * @see Related Class * @version 1.0 26 November 2007 * @author kmchugh **/ public abstract class UIApplicationSettings<A extends IApplicationController> extends Goliath.Applications.ApplicationSettings<A> implements IUIApplicationSettings { private HashTable<String, IApplicationWindow> m_oApplicationWindows; private Menu m_oMenu; private String m_cTrayName; /** * This method is used to get the ApplicationWindow, the application * window is the controlling, or top level, window for the application * @param toSession the session. * @return the application window for the specified application */ @Override public final IApplicationWindow getApplicationWindow() { // TODO: See if this is still needed to contain a collection. Rules should be changed so there is only one window per app ISession loSession = Session.getCurrentSession(); String lcKey = loSession.getSessionID(); if (m_oApplicationWindows == null || !m_oApplicationWindows.containsKey(lcKey)) { if (m_oApplicationWindows == null) { m_oApplicationWindows = new HashTable<String, IApplicationWindow>(); } if (m_oApplicationWindows.size() == 1) { return m_oApplicationWindows.values().iterator().next(); } try { IApplicationWindow loWindow = createApplicationWindow(); m_oApplicationWindows.put(lcKey, loWindow); } catch (Throwable ex) { Application.getInstance().log(ex); } } return m_oApplicationWindows.get(lcKey); } /** * Gets the default implementation type for this type of application, this can be overridden in subclasses to change the type * @return the default implementation type */ @Override public abstract ControlImplementationType getDefaultImplementationType(); /** * Alerts the user by popping up in the Application window * @param tcMessage the message to alert the user with * @param tcTitle the title of the message */ @Override public final void alert(String tcMessage, String tcTitle) { // TODO: Implement proper and custom dialogs onAlert(tcMessage, tcTitle); } /** * Hook method to allow subclasses to interact with alert * @param tcMessage the message * @param tcTitle the title of the message */ protected void onAlert(String tcMessage, String tcTitle) { } /** * Displays the user interface to the user */ protected abstract void showUserInterface(); /** * True if this Application should show a user interface when it starts up, false otherwise * This should be overridden in sub classes to change the action * @return true to display a user interface, false otherwise */ protected boolean getShowUserInterface() { return true; } /** * Creates the window that becomes the controlling window for the session * @param toSession The session to create the window for * @return the application window for the specified session */ protected final IApplicationWindow createApplicationWindow() { try { return onCreateApplicationWindow(); } catch (Throwable ex) { Application.getInstance().log(ex); } return null; } private void onSessionExpired(Event<ISession> toEvent) { // Clean up the application windows if there is one for this session if (m_oApplicationWindows != null) { m_oApplicationWindows.remove(toEvent.getTarget().getSessionID()); } } /** * Creates the application window for the specified session * @param toSession the session to create the window for * @return the new application window */ protected abstract IApplicationWindow onCreateApplicationWindow(); private void onCloseClicked(Event toEvent) { Application.getInstance().shutdown(); } private void onReclaimMemoryClicked(Event toEvent) { System.gc(); } @Override public void doSetup() { super.doSetup(); } @Override public void applicationStateChanged(ApplicationState toNewState) { if (toNewState == ApplicationState.RUNNING()) { // Check if we will be using the system tray if (this.getUsesSystemTray()) { createSystemTray(); // Add the default menu items to the system tray m_oMenu.addControl(new MenuItem(m_oMenu.getImplementationType(), "Close Application", Delegate.build(this, "onCloseClicked"))); m_oMenu.addControl(new MenuItem(m_oMenu.getImplementationType(), "Reclaim Memory", Delegate.build(this, "onReclaimMemoryClicked"))); } if (getShowUserInterface()) { showUserInterface(); } } } public void addMenuItem(Goliath.UI.Controls.Control toControl) { if (m_oMenu != null) { m_oMenu.addControl(toControl); } } /** * Determines if this application uses the system tray * @return true if it does use the system tray, false otherwise */ @Override public final boolean getUsesSystemTray() { return onGetUsesSystemTray() && SystemTray.isSupported(); } /** * Returns true if this application uses the system tray, false if not, this should be overridden by subclasses to change functionality * @return true to use the system tray, false otherwise */ protected boolean onGetUsesSystemTray() { return true; } private void createSystemTray() { // TODO: System Tray should be dynamic not hard coded SystemTray tray = SystemTray.getSystemTray(); Toolkit loToolkit = Toolkit.getDefaultToolkit(); // TODO: Implement .ico reader Image loImage = loToolkit.getImage(Application.getInstance().getPropertyHandlerProperty("SystemTray.Icon", "./resources/icon.png")); // Create the popup menu // TODO: See if it is possible to create a system tray menu without using AWT m_oMenu = new Menu(ControlImplementationType.AWTSYSTEMTRAY()); final TrayIcon m_oIcon = new TrayIcon(loImage, Application.getInstance().getName(), (PopupMenu)m_oMenu.getControl()); m_oIcon.setToolTip(Application.getInstance().getPropertyHandlerProperty("SystemTray.Name", Application.getInstance().getName())); m_oIcon.setImageAutoSize(true); // TODO: This can be implemented better by using the mouse over event instead Application.getInstance().scheduleTask(new TimerTask() { @Override public void run() { // TODO: Optimise this method StringBuilder lcVersions = new StringBuilder(); for (LibraryVersion loVersion :Application.getInstance().getObjectCache().getObjects(LibraryVersion.class, "getName")) { lcVersions.append(loVersion.toString() + "\n"); } Application.getInstance().getObjectCache().clearCache(LibraryVersion.class); if (m_cTrayName == null) { m_cTrayName = Application.getInstance().getPropertyHandlerProperty("SystemTray.Name", Application.getInstance().getName()); } StringBuilder lcToolTip = new StringBuilder(m_cTrayName); long lnHeap = Utilities.getCurrentHeapSize(); long lnUsed = Utilities.getCurrentHeapSize() - Utilities.getFreeHeapSize(); lcToolTip.append("\n (" + (lnUsed / 1024) + " kb / " + (lnHeap / 1024) + " kb)"); lcToolTip.append("\n\n" + lcVersions.toString()); m_oIcon.setToolTip(lcToolTip.toString()); } }, 1000); try { tray.add(m_oIcon); } catch (AWTException e) { new Goliath.Exceptions.Exception(e); } } }
package org.vaadin.mideaas.frontend; import java.util.regex.Pattern; import org.vaadin.mideaas.model.ProjectFile; import org.vaadin.mideaas.model.SharedProject; import org.vaadin.mideaas.model.User; import com.vaadin.data.Item; import com.vaadin.data.Validator; import com.vaadin.data.fieldgroup.FieldGroup; import com.vaadin.data.fieldgroup.FieldGroup.CommitException; import com.vaadin.data.util.ObjectProperty; import com.vaadin.data.util.PropertysetItem; import com.vaadin.data.validator.AbstractStringValidator; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Component; import com.vaadin.ui.FormLayout; import com.vaadin.ui.TabSheet; import com.vaadin.ui.TextField; import com.vaadin.ui.Window; @SuppressWarnings("serial") public class AddNewWindow extends Window { private static final Pattern validClass = Pattern .compile("^[A-Z][A-Za-z1-9_]*$"); private static final Pattern validFile = Pattern .compile("^[A-Za-z1-9_.]+$"); private static final String VIEW_TYPE = "view"; private static final String CLASS_TYPE = "class"; private static final String FILE_TYPE = "file"; private final SharedProject project; private final User user; public AddNewWindow(SharedProject project, User user) { super("Create a new..."); this.project = project; this.user = user; setWidth("60%"); setHeight("60%"); center(); } @Override public void attach() { super.attach(); Component form1 = createComponentForm(); Component form2 = createClassForm(); Component form3 = createFileForm(); TabSheet tabs = new TabSheet(form1, form2, form3); tabs.setSizeFull(); setContent(tabs); } private Validator javaClassValidator = new AbstractStringValidator( "Not a proper Java class name. Start with a capital letter. Example: MyView") { @Override protected boolean isValidValue(String value) { return validClass.matcher(value).matches(); } }; private Validator javaFileValidator = new AbstractStringValidator( "Not a proper Java file name. Start with a capital letter. Example: Jee.java") { @Override protected boolean isValidValue(String value) { return !badJavaFileName(value); } }; private Validator filenameValidator = new AbstractStringValidator("Not a valid file name.") { @Override protected boolean isValidValue(String value) { return validFile.matcher(value).matches(); } }; private Validator viewExistsValidator = new AbstractStringValidator("Already exists.") { @Override protected boolean isValidValue(String value) { return !project.containsProjectItem(value); } }; private Validator fileExistsValidator = new AbstractStringValidator("Already exists.") { @Override protected boolean isValidValue(String value) { return !project.containsProjectItem(value); } }; private Validator reservedWordValidator = new AbstractStringValidator("Java reserved word.") { @Override protected boolean isValidValue(String value) { return !JavaUtil.isJavaReservedWord(value.toLowerCase()); } }; private Component createComponentForm() { AddForm form = new AddForm(VIEW_TYPE, "Add View", javaClassValidator, viewExistsValidator, reservedWordValidator); form.setCaption("View"); return form; } private Component createClassForm() { AddForm form = new AddForm(CLASS_TYPE, "Add Class", javaClassValidator, viewExistsValidator, reservedWordValidator); form.setCaption("Java Class"); return form; } private Component createFileForm() { AddForm form = new AddForm(FILE_TYPE, "Add File", filenameValidator, fileExistsValidator, javaFileValidator); form.setCaption("File"); return form; } private class AddForm extends FormLayout { private TextField name = new TextField("Name:"); private AddForm(String type, String addText, Validator... nameValidators) { PropertysetItem item = new PropertysetItem(); item.addItemProperty("type", new ObjectProperty<String>(type)); addItemProperties(item); name.setRequired(true); addComponent(name); final FieldGroup binder = new FieldGroup(item); binder.bindMemberFields(this); Button b = new Button(addText); b.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { try { binder.commit(); addToProject(binder.getItemDataSource()); } catch (CommitException e) { } } }); addComponent(b); for (Validator v : nameValidators) { name.addValidator(v); } } protected void addItemProperties(PropertysetItem item) { item.addItemProperty("name", new ObjectProperty<String>("")); } } private void addToProject(Item item) { String type = (String) item.getItemProperty("type").getValue(); String className = (String) item.getItemProperty("name").getValue(); if (VIEW_TYPE.equals(type)) { project.createView(className, user); } else if (CLASS_TYPE.equals(type)) { String cls = project.getPackageName()+"."+className; String filename = className+".java"; ProjectFile f = ProjectFile.newJavaFile(filename, JavaUtil.generateClass(cls, null), project.getSourceFileLocation(filename), project.getLog()); project.addFile(f, user); } else if (FILE_TYPE.equals(type)) { ProjectFile f = new ProjectFile(className, "", null, project.getSourceFileLocation(className), project.getLog()); project.addFile(f, user); } else { return; } close(); } private static boolean badJavaFileName(String name) { return name.endsWith(".java") && validClass.matcher(name.subSequence(0, name.length() - 5)) .matches(); } }
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.indexing.overlord; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.inject.Inject; import io.druid.concurrent.TaskThreadPriority; import io.druid.guice.annotations.Self; import io.druid.indexer.TaskLocation; import io.druid.indexing.common.TaskStatus; import io.druid.indexing.common.TaskToolbox; import io.druid.indexing.common.TaskToolboxFactory; import io.druid.indexing.common.config.TaskConfig; import io.druid.indexing.common.task.Task; import io.druid.indexing.overlord.autoscaling.ScalingStats; import io.druid.java.util.common.DateTimes; import io.druid.java.util.common.ISE; import io.druid.java.util.common.Numbers; import io.druid.java.util.common.Pair; import io.druid.java.util.common.concurrent.Execs; import io.druid.java.util.common.lifecycle.LifecycleStart; import io.druid.java.util.common.lifecycle.LifecycleStop; import io.druid.java.util.emitter.EmittingLogger; import io.druid.java.util.emitter.service.ServiceEmitter; import io.druid.java.util.emitter.service.ServiceMetricEvent; import io.druid.query.NoopQueryRunner; import io.druid.query.Query; import io.druid.query.QueryRunner; import io.druid.query.QuerySegmentWalker; import io.druid.query.SegmentDescriptor; import io.druid.server.DruidNode; import io.druid.server.SetAndVerifyContextQueryRunner; import io.druid.server.initialization.ServerConfig; import org.joda.time.Interval; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; /** * Runs a single task in a JVM thread using an ExecutorService. */ public class SingleTaskBackgroundRunner implements TaskRunner, QuerySegmentWalker { private static final EmittingLogger log = new EmittingLogger(SingleTaskBackgroundRunner.class); private final TaskToolboxFactory toolboxFactory; private final TaskConfig taskConfig; private final ServiceEmitter emitter; private final TaskLocation location; private final ServerConfig serverConfig; // Currently any listeners are registered in peons, but they might be used in the future. private final CopyOnWriteArrayList<Pair<TaskRunnerListener, Executor>> listeners = new CopyOnWriteArrayList<>(); private volatile ListeningExecutorService executorService; private volatile SingleTaskBackgroundRunnerWorkItem runningItem; private volatile boolean stopping; @Inject public SingleTaskBackgroundRunner( TaskToolboxFactory toolboxFactory, TaskConfig taskConfig, ServiceEmitter emitter, @Self DruidNode node, ServerConfig serverConfig ) { this.toolboxFactory = Preconditions.checkNotNull(toolboxFactory, "toolboxFactory"); this.taskConfig = taskConfig; this.emitter = Preconditions.checkNotNull(emitter, "emitter"); this.location = TaskLocation.create(node.getHost(), node.getPlaintextPort(), node.getTlsPort()); this.serverConfig = serverConfig; } @Override public List<Pair<Task, ListenableFuture<TaskStatus>>> restore() { return Collections.emptyList(); } @Override public void registerListener(TaskRunnerListener listener, Executor executor) { for (Pair<TaskRunnerListener, Executor> pair : listeners) { if (pair.lhs.getListenerId().equals(listener.getListenerId())) { throw new ISE("Listener [%s] already registered", listener.getListenerId()); } } final Pair<TaskRunnerListener, Executor> listenerPair = Pair.of(listener, executor); // Location never changes for an existing task, so it's ok to add the listener first and then issue bootstrap // callbacks without any special synchronization. listeners.add(listenerPair); log.info("Registered listener [%s]", listener.getListenerId()); if (runningItem != null) { TaskRunnerUtils.notifyLocationChanged( ImmutableList.of(listenerPair), runningItem.getTaskId(), runningItem.getLocation() ); } } @Override public void unregisterListener(String listenerId) { for (Pair<TaskRunnerListener, Executor> pair : listeners) { if (pair.lhs.getListenerId().equals(listenerId)) { listeners.remove(pair); log.info("Unregistered listener [%s]", listenerId); return; } } } private static ListeningExecutorService buildExecutorService(int priority) { return MoreExecutors.listeningDecorator( Execs.singleThreaded( "task-runner-%d-priority-" + priority, TaskThreadPriority.getThreadPriorityFromTaskPriority(priority) ) ); } @Override @LifecycleStart public void start() { // No state startup required } @Override @LifecycleStop public void stop() { stopping = true; if (executorService != null) { try { executorService.shutdown(); } catch (SecurityException ex) { log.wtf(ex, "I can't control my own threads!"); } } if (runningItem != null) { final Task task = runningItem.getTask(); final long start = System.currentTimeMillis(); final boolean graceful; final long elapsed; boolean error = false; if (taskConfig.isRestoreTasksOnRestart() && task.canRestore()) { // Attempt graceful shutdown. graceful = true; log.info("Starting graceful shutdown of task[%s].", task.getId()); try { task.stopGracefully(); final TaskStatus taskStatus = runningItem.getResult().get( new Interval(DateTimes.utc(start), taskConfig.getGracefulShutdownTimeout()).toDurationMillis(), TimeUnit.MILLISECONDS ); // Ignore status, it doesn't matter for graceful shutdowns. log.info( "Graceful shutdown of task[%s] finished in %,dms.", task.getId(), System.currentTimeMillis() - start ); TaskRunnerUtils.notifyStatusChanged(listeners, task.getId(), taskStatus); } catch (Exception e) { log.makeAlert(e, "Graceful task shutdown failed: %s", task.getDataSource()) .addData("taskId", task.getId()) .addData("dataSource", task.getDataSource()) .emit(); log.warn(e, "Graceful shutdown of task[%s] aborted with exception.", task.getId()); error = true; TaskRunnerUtils.notifyStatusChanged(listeners, task.getId(), TaskStatus.failure(task.getId())); } } else { graceful = false; TaskRunnerUtils.notifyStatusChanged(listeners, task.getId(), TaskStatus.failure(task.getId())); } elapsed = System.currentTimeMillis() - start; final ServiceMetricEvent.Builder metricBuilder = ServiceMetricEvent .builder() .setDimension("task", task.getId()) .setDimension("dataSource", task.getDataSource()) .setDimension("graceful", String.valueOf(graceful)) .setDimension("error", String.valueOf(error)); emitter.emit(metricBuilder.build("task/interrupt/count", 1L)); emitter.emit(metricBuilder.build("task/interrupt/elapsed", elapsed)); } // Ok, now interrupt everything. if (executorService != null) { try { executorService.shutdownNow(); } catch (SecurityException ex) { log.wtf(ex, "I can't control my own threads!"); } } } @Override public ListenableFuture<TaskStatus> run(final Task task) { if (runningItem == null) { final TaskToolbox toolbox = toolboxFactory.build(task); final Object taskPriorityObj = task.getContextValue(TaskThreadPriority.CONTEXT_KEY); int taskPriority = 0; try { taskPriority = taskPriorityObj == null ? 0 : Numbers.parseInt(taskPriorityObj); } catch (NumberFormatException e) { log.error(e, "Error parsing task priority [%s] for task [%s]", taskPriorityObj, task.getId()); } // Ensure an executor for that priority exists executorService = buildExecutorService(taskPriority); final ListenableFuture<TaskStatus> statusFuture = executorService.submit( new SingleTaskBackgroundRunnerCallable(task, location, toolbox) ); runningItem = new SingleTaskBackgroundRunnerWorkItem( task, location, statusFuture ); return statusFuture; } else { throw new ISE("Already running task[%s]", runningItem.getTask().getId()); } } /** * There might be a race between {@link #run(Task)} and this method, but it shouldn't happen in real applications * because this method is called only in unit tests. See TaskLifecycleTest. * * @param taskid task ID to clean up resources for */ @Override public void shutdown(final String taskid) { if (runningItem != null && runningItem.getTask().getId().equals(taskid)) { runningItem.getResult().cancel(true); } } @Override public Collection<TaskRunnerWorkItem> getRunningTasks() { return runningItem == null ? Collections.emptyList() : Collections.singletonList(runningItem); } @Override public Collection<TaskRunnerWorkItem> getPendingTasks() { return Collections.emptyList(); } @Override public Collection<TaskRunnerWorkItem> getKnownTasks() { return runningItem == null ? Collections.emptyList() : Collections.singletonList(runningItem); } @Override public Optional<ScalingStats> getScalingStats() { return Optional.absent(); } @Override public <T> QueryRunner<T> getQueryRunnerForIntervals(Query<T> query, Iterable<Interval> intervals) { return getQueryRunnerImpl(query); } @Override public <T> QueryRunner<T> getQueryRunnerForSegments(Query<T> query, Iterable<SegmentDescriptor> specs) { return getQueryRunnerImpl(query); } private <T> QueryRunner<T> getQueryRunnerImpl(Query<T> query) { QueryRunner<T> queryRunner = null; final String queryDataSource = Iterables.getOnlyElement(query.getDataSource().getNames()); if (runningItem != null) { final Task task = runningItem.getTask(); if (task.getDataSource().equals(queryDataSource)) { final QueryRunner<T> taskQueryRunner = task.getQueryRunner(query); if (taskQueryRunner != null) { if (queryRunner == null) { queryRunner = taskQueryRunner; } else { log.makeAlert("Found too many query runners for datasource") .addData("dataSource", queryDataSource) .emit(); } } } } return new SetAndVerifyContextQueryRunner<>( serverConfig, queryRunner == null ? new NoopQueryRunner<>() : queryRunner ); } private static class SingleTaskBackgroundRunnerWorkItem extends TaskRunnerWorkItem { private final Task task; private final TaskLocation location; private SingleTaskBackgroundRunnerWorkItem( Task task, TaskLocation location, ListenableFuture<TaskStatus> result ) { super(task.getId(), result); this.task = task; this.location = location; } public Task getTask() { return task; } @Override public TaskLocation getLocation() { return location; } @Override public String getTaskType() { return task.getType(); } @Override public String getDataSource() { return task.getDataSource(); } } private class SingleTaskBackgroundRunnerCallable implements Callable<TaskStatus> { private final Task task; private final TaskLocation location; private final TaskToolbox toolbox; SingleTaskBackgroundRunnerCallable(Task task, TaskLocation location, TaskToolbox toolbox) { this.task = task; this.location = location; this.toolbox = toolbox; } @Override public TaskStatus call() { final long startTime = System.currentTimeMillis(); TaskStatus status; try { log.info("Running task: %s", task.getId()); TaskRunnerUtils.notifyLocationChanged( listeners, task.getId(), location ); TaskRunnerUtils.notifyStatusChanged(listeners, task.getId(), TaskStatus.running(task.getId())); status = task.run(toolbox); } catch (InterruptedException e) { // Don't reset the interrupt flag of the thread, as we do want to continue to the end of this callable. if (stopping) { // Tasks may interrupt their own run threads to stop themselves gracefully; don't be too scary about this. log.debug(e, "Interrupted while running task[%s] during graceful shutdown.", task); } else { // Not stopping, this is definitely unexpected. log.warn(e, "Interrupted while running task[%s]", task); } status = TaskStatus.failure(task.getId(), e.toString()); } catch (Exception e) { log.error(e, "Exception while running task[%s]", task); status = TaskStatus.failure(task.getId(), e.toString()); } catch (Throwable t) { log.error(t, "Uncaught Throwable while running task[%s]", task); throw t; } status = status.withDuration(System.currentTimeMillis() - startTime); TaskRunnerUtils.notifyStatusChanged(listeners, task.getId(), status); return status; } } }
/* Copyright (c) 2014-2015 F-Secure See LICENSE for details */ package cc.softwarefactory.lokki.android.androidServices; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.os.Vibrator; import android.support.v4.app.NotificationCompat; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import org.json.JSONException; import cc.softwarefactory.lokki.android.MainApplication; import cc.softwarefactory.lokki.android.R; import cc.softwarefactory.lokki.android.activities.BuzzActivity; import cc.softwarefactory.lokki.android.activities.MainActivity; import cc.softwarefactory.lokki.android.models.BuzzPlace; import cc.softwarefactory.lokki.android.models.Place; import cc.softwarefactory.lokki.android.services.PlaceService; import cc.softwarefactory.lokki.android.utilities.PreferenceUtils; import cc.softwarefactory.lokki.android.utilities.ServerApi; import cc.softwarefactory.lokki.android.utilities.Utils; import cc.softwarefactory.lokki.android.utilities.map.MapUtils; public class LocationService extends Service implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { // INTERVALS /** * Location polling interval when the service is set to get high accuracy updates (App running in foreground) */ private static final long LOCATION_CHECK_INTERVAL_ACCURATE = 5000; //5 seconds /** * Location polling interval when the service is set to get medium accuracy updates (App running in background with Location Buzz) */ private static final long LOCATION_CHECK_INTERVAL_BACKGROUND_ACCURATE = 15000; //15 seconds /** * Location polling interval when the service is set to get low accuracy updates (App running in background without Location Buzz) */ private static final long LOCATION_CHECK_INTERVAL_BACKGROUND_INACCURATE = 1000 * 60 * 15; //15 minutes private static final long INTERVAL_30_SECS = 30 * 1000; private static final long INTERVAL_1_MIN = 60 * 1000; // - SERVICE private static final int NOTIFICATION_SERVICE = 100; // OTHER private static final String TAG = "LocationService"; private static final String RUN_1_MIN = "RUN_1_MIN"; private static final String ALARM_TIMER = "ALARM_TIMER"; private GoogleApiClient mGoogleApiClient; /** * Location request used to request accurate foreground updates from the Location API */ private LocationRequest locationRequestAccurate; /** * Location request used to request accurate background updates from the Location API */ private LocationRequest locationRequestBGAccurate; /** * Location request used to request inaccurate background updates from the Location API */ private LocationRequest locationRequestBGInaccurate; private static Boolean serviceRunning = false; private static Location lastLocation = null; private PowerManager.WakeLock wakeLock; /** * Current accuracy of location updates */ private LocationAccuracy currentAccuracy = LocationAccuracy.BGINACCURATE; private static PlaceService placeService; /** * Location polling accuracy levels: * ACCURATE: App running in foreground * BGACCURATE: App running in background, but still needs relatively high accuracy for e.g. Location Buzz * BGINACCURATE: App running in background, low accuracy */ public enum LocationAccuracy{ACCURATE, BGACCURATE, BGINACCURATE} public static void start(Context context) { Log.d(TAG, "start Service called"); placeService = new PlaceService(context); if (serviceRunning) { // If service is running, no need to start it again. Log.w(TAG, "Service already running..."); return; } context.startService(new Intent(context, LocationService.class)); } public static void stop(Context context) { Log.d(TAG, "stop Service called"); context.stopService(new Intent(context, LocationService.class)); } public static void run1min(Context context) { if (serviceRunning || !MainApplication.visible) { return; // If service is running or user is not visible, stop } Log.d(TAG, "run1min called"); Intent intent = new Intent(context, LocationService.class); intent.putExtra(RUN_1_MIN, 1); context.startService(intent); } @Override public void onCreate() { Log.d(TAG, "onCreate"); super.onCreate(); if (PreferenceUtils.getString(this, PreferenceUtils.KEY_AUTH_TOKEN).isEmpty()) { Log.d(TAG, "User disabled reporting in App. Service not started."); stopSelf(); } else if (Utils.checkGooglePlayServices(this)) { Log.d(TAG, "Starting Service.."); setLocationClient(); setNotificationAndForeground(); PowerManager mgr = (PowerManager)getApplicationContext().getSystemService(Context.POWER_SERVICE); wakeLock=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"Lokki Wake Lock"); wakeLock.acquire(); serviceRunning = true; } else { Log.e(TAG, "Google Play Services Are NOT installed."); stopSelf(); } } private void setTemporalTimer() { AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE); Intent alarmIntent = new Intent(this, LocationService.class); alarmIntent.putExtra(ALARM_TIMER, 1); PendingIntent alarmCallback = PendingIntent.getService(this, 0, alarmIntent, 0); alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + INTERVAL_1_MIN, alarmCallback); Log.d(TAG, "Time created."); } private void setLocationClient() { //Build location requests for different power profiles locationRequestAccurate = LocationRequest.create(); locationRequestAccurate.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequestAccurate.setInterval(LOCATION_CHECK_INTERVAL_ACCURATE); locationRequestBGAccurate = LocationRequest.create(); locationRequestBGAccurate.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); locationRequestBGAccurate.setInterval(LOCATION_CHECK_INTERVAL_BACKGROUND_ACCURATE); locationRequestBGInaccurate = LocationRequest.create(); locationRequestBGInaccurate.setPriority(LocationRequest.PRIORITY_LOW_POWER); locationRequestBGInaccurate.setInterval(LOCATION_CHECK_INTERVAL_BACKGROUND_INACCURATE); //Create and connect to Google API client mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mGoogleApiClient.connect(); Log.d(TAG, "Location Client created."); } private void setNotificationAndForeground() { NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); notificationBuilder.setContentTitle("Lokki"); notificationBuilder.setContentText("Running..."); notificationBuilder.setSmallIcon(R.drawable.ic_stat_notify); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); notificationBuilder.setContentIntent(contentIntent); startForeground(NOTIFICATION_SERVICE, notificationBuilder.build()); } /** * Switched current location update accuracy level to prioritize accuracy or power saving * @param acc The new accuracy level */ public void setLocationCheckAccuracy(LocationAccuracy acc){ currentAccuracy = acc; if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()){ Log.i(TAG, "Google API client not yet initialized, so not requesting updates yet"); return; } LocationRequest req; switch (acc){ case ACCURATE:{ Log.d(TAG, "Setting location request accuracy to accurate"); req = locationRequestAccurate; break; } case BGACCURATE:{ Log.d(TAG, "Setting location request accuracy to background accurate"); req = locationRequestBGAccurate; break; } case BGINACCURATE:{ Log.d(TAG, "Setting location request accuracy to background inaccurate"); req = locationRequestBGInaccurate; break; } default:{ Log.wtf(TAG, "Unknown location accuracy level"); throw new IllegalArgumentException("Unknown location accuracy level"); } } LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, req, this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand invoked"); if (intent == null) { return START_STICKY; } Bundle extras = intent.getExtras(); if (extras == null) { return START_STICKY; } if (extras.containsKey(RUN_1_MIN)) { Log.d(TAG, "onStartCommand RUN_1_MIN"); setTemporalTimer(); } else if (extras.containsKey(ALARM_TIMER)) { Log.d(TAG, "onStartCommand ALARM_TIMER"); stopSelf(); } return START_STICKY; } @Override public void onConnected(Bundle bundle) { Log.d(TAG, "locationClient connected"); //Set location update accuracy to whichever value was set last setLocationCheckAccuracy(currentAccuracy); Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { updateLokkiLocation(mLastLocation); } else { Log.e(TAG, "Location is null?! Check location service?!"); // todo add prompt for checking that location services are enabled maybe? } } @Override public void onConnectionSuspended(int i) { } @Override public void onLocationChanged(Location location) { Log.d(TAG, String.format("onLocationChanged - Location: %s", location)); if (serviceRunning && mGoogleApiClient.isConnected() && location != null) { updateLokkiLocation(location); checkBuzzPlaces(); } else { this.stopSelf(); onDestroy(); } } private void updateLokkiLocation(Location location) { if (!MapUtils.useNewLocation(location, lastLocation, INTERVAL_30_SECS)) { Log.d(TAG, "New location discarded."); return; } Log.d(TAG, "New location taken into use."); lastLocation = location; MainApplication.user.setLocationFromAndroidLocation(location); Intent intent = new Intent("LOCATION-UPDATE"); intent.putExtra("current-location", 1); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); if (MainApplication.visible) { try { ServerApi.sendLocation(this, location); } catch (JSONException e) { e.printStackTrace(); } } } private void showArrivalNotification() { Intent showIntent = new Intent(this, BuzzActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, showIntent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_notify) .setContentTitle("Lokki") .setContentText(getString(R.string.you_have_arrived)) .setAutoCancel(true) .setContentIntent(contentIntent); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(42, mBuilder.build()); } class VibrationThread implements Runnable { private String id; VibrationThread(String id) { this.id = id; } @Override public void run() { BuzzPlace buzzPlace = BuzzActivity.getBuzz(id); try { while (buzzPlace != null && buzzPlace.getBuzzCount() > 0) { Log.d(TAG, "Vibrating..."); Vibrator v = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE); v.vibrate(1000); Thread.sleep(2500); buzzPlace.decBuzzCount(); } } catch (InterruptedException e) { e.printStackTrace(); } } } private void triggerBuzzing(final BuzzPlace buzzPlace) throws JSONException { if (buzzPlace.getBuzzCount() <= 0 || buzzPlace.isActivated()) return; buzzPlace.setActivated(false); Intent i = new Intent(); i.setClass(this, BuzzActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); showArrivalNotification(); Log.d(TAG, "Starting vibration..."); new Thread(new VibrationThread(buzzPlace.getPlaceId())).start(); } private void checkBuzzPlaces() { for (BuzzPlace buzzPlace : MainApplication.buzzPlaces) { try { String placeId = buzzPlace.getPlaceId(); Place place = placeService.getPlaceById(placeId); //create android location from Place location information Location placeLocation = new Location(placeId); placeLocation.setLatitude(place.getLocation().getLat()); placeLocation.setLongitude((place.getLocation().getLon())); if (placeLocation.distanceTo(lastLocation) < place.getLocation().getAcc()) triggerBuzzing(buzzPlace); else { buzzPlace.setBuzzCount(5); buzzPlace.setActivated(false); } } catch (JSONException e) { Log.e(TAG,"Error in checking buzz places" + e); } } } @Override public void onConnectionFailed(ConnectionResult connectionResult) { Log.e(TAG, "locationClient onConnectionFailed"); } @Override public void onDestroy() { Log.d(TAG, "onDestroy called"); if(wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); } stopForeground(true); if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); mGoogleApiClient.disconnect(); Log.d(TAG, "Location Updates removed."); } else { Log.e(TAG, "locationClient didn't exist."); } serviceRunning = false; super.onDestroy(); } //------------Service binding------------ /** * The service binder for this service instance */ private final LocationBinder mBinder = new LocationBinder(); /** * Binder object that allows this service to be accessed from other objects in the same process */ public class LocationBinder extends Binder { /** * Gets a reference to the currently running LocationService instance * @return Reference to the current LocationService */ public LocationService getService(){ return LocationService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } }
/* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ package com.gemstone.gemfire.cache.hdfs.internal.hoplog.mapreduce; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit; import com.gemstone.gemfire.cache.hdfs.internal.hoplog.BaseHoplogTestCase; import com.gemstone.gemfire.cache.hdfs.internal.hoplog.HdfsSortedOplogOrganizer; import com.gemstone.gemfire.cache.hdfs.internal.hoplog.Hoplog; import com.gemstone.gemfire.internal.AvailablePort; import com.gemstone.gemfire.internal.AvailablePortHelper; import com.gemstone.gemfire.internal.cache.persistence.soplog.TrackedReference; public class GFInputFormatJUnitTest extends BaseHoplogTestCase { MiniDFSCluster cluster; private int CLUSTER_PORT = AvailablePortHelper.getRandomAvailableTCPPort(); private File configFile; Path regionPath = null; /* * Tests if a file split is created for each hdfs block occupied by hoplogs of * a region */ public void testNBigFiles1Dn() throws Exception { cluster = initMiniCluster(CLUSTER_PORT, 1); int count = 30; HdfsSortedOplogOrganizer bucket1 = new HdfsSortedOplogOrganizer( regionManager, 1); int hopCount = 3; for (int j = 0; j < hopCount; j++) { ArrayList<TestEvent> items = new ArrayList<TestEvent>(); for (int i = 0; i < count; i++) { items.add(new TestEvent(("key-" + i), ("value-" + System.nanoTime()))); } bucket1.flush(items.iterator(), count); } Path bucketPath = new Path(regionPath, "1"); int expectedBlocks = 0; long remainder = 0; long blockSize = 2048; List<TrackedReference<Hoplog>> hoplogs = bucket1.getSortedOplogs(); for (TrackedReference<Hoplog> hop : hoplogs) { Path hopPath = new Path(bucketPath, hop.get().getFileName()); FileStatus status = hdfsStore.getFileSystem().getFileStatus(hopPath); blockSize = status.getBlockSize(); long len = status.getLen(); assertNotSame(blockSize, len); while (len > status.getBlockSize()) { expectedBlocks ++; len -= blockSize; }; remainder += len; } expectedBlocks += remainder / blockSize; assertTrue(expectedBlocks > 1); Configuration conf = hdfsStore.getFileSystem().getConf(); GFInputFormat gfInputFormat = new GFInputFormat(); Job job = Job.getInstance(conf, "test"); conf = job.getConfiguration(); conf.set(GFInputFormat.INPUT_REGION, getName()); conf.set(GFInputFormat.HOME_DIR, testDataDir.getName()); conf.setBoolean(GFInputFormat.CHECKPOINT, false); List<InputSplit> splits = gfInputFormat.getSplits(job); assertTrue(Math.abs(expectedBlocks - splits.size()) <= 1); assertTrue(hopCount < splits.size()); for (InputSplit split : splits) { assertEquals(1, split.getLocations().length); } } public void testNSmallFiles1Dn() throws Exception { cluster = initMiniCluster(CLUSTER_PORT, 1); int count = 1; HdfsSortedOplogOrganizer bucket1 = new HdfsSortedOplogOrganizer( regionManager, 1); int hopCount = 3; for (int j = 0; j < hopCount; j++) { ArrayList<TestEvent> items = new ArrayList<TestEvent>(); for (int i = 0; i < count; i++) { items.add(new TestEvent(("key-" + i), ("value-" + System.nanoTime()))); } bucket1.flush(items.iterator(), count); } Path bucketPath = new Path(regionPath, "1"); int expectedBlocks = 0; long remainder = 0; long blockSize = 2048; List<TrackedReference<Hoplog>> hoplogs = bucket1.getSortedOplogs(); for (TrackedReference<Hoplog> hop : hoplogs) { Path hopPath = new Path(bucketPath, hop.get().getFileName()); FileStatus status = hdfsStore.getFileSystem().getFileStatus(hopPath); blockSize = status.getBlockSize(); long len = status.getLen(); while (len > status.getBlockSize()) { expectedBlocks ++; len -= blockSize; }; remainder += len; } expectedBlocks += remainder / blockSize; Configuration conf = hdfsStore.getFileSystem().getConf(); GFInputFormat gfInputFormat = new GFInputFormat(); Job job = Job.getInstance(conf, "test"); conf = job.getConfiguration(); conf.set(GFInputFormat.INPUT_REGION, getName()); conf.set(GFInputFormat.HOME_DIR, testDataDir.getName()); conf.setBoolean(GFInputFormat.CHECKPOINT, false); List<InputSplit> splits = gfInputFormat.getSplits(job); assertEquals(expectedBlocks, splits.size()); assertTrue(hopCount > splits.size()); for (InputSplit split : splits) { assertEquals(1, split.getLocations().length); } } /* * Test splits cover all the data in the hoplog */ public void testHfileSplitCompleteness() throws Exception { cluster = initMiniCluster(CLUSTER_PORT, 1); int count = 40; HdfsSortedOplogOrganizer bucket1 = new HdfsSortedOplogOrganizer( regionManager, 1); ArrayList<TestEvent> items = new ArrayList<TestEvent>(); for (int i = 0; i < count; i++) { items.add(new TestEvent(("key-" + i), ("value-" + System.nanoTime()))); } bucket1.flush(items.iterator(), count); Configuration conf = hdfsStore.getFileSystem().getConf(); GFInputFormat gfInputFormat = new GFInputFormat(); Job job = Job.getInstance(conf, "test"); conf = job.getConfiguration(); conf.set(GFInputFormat.INPUT_REGION, getName()); conf.set(GFInputFormat.HOME_DIR, testDataDir.getName()); conf.setBoolean(GFInputFormat.CHECKPOINT, false); List<InputSplit> splits = gfInputFormat.getSplits(job); assertTrue(1 < splits.size()); long lastBytePositionOfPrevious = 0; for (InputSplit inputSplit : splits) { CombineFileSplit split = (CombineFileSplit) inputSplit; assertEquals(1, split.getPaths().length); assertEquals(lastBytePositionOfPrevious, split.getOffset(0)); lastBytePositionOfPrevious += split.getLength(); assertEquals(1, split.getLocations().length); } Path bucketPath = new Path(regionPath, "1"); Path hopPath = new Path(bucketPath, bucket1.getSortedOplogs().iterator() .next().get().getFileName()); FileStatus status = hdfsStore.getFileSystem().getFileStatus(hopPath); assertEquals(status.getLen(), lastBytePositionOfPrevious); } @Override protected void configureHdfsStoreFactory() throws Exception { super.configureHdfsStoreFactory(); configFile = new File("testGFInputFormat-config"); String hadoopClientConf = "<configuration>\n " + " <property>\n " + " <name>dfs.block.size</name>\n " + " <value>2048</value>\n " + " </property>\n " + " <property>\n " + " <name>fs.default.name</name>\n " + " <value>hdfs://127.0.0.1:" + CLUSTER_PORT + "</value>\n" + " </property>\n " + " <property>\n " + " <name>dfs.replication</name>\n " + " <value>1</value>\n " + " </property>\n " + "</configuration>"; BufferedWriter bw = new BufferedWriter(new FileWriter(configFile)); bw.write(hadoopClientConf); bw.close(); hsf.setHDFSClientConfigFile(configFile.getName()); } @Override protected void setUp() throws Exception { CLUSTER_PORT = AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS); super.setUp(); regionPath = new Path(testDataDir, getName()); } @Override protected void tearDown() throws Exception { if (configFile != null) { configFile.delete(); } super.tearDown(); if (cluster != null) { cluster.shutdown(); } deleteMiniClusterDir(); } }
package com.mixpanel.android.mpmetrics; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.test.AndroidTestCase; import android.util.Pair; import com.mixpanel.android.util.Base64Coder; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; public class HttpTest extends AndroidTestCase { public void setUp() { mDisableFallback = false; mMockPreferences = new TestUtils.EmptyPreferences(getContext()); mFlushResults = new ArrayList<Object>(); mPerformRequestCalls = new LinkedBlockingQueue<String>(); mDecideCalls = new LinkedBlockingQueue<String>(); mCleanupCalls = new ArrayList<String>(); mDecideResults = new ArrayList<Object>(); final ServerMessage mockPoster = new ServerMessage() { @Override public byte[] performRequest(String endpointUrl, List<NameValuePair> nameValuePairs) throws IOException { try { if (null == nameValuePairs) { mDecideCalls.put(endpointUrl); if (mDecideResults.isEmpty()) { return TestUtils.bytes("{}"); } final Object obj = mDecideResults.remove(0); if (obj instanceof IOException) { throw (IOException)obj; } else if (obj instanceof MalformedURLException) { throw (MalformedURLException)obj; } return (byte[])obj; } // ELSE assertEquals(nameValuePairs.get(0).getName(), "data"); final String jsonData = Base64Coder.decodeString(nameValuePairs.get(0).getValue()); JSONArray msg = new JSONArray(jsonData); JSONObject event = msg.getJSONObject(0); mPerformRequestCalls.put(event.getString("event")); if (mFlushResults.isEmpty()) { return TestUtils.bytes("1"); } final Object obj = mFlushResults.remove(0); if (obj instanceof IOException) { throw (IOException)obj; } else if (obj instanceof MalformedURLException) { throw (MalformedURLException)obj; } return (byte[])obj; } catch (JSONException e) { throw new RuntimeException("Malformed data passed to test mock", e); } catch (InterruptedException e) { throw new RuntimeException("Could not write message to reporting queue for tests.", e); } } }; final MPConfig config = new MPConfig(new Bundle()) { @Override public String getDecideEndpoint() { return "DECIDE ENDPOINT"; } @Override public String getDecideFallbackEndpoint() { return "DECIDE FALLBACK"; } @Override public String getEventsEndpoint() { return "EVENTS ENDPOINT"; } @Override public String getEventsFallbackEndpoint() { return "EVENTS FALLBACK"; } @Override public boolean getDisableFallback() { return mDisableFallback; } }; final MPDbAdapter mockAdapter = new MPDbAdapter(getContext()) { @Override public void cleanupEvents(String last_id, Table table) { mCleanupCalls.add("called"); super.cleanupEvents(last_id, table); } }; final AnalyticsMessages listener = new AnalyticsMessages(getContext()) { @Override protected MPDbAdapter makeDbAdapter(Context context) { return mockAdapter; } @Override protected ServerMessage getPoster() { return mockPoster; } @Override protected MPConfig getConfig(Context context) { return config; } }; mMetrics = new TestUtils.CleanMixpanelAPI(getContext(), mMockPreferences, "Test Message Queuing") { @Override protected AnalyticsMessages getAnalyticsMessages() { return listener; } }; } public void testHTTPFailures() { try { // Basic succeed on first, non-fallback url mCleanupCalls.clear(); mFlushResults.add(TestUtils.bytes("1\n")); mMetrics.track("Should Succeed", null); mMetrics.flush(); Thread.sleep(500); assertEquals("Should Succeed", mPerformRequestCalls.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS)); assertEquals(null, mPerformRequestCalls.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS)); assertEquals(1, mCleanupCalls.size()); // Fallback test--first URL throws IOException mCleanupCalls.clear(); mFlushResults.add(new IOException()); mFlushResults.add(TestUtils.bytes("1\n")); mMetrics.track("Should Succeed", null); mMetrics.flush(); Thread.sleep(500); assertEquals("Should Succeed", mPerformRequestCalls.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS)); assertEquals("Should Succeed", mPerformRequestCalls.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS)); assertEquals(1, mCleanupCalls.size()); // Two IOExceptions -- assume temporary network failure, no cleanup should happen until // second flush mCleanupCalls.clear(); mFlushResults.add(new IOException()); mFlushResults.add(new IOException()); mFlushResults.add(TestUtils.bytes("1\n")); mMetrics.track("Should Succeed", null); mMetrics.flush(); Thread.sleep(500); assertEquals("Should Succeed", mPerformRequestCalls.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS)); assertEquals("Should Succeed", mPerformRequestCalls.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS)); assertEquals(0, mCleanupCalls.size()); mMetrics.flush(); Thread.sleep(500); assertEquals("Should Succeed", mPerformRequestCalls.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS)); assertEquals(null, mPerformRequestCalls.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS)); assertEquals(1, mCleanupCalls.size()); // MalformedURLException -- should dump the events since this will probably never succeed mCleanupCalls.clear(); mFlushResults.add(new MalformedURLException()); mMetrics.track("Should Fail", null); mMetrics.flush(); Thread.sleep(500); assertEquals("Should Fail", mPerformRequestCalls.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS)); assertEquals(null, mPerformRequestCalls.poll(POLL_WAIT_SECONDS, TimeUnit.SECONDS)); assertEquals(1, mCleanupCalls.size()); } catch (InterruptedException e) { throw new RuntimeException("Test was interrupted."); } } private Future<SharedPreferences> mMockPreferences; private List<Object> mFlushResults, mDecideResults; private BlockingQueue<String> mPerformRequestCalls, mDecideCalls; private List<String> mCleanupCalls; private MixpanelAPI mMetrics; private volatile boolean mDisableFallback; private static final int POLL_WAIT_SECONDS = 5; }
/** * 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.azurereport.implementation; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureClient; import com.microsoft.azure.AzureServiceClient; import com.microsoft.azure.AzureServiceResponseBuilder; import com.microsoft.azure.RestClient; import com.microsoft.rest.credentials.ServiceClientCredentials; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.ServiceResponseCallback; import fixtures.azurereport.AutoRestReportServiceForAzure; import fixtures.azurereport.models.ErrorException; import java.io.IOException; import java.util.Map; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.Response; /** * Initializes a new instance of the AutoRestReportServiceForAzureImpl class. */ public final class AutoRestReportServiceForAzureImpl extends AzureServiceClient implements AutoRestReportServiceForAzure { /** The Retrofit service to perform REST calls. */ private AutoRestReportServiceForAzureService service; /** the {@link AzureClient} used for long running operations. */ private AzureClient azureClient; /** * Gets the {@link AzureClient} used for long running operations. * @return the azure client; */ public AzureClient getAzureClient() { return this.azureClient; } /** Gets or sets the preferred language for the response. */ private String acceptLanguage; /** * Gets Gets or sets the preferred language for the response. * * @return the acceptLanguage value. */ public String acceptLanguage() { return this.acceptLanguage; } /** * Sets Gets or sets the preferred language for the response. * * @param acceptLanguage the acceptLanguage value. * @return the service client itself */ public AutoRestReportServiceForAzureImpl withAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; return this; } /** Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. */ private int longRunningOperationRetryTimeout; /** * Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @return the longRunningOperationRetryTimeout value. */ public int longRunningOperationRetryTimeout() { return this.longRunningOperationRetryTimeout; } /** * Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. * @return the service client itself */ public AutoRestReportServiceForAzureImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; return this; } /** When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ private boolean generateClientRequestId; /** * Gets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @return the generateClientRequestId value. */ public boolean generateClientRequestId() { return this.generateClientRequestId; } /** * Sets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @param generateClientRequestId the generateClientRequestId value. * @return the service client itself */ public AutoRestReportServiceForAzureImpl withGenerateClientRequestId(boolean generateClientRequestId) { this.generateClientRequestId = generateClientRequestId; return this; } /** * Initializes an instance of AutoRestReportServiceForAzure client. * * @param credentials the management credentials for Azure */ public AutoRestReportServiceForAzureImpl(ServiceClientCredentials credentials) { this("http://localhost", credentials); } /** * Initializes an instance of AutoRestReportServiceForAzure client. * * @param baseUrl the base URL of the host * @param credentials the management credentials for Azure */ public AutoRestReportServiceForAzureImpl(String baseUrl, ServiceClientCredentials credentials) { this(new RestClient.Builder() .withBaseUrl(baseUrl) .withCredentials(credentials) .build()); } /** * Initializes an instance of AutoRestReportServiceForAzure client. * * @param restClient the REST client to connect to Azure. */ public AutoRestReportServiceForAzureImpl(RestClient restClient) { super(restClient); initialize(); } protected void initialize() { this.acceptLanguage = "en-US"; this.longRunningOperationRetryTimeout = 30; this.generateClientRequestId = true; this.azureClient = new AzureClient(this); initializeService(); } /** * Gets the User-Agent header for the client. * * @return the user agent string. */ @Override public String userAgent() { return String.format("Azure-SDK-For-Java/%s (%s)", getClass().getPackage().getImplementationVersion(), "AutoRestReportServiceForAzure, 1.0.0"); } private void initializeService() { service = restClient().retrofit().create(AutoRestReportServiceForAzureService.class); } /** * The interface defining all the services for AutoRestReportServiceForAzure to be * used by Retrofit to perform actually REST calls. */ interface AutoRestReportServiceForAzureService { @Headers("Content-Type: application/json; charset=utf-8") @GET("report/azure") Call<ResponseBody> getReport(@Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Get test coverage report. * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @return the Map&lt;String, Integer&gt; object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse<Map<String, Integer>> getReport() throws ErrorException, IOException { Call<ResponseBody> call = service.getReport(this.acceptLanguage(), this.userAgent()); return getReportDelegate(call.execute()); } /** * Get test coverage report. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @return the {@link Call} object */ public ServiceCall<Map<String, Integer>> getReportAsync(final ServiceCallback<Map<String, Integer>> serviceCallback) { Call<ResponseBody> call = service.getReport(this.acceptLanguage(), this.userAgent()); final ServiceCall<Map<String, Integer>> serviceCall = new ServiceCall<>(call); call.enqueue(new ServiceResponseCallback<Map<String, Integer>>(serviceCall, serviceCallback) { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { ServiceResponse<Map<String, Integer>> clientResponse = getReportDelegate(response); if (serviceCallback != null) { serviceCallback.success(clientResponse); } serviceCall.success(clientResponse); } catch (ErrorException | IOException exception) { if (serviceCallback != null) { serviceCallback.failure(exception); } serviceCall.failure(exception); } } }); return serviceCall; } private ServiceResponse<Map<String, Integer>> getReportDelegate(Response<ResponseBody> response) throws ErrorException, IOException { return new AzureServiceResponseBuilder<Map<String, Integer>, ErrorException>(this.mapperAdapter()) .register(200, new TypeToken<Map<String, Integer>>() { }.getType()) .registerError(ErrorException.class) .build(response); } }
package net.tinyos.mcenter.treeTable; import java.io.IOException; import java.util.*; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.XMLOutputter; import java.util.prefs.*; public class PreferenceModel extends AbstractTreeTableModel { // Names of the columns. static protected String[] cNames = {"Name", "Value", "Selected"}; // Types of the columns. static protected Class[] cTypes = { TreeTableModel.class, String.class, Boolean.class}; Preferences prefs = null; PreferenceModel.PreferenceTreeItem itemTreeRoot; private JTreeTable jTreeTable = null; public PreferenceModel() { super(null); //prefs = Preferences.userNodeForPackage(this.getClass()); prefs = Preferences.userRoot(); itemTreeRoot = new PreferenceModel.PreferenceRoot(prefs,null); createTree(prefs, itemTreeRoot); root = itemTreeRoot; } public PreferenceModel(Class path) { super(null); prefs = Preferences.userNodeForPackage(path); itemTreeRoot = new PreferenceModel.PreferenceTreeItem(prefs,null); createTree(prefs, itemTreeRoot); root = itemTreeRoot; } public void setTreeTable(JTreeTable jTreeTable){ this.jTreeTable = jTreeTable; } public void exportSelection(java.io.OutputStream outStream){ Document document = new Document(); Element treeElement = itemTreeRoot.getXMLElement(true); if(treeElement != null) document.setRootElement(treeElement); XMLOutputter outputter = new XMLOutputter(); outputter.setIndent(" "); // use two space indent outputter.setNewlines(true); try { outputter.output(document,outStream); } catch (IOException e) { System.err.println(e); } } /** * Creates a FileSystemModel2 with the root being <code>rootPath</code>. * This does not load it, you should invoke * <code>reloadChildren</code> with the root to start loading. */ // // The TreeModel interface // /** * Returns the number of children of <code>node</code>. */ public int getChildCount(Object node) { //return ((PreferencesTreeAdapter)node).getChildCount(); return ((PreferenceTreeItem)node).getChildCount(); } /** * Returns the child of <code>node</code> at index <code>i</code>. */ public Object getChild(Object node, int i) { //return ((PreferencesTreeAdapter)node).getChild(i); return ((PreferenceTreeItem)node).getChild(i); } /** * Returns true if the passed in object represents a leaf, false * otherwise. */ public boolean isLeaf(Object node) { //return ((PreferencesTreeAdapter)node).isLeaf(); return ((PreferenceTreeItem)node).isLeaf(); } public boolean isCellEditable(Object node, int column) { if(column==0) return getColumnClass(column) == TreeTableModel.class; else if(column==2) return true; return false; } // // The TreeTableNode interface. // /** * Returns the number of columns. */ public int getColumnCount() { return cNames.length; } /** * Returns the name for a particular column. */ public String getColumnName(int column) { return cNames[column]; } /** * Returns the class for the particular column. */ public Class getColumnClass(int column) { return cTypes[column]; } /** * Returns the value of the particular column. */ public Object getValueAt(Object node, int column) { PreferenceTreeItem parent = (PreferenceTreeItem)node; try { switch(column) { case 0: return ""; case 1: return parent.toString(column); case 2: return new Boolean(parent.getSelected()); } } catch (SecurityException se) { } /*catch(java.util.prefs.BackingStoreException bse){ System.out.println("StoreException4"); }*/ return null; } public void setValueAt(Object aValue, Object node, int column) { if(column ==2){ ((PreferenceTreeItem)node).setSelected(((Boolean)aValue).booleanValue(),true); this.jTreeTable.tableChanged(new javax.swing.event.TableModelEvent(jTreeTable.getModel(),0,jTreeTable.getRowCount(),2)); } } private void createTree(Preferences parentPrefs, PreferenceTreeItem treeParent){ PreferenceTreeItem parent; ArrayList childList = new ArrayList(); if(treeParent == null){ parent = new PreferenceTreeItem(parentPrefs,null); }else{ parent = treeParent; } try{ String[] childNames = parentPrefs.childrenNames(); for(int i=0; i< childNames.length; i++){ Preferences childPrefs = parentPrefs.node(childNames[i]); PreferenceTreeItem childTree = new PreferenceTreeItem(childPrefs, parent); childList.add(childTree); createTree(childPrefs, childTree ); } String[] keyNames = parentPrefs.keys(); for(int i=0; i< keyNames.length; i++){ PreferenceAttribute prefAttr = new PreferenceAttribute(parentPrefs,parent,keyNames[i],parentPrefs.get(keyNames[i], "")); childList.add(prefAttr); } parent.addChilds(childList); }catch(java.util.prefs.BackingStoreException bse){ } } public class PreferenceTreeItem{ protected Preferences parentPrefs; protected boolean selected = false; protected ArrayList childs = new ArrayList(); protected PreferenceTreeItem parentItem; public PreferenceTreeItem(Preferences parentPrefs, PreferenceTreeItem parent){ this.parentPrefs = parentPrefs; parentItem = parent; } public boolean addChilds(ArrayList newChilds){ return childs.addAll(newChilds); } public boolean getSelected(){ return selected; } public void setSelected(boolean selected, boolean deep){ if(deep){ Iterator childIt = childs.iterator(); while (childIt.hasNext()){ ((PreferenceTreeItem)childIt.next()).setSelected(selected, deep); } } this.selected = selected; if(selected) setParentSelection(); } protected void setParentSelection(){ selected = true; if(selected && (parentItem != null)) parentItem.setParentSelection(); } public String toString(){ //return parentPrefs.absolutePath(); return parentPrefs.name(); } public String toString(int column){ switch (column){ case 0: return parentPrefs.absolutePath(); case 1: return ""; case 2: return new String(""+selected); } return ""; } public int getChildCount(){ return childs.size(); } public Object getChild(int i) { return childs.get(i); } public boolean isLeaf() { return (childs.size()==0); } public Element getXMLElement(boolean deep){ if(!selected) return null; Element elem = new Element("node"); elem.setAttribute("name",parentPrefs.name()); if(deep){ Iterator childIt = childs.iterator(); while (childIt.hasNext()){ Element childElem = ((PreferenceTreeItem)childIt.next()).getXMLElement(deep); if(childElem != null) elem.addContent( childElem ); } } return elem; } } public class PreferenceRoot extends PreferenceTreeItem{ public PreferenceRoot(Preferences parentPrefs, PreferenceTreeItem parent){ super(parentPrefs,parent); } public String toString(){ return "User Preferences"; } public Element getXMLElement(boolean deep){ if(!selected) return null; Element elem = new Element("preferences"); if(deep){ Iterator childIt = childs.iterator(); while (childIt.hasNext()){ Element childElem = ((PreferenceTreeItem)childIt.next()).getXMLElement(deep); if(childElem != null) elem.addContent( childElem ); } } return elem; } } public class PreferenceAttribute extends PreferenceTreeItem{ private String key; private String value; public PreferenceAttribute(Preferences parentPrefs, PreferenceTreeItem parent, String key, String value){ super(parentPrefs,parent); this.key =key; this. value = value; } public String toString(){ return key; } public String toString(int column){ switch (column){ case 0: return ""; case 1: return value; case 2: return new String(""+this.selected); } return ""; } public Element getXMLElement(boolean deep){ if(!selected) return null; Element elem = new Element("entry"); elem.setAttribute("key",key); elem.setAttribute("value",value); return elem; } } }
package org.diorite.material.blocks.wooden.wood.door; import java.util.Map; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.diorite.BlockFace; import org.diorite.material.Material; import org.diorite.material.WoodTypeMat; import org.diorite.material.blocks.DoorMat; import org.diorite.utils.collections.maps.CaseInsensitiveMap; import gnu.trove.map.TByteObjectMap; import gnu.trove.map.hash.TByteObjectHashMap; /** * Class representing block "DarkOakDoor" and all its subtypes. * <p> * NOTE: Will crash game when in inventory. */ public class DarkOakDoorMat extends WoodenDoorMat { /** * Sub-ids used by diorite/minecraft by default */ public static final int USED_DATA_VALUES = 12; public static final DarkOakDoorMat DARK_OAK_DOOR_BOTTOM_EAST = new DarkOakDoorMat(); public static final DarkOakDoorMat DARK_OAK_DOOR_BOTTOM_SOUTH = new DarkOakDoorMat(BlockFace.SOUTH, false); public static final DarkOakDoorMat DARK_OAK_DOOR_BOTTOM_WEST = new DarkOakDoorMat(BlockFace.WEST, false); public static final DarkOakDoorMat DARK_OAK_DOOR_BOTTOM_NORTH = new DarkOakDoorMat(BlockFace.NORTH, false); public static final DarkOakDoorMat DARK_OAK_DOOR_BOTTOM_OPEN_EAST = new DarkOakDoorMat(BlockFace.EAST, true); public static final DarkOakDoorMat DARK_OAK_DOOR_BOTTOM_OPEN_SOUTH = new DarkOakDoorMat(BlockFace.SOUTH, true); public static final DarkOakDoorMat DARK_OAK_DOOR_BOTTOM_OPEN_WEST = new DarkOakDoorMat(BlockFace.WEST, true); public static final DarkOakDoorMat DARK_OAK_DOOR_BOTTOM_OPEN_NORTH = new DarkOakDoorMat(BlockFace.NORTH, true); public static final DarkOakDoorMat DARK_OAK_DOOR_TOP_LEFT = new DarkOakDoorMat(false, false); public static final DarkOakDoorMat DARK_OAK_DOOR_TOP_RIGHT = new DarkOakDoorMat(false, true); public static final DarkOakDoorMat DARK_OAK_DOOR_TOP_LEFT_POWERED = new DarkOakDoorMat(true, false); public static final DarkOakDoorMat DARK_OAK_DOOR_TOP_RIGHT_POWERED = new DarkOakDoorMat(true, true); private static final Map<String, DarkOakDoorMat> byName = new CaseInsensitiveMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR); private static final TByteObjectMap<DarkOakDoorMat> byID = new TByteObjectHashMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR, Byte.MIN_VALUE); protected final boolean powered; protected final boolean hingeOnRightSide; protected final boolean open; protected final boolean topPart; protected final BlockFace blockFace; @SuppressWarnings("MagicNumber") protected DarkOakDoorMat() { super("DARK_OAK_DOOR", 197, "minecraft:dark_oak_door", "BOTTOM_EAST", WoodTypeMat.DARK_OAK, 3, 15); this.powered = false; this.hingeOnRightSide = false; this.open = false; this.topPart = false; this.blockFace = BlockFace.EAST; } protected DarkOakDoorMat(final boolean powered, final boolean hingeOnRightSide) { super(DARK_OAK_DOOR_BOTTOM_EAST.name(), DARK_OAK_DOOR_BOTTOM_EAST.ordinal(), DARK_OAK_DOOR_BOTTOM_EAST.getMinecraftId(), "TOP_" + (hingeOnRightSide ? "RIGHT" : "LEFT") + (powered ? "_POWERED" : ""), DoorMat.combine(powered, hingeOnRightSide), WoodTypeMat.DARK_OAK, DARK_OAK_DOOR_BOTTOM_EAST.getHardness(), DARK_OAK_DOOR_BOTTOM_EAST.getBlastResistance()); this.powered = powered; this.hingeOnRightSide = hingeOnRightSide; this.open = false; this.topPart = true; this.blockFace = null; } protected DarkOakDoorMat(final BlockFace blockFace, final boolean open) { super(DARK_OAK_DOOR_BOTTOM_EAST.name(), DARK_OAK_DOOR_BOTTOM_EAST.ordinal(), DARK_OAK_DOOR_BOTTOM_EAST.getMinecraftId(), "BOTTOM_" + (open ? "OPEN_" : "") + blockFace.name(), DoorMat.combine(blockFace, open), WoodTypeMat.DARK_OAK, DARK_OAK_DOOR_BOTTOM_EAST.getHardness(), DARK_OAK_DOOR_BOTTOM_EAST.getBlastResistance()); this.powered = false; this.hingeOnRightSide = false; this.open = open; this.topPart = false; this.blockFace = blockFace; } protected DarkOakDoorMat(final String enumName, final int id, final String minecraftId, final String typeName, final byte type, final WoodTypeMat woodType, final boolean powered, final boolean hingeOnRightSide, final boolean open, final boolean topPart, final BlockFace blockFace) { super(enumName, id, minecraftId, typeName, type, woodType, DARK_OAK_DOOR_BOTTOM_EAST.getHardness(), DARK_OAK_DOOR_BOTTOM_EAST.getBlastResistance()); this.powered = powered; this.hingeOnRightSide = hingeOnRightSide; this.open = open; this.topPart = topPart; this.blockFace = blockFace; } @Override public Material ensureValidInventoryItem() { return Material.DARK_OAK_DOOR_ITEM; } @Override public DarkOakDoorMat getType(final String name) { return getByEnumName(name); } @Override public DarkOakDoorMat getType(final int id) { return getByID(id); } @Override public DarkOakDoorMat getType(final boolean isPowered, final boolean hingeOnRightSide) { return getByID(DoorMat.combine(isPowered, hingeOnRightSide)); } @Override public DarkOakDoorMat getType(final BlockFace face, final boolean isOpen) { return getByID(DoorMat.combine(face, isOpen)); } @Override public boolean isTopPart() { return this.topPart; } @Override public DarkOakDoorMat getTopPart(final boolean top) { if (top) { return getByID(DoorMat.combine(this.powered, this.hingeOnRightSide)); } return getByID(DoorMat.combine(this.blockFace, this.open)); } @Override public BlockFace getBlockFacing() throws RuntimeException { if (this.topPart) { throw new RuntimeException("Top part don't define facing direction of door."); } return this.blockFace; } @Override public DarkOakDoorMat getBlockFacing(final BlockFace face) throws RuntimeException { if (this.topPart) { throw new RuntimeException("Top part don't define facing direction of door."); } return getByID(DoorMat.combine(face, this.open)); } @Override public boolean isOpen() throws RuntimeException { if (this.topPart) { throw new RuntimeException("Top part don't define if door is open!"); } return this.open; } @Override public DarkOakDoorMat getOpen(final boolean open) throws RuntimeException { if (this.topPart) { throw new RuntimeException("Top part don't define if door is open!"); } return getByID(DoorMat.combine(this.blockFace, open)); } @Override public boolean isPowered() throws RuntimeException { if (! this.topPart) { throw new RuntimeException("Bottom part don't define if door is powered!"); } return this.powered; } @Override public DarkOakDoorMat getPowered(final boolean powered) throws RuntimeException { if (! this.topPart) { throw new RuntimeException("Bottom part don't define if door is powered!"); } return getByID(DoorMat.combine(powered, this.hingeOnRightSide)); } @Override public boolean hasHingeOnRightSide() throws RuntimeException { if (! this.topPart) { throw new RuntimeException("Bottom part don't define side of hinge!"); } return this.hingeOnRightSide; } @Override public DarkOakDoorMat getHingeOnRightSide(final boolean onRightSide) throws RuntimeException { if (! this.topPart) { throw new RuntimeException("Bottom part don't define side of hinge!"); } return getByID(DoorMat.combine(this.powered, onRightSide)); } @Override public String toString() { if (this.topPart) { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("powered", this.powered).append("topPart", true).toString(); } else { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("open", this.open).append("blockFace", this.blockFace).append("topPart", false).toString(); } } /** * Returns one of DarkOakDoor sub-type based on sub-id, may return null * * @param id sub-type id * * @return sub-type of DarkOakDoor or null */ public static DarkOakDoorMat getByID(final int id) { return byID.get((byte) id); } /** * Returns one of DarkOakDoor sub-type based on name (selected by diorite team), may return null * If block contains only one type, sub-name of it will be this same as name of material. * * @param name name of sub-type * * @return sub-type of DarkOakDoor or null */ public static DarkOakDoorMat getByEnumName(final String name) { return byName.get(name); } /** * Returns one of DarkOakDoor sub-type based on powered state. * It will never return null, and always return top part of door. * * @param powered if door should be powered. * @param hingeOnRightSide if door should have hinge on right side. * * @return sub-type of DarkOakDoor */ public static DarkOakDoorMat getDarkOakDoor(final boolean powered, final boolean hingeOnRightSide) { return getByID(DoorMat.combine(powered, hingeOnRightSide)); } /** * Returns one of DarkOakDoor sub-type based on facing direction and open state. * It will never return null, and always return bottom part of door. * * @param blockFace facing direction of door. * @param open if door should be open. * * @return sub-type of DarkOakDoor */ public static DarkOakDoorMat getDarkOakDoor(final BlockFace blockFace, final boolean open) { return getByID(DoorMat.combine(blockFace, open)); } /** * Register new sub-type, may replace existing sub-types. * Should be used only if you know what are you doing, it will not create fully usable material. * * @param element sub-type to register */ public static void register(final DarkOakDoorMat element) { byID.put((byte) element.getType(), element); byName.put(element.getTypeName(), element); } @Override public DarkOakDoorMat[] types() { return DarkOakDoorMat.darkOakDoorTypes(); } /** * @return array that contains all sub-types of this block. */ public static DarkOakDoorMat[] darkOakDoorTypes() { return byID.values(new DarkOakDoorMat[byID.size()]); } static { DarkOakDoorMat.register(DARK_OAK_DOOR_BOTTOM_EAST); DarkOakDoorMat.register(DARK_OAK_DOOR_BOTTOM_SOUTH); DarkOakDoorMat.register(DARK_OAK_DOOR_BOTTOM_WEST); DarkOakDoorMat.register(DARK_OAK_DOOR_BOTTOM_NORTH); DarkOakDoorMat.register(DARK_OAK_DOOR_BOTTOM_OPEN_EAST); DarkOakDoorMat.register(DARK_OAK_DOOR_BOTTOM_OPEN_SOUTH); DarkOakDoorMat.register(DARK_OAK_DOOR_BOTTOM_OPEN_WEST); DarkOakDoorMat.register(DARK_OAK_DOOR_BOTTOM_OPEN_NORTH); DarkOakDoorMat.register(DARK_OAK_DOOR_TOP_LEFT); DarkOakDoorMat.register(DARK_OAK_DOOR_TOP_RIGHT); DarkOakDoorMat.register(DARK_OAK_DOOR_TOP_LEFT_POWERED); DarkOakDoorMat.register(DARK_OAK_DOOR_TOP_RIGHT_POWERED); } }
/* * The MIT License (MIT) * * Copyright (c) 2015-2019 TweetWallFX * * 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 org.tweetwallfx.controls; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javafx.css.CssMetaData; import javafx.css.SimpleStyleableBooleanProperty; import javafx.css.SimpleStyleableIntegerProperty; import javafx.css.SimpleStyleableObjectProperty; import javafx.css.SimpleStyleableStringProperty; import javafx.css.StyleConverter; import javafx.css.Styleable; import javafx.css.StyleableProperty; import javafx.scene.control.Control; import javafx.scene.control.Skin; import javafx.scene.text.Font; /** * @author Sven Reimers */ public class Wordle extends Control { private SimpleStyleableStringProperty logo; private SimpleStyleableStringProperty secondLogo; private SimpleStyleableStringProperty backgroundGraphic; private SimpleStyleableBooleanProperty favIconsVisible; private SimpleStyleableIntegerProperty displayedNumberOfTagsProperty; private SimpleStyleableObjectProperty<Font> fontProperty; private SimpleStyleableIntegerProperty fontSizeMinProperty; private SimpleStyleableIntegerProperty fontSizeMaxProperty; private SimpleStyleableIntegerProperty tweetFontSizeProperty; private String userAgentStylesheet = null; public Wordle() { getStyleClass().setAll("wordle"); } @Override protected Skin<?> createDefaultSkin() { return new WordleSkin(this); } public String getLogo() { return logo.get(); } public void setLogo(String value) { logo.set(value); } public SimpleStyleableStringProperty logoProperty() { if (logo == null) { logo = new SimpleStyleableStringProperty(StyleableProperties.LOGO_GRAPHIC, Wordle.this, "logo", null); } return logo; } public String getSecondLogo() { return secondLogo.get(); } public void setSecondLogo(String value) { secondLogo.set(value); } public SimpleStyleableStringProperty secondLogoProperty() { if (secondLogo == null) { secondLogo = new SimpleStyleableStringProperty(StyleableProperties.SECOND_LOGO_GRAPHIC, Wordle.this, "secondlogo", null); } return secondLogo; } public String getBackgroundGraphic() { return backgroundGraphic.get(); } public void setBackgroundGraphic(String value) { backgroundGraphic.set(value); } public SimpleStyleableStringProperty backgroundGraphicProperty() { if (backgroundGraphic == null) { backgroundGraphic = new SimpleStyleableStringProperty(StyleableProperties.BACKGROUND_GRAPHIC, Wordle.this, "background", null); } return backgroundGraphic; } public Boolean isFavIconsVisible() { return favIconsVisible.get(); } public void setFavIconsVisible(Boolean value) { favIconsVisible.set(value); } public SimpleStyleableBooleanProperty favIconsVisibleProperty() { if (favIconsVisible == null) { favIconsVisible = new SimpleStyleableBooleanProperty(StyleableProperties.FAVICONS_VISIBLE, Wordle.this, "-fx-fav-icons-visible", true); } return favIconsVisible; } public Integer getDisplayedTagNum() { return displayedNumberOfTagsProperty.get(); } public void setDisplayedNumberOfTags(Integer value) { displayedNumberOfTagsProperty.set(value); } public SimpleStyleableIntegerProperty displayedNumberOfTagsProperty() { if (displayedNumberOfTagsProperty == null) { displayedNumberOfTagsProperty = new SimpleStyleableIntegerProperty(StyleableProperties.DISPLAYED_TAGS_NUMBER, Wordle.this, "-fx-display-tag-num", 50); } return displayedNumberOfTagsProperty; } public Font getFont() { return fontProperty.get(); } public void setFont(Font value) { fontProperty.set(value); } public SimpleStyleableObjectProperty<Font> fontProperty() { if (fontProperty == null) { fontProperty = new SimpleStyleableObjectProperty<>(StyleableProperties.FONT, Wordle.this, "-fx-font", Font.getDefault()); } return fontProperty; } public Integer getFontSizeMin() { return fontSizeMinProperty.get(); } public void setFontSizeMin(Integer value) { fontSizeMinProperty.set(value); } public SimpleStyleableIntegerProperty fontSizeMinProperty() { if (fontSizeMinProperty == null) { fontSizeMinProperty = new SimpleStyleableIntegerProperty(StyleableProperties.FONT_SIZE_MIN, Wordle.this, "-fx-font-size-min", 36); } return fontSizeMinProperty; } public Integer getFontSizeMax() { return fontSizeMaxProperty.get(); } public void setFontSizeMax(Integer value) { fontSizeMaxProperty.set(value); } public SimpleStyleableIntegerProperty fontSizeMaxProperty() { if (fontSizeMaxProperty == null) { fontSizeMaxProperty = new SimpleStyleableIntegerProperty(StyleableProperties.FONT_SIZE_MAX, Wordle.this, "-fx-font-size-max", 72); } return fontSizeMaxProperty; } public Integer getTweetFontSize() { return tweetFontSizeProperty.get(); } public void setTweetFontSize(Integer value) { tweetFontSizeProperty.set(value); } public SimpleStyleableIntegerProperty tweetFontSizeProperty() { if (tweetFontSizeProperty == null) { tweetFontSizeProperty = new SimpleStyleableIntegerProperty(StyleableProperties.TWEET_FONT_SIZE, Wordle.this, "-fx-tweet-font-size", 54); } return tweetFontSizeProperty; } @Override public String getUserAgentStylesheet() { if (null == userAgentStylesheet) { userAgentStylesheet = this.getClass().getResource("wordle.css").toExternalForm(); } return userAgentStylesheet; } private static class StyleableProperties { private static final CssMetaData< Wordle, String> LOGO_GRAPHIC = new CssMetaData<Wordle, String>("-fx-graphic", StyleConverter.getUrlConverter(), null) { @Override public boolean isSettable(Wordle control) { return control.logo == null || !control.logo.isBound(); } @Override public StyleableProperty<String> getStyleableProperty(Wordle control) { return control.logoProperty(); } }; private static final CssMetaData< Wordle, String> SECOND_LOGO_GRAPHIC = new CssMetaData<Wordle, String>("-fx-second-graphic", StyleConverter.getUrlConverter(), null) { @Override public boolean isSettable(Wordle control) { return control.secondLogo == null || !control.secondLogo.isBound(); } @Override public StyleableProperty<String> getStyleableProperty(Wordle control) { return control.secondLogoProperty(); } }; private static final CssMetaData< Wordle, String> BACKGROUND_GRAPHIC = new CssMetaData<Wordle, String>("-fx-background-graphic", StyleConverter.getUrlConverter(), null) { @Override public boolean isSettable(Wordle control) { return control.backgroundGraphic == null || !control.backgroundGraphic.isBound(); } @Override public StyleableProperty<String> getStyleableProperty(Wordle control) { return control.backgroundGraphicProperty(); } }; private static final CssMetaData< Wordle, Boolean> FAVICONS_VISIBLE = new CssMetaData<Wordle, Boolean>("-fx-fav-icons-visible", StyleConverter.getBooleanConverter()) { @Override public boolean isSettable(Wordle control) { return control.favIconsVisible == null || !control.favIconsVisible.isBound(); } @Override public StyleableProperty<Boolean> getStyleableProperty(Wordle control) { return control.favIconsVisibleProperty(); } }; private static final CssMetaData<Wordle, Number> DISPLAYED_TAGS_NUMBER = new CssMetaData<Wordle, Number>("-fx-display-tag-num", StyleConverter.getSizeConverter()) { @Override public boolean isSettable(Wordle control) { return control.displayedNumberOfTagsProperty == null || !control.displayedNumberOfTagsProperty.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(Wordle control) { return control.displayedNumberOfTagsProperty(); } }; private static final CssMetaData<Wordle, Font> FONT = new CssMetaData<Wordle, Font>("-fx-font", StyleConverter.getFontConverter()) { @Override public boolean isSettable(Wordle control) { return control.fontProperty == null || !control.fontProperty.isBound(); } @Override public StyleableProperty<Font> getStyleableProperty(Wordle control) { return control.fontProperty(); } }; private static final CssMetaData<Wordle, Number> FONT_SIZE_MIN = new CssMetaData<Wordle, Number>("-fx-font-size-min", StyleConverter.getSizeConverter()) { @Override public boolean isSettable(Wordle control) { return control.fontSizeMinProperty == null || !control.fontSizeMinProperty.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(Wordle control) { return control.fontSizeMinProperty(); } }; private static final CssMetaData<Wordle, Number> FONT_SIZE_MAX = new CssMetaData<Wordle, Number>("-fx-font-size-max", StyleConverter.getSizeConverter()) { @Override public boolean isSettable(Wordle control) { return control.fontSizeMaxProperty == null || !control.fontSizeMaxProperty.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(Wordle control) { return control.fontSizeMaxProperty(); } }; private static final CssMetaData<Wordle, Number> TWEET_FONT_SIZE = new CssMetaData<Wordle, Number>("-fx-tweet-font-size", StyleConverter.getSizeConverter()) { @Override public boolean isSettable(Wordle control) { return control.tweetFontSizeProperty == null || !control.tweetFontSizeProperty.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(Wordle control) { return control.tweetFontSizeProperty(); } }; private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES; static { final List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<>(Control.getClassCssMetaData()); Collections.addAll(styleables, LOGO_GRAPHIC, SECOND_LOGO_GRAPHIC, BACKGROUND_GRAPHIC, FAVICONS_VISIBLE, DISPLAYED_TAGS_NUMBER, FONT, FONT_SIZE_MIN, FONT_SIZE_MAX, TWEET_FONT_SIZE ); STYLEABLES = Collections.unmodifiableList(styleables); } } @Override public List<CssMetaData<? extends Styleable, ?>> getControlCssMetaData() { return getClassCssMetaData(); } public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return StyleableProperties.STYLEABLES; } }
package com.apollographql.apollo; import com.apollographql.apollo.api.Response; import com.apollographql.apollo.cache.normalized.lru.EvictionPolicy; import com.apollographql.apollo.cache.normalized.lru.LruNormalizedCacheFactory; import com.apollographql.apollo.exception.ApolloException; import com.apollographql.apollo.fetcher.ApolloResponseFetchers; import com.apollographql.apollo.integration.normalizer.HeroAndFriendsNamesQuery; import com.apollographql.apollo.integration.normalizer.HeroAndFriendsNamesWithIDsQuery; import com.apollographql.apollo.integration.normalizer.HeroNameQuery; import com.apollographql.apollo.integration.normalizer.HeroNameWithEnumsQuery; import com.apollographql.apollo.integration.normalizer.HeroNameWithIdQuery; import com.apollographql.apollo.integration.normalizer.ReviewsByEpisodeQuery; import com.apollographql.apollo.integration.normalizer.UpdateReviewMutation; import com.apollographql.apollo.integration.normalizer.type.ColorInput; import com.apollographql.apollo.integration.normalizer.type.Episode; import com.apollographql.apollo.integration.normalizer.type.ReviewInput; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import okhttp3.OkHttpClient; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static com.google.common.truth.Truth.assertThat; public class OptimisticCacheTestCase { private ApolloClient apolloClient; private MockWebServer server; @Before public void setUp() { server = new MockWebServer(); OkHttpClient okHttpClient = new OkHttpClient.Builder() .writeTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .build(); apolloClient = ApolloClient.builder() .serverUrl(server.url("/")) .okHttpClient(okHttpClient) .normalizedCache(new LruNormalizedCacheFactory(EvictionPolicy.NO_EVICTION), new IdFieldCacheKeyResolver()) .dispatcher(Utils.immediateExecutorService()) .build(); } @After public void tearDown() { try { server.shutdown(); } catch (IOException ignored) { } } private MockResponse mockResponse(String fileName) throws IOException { return new MockResponse().setChunkedBody(Utils.readFileToString(getClass(), "/" + fileName), 32); } @Test public void simple() throws Exception { server.enqueue(mockResponse("HeroAndFriendsNameResponse.json")); HeroAndFriendsNamesQuery query = new HeroAndFriendsNamesQuery(Episode.JEDI); apolloClient.query(query).execute(); UUID mutationId = UUID.randomUUID(); HeroAndFriendsNamesQuery.Data data = new HeroAndFriendsNamesQuery.Data(new HeroAndFriendsNamesQuery.Hero( "Droid", "R222-D222", Arrays.asList( new HeroAndFriendsNamesQuery.Friend( "Human", "SuperMan" ), new HeroAndFriendsNamesQuery.Friend( "Human", "Batman" ) ) )); apolloClient.apolloStore().writeOptimisticUpdatesAndPublish(query, data, mutationId).execute(); data = apolloClient.query(query).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data.hero().name()).isEqualTo("R222-D222"); assertThat(data.hero().friends()).hasSize(2); assertThat(data.hero().friends().get(0).name()).isEqualTo("SuperMan"); assertThat(data.hero().friends().get(1).name()).isEqualTo("Batman"); apolloClient.apolloStore().rollbackOptimisticUpdates(mutationId).execute(); data = apolloClient.query(query).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data.hero().name()).isEqualTo("R2-D2"); assertThat(data.hero().friends()).hasSize(3); assertThat(data.hero().friends().get(0).name()).isEqualTo("Luke Skywalker"); assertThat(data.hero().friends().get(1).name()).isEqualTo("Han Solo"); assertThat(data.hero().friends().get(2).name()).isEqualTo("Leia Organa"); } @Test public void two_optimistic_two_rollback() throws Exception { server.enqueue(mockResponse("HeroAndFriendsNameWithIdsResponse.json")); HeroAndFriendsNamesWithIDsQuery query1 = new HeroAndFriendsNamesWithIDsQuery(Episode.JEDI); apolloClient.query(query1).execute(); UUID mutationId1 = UUID.randomUUID(); HeroAndFriendsNamesWithIDsQuery.Data data1 = new HeroAndFriendsNamesWithIDsQuery.Data( new HeroAndFriendsNamesWithIDsQuery.Hero( "Droid", "2001", "R222-D222", Arrays.asList( new HeroAndFriendsNamesWithIDsQuery.Friend( "Human", "1000", "SuperMan" ), new HeroAndFriendsNamesWithIDsQuery.Friend( "Human", "1003", "Batman" ) ) ) ); apolloClient.apolloStore().writeOptimisticUpdatesAndPublish(query1, data1, mutationId1).execute(); // check if query1 see optimistic updates data1 = apolloClient.query(query1).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data1.hero().id()).isEqualTo("2001"); assertThat(data1.hero().name()).isEqualTo("R222-D222"); assertThat(data1.hero().friends()).hasSize(2); assertThat(data1.hero().friends().get(0).id()).isEqualTo("1000"); assertThat(data1.hero().friends().get(0).name()).isEqualTo("SuperMan"); assertThat(data1.hero().friends().get(1).id()).isEqualTo("1003"); assertThat(data1.hero().friends().get(1).name()).isEqualTo("Batman"); server.enqueue(mockResponse("HeroNameWithIdResponse.json")); HeroNameWithIdQuery query2 = new HeroNameWithIdQuery(); apolloClient.query(query2).execute(); UUID mutationId2 = UUID.randomUUID(); HeroNameWithIdQuery.Data data2 = new HeroNameWithIdQuery.Data(new HeroNameWithIdQuery.Hero( "Human", "1000", "Beast" )); apolloClient.apolloStore().writeOptimisticUpdatesAndPublish(query2, data2, mutationId2).execute(); // check if query1 see the latest optimistic updates data1 = apolloClient.query(query1).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data1.hero().id()).isEqualTo("2001"); assertThat(data1.hero().name()).isEqualTo("R222-D222"); assertThat(data1.hero().friends()).hasSize(2); assertThat(data1.hero().friends().get(0).id()).isEqualTo("1000"); assertThat(data1.hero().friends().get(0).name()).isEqualTo("Beast"); assertThat(data1.hero().friends().get(1).id()).isEqualTo("1003"); assertThat(data1.hero().friends().get(1).name()).isEqualTo("Batman"); // check if query2 see the latest optimistic updates data2 = apolloClient.query(query2).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data2.hero().id()).isEqualTo("1000"); assertThat(data2.hero().name()).isEqualTo("Beast"); // rollback query1 optimistic updates apolloClient.apolloStore().rollbackOptimisticUpdates(mutationId1).execute(); // check if query1 see the latest optimistic updates data1 = apolloClient.query(query1).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data1.hero().id()).isEqualTo("2001"); assertThat(data1.hero().name()).isEqualTo("R2-D2"); assertThat(data1.hero().friends()).hasSize(3); assertThat(data1.hero().friends().get(0).id()).isEqualTo("1000"); assertThat(data1.hero().friends().get(0).name()).isEqualTo("Beast"); assertThat(data1.hero().friends().get(1).id()).isEqualTo("1002"); assertThat(data1.hero().friends().get(1).name()).isEqualTo("Han Solo"); assertThat(data1.hero().friends().get(2).id()).isEqualTo("1003"); assertThat(data1.hero().friends().get(2).name()).isEqualTo("Leia Organa"); // check if query2 see the latest optimistic updates data2 = apolloClient.query(query2).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data2.hero().id()).isEqualTo("1000"); assertThat(data2.hero().name()).isEqualTo("Beast"); // rollback query2 optimistic updates apolloClient.apolloStore().rollbackOptimisticUpdates(mutationId2).execute(); // check if query2 see the latest optimistic updates data2 = apolloClient.query(query2).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data2.hero().id()).isEqualTo("1000"); assertThat(data2.hero().name()).isEqualTo("SuperMan"); } @Test public void full_persisted_partial_optimistic() throws Exception { server.enqueue(mockResponse("HeroNameWithEnumsResponse.json")); apolloClient.query(new HeroNameWithEnumsQuery()).execute(); UUID mutationId = UUID.randomUUID(); apolloClient.apolloStore().writeOptimisticUpdates( new HeroNameQuery(), new HeroNameQuery.Data(new HeroNameQuery.Hero("Droid", "R22-D22")), mutationId ).execute(); HeroNameWithEnumsQuery.Data data = apolloClient.query(new HeroNameWithEnumsQuery()).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data.hero().name()).isEqualTo("R22-D22"); assertThat(data.hero().firstAppearsIn()).isEqualTo(Episode.EMPIRE); assertThat(data.hero().appearsIn()).isEqualTo(Arrays.asList(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI)); apolloClient.apolloStore().rollbackOptimisticUpdates(mutationId).execute(); data = apolloClient.query(new HeroNameWithEnumsQuery()).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data.hero().name()).isEqualTo("R2-D2"); assertThat(data.hero().firstAppearsIn()).isEqualTo(Episode.EMPIRE); assertThat(data.hero().appearsIn()).isEqualTo(Arrays.asList(Episode.NEWHOPE, Episode.EMPIRE, Episode.JEDI)); } @Test public void mutation_and_query_watcher() throws Exception { server.enqueue(mockResponse("ReviewsEmpireEpisodeResponse.json")); final NamedCountDownLatch watcherFirstCallLatch = new NamedCountDownLatch("WatcherFirstCall", 1); final List<ReviewsByEpisodeQuery.Data> watcherData = new ArrayList<>(); apolloClient.query(new ReviewsByEpisodeQuery(Episode.EMPIRE)).responseFetcher(ApolloResponseFetchers.NETWORK_FIRST) .watcher().refetchResponseFetcher(ApolloResponseFetchers.CACHE_FIRST) .enqueueAndWatch(new ApolloCall.Callback<ReviewsByEpisodeQuery.Data>() { @Override public void onResponse(@Nonnull Response<ReviewsByEpisodeQuery.Data> response) { watcherData.add(response.data()); watcherFirstCallLatch.countDown(); } @Override public void onFailure(@Nonnull ApolloException e) { watcherFirstCallLatch.countDown(); } }); watcherFirstCallLatch.awaitOrThrowWithTimeout(2, TimeUnit.SECONDS); server.enqueue(mockResponse("UpdateReviewResponse.json").setBodyDelay(2, TimeUnit.SECONDS)); UpdateReviewMutation updateReviewMutation = new UpdateReviewMutation( "empireReview2", ReviewInput.builder() .commentary("Great") .stars(5) .favoriteColor(ColorInput.builder().build()) .build() ); final NamedCountDownLatch mutationCallLatch = new NamedCountDownLatch("MutationCall", 1); apolloClient.mutate(updateReviewMutation, new UpdateReviewMutation.Data(new UpdateReviewMutation.UpdateReview( "Review", "empireReview2", 5, "Great"))).enqueue( new ApolloCall.Callback<UpdateReviewMutation.Data>() { @Override public void onResponse(@Nonnull Response<UpdateReviewMutation.Data> response) { mutationCallLatch.countDown(); } @Override public void onFailure(@Nonnull ApolloException e) { mutationCallLatch.countDown(); } } ); mutationCallLatch.await(3, TimeUnit.SECONDS); // sleep a while to wait if watcher gets another notification Thread.sleep(TimeUnit.SECONDS.toMillis(2)); assertThat(watcherData).hasSize(3); // before mutation and optimistic updates assertThat(watcherData.get(0).reviews()).hasSize(3); assertThat(watcherData.get(0).reviews().get(0).id()).isEqualTo("empireReview1"); assertThat(watcherData.get(0).reviews().get(0).stars()).isEqualTo(1); assertThat(watcherData.get(0).reviews().get(0).commentary()).isEqualTo("Boring"); assertThat(watcherData.get(0).reviews().get(1).id()).isEqualTo("empireReview2"); assertThat(watcherData.get(0).reviews().get(1).stars()).isEqualTo(2); assertThat(watcherData.get(0).reviews().get(1).commentary()).isEqualTo("So-so"); assertThat(watcherData.get(0).reviews().get(2).id()).isEqualTo("empireReview3"); assertThat(watcherData.get(0).reviews().get(2).stars()).isEqualTo(5); assertThat(watcherData.get(0).reviews().get(2).commentary()).isEqualTo("Amazing"); // optimistic updates assertThat(watcherData.get(1).reviews()).hasSize(3); assertThat(watcherData.get(1).reviews().get(0).id()).isEqualTo("empireReview1"); assertThat(watcherData.get(1).reviews().get(0).stars()).isEqualTo(1); assertThat(watcherData.get(1).reviews().get(0).commentary()).isEqualTo("Boring"); assertThat(watcherData.get(1).reviews().get(1).id()).isEqualTo("empireReview2"); assertThat(watcherData.get(1).reviews().get(1).stars()).isEqualTo(5); assertThat(watcherData.get(1).reviews().get(1).commentary()).isEqualTo("Great"); assertThat(watcherData.get(1).reviews().get(2).id()).isEqualTo("empireReview3"); assertThat(watcherData.get(1).reviews().get(2).stars()).isEqualTo(5); assertThat(watcherData.get(1).reviews().get(2).commentary()).isEqualTo("Amazing"); // after mutation with rolled back optimistic updates assertThat(watcherData.get(2).reviews()).hasSize(3); assertThat(watcherData.get(2).reviews().get(0).id()).isEqualTo("empireReview1"); assertThat(watcherData.get(2).reviews().get(0).stars()).isEqualTo(1); assertThat(watcherData.get(2).reviews().get(0).commentary()).isEqualTo("Boring"); assertThat(watcherData.get(2).reviews().get(1).id()).isEqualTo("empireReview2"); assertThat(watcherData.get(2).reviews().get(1).stars()).isEqualTo(4); assertThat(watcherData.get(2).reviews().get(1).commentary()).isEqualTo("Not Bad"); assertThat(watcherData.get(2).reviews().get(2).id()).isEqualTo("empireReview3"); assertThat(watcherData.get(2).reviews().get(2).stars()).isEqualTo(5); assertThat(watcherData.get(2).reviews().get(2).commentary()).isEqualTo("Amazing"); } @Test public void two_optimistic_reverse_rollback_order() throws Exception { server.enqueue(mockResponse("HeroAndFriendsNameWithIdsResponse.json")); HeroAndFriendsNamesWithIDsQuery query1 = new HeroAndFriendsNamesWithIDsQuery(Episode.JEDI); apolloClient.query(query1).execute(); server.enqueue(mockResponse("HeroNameWithIdResponse.json")); HeroNameWithIdQuery query2 = new HeroNameWithIdQuery(); apolloClient.query(query2).execute(); UUID mutationId1 = UUID.randomUUID(); HeroAndFriendsNamesWithIDsQuery.Data data1 = new HeroAndFriendsNamesWithIDsQuery.Data( new HeroAndFriendsNamesWithIDsQuery.Hero( "Droid", "2001", "R222-D222", Arrays.asList( new HeroAndFriendsNamesWithIDsQuery.Friend( "Human", "1000", "Robocop" ), new HeroAndFriendsNamesWithIDsQuery.Friend( "Human", "1003", "Batman" ) ) ) ); apolloClient.apolloStore().writeOptimisticUpdatesAndPublish(query1, data1, mutationId1).execute(); UUID mutationId2 = UUID.randomUUID(); HeroNameWithIdQuery.Data data2 = new HeroNameWithIdQuery.Data(new HeroNameWithIdQuery.Hero( "Human", "1000", "Spiderman" )); apolloClient.apolloStore().writeOptimisticUpdatesAndPublish(query2, data2, mutationId2).execute(); // check if query1 see optimistic updates data1 = apolloClient.query(query1).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data1.hero().id()).isEqualTo("2001"); assertThat(data1.hero().name()).isEqualTo("R222-D222"); assertThat(data1.hero().friends()).hasSize(2); assertThat(data1.hero().friends().get(0).id()).isEqualTo("1000"); assertThat(data1.hero().friends().get(0).name()).isEqualTo("Spiderman"); assertThat(data1.hero().friends().get(1).id()).isEqualTo("1003"); assertThat(data1.hero().friends().get(1).name()).isEqualTo("Batman"); // check if query2 see the latest optimistic updates data2 = apolloClient.query(query2).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data2.hero().id()).isEqualTo("1000"); assertThat(data2.hero().name()).isEqualTo("Spiderman"); // rollback query2 optimistic updates apolloClient.apolloStore().rollbackOptimisticUpdates(mutationId2).execute(); // check if query1 see the latest optimistic updates data1 = apolloClient.query(query1).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data1.hero().id()).isEqualTo("2001"); assertThat(data1.hero().name()).isEqualTo("R222-D222"); assertThat(data1.hero().friends()).hasSize(2); assertThat(data1.hero().friends().get(0).id()).isEqualTo("1000"); assertThat(data1.hero().friends().get(0).name()).isEqualTo("Robocop"); assertThat(data1.hero().friends().get(1).id()).isEqualTo("1003"); assertThat(data1.hero().friends().get(1).name()).isEqualTo("Batman"); // check if query2 see the latest optimistic updates data2 = apolloClient.query(query2).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data2.hero().id()).isEqualTo("1000"); assertThat(data2.hero().name()).isEqualTo("Robocop"); // rollback query1 optimistic updates apolloClient.apolloStore().rollbackOptimisticUpdates(mutationId1).execute(); // check if query1 see the latest non-optimistic updates data1 = apolloClient.query(query1).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data1.hero().id()).isEqualTo("2001"); assertThat(data1.hero().name()).isEqualTo("R2-D2"); assertThat(data1.hero().friends()).hasSize(3); assertThat(data1.hero().friends().get(0).id()).isEqualTo("1000"); assertThat(data1.hero().friends().get(0).name()).isEqualTo("SuperMan"); assertThat(data1.hero().friends().get(1).id()).isEqualTo("1002"); assertThat(data1.hero().friends().get(1).name()).isEqualTo("Han Solo"); assertThat(data1.hero().friends().get(2).id()).isEqualTo("1003"); assertThat(data1.hero().friends().get(2).name()).isEqualTo("Leia Organa"); // check if query2 see the latest non-optimistic updates data2 = apolloClient.query(query2).responseFetcher(ApolloResponseFetchers.CACHE_ONLY).execute().data(); assertThat(data2.hero().id()).isEqualTo("1000"); assertThat(data2.hero().name()).isEqualTo("SuperMan"); } }
// // Copyright 2016 Cityzen Data // // 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.warp10.app; import android.app.Activity; import android.app.IntentService; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.util.Pair; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * An {@link IntentService} subclass for handling asynchronous task requests in * a service on a separate handler thread. This service collect data on all sensors the application listen * <p/> * TODO: Customize class - update intent actions, extra parameters and static * helper methods. */ public class SensorService extends IntentService implements SensorEventListener { // TODO: Rename actions, choose action names that describe tasks that this // Boolean used to stop intent service public static volatile boolean shouldContinue = true; /** * Boolean used to know if user want to listen to the GPS */ protected static boolean isListenGPS = false; /** * Boolean used to know if user want to listen to the Network position */ protected static boolean isListenNetWork = false; /** * Connection with location Service */ protected boolean mBound = false; /** * */ protected static boolean isLocationServiceStarted = false; // MAX Buffer size private final static int BUFFER_SIZE = 1000; // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS private static final String ACTION_START = "com.cityzendata.warpapp.action.STARTLOC"; private static final String ACTION_STARTB = "com.cityzendata.warpapp.action.STARTSENSORB"; private static final String ACTION_STOP = "com.cityzendata.warpapp.action.STOP"; /** * Location service */ private static LocationService locationService = new LocationService(); /** * Warp url parameter */ protected static String url = "localhost:4242"; /** * Write token of the application */ protected static String token = "token"; /** * Prefix of the GTS given by the user */ protected String prefixGTS; // String Buffer protected StringBuffer stringBuffer; // Parameters of start/stop service function private static final String EXTRA_SENSORS = "com.cityzendata.warpapp.extra.SENSORS"; private static final String EXTRA_PREFIX = "com.cityzendata.warpapp.extra.PREFIX"; private static final String EXTRA_URL = "com.cityzendata.warpapp.extra.URL"; private static final String EXTRA_TOKEN = "com.cityzendata.warpapp.extra.TOKEN"; private static final String EXTRA_FLUSH = "com.cityzendata.warpapp.extra.FLUSH"; private static final String EXTRA_SENSORTIME = "com.cityzendata.warpapp.extra.SENSORTIME"; // Sensor Manager to detect captors to collect data private SensorManager mSensorManager = null; protected static Map<String, Sensor> sensorMap; protected static Map<String, String> mapSensorDescription; protected static Map<String, String> mapSensorNameType; /** * Connection with the location Service */ /** * Basic Constructor */ public SensorService() { super("SensorService"); } /** * Starts this service to perform action Start with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ // TODO: Customize helper method @Deprecated public static void startActionStart(Context context, List<CharSequence> sensorNameList, String prefixGTS, String warpUrl, String warpToken, int flushTime) { Intent intent = new Intent(context, SensorService.class); intent.setAction(ACTION_START); intent.putCharSequenceArrayListExtra(EXTRA_SENSORS, (ArrayList<CharSequence>) sensorNameList); intent.putExtra(EXTRA_PREFIX, prefixGTS); intent.putExtra(EXTRA_URL, warpUrl); intent.putExtra(EXTRA_TOKEN, warpToken); intent.putExtra(EXTRA_FLUSH, flushTime); context.startService(intent); } /** * Starts this service to perform action Stop with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ public static void startActionStop(Context context) { Intent intent = new Intent(context, SensorService.class); intent.setAction(ACTION_STOP); //intent.putCharSequenceArrayListExtra(EXTRA_PARAM1, (ArrayList<CharSequence>) param1); context.startService(intent); } /** * Handle intent that can be start or stop an action * @param intent contain an action, and it's parameter */ protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_START.equals(action)) { final ArrayList<CharSequence> sensorNameList = intent.getCharSequenceArrayListExtra(EXTRA_SENSORS); final String prefixGTS = intent.getStringExtra(EXTRA_PREFIX); final String warpUrl = intent.getStringExtra(EXTRA_URL); final String warpToken = intent.getStringExtra(EXTRA_TOKEN); final int flushTime = intent.getIntExtra(EXTRA_FLUSH,60); handleActionStart(sensorNameList, prefixGTS, warpUrl, warpToken, flushTime); } else if (ACTION_STOP.equals(action)) { handleActionStop(); } else if (ACTION_STARTB.equals(action)) { final String sensorName = intent.getStringExtra(EXTRA_SENSORS); final String prefixGTS = intent.getStringExtra(EXTRA_PREFIX); final int sensorTime = intent.getIntExtra(EXTRA_SENSORTIME, 10); handleActionStartB(sensorName, prefixGTS, sensorTime); } } } private void handleActionStartB(String sensorName, String prefixGTS, int sensorTime) { mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); if (mSensorManager != null) { setUpMap(); registerListeners(sensorName, sensorTime); } Log.d("SensorService", "Action START"); shouldContinue = true; this.prefixGTS = prefixGTS; SharedPreferences sharedPrefs = this.getSharedPreferences(SensorsFragment.NAME_SHARED_FILE_SENSORS, Activity.MODE_PRIVATE); // SharedPreferences sharedPrefs = PreferenceManager // .getDefaultSharedPreferences(this); initialiseHashMap(sharedPrefs); createMapSensorType(); //wsDL = new WebSocketDataListener(sharedPrefs.getString("url", "NULL"),sharedPrefs.getString("token", "NULL")); } protected void setUpMap() { if(sensorMap == null || sensorMap.isEmpty()) { sensorMap = new HashMap<>(); for (Sensor sensor : mSensorManager.getSensorList(Sensor.TYPE_ALL)) { sensorMap.put(sensor.getName(), sensor); } } } /** * Handle action Start in the provided background thread with the provided * parameters. */ @Deprecated private void handleActionStart(List<CharSequence> sensorNameList, String prefixGTS, String warpUrl, String warpToken, int flushTime) { if (flushTime < 60) { flushTime = 60; } int flushTimeInSeconds = flushTime * 1000; FileService.FLUSH_TIME = (flushTimeInSeconds*3)/4; //Log.v("SensorService", "SensingService.onHandleIntent"); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); if (mSensorManager != null) { registerListeners(sensorNameList); } Log.d("SensorService", "Action START"); shouldContinue = true; url = warpUrl; token = warpToken; this.prefixGTS = prefixGTS; if (stringBuffer == null) { stringBuffer = new StringBuffer(); } if(sensorNameList.contains("GPS")) { isListenGPS = true; } if(sensorNameList.contains("NETWORK")){ isListenNetWork = true; } boolean recGPS= false, recNetwork = false; if(sensorNameList.contains("GPS GTS")) { recGPS = true; } if(sensorNameList.contains("NETWORK GTS")){ recNetwork = true; } if(isListenGPS || isListenNetWork || recGPS || recNetwork) { locationService.handleStartCommand(this, isListenGPS, isListenNetWork, recGPS, recNetwork, prefixGTS); isLocationServiceStarted = true; } SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(this); //SharedPreferences.Editor ed = sharedPrefs.edit(); //ed.putBoolean("isActive", true); //ed.commit(); } /** * Handle action Stop in the provided background thread with the provided * parameters. */ private void handleActionStop() { shouldContinue = false; SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(this); //boolean isActive = sharedPrefs.getBoolean("isActive", false); Log.d("ActionSTOP", "Handled"); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); for (Sensor sensor : mSensorManager.getSensorList(Sensor.TYPE_ALL)) { mSensorManager.unregisterListener(this); //Log.d("SensorService", sensor.getName().toString()); } /* if (isLocationServiceStarted) { stopService(new Intent(this, LocationService.class)); } */ //FlushService.flushAllFiles("fill", this, url, token, true); } /** Defines callbacks for service binding, passed to bindService() */ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance LocationService.LocalBinder binder = (LocationService.LocalBinder) service; locationService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; /** * Action executed every time one value of a recorded sensor changed * @param currentEvent event */ public void onSensorChanged(SensorEvent currentEvent) { // If app continue if (shouldContinue == true) { String locString; //Log.d("IsLocStarted", "" + isLocationServiceStarted); if (isLocationServiceStarted) { //onBind(new Intent(this, LocationService.class)); locString = getPositionString(); //unbindService(mConnection); } else { locString = "// "; } //Log.d("LOCATION", locString); // If buffer have full size if (stringBuffer == null) { stringBuffer = new StringBuffer(); } if (stringBuffer.length() >= BUFFER_SIZE) { emptyBuffer(); } if (stringBuffer.length() > 0 ) { stringBuffer.append("\n"); } String fix = ""; /** if(prefixGTS.equals(new String())) { prefixGTS = "android"; }*/ if (prefixGTS.length() != prefixGTS.lastIndexOf(".")) { fix = "."; } long timestamp = System.currentTimeMillis() * 1000; int counter = 0; String[] splitDescription = null; String type = mapSensorNameType.get(getSensorName(currentEvent)); String description = "NULL"; if(mapSensorDescription.containsKey(type)) { description = mapSensorDescription.get(type); } if (!description.equals("NULL")) { splitDescription = description.replaceAll("\\s", "").split(","); } for (Float val : currentEvent.values) { String currentDesc = ""; if( null != splitDescription && splitDescription.length >= counter+1) { currentDesc += "."; currentDesc += splitDescription[counter]; } //Log.d("SensorDesc", description); String string = timestamp + locString + prefixGTS.replaceAll("\\s","") + fix + getSensorName(currentEvent).replace(" ", ".") + currentDesc + "{" + "type=" + getSensorType(currentEvent) + ",vendor=" + currentEvent.sensor.getVendor().replace(" ", "-") + ",version=" + currentEvent.sensor.getVersion() + ",source=android"; //Log.d("Val", string); if(counter > 0) { stringBuffer.append("\n"); } stringBuffer.append(string); stringBuffer.append(",valueIndex=" + counter + "} "); stringBuffer.append(val); counter++; } } // If app stopped if (shouldContinue == false) { emptyBuffer(); stringBuffer = null; for (Sensor sensor : mSensorManager.getSensorList(Sensor.TYPE_ALL)) { mSensorManager.unregisterListener(this); } stopSelf(); return; } } /** * Method used for testing purposes * @param event * @return */ protected String getSensorName(SensorEvent event){ return event.sensor.getName(); } /** * Method used for testing purposes * @param event * @return */ protected int getSensorType(SensorEvent event){ return event.sensor.getType(); } /** * Method used to detect last known position of a user * @return string containing /lat:long/ if last position is null contain // */ protected String getPositionString() { String locString = "// "; Location mLastLocation = LocationService.getLastLocation(isListenGPS,isListenNetWork); if (mLastLocation != null) { locString = "/" + mLastLocation.getLatitude() + ":" + mLastLocation.getLongitude() + "/ "; //Log.d("LOCATIONB", mLastLocation.toString()); } return locString; } /** * empty current buffer */ public void emptyBuffer() { if (stringBuffer != null) { //Log.d("SensorService", stringBuffer.toString()); final StringBuffer buffer = new StringBuffer(stringBuffer); FileService.writeToFile(buffer.toString(), this); if (!CollectService.isPostActive) { if(!CollectService.ws.isClosed()) { CollectService.ws.writeData(buffer.toString()); } } //FlushWithSocket.writeValues(buffer.toString()); //Log.d("Buffer", buffer.toString()); //CollectService.webSocket.writeMessage(buffer.toString()); stringBuffer = new StringBuffer(); } } /** * Required method, when accuracy of sensor changed */ public void onAccuracyChanged(Sensor sensor, int accuracy) { } /** * Method used to register a listener on sensors, only the one corresponding to the user wishes are registered * @param param List of captors name to register */ @Deprecated private void registerListeners(List<CharSequence> param) { //Log.v("SensorService", "Registering sensors listeners"); for (Sensor sensor : mSensorManager.getSensorList(Sensor.TYPE_ALL)) { if(param.contains(sensor.getName())) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL, 1000*60); mSensorManager.flush(this); } else { mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL); } //Log.d("SensorService", sensor.getName().toString()); FileService.setContext(this); //FileService.writeLogFile("CollectSensor: " + sensor.getName().toString()); } } } /** * Method registering listener on a sensor * @param sensor sensor name */ private void registerListeners(String sensor, int time) { if(sensorMap.containsKey(sensor)) { /** * For new version android >= 20 */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mSensorManager.registerListener(this, sensorMap.get(sensor), SensorManager.SENSOR_DELAY_NORMAL, time*1000*1000); mSensorManager.flush(this); } else { /** * For old version android <= 20 */ mSensorManager.registerListener(this, sensorMap.get(sensor), SensorManager.SENSOR_DELAY_NORMAL); } } } /** * New action start, used to start an intent service which listen to a sensor * @param context application context * @param sensorName sensor name * @param prefGts user choice of GTS prefix */ public void startActionStart(Context context, String sensorName, String prefGts, int sensorTime) { Intent intent = new Intent(context, SensorService.class); intent.setAction(ACTION_STARTB); intent.putExtra(EXTRA_SENSORS, sensorName); intent.putExtra(EXTRA_PREFIX, prefGts); intent.putExtra(EXTRA_SENSORTIME, sensorTime); context.startService(intent); } /** * Function used to initialise HashMap containing user choices of value name for * a kind of sensor * @param sharedPreferences */ private void initialiseHashMap(SharedPreferences sharedPreferences) { mapSensorDescription = new HashMap<>(); Map<String, ?> keySet = sharedPreferences.getAll(); //List<String> lString = SensorsFragment.preferencesList; //Log.d("ALLPREF", lString.toString()); for (String pref:keySet.keySet()) { //if (!lString.contains(pref)) { String value = sharedPreferences.getString(pref, "NULL"); if(!value.equals("NULL")) { Pair<String, String> pair = SensorPreference.parseValue(value); String type = "android.sensor." + pair.first.replaceAll("\\s+", "_").toLowerCase(); mapSensorDescription.put(type,pair.second); } //} } } /** * Function used to initialize the map relating a sensor name to a type */ private void createMapSensorType() { mapSensorNameType = new HashMap<>(); SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE); List<Sensor> list = sm.getSensorList(Sensor.TYPE_ALL); for (Sensor sensor :list) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { /** * For new version android >= 20 */ mapSensorNameType.put(sensor.getName(),sensor.getStringType()); } else { /** * For android version <= 20 */ String sensorType = "android.sensor."; int type = sensor.getType(); switch (type) { case Sensor.TYPE_ACCELEROMETER: sensorType += "accelerometer"; break; case Sensor.TYPE_AMBIENT_TEMPERATURE: sensorType += "ambient_temperature"; break; case Sensor.TYPE_GAME_ROTATION_VECTOR: sensorType += "game_rotation_vector"; break; case Sensor.TYPE_GRAVITY: sensorType += "gravity"; break; case Sensor.TYPE_GYROSCOPE: sensorType += "gyroscope"; break; case Sensor.TYPE_GYROSCOPE_UNCALIBRATED: sensorType += "gyroscope_uncalibrated"; break; case Sensor.TYPE_LIGHT: sensorType += "light"; break; case Sensor.TYPE_LINEAR_ACCELERATION: sensorType += "linear_acceleration"; break; case Sensor.TYPE_MAGNETIC_FIELD: sensorType += "magnetic_field"; break; case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED: sensorType += "magnetic_field_uncalibrated"; break; case Sensor.TYPE_ORIENTATION: sensorType += "orientation"; break; case Sensor.TYPE_PRESSURE: sensorType += "pressure"; break; case Sensor.TYPE_PROXIMITY: sensorType += "proximity"; break; case Sensor.TYPE_RELATIVE_HUMIDITY: sensorType += "relative_humidity"; break; case Sensor.TYPE_ROTATION_VECTOR: sensorType += "rotation_vector"; break; case Sensor.TYPE_SIGNIFICANT_MOTION: sensorType += "significant_motion"; break; case Sensor.TYPE_TEMPERATURE: sensorType += "temperature"; break; default: sensorType = "NULL"; break; } mapSensorNameType.put(sensor.getName(),sensorType); } } //Log.d("MAP TYPEs",mapSensorNameType.toString()); } }
/** */ package isostdisots_29002_4ed_1techxmlschemabasicSimplified.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import isostdisots_29002_4ed_1techxmlschemabasicSimplified.Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage; import isostdisots_29002_4ed_1techxmlschemabasicSimplified.LanguageString; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Language String</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link isostdisots_29002_4ed_1techxmlschemabasicSimplified.impl.LanguageStringImpl#getContent <em>Content</em>}</li> * <li>{@link isostdisots_29002_4ed_1techxmlschemabasicSimplified.impl.LanguageStringImpl#getLanguageRef <em>Language Ref</em>}</li> * <li>{@link isostdisots_29002_4ed_1techxmlschemabasicSimplified.impl.LanguageStringImpl#getLanguageCode <em>Language Code</em>}</li> * <li>{@link isostdisots_29002_4ed_1techxmlschemabasicSimplified.impl.LanguageStringImpl#getCountryCode <em>Country Code</em>}</li> * </ul> * * @generated */ public class LanguageStringImpl extends MinimalEObjectImpl.Container implements LanguageString { /** * The default value of the '{@link #getContent() <em>Content</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getContent() * @generated * @ordered */ protected static final String CONTENT_EDEFAULT = null; /** * The cached value of the '{@link #getContent() <em>Content</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getContent() * @generated * @ordered */ protected String content = CONTENT_EDEFAULT; /** * The default value of the '{@link #getLanguageRef() <em>Language Ref</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLanguageRef() * @generated * @ordered */ protected static final String LANGUAGE_REF_EDEFAULT = null; /** * The cached value of the '{@link #getLanguageRef() <em>Language Ref</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLanguageRef() * @generated * @ordered */ protected String languageRef = LANGUAGE_REF_EDEFAULT; /** * The default value of the '{@link #getLanguageCode() <em>Language Code</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLanguageCode() * @generated * @ordered */ protected static final String LANGUAGE_CODE_EDEFAULT = null; /** * The cached value of the '{@link #getLanguageCode() <em>Language Code</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLanguageCode() * @generated * @ordered */ protected String languageCode = LANGUAGE_CODE_EDEFAULT; /** * The default value of the '{@link #getCountryCode() <em>Country Code</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCountryCode() * @generated * @ordered */ protected static final String COUNTRY_CODE_EDEFAULT = null; /** * The cached value of the '{@link #getCountryCode() <em>Country Code</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCountryCode() * @generated * @ordered */ protected String countryCode = COUNTRY_CODE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected LanguageStringImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.Literals.LANGUAGE_STRING; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getContent() { return content; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setContent(String newContent) { String oldContent = content; content = newContent; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__CONTENT, oldContent, content)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLanguageRef() { return languageRef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLanguageRef(String newLanguageRef) { String oldLanguageRef = languageRef; languageRef = newLanguageRef; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__LANGUAGE_REF, oldLanguageRef, languageRef)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLanguageCode() { return languageCode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLanguageCode(String newLanguageCode) { String oldLanguageCode = languageCode; languageCode = newLanguageCode; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__LANGUAGE_CODE, oldLanguageCode, languageCode)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getCountryCode() { return countryCode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCountryCode(String newCountryCode) { String oldCountryCode = countryCode; countryCode = newCountryCode; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__COUNTRY_CODE, oldCountryCode, countryCode)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__CONTENT: return getContent(); case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__LANGUAGE_REF: return getLanguageRef(); case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__LANGUAGE_CODE: return getLanguageCode(); case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__COUNTRY_CODE: return getCountryCode(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__CONTENT: setContent((String)newValue); return; case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__LANGUAGE_REF: setLanguageRef((String)newValue); return; case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__LANGUAGE_CODE: setLanguageCode((String)newValue); return; case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__COUNTRY_CODE: setCountryCode((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__CONTENT: setContent(CONTENT_EDEFAULT); return; case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__LANGUAGE_REF: setLanguageRef(LANGUAGE_REF_EDEFAULT); return; case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__LANGUAGE_CODE: setLanguageCode(LANGUAGE_CODE_EDEFAULT); return; case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__COUNTRY_CODE: setCountryCode(COUNTRY_CODE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__CONTENT: return CONTENT_EDEFAULT == null ? content != null : !CONTENT_EDEFAULT.equals(content); case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__LANGUAGE_REF: return LANGUAGE_REF_EDEFAULT == null ? languageRef != null : !LANGUAGE_REF_EDEFAULT.equals(languageRef); case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__LANGUAGE_CODE: return LANGUAGE_CODE_EDEFAULT == null ? languageCode != null : !LANGUAGE_CODE_EDEFAULT.equals(languageCode); case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.LANGUAGE_STRING__COUNTRY_CODE: return COUNTRY_CODE_EDEFAULT == null ? countryCode != null : !COUNTRY_CODE_EDEFAULT.equals(countryCode); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (content: "); result.append(content); result.append(", languageRef: "); result.append(languageRef); result.append(", languageCode: "); result.append(languageCode); result.append(", countryCode: "); result.append(countryCode); result.append(')'); return result.toString(); } } //LanguageStringImpl
/** * 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.sqoop.mapreduce.db.netezza; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.sqoop.io.NamedFifo; import org.apache.sqoop.lib.SqoopRecord; import org.apache.sqoop.manager.DirectNetezzaManager; import org.apache.sqoop.mapreduce.SqoopMapper; import org.apache.sqoop.mapreduce.db.DBConfiguration; import org.apache.sqoop.util.FileUploader; import org.apache.sqoop.util.PerfCounters; import org.apache.sqoop.util.TaskId; import com.cloudera.sqoop.lib.DelimiterSet; /** * Netezza export mapper using external tables. */ public abstract class NetezzaExternalTableExportMapper<K, V> extends SqoopMapper<K, V, NullWritable, NullWritable> { /** * Create a named FIFO, and start the Netezza JDBC thread connected to that * FIFO. A File object representing the FIFO is in 'fifoFile'. */ private Configuration conf; private DBConfiguration dbc; private File fifoFile; private Connection con; private OutputStream recordWriter; public static final Log LOG = LogFactory .getLog(NetezzaExternalTableImportMapper.class.getName()); private NetezzaJDBCStatementRunner extTableThread; private PerfCounters counter; private DelimiterSet outputDelimiters; private String localLogDir = null; private String logDir = null; private File taskAttemptDir = null; private String getSqlStatement(DelimiterSet delimiters) throws IOException { char fd = delimiters.getFieldsTerminatedBy(); char qc = delimiters.getEnclosedBy(); char ec = delimiters.getEscapedBy(); String nullValue = conf.get(DirectNetezzaManager.NETEZZA_NULL_VALUE); int errorThreshold = conf.getInt( DirectNetezzaManager.NETEZZA_ERROR_THRESHOLD_OPT, 1); boolean ctrlChars = conf.getBoolean(DirectNetezzaManager.NETEZZA_CTRL_CHARS_OPT, false); boolean truncString = conf.getBoolean(DirectNetezzaManager.NETEZZA_TRUNC_STRING_OPT, false); boolean ignoreZero = conf.getBoolean(DirectNetezzaManager.NETEZZA_IGNORE_ZERO_OPT, false); boolean crinString = conf.getBoolean(DirectNetezzaManager.NETEZZA_CRIN_STRING_OPT, false); StringBuilder sqlStmt = new StringBuilder(2048); sqlStmt.append("INSERT INTO "); sqlStmt.append(dbc.getOutputTableName()); sqlStmt.append(" SELECT * FROM EXTERNAL '"); sqlStmt.append(fifoFile.getAbsolutePath()); sqlStmt.append("' USING (REMOTESOURCE 'JDBC' "); sqlStmt.append(" BOOLSTYLE 'TRUE_FALSE' "); if (crinString) { sqlStmt.append(" CRINSTRING TRUE "); } else { sqlStmt.append(" CRINSTRING FALSE "); } if (ctrlChars) { sqlStmt.append(" CTRLCHARS TRUE "); } if (truncString) { sqlStmt.append(" TRUNCSTRING TRUE "); } if (ignoreZero) { sqlStmt.append(" IGNOREZERO TRUE "); } sqlStmt.append(" DELIMITER "); sqlStmt.append(Integer.toString(fd)); sqlStmt.append(" ENCODING 'internal' "); if (ec > 0) { sqlStmt.append(" ESCAPECHAR '\\' "); } sqlStmt.append(" FORMAT 'Text' "); sqlStmt.append(" INCLUDEZEROSECONDS TRUE "); sqlStmt.append(" NULLVALUE '"); if (nullValue != null) { sqlStmt.append(nullValue); } else { sqlStmt.append("null"); } sqlStmt.append("' "); if (qc > 0) { switch (qc) { case '\'': sqlStmt.append(" QUOTEDVALUE SINGLE "); break; case '\"': sqlStmt.append(" QUOTEDVALUE DOUBLE "); break; default: LOG.warn("Unsupported enclosed by character: " + qc + " - ignoring."); } } sqlStmt.append(" MAXERRORS ").append(errorThreshold); File logDirPath = new File(taskAttemptDir, localLogDir); logDirPath.mkdirs(); if (logDirPath.canWrite() && logDirPath.isDirectory()) { sqlStmt.append(" LOGDIR ") .append(logDirPath.getAbsolutePath()).append(' '); } else { throw new IOException("Unable to create log directory specified"); } sqlStmt.append(")"); String stmt = sqlStmt.toString(); LOG.debug("SQL generated for external table export" + stmt); return stmt; } private void initNetezzaExternalTableExport(Context context) throws IOException { this.conf = context.getConfiguration(); taskAttemptDir = TaskId.getLocalWorkPath(conf); localLogDir = DirectNetezzaManager.getLocalLogDir(context.getTaskAttemptID()); logDir = conf.get(DirectNetezzaManager.NETEZZA_LOG_DIR_OPT); dbc = new DBConfiguration(conf); File taskAttemptDir = TaskId.getLocalWorkPath(conf); char fd = (char) conf.getInt(DelimiterSet.INPUT_FIELD_DELIM_KEY, ','); char qc = (char) conf.getInt(DelimiterSet.INPUT_ENCLOSED_BY_KEY, 0); char ec = (char) conf.getInt(DelimiterSet.INPUT_ESCAPED_BY_KEY, 0); this.outputDelimiters = new DelimiterSet(fd, '\n', qc, ec, false); this.fifoFile = new File(taskAttemptDir, ("nzexttable-export.txt")); String filename = fifoFile.toString(); NamedFifo nf; // Create the FIFO itself. try { nf = new NamedFifo(this.fifoFile); nf.create(); } catch (IOException ioe) { // Command failed. LOG.error("Could not create FIFO file " + filename); this.fifoFile = null; throw new IOException( "Could not create FIFO for netezza external table import", ioe); } String sqlStmt = getSqlStatement(outputDelimiters); boolean cleanup = false; try { con = dbc.getConnection(); extTableThread = new NetezzaJDBCStatementRunner(Thread.currentThread(), con, sqlStmt); } catch (SQLException sqle) { cleanup = true; throw new IOException(sqle); } catch (ClassNotFoundException cnfe) { throw new IOException(cnfe); } finally { if (con != null && cleanup) { try { con.close(); } catch (Exception e) { LOG.debug("Exception closing connection " + e.getMessage()); } } con = null; } counter = new PerfCounters(); extTableThread.start(); // We start the JDBC thread first in this case as we want the FIFO reader to // be running. recordWriter = new BufferedOutputStream(new FileOutputStream(nf.getFile())); counter.startClock(); } @Override public void run(Context context) throws IOException, InterruptedException { setup(context); initNetezzaExternalTableExport(context); if (extTableThread.isAlive()) { try { while (context.nextKeyValue()) { if (Thread.interrupted()) { if (!extTableThread.isAlive()) { break; } } map(context.getCurrentKey(), context.getCurrentValue(), context); } cleanup(context); } finally { try { recordWriter.close(); extTableThread.join(); } catch (Exception e) { LOG.debug("Exception cleaning up mapper operation : " + e.getMessage()); } counter.stopClock(); LOG.info("Transferred " + counter.toString()); FileUploader.uploadFilesToDFS(taskAttemptDir.getAbsolutePath(), localLogDir, logDir, context.getJobID().toString(), conf); if (extTableThread.hasExceptions()) { extTableThread.printException(); throw new IOException(extTableThread.getException()); } } } } protected void writeTextRecord(Text record) throws IOException, InterruptedException { String outputStr = record.toString() + "\n"; byte[] outputBytes = outputStr.getBytes("UTF-8"); counter.addBytes(outputBytes.length); recordWriter.write(outputBytes, 0, outputBytes.length); } protected void writeSqoopRecord(SqoopRecord sqr) throws IOException, InterruptedException { String outputStr = sqr.toString(this.outputDelimiters); byte[] outputBytes = outputStr.getBytes("UTF-8"); counter.addBytes(outputBytes.length); recordWriter.write(outputBytes, 0, outputBytes.length); } }
/** * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999. * * This program is free software; you can redistribute it and/or modify * it under the terms of the latest version of the GNU Lesser General * Public License as published by the Free Software Foundation; * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program (LICENSE.txt); if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jamwiki.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.jamwiki.DataAccessException; import org.jamwiki.WikiBase; import org.jamwiki.WikiException; import org.jamwiki.model.Topic; import org.jamwiki.model.TopicType; import org.jamwiki.model.TopicVersion; import org.jamwiki.model.WikiUser; import org.jamwiki.parser.WikiLink; /** * This class parse a TiddlyWiki file and imports it to JamWiki * * @author Michael Greifeneder mikegr@gmx.net * @deprecated Tiddly wiki import support has been unmaintained since JAMWiki * 0.6.0 and will be removed in a future release unless a new maintainer is * found. */ public class TiddlyWikiParser { private static final WikiLogger logger = WikiLogger.getLogger(TiddlyWikiParser.class.getName()); private static final String DIV_START = "<div tiddler"; private static final String DIV_END = "</div>"; private static final String TIDLLER = "tiddler"; //private static final String MODIFIER = "modifier"; private static final String MODIFIED = "modified"; //private static final String TAGS = "tags"; private static final SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHHmm"); private StringBuilder messages = new StringBuilder(); private String virtualWiki; private WikiUser user; private String authorDisplay; /** * Facade for WikiBase. Used for enable unit testing. * @author Michael Greifeneder mikegr@gmx.net */ public interface WikiBaseFascade { public void writeTopic(Topic topic, TopicVersion topicVersion, LinkedHashMap categories, List<String> links, Object transactionObject) throws DataAccessException, WikiException; } /** * Defaul WikiBaseFascade for production. */ private WikiBaseFascade wikiBase = new WikiBaseFascade() { public void writeTopic(Topic topic, TopicVersion topicVersion, LinkedHashMap categories, List<String> links, Object transactionObject) throws DataAccessException, WikiException { WikiBase.getDataHandler().writeTopic(topic, topicVersion, null, null); } }; private TiddlyWiki2MediaWikiTranslator translator = new TiddlyWiki2MediaWikiTranslator(); /** * Main constructor * * @param virtualWiki virtualWiki * @param user user who is currently logged in * @param authorDisplay A display value for the importing user, typically the IP address. */ public TiddlyWikiParser(String virtualWiki, WikiUser user, String authorDisplay) { this.virtualWiki = virtualWiki; this.user = user; this.authorDisplay = authorDisplay; } /** * Use this contructor for test cases * * @param virtualWiki Name of VirtualWiki * @param user User who is logged in. * @param authorDisplay A display value for the importing user, typically the IP address. * @param wikiBase Overwrites default WikiBaseFascade */ public TiddlyWikiParser(String virtualWiki, WikiUser user, String authorDisplay, WikiBaseFascade wikiBase) { this(virtualWiki, user, authorDisplay); this.wikiBase = wikiBase; } /** * Parses file and returns default topic. * * @param file TiddlyWiki file * @return main topic for this TiddlyWiki */ public String parse(File file) throws DataAccessException, IOException, WikiException { Reader r = new FileReader(file); BufferedReader br = new BufferedReader(r); return parse(br); } /** * Parses TiddlyWiki content and returns default topic. * * @param br TiddlyWiki file content * @return main topic for this TiddlyWiki */ public String parse(BufferedReader br) throws DataAccessException, IOException, WikiException { String line = br.readLine(); boolean inTiddler = false; int start = 0; int end = 0; StringBuilder content = new StringBuilder(); while (line != null) { if (inTiddler) { end = line.indexOf(DIV_END); if (end != -1) { inTiddler = false; content.append(line.substring(0, end)); processContent(content.toString()); content.setLength(0); line = line.substring(end); } else { content.append(line); line = br.readLine(); } } else { start = line.indexOf(DIV_START); if (start != -1 && (line.indexOf("<div tiddler=\"%0\"") == -1)) { inTiddler = true; logger.debug("Ignoring:\n" + line.substring(0, start)); line = line.substring(start); } else { logger.debug("Div tiddler not found in: \n" + line); line = br.readLine(); } } } return "DefaultTiddlers"; } /** * */ private void processContent(String content) throws DataAccessException, IOException, WikiException { logger.debug("Content: " + content); String name = findName(content, TIDLLER); if (name == null|| "%0".equals(user)) { return; } /* no need for user String user = findName(content, MODIFIER); if (user == null ) { messages.append("WARN: ") return; } */ Date lastMod = null; try { lastMod = formater.parse(findName(content, MODIFIED)); } catch (Exception e) { messages.append("WARNING: corrupt line: ").append(content); } if (lastMod == null) { return; } /* ignoring tags String tags = findName(content, TAGS); if (tags == null) { return; } */ int idx = content.indexOf('>'); if (idx == -1) { logger.warn("No closing of tag"); messages.append("WARNING: corrupt line: ").append(content); return; } String wikicode = content.substring(idx +1); wikicode = translator.translate(wikicode); messages.append("Adding topic " + name + "\n"); saveTopic(name, lastMod, wikicode); logger.debug("Code:" + wikicode); } /** * */ private void saveTopic(String name, Date lastMod, String content) throws DataAccessException, WikiException { WikiLink wikiLink = new WikiLink(null, virtualWiki, name); Topic topic = new Topic(virtualWiki, wikiLink.getNamespace(), wikiLink.getArticle()); topic.setTopicContent(content); int charactersChanged = StringUtils.length(content); TopicVersion topicVersion = new TopicVersion(user, authorDisplay, "imported", content, charactersChanged); topicVersion.setEditDate(new Timestamp(lastMod.getTime())); // manage mapping bitween MediaWiki and JAMWiki namespaces topic.setTopicType(TopicType.ARTICLE); // Store topic in database wikiBase.writeTopic(topic, topicVersion, null, null, null); } /** * */ private String findName(String content, String name) { int startIdx = content.indexOf(name); if (startIdx == -1) { logger.warn("no tiddler name found"); return null; } startIdx = content.indexOf('\"', startIdx); int endIdx = content.indexOf('\"', startIdx+1); String value = content.substring(startIdx+1, endIdx); logger.debug(name + ":" + value); return value; } /** * */ public String getOutput() { return messages.toString(); } }
/* * Copyright 2012-2014 eBay Software Foundation and selendroid committers. * * 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 io.selendroid.testapp; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnLongClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; /** * Demo project to verify selendroid actions. * * @author ddary */ public class HomeScreenActivity extends Activity { private static final int DIALOG_ALERT = 10; private static final int DIALOG_LONG_PRESS = 12; private static final int DIALOG_DOWNLOAD_PROGRESS = 11; private static String TAG = "Selendroid-demoapp"; private ProgressDialog progressDialog = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "onCreate"); setContentView(R.layout.homescreen); Button button = (Button) findViewById(R.id.buttonTest); button.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { showDialog(DIALOG_LONG_PRESS); return true; } }); initExceptionTestButton(); initExceptionTestField(); } @Override protected void onResume() { TextView textview = ((TextView) findViewById(R.id.visibleTextView)); textview.setVisibility(View.INVISIBLE); super.onResume(); } public void displayPopupWindow(View view) { LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE); View popupView = layoutInflater.inflate(R.layout.popup_window, null); final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); Button btnDismiss = (Button) popupView.findViewById(R.id.popup_dismiss_button); btnDismiss.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub popupWindow.dismiss(); } }); Button btnOpenPopup = (Button) findViewById(R.id.showPopupWindowButton); popupWindow.showAsDropDown(btnOpenPopup, -50, -300); } public void showL10nDialog(View view) { showDialog(DIALOG_ALERT); } public void showWaitingDialog(View view) { new MyAsyncTask().execute(""); } public void showWebViewDialog(View view) { Intent nextScreen = new Intent(getApplicationContext(), WebViewActivity.class); startActivity(nextScreen); } public void showSearchDialog(View view) { Intent nextScreen = new Intent(getApplicationContext(), SearchUsersActivity.class); startActivity(nextScreen); } public void showUserRegistrationDialog(View view) { Intent nextScreen = new Intent(getApplicationContext(), RegisterUserActivity.class); startActivity(nextScreen); } public void displayToast(View view) { Context context = getApplicationContext(); CharSequence text = "Hello selendroid toast!"; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } public void displayTextView(View view) { TextView textview = ((TextView) findViewById(R.id.visibleTextView)); if (textview.isShown()) { textview.setVisibility(View.INVISIBLE); } else { textview.setVisibility(View.VISIBLE); } } public void displayAndFocus(View view) { LinearLayout linearLayout = ((LinearLayout) findViewById(R.id.focusedLayout)); if (linearLayout.isShown()) { linearLayout.setVisibility(View.GONE); } else { linearLayout.setVisibility(View.VISIBLE); linearLayout.requestFocus(); } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ALERT: // Create out AlterDialog Builder builder = new AlertDialog.Builder(this); builder.setMessage("This will end the activity"); builder.setCancelable(true); builder.setPositiveButton("I agree", new OkOnClickListener()); builder.setNegativeButton("No, no", new CancelOnClickListener()); AlertDialog dialog = builder.create(); dialog.show(); return dialog; case DIALOG_LONG_PRESS: Builder builder2 = new AlertDialog.Builder(this); builder2.setMessage("Long Press Tap has been received."); builder2.setCancelable(true); builder2.setPositiveButton("Ok", new CancelOnClickListener()); AlertDialog dialog2 = builder2.create(); dialog2.show(); return dialog2; case DIALOG_DOWNLOAD_PROGRESS: progressDialog = new ProgressDialog(this); progressDialog.setMessage("Waiting Dialog"); progressDialog.setIndeterminate(false); progressDialog.setMax(100); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setCancelable(true); progressDialog.show(); return progressDialog; } return super.onCreateDialog(id); } private final class CancelOnClickListener implements DialogInterface.OnClickListener { public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(), "Activity will continue", Toast.LENGTH_LONG).show(); } } private final class OkOnClickListener implements DialogInterface.OnClickListener { public void onClick(DialogInterface dialog, int which) { HomeScreenActivity.this.finish(); } } class MyAsyncTask extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); showDialog(DIALOG_DOWNLOAD_PROGRESS); } @Override protected String doInBackground(String... params) { try { Thread.sleep(3000); progressDialog.setProgress(25); Thread.sleep(3000); progressDialog.setProgress(50); Thread.sleep(3000); progressDialog.setProgress(75); Thread.sleep(3000); progressDialog.setProgress(100); } catch (Exception e) { } return null; } @Override protected void onPostExecute(String unused) { try { dismissDialog(DIALOG_DOWNLOAD_PROGRESS); } catch (Exception e) { // ignore } showUserRegistrationDialog(null); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.layout.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_home) { startActivity(new Intent(getApplicationContext(), HomeScreenActivity.class)); return true; } else if (item.getItemId() == R.id.menu_web_view) { startActivity(new Intent(getApplicationContext(), WebViewActivity.class)); return true; } else if (item.getItemId() == R.id.menu_multiple_web_views) { startActivity(new Intent(getApplicationContext(), MultipleWebViewsActivity.class)); return true; } else if (item.getItemId() == R.id.extreem_large_view) { startActivity(new Intent(getApplicationContext(), ExtremLargeActivity.class)); return true; } else if (item.getItemId() == R.id.menu_find_employee) { Intent intent = new Intent("android.intent.action.MAIN"); intent .setComponent(ComponentName .unflattenFromString( "io.selendroid.directory/io.selendroid.directory.EmployeeDirectoy")); intent.addCategory("android.intent.category.LAUNCHER"); intent.setData(Uri.parse("http://selendroid.io/directory#employees/4")); startActivity(intent); return true; } else { return super.onOptionsItemSelected(item); } } private void initExceptionTestButton() { Button exceptionTestButton = (Button) findViewById(R.id.exceptionTestButton); exceptionTestButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { throw new RuntimeException("Unhandled Exception Test!"); } }); } private void initExceptionTestField() { EditText exceptionTestField = (EditText) findViewById(R.id.exceptionTestField); exceptionTestField.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable editable) { throw new RuntimeException("Unhandled Exception Test!"); } }); } }
/* * Created on Jul 1, 2004 */ package jeliot.historyview; import java.awt.BorderLayout; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Vector; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import jeliot.gui.CodePane2; import jeliot.mcode.Highlight; import jeliot.util.DebugUtil; import jeliot.util.Util; /** * @author nmyller */ public class HistoryView extends JComponent implements ActionListener { /** * Not currently used * Comment for <code>HISTORY_SIZE</code> */ private static final int HISTORY_SIZE = 10; /** * Not currently used * Comment for <code>LIMIT_HISTORY_SIZE</code> */ private static final boolean LIMIT_HISTORY_SIZE = true; /** * Comment for <code>images</code> */ private Vector imageFiles = new Vector(); /** * Comment for <code>highlights</code> */ private Vector highlights = new Vector(); /** * Comment for <code>buttonL</code> */ private final JButton buttonL = new JButton("<"); /** * Comment for <code>buttonR</code> */ private final JButton buttonR = new JButton(">"); /** * Comment for <code>slider</code> */ private JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 0, 0); /** * Comment for <code>ic</code> */ private ImageCanvas imageCanvas = new ImageCanvas(); /** * Comment for <code>codePane</code> */ private CodePane2 codePane; /** * Comment for <code>bottomComponent</code> */ private JPanel bottomComponent = new JPanel(new BorderLayout()); /** * Comment for <code>imageTemp</code> */ private File imageTemp; /** * Comment for <code>imageNumber</code> */ private int imageNumber; /** * Comment for <code>current</code> */ private BufferedImage current; /** * Comment for <code>newImageAdded</code> */ private boolean newImageAdded = false; /** * Comment for <code>enabled</code> */ private boolean enabled = false; /** * * @param c * @param udir */ public HistoryView(final CodePane2 c, String udir) { //TODO: add some of the literals below to a resourceBundle. this.codePane = c; File userPath = Util.createUserPath(); do { String dirName = "images" + System.currentTimeMillis(); imageTemp = new File(userPath, dirName); } while (imageTemp.exists()); imageTemp.mkdir(); initialize(); setLayout(new BorderLayout()); slider.setMajorTickSpacing(5); slider.setMinorTickSpacing(1); slider.setPaintTicks(true); slider.setPaintLabels(false); slider.setSnapToTicks(true); bottomComponent.add("Center", slider); bottomComponent.add("West", buttonL); bottomComponent.add("East", buttonR); add("Center", new JScrollPane(imageCanvas)); add("South", bottomComponent); buttonL.setEnabled(false); buttonR.setEnabled(false); buttonL.addActionListener(this); buttonR.addActionListener(this); buttonR.setMnemonic(KeyEvent.VK_GREATER); buttonL.setMnemonic(KeyEvent.VK_LESS); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { try { //previousImageNumber = imageNumber; imageNumber = slider.getValue(); if (imageNumber == slider.getMaximum()) { buttonR.setEnabled(false); } else { buttonR.setEnabled(true); } if (imageNumber == slider.getMinimum()) { buttonL.setEnabled(false); } else { buttonL.setEnabled(true); } if (imageNumber < imageFiles.size() && imageNumber >= 0) { if (newImageAdded) { imageCanvas.setImage(current); } else { try { current = ImageIO.read((File) imageFiles.get(imageNumber)); } catch (IOException e1) { //TODO: report to user that something went wrong! if (DebugUtil.DEBUGGING) { e1.printStackTrace(); } } imageCanvas.setImage(current); } } if (highlights.size() > imageNumber && highlights.get(imageNumber) != null) { if (HistoryView.this.isVisible()) { c.highlightStatement((Highlight) highlights.get(imageNumber)); } } newImageAdded = false; imageCanvas.repaint(); validate(); } catch (Exception e1) { if (DebugUtil.DEBUGGING) { e1.printStackTrace(); } } } }); } /** * */ public void initialize() { //next = null; //previous = null; current = null; imageFiles.removeAllElements(); highlights.removeAllElements(); imageCanvas.setImage(null); File[] files = imageTemp.listFiles(); int n = files.length; for (int i = 0; i < n; i++) { files[i].delete(); } slider.setEnabled(false); buttonL.setEnabled(false); buttonR.setEnabled(false); imageCanvas.repaint(); validate(); } public void close() { initialize(); imageTemp.delete(); } /** * @param i * @param h */ public void addImage(final Image i, final Highlight h) { if (enabled) { if (!slider.isEnabled()) { slider.setEnabled(true); } int size = imageFiles.size(); BufferedImage newImage = getBufferedImage(i); File imageFile = new File(imageTemp, "image" + size + ".png"); //TODO: This could be done in a thread to maybe increase the performance try { ImageIO.write(newImage, "png", imageFile); } catch (IOException e1) { //TODO: report to user that something went wrong! if (DebugUtil.DEBUGGING) { e1.printStackTrace(); } } imageFiles.add(imageFile); highlights.add(h); current = newImage; newImageAdded = true; size = imageFiles.size() - 1; slider.setMaximum(size); slider.setValue(size); } } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent arg0) { if (arg0.getSource().equals(buttonL)) { slider.setValue(slider.getValue() - 1); } else if (arg0.getSource().equals(buttonR)) { slider.setValue(slider.getValue() + 1); } } /** * * @param img * @return */ public static BufferedImage getBufferedImage(Image img) { // if the image is already a BufferedImage, cast and return it if ((img instanceof BufferedImage)) { return (BufferedImage) img; } // otherwise, create a new BufferedImage and draw the original // image on it int w = img.getWidth(null); int h = img.getHeight(null); BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = bi.createGraphics(); g2d.drawImage(img, 0, 0, w, h, null); g2d.dispose(); return bi; } /** * @return Returns the enabled. */ public boolean isEnabled() { return enabled; } /** * @param enabled The enabled to set. */ public void setEnabled(boolean enabled) { this.enabled = enabled; if (enabled) { initialize(); } } /** * @return Returns the imageCanvas. */ public ImageCanvas getImageCanvas() { return imageCanvas; } }
/* * Copyright 2010-2015 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.logs.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * Container for the parameters to the {@link com.amazonaws.services.logs.AWSLogs#putSubscriptionFilter(PutSubscriptionFilterRequest) PutSubscriptionFilter operation}. * <p> * Creates or updates a subscription filter and associates it with the * specified log group. Subscription filters allow you to subscribe to a * real-time stream of log events ingested through * <code>PutLogEvents</code> requests and have them delivered to a * specific destination. Currently, the supported destinations are: * <ul> * <li> A Amazon Kinesis stream belonging to the same account as the * subscription filter, for same-account delivery. </li> * <li> A logical destination (used via an ARN of * <code>Destination</code> ) belonging to a different account, for * cross-account delivery. </li> * * </ul> * * </p> * <p> * Currently there can only be one subscription filter associated with a * log group. * </p> * * @see com.amazonaws.services.logs.AWSLogs#putSubscriptionFilter(PutSubscriptionFilterRequest) */ public class PutSubscriptionFilterRequest extends AmazonWebServiceRequest implements Serializable, Cloneable { /** * The name of the log group to associate the subscription filter with. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 512<br/> * <b>Pattern: </b>[\.\-_/#A-Za-z0-9]+<br/> */ private String logGroupName; /** * A name for the subscription filter. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 512<br/> * <b>Pattern: </b>[^:*]*<br/> */ private String filterName; /** * A valid CloudWatch Logs filter pattern for subscribing to a filtered * stream of log events. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 512<br/> */ private String filterPattern; /** * The ARN of the destination to deliver matching log events to. * Currently, the supported destinations are: <ul> <li> A Amazon Kinesis * stream belonging to the same account as the subscription filter, for * same-account delivery. </li> <li> A logical destination (used via an * ARN of <code>Destination</code>) belonging to a different account, for * cross-account delivery. </li> </ul> * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> */ private String destinationArn; /** * The ARN of an IAM role that grants Amazon CloudWatch Logs permissions * to deliver ingested log events to the destination stream. You don't * need to provide the ARN when you are working with a logical * destination (used via an ARN of <code>Destination</code>) for * cross-account delivery. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> */ private String roleArn; /** * The name of the log group to associate the subscription filter with. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 512<br/> * <b>Pattern: </b>[\.\-_/#A-Za-z0-9]+<br/> * * @return The name of the log group to associate the subscription filter with. */ public String getLogGroupName() { return logGroupName; } /** * The name of the log group to associate the subscription filter with. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 512<br/> * <b>Pattern: </b>[\.\-_/#A-Za-z0-9]+<br/> * * @param logGroupName The name of the log group to associate the subscription filter with. */ public void setLogGroupName(String logGroupName) { this.logGroupName = logGroupName; } /** * The name of the log group to associate the subscription filter with. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 512<br/> * <b>Pattern: </b>[\.\-_/#A-Za-z0-9]+<br/> * * @param logGroupName The name of the log group to associate the subscription filter with. * * @return A reference to this updated object so that method calls can be chained * together. */ public PutSubscriptionFilterRequest withLogGroupName(String logGroupName) { this.logGroupName = logGroupName; return this; } /** * A name for the subscription filter. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 512<br/> * <b>Pattern: </b>[^:*]*<br/> * * @return A name for the subscription filter. */ public String getFilterName() { return filterName; } /** * A name for the subscription filter. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 512<br/> * <b>Pattern: </b>[^:*]*<br/> * * @param filterName A name for the subscription filter. */ public void setFilterName(String filterName) { this.filterName = filterName; } /** * A name for the subscription filter. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 512<br/> * <b>Pattern: </b>[^:*]*<br/> * * @param filterName A name for the subscription filter. * * @return A reference to this updated object so that method calls can be chained * together. */ public PutSubscriptionFilterRequest withFilterName(String filterName) { this.filterName = filterName; return this; } /** * A valid CloudWatch Logs filter pattern for subscribing to a filtered * stream of log events. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 512<br/> * * @return A valid CloudWatch Logs filter pattern for subscribing to a filtered * stream of log events. */ public String getFilterPattern() { return filterPattern; } /** * A valid CloudWatch Logs filter pattern for subscribing to a filtered * stream of log events. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 512<br/> * * @param filterPattern A valid CloudWatch Logs filter pattern for subscribing to a filtered * stream of log events. */ public void setFilterPattern(String filterPattern) { this.filterPattern = filterPattern; } /** * A valid CloudWatch Logs filter pattern for subscribing to a filtered * stream of log events. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 512<br/> * * @param filterPattern A valid CloudWatch Logs filter pattern for subscribing to a filtered * stream of log events. * * @return A reference to this updated object so that method calls can be chained * together. */ public PutSubscriptionFilterRequest withFilterPattern(String filterPattern) { this.filterPattern = filterPattern; return this; } /** * The ARN of the destination to deliver matching log events to. * Currently, the supported destinations are: <ul> <li> A Amazon Kinesis * stream belonging to the same account as the subscription filter, for * same-account delivery. </li> <li> A logical destination (used via an * ARN of <code>Destination</code>) belonging to a different account, for * cross-account delivery. </li> </ul> * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> * * @return The ARN of the destination to deliver matching log events to. * Currently, the supported destinations are: <ul> <li> A Amazon Kinesis * stream belonging to the same account as the subscription filter, for * same-account delivery. </li> <li> A logical destination (used via an * ARN of <code>Destination</code>) belonging to a different account, for * cross-account delivery. </li> </ul> */ public String getDestinationArn() { return destinationArn; } /** * The ARN of the destination to deliver matching log events to. * Currently, the supported destinations are: <ul> <li> A Amazon Kinesis * stream belonging to the same account as the subscription filter, for * same-account delivery. </li> <li> A logical destination (used via an * ARN of <code>Destination</code>) belonging to a different account, for * cross-account delivery. </li> </ul> * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> * * @param destinationArn The ARN of the destination to deliver matching log events to. * Currently, the supported destinations are: <ul> <li> A Amazon Kinesis * stream belonging to the same account as the subscription filter, for * same-account delivery. </li> <li> A logical destination (used via an * ARN of <code>Destination</code>) belonging to a different account, for * cross-account delivery. </li> </ul> */ public void setDestinationArn(String destinationArn) { this.destinationArn = destinationArn; } /** * The ARN of the destination to deliver matching log events to. * Currently, the supported destinations are: <ul> <li> A Amazon Kinesis * stream belonging to the same account as the subscription filter, for * same-account delivery. </li> <li> A logical destination (used via an * ARN of <code>Destination</code>) belonging to a different account, for * cross-account delivery. </li> </ul> * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> * * @param destinationArn The ARN of the destination to deliver matching log events to. * Currently, the supported destinations are: <ul> <li> A Amazon Kinesis * stream belonging to the same account as the subscription filter, for * same-account delivery. </li> <li> A logical destination (used via an * ARN of <code>Destination</code>) belonging to a different account, for * cross-account delivery. </li> </ul> * * @return A reference to this updated object so that method calls can be chained * together. */ public PutSubscriptionFilterRequest withDestinationArn(String destinationArn) { this.destinationArn = destinationArn; return this; } /** * The ARN of an IAM role that grants Amazon CloudWatch Logs permissions * to deliver ingested log events to the destination stream. You don't * need to provide the ARN when you are working with a logical * destination (used via an ARN of <code>Destination</code>) for * cross-account delivery. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> * * @return The ARN of an IAM role that grants Amazon CloudWatch Logs permissions * to deliver ingested log events to the destination stream. You don't * need to provide the ARN when you are working with a logical * destination (used via an ARN of <code>Destination</code>) for * cross-account delivery. */ public String getRoleArn() { return roleArn; } /** * The ARN of an IAM role that grants Amazon CloudWatch Logs permissions * to deliver ingested log events to the destination stream. You don't * need to provide the ARN when you are working with a logical * destination (used via an ARN of <code>Destination</code>) for * cross-account delivery. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> * * @param roleArn The ARN of an IAM role that grants Amazon CloudWatch Logs permissions * to deliver ingested log events to the destination stream. You don't * need to provide the ARN when you are working with a logical * destination (used via an ARN of <code>Destination</code>) for * cross-account delivery. */ public void setRoleArn(String roleArn) { this.roleArn = roleArn; } /** * The ARN of an IAM role that grants Amazon CloudWatch Logs permissions * to deliver ingested log events to the destination stream. You don't * need to provide the ARN when you are working with a logical * destination (used via an ARN of <code>Destination</code>) for * cross-account delivery. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - <br/> * * @param roleArn The ARN of an IAM role that grants Amazon CloudWatch Logs permissions * to deliver ingested log events to the destination stream. You don't * need to provide the ARN when you are working with a logical * destination (used via an ARN of <code>Destination</code>) for * cross-account delivery. * * @return A reference to this updated object so that method calls can be chained * together. */ public PutSubscriptionFilterRequest withRoleArn(String roleArn) { this.roleArn = roleArn; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getLogGroupName() != null) sb.append("LogGroupName: " + getLogGroupName() + ","); if (getFilterName() != null) sb.append("FilterName: " + getFilterName() + ","); if (getFilterPattern() != null) sb.append("FilterPattern: " + getFilterPattern() + ","); if (getDestinationArn() != null) sb.append("DestinationArn: " + getDestinationArn() + ","); if (getRoleArn() != null) sb.append("RoleArn: " + getRoleArn() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getLogGroupName() == null) ? 0 : getLogGroupName().hashCode()); hashCode = prime * hashCode + ((getFilterName() == null) ? 0 : getFilterName().hashCode()); hashCode = prime * hashCode + ((getFilterPattern() == null) ? 0 : getFilterPattern().hashCode()); hashCode = prime * hashCode + ((getDestinationArn() == null) ? 0 : getDestinationArn().hashCode()); hashCode = prime * hashCode + ((getRoleArn() == null) ? 0 : getRoleArn().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PutSubscriptionFilterRequest == false) return false; PutSubscriptionFilterRequest other = (PutSubscriptionFilterRequest)obj; if (other.getLogGroupName() == null ^ this.getLogGroupName() == null) return false; if (other.getLogGroupName() != null && other.getLogGroupName().equals(this.getLogGroupName()) == false) return false; if (other.getFilterName() == null ^ this.getFilterName() == null) return false; if (other.getFilterName() != null && other.getFilterName().equals(this.getFilterName()) == false) return false; if (other.getFilterPattern() == null ^ this.getFilterPattern() == null) return false; if (other.getFilterPattern() != null && other.getFilterPattern().equals(this.getFilterPattern()) == false) return false; if (other.getDestinationArn() == null ^ this.getDestinationArn() == null) return false; if (other.getDestinationArn() != null && other.getDestinationArn().equals(this.getDestinationArn()) == false) return false; if (other.getRoleArn() == null ^ this.getRoleArn() == null) return false; if (other.getRoleArn() != null && other.getRoleArn().equals(this.getRoleArn()) == false) return false; return true; } @Override public PutSubscriptionFilterRequest clone() { return (PutSubscriptionFilterRequest) super.clone(); } }
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI 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 net.sf.farrago.query; import java.util.*; import net.sf.farrago.cwm.behavioral.*; import net.sf.farrago.fem.security.*; import net.sf.farrago.fem.sql2003.*; import org.eigenbase.reltype.*; import org.eigenbase.resgen.*; import org.eigenbase.sql.*; import org.eigenbase.sql.parser.*; import org.eigenbase.sql.type.*; import org.eigenbase.sql.validate.*; import org.eigenbase.util.*; /** * FarragoSqlValidator refines SqlValidator with some Farrago-specifics. * * @author John V. Sichi * @version $Id$ */ public class FarragoSqlValidator extends SqlValidatorImpl { //~ Instance fields -------------------------------------------------------- final FarragoPreparingStmt preparingStmt; //~ Constructors ----------------------------------------------------------- /** * Constructor that allows caller to specify dependant objects rather than * relying on the preparingStmt to supply them. This constructor is is * friendlier to class extension as well as providing more control during * test setup. */ public FarragoSqlValidator( SqlOperatorTable opTab, SqlValidatorCatalogReader catalogReader, RelDataTypeFactory typeFactory, SqlConformance conformance, FarragoPreparingStmt preparingStmt) { super( opTab, catalogReader, typeFactory, conformance); this.preparingStmt = preparingStmt; } /** * Constructor that relies on the preparingStmt object to provide various * other objects during initialization. */ public FarragoSqlValidator( FarragoPreparingStmt preparingStmt, SqlConformance conformance) { super( preparingStmt.getSqlOperatorTable(), preparingStmt, preparingStmt.getFarragoTypeFactory(), conformance); this.preparingStmt = preparingStmt; } //~ Methods ---------------------------------------------------------------- // override SqlValidator public SqlNode validate(SqlNode topNode) { try { SqlNode node = super.validate(topNode); getPreparingStmt().analyzeRoutineDependencies(node); return node; } catch (EigenbaseContextException e) { e.setOriginalStatement(preparingStmt.getSql()); throw e; } } // override SqlValidator public boolean shouldExpandIdentifiers() { // Farrago always wants to expand stars and identifiers during // validation since we use the validated representation as a canonical // form. return true; } // override SqlValidator protected boolean shouldAllowIntermediateOrderBy() { // Farrago follows the SQL standard on this. return false; } public void validateDataType(SqlDataTypeSpec dataType) { super.validateDataType(dataType); FarragoPreparingStmt preparingStmt = getPreparingStmt(); try { preparingStmt.getStmtValidator().validateDataType(dataType); } catch (SqlValidatorException ex) { throw newValidationError(dataType, ex); } } protected FarragoPreparingStmt getPreparingStmt() { return preparingStmt; } // override SqlValidatorImpl public void validateInsert(SqlInsert call) { getPreparingStmt().setDmlValidation( call.getTargetTable(), PrivilegedActionEnum.INSERT); super.validateInsert(call); getPreparingStmt().clearDmlValidation(); } // override SqlValidatorImpl public void validateUpdate(SqlUpdate call) { getPreparingStmt().setDmlValidation( call.getTargetTable(), PrivilegedActionEnum.UPDATE); super.validateUpdate(call); getPreparingStmt().clearDmlValidation(); } // override SqlValidatorImpl public void validateDelete(SqlDelete call) { getPreparingStmt().setDmlValidation( call.getTargetTable(), PrivilegedActionEnum.DELETE); super.validateDelete(call); getPreparingStmt().clearDmlValidation(); } // override SqlValidatorImpl public void validateMerge(SqlMerge call) { getPreparingStmt().setDmlValidation( call.getTargetTable(), PrivilegedActionEnum.UPDATE); super.validateMerge(call); getPreparingStmt().clearDmlValidation(); } // override SqlValidatorImpl protected void validateFeature( ResourceDefinition feature, SqlParserPos context) { super.validateFeature(feature, context); getPreparingStmt().getStmtValidator().validateFeature( feature, context); } // override SqlValidatorImpl public void validateColumnListParams( SqlFunction function, RelDataType [] argTypes, SqlNode [] operands) { // get the UDR that the function corresponds to FarragoUserDefinedRoutine routine = (FarragoUserDefinedRoutine) function; FemRoutine femRoutine = routine.getFemRoutine(); List<CwmParameter> params = femRoutine.getParameter(); FunctionParamInfo funcParamInfo = functionCallStack.peek(); Map<Integer, SqlSelect> cursorMap = funcParamInfo.cursorPosToSelectMap; Map<String, String> parentCursorMap = funcParamInfo.columnListParamToParentCursorMap; // locate arguments that are COLUMN_LIST types; locate the select // scope corresponding to the source cursor and revalidate the // function operand using that scope for (int i = 0; i < argTypes.length; i++) { if (argTypes[i].getSqlTypeName() == SqlTypeName.COLUMN_LIST) { FemColumnListRoutineParameter clParam = (FemColumnListRoutineParameter) params.get(i); String sourceCursor = clParam.getSourceCursorName(); int cursorPosition = -1; for ( FemRoutineParameter p : Util.cast(params, FemRoutineParameter.class)) { if (p.getType().getName().equals("CURSOR")) { cursorPosition++; if (p.getName().equals(sourceCursor)) { SqlSelect sourceSelect = cursorMap.get(cursorPosition); SqlValidatorScope cursorScope = getCursorScope(sourceSelect); // save the original node type so we can reset it // after we've validated the column references RelDataType origNodeType = getValidatedNodeType(operands[i]); removeValidatedNodeType(operands[i]); deriveType(cursorScope, operands[i]); setValidatedNodeType(operands[i], origNodeType); parentCursorMap.put( clParam.getName(), sourceCursor); break; } } } } } } } // End FarragoSqlValidator.java
package com.redhat.ceylon.compiler.typechecker.analyzer; import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.buildAnnotations; import static com.redhat.ceylon.compiler.typechecker.tree.Util.formatPath; import static com.redhat.ceylon.compiler.typechecker.tree.Util.hasAnnotation; import static com.redhat.ceylon.compiler.typechecker.tree.Util.name; import static java.util.Arrays.asList; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.ModuleImport; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ImportPath; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; /** * Detect and populate the list of imports for modules. * In theory should only be called on module.ceylon and * package.ceylon files * * Put restrictions on how module.ceylon files are built today: * - names and versions must be string literals or else the * visitor cannot extract them * - imports must be "explicitly" defined, ie not imported as * List<Import> or else the module names cannot be extracted * * @author Emmanuel Bernard <emmanuel@hibernate.org> */ public class ModuleVisitor extends Visitor { /** * Instance of the visited module which will receive * the dependencies declaration */ private Module mainModule; private final ModuleManager moduleManager; private final Package pkg; private Tree.CompilationUnit unit; private Phase phase = Phase.SRC_MODULE; private boolean completeOnlyAST = false; public void setCompleteOnlyAST(boolean completeOnlyAST) { this.completeOnlyAST = completeOnlyAST; } public boolean isCompleteOnlyAST() { return completeOnlyAST; } public ModuleVisitor(ModuleManager moduleManager, Package pkg) { this.moduleManager = moduleManager; this.pkg = pkg; } public void setPhase(Phase phase) { this.phase = phase; } @Override public void visit(Tree.CompilationUnit that) { unit = that; super.visit(that); } private static String getVersionString(Tree.QuotedLiteral quoted) { if (quoted==null) { return null; } else { String versionString = quoted.getText(); if (versionString.length()<2) { return ""; } else { if (versionString.charAt(0)=='\'') { quoted.addError("version should be double-quoted"); } return versionString.substring(1, versionString.length()-1); } } } private static String getNameString(Tree.QuotedLiteral quoted) { String nameString = quoted.getText(); if (nameString.length()<2) { return ""; } else { if (nameString.charAt(0)=='\'') { quoted.addError("module name should be double-quoted"); } return nameString.substring(1, nameString.length()-1); } } @Override public void visit(Tree.ModuleDescriptor that) { super.visit(that); if (phase==Phase.SRC_MODULE) { String version = getVersionString(that.getVersion()); ImportPath importPath = that.getImportPath(); List<String> name = getNameAsList(importPath); if (pkg.getNameAsString().isEmpty()) { that.addError("module descriptor encountered in root source directory"); } else if (name.isEmpty()) { that.addError("missing module name"); } else if (name.get(0).equals(Module.DEFAULT_MODULE_NAME)) { importPath.addError("reserved module name: default"); } else if (name.size()==1 && name.get(0).equals("ceylon")) { importPath.addError("reserved module name: ceylon"); } else { if (name.get(0).equals("ceylon")) { importPath.addUsageWarning("discouraged module name: this namespace is used by Ceylon platform modules"); } else if (name.get(0).equals("java")||name.get(0).equals("javax")) { importPath.addUsageWarning("discouraged module name: this namespace is used by Java platform modules"); } mainModule = moduleManager.getOrCreateModule(name, version); importPath.setModel(mainModule); if (!completeOnlyAST) { mainModule.setUnit(unit.getUnit()); mainModule.setVersion(version); } String nameString = formatPath(importPath.getIdentifiers()); if ( !pkg.getNameAsString().equals(nameString) ) { importPath .addError("module name does not match descriptor location: " + nameString + " should be " + pkg.getNameAsString(), 8000); } if (!completeOnlyAST) { moduleManager.addLinkBetweenModuleAndNode(mainModule, that); mainModule.setAvailable(true); buildAnnotations(that.getAnnotationList(), mainModule.getAnnotations()); } } HashSet<String> set = new HashSet<String>(); Tree.ImportModuleList iml = that.getImportModuleList(); if (iml!=null) { for (Tree.ImportModule im: iml.getImportModules()) { Tree.ImportPath ip = im.getImportPath(); if (ip!=null) { String mp = formatPath(ip.getIdentifiers()); if (!set.add(mp)) { ip.addError("duplicate module import: " + mp); } } } } } } @Override public void visit(Tree.PackageDescriptor that) { super.visit(that); if (phase==Phase.REMAINING) { Tree.ImportPath importPath = that.getImportPath(); List<String> name = getNameAsList(importPath); if (pkg.getNameAsString().isEmpty()) { that.addError("package descriptor encountered in root source directory"); } else if (name.isEmpty()) { that.addError("missing package name"); } else if (name.get(0).equals(Module.DEFAULT_MODULE_NAME)) { importPath.addError("reserved module name: default"); } else if (name.size()==1 && name.get(0).equals("ceylon")) { importPath.addError("reserved module name: ceylon"); } else { if (name.get(0).equals("ceylon")) { importPath.addUsageWarning("discouraged package name: this namespace is used by Ceylon platform modules"); } else if (name.get(0).equals("java")||name.get(0).equals("javax")) { importPath.addUsageWarning("discouraged package name: this namespace is used by Java platform modules"); } importPath.setModel(pkg); if (!completeOnlyAST) { pkg.setUnit(unit.getUnit()); } String nameString = formatPath(importPath.getIdentifiers()); if ( !pkg.getNameAsString().equals(nameString) ) { importPath .addError("package name does not match descriptor location: " + nameString + " should be " + pkg.getNameAsString(), 8000); } if (!completeOnlyAST) { if (hasAnnotation(that.getAnnotationList(), "shared", unit.getUnit())) { pkg.setShared(true); } else { pkg.setShared(false); } buildAnnotations(that.getAnnotationList(), pkg.getAnnotations()); } } } } @Override public void visit(Tree.ImportModule that) { super.visit(that); if (phase==Phase.REMAINING) { if (that.getVersion()==null) { that.addError("missing module version"); } String version = getVersionString(that.getVersion()); List<String> name; Node node; if (that.getImportPath()!=null) { name = getNameAsList(that.getImportPath()); node = that.getImportPath(); } else if (that.getQuotedLiteral()!=null) { String nameString = getNameString(that.getQuotedLiteral()); name = asList(nameString.split("\\.")); node = that.getQuotedLiteral(); } else { name = Collections.emptyList(); node = null; } if (name.isEmpty()) { that.addError("missing module name"); } else if (name.get(0).equals(Module.DEFAULT_MODULE_NAME)) { if (that.getImportPath()!=null) { node.addError("reserved module name: default"); } } else if (name.size()==1 && name.get(0).equals("ceylon")) { if (that.getImportPath()!=null) { node.addError("reserved module name: ceylon"); } } else if (name.size()>1 && name.get(0).equals("ceylon") && name.get(1).equals("language")) { if (that.getImportPath()!=null) { node.addError("the language module is imported implicitly"); } } else { Module importedModule = moduleManager.getOrCreateModule(name,version); if (that.getImportPath()!=null) { that.getImportPath().setModel(importedModule); } if (!completeOnlyAST) { if (mainModule != null) { if (importedModule.getVersion() == null) { importedModule.setVersion(version); } ModuleImport moduleImport = moduleManager.findImport(mainModule, importedModule); if (moduleImport == null) { Tree.AnnotationList al = that.getAnnotationList(); boolean optional = hasAnnotation(al, "optional", unit.getUnit()); boolean export = hasAnnotation(al, "shared", unit.getUnit()); moduleImport = new ModuleImport(importedModule, optional, export); buildAnnotations(al, moduleImport.getAnnotations()); mainModule.addImport(moduleImport); } moduleManager.addModuleDependencyDefinition(moduleImport, that); } } } } } private List<String> getNameAsList(Tree.ImportPath that) { List<String> name = new ArrayList<String>(); for (Tree.Identifier i: that.getIdentifiers()) { name.add(i.getText()); } return name; } public enum Phase { SRC_MODULE, REMAINING } public Module getMainModule() { return mainModule; } @Override public void visit(Tree.Import that) { super.visit(that); Tree.ImportPath path = that.getImportPath(); if (path!=null && formatPath(path.getIdentifiers()).equals(Module.LANGUAGE_MODULE_NAME)) { Tree.ImportMemberOrTypeList imtl = that.getImportMemberOrTypeList(); if (imtl!=null) { for (Tree.ImportMemberOrType imt: imtl.getImportMemberOrTypes()) { if (imt.getAlias()!=null && imt.getIdentifier()!=null) { String name = name(imt.getIdentifier()); String alias = name(imt.getAlias().getIdentifier()); Map<String, String> mods = unit.getUnit().getModifiers(); if (mods.containsKey(name)) { mods.put(name, alias); } } } } } } }
/* * Copyright (C) 2012-2017 DataStax 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.datastax.driver.core; import com.google.common.collect.Lists; import org.scassandra.http.client.PreparedStatementPreparation; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.List; import java.util.concurrent.TimeUnit; import static com.datastax.driver.core.Assertions.assertThat; import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; public class QueryOptionsTest { ScassandraCluster scassandra; QueryOptions queryOptions; SortingLoadBalancingPolicy loadBalancingPolicy; Cluster cluster = null; Session session = null; Host host1, host2, host3; @BeforeMethod(groups = "short") public void beforeMethod() { scassandra = ScassandraCluster.builder().withNodes(3).build(); scassandra.init(); queryOptions = new QueryOptions(); loadBalancingPolicy = new SortingLoadBalancingPolicy(); cluster = Cluster.builder() .addContactPoints(scassandra.address(2).getAddress()) .withPort(scassandra.getBinaryPort()) .withLoadBalancingPolicy(loadBalancingPolicy) .withQueryOptions(queryOptions) .withNettyOptions(nonQuietClusterCloseOptions) .build(); session = cluster.connect(); host1 = TestUtils.findHost(cluster, 1); host2 = TestUtils.findHost(cluster, 2); host3 = TestUtils.findHost(cluster, 3); // Make sure there are no prepares for (int host : Lists.newArrayList(1, 2, 3)) { assertThat(scassandra.node(host).activityClient().retrievePreparedStatementPreparations()).hasSize(0); scassandra.node(host).activityClient().clearAllRecordedActivity(); } } public void validatePrepared(boolean expectAll) { // Prepare the statement String query = "select sansa_stark from the_known_world"; PreparedStatement statement = session.prepare(query); assertThat(cluster.manager.preparedQueries).containsValue(statement); // Ensure prepared properly based on expectation. List<PreparedStatementPreparation> preparationOne = scassandra.node(1).activityClient().retrievePreparedStatementPreparations(); List<PreparedStatementPreparation> preparationTwo = scassandra.node(2).activityClient().retrievePreparedStatementPreparations(); List<PreparedStatementPreparation> preparationThree = scassandra.node(3).activityClient().retrievePreparedStatementPreparations(); assertThat(preparationOne).hasSize(1); assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query); if (expectAll) { assertThat(preparationTwo).hasSize(1); assertThat(preparationTwo.get(0).getPreparedStatementText()).isEqualTo(query); assertThat(preparationThree).hasSize(1); assertThat(preparationThree.get(0).getPreparedStatementText()).isEqualTo(query); } else { assertThat(preparationTwo).isEmpty(); assertThat(preparationThree).isEmpty(); } } /** * <p> * Validates that statements are only prepared on one node when * {@link QueryOptions#setPrepareOnAllHosts(boolean)} is set to false. * </p> * * @test_category prepared_statements:prepared * @expected_result prepare query only on the first node. * @jira_ticket JAVA-797 * @since 2.0.11, 2.1.8, 2.2.1 */ @Test(groups = "short") public void should_prepare_once_when_prepare_on_all_hosts_false() { queryOptions.setPrepareOnAllHosts(false); validatePrepared(false); } /** * <p> * Validates that statements are prepared on one node when * {@link QueryOptions#setPrepareOnAllHosts(boolean)} is set to true. * </p> * * @test_category prepared_statements:prepared * @expected_result all nodes prepared the query * @jira_ticket JAVA-797 * @since 2.0.11, 2.1.8, 2.2.1 */ @Test(groups = "short") public void should_prepare_everywhere_when_prepare_on_all_hosts_true() { queryOptions.setPrepareOnAllHosts(true); validatePrepared(true); } /** * <p> * Validates that statements are prepared on one node when * {@link QueryOptions#setPrepareOnAllHosts(boolean)} is not set. * </p> * * @test_category prepared_statements:prepared * @expected_result all nodes prepared the query. * @jira_ticket JAVA-797 * @since 2.0.11 */ @Test(groups = "short") public void should_prepare_everywhere_when_not_configured() { validatePrepared(true); } private void valideReprepareOnUp(boolean expectReprepare) { String query = "select sansa_stark from the_known_world"; int maxTries = 3; for (int i = 1; i <= maxTries; i++) { session.prepare(query); List<PreparedStatementPreparation> preparationOne = scassandra.node(1).activityClient().retrievePreparedStatementPreparations(); assertThat(preparationOne).hasSize(1); assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query); scassandra.node(1).activityClient().clearAllRecordedActivity(); scassandra.node(1).stop(); assertThat(cluster).host(1).goesDownWithin(10, TimeUnit.SECONDS); scassandra.node(1).start(); assertThat(cluster).host(1).comesUpWithin(60, TimeUnit.SECONDS); preparationOne = scassandra.node(1).activityClient().retrievePreparedStatementPreparations(); if (expectReprepare) { // tests fail randomly at this point, probably due to // https://github.com/scassandra/scassandra-server/issues/116 try { assertThat(preparationOne).hasSize(1); assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query); break; } catch (AssertionError e) { if (i == maxTries) throw e; // retry scassandra.node(1).activityClient().clearAllRecordedActivity(); } } else { assertThat(preparationOne).isEmpty(); break; } } } /** * <p> * Validates that statements are reprepared when a node comes back up when * {@link QueryOptions#setReprepareOnUp(boolean)} is set to true. * </p> * * @test_category prepared_statements:prepared * @expected_result reprepare query on the restarted node. * @jira_ticket JAVA-658 * @since 2.0.11, 2.1.8, 2.2.1 */ @Test(groups = "short") public void should_reprepare_on_up_when_enabled() { queryOptions.setReprepareOnUp(true); valideReprepareOnUp(true); } /** * <p> * Validates that statements are reprepared when a node comes back up with * the default configuration. * </p> * * @test_category prepared_statements:prepared * @expected_result reprepare query on the restarted node. * @jira_ticket JAVA-658 * @since 2.0.11, 2.1.8, 2.2.1 */ @Test(groups = "short") public void should_reprepare_on_up_by_default() { valideReprepareOnUp(true); } /** * <p> * Validates that statements are not reprepared when a node comes back up when * {@link QueryOptions#setReprepareOnUp(boolean)} is set to false. * </p> * * @test_category prepared_statements:prepared * @expected_result do not reprepare query on the restarted node. * @jira_ticket JAVA-658 * @since 2.0.11, 2.1.8, 2.2.1 */ @Test(groups = "short") public void should_not_reprepare_on_up_when_disabled() { queryOptions.setReprepareOnUp(false); valideReprepareOnUp(false); } @AfterMethod(groups = "short", alwaysRun = true) public void afterMethod() { if (cluster != null) cluster.close(); if (scassandra != null) scassandra.stop(); } }
/* * Copyright (C) 2011 Jake Wharton * Copyright (C) 2011 Patrik Akerfeldt * Copyright (C) 2011 Francisco Figueiredo Jr. * * 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 viewpagerindicator; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.*; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewConfigurationCompat; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import com.viewpagerindicator.R; import java.util.ArrayList; /** * A TitlePageIndicator is a PageIndicator which displays the title of left view * (if exist), the title of the current select view (centered) and the title of * the right view (if exist). When the user scrolls the ViewPager then titles are * also scrolled. */ public class TitlePageIndicator extends View implements PageIndicator { /** * Percentage indicating what percentage of the screen width away from * center should the underline be fully faded. A value of 0.25 means that * halfway between the center of the screen and an edge. */ private static final float SELECTION_FADE_PERCENTAGE = 0.25f; /** * Percentage indicating what percentage of the screen width away from * center should the selected text bold turn off. A value of 0.05 means * that 10% between the center and an edge. */ private static final float BOLD_FADE_PERCENTAGE = 0.05f; /** * Title text used when no title is provided by the adapter. */ private static final String EMPTY_TITLE = ""; /** * Interface for a callback when the center item has been clicked. */ public interface OnCenterItemClickListener { /** * Callback when the center item has been clicked. * * @param position Position of the current center item. */ void onCenterItemClick(int position); } public enum IndicatorStyle { None(0), Triangle(1), Underline(2); public final int value; private IndicatorStyle(int value) { this.value = value; } public static IndicatorStyle fromValue(int value) { for (IndicatorStyle style : IndicatorStyle.values()) { if (style.value == value) { return style; } } return null; } } public enum LinePosition { Bottom(0), Top(1); public final int value; private LinePosition(int value) { this.value = value; } public static LinePosition fromValue(int value) { for (LinePosition position : LinePosition.values()) { if (position.value == value) { return position; } } return null; } } private ViewPager mViewPager; private ViewPager.OnPageChangeListener mListener; private int mCurrentPage = -1; private float mPageOffset; private int mScrollState; private final Paint mPaintText = new Paint(); private boolean mBoldText; private int mColorText; private int mColorSelected; private Path mPath = new Path(); private final Rect mBounds = new Rect(); private final Paint mPaintFooterLine = new Paint(); private IndicatorStyle mFooterIndicatorStyle; private LinePosition mLinePosition; private final Paint mPaintFooterIndicator = new Paint(); private float mFooterIndicatorHeight; private float mFooterIndicatorUnderlinePadding; private float mFooterPadding; private float mTitlePadding; private float mTopPadding; /** Left and right side padding for not active view titles. */ private float mClipPadding; private float mFooterLineHeight; private static final int INVALID_POINTER = -1; private int mTouchSlop; private float mLastMotionX = -1; private int mActivePointerId = INVALID_POINTER; private boolean mIsDragging; private OnCenterItemClickListener mCenterItemClickListener; public TitlePageIndicator(Context context) { this(context, null); } public TitlePageIndicator(Context context, AttributeSet attrs) { this(context, attrs, R.attr.vpiTitlePageIndicatorStyle); } public TitlePageIndicator(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (isInEditMode()) return; //Load defaults from resources final Resources res = getResources(); final int defaultFooterColor = res.getColor(R.color.default_title_indicator_footer_color); final float defaultFooterLineHeight = res.getDimension(R.dimen.default_title_indicator_footer_line_height); final int defaultFooterIndicatorStyle = res.getInteger(R.integer.default_title_indicator_footer_indicator_style); final float defaultFooterIndicatorHeight = res.getDimension(R.dimen.default_title_indicator_footer_indicator_height); final float defaultFooterIndicatorUnderlinePadding = res.getDimension(R.dimen.default_title_indicator_footer_indicator_underline_padding); final float defaultFooterPadding = res.getDimension(R.dimen.default_title_indicator_footer_padding); final int defaultLinePosition = res.getInteger(R.integer.default_title_indicator_line_position); final int defaultSelectedColor = res.getColor(R.color.default_title_indicator_selected_color); final boolean defaultSelectedBold = res.getBoolean(R.bool.default_title_indicator_selected_bold); final int defaultTextColor = res.getColor(R.color.default_title_indicator_text_color); final float defaultTextSize = res.getDimension(R.dimen.default_title_indicator_text_size); final float defaultTitlePadding = res.getDimension(R.dimen.default_title_indicator_title_padding); final float defaultClipPadding = res.getDimension(R.dimen.default_title_indicator_clip_padding); final float defaultTopPadding = res.getDimension(R.dimen.default_title_indicator_top_padding); //Retrieve styles attributes TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TitlePageIndicator, defStyle, 0); //Retrieve the colors to be used for this view and apply them. mFooterLineHeight = a.getDimension(R.styleable.TitlePageIndicator_footerLineHeight, defaultFooterLineHeight); mFooterIndicatorStyle = IndicatorStyle.fromValue(a.getInteger(R.styleable.TitlePageIndicator_footerIndicatorStyle, defaultFooterIndicatorStyle)); mFooterIndicatorHeight = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorHeight, defaultFooterIndicatorHeight); mFooterIndicatorUnderlinePadding = a.getDimension(R.styleable.TitlePageIndicator_footerIndicatorUnderlinePadding, defaultFooterIndicatorUnderlinePadding); mFooterPadding = a.getDimension(R.styleable.TitlePageIndicator_footerPadding, defaultFooterPadding); mLinePosition = LinePosition.fromValue(a.getInteger(R.styleable.TitlePageIndicator_linePosition, defaultLinePosition)); mTopPadding = a.getDimension(R.styleable.TitlePageIndicator_topPadding, defaultTopPadding); mTitlePadding = a.getDimension(R.styleable.TitlePageIndicator_titlePadding, defaultTitlePadding); mClipPadding = a.getDimension(R.styleable.TitlePageIndicator_clipPadding, defaultClipPadding); mColorSelected = a.getColor(R.styleable.TitlePageIndicator_selectedColor, defaultSelectedColor); mColorText = a.getColor(R.styleable.TitlePageIndicator_android_textColor, defaultTextColor); mBoldText = a.getBoolean(R.styleable.TitlePageIndicator_selectedBold, defaultSelectedBold); final float textSize = a.getDimension(R.styleable.TitlePageIndicator_android_textSize, defaultTextSize); final int footerColor = a.getColor(R.styleable.TitlePageIndicator_footerColor, defaultFooterColor); mPaintText.setTextSize(textSize); mPaintText.setAntiAlias(true); mPaintFooterLine.setStyle(Paint.Style.FILL_AND_STROKE); mPaintFooterLine.setStrokeWidth(mFooterLineHeight); mPaintFooterLine.setColor(footerColor); mPaintFooterIndicator.setStyle(Paint.Style.FILL_AND_STROKE); mPaintFooterIndicator.setColor(footerColor); Drawable background = a.getDrawable(R.styleable.TitlePageIndicator_android_background); if (background != null) { setBackgroundDrawable(background); } a.recycle(); final ViewConfiguration configuration = ViewConfiguration.get(context); mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); } public int getFooterColor() { return mPaintFooterLine.getColor(); } public void setFooterColor(int footerColor) { mPaintFooterLine.setColor(footerColor); mPaintFooterIndicator.setColor(footerColor); invalidate(); } public float getFooterLineHeight() { return mFooterLineHeight; } public void setFooterLineHeight(float footerLineHeight) { mFooterLineHeight = footerLineHeight; mPaintFooterLine.setStrokeWidth(mFooterLineHeight); invalidate(); } public float getFooterIndicatorHeight() { return mFooterIndicatorHeight; } public void setFooterIndicatorHeight(float footerTriangleHeight) { mFooterIndicatorHeight = footerTriangleHeight; invalidate(); } public float getFooterIndicatorPadding() { return mFooterPadding; } public void setFooterIndicatorPadding(float footerIndicatorPadding) { mFooterPadding = footerIndicatorPadding; invalidate(); } public IndicatorStyle getFooterIndicatorStyle() { return mFooterIndicatorStyle; } public void setFooterIndicatorStyle(IndicatorStyle indicatorStyle) { mFooterIndicatorStyle = indicatorStyle; invalidate(); } public LinePosition getLinePosition() { return mLinePosition; } public void setLinePosition(LinePosition linePosition) { mLinePosition = linePosition; invalidate(); } public int getSelectedColor() { return mColorSelected; } public void setSelectedColor(int selectedColor) { mColorSelected = selectedColor; invalidate(); } public boolean isSelectedBold() { return mBoldText; } public void setSelectedBold(boolean selectedBold) { mBoldText = selectedBold; invalidate(); } public int getTextColor() { return mColorText; } public void setTextColor(int textColor) { mPaintText.setColor(textColor); mColorText = textColor; invalidate(); } public float getTextSize() { return mPaintText.getTextSize(); } public void setTextSize(float textSize) { mPaintText.setTextSize(textSize); invalidate(); } public float getTitlePadding() { return this.mTitlePadding; } public void setTitlePadding(float titlePadding) { mTitlePadding = titlePadding; invalidate(); } public float getTopPadding() { return this.mTopPadding; } public void setTopPadding(float topPadding) { mTopPadding = topPadding; invalidate(); } public float getClipPadding() { return this.mClipPadding; } public void setClipPadding(float clipPadding) { mClipPadding = clipPadding; invalidate(); } public void setTypeface(Typeface typeface) { mPaintText.setTypeface(typeface); invalidate(); } public Typeface getTypeface() { return mPaintText.getTypeface(); } /* * (non-Javadoc) * * @see android.view.View#onDraw(android.graphics.Canvas) */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mViewPager == null) { return; } final int count = mViewPager.getAdapter().getCount(); if (count == 0) { return; } // mCurrentPage is -1 on first start and after orientation changed. If so, retrieve the correct index from viewpager. if (mCurrentPage == -1 && mViewPager != null) { mCurrentPage = mViewPager.getCurrentItem(); } //Calculate views bounds ArrayList<Rect> bounds = calculateAllBounds(mPaintText); final int boundsSize = bounds.size(); //Make sure we're on a page that still exists if (mCurrentPage >= boundsSize) { setCurrentItem(boundsSize - 1); return; } final int countMinusOne = count - 1; final float halfWidth = getWidth() / 2f; final int left = getLeft(); final float leftClip = left + mClipPadding; final int width = getWidth(); int height = getHeight(); final int right = left + width; final float rightClip = right - mClipPadding; int page = mCurrentPage; float offsetPercent; if (mPageOffset <= 0.5) { offsetPercent = mPageOffset; } else { page += 1; offsetPercent = 1 - mPageOffset; } final boolean currentSelected = (offsetPercent <= SELECTION_FADE_PERCENTAGE); final boolean currentBold = (offsetPercent <= BOLD_FADE_PERCENTAGE); final float selectedPercent = (SELECTION_FADE_PERCENTAGE - offsetPercent) / SELECTION_FADE_PERCENTAGE; //Verify if the current view must be clipped to the screen Rect curPageBound = bounds.get(mCurrentPage); float curPageWidth = curPageBound.right - curPageBound.left; if (curPageBound.left < leftClip) { //Try to clip to the screen (left side) clipViewOnTheLeft(curPageBound, curPageWidth, left); } if (curPageBound.right > rightClip) { //Try to clip to the screen (right side) clipViewOnTheRight(curPageBound, curPageWidth, right); } //Left views starting from the current position if (mCurrentPage > 0) { for (int i = mCurrentPage - 1; i >= 0; i--) { Rect bound = bounds.get(i); //Is left side is outside the screen if (bound.left < leftClip) { int w = bound.right - bound.left; //Try to clip to the screen (left side) clipViewOnTheLeft(bound, w, left); //Except if there's an intersection with the right view Rect rightBound = bounds.get(i + 1); //Intersection if (bound.right + mTitlePadding > rightBound.left) { bound.left = (int) (rightBound.left - w - mTitlePadding); bound.right = bound.left + w; } } } } //Right views starting from the current position if (mCurrentPage < countMinusOne) { for (int i = mCurrentPage + 1 ; i < count; i++) { Rect bound = bounds.get(i); //If right side is outside the screen if (bound.right > rightClip) { int w = bound.right - bound.left; //Try to clip to the screen (right side) clipViewOnTheRight(bound, w, right); //Except if there's an intersection with the left view Rect leftBound = bounds.get(i - 1); //Intersection if (bound.left - mTitlePadding < leftBound.right) { bound.left = (int) (leftBound.right + mTitlePadding); bound.right = bound.left + w; } } } } //Now draw views int colorTextAlpha = mColorText >>> 24; for (int i = 0; i < count; i++) { //Get the title Rect bound = bounds.get(i); //Only if one side is visible if ((bound.left > left && bound.left < right) || (bound.right > left && bound.right < right)) { final boolean currentPage = (i == page); final CharSequence pageTitle = getTitle(i); //Only set bold if we are within bounds mPaintText.setFakeBoldText(currentPage && currentBold && mBoldText); //Draw text as unselected mPaintText.setColor(mColorText); if(currentPage && currentSelected) { //Fade out/in unselected text as the selected text fades in/out mPaintText.setAlpha(colorTextAlpha - (int)(colorTextAlpha * selectedPercent)); } //Except if there's an intersection with the right view if (i < boundsSize - 1) { Rect rightBound = bounds.get(i + 1); //Intersection if (bound.right + mTitlePadding > rightBound.left) { int w = bound.right - bound.left; bound.left = (int) (rightBound.left - w - mTitlePadding); bound.right = bound.left + w; } } canvas.drawText(pageTitle, 0, pageTitle.length(), bound.left, bound.bottom + mTopPadding, mPaintText); //If we are within the selected bounds draw the selected text if (currentPage && currentSelected) { mPaintText.setColor(mColorSelected); mPaintText.setAlpha((int)((mColorSelected >>> 24) * selectedPercent)); canvas.drawText(pageTitle, 0, pageTitle.length(), bound.left, bound.bottom + mTopPadding, mPaintText); } } } //If we want the line on the top change height to zero and invert the line height to trick the drawing code float footerLineHeight = mFooterLineHeight; float footerIndicatorLineHeight = mFooterIndicatorHeight; if (mLinePosition == LinePosition.Top) { height = 0; footerLineHeight = -footerLineHeight; footerIndicatorLineHeight = -footerIndicatorLineHeight; } //Draw the footer line mPath.reset(); mPath.moveTo(0, height - footerLineHeight / 2f); mPath.lineTo(width, height - footerLineHeight / 2f); mPath.close(); canvas.drawPath(mPath, mPaintFooterLine); float heightMinusLine = height - footerLineHeight; switch (mFooterIndicatorStyle) { case Triangle: mPath.reset(); mPath.moveTo(halfWidth, heightMinusLine - footerIndicatorLineHeight); mPath.lineTo(halfWidth + footerIndicatorLineHeight, heightMinusLine); mPath.lineTo(halfWidth - footerIndicatorLineHeight, heightMinusLine); mPath.close(); canvas.drawPath(mPath, mPaintFooterIndicator); break; case Underline: if (!currentSelected || page >= boundsSize) { break; } Rect underlineBounds = bounds.get(page); final float rightPlusPadding = underlineBounds.right + mFooterIndicatorUnderlinePadding; final float leftMinusPadding = underlineBounds.left - mFooterIndicatorUnderlinePadding; final float heightMinusLineMinusIndicator = heightMinusLine - footerIndicatorLineHeight; mPath.reset(); mPath.moveTo(leftMinusPadding, heightMinusLine); mPath.lineTo(rightPlusPadding, heightMinusLine); mPath.lineTo(rightPlusPadding, heightMinusLineMinusIndicator); mPath.lineTo(leftMinusPadding, heightMinusLineMinusIndicator); mPath.close(); mPaintFooterIndicator.setAlpha((int)(0xFF * selectedPercent)); canvas.drawPath(mPath, mPaintFooterIndicator); mPaintFooterIndicator.setAlpha(0xFF); break; } } public boolean onTouchEvent(android.view.MotionEvent ev) { if (super.onTouchEvent(ev)) { return true; } if ((mViewPager == null) || (mViewPager.getAdapter().getCount() == 0)) { return false; } final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; switch (action) { case MotionEvent.ACTION_DOWN: mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mLastMotionX = ev.getX(); break; case MotionEvent.ACTION_MOVE: { final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); final float deltaX = x - mLastMotionX; if (!mIsDragging) { if (Math.abs(deltaX) > mTouchSlop) { mIsDragging = true; } } if (mIsDragging) { mLastMotionX = x; if (mViewPager.isFakeDragging() || mViewPager.beginFakeDrag()) { mViewPager.fakeDragBy(deltaX); } } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: if (!mIsDragging) { final int count = mViewPager.getAdapter().getCount(); final int width = getWidth(); final float halfWidth = width / 2f; final float sixthWidth = width / 6f; final float leftThird = halfWidth - sixthWidth; final float rightThird = halfWidth + sixthWidth; final float eventX = ev.getX(); if (eventX < leftThird) { if (mCurrentPage > 0) { if (action != MotionEvent.ACTION_CANCEL) { mViewPager.setCurrentItem(mCurrentPage - 1); } return true; } } else if (eventX > rightThird) { if (mCurrentPage < count - 1) { if (action != MotionEvent.ACTION_CANCEL) { mViewPager.setCurrentItem(mCurrentPage + 1); } return true; } } else { //Middle third if (mCenterItemClickListener != null && action != MotionEvent.ACTION_CANCEL) { mCenterItemClickListener.onCenterItemClick(mCurrentPage); } } } mIsDragging = false; mActivePointerId = INVALID_POINTER; if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag(); break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int index = MotionEventCompat.getActionIndex(ev); mLastMotionX = MotionEventCompat.getX(ev, index); mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; } case MotionEventCompat.ACTION_POINTER_UP: final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); } mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId)); break; } return true; } /** * Set bounds for the right textView including clip padding. * * @param curViewBound * current bounds. * @param curViewWidth * width of the view. */ private void clipViewOnTheRight(Rect curViewBound, float curViewWidth, int right) { curViewBound.right = (int) (right - mClipPadding); curViewBound.left = (int) (curViewBound.right - curViewWidth); } /** * Set bounds for the left textView including clip padding. * * @param curViewBound * current bounds. * @param curViewWidth * width of the view. */ private void clipViewOnTheLeft(Rect curViewBound, float curViewWidth, int left) { curViewBound.left = (int) (left + mClipPadding); curViewBound.right = (int) (mClipPadding + curViewWidth); } /** * Calculate views bounds and scroll them according to the current index * * @param paint * @return */ private ArrayList<Rect> calculateAllBounds(Paint paint) { ArrayList<Rect> list = new ArrayList<Rect>(); //For each views (If no values then add a fake one) final int count = mViewPager.getAdapter().getCount(); final int width = getWidth(); final int halfWidth = width / 2; for (int i = 0; i < count; i++) { Rect bounds = calcBounds(i, paint); int w = bounds.right - bounds.left; int h = bounds.bottom - bounds.top; bounds.left = (int)(halfWidth - (w / 2f) + ((i - mCurrentPage - mPageOffset) * width)); bounds.right = bounds.left + w; bounds.top = 0; bounds.bottom = h; list.add(bounds); } return list; } /** * Calculate the bounds for a view's title * * @param index * @param paint * @return */ private Rect calcBounds(int index, Paint paint) { //Calculate the text bounds Rect bounds = new Rect(); CharSequence title = getTitle(index); bounds.right = (int) paint.measureText(title, 0, title.length()); bounds.bottom = (int) (paint.descent() - paint.ascent()); return bounds; } @Override public void setViewPager(ViewPager view) { if (mViewPager == view) { return; } if (mViewPager != null) { mViewPager.setOnPageChangeListener(null); } if (view.getAdapter() == null) { throw new IllegalStateException("ViewPager does not have adapter instance."); } mViewPager = view; mViewPager.setOnPageChangeListener(this); invalidate(); } @Override public void setViewPager(ViewPager view, int initialPosition) { setViewPager(view); setCurrentItem(initialPosition); } @Override public void notifyDataSetChanged() { invalidate(); } /** * Set a callback listener for the center item click. * * @param listener Callback instance. */ public void setOnCenterItemClickListener(OnCenterItemClickListener listener) { mCenterItemClickListener = listener; } @Override public void setCurrentItem(int item) { if (mViewPager == null) { throw new IllegalStateException("ViewPager has not been bound."); } mViewPager.setCurrentItem(item); mCurrentPage = item; invalidate(); } @Override public void onPageScrollStateChanged(int state) { mScrollState = state; if (mListener != null) { mListener.onPageScrollStateChanged(state); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { mCurrentPage = position; mPageOffset = positionOffset; invalidate(); if (mListener != null) { mListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageSelected(int position) { if (mScrollState == ViewPager.SCROLL_STATE_IDLE) { mCurrentPage = position; invalidate(); } if (mListener != null) { mListener.onPageSelected(position); } } @Override public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) { mListener = listener; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //Measure our width in whatever mode specified final int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); //Determine our height float height; final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); if (heightSpecMode == MeasureSpec.EXACTLY) { //We were told how big to be height = MeasureSpec.getSize(heightMeasureSpec); } else { //Calculate the text bounds mBounds.setEmpty(); mBounds.bottom = (int) (mPaintText.descent() - mPaintText.ascent()); height = mBounds.bottom - mBounds.top + mFooterLineHeight + mFooterPadding + mTopPadding; if (mFooterIndicatorStyle != IndicatorStyle.None) { height += mFooterIndicatorHeight; } } final int measuredHeight = (int)height; setMeasuredDimension(measuredWidth, measuredHeight); } @Override public void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState)state; super.onRestoreInstanceState(savedState.getSuperState()); mCurrentPage = savedState.currentPage; requestLayout(); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.currentPage = mCurrentPage; return savedState; } static class SavedState extends BaseSavedState { int currentPage; public SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentPage = in.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(currentPage); } @SuppressWarnings("UnusedDeclaration") public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } private CharSequence getTitle(int i) { CharSequence title = mViewPager.getAdapter().getPageTitle(i); if (title == null) { title = EMPTY_TITLE; } return title; } }
/* * 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.wicket.markup.html; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import org.apache.wicket.protocol.http.WebResponse; import org.apache.wicket.util.resource.IResourceStream; import org.apache.wicket.util.resource.ResourceStreamNotFoundException; import org.apache.wicket.util.time.Time; /** * An WebResource subclass for dynamic resources (resources created programmatically). * <p> * This class caches the generated resource in memory, and is thus very useful for things you * generate dynamically, but reuse for a while after that. If you need resources that stream * directly and are not cached, extend {@link WebResource} directly and implement * {@link WebResource#getResourceStream()} yourself. * </p> * * @author Jonathan Locke * @author Johan Compagner * @author Gili Tzabari */ public abstract class DynamicWebResource extends WebResource { /** * */ private static final long serialVersionUID = 1L; /** * The resource state returned by the getResourceState() method. This state needs to be * thread-safe and its methods must return the same values no matter how many times they are * invoked. A ResourceState may assume getParameters() will remain unchanged during its * lifetime. * * @author jcompagner */ public static abstract class ResourceState { protected Time lastModifiedTime; /** * @return The Byte array for this resource */ public abstract byte[] getData(); /** * @return The content type of this resource */ public abstract String getContentType(); /** * @return The last modified time of this resource */ public Time lastModifiedTime() { if (lastModifiedTime == null) { lastModifiedTime = Time.now(); } return lastModifiedTime; } /** * @return The length of the data */ public int getLength() { byte[] data = getData(); return data != null ? data.length : 0; } } /** * The resource locale. */ private final Locale locale; /** The filename that will be set as the Content-Disposition header. */ private final String filename; /** * Creates a dynamic resource. */ public DynamicWebResource() { this(null, null); } /** * Creates a dynamic resource. * * @param filename * The filename that will be set as the Content-Disposition header. */ public DynamicWebResource(String filename) { this(null, filename); } /** * Creates a dynamic resource from for the given locale * * @param locale * The locale of this resource */ public DynamicWebResource(Locale locale) { this(locale, null); } /** * Creates a dynamic resource from for the given locale * * @param locale * The locale of this resource * @param filename * The filename that will be set as the Content-Disposition header. */ public DynamicWebResource(Locale locale, String filename) { this.locale = locale; this.filename = filename; setCacheable(false); } /** * @see org.apache.wicket.markup.html.WebResource#setHeaders(org.apache.wicket.protocol.http.WebResponse) */ protected void setHeaders(WebResponse response) { super.setHeaders(response); if (filename != null) { response.setAttachmentHeader(filename); } } /** * Returns the resource locale. * * @return The locale of this resource */ public Locale getLocale() { return locale; } /** * @return Gets the resource to attach to the component. */ // this method is deliberately non-final. some users depend on it public IResourceStream getResourceStream() { return new IResourceStream() { private static final long serialVersionUID = 1L; private Locale locale = DynamicWebResource.this.getLocale(); /** Transient input stream to resource */ private transient InputStream inputStream = null; /** * Transient ResourceState of the resources, will always be deleted in the close */ private transient ResourceState data = null; /** * @see org.apache.wicket.util.resource.IResourceStream#close() */ public void close() throws IOException { if (inputStream != null) { inputStream.close(); inputStream = null; } data = null; } /** * @see org.apache.wicket.util.resource.IResourceStream#getContentType() */ public String getContentType() { checkLoadData(); return data.getContentType(); } /** * @see org.apache.wicket.util.resource.IResourceStream#getInputStream() */ public InputStream getInputStream() throws ResourceStreamNotFoundException { checkLoadData(); if (inputStream == null) { inputStream = new ByteArrayInputStream(data.getData()); } return inputStream; } /** * @see org.apache.wicket.util.watch.IModifiable#lastModifiedTime() */ public Time lastModifiedTime() { checkLoadData(); return data.lastModifiedTime(); } /** * @see org.apache.wicket.util.resource.IResourceStream#length() */ public long length() { checkLoadData(); return data.getLength(); } /** * @see org.apache.wicket.util.resource.IResourceStream#getLocale() */ public Locale getLocale() { return locale; } /** * @see org.apache.wicket.util.resource.IResourceStream#setLocale(java.util.Locale) */ public void setLocale(Locale loc) { locale = loc; } /** * Check whether the data was loaded yet. If not, load it now. */ private void checkLoadData() { if (data == null) { data = getResourceState(); } } }; } /** * Gets the byte array for our dynamic resource. If the subclass regenerates the data, it should * set the lastModifiedTime too. This ensures that resource caching works correctly. * * @return The byte array for this dynamic resource. */ protected abstract ResourceState getResourceState(); }
/* * Copyright 2021 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. */ package com.thoughtworks.go.api.spring; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.RoleConfig; import com.thoughtworks.go.config.Users; import com.thoughtworks.go.config.policy.*; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.service.GoConfigService; import com.thoughtworks.go.server.service.SecurityService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import spark.HaltException; import java.util.Arrays; import java.util.Map; import static com.thoughtworks.go.domain.ArtifactPlan.GSON; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class ApiAuthenticationHelperTest { @Mock(lenient = true) private SecurityService securityService; @Mock private GoConfigService goConfigService; private ApiAuthenticationHelper helper; private final Username ADMIN = new Username("Admin"); private final Username BOB = new Username("Bob"); @BeforeEach void setUp() { when(securityService.isUserAdmin(ADMIN)).thenReturn(true); when(securityService.isUserAdmin(BOB)).thenReturn(false); } @Nested class GranularAuth { @BeforeEach void setUp() { helper = new ApiAuthenticationHelper(securityService, goConfigService); } @Test void shouldAllowAllAdministratorsToViewAllEnvironments() { assertDoesNotThrow(() -> helper.checkUserHasPermissions(ADMIN, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, null)); } @Test void shouldAllowAllAdministratorsToViewSingleEnvironments() { assertDoesNotThrow(() -> helper.checkUserHasPermissions(ADMIN, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "env_1")); } @Test void shouldNotAllNormalUsersToViewAllEnvironments() { assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, null)); } @Test void shouldNotAllNormalUsersToViewSingleEnvironments() { assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "env_1")); } @Test /* <role name="allow-all-environments"> <policy> <allow action="view" type="environment">*</allow> </policy> <users> <user>Bob</user> </users> </role> */ void shouldAllowNormalUserWithAllowedEnvironmentPolicyToViewEnvironments() { Policy directives = new Policy(); directives.add(new Allow("view", "environment", "*")); RoleConfig roleConfig = new RoleConfig(new CaseInsensitiveString("read-only-environments"), new Users(), directives); when(goConfigService.rolesForUser(BOB.getUsername())).thenReturn(Arrays.asList(roleConfig)); assertDoesNotThrow(() -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, null)); assertDoesNotThrow(() -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "foo")); } @Test /* <role name="allow-one-environments"> <policy> <allow action="view" type="environment">env_1</allow> </policy> <users> <user>Bob</user> </users> </role> */ void shouldAllowNormalUserWithAllowedEnvironmentPolicyToViewSpecificEnvironment() { Policy directives = new Policy(); directives.add(new Allow("view", "environment", "env_1")); RoleConfig roleConfig = new RoleConfig(new CaseInsensitiveString("read-only-environments"), new Users(), directives); when(goConfigService.rolesForUser(BOB.getUsername())).thenReturn(Arrays.asList(roleConfig)); assertDoesNotThrow(() -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "env_1")); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, null)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "env_2")); } @Test /* <role name="disallowed-directive-first-environment"> <policy> <deny action="view" type="environment">*</deny> <allow action="view" type="environment">env_1</allow> </policy> <users> <user>Bob</user> </users> </role> */ void shouldNotAllowNormalUserWithDisallowPolicyFirstToViewEnvironment() { Policy directives = new Policy(); directives.add(new Deny("view", "environment", "*")); directives.add(new Allow("view", "environment", "env_1")); RoleConfig roleConfig = new RoleConfig(new CaseInsensitiveString("read-only-environments"), new Users(), directives); when(goConfigService.rolesForUser(BOB.getUsername())).thenReturn(Arrays.asList(roleConfig)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, null)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "env_1")); } @Test /* <role name="disallowed-directive-first-environment"> <policy> <allow action="view" type="environment">env_1</allow> <deny action="view" type="environment">*</deny> </policy> <users> <user>Bob</user> </users> </role> */ void shouldAllowNormalUserWithAllowedPolicyFirstToViewEnvironment() { Policy directives = new Policy(); directives.add(new Allow("view", "environment", "env_1")); directives.add(new Deny("view", "environment", "*")); RoleConfig roleConfig = new RoleConfig(new CaseInsensitiveString("read-only-environments"), new Users(), directives); when(goConfigService.rolesForUser(BOB.getUsername())).thenReturn(Arrays.asList(roleConfig)); assertDoesNotThrow(() -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "env_1")); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, null)); } @Test /* <role name="allow-all-environments"> <policy> <allow action="administer" type="environment">*</allow> </policy> <users> <user>Bob</user> </users> </role> */ void shouldAllowNormalUserWithAllowedEnvironmentPolicyToAdministerEnvironments() { Policy directives = new Policy(); directives.add(new Allow("administer", "environment", "*")); RoleConfig roleConfig = new RoleConfig(new CaseInsensitiveString("read-only-environments"), new Users(), directives); when(goConfigService.rolesForUser(BOB.getUsername())).thenReturn(Arrays.asList(roleConfig)); assertDoesNotThrow(() -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, null)); assertDoesNotThrow(() -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "foo")); assertDoesNotThrow(() -> helper.checkUserHasPermissions(BOB, SupportedAction.ADMINISTER, SupportedEntity.ENVIRONMENT, null)); assertDoesNotThrow(() -> helper.checkUserHasPermissions(BOB, SupportedAction.ADMINISTER, SupportedEntity.ENVIRONMENT, "foo")); } @Test /* <role name="disallowed-directive-first-environment"> <policy> <deny action="administer" type="environment">*</deny> <allow action="administer" type="environment">env_1</allow> </policy> <users> <user>Bob</user> </users> </role> */ void shouldNotAllowNormalUserWithDisallowPolicyFirstToAdministerEnvironment() { Policy directives = new Policy(); directives.add(new Deny("administer", "environment", "*")); directives.add(new Allow("administer", "environment", "env_1")); RoleConfig roleConfig = new RoleConfig(new CaseInsensitiveString("read-only-environments"), new Users(), directives); when(goConfigService.rolesForUser(BOB.getUsername())).thenReturn(Arrays.asList(roleConfig)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, null)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "env_1")); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.ADMINISTER, SupportedEntity.ENVIRONMENT, null)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.ADMINISTER, SupportedEntity.ENVIRONMENT, "env_1")); } @Test /* <role name="deny-permissions"> <policy> <deny action="administer" type="environment">*</deny> </policy> <users> <user>Bob</user> </users> </role> <role name="allow-permissions"> <policy> <allow action="administer" type="environment">*</allow> </policy> <users> <user>Bob</user> </users> </role> */ void shouldNotAllowNormalUserAccessToEnvironmentWhenOnOfTheRoleHasAnExplicitDeny_WithFirstRoleAsDeny() { Policy directives = new Policy(); directives.add(new Deny("administer", "environment", "*")); RoleConfig denyRoleConfig = new RoleConfig(new CaseInsensitiveString("deny-permissions"), new Users(), directives); Policy directives2 = new Policy(); directives2.add(new Allow("administer", "environment", "*")); RoleConfig allowRoleConfig = new RoleConfig(new CaseInsensitiveString("allow-permissions"), new Users(), directives2); when(goConfigService.rolesForUser(BOB.getUsername())).thenReturn(Arrays.asList(denyRoleConfig, allowRoleConfig)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, null)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "env_1")); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.ADMINISTER, SupportedEntity.ENVIRONMENT, null)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.ADMINISTER, SupportedEntity.ENVIRONMENT, "env_1")); } @Test /* <role name="allow-permissions"> <policy> <allow action="administer" type="environment">*</allow> </policy> <users> <user>Bob</user> </users> </role> <role name="deny-permissions"> <policy> <deny action="administer" type="environment">*</deny> </policy> <users> <user>Bob</user> </users> </role> */ void shouldNotAllowNormalUserAccessToEnvironmentWhenOnOfTheRoleHasAnExplicitDeny_WithFirstRoleAsAllow() { Policy directives = new Policy(); directives.add(new Deny("administer", "environment", "*")); RoleConfig denyRoleConfig = new RoleConfig(new CaseInsensitiveString("deny-permissions"), new Users(), directives); Policy directives2 = new Policy(); directives2.add(new Allow("administer", "environment", "*")); RoleConfig allowRoleConfig = new RoleConfig(new CaseInsensitiveString("allow-permissions"), new Users(), directives2); when(goConfigService.rolesForUser(BOB.getUsername())).thenReturn(Arrays.asList(allowRoleConfig, denyRoleConfig)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, null)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "env_1")); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.ADMINISTER, SupportedEntity.ENVIRONMENT, null)); assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.ADMINISTER, SupportedEntity.ENVIRONMENT, "env_1")); } @Test void shouldRenderAppropriateForbiddenErrorMessageWhenUserDoesNotHaveViewPermissions() { HaltException thrown = assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.VIEW, SupportedEntity.ENVIRONMENT, "env_1")); String expectedMessage = "User 'Bob' does not have permissions to view 'env_1' environment(s)."; assertThat(GSON.fromJson(thrown.body(), Map.class).get("message")).isEqualTo(expectedMessage); } @Test void shouldRenderAppropriateForbiddenErrorMessageWhenUserDoesNotHaveAdministerPermissions() { HaltException thrown = assertThrows(HaltException.class, () -> helper.checkUserHasPermissions(BOB, SupportedAction.ADMINISTER, SupportedEntity.ENVIRONMENT, "env_1")); String expectedMessage = "User 'Bob' does not have permissions to administer 'env_1' environment(s)."; assertThat(GSON.fromJson(thrown.body(), Map.class).get("message")).isEqualTo(expectedMessage); } } }
/*--- Copyright 2006-2007 Visual Systems Corporation. http://www.vscorp.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ---*/ package com.googlecode.wicketwebbeans.containers; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator; import org.apache.wicket.extensions.markup.html.repeater.data.sort.ISortStateLocator; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.ISortableDataProvider; import org.apache.wicket.extensions.markup.html.repeater.data.table.NavigatorLabel; import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.IDataProvider; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import com.googlecode.wicketwebbeans.actions.BeanActionButton; import com.googlecode.wicketwebbeans.model.BeanMetaData; import com.googlecode.wicketwebbeans.model.ElementMetaData; /** * Displays a list of beans as an editable or viewable table. <p> * * @author Dan Syrstad * @author Mark Southern (mrsouthern) */ public class BeanTablePanel extends Panel { private static final long serialVersionUID = -5452855853289381110L; private BeanMetaData metaData; /** * Construct a new BeanTablePanel. * * @param id the Wicket id for the editor. * @param model the model, which must return a Collection type for its object. * @param metaData the meta data for the bean/row. * @param numRows the number of rows to be displayed. */ public BeanTablePanel(String id, IModel model, BeanMetaData metaData, int numRows) { this(id, model, metaData, metaData.isViewOnly(), numRows); } /** * Construct a new BeanTablePanel. * * @param id the Wicket id for the editor. * @param model the model, which must return a Collection type for its object. * @param metaData the meta data for the bean/row. * @param viewOnly * @param numRows the number of rows to be displayed. */ public BeanTablePanel(String id, IModel model, BeanMetaData metaData, boolean viewOnly, int numRows) { this(id, new BeanSortableDataProvider(metaData, model), metaData, viewOnly, numRows); } /** * Construct a new BeanTablePanel. * * @param id the Wicket id for the editor. * @param dataProvider - sortable source of the data * @param metaData the meta data for the bean/row. * @param viewOnly * @param numRows the number of rows to be displayed. */ public BeanTablePanel(String id, ISortableDataProvider dataProvider, BeanMetaData metaData, boolean viewOnly, int numRows) { this(id, dataProvider, dataProvider, metaData, viewOnly, numRows); } /** * Construct a new BeanTablePanel. * * @param id the Wicket id for the editor. * @param dataProvider - source of the data * @param sortStateLocator - the sorter for the dataProvider * @param metaData the meta data for the bean/row. * @param viewOnly * @param numRows the number of rows to be displayed. */ public BeanTablePanel(String id, IDataProvider dataProvider, ISortStateLocator sortStateLocator, BeanMetaData metaData, boolean viewOnly, int numRows) { super(id); this.metaData = metaData; List<IColumn> columns = new ArrayList<IColumn>(); for (ElementMetaData element : metaData.getDisplayedElements()) { columns.add(new BeanElementColumn(element, this)); } if (columns.isEmpty()) { columns.add(new EmptyColumn()); } final BeanDataTable table = new BeanDataTable("t", columns, dataProvider, sortStateLocator, numRows, metaData); add(table); final NavigatorLabel navigatorLabel = new NavigatorLabel("nl", table); navigatorLabel.setOutputMarkupId(true); add(navigatorLabel); add(new AjaxPagingNavigator("np", table) { private static final long serialVersionUID = 1L; protected void onAjaxEvent(AjaxRequestTarget target) { super.onAjaxEvent(target); target.addComponent(table); target.addComponent(navigatorLabel); } }); } @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); metaData.warnIfAnyParameterNotConsumed(null); } public static class BeanSortableDataProvider extends SortableDataProvider { private static final long serialVersionUID = 6712923396580294568L; private IModel listModel; private BeanMetaData metaData; private SortParam lastSortParam = null; public BeanSortableDataProvider(BeanMetaData metaData, IModel listModel) { this.metaData = metaData; this.listModel = listModel; } List getList() { Collection collection = (Collection)listModel.getObject(); if (collection == null) { return new ArrayList(); } if (collection instanceof List) { return (List)collection; } // Make any other kind of non-List collection a List. return new ArrayList(collection); } public Iterator iterator(int first, int count) { List list = getList(); final SortParam sortParam = getSort(); if (sortParam != null) { if (list != listModel.getObject() || // Synthesized list. Always sort. lastSortParam == null || // Haven't sorted yet. !lastSortParam.getProperty().equals(sortParam.getProperty()) || // Sort params changed. lastSortParam.isAscending() != sortParam.isAscending()) { lastSortParam = new SortParam(sortParam.getProperty(), sortParam.isAscending()); ElementMetaData property = metaData.findElement(sortParam.getProperty()); Collections.sort(list, new PropertyComparator(property, sortParam.isAscending())); } } return list.subList(first, first + count).iterator(); } public int size() { Collection collection = (Collection)listModel.getObject(); if (collection == null) { return 0; } return collection.size(); } /** * @param object * @return * @see org.apache.wicket.extensions.markup.html.repeater.data.IDataProvider#model(java.lang.Object) */ public IModel model(Object object) { return new Model<Serializable>((Serializable) object); } @Override public void detach() { super.detach(); listModel.detach(); } } public static class BeanElementColumn implements IColumn { private static final long serialVersionUID = -7194001360552686010L; private ElementMetaData element; private Component parentComponent; public BeanElementColumn(ElementMetaData property, Component parentComponent) { this.element = property; this.parentComponent = parentComponent; } public Component getHeader(String componentId) { //if (element.isAction()) { // return new Label(componentId, ""); //} return element.getLabelComponent(componentId); } public String getSortProperty() { return element.getPropertyName(); } public boolean isSortable() { Class propertyType = element.getPropertyType(); return !element.isAction() && (propertyType.isPrimitive() || Comparable.class.isAssignableFrom(propertyType)); } public void populateItem(Item cellItem, String componentId, IModel rowModel) { Object bean = rowModel.getObject(); Component component; BeanMetaData beanMetaData = element.getBeanMetaData(); if (element.isAction()) { Form form = parentComponent.findParent(Form.class); component = new BeanActionButton(componentId, element, form, bean); } else { component = beanMetaData.getComponentRegistry().getComponent(bean, componentId, element); } beanMetaData.applyCss(bean, element, component); cellItem.add(component); } public void detach() { } } private static final class PropertyComparator implements Comparator { private ElementMetaData property; private boolean isAscending; public PropertyComparator(ElementMetaData property, boolean isAscending) { // We already know by this point that the property type is Comparable. BeanPropertyColumn.isSortable enforces this. this.property = property; this.isAscending = isAscending; } public int compare(Object o1, Object o2) { Object v1 = property.getPropertyValue(o1); Object v2 = property.getPropertyValue(o2); if (v1 == v2) { return 0; } int rc; // Nulls sort smaller if (v1 == null) { rc = -1; } else if (v2 == null) { rc = 1; } else { rc = ((Comparable) v1).compareTo(v2); } if (!isAscending) { rc = -rc; } return rc; } } private static final class EmptyColumn implements IColumn { private static final long serialVersionUID = 1L; public Component getHeader(String id) { return new Label(id, ""); } public String getSortProperty() { return ""; } public boolean isSortable() { return false; } public void populateItem(Item cellItem, String componentId, IModel rowModel) { cellItem.add(new Label(componentId, "")); } public void detach() { } } }
/* * Copyright 2014 Matti Tahvonen. * * 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.vaadin.viritin; import org.vaadin.viritin.testdomain.Person; import com.vaadin.data.Container; import com.vaadin.data.Container.Filter; import com.vaadin.data.Item; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.data.util.filter.Between; import com.vaadin.data.util.filter.Compare; import com.vaadin.data.util.filter.SimpleStringFilter; import java.lang.management.ManagementFactory; import java.lang.management.MemoryUsage; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Random; import junit.framework.Assert; import org.apache.commons.lang3.mutable.MutableBoolean; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Ignore; import static org.junit.matchers.JUnitMatchers.hasItems; /** * */ public class FilterableListContainerTest { Random r = new Random(0); private List<Person> getListOfPersons(int total) { List<Person> l = new ArrayList<Person>(total); for (int i = 0; i < total; i++) { Person p = new Person(); p.setFirstName("First" + i); p.setLastName("Lastname" + i); p.setAge(r.nextInt(100)); l.add(p); } return l; } final static int amount = 1000000; //final static int amount = 100000; private Filter ageFilter = new Between("age", 30, 40); private List<Person> persons = getListOfPersons(amount); @Test public void clearFilters() { final List<Person> listOfPersons = getListOfPersons(100); FilterableListContainer<Person> container = new FilterableListContainer<Person>( listOfPersons); container.addContainerFilter(new SimpleStringFilter("firstName", "First1", true, true)); Assert.assertNotSame(listOfPersons.size(), container.size()); container.removeAllContainerFilters(); Assert.assertEquals(listOfPersons.size(), container.size()); container.addContainerFilter(new SimpleStringFilter("firstName", "foobar", true, true)); Assert.assertEquals(0, container.size()); final MutableBoolean fired = new MutableBoolean(false); container.addListener(new Container.ItemSetChangeListener() { @Override public void containerItemSetChange( Container.ItemSetChangeEvent event) { fired.setTrue(); } }); container.removeAllContainerFilters(); Assert.assertTrue(fired.booleanValue()); Assert.assertEquals(listOfPersons.size(), container.size()); } @Test public void testFilterableListContainerPerformance() { System.out.println( "\n Testing FilterableListContainer from Viritin (with Filter)"); long initial = reportMemoryUsage(); long ms = System.currentTimeMillis(); FilterableListContainer<Person> lc = new FilterableListContainer<Person>( persons); System.out.println( "After creation with " + amount + " beans (took " + (System. currentTimeMillis() - ms) + ")"); long after = reportMemoryUsage(); System.err.println("Delta (bytes)" + (after - initial)); doTests(lc, initial); } @Test @Ignore(value = "we know BeanItemContainer filtering is veeery slow, re-activate to investigate possible enhancements in the core.") public void testFilterStd() { System.out.println( "\n Testing BeanItemContainer from core Vaadin (with Filter)"); long initial = reportMemoryUsage(); long ms = System.currentTimeMillis(); BeanItemContainer<Person> lc = new BeanItemContainer<Person>( Person.class, persons); System.out.println( "After creation with " + amount + " beans (took " + (System. currentTimeMillis() - ms) + ")"); long after = reportMemoryUsage(); System.err.println("Delta (bytes)" + (after - initial)); doTests(lc, initial); } @Test public void testSortingWhenFiltered() { FilterableListContainer<Person> lc = new FilterableListContainer<Person>( persons); lc.addContainerFilter(new SimpleStringFilter("firstName", "First10000", true, true)); lc.sort(new Object[]{"firstName"}, new boolean[]{false}); Person p = lc.getIdByIndex(0); Assert.assertEquals("First100009", p.getFirstName()); Assert.assertEquals("First10000", lc.getIdByIndex(10).getFirstName()); lc.sort(new Object[]{"firstName"}, new boolean[]{true}); Assert.assertEquals("First10000", lc.getIdByIndex(0).getFirstName()); Assert.assertEquals("First100009", lc.getIdByIndex(10).getFirstName()); } private void doTests(Container.Filterable lc, long initial) { long ms = System.currentTimeMillis(); for (int i = 0; i < amount; i++) { Item item = lc.getItem(persons.get(i)); String str; str = item.getItemProperty("firstName").toString(); } System.out.println( "After loop (took " + (System.currentTimeMillis() - ms) + ")"); long after = reportMemoryUsage(); System.err.println("Delta (bytes)" + (after - initial)); ms = System.currentTimeMillis(); lc.addContainerFilter(ageFilter); int fSize = lc.size(); System.out.println( "Time to filter " + fSize + " out of " + amount + " elements: " + (System. currentTimeMillis() - ms)); ms = System.currentTimeMillis(); for (Object o : lc.getItemIds()) { String str; Person bean = (Person) o; str = bean.getFirstName(); } System.out.println( "After loop through filtered list (took " + (System. currentTimeMillis() - ms) + ")"); long afterF = reportMemoryUsage(); System.err.println("Delta (bytes)" + (afterF - after)); // call to avoid GC:n the whole container lc.getItemIds(); System.out.println("After GC"); after = reportMemoryUsage(); System.out.println(); System.err.println("Delta (bytes)" + (after - initial)); } private long reportMemoryUsage() { try { System.gc(); Thread.sleep(100); System.gc(); Thread.sleep(100); System.gc(); Thread.sleep(100); System.gc(); } catch (InterruptedException ex) { } MemoryUsage mu = ManagementFactory.getMemoryMXBean(). getHeapMemoryUsage(); System.out.println("Memory used (M):" + mu.getUsed() / 1000000); return ManagementFactory.getMemoryMXBean(). getHeapMemoryUsage().getUsed(); } @Test public void testFirstLast() { FilterableListContainer<Person> lc = new FilterableListContainer<Person>( new ArrayList<Person>(Arrays.asList( new Person(0, "1", "1", 1), new Person(0, "2", "2", 2), new Person(0, "3", "3", 3) ))); lc.addContainerFilter(new Compare.Greater("age", 1)); assertNotSame(1, lc.firstItemId().getAge()); lc.addContainerFilter(new Compare.LessOrEqual("age", 1)); try { assertNull(lc.firstItemId()); assertNull(lc.lastItemId()); } catch (ArrayIndexOutOfBoundsException ex) { fail("Exception was thrown: " + ex); } } @Test public void testMultiLevelSort() throws Exception { FilterableListContainer<Person> lc = new FilterableListContainer<Person>( new ArrayList<Person>(Arrays.asList( new Person(0, "2", "2", 3), new Person(0, "3", "2", 2), new Person(0, "1", "2", 2), new Person(0, "1", "1", 1), new Person(0, "1", "2", 4) ))); lc.sort(new Object[]{"age", "firstName"}, new boolean[]{true, false}); Collection<Person> itemIds = lc.getItemIds(); assertThat(itemIds, hasItems( new Person(0, "1", "1", 1), new Person(0, "3", "2", 2), new Person(0, "1", "2", 2), new Person(0, "2", "2", 3), new Person(0, "1", "2", 4) )); } }
/** * Copyright (c) 2016 TermMed SA * Organization * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ /** * Author: Alejandro Rodriguez */ package com.termmed.control.roletesting; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.termmed.inheritance.model.Relationship; import com.termmed.inheritance.model.RelationshipGroup; import com.termmed.utils.TClosure; // TODO: Auto-generated Javadoc /** * The Class TestCrossover. */ public class TestCrossover { /** The Tclos. */ TClosure Tclos; /** * Instantiates a new test crossover. * * @param tclos the tclos */ public TestCrossover(TClosure tclos) { super(); Tclos = tclos; } /** * The Enum TEST_RESULTS. */ public enum TEST_RESULTS {/** The CONCEP t1_ ancestoro f_ concep t2. */ CONCEPT1_ANCESTOROF_CONCEPT2,/** The CONCEP t2_ ancestoro f_ concep t1. */ CONCEPT2_ANCESTOROF_CONCEPT1,/** The CONCEPT s_ dif f_ hierarchy. */ CONCEPTS_DIFF_HIERARCHY, /** The CONCEP t1_ subsu m_ concep t2. */ CONCEPT1_SUBSUM_CONCEPT2, /** The CONCEP t1_ equa l_ concep t2. */ CONCEPT1_EQUAL_CONCEPT2, /** The CONCEP t2_ subsu m_ concep t1. */ CONCEPT2_SUBSUM_CONCEPT1, /** The THER e_ i s_ n o_ subsum. */ THERE_IS_NO_SUBSUM, /** The ROL e1_ subsu m_ rol e2. */ ROLE1_SUBSUM_ROLE2, /** The ROL e2_ subsu m_ rol e1. */ ROLE2_SUBSUM_ROLE1, /** The ROL e1_ equa l_ rol e2. */ ROLE1_EQUAL_ROLE2, /** The ROLE s_ crossover. */ ROLES_CROSSOVER, /** The ROLEGROU p1_ subsu m_ rolegrou p2. */ ROLEGROUP1_SUBSUM_ROLEGROUP2, /** The ROLEGROU p2_ subsu m_ rolegrou p1. */ ROLEGROUP2_SUBSUM_ROLEGROUP1, /** The ROLEGROU p1_ equa l_ rolegrou p2. */ ROLEGROUP1_EQUAL_ROLEGROUP2, /** The ROLEGROUP s_ crossover. */ ROLEGROUPS_CROSSOVER }; /** * Subsumption concept test. * * @param concept1 the concept1 * @param concept2 the concept2 * @return the tES t_ results */ public TEST_RESULTS subsumptionConceptTest(long concept1, long concept2){ if (concept1==concept2){ return TEST_RESULTS.CONCEPT1_EQUAL_CONCEPT2; } if (Tclos.isAncestorOf(concept1, concept2)){ return TEST_RESULTS.CONCEPT1_ANCESTOROF_CONCEPT2; } if (Tclos.isAncestorOf(concept2, concept1)){ return TEST_RESULTS.CONCEPT2_ANCESTOROF_CONCEPT1; } return TEST_RESULTS.CONCEPTS_DIFF_HIERARCHY; } /** * Subsumption role test. * * @param role1 the role1 * @param role2 the role2 * @return the tES t_ results */ public TEST_RESULTS subsumptionRoleTest(Relationship role1, Relationship role2){ TEST_RESULTS relTargetSubSum=subsumptionConceptTest(role1.destinationId,role2.destinationId); TEST_RESULTS relTypeSubsum; switch(relTargetSubSum){ case CONCEPT1_ANCESTOROF_CONCEPT2: relTypeSubsum=subsumptionConceptTest( role1.typeId,role2.typeId); switch(relTypeSubsum){ case CONCEPT1_ANCESTOROF_CONCEPT2: case CONCEPT1_EQUAL_CONCEPT2: return TEST_RESULTS.ROLE1_SUBSUM_ROLE2; case CONCEPT2_ANCESTOROF_CONCEPT1: return TEST_RESULTS.ROLES_CROSSOVER; case CONCEPTS_DIFF_HIERARCHY: return TEST_RESULTS.THERE_IS_NO_SUBSUM; } break; case CONCEPT1_EQUAL_CONCEPT2: relTypeSubsum=subsumptionConceptTest( role1.typeId,role2.typeId); switch(relTypeSubsum){ case CONCEPT1_ANCESTOROF_CONCEPT2: return TEST_RESULTS.ROLE1_SUBSUM_ROLE2; case CONCEPT1_EQUAL_CONCEPT2: return TEST_RESULTS.ROLE1_EQUAL_ROLE2; case CONCEPT2_ANCESTOROF_CONCEPT1: return TEST_RESULTS.ROLE2_SUBSUM_ROLE1; case CONCEPTS_DIFF_HIERARCHY: return TEST_RESULTS.THERE_IS_NO_SUBSUM; } break; case CONCEPT2_ANCESTOROF_CONCEPT1: relTypeSubsum=subsumptionConceptTest(role1.typeId,role2.typeId); switch(relTypeSubsum){ case CONCEPT1_ANCESTOROF_CONCEPT2: return TEST_RESULTS.ROLES_CROSSOVER; case CONCEPT1_EQUAL_CONCEPT2: case CONCEPT2_ANCESTOROF_CONCEPT1: return TEST_RESULTS.ROLE2_SUBSUM_ROLE1; case CONCEPTS_DIFF_HIERARCHY: return TEST_RESULTS.THERE_IS_NO_SUBSUM; } break; case CONCEPTS_DIFF_HIERARCHY: return TEST_RESULTS.THERE_IS_NO_SUBSUM; } return null; } /** * Checks if is crossover. * * @param rolegroup1 the rolegroup1 * @param rolegroup2 the rolegroup2 * @return true, if is crossover */ public boolean isCrossover(RelationshipGroup rolegroup1, RelationshipGroup rolegroup2) { TEST_RESULTS result = subsumptionRoleGroupTest( rolegroup1, rolegroup2) ; return result.equals(TEST_RESULTS.ROLEGROUPS_CROSSOVER) || result.equals(TEST_RESULTS.ROLES_CROSSOVER ); } /** * Subsumption role group test. * * @param rolegroup1 the rolegroup1 * @param rolegroup2 the rolegroup2 * @return the tES t_ results */ public TEST_RESULTS subsumptionRoleGroupTest(RelationshipGroup rolegroup1, RelationshipGroup rolegroup2) { TEST_RESULTS roleTestResult ; boolean rolesCrossover=false; boolean equalRoles=false; boolean oneSubsTwoRole=false; boolean twoSubsOneRole=false; boolean thereIsNoSubsRole=false; boolean crossover=false; boolean equal=false; boolean oneSubsTwo=false; boolean twoSubsOne=false; List<Relationship> tupleToTestSwitch=new ArrayList<Relationship>(); Set<Relationship> tupleTested=new HashSet<Relationship>(); for (Relationship role1: rolegroup1){ for (Relationship role2:rolegroup2){ roleTestResult = subsumptionRoleTest(role1, role2); switch(roleTestResult){ case ROLES_CROSSOVER: crossover=true; break; case ROLE1_EQUAL_ROLE2: equal=true; tupleTested.add( role2); break; case ROLE1_SUBSUM_ROLE2: oneSubsTwo=true; break; case ROLE2_SUBSUM_ROLE1: twoSubsOne=true; tupleTested.add( role2); break; case THERE_IS_NO_SUBSUM: break; } // if (oneSubsTwo){ // break; // } } if (oneSubsTwo){ oneSubsTwoRole=true; oneSubsTwo=false; crossover=false; equal=false; twoSubsOne=false; }else if (twoSubsOne){ twoSubsOneRole=true; twoSubsOne=false; crossover=false; equal=false; }else if (equal){ equalRoles=true; equal=false; crossover=false; }else if (crossover){ rolesCrossover=true; crossover=false; }else{ thereIsNoSubsRole=true; } } if (oneSubsTwoRole && twoSubsOneRole){ return TEST_RESULTS.ROLEGROUPS_CROSSOVER; } if (rolesCrossover){ return TEST_RESULTS.ROLES_CROSSOVER; } if (oneSubsTwoRole && rolegroup1.size()>rolegroup2.size()){ return TEST_RESULTS.ROLEGROUPS_CROSSOVER; } if (twoSubsOneRole && rolegroup2.size()>rolegroup1.size()){ return TEST_RESULTS.ROLEGROUPS_CROSSOVER; } if (thereIsNoSubsRole){ return TEST_RESULTS.THERE_IS_NO_SUBSUM; } if (oneSubsTwoRole){ return TEST_RESULTS.CONCEPT1_SUBSUM_CONCEPT2; } if (twoSubsOneRole){ int tuplesTotest=rolegroup2.size()-tupleTested.size(); if (tuplesTotest>0){ for (Relationship role2:rolegroup2){ if (!tupleTested.contains(role2)){ tupleToTestSwitch.add(role2); } } RelationshipGroup relgroupToTest=new RelationshipGroup(tupleToTestSwitch,false); boolean shortResult=roleGroup1SubSumToRoleGroup2(relgroupToTest,rolegroup1); if (!shortResult){ return TEST_RESULTS.THERE_IS_NO_SUBSUM; } } return TEST_RESULTS.CONCEPT2_SUBSUM_CONCEPT1; } if (equalRoles){ return TEST_RESULTS.ROLEGROUP1_EQUAL_ROLEGROUP2; } return null; } /** * Role group1 sub sum to role group2. * * @param rolegroup1 the rolegroup1 * @param rolegroup2 the rolegroup2 * @return true, if successful */ private boolean roleGroup1SubSumToRoleGroup2( RelationshipGroup rolegroup1, RelationshipGroup rolegroup2) { TEST_RESULTS roleTestResult ; boolean equal=false; boolean oneSubsTwo=false; boolean twoSubsOne=false; for (Relationship role1: rolegroup1){ for (Relationship role2:rolegroup2){ roleTestResult = subsumptionRoleTest(role1, role2); switch(roleTestResult){ case ROLES_CROSSOVER: break; case ROLE1_EQUAL_ROLE2: equal=true; break; case ROLE1_SUBSUM_ROLE2: oneSubsTwo=true; break; case ROLE2_SUBSUM_ROLE1: twoSubsOne=true; break; case THERE_IS_NO_SUBSUM: break; } if (oneSubsTwo){ break; } } if (oneSubsTwo){ equal=false; oneSubsTwo=false; twoSubsOne=false; }else if (twoSubsOne){ return false; }else if (equal){ equal=false; }else { return false; } } return true; } /** * Checks if is redundant. * * @param rolegroup1 the rolegroup1 * @param rolegroup2 the rolegroup2 * @return true, if is redundant */ public boolean isRedundant(RelationshipGroup rolegroup1,RelationshipGroup rolegroup2) { TEST_RESULTS result = subsumptionRoleGroupTest( rolegroup1, rolegroup2) ; return result.equals(TEST_RESULTS.CONCEPT1_SUBSUM_CONCEPT2) || result.equals(TEST_RESULTS.CONCEPT2_SUBSUM_CONCEPT1) || result.equals(TEST_RESULTS.ROLEGROUP1_EQUAL_ROLEGROUP2 ); } }
/** * This project is licensed under the Apache License, Version 2.0 * if the following condition is met: * (otherwise it cannot be used by anyone but the author, Kevin, only) * * The original KommonLee project is owned by Lee, Seong Hyun (Kevin). * * -What does it mean to you? * Nothing, unless you want to take the ownership of * "the original project" (not yours or forked & modified one). * You are free to use it for both non-commercial and commercial projects * and free to modify it as the Apache License allows. * * -So why is this condition necessary? * It is only to protect the original project (See the case of Java). * * * Copyright 2009 Lee, Seong Hyun (Kevin) * * 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.elixirian.kommonlee.collect; import static org.elixirian.kommonlee.collect.KollectionUtil.*; import static org.elixirian.kommonlee.util.collect.Lists.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.elixirian.kommonlee.functional.BreakableFunction1; import org.elixirian.kommonlee.functional.IndexedBreakableFunction1; import org.elixirian.kommonlee.functional.IndexedVoidFunction1; import org.elixirian.kommonlee.functional.VoidFunction1; import org.elixirian.kommonlee.type.functional.BreakOrContinue; import org.elixirian.kommonlee.type.functional.Condition1; import org.elixirian.kommonlee.type.functional.Function1; import org.elixirian.kommonlee.type.functional.Function2; /** * <pre> * ___ _____ _____ * / \/ / ______ __________________ ______ __ ______ / / ______ ______ * / / _/ __ // / / / / / /_/ __ // // // / / ___ \/ ___ \ * / \ / /_/ _/ _ _ / _ _ // /_/ _/ __ // /___/ _____/ _____/ * /____/\____\/_____//__//_//_/__//_//_/ /_____//___/ /__//________/\_____/ \_____/ * </pre> * * <pre> * ___ _____ _____ * / \/ /_________ ___ ____ __ ______ / / ______ ______ * / / / ___ \ \/ //___// // / / / / ___ \/ ___ \ * / \ / _____/\ // // __ / / /___/ _____/ _____/ * /____/\____\\_____/ \__//___//___/ /__/ /________/\_____/ \_____/ * </pre> * * @author Lee, SeongHyun (Kevin) * @version 0.0.1 (2011-10-13) */ public class ReadableArrayList<E> extends AbstractReadableList<E> implements ReadableList<E> { private Object[] elements; private int length; protected ReadableArrayList(final Object... elements) { final int length = elements.length; this.elements = new Object[length]; System.arraycopy(elements, 0, this.elements, 0, length); this.length = this.elements.length; } protected ReadableArrayList(final Object[] elements, final int howMany) { final int length = Math.min(elements.length, howMany); this.elements = new Object[length]; System.arraycopy(elements, 0, this.elements, 0, length); this.length = length; } protected ReadableArrayList(final Collection<? extends E> collection) { this(collection.toArray()); } protected ReadableArrayList(final Kollection<? extends E> kollection) { this(kollection.toArray()); } public static <T> ReadableArrayList<T> listOf(final T[] elements, final int howMany) { final int length = Math.min(elements.length, howMany); return new ReadableArrayList<T>(elements, length); } @Override public ArrayList<E> convertTo() { @SuppressWarnings("unchecked") final E[] genericElements = (E[]) elements; final ArrayList<E> list = newArrayList(genericElements); return list; } @Override public Iterator<E> iterator() { return new McHammerIteratorForReadableList(); } @Override public int length() { return length; } @Override public boolean contains(final Object element) { return 0 <= indexOf0(element); } @Override public boolean containsAll(final Kollection<?> kollection) { for (final Object element : kollection) { if (!contains(element)) { return false; } } return true; } @Override public E find(final Condition1<? super E> condition) { for (final Object object : this.elements) { @SuppressWarnings("unchecked") final E element = (E) object; if (condition.isMet(element)) { return element; } } return null; } @Override public ReadableArrayList<E> select(final Condition1<? super E> condition) { final Object[] arrayOfObject = new Object[length]; int i = 0; for (final Object object : this.elements) { @SuppressWarnings("unchecked") final E element = (E) object; if (condition.isMet(element)) { arrayOfObject[i++] = element; } } @SuppressWarnings("unchecked") final ReadableArrayList<E> copyOf = (ReadableArrayList<E>) listOf(arrayOfObject, i); return copyOf; } @Override public <R> ReadableArrayList<R> map(final Function1<? super E, R> function) { final List<R> list = newArrayList(); for (final Object object : this.elements) { @SuppressWarnings("unchecked") final E element = (E) object; list.add(function.apply(element)); } return new ReadableArrayList<R>(list); } @Override public <R> ReadableArrayList<R> mapSelectively(final Condition1<? super E> condition, final Function1<? super E, R> function) { final List<R> list = newArrayList(); for (final Object object : this.elements) { @SuppressWarnings("unchecked") final E element = (E) object; if (condition.isMet(element)) { list.add(function.apply(element)); } } return new ReadableArrayList<R>(list); } @Override public void forEach(final VoidFunction1<? super E> function) { for (final Object object : this.elements) { @SuppressWarnings("unchecked") final E element = (E) object; function.apply(element); } } @Override public void forEach(final IndexedVoidFunction1<? super E> function) { for (int i = 0; i < length; i++) { @SuppressWarnings("unchecked") final E element = (E) this.elements[i]; function.apply(i, element); } } @Override public void breakableForEach(final BreakableFunction1<? super E> function) { for (final Object object : this.elements) { @SuppressWarnings("unchecked") final E element = (E) object; if (BreakOrContinue.BREAK == function.apply(element)) { break; } } } @Override public void breakableForEach(final IndexedBreakableFunction1<? super E> function) { for (int i = 0; i < length; i++) { @SuppressWarnings("unchecked") final E element = (E) this.elements[i]; if (BreakOrContinue.BREAK == function.apply(i, element)) { return; } } } @Override public Object[] toArray() { final Object[] copyOf = new Object[length]; System.arraycopy(elements, 0, copyOf, 0, length); return copyOf; } @Override public E[] toArray(final E[] elements) { if (length == elements.length) { System.arraycopy(this.elements, 0, elements, 0, length); return elements; } @SuppressWarnings("unchecked") final E[] copyOf = (E[]) Arrays.copyOf(this.elements, length, elements.getClass()); return copyOf; } @Override public E get(final int index) { checkIndex(length, index); @SuppressWarnings("unchecked") final E element = (E) this.elements[index]; return element; } @Override public ReadableList<E> subList(final int fromIndex, final int toIndex) { checkRange(length, fromIndex, toIndex); final int howMany = toIndex - fromIndex; final Object[] subElements = new Object[howMany]; System.arraycopy(this.elements, fromIndex, subElements, 0, howMany); return new ReadableArrayList<E>(subElements); } @Override public <R, F2 extends Function2<? super R, ? super E, R>> R foldLeft(final R startValue, final F2 function) { R result = startValue; for (final Object object : this.elements) { @SuppressWarnings("unchecked") final E element = (E) object; result = function.apply(result, element); } return result; } @Override public <R, F2 extends Function2<? super R, ? super E, R>> Function1<F2, R> foldLeft(final R startValue) { return new Function1<F2, R>() { @Override public R apply(final F2 function) { return foldLeft(startValue, function); } }; } @Override public <R, F2 extends Function2<? super E, ? super R, R>> R foldRight(final R startValue, final F2 function) { R result = startValue; for (int i = length - 1; i >= 0; i--) { @SuppressWarnings("unchecked") final E element = (E) elements[i]; result = function.apply(element, result); } return result; } @Override public <R, F2 extends Function2<? super E, ? super R, R>> Function1<F2, R> foldRight(final R startValue) { return new Function1<F2, R>() { @Override public R apply(final F2 function) { return foldRight(startValue, function); } }; } @Override public E reduce(final Function2<? super E, ? super E, E> function) { if (length == 0) { return null; } @SuppressWarnings("unchecked") E result = (E) this.elements[0]; if (length == 1) { return result; } for (int i = 1; i < length; i++) { @SuppressWarnings("unchecked") final E element = (E) this.elements[i]; result = function.apply(result, element); } return result; } }
/* * 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.cache; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.apache.ignite.transactions.Transaction; import org.apache.ignite.transactions.TransactionIsolation; import org.junit.Test; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheMode.REPLICATED; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC; import static org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED; import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ; /** * */ public class CacheOptimisticTransactionsWithFilterTest extends GridCommonAbstractTest { /** */ private boolean client; /** */ private static final TransactionIsolation[] ISOLATIONS = {REPEATABLE_READ, READ_COMMITTED}; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setClientMode(client); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); startGrids(serversNumber()); client = true; startGrid(serversNumber()); startGrid(serversNumber() + 1); client = false; } /** * @return Number of server nodes. In addition 2 clients are started. */ protected int serversNumber() { return 4; } /** * @throws Exception If failed. */ @Test public void testCasReplace() throws Exception { executeTestForAllCaches(new TestClosure() { @Override public void apply(Ignite ignite, String cacheName) throws Exception { int nodeIdx = ThreadLocalRandom.current().nextInt(serversNumber() + 2); final IgniteCache<Integer, Integer> otherCache = ignite(nodeIdx).cache(cacheName); IgniteCache<Integer, Integer> cache = ignite.cache(cacheName); for (final Integer key : testKeys(cache)) { for (int i = 0; i < 3; i++) { for (TransactionIsolation isolation : ISOLATIONS) { try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.replace(key, 1, 2)); assertNull(cache.get(key)); tx.commit(); } checkCacheData(F.asMap(key, null), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.replace(key, 1, 2)); assertNull(cache.get(key)); tx.rollback(); } checkCacheData(F.asMap(key, null), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.replace(key, 1, 2)); GridTestUtils.runAsync(new Runnable() { @Override public void run() { otherCache.put(key, 1); } }).get(); assertNull(cache.get(key)); tx.commit(); } checkCacheData(F.asMap(key, 1), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.replace(key, 2, 3)); GridTestUtils.runAsync(new Runnable() { @Override public void run() { otherCache.put(key, 10); } }).get(); tx.commit(); } checkCacheData(F.asMap(key, 10), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertTrue(cache.replace(key, 10, 1)); GridTestUtils.runAsync(new Runnable() { @Override public void run() { otherCache.put(key, 2); } }).get(); tx.commit(); } checkCacheData(F.asMap(key, 2), cacheName); cache.remove(key); } } } } }); } /** * @throws Exception If failed. */ @Test public void testPutIfAbsent() throws Exception { executeTestForAllCaches(new TestClosure() { @Override public void apply(Ignite ignite, String cacheName) throws Exception { int nodeIdx = ThreadLocalRandom.current().nextInt(serversNumber() + 2); final IgniteCache<Integer, Integer> otherCache = ignite(nodeIdx).cache(cacheName); IgniteCache<Integer, Integer> cache = ignite.cache(cacheName); for (final Integer key : testKeys(cache)) { for (int i = 0; i < 3; i++) { for (TransactionIsolation isolation : ISOLATIONS) { try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertTrue(cache.putIfAbsent(key, 1)); assertEquals((Integer)1, cache.get(key)); tx.rollback(); } checkCacheData(F.asMap(key, null), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertTrue(cache.putIfAbsent(key, 1)); GridTestUtils.runAsync(new Runnable() { @Override public void run() { otherCache.put(key, 2); } }).get(); tx.commit(); } checkCacheData(F.asMap(key, 2), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.putIfAbsent(key, 3)); GridTestUtils.runAsync(new Runnable() { @Override public void run() { otherCache.remove(key); } }).get(); tx.commit(); } checkCacheData(F.asMap(key, null), cacheName); } } } } }); } /** * @throws Exception If failed. */ @Test public void testReplace() throws Exception { executeTestForAllCaches(new TestClosure() { @Override public void apply(Ignite ignite, String cacheName) throws Exception { int nodeIdx = ThreadLocalRandom.current().nextInt(serversNumber() + 2); final IgniteCache<Integer, Integer> otherCache = ignite(nodeIdx).cache(cacheName); IgniteCache<Integer, Integer> cache = ignite.cache(cacheName); for (final Integer key : testKeys(cache)) { for (int i = 0; i < 3; i++) { for (TransactionIsolation isolation : ISOLATIONS) { try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.replace(key, 1)); assertNull(cache.get(key)); tx.rollback(); } assertNull(cache.get(key)); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.replace(key, 1)); GridTestUtils.runAsync(new Runnable() { @Override public void run() { otherCache.put(key, 2); } }).get(); tx.commit(); } checkCacheData(F.asMap(key, 2), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertTrue(cache.replace(key, 3)); GridTestUtils.runAsync(new Runnable() { @Override public void run() { otherCache.remove(key); } }).get(); tx.commit(); } checkCacheData(F.asMap(key, null), cacheName); } } } } }); } /** * @throws Exception If failed. */ @Test public void testRemoveWithOldValue() throws Exception { executeTestForAllCaches(new TestClosure() { @Override public void apply(Ignite ignite, String cacheName) throws Exception { int nodeIdx = ThreadLocalRandom.current().nextInt(serversNumber() + 2); final IgniteCache<Integer, Integer> otherCache = ignite(nodeIdx).cache(cacheName); IgniteCache<Integer, Integer> cache = ignite.cache(cacheName); for (final Integer key : testKeys(cache)) { for (int i = 0; i < 3; i++) { for (TransactionIsolation isolation : ISOLATIONS) { try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.remove(key, 1)); assertNull(cache.get(key)); tx.commit(); } checkCacheData(F.asMap(key, null), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.remove(key, 1)); assertNull(cache.get(key)); tx.rollback(); } checkCacheData(F.asMap(key, null), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.remove(key, 1)); GridTestUtils.runAsync(new Runnable() { @Override public void run() { otherCache.put(key, 1); } }).get(); assertNull(cache.get(key)); tx.commit(); } checkCacheData(F.asMap(key, 1), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertFalse(cache.remove(key, 2)); GridTestUtils.runAsync(new Runnable() { @Override public void run() { otherCache.put(key, 10); } }).get(); tx.commit(); } checkCacheData(F.asMap(key, 10), cacheName); try (Transaction tx = ignite.transactions().txStart(OPTIMISTIC, isolation)) { assertTrue(cache.remove(key, 10)); GridTestUtils.runAsync(new Runnable() { @Override public void run() { otherCache.put(key, 2); } }).get(); tx.commit(); } checkCacheData(F.asMap(key, 2), cacheName); cache.remove(key); } } } } }); } /** * @param c Closure. * @throws Exception If failed. */ private void executeTestForAllCaches(TestClosure c) throws Exception { for (CacheConfiguration ccfg : cacheConfigurations()) { ignite(0).createCache(ccfg); log.info("Run test for cache [cache=" + ccfg.getCacheMode() + ", backups=" + ccfg.getBackups() + ", near=" + (ccfg.getNearConfiguration() != null) + "]"); ignite(serversNumber() + 1).createNearCache(ccfg.getName(), new NearCacheConfiguration<>()); try { for (int i = 0; i < serversNumber() + 2; i++) { log.info("Run test for node [node=" + i + ", client=" + ignite(i).configuration().isClientMode() + ']'); c.apply(ignite(i), ccfg.getName()); } } finally { ignite(0).destroyCache(ccfg.getName()); } } } /** * @param cache Cache. * @return Test keys. * @throws Exception If failed. */ private List<Integer> testKeys(IgniteCache<Integer, Integer> cache) throws Exception { CacheConfiguration ccfg = cache.getConfiguration(CacheConfiguration.class); List<Integer> keys = new ArrayList<>(); if (!cache.unwrap(Ignite.class).configuration().isClientMode()) { if (ccfg.getCacheMode() == PARTITIONED && serversNumber() > 1) keys.add(nearKey(cache)); keys.add(primaryKey(cache)); if (ccfg.getBackups() != 0 && serversNumber() > 1) keys.add(backupKey(cache)); } else keys.add(nearKey(cache)); return keys; } /** * @return Cache configurations to test. */ private List<CacheConfiguration> cacheConfigurations() { List<CacheConfiguration> cfgs = new ArrayList<>(); cfgs.add(cacheConfiguration(PARTITIONED, 0, false)); cfgs.add(cacheConfiguration(PARTITIONED, 1, false)); cfgs.add(cacheConfiguration(PARTITIONED, 1, true)); cfgs.add(cacheConfiguration(REPLICATED, 0, false)); return cfgs; } /** * @param cacheMode Cache mode. * @param backups Number of backups. * @param nearCache If {@code true} near cache is enabled. * @return Cache configuration. */ private CacheConfiguration<Integer, Integer> cacheConfiguration( CacheMode cacheMode, int backups, boolean nearCache) { CacheConfiguration<Integer, Integer> ccfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME); ccfg.setCacheMode(cacheMode); ccfg.setAtomicityMode(TRANSACTIONAL); ccfg.setWriteSynchronizationMode(FULL_SYNC); if (cacheMode == PARTITIONED) ccfg.setBackups(backups); if (nearCache) ccfg.setNearConfiguration(new NearCacheConfiguration<Integer, Integer>()); return ccfg; } /** * */ static interface TestClosure { /** * @param ignite Node. * @param cacheName Cache name. * @throws Exception If failed. */ public void apply(Ignite ignite, String cacheName) throws Exception; } }
// Copyright 2017 The Bazel Authors. 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.devtools.build.android.desugar; import static com.google.common.truth.Truth.assertThat; import static com.google.devtools.build.android.desugar.runtime.ThrowableExtensionTestUtility.getStrategyClassName; import static com.google.devtools.build.android.desugar.runtime.ThrowableExtensionTestUtility.getTwrStrategyClassNameSpecifiedInSystemProperty; import static com.google.devtools.build.android.desugar.runtime.ThrowableExtensionTestUtility.isMimicStrategy; import static com.google.devtools.build.android.desugar.runtime.ThrowableExtensionTestUtility.isNullStrategy; import static com.google.devtools.build.android.desugar.runtime.ThrowableExtensionTestUtility.isReuseStrategy; import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows; import static org.junit.Assert.fail; import static org.objectweb.asm.ClassWriter.COMPUTE_MAXS; import static org.objectweb.asm.Opcodes.ASM5; import static org.objectweb.asm.Opcodes.INVOKESTATIC; import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; import com.google.devtools.build.android.desugar.io.BitFlags; import com.google.devtools.build.android.desugar.runtime.ThrowableExtension; import com.google.devtools.build.android.desugar.testdata.ClassUsingTryWithResources; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** This is the unit test for {@link TryWithResourcesRewriter} */ @RunWith(JUnit4.class) public class TryWithResourcesRewriterTest { private final DesugaringClassLoader classLoader = new DesugaringClassLoader(ClassUsingTryWithResources.class.getName()); private Class<?> desugaredClass; @Before public void setup() { try { desugaredClass = classLoader.findClass(ClassUsingTryWithResources.class.getName()); } catch (ClassNotFoundException e) { throw new AssertionError(e); } } @Test public void testMethodsAreDesugared() { // verify whether the desugared class is indeed desugared. DesugaredThrowableMethodCallCounter origCounter = countDesugaredThrowableMethodCalls(ClassUsingTryWithResources.class); DesugaredThrowableMethodCallCounter desugaredCounter = countDesugaredThrowableMethodCalls(classLoader.classContent, classLoader); /** * In java9, javac creates a helper method {@code $closeResource(Throwable, AutoCloseable) * to close resources. So, the following number 3 is highly dependant on the version of javac. */ assertThat(hasAutoCloseable(classLoader.classContent)).isFalse(); assertThat(classLoader.numOfTryWithResourcesInvoked.intValue()).isAtLeast(2); assertThat(classLoader.visitedExceptionTypes) .containsExactly( "java/lang/Exception", "java/lang/Throwable", "java/io/UnsupportedEncodingException"); assertDesugaringBehavior(origCounter, desugaredCounter); } @Test public void testCheckSuppressedExceptionsReturningEmptySuppressedExceptions() { { Throwable[] suppressed = ClassUsingTryWithResources.checkSuppressedExceptions(false); assertThat(suppressed).isEmpty(); } try { Throwable[] suppressed = (Throwable[]) desugaredClass .getMethod("checkSuppressedExceptions", boolean.class) .invoke(null, Boolean.FALSE); assertThat(suppressed).isEmpty(); } catch (Exception e) { e.printStackTrace(); throw new AssertionError(e); } } @Test public void testPrintStackTraceOfCaughtException() { { String trace = ClassUsingTryWithResources.printStackTraceOfCaughtException(); assertThat(trace.toLowerCase()).contains("suppressed"); } try { String trace = (String) desugaredClass.getMethod("printStackTraceOfCaughtException").invoke(null); if (isMimicStrategy()) { assertThat(trace.toLowerCase()).contains("suppressed"); } else if (isReuseStrategy()) { assertThat(trace.toLowerCase()).contains("suppressed"); } else if (isNullStrategy()) { assertThat(trace.toLowerCase()).doesNotContain("suppressed"); } else { fail("unexpected desugaring strategy " + ThrowableExtension.getStrategy()); } } catch (Exception e) { e.printStackTrace(); throw new AssertionError(e); } } @Test public void testCheckSuppressedExceptionReturningOneSuppressedException() { { Throwable[] suppressed = ClassUsingTryWithResources.checkSuppressedExceptions(true); assertThat(suppressed).hasLength(1); } try { Throwable[] suppressed = (Throwable[]) desugaredClass .getMethod("checkSuppressedExceptions", boolean.class) .invoke(null, Boolean.TRUE); if (isMimicStrategy()) { assertThat(suppressed).hasLength(1); } else if (isReuseStrategy()) { assertThat(suppressed).hasLength(1); } else if (isNullStrategy()) { assertThat(suppressed).isEmpty(); } else { fail("unexpected desugaring strategy " + ThrowableExtension.getStrategy()); } } catch (Exception e) { e.printStackTrace(); throw new AssertionError(e); } } @Test public void testSimpleTryWithResources() throws Throwable { { RuntimeException expected = assertThrows( RuntimeException.class, () -> ClassUsingTryWithResources.simpleTryWithResources()); assertThat(expected.getClass()).isEqualTo(RuntimeException.class); assertThat(expected.getSuppressed()).hasLength(1); assertThat(expected.getSuppressed()[0].getClass()).isEqualTo(IOException.class); } try { InvocationTargetException e = assertThrows( InvocationTargetException.class, () -> desugaredClass.getMethod("simpleTryWithResources").invoke(null)); throw e.getCause(); } catch (RuntimeException expected) { String expectedStrategyName = getTwrStrategyClassNameSpecifiedInSystemProperty(); assertThat(getStrategyClassName()).isEqualTo(expectedStrategyName); if (isMimicStrategy()) { assertThat(expected.getSuppressed()).isEmpty(); assertThat(ThrowableExtension.getSuppressed(expected)).hasLength(1); assertThat(ThrowableExtension.getSuppressed(expected)[0].getClass()) .isEqualTo(IOException.class); } else if (isReuseStrategy()) { assertThat(expected.getSuppressed()).hasLength(1); assertThat(expected.getSuppressed()[0].getClass()).isEqualTo(IOException.class); assertThat(ThrowableExtension.getSuppressed(expected)[0].getClass()) .isEqualTo(IOException.class); } else if (isNullStrategy()) { assertThat(expected.getSuppressed()).isEmpty(); assertThat(ThrowableExtension.getSuppressed(expected)).isEmpty(); } else { fail("unexpected desugaring strategy " + ThrowableExtension.getStrategy()); } } } private static void assertDesugaringBehavior( DesugaredThrowableMethodCallCounter orig, DesugaredThrowableMethodCallCounter desugared) { assertThat(desugared.countThrowableGetSuppressed()).isEqualTo(orig.countExtGetSuppressed()); assertThat(desugared.countThrowableAddSuppressed()).isEqualTo(orig.countExtAddSuppressed()); assertThat(desugared.countThrowablePrintStackTrace()).isEqualTo(orig.countExtPrintStackTrace()); assertThat(desugared.countThrowablePrintStackTracePrintStream()) .isEqualTo(orig.countExtPrintStackTracePrintStream()); assertThat(desugared.countThrowablePrintStackTracePrintWriter()) .isEqualTo(orig.countExtPrintStackTracePrintWriter()); assertThat(orig.countThrowableGetSuppressed()).isEqualTo(desugared.countExtGetSuppressed()); // $closeResource may be specialized into multiple versions. assertThat(orig.countThrowableAddSuppressed()).isAtMost(desugared.countExtAddSuppressed()); assertThat(orig.countThrowablePrintStackTrace()).isEqualTo(desugared.countExtPrintStackTrace()); assertThat(orig.countThrowablePrintStackTracePrintStream()) .isEqualTo(desugared.countExtPrintStackTracePrintStream()); assertThat(orig.countThrowablePrintStackTracePrintWriter()) .isEqualTo(desugared.countExtPrintStackTracePrintWriter()); if (orig.getSyntheticCloseResourceCount() > 0) { // Depending on the specific javac version, $closeResource(Throwable, AutoCloseable) may not // be there. assertThat(orig.getSyntheticCloseResourceCount()).isEqualTo(1); assertThat(desugared.getSyntheticCloseResourceCount()).isAtLeast(1); } assertThat(desugared.countThrowablePrintStackTracePrintStream()).isEqualTo(0); assertThat(desugared.countThrowablePrintStackTracePrintStream()).isEqualTo(0); assertThat(desugared.countThrowablePrintStackTracePrintWriter()).isEqualTo(0); assertThat(desugared.countThrowableAddSuppressed()).isEqualTo(0); assertThat(desugared.countThrowableGetSuppressed()).isEqualTo(0); } private static DesugaredThrowableMethodCallCounter countDesugaredThrowableMethodCalls( Class<?> klass) { try { ClassReader reader = new ClassReader(klass.getName()); DesugaredThrowableMethodCallCounter counter = new DesugaredThrowableMethodCallCounter(klass.getClassLoader()); reader.accept(counter, 0); return counter; } catch (IOException e) { e.printStackTrace(); fail(e.toString()); return null; } } private static DesugaredThrowableMethodCallCounter countDesugaredThrowableMethodCalls( byte[] content, ClassLoader loader) { ClassReader reader = new ClassReader(content); DesugaredThrowableMethodCallCounter counter = new DesugaredThrowableMethodCallCounter(loader); reader.accept(counter, 0); return counter; } /** Check whether java.lang.AutoCloseable is used as arguments of any method. */ private static boolean hasAutoCloseable(byte[] classContent) { ClassReader reader = new ClassReader(classContent); final AtomicInteger counter = new AtomicInteger(); ClassVisitor visitor = new ClassVisitor(Opcodes.ASM5) { @Override public MethodVisitor visitMethod( int access, String name, String desc, String signature, String[] exceptions) { for (Type argumentType : Type.getArgumentTypes(desc)) { if ("Ljava/lang/AutoCloseable;".equals(argumentType.getDescriptor())) { counter.incrementAndGet(); } } return null; } }; reader.accept(visitor, 0); return counter.get() > 0; } private static class DesugaredThrowableMethodCallCounter extends ClassVisitor { private final ClassLoader classLoader; private final Map<String, AtomicInteger> counterMap; private int syntheticCloseResourceCount; public DesugaredThrowableMethodCallCounter(ClassLoader loader) { super(ASM5); classLoader = loader; counterMap = new HashMap<>(); TryWithResourcesRewriter.TARGET_METHODS .entries() .forEach(entry -> counterMap.put(entry.getKey() + entry.getValue(), new AtomicInteger())); TryWithResourcesRewriter.TARGET_METHODS .entries() .forEach( entry -> counterMap.put( entry.getKey() + TryWithResourcesRewriter.METHOD_DESC_MAP.get(entry.getValue()), new AtomicInteger())); } @Override public MethodVisitor visitMethod( int access, String name, String desc, String signature, String[] exceptions) { if (BitFlags.isSet(access, Opcodes.ACC_SYNTHETIC | Opcodes.ACC_STATIC) && name.equals("$closeResource") && Type.getArgumentTypes(desc).length == 2 && Type.getArgumentTypes(desc)[0].getDescriptor().equals("Ljava/lang/Throwable;")) { ++syntheticCloseResourceCount; } return new InvokeCounter(); } private class InvokeCounter extends MethodVisitor { public InvokeCounter() { super(ASM5); } private boolean isAssignableToThrowable(String owner) { try { Class<?> ownerClass = classLoader.loadClass(owner.replace('/', '.')); return Throwable.class.isAssignableFrom(ownerClass); } catch (ClassNotFoundException e) { throw new AssertionError(e); } } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { String signature = name + desc; if ((opcode == INVOKEVIRTUAL && isAssignableToThrowable(owner)) || (opcode == INVOKESTATIC && Type.getInternalName(ThrowableExtension.class).equals(owner))) { AtomicInteger counter = counterMap.get(signature); if (counter == null) { return; } counter.incrementAndGet(); } } } public int getSyntheticCloseResourceCount() { return syntheticCloseResourceCount; } public int countThrowableAddSuppressed() { return counterMap.get("addSuppressed(Ljava/lang/Throwable;)V").get(); } public int countThrowableGetSuppressed() { return counterMap.get("getSuppressed()[Ljava/lang/Throwable;").get(); } public int countThrowablePrintStackTrace() { return counterMap.get("printStackTrace()V").get(); } public int countThrowablePrintStackTracePrintStream() { return counterMap.get("printStackTrace(Ljava/io/PrintStream;)V").get(); } public int countThrowablePrintStackTracePrintWriter() { return counterMap.get("printStackTrace(Ljava/io/PrintWriter;)V").get(); } public int countExtAddSuppressed() { return counterMap.get("addSuppressed(Ljava/lang/Throwable;Ljava/lang/Throwable;)V").get(); } public int countExtGetSuppressed() { return counterMap.get("getSuppressed(Ljava/lang/Throwable;)[Ljava/lang/Throwable;").get(); } public int countExtPrintStackTrace() { return counterMap.get("printStackTrace(Ljava/lang/Throwable;)V").get(); } public int countExtPrintStackTracePrintStream() { return counterMap.get("printStackTrace(Ljava/lang/Throwable;Ljava/io/PrintStream;)V").get(); } public int countExtPrintStackTracePrintWriter() { return counterMap.get("printStackTrace(Ljava/lang/Throwable;Ljava/io/PrintWriter;)V").get(); } } private static class DesugaringClassLoader extends ClassLoader { private final String targetedClassName; private Class<?> klass; private byte[] classContent; private final Set<String> visitedExceptionTypes = new HashSet<>(); private final AtomicInteger numOfTryWithResourcesInvoked = new AtomicInteger(); public DesugaringClassLoader(String targetedClassName) { super(DesugaringClassLoader.class.getClassLoader()); this.targetedClassName = targetedClassName; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (name.equals(targetedClassName)) { if (klass != null) { return klass; } // desugar the class, and return the desugared one. classContent = desugarTryWithResources(name); klass = defineClass(name, classContent, 0, classContent.length); return klass; } else { return super.findClass(name); } } private byte[] desugarTryWithResources(String className) { try { ClassReader reader = new ClassReader(className); CloseResourceMethodScanner scanner = new CloseResourceMethodScanner(); reader.accept(scanner, ClassReader.SKIP_DEBUG); ClassWriter writer = new ClassWriter(reader, COMPUTE_MAXS); TryWithResourcesRewriter rewriter = new TryWithResourcesRewriter( writer, TryWithResourcesRewriterTest.class.getClassLoader(), visitedExceptionTypes, numOfTryWithResourcesInvoked, scanner.hasCloseResourceMethod()); reader.accept(rewriter, 0); return writer.toByteArray(); } catch (IOException e) { fail(e.toString()); return null; // suppress compiler 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. */ package org.apache.hadoop.hdfs.server.datanode; import org.apache.hadoop.hdfs.AppendTestUtil; import org.apache.hadoop.hdfs.DFSClient; import org.apache.hadoop.hdfs.server.namenode.NameNode; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCK_SIZE_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import com.google.common.collect.Iterators; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.StorageType; import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.StripedFileTestUtil; import org.apache.hadoop.util.AutoCloseableLock; import org.apache.hadoop.hdfs.protocol.DatanodeID; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.DatanodeInfo.DatanodeInfoBuilder; import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.RecoveryInProgressException; import org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolClientSideTranslatorPB; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.ReplicaState; import org.apache.hadoop.hdfs.server.datanode.BlockRecoveryWorker.BlockRecord; import org.apache.hadoop.hdfs.server.datanode.fsdataset.ReplicaOutputStreams; import org.apache.hadoop.hdfs.server.namenode.FSNamesystem; import org.apache.hadoop.hdfs.server.protocol.BlockRecoveryCommand.RecoveringBlock; import org.apache.hadoop.hdfs.server.protocol.BlockRecoveryCommand.RecoveringStripedBlock; import org.apache.hadoop.hdfs.server.protocol.DatanodeCommand; import org.apache.hadoop.hdfs.server.protocol.DatanodeProtocol; import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration; import org.apache.hadoop.hdfs.server.protocol.HeartbeatResponse; import org.apache.hadoop.hdfs.server.protocol.InterDatanodeProtocol; import org.apache.hadoop.hdfs.server.protocol.NNHAStatusHeartbeat; import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols; import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo; import org.apache.hadoop.hdfs.server.protocol.ReplicaRecoveryInfo; import org.apache.hadoop.test.GenericTestUtils; import org.apache.hadoop.test.GenericTestUtils.SleepAnswer; import org.apache.hadoop.util.DataChecksum; import org.apache.hadoop.util.Time; import org.slf4j.event.Level; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.function.Supplier; /** * This tests if sync all replicas in block recovery works correctly. */ public class TestBlockRecovery { private static final Logger LOG = LoggerFactory.getLogger(TestBlockRecovery.class); private static final String DATA_DIR = MiniDFSCluster.getBaseDirectory() + "data"; private DataNode dn; private DataNode spyDN; private BlockRecoveryWorker recoveryWorker; private Configuration conf; private boolean tearDownDone; private final static long RECOVERY_ID = 3000L; private final static String CLUSTER_ID = "testClusterID"; private final static String POOL_ID = "BP-TEST"; private final static InetSocketAddress NN_ADDR = new InetSocketAddress( "localhost", 5020); private final static long BLOCK_ID = 1000L; private final static long GEN_STAMP = 2000L; private final static long BLOCK_LEN = 3000L; private final static long REPLICA_LEN1 = 6000L; private final static long REPLICA_LEN2 = 5000L; private final static ExtendedBlock block = new ExtendedBlock(POOL_ID, BLOCK_ID, BLOCK_LEN, GEN_STAMP); @Rule public TestName currentTestName = new TestName(); private final int cellSize = StripedFileTestUtil.getDefaultECPolicy().getCellSize(); private final int bytesPerChecksum = 512; private final int[][][] blockLengthsSuite = { {{11 * cellSize, 10 * cellSize, 9 * cellSize, 8 * cellSize, 7 * cellSize, 6 * cellSize, 5 * cellSize, 4 * cellSize, 3 * cellSize}, {36 * cellSize}}, {{3 * cellSize, 4 * cellSize, 5 * cellSize, 6 * cellSize, 7 * cellSize, 8 * cellSize, 9 * cellSize, 10 * cellSize, 11 * cellSize}, {36 * cellSize}}, {{11 * cellSize, 7 * cellSize, 6 * cellSize, 5 * cellSize, 4 * cellSize, 2 * cellSize, 9 * cellSize, 10 * cellSize, 11 * cellSize}, {36 * cellSize}}, {{8 * cellSize + bytesPerChecksum, 7 * cellSize + bytesPerChecksum * 2, 6 * cellSize + bytesPerChecksum * 2, 5 * cellSize - bytesPerChecksum * 3, 4 * cellSize - bytesPerChecksum * 4, 3 * cellSize - bytesPerChecksum * 4, 9 * cellSize, 10 * cellSize, 11 * cellSize}, {36 * cellSize}}, }; static { GenericTestUtils.setLogLevel(FSNamesystem.LOG, Level.TRACE); GenericTestUtils.setLogLevel(LOG, Level.TRACE); } private final long TEST_STOP_WORKER_XCEIVER_STOP_TIMEOUT_MILLIS = 1000000000L; /** * Starts an instance of DataNode * @throws IOException */ @Before public void startUp() throws IOException, URISyntaxException { tearDownDone = false; conf = new HdfsConfiguration(); conf.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, DATA_DIR); conf.set(DFSConfigKeys.DFS_DATANODE_ADDRESS_KEY, "0.0.0.0:0"); conf.set(DFSConfigKeys.DFS_DATANODE_HTTP_ADDRESS_KEY, "0.0.0.0:0"); conf.set(DFSConfigKeys.DFS_DATANODE_IPC_ADDRESS_KEY, "0.0.0.0:0"); if (currentTestName.getMethodName().contains("DoesNotHoldLock")) { // This test requires a very long value for the xceiver stop timeout. conf.setLong(DFSConfigKeys.DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_KEY, TEST_STOP_WORKER_XCEIVER_STOP_TIMEOUT_MILLIS); } conf.setInt(CommonConfigurationKeys.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY, 0); FileSystem.setDefaultUri(conf, "hdfs://" + NN_ADDR.getHostName() + ":" + NN_ADDR.getPort()); ArrayList<StorageLocation> locations = new ArrayList<StorageLocation>(); File dataDir = new File(DATA_DIR); FileUtil.fullyDelete(dataDir); dataDir.mkdirs(); StorageLocation location = StorageLocation.parse(dataDir.getPath()); locations.add(location); final DatanodeProtocolClientSideTranslatorPB namenode = mock(DatanodeProtocolClientSideTranslatorPB.class); Mockito.doAnswer(new Answer<DatanodeRegistration>() { @Override public DatanodeRegistration answer(InvocationOnMock invocation) throws Throwable { return (DatanodeRegistration) invocation.getArguments()[0]; } }).when(namenode).registerDatanode( Mockito.any(DatanodeRegistration.class)); when(namenode.versionRequest()).thenReturn(new NamespaceInfo (1, CLUSTER_ID, POOL_ID, 1L)); when(namenode.sendHeartbeat( Mockito.any(), Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt(), Mockito.any(), Mockito.anyBoolean(), Mockito.any(), Mockito.any())) .thenReturn(new HeartbeatResponse( new DatanodeCommand[0], new NNHAStatusHeartbeat(HAServiceState.ACTIVE, 1), null, ThreadLocalRandom.current().nextLong() | 1L)); dn = new DataNode(conf, locations, null, null) { @Override DatanodeProtocolClientSideTranslatorPB connectToNN( InetSocketAddress nnAddr) throws IOException { Assert.assertEquals(NN_ADDR, nnAddr); return namenode; } }; // Trigger a heartbeat so that it acknowledges the NN as active. dn.getAllBpOs().get(0).triggerHeartbeatForTests(); waitForActiveNN(); spyDN = spy(dn); recoveryWorker = new BlockRecoveryWorker(spyDN); } /** * Wait for active NN up to 15 seconds. */ private void waitForActiveNN() { try { GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { return dn.getAllBpOs().get(0).getActiveNN() != null; } }, 1000, 15 * 1000); } catch (TimeoutException e) { // Here its not failing, will again do the assertions for activeNN after // this waiting period and fails there if BPOS has not acknowledged // any NN as active. LOG.warn("Failed to get active NN", e); } catch (InterruptedException e) { LOG.warn("InterruptedException while waiting to see active NN", e); } Assert.assertNotNull("Failed to get ActiveNN", dn.getAllBpOs().get(0).getActiveNN()); } /** * Cleans the resources and closes the instance of datanode * @throws IOException if an error occurred */ @After public void tearDown() throws IOException { if (!tearDownDone && dn != null) { try { dn.shutdown(); } catch(Exception e) { LOG.error("Cannot close: ", e); } finally { File dir = new File(DATA_DIR); if (dir.exists()) Assert.assertTrue( "Cannot delete data-node dirs", FileUtil.fullyDelete(dir)); } tearDownDone = true; } } /** Sync two replicas */ private void testSyncReplicas(ReplicaRecoveryInfo replica1, ReplicaRecoveryInfo replica2, InterDatanodeProtocol dn1, InterDatanodeProtocol dn2, long expectLen) throws IOException { DatanodeInfo[] locs = new DatanodeInfo[]{ mock(DatanodeInfo.class), mock(DatanodeInfo.class)}; RecoveringBlock rBlock = new RecoveringBlock(block, locs, RECOVERY_ID); ArrayList<BlockRecord> syncList = new ArrayList<BlockRecord>(2); BlockRecord record1 = new BlockRecord( DFSTestUtil.getDatanodeInfo("1.2.3.4", "bogus", 1234), dn1, replica1); BlockRecord record2 = new BlockRecord( DFSTestUtil.getDatanodeInfo("1.2.3.4", "bogus", 1234), dn2, replica2); syncList.add(record1); syncList.add(record2); when(dn1.updateReplicaUnderRecovery(any(ExtendedBlock.class), anyLong(), anyLong(), anyLong())).thenReturn("storage1"); when(dn2.updateReplicaUnderRecovery(any(ExtendedBlock.class), anyLong(), anyLong(), anyLong())).thenReturn("storage2"); BlockRecoveryWorker.RecoveryTaskContiguous RecoveryTaskContiguous = recoveryWorker.new RecoveryTaskContiguous(rBlock); RecoveryTaskContiguous.syncBlock(syncList); } /** * BlockRecovery_02.8. * Two replicas are in Finalized state * @throws IOException in case of an error */ @Test(timeout=60000) public void testFinalizedReplicas () throws IOException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } ReplicaRecoveryInfo replica1 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-1, ReplicaState.FINALIZED); ReplicaRecoveryInfo replica2 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-2, ReplicaState.FINALIZED); InterDatanodeProtocol dn1 = mock(InterDatanodeProtocol.class); InterDatanodeProtocol dn2 = mock(InterDatanodeProtocol.class); testSyncReplicas(replica1, replica2, dn1, dn2, REPLICA_LEN1); verify(dn1).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); verify(dn2).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); // two finalized replicas have different length replica1 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-1, ReplicaState.FINALIZED); replica2 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN2, GEN_STAMP-2, ReplicaState.FINALIZED); try { testSyncReplicas(replica1, replica2, dn1, dn2, REPLICA_LEN1); Assert.fail("Two finalized replicas should not have different lengthes!"); } catch (IOException e) { Assert.assertTrue(e.getMessage().startsWith( "Inconsistent size of finalized replicas. ")); } } /** * BlockRecovery_02.9. * One replica is Finalized and another is RBW. * @throws IOException in case of an error */ @Test(timeout=60000) public void testFinalizedRbwReplicas() throws IOException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } // rbw and finalized replicas have the same length ReplicaRecoveryInfo replica1 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-1, ReplicaState.FINALIZED); ReplicaRecoveryInfo replica2 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-2, ReplicaState.RBW); InterDatanodeProtocol dn1 = mock(InterDatanodeProtocol.class); InterDatanodeProtocol dn2 = mock(InterDatanodeProtocol.class); testSyncReplicas(replica1, replica2, dn1, dn2, REPLICA_LEN1); verify(dn1).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); verify(dn2).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); // rbw replica has a different length from the finalized one replica1 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-1, ReplicaState.FINALIZED); replica2 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN2, GEN_STAMP-2, ReplicaState.RBW); dn1 = mock(InterDatanodeProtocol.class); dn2 = mock(InterDatanodeProtocol.class); testSyncReplicas(replica1, replica2, dn1, dn2, REPLICA_LEN1); verify(dn1).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); verify(dn2, never()).updateReplicaUnderRecovery( block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); } /** * BlockRecovery_02.10. * One replica is Finalized and another is RWR. * @throws IOException in case of an error */ @Test(timeout=60000) public void testFinalizedRwrReplicas() throws IOException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } // rbw and finalized replicas have the same length ReplicaRecoveryInfo replica1 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-1, ReplicaState.FINALIZED); ReplicaRecoveryInfo replica2 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-2, ReplicaState.RWR); InterDatanodeProtocol dn1 = mock(InterDatanodeProtocol.class); InterDatanodeProtocol dn2 = mock(InterDatanodeProtocol.class); testSyncReplicas(replica1, replica2, dn1, dn2, REPLICA_LEN1); verify(dn1).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); verify(dn2, never()).updateReplicaUnderRecovery( block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); // rbw replica has a different length from the finalized one replica1 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-1, ReplicaState.FINALIZED); replica2 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN2, GEN_STAMP-2, ReplicaState.RBW); dn1 = mock(InterDatanodeProtocol.class); dn2 = mock(InterDatanodeProtocol.class); testSyncReplicas(replica1, replica2, dn1, dn2, REPLICA_LEN1); verify(dn1).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); verify(dn2, never()).updateReplicaUnderRecovery( block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); } /** * BlockRecovery_02.11. * Two replicas are RBW. * @throws IOException in case of an error */ @Test(timeout=60000) public void testRBWReplicas() throws IOException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } ReplicaRecoveryInfo replica1 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-1, ReplicaState.RBW); ReplicaRecoveryInfo replica2 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN2, GEN_STAMP-2, ReplicaState.RBW); InterDatanodeProtocol dn1 = mock(InterDatanodeProtocol.class); InterDatanodeProtocol dn2 = mock(InterDatanodeProtocol.class); long minLen = Math.min(REPLICA_LEN1, REPLICA_LEN2); testSyncReplicas(replica1, replica2, dn1, dn2, minLen); verify(dn1).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, minLen); verify(dn2).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, minLen); } /** * BlockRecovery_02.12. * One replica is RBW and another is RWR. * @throws IOException in case of an error */ @Test(timeout=60000) public void testRBW_RWRReplicas() throws IOException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } ReplicaRecoveryInfo replica1 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-1, ReplicaState.RBW); ReplicaRecoveryInfo replica2 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-2, ReplicaState.RWR); InterDatanodeProtocol dn1 = mock(InterDatanodeProtocol.class); InterDatanodeProtocol dn2 = mock(InterDatanodeProtocol.class); testSyncReplicas(replica1, replica2, dn1, dn2, REPLICA_LEN1); verify(dn1).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); verify(dn2, never()).updateReplicaUnderRecovery( block, RECOVERY_ID, BLOCK_ID, REPLICA_LEN1); } /** * BlockRecovery_02.13. * Two replicas are RWR. * @throws IOException in case of an error */ @Test(timeout=60000) public void testRWRReplicas() throws IOException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } ReplicaRecoveryInfo replica1 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN1, GEN_STAMP-1, ReplicaState.RWR); ReplicaRecoveryInfo replica2 = new ReplicaRecoveryInfo(BLOCK_ID, REPLICA_LEN2, GEN_STAMP-2, ReplicaState.RWR); InterDatanodeProtocol dn1 = mock(InterDatanodeProtocol.class); InterDatanodeProtocol dn2 = mock(InterDatanodeProtocol.class); long minLen = Math.min(REPLICA_LEN1, REPLICA_LEN2); testSyncReplicas(replica1, replica2, dn1, dn2, minLen); verify(dn1).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, minLen); verify(dn2).updateReplicaUnderRecovery(block, RECOVERY_ID, BLOCK_ID, minLen); } private Collection<RecoveringBlock> initRecoveringBlocks() throws IOException { Collection<RecoveringBlock> blocks = new ArrayList<RecoveringBlock>(1); DatanodeInfo mockOtherDN = DFSTestUtil.getLocalDatanodeInfo(); DatanodeInfo[] locs = new DatanodeInfo[] {new DatanodeInfoBuilder() .setNodeID(dn.getDNRegistrationForBP( block.getBlockPoolId())).build(), mockOtherDN }; RecoveringBlock rBlock = new RecoveringBlock(block, locs, RECOVERY_ID); blocks.add(rBlock); return blocks; } /** * BlockRecoveryFI_05. One DN throws RecoveryInProgressException. * * @throws IOException * in case of an error */ @Test(timeout=60000) public void testRecoveryInProgressException() throws IOException, InterruptedException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } doThrow(new RecoveryInProgressException("Replica recovery is in progress")). when(spyDN).initReplicaRecovery(any(RecoveringBlock.class)); for(RecoveringBlock rBlock: initRecoveringBlocks()){ BlockRecoveryWorker.RecoveryTaskContiguous RecoveryTaskContiguous = recoveryWorker.new RecoveryTaskContiguous(rBlock); BlockRecoveryWorker.RecoveryTaskContiguous spyTask = spy(RecoveryTaskContiguous); spyTask.recover(); verify(spyTask, never()).syncBlock(anyList()); } } /** * BlockRecoveryFI_06. all datanodes throws an exception. * * @throws IOException * in case of an error */ @Test(timeout=60000) public void testErrorReplicas() throws IOException, InterruptedException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } doThrow(new IOException()). when(spyDN).initReplicaRecovery(any(RecoveringBlock.class)); for(RecoveringBlock rBlock: initRecoveringBlocks()){ BlockRecoveryWorker.RecoveryTaskContiguous RecoveryTaskContiguous = recoveryWorker.new RecoveryTaskContiguous(rBlock); BlockRecoveryWorker.RecoveryTaskContiguous spyTask = spy(RecoveryTaskContiguous); try { spyTask.recover(); fail(); } catch(IOException e){ GenericTestUtils.assertExceptionContains("All datanodes failed", e); } verify(spyTask, never()).syncBlock(anyList()); } } /** * BlockRecoveryFI_07. max replica length from all DNs is zero. * * @throws IOException in case of an error */ @Test(timeout=60000) public void testZeroLenReplicas() throws IOException, InterruptedException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } doReturn(new ReplicaRecoveryInfo(block.getBlockId(), 0, block.getGenerationStamp(), ReplicaState.FINALIZED)).when(spyDN). initReplicaRecovery(any(RecoveringBlock.class)); for(RecoveringBlock rBlock: initRecoveringBlocks()){ BlockRecoveryWorker.RecoveryTaskContiguous RecoveryTaskContiguous = recoveryWorker.new RecoveryTaskContiguous(rBlock); BlockRecoveryWorker.RecoveryTaskContiguous spyTask = spy(RecoveryTaskContiguous); spyTask.recover(); } DatanodeProtocol dnP = recoveryWorker.getActiveNamenodeForBP(POOL_ID); verify(dnP).commitBlockSynchronization( block, RECOVERY_ID, 0, true, true, DatanodeID.EMPTY_ARRAY, null); } private List<BlockRecord> initBlockRecords(DataNode spyDN) throws IOException { List<BlockRecord> blocks = new ArrayList<BlockRecord>(1); DatanodeRegistration dnR = dn.getDNRegistrationForBP(block.getBlockPoolId()); BlockRecord blockRecord = new BlockRecord( new DatanodeID(dnR), spyDN, new ReplicaRecoveryInfo(block.getBlockId(), block.getNumBytes(), block.getGenerationStamp(), ReplicaState.FINALIZED)); blocks.add(blockRecord); return blocks; } private final static RecoveringBlock rBlock = new RecoveringBlock(block, null, RECOVERY_ID); /** * BlockRecoveryFI_09. some/all DNs failed to update replicas. * * @throws IOException in case of an error */ @Test(timeout=60000) public void testFailedReplicaUpdate() throws IOException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } doThrow(new IOException()).when(spyDN).updateReplicaUnderRecovery( block, RECOVERY_ID, BLOCK_ID, block.getNumBytes()); try { BlockRecoveryWorker.RecoveryTaskContiguous RecoveryTaskContiguous = recoveryWorker.new RecoveryTaskContiguous(rBlock); RecoveryTaskContiguous.syncBlock(initBlockRecords(spyDN)); fail("Sync should fail"); } catch (IOException e) { e.getMessage().startsWith("Cannot recover "); } } /** * BlockRecoveryFI_10. DN has no ReplicaUnderRecovery. * * @throws IOException in case of an error */ @Test(timeout=60000) public void testNoReplicaUnderRecovery() throws IOException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } dn.data.createRbw(StorageType.DEFAULT, null, block, false); BlockRecoveryWorker.RecoveryTaskContiguous RecoveryTaskContiguous = recoveryWorker.new RecoveryTaskContiguous(rBlock); try { RecoveryTaskContiguous.syncBlock(initBlockRecords(dn)); fail("Sync should fail"); } catch (IOException e) { e.getMessage().startsWith("Cannot recover "); } DatanodeProtocol namenode = recoveryWorker.getActiveNamenodeForBP(POOL_ID); verify(namenode, never()).commitBlockSynchronization( any(ExtendedBlock.class), anyLong(), anyLong(), anyBoolean(), anyBoolean(), any(DatanodeID[].class), any(String[].class)); } /** * BlockRecoveryFI_11. a replica's recovery id does not match new GS. * * @throws IOException in case of an error */ @Test(timeout=60000) public void testNotMatchedReplicaID() throws IOException { if(LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } ReplicaInPipeline replicaInfo = dn.data.createRbw( StorageType.DEFAULT, null, block, false).getReplica(); ReplicaOutputStreams streams = null; try { streams = replicaInfo.createStreams(true, DataChecksum.newDataChecksum(DataChecksum.Type.CRC32, 512)); streams.getChecksumOut().write('a'); dn.data.initReplicaRecovery(new RecoveringBlock(block, null, RECOVERY_ID+1)); BlockRecoveryWorker.RecoveryTaskContiguous RecoveryTaskContiguous = recoveryWorker.new RecoveryTaskContiguous(rBlock); try { RecoveryTaskContiguous.syncBlock(initBlockRecords(dn)); fail("Sync should fail"); } catch (IOException e) { e.getMessage().startsWith("Cannot recover "); } DatanodeProtocol namenode = recoveryWorker.getActiveNamenodeForBP(POOL_ID); verify(namenode, never()).commitBlockSynchronization( any(ExtendedBlock.class), anyLong(), anyLong(), anyBoolean(), anyBoolean(), any(DatanodeID[].class), any(String[].class)); } finally { streams.close(); } } @Test(timeout = 60000) public void testEcRecoverBlocks() throws Throwable { // Stop the Mocked DN started in startup() tearDown(); ErasureCodingPolicy ecPolicy = StripedFileTestUtil.getDefaultECPolicy(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(8).build(); try { cluster.waitActive(); NamenodeProtocols preSpyNN = cluster.getNameNodeRpc(); NamenodeProtocols spyNN = spy(preSpyNN); // Delay completeFile GenericTestUtils.DelayAnswer delayer = new GenericTestUtils.DelayAnswer(LOG); doAnswer(delayer).when(spyNN).complete(anyString(), anyString(), any(), anyLong()); String topDir = "/myDir"; DFSClient client = new DFSClient(null, spyNN, conf, null); Path file = new Path(topDir + "/testECLeaseRecover"); client.mkdirs(topDir, null, false); client.enableErasureCodingPolicy(ecPolicy.getName()); client.setErasureCodingPolicy(topDir, ecPolicy.getName()); OutputStream stm = client.create(file.toString(), true); // write 5MB File AppendTestUtil.write(stm, 0, 1024 * 1024 * 5); final AtomicReference<Throwable> err = new AtomicReference<Throwable>(); Thread t = new Thread() { @Override public void run() { try { stm.close(); } catch (Throwable t) { err.set(t); } } }; t.start(); // Waiting for close to get to latch delayer.waitForCall(); GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { try { return client.getNamenode().recoverLease(file.toString(), client.getClientName()); } catch (IOException e) { return false; } } }, 5000, 24000); delayer.proceed(); } finally { cluster.shutdown(); } } /** * Test to verify the race between finalizeBlock and Lease recovery * * @throws Exception */ @Test(timeout = 20000) public void testRaceBetweenReplicaRecoveryAndFinalizeBlock() throws Exception { tearDown();// Stop the Mocked DN started in startup() Configuration conf = new HdfsConfiguration(); conf.set(DFSConfigKeys.DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_KEY, "1000"); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(1).build(); try { cluster.waitClusterUp(); DistributedFileSystem fs = cluster.getFileSystem(); Path path = new Path("/test"); FSDataOutputStream out = fs.create(path); out.writeBytes("data"); out.hsync(); List<LocatedBlock> blocks = DFSTestUtil.getAllBlocks(fs.open(path)); final LocatedBlock block = blocks.get(0); final DataNode dataNode = cluster.getDataNodes().get(0); final AtomicBoolean recoveryInitResult = new AtomicBoolean(true); Thread recoveryThread = new Thread() { @Override public void run() { try { DatanodeInfo[] locations = block.getLocations(); final RecoveringBlock recoveringBlock = new RecoveringBlock( block.getBlock(), locations, block.getBlock() .getGenerationStamp() + 1); try(AutoCloseableLock lock = dataNode.data.acquireDatasetLock()) { Thread.sleep(2000); dataNode.initReplicaRecovery(recoveringBlock); } } catch (Exception e) { recoveryInitResult.set(false); } } }; recoveryThread.start(); try { out.close(); } catch (IOException e) { Assert.assertTrue("Writing should fail", e.getMessage().contains("are bad. Aborting...")); } finally { recoveryThread.join(); } Assert.assertTrue("Recovery should be initiated successfully", recoveryInitResult.get()); dataNode.updateReplicaUnderRecovery(block.getBlock(), block.getBlock() .getGenerationStamp() + 1, block.getBlock().getBlockId(), block.getBlockSize()); } finally { if (null != cluster) { cluster.shutdown(); cluster = null; } } } /** * DNs report RUR instead of RBW, RWR or FINALIZED. Primary DN expected to * throw an exception. * @throws Exception */ @Test(timeout=60000) public void testRURReplicas() throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("Running " + GenericTestUtils.getMethodName()); } doReturn(new ReplicaRecoveryInfo(block.getBlockId(), block.getNumBytes(), block.getGenerationStamp(), ReplicaState.RUR)).when(spyDN). initReplicaRecovery(any(RecoveringBlock.class)); boolean exceptionThrown = false; try { for (RecoveringBlock rBlock : initRecoveringBlocks()) { BlockRecoveryWorker.RecoveryTaskContiguous RecoveryTaskContiguous = recoveryWorker.new RecoveryTaskContiguous(rBlock); BlockRecoveryWorker.RecoveryTaskContiguous spyTask = spy(RecoveryTaskContiguous); spyTask.recover(); } } catch (IOException e) { // expect IOException to be thrown here e.printStackTrace(); assertTrue("Wrong exception was thrown: " + e.getMessage(), e.getMessage().contains("Found 1 replica(s) for block " + block + " but none is in RWR or better state")); exceptionThrown = true; } finally { assertTrue(exceptionThrown); } } @Test(timeout=60000) public void testSafeLength() throws Exception { // hard coded policy to work with hard coded test suite ErasureCodingPolicy ecPolicy = StripedFileTestUtil.getDefaultECPolicy(); RecoveringStripedBlock rBlockStriped = new RecoveringStripedBlock(rBlock, new byte[9], ecPolicy); BlockRecoveryWorker recoveryWorker = new BlockRecoveryWorker(dn); BlockRecoveryWorker.RecoveryTaskStriped recoveryTask = recoveryWorker.new RecoveryTaskStriped(rBlockStriped); for (int i = 0; i < blockLengthsSuite.length; i++) { int[] blockLengths = blockLengthsSuite[i][0]; int safeLength = blockLengthsSuite[i][1][0]; Map<Long, BlockRecord> syncList = new HashMap<>(); for (int id = 0; id < blockLengths.length; id++) { ReplicaRecoveryInfo rInfo = new ReplicaRecoveryInfo(id, blockLengths[id], 0, null); syncList.put((long) id, new BlockRecord(null, null, rInfo)); } Assert.assertEquals("BLOCK_LENGTHS_SUITE[" + i + "]", safeLength, recoveryTask.getSafeLength(syncList)); } } private static class TestStopWorkerSemaphore { final Semaphore sem; final AtomicBoolean gotInterruption = new AtomicBoolean(false); TestStopWorkerSemaphore() { this.sem = new Semaphore(0); } /** * Attempt to acquire a sempahore within a given timeout. * * This is useful for unit tests where we need to ignore InterruptedException * when attempting to take a semaphore, but still want to honor the overall * test timeout. * * @param timeoutMs The timeout in miliseconds. */ private void uninterruptiblyAcquire(long timeoutMs) throws Exception { long startTimeMs = Time.monotonicNow(); while (true) { long remTime = startTimeMs + timeoutMs - Time.monotonicNow(); if (remTime < 0) { throw new RuntimeException("Failed to acquire the semaphore within " + timeoutMs + " milliseconds."); } try { if (sem.tryAcquire(1, remTime, TimeUnit.MILLISECONDS)) { return; } } catch (InterruptedException e) { gotInterruption.set(true); } } } } private interface TestStopWorkerRunnable { /** * Return the name of the operation that this runnable performs. */ String opName(); /** * Perform the operation. */ void run(RecoveringBlock recoveringBlock) throws Exception; } @Test(timeout=90000) public void testInitReplicaRecoveryDoesNotHoldLock() throws Exception { testStopWorker(new TestStopWorkerRunnable() { @Override public String opName() { return "initReplicaRecovery"; } @Override public void run(RecoveringBlock recoveringBlock) throws Exception { try { spyDN.initReplicaRecovery(recoveringBlock); } catch (Exception e) { if (!e.getMessage().contains("meta does not exist")) { throw e; } } } }); } @Test(timeout=90000) public void testRecoverAppendDoesNotHoldLock() throws Exception { testStopWorker(new TestStopWorkerRunnable() { @Override public String opName() { return "recoverAppend"; } @Override public void run(RecoveringBlock recoveringBlock) throws Exception { try { ExtendedBlock extBlock = recoveringBlock.getBlock(); spyDN.getFSDataset().recoverAppend(extBlock, extBlock.getGenerationStamp() + 1, extBlock.getNumBytes()); } catch (Exception e) { if (!e.getMessage().contains( "Corrupted replica ReplicaBeingWritten")) { throw e; } } } }); } @Test(timeout=90000) public void testRecoverCloseDoesNotHoldLock() throws Exception { testStopWorker(new TestStopWorkerRunnable() { @Override public String opName() { return "recoverClose"; } @Override public void run(RecoveringBlock recoveringBlock) throws Exception { try { ExtendedBlock extBlock = recoveringBlock.getBlock(); spyDN.getFSDataset().recoverClose(extBlock, extBlock.getGenerationStamp() + 1, extBlock.getNumBytes()); } catch (Exception e) { if (!e.getMessage().contains( "Corrupted replica ReplicaBeingWritten")) { throw e; } } } }); } /** * Test that an FsDatasetImpl operation does not hold the lock for an * unreasonable amount of time if a writer is taking a long time to stop. */ private void testStopWorker(final TestStopWorkerRunnable tswr) throws Exception { LOG.debug("Running " + currentTestName.getMethodName()); // We need a long value for the data xceiver stop timeout. // Otherwise the timeout will trigger, and we will not have tested that // thread join was done locklessly. Assert.assertEquals( TEST_STOP_WORKER_XCEIVER_STOP_TIMEOUT_MILLIS, dn.getDnConf().getXceiverStopTimeout()); final TestStopWorkerSemaphore progressParent = new TestStopWorkerSemaphore(); final TestStopWorkerSemaphore terminateSlowWriter = new TestStopWorkerSemaphore(); final AtomicReference<String> failure = new AtomicReference<String>(null); Collection<RecoveringBlock> recoveringBlocks = initRecoveringBlocks(); final RecoveringBlock recoveringBlock = Iterators.get(recoveringBlocks.iterator(), 0); final ExtendedBlock block = recoveringBlock.getBlock(); Thread slowWriterThread = new Thread(new Runnable() { @Override public void run() { try { // Register this thread as the writer for the recoveringBlock. LOG.debug("slowWriter creating rbw"); ReplicaHandler replicaHandler = spyDN.data.createRbw(StorageType.DISK, null, block, false); replicaHandler.close(); LOG.debug("slowWriter created rbw"); // Tell the parent thread to start progressing. progressParent.sem.release(); terminateSlowWriter.uninterruptiblyAcquire(60000); LOG.debug("slowWriter exiting"); } catch (Throwable t) { LOG.error("slowWriter got exception", t); failure.compareAndSet(null, "slowWriter got exception " + t.getMessage()); } } }); // Start the slow worker thread and wait for it to take ownership of the // ReplicaInPipeline slowWriterThread.start(); progressParent.uninterruptiblyAcquire(60000); // Start a worker thread which will attempt to stop the writer. Thread stopWriterThread = new Thread(new Runnable() { @Override public void run() { try { LOG.debug("initiating " + tswr.opName()); tswr.run(recoveringBlock); LOG.debug("finished " + tswr.opName()); } catch (Throwable t) { LOG.error("stopWriterThread got unexpected exception for " + tswr.opName(), t); failure.compareAndSet(null, "stopWriterThread got unexpected " + "exception for " + tswr.opName() + ": " + t.getMessage()); } } }); stopWriterThread.start(); while (!terminateSlowWriter.gotInterruption.get()) { // Wait until stopWriterThread attempts to stop our slow writer by sending // it an InterruptedException. Thread.sleep(1); } // We know that stopWriterThread is in the process of joining our slow // writer. It must not hold the lock during this operation. // In order to test that it does not, we attempt to do an operation that // requires the lock-- getReplicaString. spyDN.getFSDataset().getReplicaString( recoveringBlock.getBlock().getBlockPoolId(), recoveringBlock.getBlock().getBlockId()); // Tell the slow writer to exit, and then wait for all threads to join. terminateSlowWriter.sem.release(); slowWriterThread.join(); stopWriterThread.join(); // Check that our worker threads exited cleanly. This is not checked by the // unit test framework, so we have to do it manually here. String failureReason = failure.get(); if (failureReason != null) { Assert.fail("Thread failure: " + failureReason); } } /** * Test for block recovery taking longer than the heartbeat interval. */ @Test(timeout = 300000L) public void testRecoverySlowerThanHeartbeat() throws Exception { tearDown(); // Stop the Mocked DN started in startup() SleepAnswer delayer = new SleepAnswer(3000, 6000); testRecoveryWithDatanodeDelayed(delayer); } /** * Test for block recovery timeout. All recovery attempts will be delayed * and the first attempt will be lost to trigger recovery timeout and retry. */ @Test(timeout = 300000L) public void testRecoveryTimeout() throws Exception { tearDown(); // Stop the Mocked DN started in startup() final Random r = new Random(); // Make sure first commitBlockSynchronization call from the DN gets lost // for the recovery timeout to expire and new recovery attempt // to be started. SleepAnswer delayer = new SleepAnswer(3000) { private final AtomicBoolean callRealMethod = new AtomicBoolean(); @Override public Object answer(InvocationOnMock invocation) throws Throwable { boolean interrupted = false; try { Thread.sleep(r.nextInt(3000) + 6000); } catch (InterruptedException ie) { interrupted = true; } try { if (callRealMethod.get()) { return invocation.callRealMethod(); } callRealMethod.set(true); return null; } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } }; testRecoveryWithDatanodeDelayed(delayer); } private void testRecoveryWithDatanodeDelayed( GenericTestUtils.SleepAnswer recoveryDelayer) throws Exception { Configuration configuration = new HdfsConfiguration(); configuration.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(configuration) .numDataNodes(2).build(); cluster.waitActive(); final FSNamesystem ns = cluster.getNamesystem(); final NameNode nn = cluster.getNameNode(); final DistributedFileSystem dfs = cluster.getFileSystem(); cluster.setBlockRecoveryTimeout(TimeUnit.SECONDS.toMillis(15)); // Create a file and never close the output stream to trigger recovery FSDataOutputStream out = dfs.create(new Path("/testSlowRecovery"), (short) 2); out.write(AppendTestUtil.randomBytes(0, 4096)); out.hsync(); List<DataNode> dataNodes = cluster.getDataNodes(); for (DataNode datanode : dataNodes) { DatanodeProtocolClientSideTranslatorPB nnSpy = InternalDataNodeTestUtils.spyOnBposToNN(datanode, nn); Mockito.doAnswer(recoveryDelayer).when(nnSpy). commitBlockSynchronization( Mockito.any(ExtendedBlock.class), Mockito.anyInt(), Mockito.anyLong(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.any(DatanodeID[].class), Mockito.any(String[].class)); } // Make sure hard lease expires to trigger replica recovery cluster.setLeasePeriod(100L, 100L); // Wait for recovery to succeed GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { return ns.getCompleteBlocksTotal() > 0; } }, 300, 300000); } finally { if (cluster != null) { cluster.shutdown(); } } } /** * Test that block will be recovered even if there are less than the * specified minReplication datanodes involved in its recovery. * * Check that, after recovering, the block will be successfully replicated. */ @Test(timeout = 300000L) public void testRecoveryWillIgnoreMinReplication() throws Exception { tearDown(); // Stop the Mocked DN started in startup() final int blockSize = 4096; final int numReplicas = 3; final String filename = "/testIgnoreMinReplication"; final Path filePath = new Path(filename); Configuration configuration = new HdfsConfiguration(); configuration.setInt(DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 2000); configuration.setInt(DFS_NAMENODE_REPLICATION_MIN_KEY, 2); configuration.setLong(DFS_BLOCK_SIZE_KEY, blockSize); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(configuration).numDataNodes(5) .build(); cluster.waitActive(); final DistributedFileSystem dfs = cluster.getFileSystem(); final FSNamesystem fsn = cluster.getNamesystem(); // Create a file and never close the output stream to trigger recovery FSDataOutputStream out = dfs.create(filePath, (short) numReplicas); out.write(AppendTestUtil.randomBytes(0, blockSize)); out.hsync(); DFSClient dfsClient = new DFSClient(new InetSocketAddress("localhost", cluster.getNameNodePort()), configuration); LocatedBlock blk = dfsClient.getNamenode(). getBlockLocations(filename, 0, blockSize). getLastLocatedBlock(); // Kill 2 out of 3 datanodes so that only 1 alive, thus < minReplication List<DatanodeInfo> dataNodes = Arrays.asList(blk.getLocations()); assertEquals(dataNodes.size(), numReplicas); for (DatanodeInfo dataNode : dataNodes.subList(0, numReplicas - 1)) { cluster.stopDataNode(dataNode.getName()); } GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { return fsn.getNumDeadDataNodes() == 2; } }, 300, 300000); // Make sure hard lease expires to trigger replica recovery cluster.setLeasePeriod(100L, 100L); // Wait for recovery to succeed GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { try { return dfs.isFileClosed(filePath); } catch (IOException e) {} return false; } }, 300, 300000); // Wait for the block to be replicated DFSTestUtil.waitForReplication(cluster, DFSTestUtil.getFirstBlock( dfs, filePath), 1, numReplicas, 0); } finally { if (cluster != null) { cluster.shutdown(); } } } }
/* Copyright 2019 The TensorFlow Authors. 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.tensorflow; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.tensorflow.EagerSession.ResourceCleanupStrategy; @RunWith(JUnit4.class) public class EagerSessionTest { @Test public void closeSessionTwiceDoesNotFail() { try (EagerSession s = EagerSession.create()) { s.close(); } } @Test public void cleanupResourceOnSessionClose() { TestReference ref; try (EagerSession s = EagerSession.options() .resourceCleanupStrategy(ResourceCleanupStrategy.ON_SESSION_CLOSE) .build()) { ref = new TestReference(s, new Object()); assertFalse(ref.isDeleted()); // check that reaching safe point did not release resources buildOp(s); assertFalse(ref.isDeleted()); } assertTrue(ref.isDeleted()); } @Test public void cleanupResourceOnSafePoints() { TestGarbageCollectorQueue gcQueue = new TestGarbageCollectorQueue(); try (EagerSession s = EagerSession.options() .resourceCleanupStrategy(ResourceCleanupStrategy.ON_SAFE_POINTS) .buildForGcTest(gcQueue)) { TestReference ref = new TestReference(s, new Object()); assertFalse(ref.isDeleted()); // garbage collecting the reference won't release until we reached safe point gcQueue.collect(ref); assertFalse(ref.isDeleted()); buildOp(s); // safe point assertTrue(ref.isDeleted()); assertTrue(gcQueue.isEmpty()); } } @Test public void cleanupResourceInBackground() { TestGarbageCollectorQueue gcQueue = new TestGarbageCollectorQueue(); try (EagerSession s = EagerSession.options() .resourceCleanupStrategy(ResourceCleanupStrategy.IN_BACKGROUND) .buildForGcTest(gcQueue)) { TestReference ref = new TestReference(s, new Object()); assertFalse(ref.isDeleted()); gcQueue.collect(ref); sleep(50); // allow some time to the background thread for cleaning up resources assertTrue(ref.isDeleted()); assertTrue(gcQueue.isEmpty()); } } @Test public void clearedResourcesAreNotCleanedUp() { TestReference ref; try (EagerSession s = EagerSession.create()) { ref = new TestReference(s, new Object()); ref.clear(); } assertFalse(ref.isDeleted()); } @Test public void buildingOpWithClosedSessionFails() { EagerSession s = EagerSession.create(); s.close(); try { buildOp(s); fail(); } catch (IllegalStateException e) { // ok } } @Test public void addingReferenceToClosedSessionFails() { EagerSession s = EagerSession.create(); s.close(); try { new TestReference(s, new Object()); fail(); } catch (IllegalStateException e) { // ok } } @Test public void defaultSession() throws Exception { EagerSession.Options options = EagerSession.options().resourceCleanupStrategy(ResourceCleanupStrategy.ON_SESSION_CLOSE); EagerSession.initDefault(options); EagerSession session = EagerSession.getDefault(); assertNotNull(session); assertEquals(ResourceCleanupStrategy.ON_SESSION_CLOSE, session.resourceCleanupStrategy()); try { EagerSession.initDefault(options); fail(); } catch (IllegalStateException e) { // expected } try { session.close(); fail(); } catch (IllegalStateException e) { // expected } } private static class TestReference extends EagerSession.NativeReference { TestReference(EagerSession session, Object referent) { super(session, referent); } @Override void delete() { if (!deleted.compareAndSet(false, true)) { fail("Reference was deleted more than once"); } } boolean isDeleted() { return deleted.get(); } private final AtomicBoolean deleted = new AtomicBoolean(); } private static class TestGarbageCollectorQueue extends ReferenceQueue<Object> { @Override public Reference<? extends Object> poll() { return garbage.poll(); } @Override public Reference<? extends Object> remove() throws InterruptedException { return garbage.take(); } @Override public Reference<? extends Object> remove(long timeout) throws IllegalArgumentException, InterruptedException { return garbage.poll(timeout, TimeUnit.MILLISECONDS); } void collect(TestReference ref) { garbage.add(ref); } boolean isEmpty() { return garbage.isEmpty(); } private final BlockingQueue<TestReference> garbage = new LinkedBlockingQueue<>(); } private static void buildOp(EagerSession s) { // Creating an operation is a safe point for resource cleanup try { s.opBuilder("Const", "Const"); } catch (UnsupportedOperationException e) { // TODO (karlllessard) remove this exception catch when EagerOperationBuilder is implemented } } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { } } }
/* * 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 com.jtex.plot; import com.jtex.arrays.Array1D; import com.jtex.geom.grid.S2Grid; import com.jtex.geom.projection.Projector; import com.jtex.geom.projection.SchmidtProjection; import com.jtex.geom.projection.SphericalProjection; import com.jtex.geom.Vec2; import com.jtex.geom.Vec3; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.util.Arrays; import javax.swing.JComponent; /** * * @author hios */ public class SphericalCanvasScatter extends SphericalCanvas implements ColorMapCanvas, ScatterCanvas { public static void main(String[] args) { // makeColorMap(); // vec3 v = vec3.rand(1000); S2Grid g = S2Grid.equispacedS2Grid(Math.toRadians(2.5), 0, Math.PI / 2, 0, 2 * Math.PI, false); Vec3 v = g.toVec3(); Array1D d = Array1D.linspace(0, Math.PI, v.size()); // vec3 v = vec3.concat(vec3.yvector()); // JComponent plot = plot(v,); ScatterOptions scatterOptions = new ScatterOptions(); scatterOptions.setMarker(Shapes.Named.CIRCLE); scatterOptions.setMarkerSize(2); // scatterOptions.setMarkerFaceColor(Color.white); long nanoTime = System.nanoTime(); // scatterOptions.setMarkerEdgeColor(Color.darkGray); // JComponent plot = Plotter.plot(v, Array1D.linspace(0, 100, v.size()), scatterOptions); JComponent plot = Plotter.plot(v, d, scatterOptions); System.out.println("e1 : " + (System.nanoTime() - nanoTime) / 1e9); System.out.println(v.size()); Plotter.show(plot); } private int sz = 760; Vec3 v; Array1D data; int[] datam; ColorMap cmp; double gx[]; double gy[]; double dmin, dmax; ScatterOptions options; public SphericalCanvasScatter(Vec3 v, Array1D data, ScatterOptions opts) { this(v, data, new SchmidtProjection(), new SphericalBounds(), new PlotAnnotation(data.max(), data.min()), opts); } public SphericalCanvasScatter(Vec3 v, Array1D data, String tr, String br) { this(v, data, new SchmidtProjection(), new SphericalBounds(Math.PI / 2, 2 * Math.PI), new PlotAnnotation(data.max(), data.min(), tr, br), new ScatterOptions()); } SphericalCanvasScatter(Plotter.PlotGrid grid, Array1D f, Projector projector, PlotAnnotation annon) { this(grid.getR(), f, projector, grid.getBounds(), annon, new ScatterOptions()); } public SphericalCanvasScatter(Vec3 v, Array1D data, Projector projector, SphericalBounds bounds, PlotAnnotation annon, ScatterOptions options) { this(v, data, projector, bounds, annon, options, Plotter.getDefaultColorMap()); } public SphericalCanvasScatter(Vec3 v, Array1D data, Projector projector, SphericalBounds bounds, PlotAnnotation annon, ScatterOptions options, ColorMap cmap) { super(projector, bounds); this.v = v; this.data = data; this.options = options; setAnnotation(annon); setColorMap(cmap); init(); } private void init() { Vec2 projection = getProjector().project(v); gx = projection.x(); gy = projection.y(); double xmin = getXmin(); double ymin = getYmin(); for (int i = 0; i < gx.length; i++) { gx[i] -= xmin; gy[i] -= ymin; } dmin = data.nanmin(); dmax = data.nanmax(); setCLim(dmin, dmax); } public void setScatterOption(ScatterOptions options) { this.options = options; // canvas = renderCanvas((int) (sz * getRatio())); } @Override public ScatterOptions getScatterOptions() { return this.options; } @Override public void setScatterOptions(ScatterOptions options) { this.options = options; } @Override protected BufferedImage renderCanvas(int sz) { if (sz < 50) { sz = 50; } double intend = 2D; double scale = Math.min((sz - 2 * intend) / (getDx()), (sz - 2 * intend) / (getDy())); double[] X = new double[gx.length]; double[] Y = new double[gx.length]; for (int i = 0; i < Y.length; i++) { X[i] = gx[i] * scale + intend; Y[i] = gy[i] * scale + intend; } int sh = (int) (sz / getRatio()); // System.out.println(sz + " " + sh); BufferedImage canvas = new BufferedImage(sz, sh, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = (Graphics2D) canvas.getGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); double sr = 2 * getDr() * scale; Ellipse2D.Double eli2 = new Ellipse2D.Double(intend - getXmin() * scale - sr / 2, intend - getYmin() * scale - sr / 2, sr, sr); if (getProjector() instanceof SphericalProjection) { g2d.clip(eli2); } Stroke lineStroke = options.getLineStroke(); if (lineStroke != null) { Line2D.Double line = new Line2D.Double(); g2d.setStroke(lineStroke); g2d.setColor(options.getLineColor()); for (int i = 0; i < gx.length - 1; i++) { line.setLine(X[i], Y[i], X[i + 1], Y[i + 1]); g2d.draw(line); } } double ms = 5D * options.getMarkerSize() * Math.sqrt(getRatio()); Shape shp = options.getMarker().create((float) ms); if (shp != null) { Color face = options.getMarkerFaceColor(); Color edge = options.getMarkerEdgeColor(); int nx = (int) (ms * 2.5D); BufferedImage markerImage = new BufferedImage(nx, nx, BufferedImage.TYPE_INT_ARGB); Graphics2D markerGraphics = (Graphics2D) markerImage.getGraphics(); AffineTransform markerTransform = AffineTransform.getTranslateInstance(nx / 2, nx / 2); if (face != null) { markerGraphics.setColor(face); } markerGraphics.fill(markerTransform.createTransformedShape(shp)); if (edge != null) { markerGraphics.setColor(edge); } markerGraphics.draw(markerTransform.createTransformedShape(shp)); DataBuffer usedBuffer = markerImage.getRaster().getDataBuffer(); int[] idx = new int[nx * nx]; int count = 0; for (int j = 0; j < nx * nx; j++) { if (usedBuffer.getElem(j) != 0) { idx[count++] = j; } } idx = Arrays.copyOf(idx, count); double shiftx = nx / 2; for (int i = 0; i < gx.length; i++) { if (datam != null) { int rgb = cmp.getColor(datam[i]).getRGB(); for (int j : idx) { usedBuffer.setElem(j, rgb); } } g2d.drawImage(markerImage, AffineTransform.getTranslateInstance(X[i] - shiftx, Y[i] - shiftx), null); } } if (getProjector() instanceof SphericalProjection) { g2d.setColor(Color.black); g2d.setStroke(new BasicStroke(1f)); g2d.setClip(null); g2d.draw(eli2); } return canvas; } @Override public double getCLimMin() { return dmin; } @Override public double getCLimMax() { return dmax; } @Override public void setCLim(double cmin, double cmax) { if (dmax - dmin == 0) { datam = null; } else { datam = data.minus(cmin).divided((cmax - cmin) / (cmp.size() - 1)).toIntArray(); for (int i = 0; i < datam.length; i++) { if (datam[i] < 0) { datam[i] = 0; } else if (datam[i] > cmp.size()) { datam[i] = cmp.size(); } } } // canvas = renderCanvas((int) (sz * getRatio())); } @Override public void setColorMap(ColorMap cmp) { this.cmp = cmp; } }
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */ /* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package de.upb.s2cx.parser; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public class SimpleCharStream { /** Whether parser is static. */ public static final boolean staticFlag = false; int bufsize; int available; int tokenBegin; /** Position in buffer. */ public int bufpos = -1; protected int bufline[]; protected int bufcolumn[]; protected int column = 0; protected int line = 1; protected boolean prevCharIsCR = false; protected boolean prevCharIsLF = false; protected java.io.Reader inputStream; protected char[] buffer; protected int maxNextCharInd = 0; protected int inBuf = 0; protected int tabSize = 8; protected void setTabSize(int i) { tabSize = i; } protected int getTabSize(int i) { return tabSize; } protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } /** Start. */ public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /** Read a character. */ public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; } @Deprecated /** * @deprecated * @see #getEndColumn */ public int getColumn() { return bufcolumn[bufpos]; } @Deprecated /** * @deprecated * @see #getEndLine */ public int getLine() { return bufline[bufpos]; } /** Get token end column number. */ public int getEndColumn() { return bufcolumn[bufpos]; } /** Get token end line number. */ public int getEndLine() { return bufline[bufpos]; } /** Get token beginning column number. */ public int getBeginColumn() { return bufcolumn[tokenBegin]; } /** Get token beginning line number. */ public int getBeginLine() { return bufline[tokenBegin]; } /** Backup a number of characters. */ public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { this(dstream, encoding, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { this(dstream, encoding, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Get token literal value. */ public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } /** Get the suffix. */ public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /** Reset buffer when finished. */ public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } /* JavaCC - OriginalChecksum=a52bfc607ea452ec0d4f196f0717bb72 (do not edit this line) */
/* * #! * Ontopia DB2TM * #- * Copyright (C) 2001 - 2013 The Ontopia 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 net.ontopia.topicmaps.db2tm; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.jsp.PageContext; import net.ontopia.infoset.core.LocatorIF; import net.ontopia.topicmaps.core.TMObjectIF; import net.ontopia.topicmaps.core.TopicIF; import net.ontopia.topicmaps.core.TopicMapIF; import org.apache.commons.lang3.StringUtils; /** * INTERNAL: Helper class used by DB2TM internals. */ public class Utils { private Utils() { } /** * INTERNAL: Helper method for maintaining a relation mapping * instance throughout a page context. */ public static RelationMapping getRelationMapping(PageContext ctxt) { RelationMapping db = (RelationMapping) ctxt.getAttribute("RelationMapping", PageContext.APPLICATION_SCOPE); if (db == null) { db = new RelationMapping(); ctxt.setAttribute("RelationMapping", db, PageContext.APPLICATION_SCOPE); } return db; } /** * INTERNAL: Returns a map where the keys are data sources and each * entry is a collection of their individual relations. Before * returning all relations will be verified against the relations * declared in the mapping. If relations are missing an error is * issued indicating which ones are missing. */ public static Map<DataSourceIF, Collection<Relation>> verifyRelationsForMapping(RelationMapping rmapping) { // build return value Collection<DataSourceIF> ds = rmapping.getDataSources(); Map<DataSourceIF, Collection<Relation>> foundRelations = new HashMap<DataSourceIF, Collection<Relation>>(ds.size()); for (DataSourceIF datasource : ds) { foundRelations.put(datasource, datasource.getRelations()); } // detect missing relations List<Relation> missingRelations = new ArrayList<Relation>(); for (Relation relation : rmapping.getRelations()) { boolean relationMapped = false; for (Collection<Relation> frels : foundRelations.values()) { if (frels.contains(relation)) { relationMapped = true; break; }; } if (!relationMapped) missingRelations.add(relation); } // complain if found mappings without relations int size = missingRelations.size(); if (size > 1) { String[] relnames = new String[size]; for (int i=0; i < relnames.length; i++) { relnames[i] = missingRelations.get(i).getName(); } throw new DB2TMException("No relations found for mappings: " + StringUtils.join(relnames, ", ")); } else if (size == 1) { throw new DB2TMException("No relation found for mapping: " + missingRelations.get(0).getName()); } return foundRelations; } // --------------------------------------------------------------------------- // Utility methods // --------------------------------------------------------------------------- protected static TopicIF getTopic(String id, Context ctx) { // Note: null values or empty strings are considered dead if (isValueEmpty(id)) return null; if (id.charAt(0) == '#') { String entity_id = id.substring(1); return (TopicIF)ctx.getEntityObjectById(entity_id); } TopicMapIF tm = ctx.getTopicMap(); // resolve reference int loctype; LocatorIF loc; int cix = id.indexOf(':'); if (cix >= 1) { // prefix reference String prefix_id = id.substring(0, cix); Prefix prefix = ctx.getMapping().getPrefix(prefix_id); if (prefix == null) throw new DB2TMConfigException("Unknown prefix: '" + prefix_id + "' (value='" + id + "')"); String relloc = prefix.getLocator() + id.substring(cix + 1); if (ctx.getBaseLocator() == null) { throw new DB2TMException("Cannot resolve locator '" + relloc + "', missing a base locator"); } loc = ctx.getBaseLocator().resolveAbsolute(relloc); loctype = prefix.getType(); } else { throw new DB2TMConfigException("Illegal prefixed value: '" + id + "'"); } // look up topic by identifier switch (loctype) { case Prefix.TYPE_SUBJECT_IDENTIFIER: TopicIF topic = tm.getTopicBySubjectIdentifier(loc); if (topic != null) return topic; break; case Prefix.TYPE_ITEM_IDENTIFIER: TMObjectIF tmobject = tm.getObjectByItemIdentifier(loc); if (tmobject != null) return (TopicIF) tmobject; break; case Prefix.TYPE_SUBJECT_LOCATOR: topic = tm.getTopicBySubjectLocator(loc); if (topic != null) return topic; break; } // create new topic TopicIF newtopic = ctx.getBuilder().makeTopic(); ctx.registerNewObject(newtopic); // add identity switch (loctype) { case Prefix.TYPE_SUBJECT_IDENTIFIER: newtopic.addSubjectIdentifier(loc); break; case Prefix.TYPE_ITEM_IDENTIFIER: newtopic.addItemIdentifier(loc); break; case Prefix.TYPE_SUBJECT_LOCATOR: newtopic.addSubjectLocator(loc); break; } return newtopic; } protected static String getValue(Relation relation, Entity entity, Field field, String[] tuple, Context ctx) { return field.getValue(tuple); } protected static boolean isValueEmpty(String value) { return (value == null || value.equals("")); } protected static LocatorIF getLocator(Relation relation, Entity entity, Field field, String[] tuple, Context ctx) { String value = getValue(relation, entity, field, tuple, ctx); if (isValueEmpty(value)) return null; if (ctx.getBaseLocator() == null) { throw new DB2TMException("Cannot resolve locator '" + value + "', missing a base locator"); } return ctx.getBaseLocator().resolveAbsolute(value); } protected static String expandPrefixedValue(String value, Context ctx) { int cix = value.indexOf(':'); if (cix >= 1) { // prefix reference String prefix_id = value.substring(0, cix); Prefix prefix = ctx.getMapping().getPrefix(prefix_id); if (prefix == null) throw new DB2TMConfigException("Unknown prefix: '" + prefix_id + "' (value='" + value + "')"); return prefix.getLocator() + value.substring(cix + 1); } else { throw new DB2TMConfigException("Illegal prefixed value: '" + value + "'"); } } }
/* * Copyright 2013-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.rules; import com.facebook.buck.event.AbstractBuckEvent; import com.facebook.buck.event.EventKey; import com.facebook.buck.event.WorkAdvanceEvent; import com.facebook.buck.model.BuildTarget; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.collect.ImmutableSet; /** * Base class for events about building. */ public abstract class BuildEvent extends AbstractBuckEvent implements WorkAdvanceEvent { public BuildEvent(EventKey eventKey) { super(eventKey); } public static Started started(Iterable<String> buildArgs) { return new Started(ImmutableSet.copyOf(buildArgs)); } public static Finished finished(Started started, int exitCode) { return new Finished(started, exitCode); } public static DistBuildStarted distBuildStarted() { return new DistBuildStarted(); } public static DistBuildFinished distBuildFinished(DistBuildStarted started, int exitCode) { return new DistBuildFinished(started, exitCode); } public static RuleCountCalculated ruleCountCalculated( ImmutableSet<BuildTarget> buildTargets, int ruleCount) { return new RuleCountCalculated(buildTargets, ruleCount); } public static UnskippedRuleCountUpdated unskippedRuleCountUpdated(int ruleCount) { return new UnskippedRuleCountUpdated(ruleCount); } public static class Started extends BuildEvent { private final ImmutableSet<String> buildArgs; protected Started(ImmutableSet<String> buildArgs) { super(EventKey.unique()); this.buildArgs = buildArgs; } @Override public String getEventName() { return BUILD_STARTED; } @Override protected String getValueString() { return Joiner.on(", ").join(buildArgs); } public ImmutableSet<String> getBuildArgs() { return buildArgs; } } public static class Finished extends BuildEvent { private final ImmutableSet<String> buildArgs; private final int exitCode; protected Finished(Started started, int exitCode) { super(started.getEventKey()); this.buildArgs = started.getBuildArgs(); this.exitCode = exitCode; } public ImmutableSet<String> getBuildArgs() { return buildArgs; } public int getExitCode() { return exitCode; } @Override public String getEventName() { return BUILD_FINISHED; } @Override protected String getValueString() { return String.format("exit code: %d", exitCode); } @Override public boolean equals(Object o) { if (!super.equals(o)) { return false; } // Because super.equals compares the EventKey, getting here means that we've somehow managed // to create 2 Finished events for the same Started event. throw new UnsupportedOperationException("Multiple conflicting Finished events detected."); } @Override public int hashCode() { return Objects.hashCode(super.hashCode(), buildArgs, exitCode); } } public static class DistBuildStarted extends BuildEvent { protected DistBuildStarted() { super(EventKey.unique()); } @Override public String getEventName() { return DIST_BUILD_STARTED; } @Override protected String getValueString() { return ""; } } public static class DistBuildFinished extends BuildEvent { private final int exitCode; protected DistBuildFinished(DistBuildStarted started, int exitCode) { super(started.getEventKey()); this.exitCode = exitCode; } public int getExitCode() { return exitCode; } @Override public String getEventName() { return DIST_BUILD_FINISHED; } @Override protected String getValueString() { return String.format("exit code: %d", exitCode); } @Override public boolean equals(Object o) { if (!super.equals(o)) { return false; } // Because super.equals compares the EventKey, getting here means that we've somehow managed // to create 2 Finished events for the same Started event. throw new UnsupportedOperationException("Multiple conflicting Finished events detected."); } @Override public int hashCode() { return Objects.hashCode(super.hashCode(), exitCode); } } public static class RuleCountCalculated extends BuildEvent { private final ImmutableSet<BuildTarget> buildRules; private final int numRules; protected RuleCountCalculated(ImmutableSet<BuildTarget> buildRules, int numRulesToBuild) { super(EventKey.unique()); this.buildRules = buildRules; this.numRules = numRulesToBuild; } public ImmutableSet<BuildTarget> getBuildRules() { return buildRules; } public int getNumRules() { return numRules; } @Override public String getEventName() { return "RuleCountCalculated"; } @Override protected String getValueString() { return Joiner.on(", ").join(buildRules); } @Override public boolean equals(Object o) { if (!super.equals(o)) { return false; } // Because super.equals compares the EventKey, getting here means that we've somehow managed // to create 2 Finished events for the same Started event. throw new UnsupportedOperationException("Multiple conflicting Finished events detected."); } @Override public int hashCode() { return Objects.hashCode(super.hashCode(), buildRules, numRules); } } public static class UnskippedRuleCountUpdated extends BuildEvent { private final int numRules; protected UnskippedRuleCountUpdated(int numRulesToBuild) { super(EventKey.unique()); this.numRules = numRulesToBuild; } public int getNumRules() { return numRules; } @Override public String getEventName() { return "UnskippedRuleCountUpdated"; } @Override protected String getValueString() { return Integer.toString(numRules); } @Override public boolean equals(Object o) { return this == o; } @Override public int hashCode() { return System.identityHashCode(this); } } }
/* * Copyright 2012-2019 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 * * 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 org.springframework.boot.autoconfigure.web.reactive.error; import java.nio.charset.StandardCharsets; import javax.validation.Valid; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import reactor.core.publisher.Mono; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration; import org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration; import org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration; import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration; import org.springframework.boot.test.context.assertj.AssertableReactiveWebApplicationContext; import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Integration tests for {@link DefaultErrorWebExceptionHandler} * * @author Brian Clozel */ @ExtendWith(OutputCaptureExtension.class) class DefaultErrorWebExceptionHandlerIntegrationTests { private static final MediaType TEXT_HTML_UTF8 = new MediaType("text", "html", StandardCharsets.UTF_8); private final LogIdFilter logIdFilter = new LogIdFilter(); private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ReactiveWebServerFactoryAutoConfiguration.class, HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class, ErrorWebFluxAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, MustacheAutoConfiguration.class)) .withPropertyValues("spring.main.web-application-type=reactive", "server.port=0") .withUserConfiguration(Application.class); @Test void jsonError(CapturedOutput output) { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/").exchange().expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody() .jsonPath("status").isEqualTo("500").jsonPath("error") .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("path").isEqualTo(("/")) .jsonPath("message").isEqualTo("Expected!").jsonPath("exception").doesNotExist().jsonPath("trace") .doesNotExist().jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); assertThat(output).contains("500 Server Error for HTTP GET \"/\"") .contains("java.lang.IllegalStateException: Expected!"); }); } @Test void notFound() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/notFound").exchange().expectStatus().isNotFound().expectBody().jsonPath("status") .isEqualTo("404").jsonPath("error").isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()) .jsonPath("path").isEqualTo(("/notFound")).jsonPath("exception").doesNotExist() .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); }); } @Test void htmlError() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) .expectBody(String.class).returnResult().getResponseBody(); assertThat(body).contains("status: 500").contains("message: Expected!"); }); } @Test void bindingResultError() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); client.post().uri("/bind").contentType(MediaType.APPLICATION_JSON).bodyValue("{}").exchange().expectStatus() .isBadRequest().expectBody().jsonPath("status").isEqualTo("400").jsonPath("error") .isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()).jsonPath("path").isEqualTo(("/bind")) .jsonPath("exception").doesNotExist().jsonPath("errors").isArray().jsonPath("message").isNotEmpty() .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); }); } @Test void includeStackTraceOnParam() { this.contextRunner.withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=on-trace-param").run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/?trace=true").exchange().expectStatus() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") .isEqualTo("500").jsonPath("error") .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").exists() .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); }); } @Test void alwaysIncludeStackTrace() { this.contextRunner .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=always") .run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/?trace=false").exchange().expectStatus() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") .isEqualTo("500").jsonPath("error") .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").exists() .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); }); } @Test void neverIncludeStackTrace() { this.contextRunner .withPropertyValues("server.error.include-exception=true", "server.error.include-stacktrace=never") .run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/?trace=true").exchange().expectStatus() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody().jsonPath("status") .isEqualTo("500").jsonPath("error") .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).jsonPath("exception") .isEqualTo(IllegalStateException.class.getName()).jsonPath("trace").doesNotExist() .jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId()); }); } @Test void statusException() { this.contextRunner.withPropertyValues("server.error.include-exception=true").run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/badRequest").exchange().expectStatus().isBadRequest().expectBody().jsonPath("status") .isEqualTo("400").jsonPath("error").isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()) .jsonPath("exception").isEqualTo(ResponseStatusException.class.getName()).jsonPath("requestId") .isEqualTo(this.logIdFilter.getLogId()); }); } @Test void defaultErrorView() { this.contextRunner.withPropertyValues("spring.mustache.prefix=classpath:/unknown/", "server.error.include-stacktrace=always").run((context) -> { WebTestClient client = getWebClient(context); String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange().expectStatus() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) .expectBody(String.class).returnResult().getResponseBody(); assertThat(body).contains("Whitelabel Error Page").contains(this.logIdFilter.getLogId()) .contains("<div>Expected!</div>") .contains("<div style='white-space:pre-wrap;'>java.lang.IllegalStateException"); }); } @Test void escapeHtmlInDefaultErrorView() { this.contextRunner.withPropertyValues("spring.mustache.prefix=classpath:/unknown/").run((context) -> { WebTestClient client = getWebClient(context); String body = client.get().uri("/html").accept(MediaType.TEXT_HTML).exchange().expectStatus() .isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader().contentType(TEXT_HTML_UTF8) .expectBody(String.class).returnResult().getResponseBody(); assertThat(body).contains("Whitelabel Error Page").contains(this.logIdFilter.getLogId()) .doesNotContain("<script>").contains("&lt;script&gt;"); }); } @Test void testExceptionWithNullMessage() { this.contextRunner.withPropertyValues("spring.mustache.prefix=classpath:/unknown/").run((context) -> { WebTestClient client = getWebClient(context); String body = client.get().uri("/notfound").accept(MediaType.TEXT_HTML).exchange().expectStatus() .isNotFound().expectHeader().contentType(TEXT_HTML_UTF8).expectBody(String.class).returnResult() .getResponseBody(); assertThat(body).contains("Whitelabel Error Page").contains(this.logIdFilter.getLogId()) .contains("type=Not Found, status=404"); }); } @Test void responseCommitted() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> client.get().uri("/commit").exchange().expectStatus()) .withCauseInstanceOf(IllegalStateException.class).withMessageContaining("already committed!"); }); } @Test void whitelabelDisabled() { this.contextRunner.withPropertyValues("server.error.whitelabel.enabled=false", "spring.mustache.prefix=classpath:/unknown/").run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/notfound").accept(MediaType.TEXT_HTML).exchange().expectStatus().isNotFound() .expectBody().isEmpty(); }); } @Test void exactStatusTemplateErrorPage() { this.contextRunner.withPropertyValues("server.error.whitelabel.enabled=false", "spring.mustache.prefix=" + getErrorTemplatesLocation()).run((context) -> { WebTestClient client = getWebClient(context); String body = client.get().uri("/notfound").accept(MediaType.TEXT_HTML).exchange().expectStatus() .isNotFound().expectBody(String.class).returnResult().getResponseBody(); assertThat(body).contains("404 page"); }); } @Test void seriesStatusTemplateErrorPage() { this.contextRunner.withPropertyValues("server.error.whitelabel.enabled=false", "spring.mustache.prefix=" + getErrorTemplatesLocation()).run((context) -> { WebTestClient client = getWebClient(context); String body = client.get().uri("/badRequest").accept(MediaType.TEXT_HTML).exchange().expectStatus() .isBadRequest().expectBody(String.class).returnResult().getResponseBody(); assertThat(body).contains("4xx page"); }); } @Test void invalidAcceptMediaType() { this.contextRunner.run((context) -> { WebTestClient client = getWebClient(context); client.get().uri("/notfound").header("Accept", "v=3.0").exchange().expectStatus() .isEqualTo(HttpStatus.NOT_FOUND); }); } private String getErrorTemplatesLocation() { String packageName = getClass().getPackage().getName(); return "classpath:/" + packageName.replace('.', '/') + "/templates/"; } private WebTestClient getWebClient(AssertableReactiveWebApplicationContext context) { return WebTestClient.bindToApplicationContext(context).webFilter(this.logIdFilter).build(); } private static final class LogIdFilter implements WebFilter { private String logId; @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { this.logId = exchange.getRequest().getId(); return chain.filter(exchange); } String getLogId() { return this.logId; } } @Configuration(proxyBeanMethods = false) static class Application { @RestController static class ErrorController { @GetMapping("/") String home() { throw new IllegalStateException("Expected!"); } @GetMapping("/badRequest") Mono<String> badRequest() { return Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST)); } @GetMapping("/commit") Mono<Void> commit(ServerWebExchange exchange) { return exchange.getResponse().setComplete() .then(Mono.error(new IllegalStateException("already committed!"))); } @GetMapping("/html") String htmlEscape() { throw new IllegalStateException("<script>"); } @PostMapping(path = "/bind", produces = "application/json") @ResponseBody String bodyValidation(@Valid @RequestBody DummyBody body) { return body.getContent(); } } } }
package net.sourceforge.mayfly.acceptance.expression; import net.sourceforge.mayfly.acceptance.SqlTestCase; import java.sql.ResultSet; public class WhereTest extends SqlTestCase { public void testWhere() throws Exception { execute("create table foo (a integer, b integer)"); execute("insert into foo (a, b) values (4, 16)"); execute("insert into foo (a, b) values (5, 25)"); ResultSet results = query("select a, b from foo where b = 25"); assertTrue(results.next()); assertEquals(5, results.getInt("a")); assertEquals(25, results.getInt("b")); assertFalse(results.next()); } public void testWhereIsCaseSensitive() throws Exception { execute("create table foo (a varchar(80))"); execute("insert into foo (a) values ('Foo')"); ResultSet wrongCase = query("select a from foo where a = 'FOO'"); if (dialect.stringComparisonsAreCaseInsensitive()) { assertTrue(wrongCase.next()); assertEquals("Foo", wrongCase.getString("a")); } assertFalse(wrongCase.next()); ResultSet correctCase = query("select a from foo where a = 'Foo'"); assertTrue(correctCase.next()); assertEquals("Foo", correctCase.getString("a")); assertFalse(correctCase.next()); } public void testWhereAnd() throws Exception { execute("create table foo (a integer, b integer, c integer)"); execute("insert into foo (a, b, c) values (1, 1, 1)"); execute("insert into foo (a, b, c) values (1, 1, 2)"); execute("insert into foo (a, b, c) values (1, 2, 1)"); execute("insert into foo (a, b, c) values (1, 2, 2)"); execute("insert into foo (a, b, c) values (2, 2, 2)"); execute("insert into foo (a, b, c) values (1, 2, null)"); execute("insert into foo (a, b, c) values (null, 1, 1)"); assertResultSet( new String[] { " 1, 1, 1 ", " 1, 2, 1 " }, query("select a, b, c from foo where a=1 and c=1") ); } public void testWhatOr() throws Exception { execute("create table foo (a integer, b integer, c integer)"); execute("insert into foo (a, b, c) values (1, 1, 1)"); execute("insert into foo (a, b, c) values (1, 1, 2)"); execute("insert into foo (a, b, c) values (1, 2, 1)"); execute("insert into foo (a, b, c) values (1, 2, 2)"); execute("insert into foo (a, b, c) values (2, 2, 2)"); execute("insert into foo (a, b, c) values (2, null, 1)"); execute("insert into foo (a, b, c) values (null, 1, 1)"); execute("insert into foo (a, b, c) values (null, null, 1)"); assertResultSet( new String[] { " 1, 1, 1 ", " 1, 1, 2 ", " 2, 2, 2 ", " 2, null, 1 ", " null, 1, 1 ", }, query("select a, b, c from foo where a=2 or b=1") ); } public void testNotEqual() throws Exception { execute("create table foo (a integer)"); execute("insert into foo (a) values (4)"); execute("insert into foo (a) values (5)"); execute("insert into foo (a) values (6)"); assertResultSet( new String[] { " 4 ", " 6 ", }, query("select a from foo where a != 5") ); assertResultSet( new String[] { " 4 ", " 6 ", }, query("select a from foo where 5 != a") ); assertResultSet( new String[] { " 4 ", " 6 ", }, query("select a from foo where a <> 5") ); assertResultSet( new String[] { " 4 ", " 6 ", }, query("select a from foo where 5 <> a") ); } public void testGreaterThan() throws Exception { execute("create table foo (a integer)"); execute("insert into foo (a) values (4)"); execute("insert into foo (a) values (5)"); execute("insert into foo (a) values (6)"); execute("insert into foo (a) values (null)"); assertResultSet( new String[] { " 5 ", " 6 ", }, query("select a from foo where a > 4") ); assertResultSet( new String[] { " 4 ", " 5 ", }, query("select a from foo where 6 > a ") ); assertResultSet( new String[] { " 4 ", " 5 ", }, query("select a from foo where a < 6 ") ); } public void testLessThanOrEqual() throws Exception { execute("create table foo (a integer)"); execute("insert into foo (a) values (4)"); execute("insert into foo (a) values (5)"); execute("insert into foo (a) values (6)"); execute("insert into foo (a) values (null)"); assertResultSet( new String[] { " 4 ", " 5 ", }, query("select a from foo where a <= 5") ); } public void testGreaterThanOrEqual() throws Exception { execute("create table foo (a integer)"); execute("insert into foo (a) values (4)"); execute("insert into foo (a) values (5)"); execute("insert into foo (a) values (6)"); execute("insert into foo (a) values (null)"); assertResultSet( new String[] { " 5 ", " 6 ", }, query("select a from foo where a >= 5") ); } public void testSimpleIn() throws Exception { execute("create table foo (a integer, b integer)"); execute("insert into foo (a, b) values (1, 1)"); execute("insert into foo (a, b) values (2, 4)"); execute("insert into foo (a, b) values (3, 9)"); // OK, this one is where an SQL boolean needs to be true,false,null. // I think. // execute("insert into foo (a, b) values (null, -1)"); assertResultSet( new String[] { " 1 ", " 9 ", }, query("select b from foo where foo.a in (1, 3)") ); assertResultSet( new String[] { " 4 ", }, query("select b from foo where not (foo.a in (1, 3))") ); assertResultSet( new String[] { " 4 ", }, query("select b from foo where foo.a not in (1, 3)") ); } public void testExpressions() throws Exception { execute("create table foo (a integer, b integer, c integer, description varchar(255))"); execute("insert into foo(a, b, c, description) values (1, 1, 3, 'equals b')"); execute("insert into foo(a, b, c, description) values (null, null, 3, 'is null')"); execute("insert into foo(a, b, c, description) values (1, 2, 3, 'equals nothing')"); assertResultSet( new String[] { " 'equals b' " }, query("select description from foo where a in (b, c)") ); assertResultSet( new String[] { " 'equals nothing' " , " 'equals b' " }, query("select description from foo where a in (b, b - 1)") ); } public void testNullLiteralOnRightHandSideOfIn() throws Exception { execute("create table foo (a integer, b integer)"); execute("insert into foo(a, b) values (null, 17)"); String sql = "select b from foo where a in (null, 5)"; if (dialect.disallowNullOnRightHandSideOfIn()) { expectQueryFailure(sql, "To check for null, use IS NULL or IS NOT NULL, not a null literal"); } else { // Hah! Gotcha! null = null evaluates to false. assertResultSet(new String[] { }, query(sql)); } } public void testInPrecedence() throws Exception { execute("create table foo (a integer, b integer)"); execute("insert into foo (a, b) values (1, 1)"); execute("insert into foo (a, b) values (2, 4)"); execute("insert into foo (a, b) values (3, 9)"); String negateTheIn = "select b from foo where not foo.a in (1, 3)"; if (dialect.notBindsMoreTightlyThanIn()) { assertResultSet( new String[] { }, query(negateTheIn) ); } else { assertResultSet( new String[] { " 4 " }, query(negateTheIn) ); } String booleanAsLeftSideOfIn = "select b from foo where (not foo.a) in (1, 3)"; if (dialect.notRequiresBoolean()) { // Mayfly and Postgres are pickier than some databases about boolean vs non-boolean // If some writes SQL like that they are either making a mistake, or they are // being too clever for our tastes. expectQueryFailure(booleanAsLeftSideOfIn, "expected boolean expression but got non-boolean expression"); // The message should identify what part of the expression is the problem. // For example, "expected boolean expression but got foo.a" // And/or by context, for example: // expectQueryFailure(booleanAsLeftSideOfIn, "operand of NOT must be a boolean expression"); } else { assertResultSet(new String[] { }, query(booleanAsLeftSideOfIn)); } } public void testLikePrecedence() throws Exception { /* Another case involving NOT and an infix. Inspired by a blog post by David Pashley. */ execute("create table foo(a varchar(40))"); execute("insert into foo(a) values(null)"); execute("insert into foo(a) values('aa')"); execute("insert into foo(a) values('a-a')"); execute("insert into foo(a) values('0')"); execute("insert into foo(a) values('1')"); assertResultSet(new String[] { " null ", " 'aa' ", " '0' ", " '1' " }, query("select a from foo where a is null or not a like '%-%'")); assertResultSet(new String[] { " null ", " 'aa' ", " '0' ", " '1' " }, query("select a from foo where a is null or a not like '%-%'")); String notOnAString = "select a from foo where a is null or (not a) like '%-%'"; if (dialect.notRequiresBooleanForLike()) { expectQueryFailure(notOnAString, "expected boolean expression but got non-boolean expression"); } else { assertResultSet(new String[] { " null " }, query(notOnAString)); } } public void testInWithSubselect() throws Exception { execute("create table foo (a integer, b integer)"); execute("insert into foo (a, b) values (1, 1)"); execute("insert into foo (a, b) values (2, 4)"); execute("insert into foo (a, b) values (3, 9)"); execute("create table bar (c integer)"); execute("insert into bar (c) values (2)"); execute("insert into bar (c) values (3)"); assertResultSet( new String[] { " 4 ", " 9 ", }, query("select b from foo where foo.a in (select c from bar)") ); } public void testReferToColumnAlias() throws Exception { execute("create table foo(a integer, b integer)"); execute("insert into foo(a, b) values(3, 10)"); execute("insert into foo(a, b) values(7, 20)"); String sql = "select a + b as a_and_b from foo where a_and_b < 20"; if (dialect.whereCanReferToColumnAlias()) { assertResultSet( new String[] { " 13 " }, query(sql) ); } else { expectQueryFailure(sql, "no column a_and_b"); } } }
// // $ // package edu.gemini.wdba.tcc; import edu.gemini.pot.sp.ISPObsComponent; import edu.gemini.pot.sp.SPComponentType; import edu.gemini.spModel.gemini.altair.AltairParams; import edu.gemini.spModel.gemini.altair.InstAltair; import edu.gemini.spModel.gemini.gmos.InstGmosSouth; import edu.gemini.spModel.gemini.gpi.Gpi; import edu.gemini.spModel.gemini.nici.InstNICI; import edu.gemini.spModel.gemini.nici.NICIParams; import edu.gemini.spModel.gemini.niri.InstNIRI; import org.dom4j.Document; import org.dom4j.Element; import java.util.List; /** * Test cases for RotatorConfig. The logic is about as convoluted as the * class itself ... */ public class RotatorConfigTest extends TestBase { private ISPObsComponent instObsComp; private ISPObsComponent altairObsComp; private ISPObsComponent addInstrument(SPComponentType type) throws Exception { instObsComp = odb.getFactory().createObsComponent(prog, type, null); obs.addObsComponent(instObsComp); return instObsComp; } private InstAltair addAltair() throws Exception { altairObsComp = odb.getFactory().createObsComponent(prog, InstAltair.SP_TYPE, null); obs.addObsComponent(altairObsComp); return (InstAltair) altairObsComp.getDataObject(); } private InstNIRI addNiri() throws Exception { return (InstNIRI) addInstrument(InstNIRI.SP_TYPE).getDataObject(); } private InstNICI addNici() throws Exception { return (InstNICI) addInstrument(InstNICI.SP_TYPE).getDataObject(); } private Gpi addGpi() throws Exception { return (Gpi) addInstrument(Gpi.SP_TYPE).getDataObject(); } private InstGmosSouth addGmos() throws Exception { return (InstGmosSouth) addInstrument(InstGmosSouth.SP_TYPE).getDataObject(); } private String getRotatorConfigParamValue(Document doc, Type type) throws Exception { Element fieldConfigElement = getTccFieldConfig(doc); @SuppressWarnings({"unchecked"}) List<Element> params = (List<Element>) fieldConfigElement.elements("param"); for (Element param : params) { if (type.name().equals(param.attributeValue("name"))) { return param.attributeValue("value"); } } fail("Could not find rotator config param value"); return null; } private enum Site { north() { Document getResults(TestBase base) throws Exception { return base.getNorthResults(); } }, south() { Document getResults(TestBase base) throws Exception { return base.getSouthResults(); } }, ; abstract Document getResults(TestBase base) throws Exception; } private enum Type { posAngle, rotator, ; Element getElement(Document doc, TestBase base) throws Exception { return base.getTccFieldContainedParamSet(doc, name()).get(0); } } private enum RotConfigExtractor { name() { String extract(Element element) { return element.attributeValue("name"); } }, ipa() { String extract(Element element) { return child(element, name()).attributeValue("value"); } }, cosys() { String extract(Element element) { return child(element, name()).attributeValue("value"); } }, ; abstract String extract(Element element); private static Element child(Element element, String name) { //noinspection unchecked for (Element child : (List<Element>) element.elements()) { if (name.equals(child.attributeValue("name"))) return child; } fail("Could not find child element '" + name + "'"); return null; } } private class RotConfigValidator { Site site; Type type; String name; String ipa; String cosys; void validate() throws Exception { Document res = site.getResults(RotatorConfigTest.this); // RotatorConfig is added as a parameter whose name is // based on the type "rotator" or "posAngle" and a value which // is, for example, "AltairFixed", "NICIFixed", or a position // angle. assertEquals(name, getRotatorConfigParamValue(res, type)); // In addition to the parameter, we add a param set that contains // detail information including the actual position angle. Element paramSet = type.getElement(res, RotatorConfigTest.this); assertEquals(name, RotConfigExtractor.name.extract(paramSet)); assertEquals(ipa, RotConfigExtractor.ipa.extract(paramSet)); assertEquals(cosys, RotConfigExtractor.cosys.extract(paramSet)); } } public void testPosAngle() throws Exception { InstGmosSouth gmos = addGmos(); gmos.setPosAngle(10.5); instObsComp.setDataObject(gmos); RotConfigValidator val = new RotConfigValidator(); val.site = Site.south; val.type = Type.posAngle; val.name = "10.5"; val.ipa = "10.5"; val.cosys = TccNames.FK5J2000; val.validate(); } public void testAltairPosAngle() throws Exception { InstNIRI niri = addNiri(); niri.setPosAngle(10.5); instObsComp.setDataObject(niri); InstAltair altair = addAltair(); assertEquals(AltairParams.CassRotator.FOLLOWING, altair.getCassRotator()); RotConfigValidator val = new RotConfigValidator(); val.site = Site.north; val.type = Type.posAngle; val.name = "10.5"; val.ipa = "10.5"; val.cosys = TccNames.FK5J2000; val.validate(); } public void testAltairFixed() throws Exception { InstNIRI niri = addNiri(); niri.setPosAngle(10.5); instObsComp.setDataObject(niri); InstAltair altair = addAltair(); altair.setCassRotator(AltairParams.CassRotator.FIXED); altairObsComp.setDataObject(altair); // A param set isn't added in this case for some unknown reason. Document res = getNorthResults(); getRotatorConfigParamValue(res, Type.rotator); assertEquals(0, getTccFieldContainedParamSet(res, "rotator").size()); } public void testNiciFixed() throws Exception { InstNICI nici = addNici(); nici.setPosAngle(10.5); nici.setCassRotator(NICIParams.CassRotator.FIXED); instObsComp.setDataObject(nici); RotConfigValidator val = new RotConfigValidator(); val.site = Site.south; val.type = Type.rotator; val.name = "NICIFixed"; val.ipa = "10.5"; val.cosys = TccNames.FIXED; val.validate(); } public void testNiciPosAngle() throws Exception { InstNICI nici = addNici(); nici.setCassRotator(NICIParams.CassRotator.FOLLOW); nici.setPosAngle(10.5); instObsComp.setDataObject(nici); RotConfigValidator val = new RotConfigValidator(); val.site = Site.south; val.type = Type.posAngle; val.name = "10.5"; val.ipa = "10.5"; val.cosys = TccNames.FK5J2000; val.validate(); } public void testGpiFixed() throws Exception { Gpi gpi = addGpi(); instObsComp.setDataObject(gpi); RotConfigValidator val = new RotConfigValidator(); val.site = Site.south; val.type = Type.rotator; val.name = "GPIFixed"; val.ipa = "0"; val.cosys = TccNames.FIXED; val.validate(); } public void testGpiPosAngle0() throws Exception { Gpi gpi = addGpi(); gpi.setPosAngle(0); instObsComp.setDataObject(gpi); RotConfigValidator val = new RotConfigValidator(); val.site = Site.south; val.type = Type.rotator; val.name = "GPIFixed"; val.ipa = "0"; val.cosys = TccNames.FIXED; val.validate(); } public void testGpiPosAngle180() throws Exception { Gpi gpi = addGpi(); gpi.setPosAngle(180); instObsComp.setDataObject(gpi); RotConfigValidator val = new RotConfigValidator(); val.site = Site.south; val.type = Type.rotator; val.name = "GPIFixed"; val.ipa = "180"; val.cosys = TccNames.FIXED; val.validate(); } }
/* 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.test.history; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.history.HistoricTaskInstance; import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity; import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.task.Task; import org.camunda.bpm.engine.test.Deployment; /** * @author Tom Baeyens * @author Frederik Heremans */ public class HistoricTaskInstanceTest extends PluggableProcessEngineTestCase { @Deployment public void testHistoricTaskInstance() throws Exception { String processInstanceId = runtimeService.startProcessInstanceByKey("HistoricTaskInstanceTest").getId(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); // Set priority to non-default value Task runtimeTask = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult(); runtimeTask.setPriority(1234); // Set due-date Date dueDate = sdf.parse("01/02/2003 04:05:06"); runtimeTask.setDueDate(dueDate); taskService.saveTask(runtimeTask); String taskId = runtimeTask.getId(); String taskDefinitionKey = runtimeTask.getTaskDefinitionKey(); HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().singleResult(); assertEquals(taskId, historicTaskInstance.getId()); assertEquals(1234, historicTaskInstance.getPriority()); assertEquals("Clean up", historicTaskInstance.getName()); assertEquals("Schedule an engineering meeting for next week with the new hire.", historicTaskInstance.getDescription()); assertEquals(dueDate, historicTaskInstance.getDueDate()); assertEquals("kermit", historicTaskInstance.getAssignee()); assertEquals(taskDefinitionKey, historicTaskInstance.getTaskDefinitionKey()); assertNull(historicTaskInstance.getEndTime()); assertNull(historicTaskInstance.getDurationInMillis()); runtimeService.setVariable(processInstanceId, "deadline", "yesterday"); taskService.complete(taskId); assertEquals(1, historyService.createHistoricTaskInstanceQuery().count()); historicTaskInstance = historyService.createHistoricTaskInstanceQuery().singleResult(); assertEquals(taskId, historicTaskInstance.getId()); assertEquals(1234, historicTaskInstance.getPriority()); assertEquals("Clean up", historicTaskInstance.getName()); assertEquals("Schedule an engineering meeting for next week with the new hire.", historicTaskInstance.getDescription()); assertEquals(dueDate, historicTaskInstance.getDueDate()); assertEquals("kermit", historicTaskInstance.getAssignee()); assertEquals(TaskEntity.DELETE_REASON_COMPLETED, historicTaskInstance.getDeleteReason()); assertEquals(taskDefinitionKey, historicTaskInstance.getTaskDefinitionKey()); assertNotNull(historicTaskInstance.getEndTime()); assertNotNull(historicTaskInstance.getDurationInMillis()); historyService.deleteHistoricTaskInstance(taskId); assertEquals(0, historyService.createHistoricTaskInstanceQuery().count()); } public void testDeleteHistoricTaskInstance() throws Exception { // deleting unexisting historic task instance should be silently ignored historyService.deleteHistoricTaskInstance("unexistingId"); } @Deployment public void testHistoricTaskInstanceQuery() throws Exception { // First instance is finished ProcessInstance finishedInstance = runtimeService.startProcessInstanceByKey("HistoricTaskQueryTest"); // Set priority to non-default value Task task = taskService.createTaskQuery().processInstanceId(finishedInstance.getId()).singleResult(); task.setPriority(1234); Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 04:05:06"); task.setDueDate(dueDate); taskService.saveTask(task); // Complete the task String taskId = task.getId(); taskService.complete(taskId); // Task id assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskId(taskId).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskId("unexistingtaskid").count()); // Name assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskName("Clean up").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskName("unexistingname").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskNameLike("Clean u%").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskNameLike("%lean up").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskNameLike("%lean u%").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskNameLike("%unexistingname%").count()); // Description assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskDescription("Historic task description").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskDescription("unexistingdescription").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskDescriptionLike("%task description").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskDescriptionLike("Historic task %").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskDescriptionLike("%task%").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskDescriptionLike("%unexistingdescripton%").count()); // Execution id assertEquals(1, historyService.createHistoricTaskInstanceQuery().executionId(finishedInstance.getId()).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().executionId("unexistingexecution").count()); // Process instance id assertEquals(1, historyService.createHistoricTaskInstanceQuery().processInstanceId(finishedInstance.getId()).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processInstanceId("unexistingid").count()); // Process definition id assertEquals(1, historyService.createHistoricTaskInstanceQuery().processDefinitionId(finishedInstance.getProcessDefinitionId()).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processDefinitionId("unexistingdefinitionid").count()); // Process definition name assertEquals(1, historyService.createHistoricTaskInstanceQuery().processDefinitionName("Historic task query test process").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processDefinitionName("unexistingdefinitionname").count()); // Process definition key assertEquals(1, historyService.createHistoricTaskInstanceQuery().processDefinitionKey("HistoricTaskQueryTest").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processDefinitionKey("unexistingdefinitionkey").count()); // Assignee assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskAssignee("kermit").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskAssignee("johndoe").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("%ermit").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("kermi%").count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("%ermi%").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskAssigneeLike("%johndoe%").count()); // Delete reason assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskDeleteReason(TaskEntity.DELETE_REASON_COMPLETED).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskDeleteReason("deleted").count()); // Task definition ID assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskDefinitionKey("task").count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskDefinitionKey("unexistingkey").count()); // Task priority assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskPriority(1234).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskPriority(5678).count()); // Due date Calendar anHourAgo = Calendar.getInstance(); anHourAgo.setTime(dueDate); anHourAgo.add(Calendar.HOUR, -1); Calendar anHourLater = Calendar.getInstance(); anHourLater.setTime(dueDate); anHourLater.add(Calendar.HOUR, 1); assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskDueDate(dueDate).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskDueDate(anHourAgo.getTime()).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskDueDate(anHourLater.getTime()).count()); // Due date before assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskDueBefore(anHourLater.getTime()).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskDueBefore(anHourAgo.getTime()).count()); // Due date after assertEquals(1, historyService.createHistoricTaskInstanceQuery().taskDueAfter(anHourAgo.getTime()).count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().taskDueAfter(anHourLater.getTime()).count()); // Finished and Unfinished - Add anther other instance that has a running task (unfinished) runtimeService.startProcessInstanceByKey("HistoricTaskQueryTest"); assertEquals(1, historyService.createHistoricTaskInstanceQuery().finished().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().unfinished().count()); } @Deployment public void testHistoricTaskInstanceQueryProcessFinished() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("TwoTaskHistoricTaskQueryTest"); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); // Running task on running process should be available assertEquals(1, historyService.createHistoricTaskInstanceQuery().processUnfinished().count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processFinished().count()); // Finished and running task on running process should be available taskService.complete(task.getId()); assertEquals(2, historyService.createHistoricTaskInstanceQuery().processUnfinished().count()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processFinished().count()); // 2 finished tasks are found for finished process after completing last task of process task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); assertEquals(0, historyService.createHistoricTaskInstanceQuery().processUnfinished().count()); assertEquals(2, historyService.createHistoricTaskInstanceQuery().processFinished().count()); } @Deployment public void testHistoricTaskInstanceQuerySorting() { ProcessInstance instance = runtimeService.startProcessInstanceByKey("HistoricTaskQueryTest"); String taskId = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult().getId(); taskService.complete(taskId); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByDeleteReason().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByExecutionId().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByHistoricActivityInstanceId().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByHistoricActivityInstanceStartTime().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByProcessDefinitionId().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByProcessInstanceId().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskDescription().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskName().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskDefinitionKey().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskPriority().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskAssignee().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskId().asc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByDeleteReason().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByExecutionId().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByHistoricActivityInstanceId().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByHistoricActivityInstanceStartTime().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByProcessDefinitionId().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByProcessInstanceId().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskDescription().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskName().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskDefinitionKey().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskPriority().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskAssignee().desc().count()); assertEquals(1, historyService.createHistoricTaskInstanceQuery().orderByTaskId().desc().count()); } public void testInvalidSorting() { try { historyService.createHistoricTaskInstanceQuery().asc(); fail(); } catch (ProcessEngineException e) { } try { historyService.createHistoricTaskInstanceQuery().desc(); fail(); } catch (ProcessEngineException e) { } try { historyService.createHistoricTaskInstanceQuery().orderByProcessInstanceId().list(); fail(); } catch (ProcessEngineException e) { } } }
/********************************************************************************** * * Copyright (c) 2003, 2004, 2008 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 edu.indiana.lib.twinpeaks.search.sru; import lombok.extern.slf4j.Slf4j; import edu.indiana.lib.twinpeaks.search.HttpTransactionQueryBase; import edu.indiana.lib.twinpeaks.util.StringUtils; /** * Basic SRU query functionality */ @Slf4j public abstract class SruQueryBase extends HttpTransactionQueryBase { /* * SRU common parameters */ public static final String SRU_VERSION = "version"; public static final String SRU_OPERATION = "operation"; public static final String SRU_EXPLAIN = "explain"; public static final String SRU_SEARCH_RETRIEVE = "searchRetrieve"; public static final String SRU_STATUS = "status"; public static final String SRU_RECORD_PACKING = "recordPacking"; public static final String SRU_RECORD_SCHEMA = "recordSchema"; public static final String SRU_START_RECORD = "startRecord"; public static final String SRU_MAX_RECORD = "maximumRecords"; public static final String SRU_SORT = "sortKeys"; public static final String SRU_QUERY = "query"; /* * GET helpers */ /** * Make a version parameter (this is the version of our SRU request) * @return The fully formed version parameter */ protected String sruVersion(String version) { return formatParameter(SRU_VERSION, version); } /** * Make an explain operation parameter * @return The fully formed operation */ protected String sruExplain() { return sruOperation(SRU_EXPLAIN); } /** * Make a searchRetrieve operation parameter * @return The fully formed operation */ protected String sruSearchRetrieve() { return sruOperation(SRU_SEARCH_RETRIEVE); } /** * Make an SRU operation parameter * @param The desired operation (<i>searchRetrieve</>, <i>explain</i>, etc) * @return The fully formed operation */ protected String sruOperation(String operation) { return formatParameter(SRU_OPERATION, operation); } /** * Make a status operation parameter * @return The fully formed operation */ protected String sruStatus() { return sruOperation(SRU_STATUS); } /** * Make a record packing parameter * @param packing How to pack (escape) result records (typically <i>xml</i>) * @return A fully formed record packing parameter */ protected String sruRecordPacking(String packing) { return formatParameter(SRU_RECORD_PACKING, packing); } /** * Make a record schema parameter * @param schema Schema to use * @return A fully formed schema parameter */ protected String sruRecordSchema(String schema) { return formatParameter(SRU_RECORD_SCHEMA, schema); } /** * Make a start record parameter * @param start The starting record number * @return A fully formed start record parameter */ protected String sruStartRecord(String start) { return formatParameter(SRU_START_RECORD, start); } /** * Make a start record parameter * @param start The starting record number * @return A fully formed start record parameter */ protected String sruStartRecord(int start) { return sruStartRecord(String.valueOf(start)); } /** * Make a maximum record parameter * @param maximum The maximum record to return * @return A fully formed maximum record parameter */ protected String sruMaximumRecords(int maximum) { return sruMaximumRecords(String.valueOf(maximum)); } /** * Make a maximum record parameter * @param maximum The maximum record to return * @return A fully formed maximum record parameter */ protected String sruMaximumRecords(String maximum) { return formatParameter(SRU_MAX_RECORD, maximum); } /** * Make a sort parameter * @param key The sort key * @return A fully formed sort parameter */ protected String sruSort(String key) { return formatParameter(SRU_SORT, key); } /** * Make a query parameter * @param criteria The search criteria * @return A fully formed query parameter */ protected String sruQuery(String criteria) { return formatParameter(SRU_QUERY, criteria); } /* * POST helpers */ /** * Make a version parameter (this is the version of our SRU request) */ protected void sruPostVersion(String version) { setParameter(SRU_VERSION, version); } /** * Make an explain operation parameter */ protected void sruPostExplain() { sruPostOperation(SRU_EXPLAIN); } /** * Make a searchRetrieve operation parameter */ protected void sruPostSearchRetrieve() { sruPostOperation(SRU_SEARCH_RETRIEVE); } /** * Make an SRU operation parameter * @param The desired operation (<i>searchRetrieve</>, <i>explain</i>, etc) */ protected void sruPostOperation(String operation) { setParameter(SRU_OPERATION, operation); } /** * Make a status operation parameter */ protected void sruPostStatus() { sruPostOperation(SRU_STATUS); } /** * Make a record packing parameter * @param packing How to pack (escape) result records (typically <i>xml</i>) */ protected void sruPostRecordPacking(String packing) { setParameter(SRU_RECORD_PACKING, packing); } /** * Make a record schema parameter * @param schema Schema to use */ protected void sruPostRecordSchema(String schema) { setParameter(SRU_RECORD_SCHEMA, schema); } /** * Make a start record parameter * @param start The starting record number */ protected void sruPostStartRecord(String start) { setParameter(SRU_START_RECORD, start); } /** * Make a start record parameter * @param start The starting record number */ protected void sruPostStartRecord(int start) { sruPostStartRecord(String.valueOf(start)); } /** * Make a maximum record parameter * @param maximum The maximum record to return */ protected void sruPostMaximumRecords(int maximum) { sruPostMaximumRecords(String.valueOf(maximum)); } /** * Make a maximum record parameter * @param maximum The maximum record to return */ protected void sruPostMaximumRecords(String maximum) { setParameter(SRU_MAX_RECORD, maximum); } /** * Make a sort parameter * @param key The sort key */ protected void sruPostSort(String key) { setParameter(SRU_SORT, key); } /** * Make a query parameter * @param criteria The search criteria */ protected void sruPostQuery(String criteria) { setParameter(SRU_QUERY, criteria); } /* * Miscellaneous helpers */ /** * Trim and concatenate all arguments * @param items Items to append * @return The concatenated items */ protected String appendItems(String... items) { StringBuilder itemBuffer = new StringBuilder(); for (String item: items) { itemBuffer.append(item.trim()); } return itemBuffer.toString(); } /** * Format a parameter (<code>name=value</code>) * @param name Parameter name * @param value Parameter value * @return The <code>name=value</code> pair */ protected String formatParameter(String name, String value) { return appendItems(name, "=", normalizeParameter(value)); } /** * Add the first parameter to a new parameter list * @param newParameter Parmeter to add * @return the updated list */ protected String addFirstParameter(String newParameter) { return addParameter(null, newParameter); } /** * Add a parameter to the parameter list * @param base Base parameter list - we'll add to this * @param newParameter Parmeter to add * @return the updated list */ protected String addParameter(String base, String newParameter) { String seperator; if (StringUtils.isNull(base)) { return appendItems("?", newParameter); } seperator = "&"; if (base.indexOf("?") == -1) { seperator = "?"; } return appendItems(base, seperator, newParameter); } /** * Normalize a query parameter value * @param value Parameter value * @return The [possibly] normalized value */ protected String normalizeParameter(String value) { if (value == null) { return ""; } return value.trim(); } }
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.sabot; import static com.dremio.sabot.Fixtures.NULL_INT; import static com.dremio.sabot.Fixtures.t; import static com.dremio.sabot.Fixtures.th; import static com.dremio.sabot.Fixtures.tr; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.List; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.vector.BigIntVector; import org.apache.arrow.vector.BitVector; import org.apache.arrow.vector.DecimalVector; import org.apache.arrow.vector.IntVector; import org.apache.arrow.vector.VarCharVector; import org.apache.arrow.vector.complex.ListVector; import org.apache.arrow.vector.complex.impl.UnionListWriter; import org.apache.arrow.vector.types.Types.MinorType; import org.apache.arrow.vector.types.pojo.ArrowType.Decimal; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.arrow.vector.util.JsonStringArrayList; import com.dremio.common.AutoCloseables; import com.dremio.common.expression.CompleteType; import com.dremio.exec.record.BatchSchema; import com.dremio.exec.record.BatchSchema.SelectionVectorMode; import com.dremio.exec.record.VectorAccessible; import com.dremio.exec.record.VectorContainer; import com.dremio.exec.record.selection.SelectionVector2; import com.dremio.sabot.Fixtures.DataRow; import com.dremio.sabot.op.filter.VectorContainerWithSV; import com.google.common.base.Preconditions; /** * Creates custom data with a Selection vector. */ public class CustomGeneratorWithSV2 implements Generator { public static final Field BITF = CompleteType.BIT.toField("BIT"); public static final Field INTF = CompleteType.INT.toField("INT"); public static final Field BIGINTF = CompleteType.BIGINT.toField("BIGINT"); public static final Field DECIMALF = new Field("DECIMAL", true, new Decimal(38, 0), null); public static final Field STRINGF = CompleteType.VARCHAR.toField("STRING"); private static final Field LISTF = CompleteType.BIGINT.asList().toField("LIST"); private static final int INNER_LIST_SIZE = 3; private final int numRows; private final BitSet bitValues; private final List<Integer> intValues; private final List<Long> longValues; private final List<BigDecimal> decimalValues; private final List<String> stringValues; private final List<JsonStringArrayList<Long>> listValues; private final BitSet selectedBitSet; private final VectorContainer container; private final BitVector bitVector; private final IntVector intVector; private final BigIntVector bigIntVector; private final DecimalVector decimalVector; private final VarCharVector stringVector; private final ListVector listVector; private final SelectionVector2 sv2; private int totalSelectedRows; private int position; public enum SelectionVariant { SELECT_ALTERNATE, SELECT_NONE, SELECT_ALL } public CustomGeneratorWithSV2(int numRows, BufferAllocator allocator, SelectionVariant variant) { Preconditions.checkState(numRows > 0); this.numRows = numRows; this.stringValues = listOfStrings(numRows); this.intValues = randomListOfInts(numRows); this.longValues = randomListOfLongs(numRows); this.decimalValues = randomListOfDecimals(numRows); this.listValues = listOfLists(numRows); this.bitValues = randomBits(numRows); this.selectedBitSet = new BitSet(numRows); this.totalSelectedRows = 0; computeSelection(variant); this.sv2 = new SelectionVector2(allocator); this.container = new VectorContainerWithSV(allocator, sv2); this.bitVector = container.addOrGet(BITF); this.intVector = container.addOrGet(INTF); this.bigIntVector = container.addOrGet(BIGINTF); this.decimalVector = container.addOrGet(DECIMALF); this.stringVector = container.addOrGet(STRINGF); this.listVector = container.addOrGet(LISTF); container.buildSchema(SelectionVectorMode.TWO_BYTE); listVector.addOrGetVector(FieldType.nullable(MinorType.BIGINT.getType())); } private static List<JsonStringArrayList<Long>> listOfLists(int size) { List<JsonStringArrayList<Long>> listOfLists = new ArrayList<>(size); for (int i = 0; i < size; i++) { final JsonStringArrayList<Long> list = new JsonStringArrayList<>(INNER_LIST_SIZE); for (int j = 0; j < INNER_LIST_SIZE; j++) { list.add((long) j + i); } listOfLists.add(list); } return listOfLists; } private void computeSelection(SelectionVariant variant) { switch (variant) { case SELECT_ALTERNATE: for (int i = 0; i < numRows; i++) { if (i % 2 == 0) { selectedBitSet.set(i); ++totalSelectedRows; } } break; case SELECT_ALL: selectedBitSet.set(0, numRows); totalSelectedRows = numRows; break; case SELECT_NONE: selectedBitSet.clear(0, numRows); totalSelectedRows = 0; break; } } @Override public VectorAccessible getOutput() { return container; } public BatchSchema getSchema() { return container.getSchema(); } public int totalSelectedRows() { return totalSelectedRows; } @Override public int next(int records) { if (position == numRows) { return 0; // no more data available } UnionListWriter listWriter = listVector.getWriter(); sv2.allocateNew(records); int toFill = Math.min(records, numRows - position); int selected = 0; container.allocateNew(); for (int i = 0; i < toFill; i++) { if (selectedBitSet.get(position + i)) { sv2.setIndex(selected, (char)i); ++selected; } int rowId = position + i; bitVector.setSafe(i, bitValues.get(rowId) ? 1 : 0); if (intValues.get(rowId) != null) { intVector.setSafe(i, intValues.get(rowId)); } bigIntVector.setSafe(i, longValues.get(rowId)); decimalVector.setSafe(i, decimalValues.get(rowId)); byte[] valueBytes = stringValues.get(rowId).getBytes(); stringVector.setSafe(i, valueBytes, 0, valueBytes.length); listWriter.setPosition(i); listWriter.startList(); List<Long> list = listValues.get(rowId); for (int j = 0; j < INNER_LIST_SIZE; j++) { listWriter.bigInt().writeBigInt(list.get(j)); } listWriter.endList(); } position += toFill; sv2.setRecordCount(selected); container.setAllCount(selected); return selected; } public Fixtures.Table getExpectedTable() { if (totalSelectedRows == 0) { return null; } final DataRow[] rows = new DataRow[totalSelectedRows]; int idx = 0; for (int i = 0; i < intValues.size(); i++) { if (!selectedBitSet.get(i)) { continue; } rows[idx] = tr( bitValues.get(i), intValues.get(i) == null ? NULL_INT : intValues.get(i), longValues.get(i), decimalValues.get(i), stringValues.get(i), listValues.get(i)); ++idx; } return t(th("BIT", "INT", "BIGINT", "DECIMAL", "STRING", "LIST"), rows); } @Override public void close() throws Exception { AutoCloseables.close(container); } private static List<String> listOfStrings(int size) { List<String> strings = new JsonStringArrayList<>(size); String appender = "Hello all, this is a brave new world !"; for (int i = 0; i < size; i++) { String subStr = appender.substring(0, i % appender.length()); strings.add(subStr + String.format("%d", System.currentTimeMillis())); } return strings; } /** @return shuffled list of integers [0..size) */ private static List<Integer> randomListOfInts(int size) { Integer[] ids = new Integer[size]; for (int i = 0; i < size; i++) { if (i % 10 == 0) { // add some nulls continue; } ids[i] = i; } List<Integer> rndList = Arrays.asList(ids); Collections.shuffle(rndList); return rndList; } private static List<BigDecimal> randomListOfDecimals(int size) { BigDecimal[] ids = new BigDecimal[size]; for (int i = 0; i < size; i++) { ids[i] = new BigDecimal(i); } List<BigDecimal> rndList = Arrays.asList(ids); Collections.shuffle(rndList); return rndList; } private static List<Long> randomListOfLongs(int size) { Long[] ids = new Long[size]; for (int i = 0; i < size; i++) { ids[i] = new Long(i); } List<Long> rndList = Arrays.asList(ids); Collections.shuffle(rndList); return rndList; } private static BitSet randomBits(int size) { BitSet bits = new BitSet(size); for (int i = 0; i < size; ++i) { if (i % 3 == 0) { bits.set(i); } } return bits; } }
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS; import java.io.*; import java.util.*; /** * A DNS Zone. This encapsulates all data related to a Zone, and provides * convenient lookup methods. * * @author Brian Wellington */ public class Zone implements Serializable { private static final long serialVersionUID = -9220510891189510942L; /** A primary zone */ public static final int PRIMARY = 1; /** A secondary zone */ public static final int SECONDARY = 2; private Map data; private Name origin; private Object originNode; private int dclass = DClass.IN; private RRset NS; private SOARecord SOA; private boolean hasWild; class ZoneIterator implements Iterator { private Iterator zentries; private RRset [] current; private int count; private boolean wantLastSOA; ZoneIterator(boolean axfr) { synchronized (Zone.this) { zentries = data.entrySet().iterator(); } wantLastSOA = axfr; RRset [] sets = allRRsets(originNode); current = new RRset[sets.length]; for (int i = 0, j = 2; i < sets.length; i++) { int type = sets[i].getType(); if (type == Type.SOA) { current[0] = sets[i]; } else if (type == Type.NS) { current[1] = sets[i]; } else { current[j++] = sets[i]; } } } public boolean hasNext() { return (current != null || wantLastSOA); } public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } if (current == null) { wantLastSOA = false; return oneRRset(originNode, Type.SOA); } Object set = current[count++]; if (count == current.length) { current = null; while (zentries.hasNext()) { Map.Entry entry = (Map.Entry) zentries.next(); if (entry.getKey().equals(origin)) { continue; } RRset [] sets = allRRsets(entry.getValue()); if (sets.length == 0) { continue; } current = sets; count = 0; break; } } return set; } public void remove() { throw new UnsupportedOperationException(); } } private void validate() throws IOException { originNode = exactName(origin); if (originNode == null) { throw new IOException(origin + ": no data specified"); } RRset rrset = oneRRset(originNode, Type.SOA); if (rrset == null || rrset.size() != 1) { throw new IOException(origin + ": exactly 1 SOA must be specified"); } Iterator it = rrset.rrs(); SOA = (SOARecord) it.next(); NS = oneRRset(originNode, Type.NS); if (NS == null) { throw new IOException(origin + ": no NS set specified"); } } private final void maybeAddRecord(Record record) throws IOException { int rtype = record.getType(); Name name = record.getName(); if (rtype == Type.SOA && !name.equals(origin)) { throw new IOException("SOA owner " + name + " does not match zone origin " + origin); } if (name.subdomain(origin)) { addRecord(record); } } /** * Creates a Zone from the records in the specified master file. * @param zone The name of the zone. * @param file The master file to read from. * @see Master */ public Zone(Name zone, String file) throws IOException { data = new TreeMap(); if (zone == null) { throw new IllegalArgumentException("no zone name specified"); } Master m = new Master(file, zone); Record record; origin = zone; while ((record = m.nextRecord()) != null) { maybeAddRecord(record); } validate(); } /** * Creates a Zone from an array of records. * @param zone The name of the zone. * @param records The records to add to the zone. * @see Master */ public Zone(Name zone, Record [] records) throws IOException { data = new TreeMap(); if (zone == null) { throw new IllegalArgumentException("no zone name specified"); } origin = zone; for (int i = 0; i < records.length; i++) { maybeAddRecord(records[i]); } validate(); } private void fromXFR(ZoneTransferIn xfrin) throws IOException, ZoneTransferException { data = new TreeMap(); origin = xfrin.getName(); List records = xfrin.run(); for (Iterator it = records.iterator(); it.hasNext(); ) { Record record = (Record) it.next(); maybeAddRecord(record); } if (!xfrin.isAXFR()) { throw new IllegalArgumentException("zones can only be " + "created from AXFRs"); } validate(); } /** * Creates a Zone by doing the specified zone transfer. * @param xfrin The incoming zone transfer to execute. * @see ZoneTransferIn */ public Zone(ZoneTransferIn xfrin) throws IOException, ZoneTransferException { fromXFR(xfrin); } /** * Creates a Zone by performing a zone transfer to the specified host. * @see ZoneTransferIn */ public Zone(Name zone, int dclass, String remote) throws IOException, ZoneTransferException { ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(zone, remote, null); xfrin.setDClass(dclass); fromXFR(xfrin); } /** Returns the Zone's origin */ public Name getOrigin() { return origin; } /** Returns the Zone origin's NS records */ public RRset getNS() { return NS; } /** Returns the Zone's SOA record */ public SOARecord getSOA() { return SOA; } /** Returns the Zone's class */ public int getDClass() { return dclass; } private synchronized Object exactName(Name name) { return data.get(name); } private synchronized RRset [] allRRsets(Object types) { if (types instanceof List) { List typelist = (List) types; return (RRset []) typelist.toArray(new RRset[typelist.size()]); } else { RRset set = (RRset) types; return new RRset [] {set}; } } private synchronized RRset oneRRset(Object types, int type) { if (type == Type.ANY) { throw new IllegalArgumentException("oneRRset(ANY)"); } if (types instanceof List) { List list = (List) types; for (int i = 0; i < list.size(); i++) { RRset set = (RRset) list.get(i); if (set.getType() == type) { return set; } } } else { RRset set = (RRset) types; if (set.getType() == type) { return set; } } return null; } private synchronized RRset findRRset(Name name, int type) { Object types = exactName(name); if (types == null) { return null; } return oneRRset(types, type); } private synchronized void addRRset(Name name, RRset rrset) { if (!hasWild && name.isWild()) { hasWild = true; } Object types = data.get(name); if (types == null) { data.put(name, rrset); return; } int rtype = rrset.getType(); if (types instanceof List) { List list = (List) types; for (int i = 0; i < list.size(); i++) { RRset set = (RRset) list.get(i); if (set.getType() == rtype) { list.set(i, rrset); return; } } list.add(rrset); } else { RRset set = (RRset) types; if (set.getType() == rtype) { data.put(name, rrset); } else { LinkedList list = new LinkedList(); list.add(set); list.add(rrset); data.put(name, list); } } } private synchronized void removeRRset(Name name, int type) { Object types = data.get(name); if (types == null) { return; } if (types instanceof List) { List list = (List) types; for (int i = 0; i < list.size(); i++) { RRset set = (RRset) list.get(i); if (set.getType() == type) { list.remove(i); if (list.size() == 0) { data.remove(name); } return; } } } else { RRset set = (RRset) types; if (set.getType() != type) { return; } data.remove(name); } } private synchronized SetResponse lookup(Name name, int type) { int labels; int olabels; int tlabels; RRset rrset; Name tname; Object types; SetResponse sr; if (!name.subdomain(origin)) { return SetResponse.ofType(SetResponse.NXDOMAIN); } labels = name.labels(); olabels = origin.labels(); for (tlabels = olabels; tlabels <= labels; tlabels++) { boolean isOrigin = (tlabels == olabels); boolean isExact = (tlabels == labels); if (isOrigin) { tname = origin; } else if (isExact) { tname = name; } else { tname = new Name(name, labels - tlabels); } types = exactName(tname); if (types == null) continue; /* If this is a delegation, return that. */ if (!isOrigin) { RRset ns = oneRRset(types, Type.NS); if (ns != null) { return new SetResponse(SetResponse.DELEGATION, ns); } } /* If this is an ANY lookup, return everything. */ if (isExact && type == Type.ANY) { sr = new SetResponse(SetResponse.SUCCESSFUL); RRset [] sets = allRRsets(types); for (int i = 0; i < sets.length; i++) { sr.addRRset(sets[i]); } return sr; } /* * If this is the name, look for the actual type or a CNAME. * Otherwise, look for a DNAME. */ if (isExact) { rrset = oneRRset(types, type); if (rrset != null) { sr = new SetResponse(SetResponse.SUCCESSFUL); sr.addRRset(rrset); return sr; } rrset = oneRRset(types, Type.CNAME); if (rrset != null) { return new SetResponse(SetResponse.CNAME, rrset); } } else { rrset = oneRRset(types, Type.DNAME); if (rrset != null) { return new SetResponse(SetResponse.DNAME, rrset); } } /* We found the name, but not the type. */ if (isExact) { return SetResponse.ofType(SetResponse.NXRRSET); } } if (hasWild) { for (int i = 0; i < labels - olabels; i++) { tname = name.wild(i + 1); types = exactName(tname); if (types == null) { continue; } rrset = oneRRset(types, type); if (rrset != null) { sr = new SetResponse(SetResponse.SUCCESSFUL); sr.addRRset(rrset); return sr; } } } return SetResponse.ofType(SetResponse.NXDOMAIN); } /** * Looks up Records in the Zone. This follows CNAMEs and wildcards. * @param name The name to look up * @param type The type to look up * @return A SetResponse object * @see SetResponse */ public SetResponse findRecords(Name name, int type) { return lookup(name, type); } /** * Looks up Records in the zone, finding exact matches only. * @param name The name to look up * @param type The type to look up * @return The matching RRset * @see RRset */ public RRset findExactMatch(Name name, int type) { Object types = exactName(name); if (types == null) { return null; } return oneRRset(types, type); } /** * Adds an RRset to the Zone * @param rrset The RRset to be added * @see RRset */ public void addRRset(RRset rrset) { Name name = rrset.getName(); addRRset(name, rrset); } /** * Adds a Record to the Zone * @param r The record to be added * @see Record */ public void addRecord(Record r) { Name name = r.getName(); int rtype = r.getRRsetType(); synchronized (this) { RRset rrset = findRRset(name, rtype); if (rrset == null) { rrset = new RRset(r); addRRset(name, rrset); } else { rrset.addRR(r); } } } /** * Removes a record from the Zone * @param r The record to be removed * @see Record */ public void removeRecord(Record r) { Name name = r.getName(); int rtype = r.getRRsetType(); synchronized (this) { RRset rrset = findRRset(name, rtype); if (rrset == null) { return; } if (rrset.size() == 1 && rrset.first().equals(r)) { removeRRset(name, rtype); } else { rrset.deleteRR(r); } } } /** * Returns an Iterator over the RRsets in the zone. */ public Iterator iterator() { return new ZoneIterator(false); } /** * Returns an Iterator over the RRsets in the zone that can be used to * construct an AXFR response. This is identical to {@link #iterator} except * that the SOA is returned at the end as well as the beginning. */ public Iterator AXFR() { return new ZoneIterator(true); } private void nodeToString(StringBuffer sb, Object node) { RRset [] sets = allRRsets(node); for (int i = 0; i < sets.length; i++) { RRset rrset = sets[i]; Iterator it = rrset.rrs(); while (it.hasNext()) { sb.append(it.next() + "\n"); } it = rrset.sigs(); while (it.hasNext()) { sb.append(it.next() + "\n"); } } } /** * Returns the contents of the Zone in master file format. */ public synchronized String toMasterFile() { Iterator zentries = data.entrySet().iterator(); StringBuffer sb = new StringBuffer(); nodeToString(sb, originNode); while (zentries.hasNext()) { Map.Entry entry = (Map.Entry) zentries.next(); if (!origin.equals(entry.getKey())) { nodeToString(sb, entry.getValue()); } } return sb.toString(); } /** * Returns the contents of the Zone as a string (in master file format). */ public String toString() { return toMasterFile(); } } // end Zone.java, line 559
/*- * -\-\- * Spotify Styx Common * -- * Copyright (C) 2016 Spotify AB * -- * 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.spotify.styx.storage; import static com.spotify.styx.serialization.Json.deserializeEvent; import static com.spotify.styx.serialization.Json.serialize; import static com.spotify.styx.util.CloserUtil.register; import static java.util.stream.Collectors.toList; import com.github.rholder.retry.Attempt; import com.github.rholder.retry.RetryException; import com.github.rholder.retry.Retryer; import com.github.rholder.retry.RetryerBuilder; import com.github.rholder.retry.StopStrategies; import com.github.rholder.retry.StopStrategy; import com.github.rholder.retry.WaitStrategies; import com.github.rholder.retry.WaitStrategy; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.Sets; import com.google.common.io.Closer; import com.spotify.styx.model.Event; import com.spotify.styx.model.SequenceEvent; import com.spotify.styx.model.WorkflowId; import com.spotify.styx.model.WorkflowInstance; import com.spotify.styx.model.data.WorkflowInstanceExecutionData; import com.spotify.styx.util.MDCUtil; import com.spotify.styx.util.ResourceNotFoundException; import io.grpc.Context; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.TimeUnit; import okio.ByteString; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.util.Bytes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A backend for {@link AggregateStorage} backed by Google Bigtable */ public class BigtableStorage implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(BigtableStorage.class); public static final TableName EVENTS_TABLE_NAME = TableName.valueOf("styx_events"); private static final byte[] EVENT_CF = Bytes.toBytes("event"); private static final byte[] EVENT_QUALIFIER = Bytes.toBytes("event"); private static final int REQUEST_CONCURRENCY = 32; private static final WaitStrategy DEFAULT_WAIT_STRATEGY = WaitStrategies.fixedWait(1, TimeUnit.SECONDS); private static final StopStrategy DEFAULT_RETRY_STOP_STRATEGY = StopStrategies.stopAfterAttempt(100); private final Closer closer = Closer.create(); private final Connection connection; private final Retryer<Void> retryer; private final Executor executor; BigtableStorage(Connection connection) { this(connection, new ForkJoinPool(REQUEST_CONCURRENCY), DEFAULT_WAIT_STRATEGY, DEFAULT_RETRY_STOP_STRATEGY); } @VisibleForTesting BigtableStorage(Connection connection, ExecutorService executor, WaitStrategy waitStrategy, StopStrategy retryStopStrategy) { this.connection = Objects.requireNonNull(connection, "connection"); this.executor = MDCUtil.withMDC(Context.currentContextExecutor( register(closer, Objects.requireNonNull(executor, "executor"), "bigtable-storage"))); retryer = RetryerBuilder.<Void>newBuilder() .retryIfExceptionOfType(IOException.class) .withWaitStrategy(Objects.requireNonNull(waitStrategy, "waitStrategy")) .withStopStrategy(Objects.requireNonNull(retryStopStrategy, "retryStopStrategy")) .withRetryListener(BigtableStorage::onRequestAttempt) .build(); } @Override public void close() throws IOException { closer.close(); } SortedSet<SequenceEvent> readEvents(WorkflowInstance workflowInstance) throws IOException { try (final Table eventsTable = connection.getTable(EVENTS_TABLE_NAME)) { final Scan scan = new Scan() .setRowPrefixFilter(Bytes.toBytes(workflowInstance.toKey() + '#')); final SortedSet<SequenceEvent> set = newSortedEventSet(); for (Result result : eventsTable.getScanner(scan)) { set.add(parseEventResult(result)); } return set; } } void writeEvent(SequenceEvent sequenceEvent) throws IOException { try { retryer.call(() -> { try (final Table eventsTable = connection.getTable(EVENTS_TABLE_NAME)) { final String workflowInstanceKey = sequenceEvent.event().workflowInstance().toKey(); final String keyString = String.format("%s#%08d", workflowInstanceKey, sequenceEvent.counter()); final byte[] key = Bytes.toBytes(keyString); final Put put = new Put(key, sequenceEvent.timestamp()); final byte[] eventBytes = serialize(sequenceEvent.event()).toByteArray(); put.addColumn(EVENT_CF, EVENT_QUALIFIER, eventBytes); eventsTable.put(put); return null; } }); } catch (ExecutionException | RetryException e) { var cause = e.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } else { throw new RuntimeException(cause); } } } List<WorkflowInstanceExecutionData> executionData(WorkflowId workflowId, String offset, int limit) throws IOException { try (final Table eventsTable = connection.getTable(EVENTS_TABLE_NAME)) { final Scan scan = new Scan() .setRowPrefixFilter(Bytes.toBytes(workflowId.toKey() + '#')) .setFilter(new FirstKeyOnlyFilter()); if (!Strings.isNullOrEmpty(offset)) { final WorkflowInstance offsetInstance = WorkflowInstance.create(workflowId, offset); scan.setStartRow(Bytes.toBytes(offsetInstance.toKey() + '#')); } final Set<WorkflowInstance> workflowInstancesSet = Sets.newHashSet(); try (ResultScanner scanner = eventsTable.getScanner(scan)) { Result result = scanner.next(); while (result != null) { final String key = new String(result.getRow()); final int lastHash = key.lastIndexOf('#'); final WorkflowInstance wfi = WorkflowInstance.parseKey(key.substring(0, lastHash)); workflowInstancesSet.add(wfi); if (workflowInstancesSet.size() == limit) { break; } result = scanner.next(); } } return executionData(workflowInstancesSet); } } List<WorkflowInstanceExecutionData> executionData(WorkflowId workflowId, String start, String stop) throws IOException { try (final Table eventsTable = connection.getTable(EVENTS_TABLE_NAME)) { final Scan scan = new Scan() .setRowPrefixFilter(Bytes.toBytes(workflowId.toKey() + '#')) .setFilter(new FirstKeyOnlyFilter()); final WorkflowInstance startRow = WorkflowInstance.create(workflowId, start); scan.setStartRow(Bytes.toBytes(startRow.toKey() + '#')); if (!Strings.isNullOrEmpty(stop)) { final WorkflowInstance stopRow = WorkflowInstance.create(workflowId, stop); scan.setStopRow(Bytes.toBytes(stopRow.toKey() + '#')); } final Set<WorkflowInstance> workflowInstancesSet = Sets.newHashSet(); try (ResultScanner scanner = eventsTable.getScanner(scan)) { Result result = scanner.next(); while (result != null) { final String key = new String(result.getRow()); final int lastHash = key.lastIndexOf('#'); final WorkflowInstance wfi = WorkflowInstance.parseKey(key.substring(0, lastHash)); workflowInstancesSet.add(wfi); result = scanner.next(); } } return executionData(workflowInstancesSet); } } Optional<Long> getLatestStoredCounter(WorkflowInstance workflowInstance) throws IOException { final Set<SequenceEvent> storedEvents = readEvents(workflowInstance); final Optional<SequenceEvent> lastStoredEvent = storedEvents.stream().reduce((a, b) -> b); return lastStoredEvent.map(SequenceEvent::counter); } WorkflowInstanceExecutionData executionData(WorkflowInstance workflowInstance) throws IOException { SortedSet<SequenceEvent> events = readEvents(workflowInstance); if (events.isEmpty()) { throw new ResourceNotFoundException("Workflow instance not found"); } return new WFIExecutionBuilder().executionInfo(events); } private List<WorkflowInstanceExecutionData> executionData( Set<WorkflowInstance> workflowInstancesSet) { return workflowInstancesSet.stream() .map(workflowInstance -> asyncIO(() -> executionData(workflowInstance))) .collect(toList()) .stream() .map(CompletableFuture::join) .sorted(WorkflowInstanceExecutionData.COMPARATOR) .collect(toList()); } private SequenceEvent parseEventResult(Result r) throws IOException { final String key = new String(r.getRow()); final long timestamp = r.getColumnLatestCell(EVENT_CF, EVENT_QUALIFIER).getTimestamp(); final byte[] value = r.getValue(EVENT_CF, EVENT_QUALIFIER); final Event event = deserializeEvent(ByteString.of(value)); return SequenceEvent.parseKey(key, event, timestamp); } private <T> CompletableFuture<T> asyncIO(IOOperation<T> f) { return f.executeAsync(executor); } private static <T> void onRequestAttempt(Attempt<T> attempt) { if (attempt.hasException()) { LOG.warn(String.format("Failed to write to Bigtable (attempt #%d)", attempt.getAttemptNumber()), attempt.getExceptionCause()); } } private static TreeSet<SequenceEvent> newSortedEventSet() { return Sets.newTreeSet(SequenceEvent.COUNTER_COMPARATOR); } }
/** * 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.mapreduce; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.testclassification.LargeTests; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.LauncherSecurityManager; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.util.GenericOptionsParser; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Basic test for the CopyTable M/R tool */ @Category(LargeTests.class) public class TestCopyTable { private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); private static final byte[] ROW1 = Bytes.toBytes("row1"); private static final byte[] ROW2 = Bytes.toBytes("row2"); private static final String FAMILY_A_STRING = "a"; private static final String FAMILY_B_STRING = "b"; private static final byte[] FAMILY_A = Bytes.toBytes(FAMILY_A_STRING); private static final byte[] FAMILY_B = Bytes.toBytes(FAMILY_B_STRING); private static final byte[] QUALIFIER = Bytes.toBytes("q"); @BeforeClass public static void beforeClass() throws Exception { TEST_UTIL.startMiniCluster(3); TEST_UTIL.startMiniMapReduceCluster(); } @AfterClass public static void afterClass() throws Exception { TEST_UTIL.shutdownMiniMapReduceCluster(); TEST_UTIL.shutdownMiniCluster(); } private void doCopyTableTest(boolean bulkload) throws Exception { final TableName TABLENAME1 = TableName.valueOf("testCopyTable1"); final TableName TABLENAME2 = TableName.valueOf("testCopyTable2"); final byte[] FAMILY = Bytes.toBytes("family"); final byte[] COLUMN1 = Bytes.toBytes("c1"); Table t1 = TEST_UTIL.createTable(TABLENAME1, FAMILY); Table t2 = TEST_UTIL.createTable(TABLENAME2, FAMILY); // put rows into the first table for (int i = 0; i < 10; i++) { Put p = new Put(Bytes.toBytes("row" + i)); p.add(FAMILY, COLUMN1, COLUMN1); t1.put(p); } CopyTable copy = new CopyTable(TEST_UTIL.getConfiguration()); int code; if (bulkload) { code = copy.run(new String[] { "--new.name=" + TABLENAME2.getNameAsString(), "--bulkload", TABLENAME1.getNameAsString() }); } else { code = copy.run(new String[] { "--new.name=" + TABLENAME2.getNameAsString(), TABLENAME1.getNameAsString() }); } assertEquals("copy job failed", 0, code); // verify the data was copied into table 2 for (int i = 0; i < 10; i++) { Get g = new Get(Bytes.toBytes("row" + i)); Result r = t2.get(g); assertEquals(1, r.size()); assertTrue(CellUtil.matchingQualifier(r.rawCells()[0], COLUMN1)); } t1.close(); t2.close(); TEST_UTIL.deleteTable(TABLENAME1); TEST_UTIL.deleteTable(TABLENAME2); } /** * Simple end-to-end test * @throws Exception */ @Test public void testCopyTable() throws Exception { doCopyTableTest(false); } /** * Simple end-to-end test with bulkload. */ @Test public void testCopyTableWithBulkload() throws Exception { doCopyTableTest(true); } @Test public void testStartStopRow() throws Exception { final TableName TABLENAME1 = TableName.valueOf("testStartStopRow1"); final TableName TABLENAME2 = TableName.valueOf("testStartStopRow2"); final byte[] FAMILY = Bytes.toBytes("family"); final byte[] COLUMN1 = Bytes.toBytes("c1"); final byte[] ROW0 = Bytes.toBytes("row0"); final byte[] ROW1 = Bytes.toBytes("row1"); final byte[] ROW2 = Bytes.toBytes("row2"); Table t1 = TEST_UTIL.createTable(TABLENAME1, FAMILY); Table t2 = TEST_UTIL.createTable(TABLENAME2, FAMILY); // put rows into the first table Put p = new Put(ROW0); p.add(FAMILY, COLUMN1, COLUMN1); t1.put(p); p = new Put(ROW1); p.add(FAMILY, COLUMN1, COLUMN1); t1.put(p); p = new Put(ROW2); p.add(FAMILY, COLUMN1, COLUMN1); t1.put(p); CopyTable copy = new CopyTable(TEST_UTIL.getConfiguration()); assertEquals( 0, copy.run(new String[] { "--new.name=" + TABLENAME2, "--startrow=row1", "--stoprow=row2", TABLENAME1.getNameAsString() })); // verify the data was copied into table 2 // row1 exist, row0, row2 do not exist Get g = new Get(ROW1); Result r = t2.get(g); assertEquals(1, r.size()); assertTrue(CellUtil.matchingQualifier(r.rawCells()[0], COLUMN1)); g = new Get(ROW0); r = t2.get(g); assertEquals(0, r.size()); g = new Get(ROW2); r = t2.get(g); assertEquals(0, r.size()); t1.close(); t2.close(); TEST_UTIL.deleteTable(TABLENAME1); TEST_UTIL.deleteTable(TABLENAME2); } /** * Test copy of table from sourceTable to targetTable all rows from family a */ @Test public void testRenameFamily() throws Exception { String sourceTable = "sourceTable"; String targetTable = "targetTable"; byte[][] families = { FAMILY_A, FAMILY_B }; Table t = TEST_UTIL.createTable(Bytes.toBytes(sourceTable), families); Table t2 = TEST_UTIL.createTable(Bytes.toBytes(targetTable), families); Put p = new Put(ROW1); p.add(FAMILY_A, QUALIFIER, Bytes.toBytes("Data11")); p.add(FAMILY_B, QUALIFIER, Bytes.toBytes("Data12")); p.add(FAMILY_A, QUALIFIER, Bytes.toBytes("Data13")); t.put(p); p = new Put(ROW2); p.add(FAMILY_B, QUALIFIER, Bytes.toBytes("Dat21")); p.add(FAMILY_A, QUALIFIER, Bytes.toBytes("Data22")); p.add(FAMILY_B, QUALIFIER, Bytes.toBytes("Data23")); t.put(p); long currentTime = System.currentTimeMillis(); String[] args = new String[] { "--new.name=" + targetTable, "--families=a:b", "--all.cells", "--starttime=" + (currentTime - 100000), "--endtime=" + (currentTime + 100000), "--versions=1", sourceTable }; assertNull(t2.get(new Get(ROW1)).getRow()); assertTrue(runCopy(args)); assertNotNull(t2.get(new Get(ROW1)).getRow()); Result res = t2.get(new Get(ROW1)); byte[] b1 = res.getValue(FAMILY_B, QUALIFIER); assertEquals("Data13", new String(b1)); assertNotNull(t2.get(new Get(ROW2)).getRow()); res = t2.get(new Get(ROW2)); b1 = res.getValue(FAMILY_A, QUALIFIER); // Data from the family of B is not copied assertNull(b1); } /** * Test main method of CopyTable. */ @Test public void testMainMethod() throws Exception { String[] emptyArgs = { "-h" }; PrintStream oldWriter = System.err; ByteArrayOutputStream data = new ByteArrayOutputStream(); PrintStream writer = new PrintStream(data); System.setErr(writer); SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSecurityManager newSecurityManager= new LauncherSecurityManager(); System.setSecurityManager(newSecurityManager); try { CopyTable.main(emptyArgs); fail("should be exit"); } catch (SecurityException e) { assertEquals(1, newSecurityManager.getExitCode()); } finally { System.setErr(oldWriter); System.setSecurityManager(SECURITY_MANAGER); } assertTrue(data.toString().contains("rs.class")); // should print usage information assertTrue(data.toString().contains("Usage:")); } private boolean runCopy(String[] args) throws IOException, InterruptedException, ClassNotFoundException { GenericOptionsParser opts = new GenericOptionsParser( new Configuration(TEST_UTIL.getConfiguration()), args); Configuration configuration = opts.getConfiguration(); args = opts.getRemainingArgs(); Job job = new CopyTable(configuration).createSubmittableJob(args); job.waitForCompletion(false); return job.isSuccessful(); } }
/* * Copyright 2006-2021 Prowide * * 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.prowidesoftware.swift.model.field; import com.prowidesoftware.swift.model.Tag; import com.prowidesoftware.Generated; import com.prowidesoftware.deprecation.ProwideDeprecated; import com.prowidesoftware.deprecation.TargetYear; import java.io.Serializable; import java.util.Locale; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import org.apache.commons.lang3.StringUtils; import com.prowidesoftware.swift.model.field.SwiftParseUtils; import com.prowidesoftware.swift.model.field.Field; import com.prowidesoftware.swift.model.*; import com.prowidesoftware.swift.utils.SwiftFormatUtils; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * SWIFT MT Field 341. * <p> * Model and parser for field 341 of a SWIFT MT message. * * <p>Subfields (components) Data types * <ol> * <li><code>String</code></li> * </ol> * * <p>Structure definition * <ul> * <li>validation pattern: <code>2!c</code></li> * <li>parser pattern: <code>S</code></li> * <li>components pattern: <code>S</code></li> * </ul> * * <p> * This class complies with standard release <strong>SRU2021</strong> */ @SuppressWarnings("unused") @Generated public class Field341 extends Field implements Serializable { /** * Constant identifying the SRU to which this class belongs to. */ public static final int SRU = 2021; private static final long serialVersionUID = 1L; /** * Constant with the field name 341. */ public static final String NAME = "341"; /** * Same as NAME, intended to be clear when using static imports. */ public static final String F_341 = "341"; /** * @deprecated use {@link #parserPattern()} method instead. */ @Deprecated @ProwideDeprecated(phase2 = TargetYear.SRU2022) public static final String PARSER_PATTERN = "S"; /** * @deprecated use {@link #typesPattern()} method instead. */ @Deprecated @ProwideDeprecated(phase2 = TargetYear.SRU2022) public static final String COMPONENTS_PATTERN = "S"; /** * @deprecated use {@link #typesPattern()} method instead. */ @Deprecated @ProwideDeprecated(phase2 = TargetYear.SRU2022) public static final String TYPES_PATTERN = "S"; /** * Component number for the Generation Time Options subfield. */ public static final Integer GENERATION_TIME_OPTIONS = 1; /** * Default constructor. Creates a new field setting all components to null. */ public Field341() { super(1); } /** * Creates a new field and initializes its components with content from the parameter value. * @param value complete field value including separators and CRLF */ public Field341(final String value) { super(value); } /** * Creates a new field and initializes its components with content from the parameter tag. * The value is parsed with {@link #parse(String)} * @throws IllegalArgumentException if the parameter tag is null or its tagname does not match the field name * @since 7.8 */ public Field341(final Tag tag) { this(); if (tag == null) { throw new IllegalArgumentException("tag cannot be null."); } if (!StringUtils.equals(tag.getName(), "341")) { throw new IllegalArgumentException("cannot create field 341 from tag "+tag.getName()+", tagname must match the name of the field."); } parse(tag.getValue()); } /** * Copy constructor. * Initializes the components list with a deep copy of the source components list. * @param source a field instance to copy * @since 7.7 */ public static Field341 newInstance(Field341 source) { Field341 cp = new Field341(); cp.setComponents(new ArrayList<>(source.getComponents())); return cp; } /** * Create a Tag with this field name and the given value. * Shorthand for <code>new Tag(NAME, value)</code> * @see #NAME * @since 7.5 */ public static Tag tag(final String value) { return new Tag(NAME, value); } /** * Create a Tag with this field name and an empty string as value. * Shorthand for <code>new Tag(NAME, "")</code> * @see #NAME * @since 7.5 */ public static Tag emptyTag() { return new Tag(NAME, ""); } /** * Parses the parameter value into the internal components structure. * * <p>Used to update all components from a full new value, as an alternative * to setting individual components. Previous component values are overwritten. * * @param value complete field value including separators and CRLF * @since 7.8 */ @Override public void parse(final String value) { init(1); setComponent1(value); } /** * Serializes the fields' components into the single string value (SWIFT format) */ @Override public String getValue() { final StringBuilder result = new StringBuilder(); append(result, 1); return result.toString(); } /** * Returns a localized suitable for showing to humans string of a field component.<br> * * @param component number of the component to display * @param locale optional locale to format date and amounts, if null, the default locale is used * @return formatted component value or null if component number is invalid or not present * @throws IllegalArgumentException if component number is invalid for the field * @since 7.8 */ @Override public String getValueDisplay(int component, Locale locale) { if (component < 1 || component > 1) { throw new IllegalArgumentException("invalid component number " + component + " for field 341"); } if (component == 1) { //default format (as is) return getComponent(1); } return null; } /** * @deprecated use {@link #typesPattern()} instead. */ @Override @Deprecated @ProwideDeprecated(phase2 = TargetYear.SRU2022) public String componentsPattern() { return "S"; } /** * Returns the field component types pattern. * * This method returns a letter representing the type for each component in the Field. It supersedes * the Components Pattern because it distinguishes between N (Number) and I (BigDecimal). * @since 9.2.7 */ @Override public String typesPattern() { return "S"; } /** * Returns the field parser pattern. */ @Override public String parserPattern() { return "S"; } /** * Returns the field validator pattern */ @Override public String validatorPattern() { return "2!c"; } /** * Given a component number it returns true if the component is optional, * regardless of the field being mandatory in a particular message.<br> * Being the field's value conformed by a composition of one or several * internal component values, the field may be present in a message with * a proper value but with some of its internal components not set. * * @param component component number, first component of a field is referenced as 1 * @return true if the component is optional for this field, false otherwise */ @Override public boolean isOptional(int component) { return false; } /** * Returns true if the field is a GENERIC FIELD as specified by the standard. * @return true if the field is generic, false otherwise */ @Override public boolean isGeneric() { return false; } /** * Returns the defined amount of components.<br> * This is not the amount of components present in the field instance, but the total amount of components * that this field accepts as defined. * @since 7.7 */ @Override public int componentsSize() { return 1; } /** * Returns english label for components. * <br> * The index in the list is in sync with specific field component structure. * @see #getComponentLabel(int) * @since 7.8.4 */ @Override public List<String> getComponentLabels() { List<String> result = new ArrayList<>(); result.add("Generation Time Options"); return result; } /** * Returns a mapping between component numbers and their label in camel case format. * @since 7.10.3 */ @Override protected Map<Integer, String> getComponentMap() { Map<Integer, String> result = new HashMap<>(); result.put(1, "generationTimeOptions"); return result; } /** * Gets the component 1 (Generation Time Options). * @return the component 1 */ public String getComponent1() { return getComponent(1); } /** * Gets the Generation Time Options (component 1). * @return the Generation Time Options from component 1 */ public String getGenerationTimeOptions() { return getComponent1(); } /** * Set the component 1 (Generation Time Options). * * @param component1 the Generation Time Options to set * @return the field object to enable build pattern */ public Field341 setComponent1(String component1) { setComponent(1, component1); return this; } /** * Set the Generation Time Options (component 1). * * @param component1 the Generation Time Options to set * @return the field object to enable build pattern */ public Field341 setGenerationTimeOptions(String component1) { return setComponent1(component1); } /** * Returns the field's name composed by the field number and the letter option (if any). * @return the static value of Field341.NAME */ @Override public String getName() { return NAME; } /** * Gets the first occurrence form the tag list or null if not found. * @return null if not found o block is null or empty * @param block may be null or empty */ public static Field341 get(final SwiftTagListBlock block) { if (block == null || block.isEmpty()) { return null; } final Tag t = block.getTagByName(NAME); if (t == null) { return null; } return new Field341(t); } /** * Gets the first instance of Field341 in the given message. * @param msg may be empty or null * @return null if not found or msg is empty or null * @see #get(SwiftTagListBlock) */ public static Field341 get(final SwiftMessage msg) { if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty()) { return null; } return get(msg.getBlock4()); } /** * Gets a list of all occurrences of the field Field341 in the given message * an empty list is returned if none found. * @param msg may be empty or null in which case an empty list is returned * @see #getAll(SwiftTagListBlock) */ public static List<Field341> getAll(final SwiftMessage msg) { if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty()) { return java.util.Collections.emptyList(); } return getAll(msg.getBlock4()); } /** * Gets a list of all occurrences of the field Field341 from the given block * an empty list is returned if none found. * * @param block may be empty or null in which case an empty list is returned */ public static List<Field341> getAll(final SwiftTagListBlock block) { final List<Field341> result = new ArrayList<>(); if (block == null || block.isEmpty()) { return result; } final Tag[] arr = block.getTagsByName(NAME); if (arr != null && arr.length > 0) { for (final Tag f : arr) { result.add(new Field341(f)); } } return result; } /** * This method deserializes the JSON data into a Field341 object. * @param json JSON structure including tuples with label and value for all field components * @return a new field instance with the JSON data parsed into field components or an empty field id the JSON is invalid * @since 7.10.3 * @see Field#fromJson(String) */ public static Field341 fromJson(final String json) { final Field341 field = new Field341(); final JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject(); // **** COMPONENT 1 - Generation Time Options if (jsonObject.get("generationTimeOptions") != null) { field.setComponent1(jsonObject.get("generationTimeOptions").getAsString()); } return field; } }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.speech.v1.model; /** * Provides information to the recognizer that specifies how to process the request. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Speech-to-Text API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class RecognitionConfig extends com.google.api.client.json.GenericJson { /** * Speech adaptation configuration improves the accuracy of speech recognition. For more * information, see the [speech adaptation](https://cloud.google.com/speech-to- * text/docs/adaptation) documentation. When speech adaptation is set it supersedes the * `speech_contexts` field. * The value may be {@code null}. */ @com.google.api.client.util.Key private SpeechAdaptation adaptation; /** * A list of up to 3 additional [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language * tags, listing possible alternative languages of the supplied audio. See [Language * Support](https://cloud.google.com/speech-to-text/docs/languages) for a list of the currently * supported language codes. If alternative languages are listed, recognition result will contain * recognition in the most likely language detected including the main language_code. The * recognition result will include the language tag of the language detected in the audio. Note: * This feature is only supported for Voice Command and Voice Search use cases and performance may * vary for other use cases (e.g., phone call transcription). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> alternativeLanguageCodes; /** * The number of channels in the input audio data. ONLY set this for MULTI-CHANNEL recognition. * Valid values for LINEAR16 and FLAC are `1`-`8`. Valid values for OGG_OPUS are '1'-'254'. Valid * value for MULAW, AMR, AMR_WB and SPEEX_WITH_HEADER_BYTE is only `1`. If `0` or omitted, * defaults to one channel (mono). Note: We only recognize the first channel by default. To * perform independent recognition on each channel set `enable_separate_recognition_per_channel` * to 'true'. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer audioChannelCount; /** * Config to enable speaker diarization and set additional parameters to make diarization better * suited for your application. Note: When this is enabled, we send all the words from the * beginning of the audio for the top alternative in every consecutive STREAMING responses. This * is done in order to improve our speaker tags as our models learn to identify the speakers in * the conversation over time. For non-streaming requests, the diarization results will be * provided only in the top alternative of the FINAL SpeechRecognitionResult. * The value may be {@code null}. */ @com.google.api.client.util.Key private SpeakerDiarizationConfig diarizationConfig; /** * If 'true', adds punctuation to recognition result hypotheses. This feature is only available in * select languages. Setting this for requests in other languages has no effect at all. The * default 'false' value does not add punctuation to result hypotheses. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableAutomaticPunctuation; /** * This needs to be set to `true` explicitly and `audio_channel_count` > 1 to get each channel * recognized separately. The recognition result will contain a `channel_tag` field to state which * channel that result belongs to. If this is not true, we will only recognize the first channel. * The request is billed cumulatively for all channels recognized: `audio_channel_count` * multiplied by the length of the audio. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableSeparateRecognitionPerChannel; /** * The spoken emoji behavior for the call If not set, uses default behavior based on model of * choice If 'true', adds spoken emoji formatting for the request. This will replace spoken emojis * with the corresponding Unicode symbols in the final transcript. If 'false', spoken emojis are * not replaced. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableSpokenEmojis; /** * The spoken punctuation behavior for the call If not set, uses default behavior based on model * of choice e.g. command_and_search will enable spoken punctuation by default If 'true', replaces * spoken punctuation with the corresponding symbols in the request. For example, "how are you * question mark" becomes "how are you?". See https://cloud.google.com/speech-to-text/docs/spoken- * punctuation for support. If 'false', spoken punctuation is not replaced. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableSpokenPunctuation; /** * If `true`, the top result includes a list of words and the confidence for those words. If * `false`, no word-level confidence information is returned. The default is `false`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableWordConfidence; /** * If `true`, the top result includes a list of words and the start and end time offsets * (timestamps) for those words. If `false`, no word-level time offset information is returned. * The default is `false`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enableWordTimeOffsets; /** * Encoding of audio data sent in all `RecognitionAudio` messages. This field is optional for * `FLAC` and `WAV` audio files and required for all other audio formats. For details, see * AudioEncoding. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String encoding; /** * Required. The language of the supplied audio as a [BCP-47](https://www.rfc- * editor.org/rfc/bcp/bcp47.txt) language tag. Example: "en-US". See [Language * Support](https://cloud.google.com/speech-to-text/docs/languages) for a list of the currently * supported language codes. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String languageCode; /** * Maximum number of recognition hypotheses to be returned. Specifically, the maximum number of * `SpeechRecognitionAlternative` messages within each `SpeechRecognitionResult`. The server may * return fewer than `max_alternatives`. Valid values are `0`-`30`. A value of `0` or `1` will * return a maximum of one. If omitted, will return a maximum of one. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer maxAlternatives; /** * Metadata regarding this request. * The value may be {@code null}. */ @com.google.api.client.util.Key private RecognitionMetadata metadata; /** * Which model to select for the given request. Select the model best suited to your domain to get * best results. If a model is not explicitly specified, then we auto-select a model based on the * parameters in the RecognitionConfig. *Model* *Description* command_and_search Best for short * queries such as voice commands or voice search. phone_call Best for audio that originated from * a phone call (typically recorded at an 8khz sampling rate). video Best for audio that * originated from video or includes multiple speakers. Ideally the audio is recorded at a 16khz * or greater sampling rate. This is a premium model that costs more than the standard rate. * default Best for audio that is not one of the specific audio models. For example, long-form * audio. Ideally the audio is high-fidelity, recorded at a 16khz or greater sampling rate. * medical_conversation Best for audio that originated from a conversation between a medical * provider and patient. medical_dictation Best for audio that originated from dictation notes by * a medical provider. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String model; /** * If set to `true`, the server will attempt to filter out profanities, replacing all but the * initial character in each filtered word with asterisks, e.g. "f***". If set to `false` or * omitted, profanities won't be filtered out. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean profanityFilter; /** * Sample rate in Hertz of the audio data sent in all `RecognitionAudio` messages. Valid values * are: 8000-48000. 16000 is optimal. For best results, set the sampling rate of the audio source * to 16000 Hz. If that's not possible, use the native sample rate of the audio source (instead of * re-sampling). This field is optional for FLAC and WAV audio files, but is required for all * other audio formats. For details, see AudioEncoding. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer sampleRateHertz; /** * Array of SpeechContext. A means to provide context to assist the speech recognition. For more * information, see [speech adaptation](https://cloud.google.com/speech-to-text/docs/adaptation). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<SpeechContext> speechContexts; /** * Set to true to use an enhanced model for speech recognition. If `use_enhanced` is set to true * and the `model` field is not set, then an appropriate enhanced model is chosen if an enhanced * model exists for the audio. If `use_enhanced` is true and an enhanced version of the specified * model does not exist, then the speech is recognized using the standard version of the specified * model. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean useEnhanced; /** * Speech adaptation configuration improves the accuracy of speech recognition. For more * information, see the [speech adaptation](https://cloud.google.com/speech-to- * text/docs/adaptation) documentation. When speech adaptation is set it supersedes the * `speech_contexts` field. * @return value or {@code null} for none */ public SpeechAdaptation getAdaptation() { return adaptation; } /** * Speech adaptation configuration improves the accuracy of speech recognition. For more * information, see the [speech adaptation](https://cloud.google.com/speech-to- * text/docs/adaptation) documentation. When speech adaptation is set it supersedes the * `speech_contexts` field. * @param adaptation adaptation or {@code null} for none */ public RecognitionConfig setAdaptation(SpeechAdaptation adaptation) { this.adaptation = adaptation; return this; } /** * A list of up to 3 additional [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language * tags, listing possible alternative languages of the supplied audio. See [Language * Support](https://cloud.google.com/speech-to-text/docs/languages) for a list of the currently * supported language codes. If alternative languages are listed, recognition result will contain * recognition in the most likely language detected including the main language_code. The * recognition result will include the language tag of the language detected in the audio. Note: * This feature is only supported for Voice Command and Voice Search use cases and performance may * vary for other use cases (e.g., phone call transcription). * @return value or {@code null} for none */ public java.util.List<java.lang.String> getAlternativeLanguageCodes() { return alternativeLanguageCodes; } /** * A list of up to 3 additional [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language * tags, listing possible alternative languages of the supplied audio. See [Language * Support](https://cloud.google.com/speech-to-text/docs/languages) for a list of the currently * supported language codes. If alternative languages are listed, recognition result will contain * recognition in the most likely language detected including the main language_code. The * recognition result will include the language tag of the language detected in the audio. Note: * This feature is only supported for Voice Command and Voice Search use cases and performance may * vary for other use cases (e.g., phone call transcription). * @param alternativeLanguageCodes alternativeLanguageCodes or {@code null} for none */ public RecognitionConfig setAlternativeLanguageCodes(java.util.List<java.lang.String> alternativeLanguageCodes) { this.alternativeLanguageCodes = alternativeLanguageCodes; return this; } /** * The number of channels in the input audio data. ONLY set this for MULTI-CHANNEL recognition. * Valid values for LINEAR16 and FLAC are `1`-`8`. Valid values for OGG_OPUS are '1'-'254'. Valid * value for MULAW, AMR, AMR_WB and SPEEX_WITH_HEADER_BYTE is only `1`. If `0` or omitted, * defaults to one channel (mono). Note: We only recognize the first channel by default. To * perform independent recognition on each channel set `enable_separate_recognition_per_channel` * to 'true'. * @return value or {@code null} for none */ public java.lang.Integer getAudioChannelCount() { return audioChannelCount; } /** * The number of channels in the input audio data. ONLY set this for MULTI-CHANNEL recognition. * Valid values for LINEAR16 and FLAC are `1`-`8`. Valid values for OGG_OPUS are '1'-'254'. Valid * value for MULAW, AMR, AMR_WB and SPEEX_WITH_HEADER_BYTE is only `1`. If `0` or omitted, * defaults to one channel (mono). Note: We only recognize the first channel by default. To * perform independent recognition on each channel set `enable_separate_recognition_per_channel` * to 'true'. * @param audioChannelCount audioChannelCount or {@code null} for none */ public RecognitionConfig setAudioChannelCount(java.lang.Integer audioChannelCount) { this.audioChannelCount = audioChannelCount; return this; } /** * Config to enable speaker diarization and set additional parameters to make diarization better * suited for your application. Note: When this is enabled, we send all the words from the * beginning of the audio for the top alternative in every consecutive STREAMING responses. This * is done in order to improve our speaker tags as our models learn to identify the speakers in * the conversation over time. For non-streaming requests, the diarization results will be * provided only in the top alternative of the FINAL SpeechRecognitionResult. * @return value or {@code null} for none */ public SpeakerDiarizationConfig getDiarizationConfig() { return diarizationConfig; } /** * Config to enable speaker diarization and set additional parameters to make diarization better * suited for your application. Note: When this is enabled, we send all the words from the * beginning of the audio for the top alternative in every consecutive STREAMING responses. This * is done in order to improve our speaker tags as our models learn to identify the speakers in * the conversation over time. For non-streaming requests, the diarization results will be * provided only in the top alternative of the FINAL SpeechRecognitionResult. * @param diarizationConfig diarizationConfig or {@code null} for none */ public RecognitionConfig setDiarizationConfig(SpeakerDiarizationConfig diarizationConfig) { this.diarizationConfig = diarizationConfig; return this; } /** * If 'true', adds punctuation to recognition result hypotheses. This feature is only available in * select languages. Setting this for requests in other languages has no effect at all. The * default 'false' value does not add punctuation to result hypotheses. * @return value or {@code null} for none */ public java.lang.Boolean getEnableAutomaticPunctuation() { return enableAutomaticPunctuation; } /** * If 'true', adds punctuation to recognition result hypotheses. This feature is only available in * select languages. Setting this for requests in other languages has no effect at all. The * default 'false' value does not add punctuation to result hypotheses. * @param enableAutomaticPunctuation enableAutomaticPunctuation or {@code null} for none */ public RecognitionConfig setEnableAutomaticPunctuation(java.lang.Boolean enableAutomaticPunctuation) { this.enableAutomaticPunctuation = enableAutomaticPunctuation; return this; } /** * This needs to be set to `true` explicitly and `audio_channel_count` > 1 to get each channel * recognized separately. The recognition result will contain a `channel_tag` field to state which * channel that result belongs to. If this is not true, we will only recognize the first channel. * The request is billed cumulatively for all channels recognized: `audio_channel_count` * multiplied by the length of the audio. * @return value or {@code null} for none */ public java.lang.Boolean getEnableSeparateRecognitionPerChannel() { return enableSeparateRecognitionPerChannel; } /** * This needs to be set to `true` explicitly and `audio_channel_count` > 1 to get each channel * recognized separately. The recognition result will contain a `channel_tag` field to state which * channel that result belongs to. If this is not true, we will only recognize the first channel. * The request is billed cumulatively for all channels recognized: `audio_channel_count` * multiplied by the length of the audio. * @param enableSeparateRecognitionPerChannel enableSeparateRecognitionPerChannel or {@code null} for none */ public RecognitionConfig setEnableSeparateRecognitionPerChannel(java.lang.Boolean enableSeparateRecognitionPerChannel) { this.enableSeparateRecognitionPerChannel = enableSeparateRecognitionPerChannel; return this; } /** * The spoken emoji behavior for the call If not set, uses default behavior based on model of * choice If 'true', adds spoken emoji formatting for the request. This will replace spoken emojis * with the corresponding Unicode symbols in the final transcript. If 'false', spoken emojis are * not replaced. * @return value or {@code null} for none */ public java.lang.Boolean getEnableSpokenEmojis() { return enableSpokenEmojis; } /** * The spoken emoji behavior for the call If not set, uses default behavior based on model of * choice If 'true', adds spoken emoji formatting for the request. This will replace spoken emojis * with the corresponding Unicode symbols in the final transcript. If 'false', spoken emojis are * not replaced. * @param enableSpokenEmojis enableSpokenEmojis or {@code null} for none */ public RecognitionConfig setEnableSpokenEmojis(java.lang.Boolean enableSpokenEmojis) { this.enableSpokenEmojis = enableSpokenEmojis; return this; } /** * The spoken punctuation behavior for the call If not set, uses default behavior based on model * of choice e.g. command_and_search will enable spoken punctuation by default If 'true', replaces * spoken punctuation with the corresponding symbols in the request. For example, "how are you * question mark" becomes "how are you?". See https://cloud.google.com/speech-to-text/docs/spoken- * punctuation for support. If 'false', spoken punctuation is not replaced. * @return value or {@code null} for none */ public java.lang.Boolean getEnableSpokenPunctuation() { return enableSpokenPunctuation; } /** * The spoken punctuation behavior for the call If not set, uses default behavior based on model * of choice e.g. command_and_search will enable spoken punctuation by default If 'true', replaces * spoken punctuation with the corresponding symbols in the request. For example, "how are you * question mark" becomes "how are you?". See https://cloud.google.com/speech-to-text/docs/spoken- * punctuation for support. If 'false', spoken punctuation is not replaced. * @param enableSpokenPunctuation enableSpokenPunctuation or {@code null} for none */ public RecognitionConfig setEnableSpokenPunctuation(java.lang.Boolean enableSpokenPunctuation) { this.enableSpokenPunctuation = enableSpokenPunctuation; return this; } /** * If `true`, the top result includes a list of words and the confidence for those words. If * `false`, no word-level confidence information is returned. The default is `false`. * @return value or {@code null} for none */ public java.lang.Boolean getEnableWordConfidence() { return enableWordConfidence; } /** * If `true`, the top result includes a list of words and the confidence for those words. If * `false`, no word-level confidence information is returned. The default is `false`. * @param enableWordConfidence enableWordConfidence or {@code null} for none */ public RecognitionConfig setEnableWordConfidence(java.lang.Boolean enableWordConfidence) { this.enableWordConfidence = enableWordConfidence; return this; } /** * If `true`, the top result includes a list of words and the start and end time offsets * (timestamps) for those words. If `false`, no word-level time offset information is returned. * The default is `false`. * @return value or {@code null} for none */ public java.lang.Boolean getEnableWordTimeOffsets() { return enableWordTimeOffsets; } /** * If `true`, the top result includes a list of words and the start and end time offsets * (timestamps) for those words. If `false`, no word-level time offset information is returned. * The default is `false`. * @param enableWordTimeOffsets enableWordTimeOffsets or {@code null} for none */ public RecognitionConfig setEnableWordTimeOffsets(java.lang.Boolean enableWordTimeOffsets) { this.enableWordTimeOffsets = enableWordTimeOffsets; return this; } /** * Encoding of audio data sent in all `RecognitionAudio` messages. This field is optional for * `FLAC` and `WAV` audio files and required for all other audio formats. For details, see * AudioEncoding. * @return value or {@code null} for none */ public java.lang.String getEncoding() { return encoding; } /** * Encoding of audio data sent in all `RecognitionAudio` messages. This field is optional for * `FLAC` and `WAV` audio files and required for all other audio formats. For details, see * AudioEncoding. * @param encoding encoding or {@code null} for none */ public RecognitionConfig setEncoding(java.lang.String encoding) { this.encoding = encoding; return this; } /** * Required. The language of the supplied audio as a [BCP-47](https://www.rfc- * editor.org/rfc/bcp/bcp47.txt) language tag. Example: "en-US". See [Language * Support](https://cloud.google.com/speech-to-text/docs/languages) for a list of the currently * supported language codes. * @return value or {@code null} for none */ public java.lang.String getLanguageCode() { return languageCode; } /** * Required. The language of the supplied audio as a [BCP-47](https://www.rfc- * editor.org/rfc/bcp/bcp47.txt) language tag. Example: "en-US". See [Language * Support](https://cloud.google.com/speech-to-text/docs/languages) for a list of the currently * supported language codes. * @param languageCode languageCode or {@code null} for none */ public RecognitionConfig setLanguageCode(java.lang.String languageCode) { this.languageCode = languageCode; return this; } /** * Maximum number of recognition hypotheses to be returned. Specifically, the maximum number of * `SpeechRecognitionAlternative` messages within each `SpeechRecognitionResult`. The server may * return fewer than `max_alternatives`. Valid values are `0`-`30`. A value of `0` or `1` will * return a maximum of one. If omitted, will return a maximum of one. * @return value or {@code null} for none */ public java.lang.Integer getMaxAlternatives() { return maxAlternatives; } /** * Maximum number of recognition hypotheses to be returned. Specifically, the maximum number of * `SpeechRecognitionAlternative` messages within each `SpeechRecognitionResult`. The server may * return fewer than `max_alternatives`. Valid values are `0`-`30`. A value of `0` or `1` will * return a maximum of one. If omitted, will return a maximum of one. * @param maxAlternatives maxAlternatives or {@code null} for none */ public RecognitionConfig setMaxAlternatives(java.lang.Integer maxAlternatives) { this.maxAlternatives = maxAlternatives; return this; } /** * Metadata regarding this request. * @return value or {@code null} for none */ public RecognitionMetadata getMetadata() { return metadata; } /** * Metadata regarding this request. * @param metadata metadata or {@code null} for none */ public RecognitionConfig setMetadata(RecognitionMetadata metadata) { this.metadata = metadata; return this; } /** * Which model to select for the given request. Select the model best suited to your domain to get * best results. If a model is not explicitly specified, then we auto-select a model based on the * parameters in the RecognitionConfig. *Model* *Description* command_and_search Best for short * queries such as voice commands or voice search. phone_call Best for audio that originated from * a phone call (typically recorded at an 8khz sampling rate). video Best for audio that * originated from video or includes multiple speakers. Ideally the audio is recorded at a 16khz * or greater sampling rate. This is a premium model that costs more than the standard rate. * default Best for audio that is not one of the specific audio models. For example, long-form * audio. Ideally the audio is high-fidelity, recorded at a 16khz or greater sampling rate. * medical_conversation Best for audio that originated from a conversation between a medical * provider and patient. medical_dictation Best for audio that originated from dictation notes by * a medical provider. * @return value or {@code null} for none */ public java.lang.String getModel() { return model; } /** * Which model to select for the given request. Select the model best suited to your domain to get * best results. If a model is not explicitly specified, then we auto-select a model based on the * parameters in the RecognitionConfig. *Model* *Description* command_and_search Best for short * queries such as voice commands or voice search. phone_call Best for audio that originated from * a phone call (typically recorded at an 8khz sampling rate). video Best for audio that * originated from video or includes multiple speakers. Ideally the audio is recorded at a 16khz * or greater sampling rate. This is a premium model that costs more than the standard rate. * default Best for audio that is not one of the specific audio models. For example, long-form * audio. Ideally the audio is high-fidelity, recorded at a 16khz or greater sampling rate. * medical_conversation Best for audio that originated from a conversation between a medical * provider and patient. medical_dictation Best for audio that originated from dictation notes by * a medical provider. * @param model model or {@code null} for none */ public RecognitionConfig setModel(java.lang.String model) { this.model = model; return this; } /** * If set to `true`, the server will attempt to filter out profanities, replacing all but the * initial character in each filtered word with asterisks, e.g. "f***". If set to `false` or * omitted, profanities won't be filtered out. * @return value or {@code null} for none */ public java.lang.Boolean getProfanityFilter() { return profanityFilter; } /** * If set to `true`, the server will attempt to filter out profanities, replacing all but the * initial character in each filtered word with asterisks, e.g. "f***". If set to `false` or * omitted, profanities won't be filtered out. * @param profanityFilter profanityFilter or {@code null} for none */ public RecognitionConfig setProfanityFilter(java.lang.Boolean profanityFilter) { this.profanityFilter = profanityFilter; return this; } /** * Sample rate in Hertz of the audio data sent in all `RecognitionAudio` messages. Valid values * are: 8000-48000. 16000 is optimal. For best results, set the sampling rate of the audio source * to 16000 Hz. If that's not possible, use the native sample rate of the audio source (instead of * re-sampling). This field is optional for FLAC and WAV audio files, but is required for all * other audio formats. For details, see AudioEncoding. * @return value or {@code null} for none */ public java.lang.Integer getSampleRateHertz() { return sampleRateHertz; } /** * Sample rate in Hertz of the audio data sent in all `RecognitionAudio` messages. Valid values * are: 8000-48000. 16000 is optimal. For best results, set the sampling rate of the audio source * to 16000 Hz. If that's not possible, use the native sample rate of the audio source (instead of * re-sampling). This field is optional for FLAC and WAV audio files, but is required for all * other audio formats. For details, see AudioEncoding. * @param sampleRateHertz sampleRateHertz or {@code null} for none */ public RecognitionConfig setSampleRateHertz(java.lang.Integer sampleRateHertz) { this.sampleRateHertz = sampleRateHertz; return this; } /** * Array of SpeechContext. A means to provide context to assist the speech recognition. For more * information, see [speech adaptation](https://cloud.google.com/speech-to-text/docs/adaptation). * @return value or {@code null} for none */ public java.util.List<SpeechContext> getSpeechContexts() { return speechContexts; } /** * Array of SpeechContext. A means to provide context to assist the speech recognition. For more * information, see [speech adaptation](https://cloud.google.com/speech-to-text/docs/adaptation). * @param speechContexts speechContexts or {@code null} for none */ public RecognitionConfig setSpeechContexts(java.util.List<SpeechContext> speechContexts) { this.speechContexts = speechContexts; return this; } /** * Set to true to use an enhanced model for speech recognition. If `use_enhanced` is set to true * and the `model` field is not set, then an appropriate enhanced model is chosen if an enhanced * model exists for the audio. If `use_enhanced` is true and an enhanced version of the specified * model does not exist, then the speech is recognized using the standard version of the specified * model. * @return value or {@code null} for none */ public java.lang.Boolean getUseEnhanced() { return useEnhanced; } /** * Set to true to use an enhanced model for speech recognition. If `use_enhanced` is set to true * and the `model` field is not set, then an appropriate enhanced model is chosen if an enhanced * model exists for the audio. If `use_enhanced` is true and an enhanced version of the specified * model does not exist, then the speech is recognized using the standard version of the specified * model. * @param useEnhanced useEnhanced or {@code null} for none */ public RecognitionConfig setUseEnhanced(java.lang.Boolean useEnhanced) { this.useEnhanced = useEnhanced; return this; } @Override public RecognitionConfig set(String fieldName, Object value) { return (RecognitionConfig) super.set(fieldName, value); } @Override public RecognitionConfig clone() { return (RecognitionConfig) super.clone(); } }
/* * Copyright 2012-2021 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 * * 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 org.springframework.boot.test.autoconfigure.web.servlet; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import jakarta.servlet.Filter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.web.servlet.AbstractFilterRegistrationBean; import org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.RegistrationBean; import org.springframework.boot.web.servlet.ServletContextInitializerBeans; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultHandler; import org.springframework.test.web.servlet.result.PrintingResultHandler; import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.context.WebApplicationContext; /** * {@link MockMvcBuilderCustomizer} for a typical Spring Boot application. Usually applied * automatically via {@link AutoConfigureMockMvc @AutoConfigureMockMvc}, but may also be * used directly. * * @author Phillip Webb * @author Andy Wilkinson * @since 1.4.0 */ public class SpringBootMockMvcBuilderCustomizer implements MockMvcBuilderCustomizer { private final WebApplicationContext context; private boolean addFilters = true; private MockMvcPrint print = MockMvcPrint.DEFAULT; private boolean printOnlyOnFailure = true; /** * Create a new {@link SpringBootMockMvcBuilderCustomizer} instance. * @param context the source application context */ public SpringBootMockMvcBuilderCustomizer(WebApplicationContext context) { Assert.notNull(context, "Context must not be null"); this.context = context; } @Override public void customize(ConfigurableMockMvcBuilder<?> builder) { if (this.addFilters) { addFilters(builder); } ResultHandler printHandler = getPrintHandler(); if (printHandler != null) { builder.alwaysDo(printHandler); } } private ResultHandler getPrintHandler() { LinesWriter writer = getLinesWriter(); if (writer == null) { return null; } if (this.printOnlyOnFailure) { writer = new DeferredLinesWriter(this.context, writer); } return new LinesWritingResultHandler(writer); } private LinesWriter getLinesWriter() { if (this.print == MockMvcPrint.NONE) { return null; } if (this.print == MockMvcPrint.LOG_DEBUG) { return new LoggingLinesWriter(); } return new SystemLinesWriter(this.print); } private void addFilters(ConfigurableMockMvcBuilder<?> builder) { FilterRegistrationBeans registrations = new FilterRegistrationBeans(this.context); registrations.stream().map(AbstractFilterRegistrationBean.class::cast) .filter(AbstractFilterRegistrationBean<?>::isEnabled) .forEach((registration) -> addFilter(builder, registration)); } private void addFilter(ConfigurableMockMvcBuilder<?> builder, AbstractFilterRegistrationBean<?> registration) { Filter filter = registration.getFilter(); Collection<String> urls = registration.getUrlPatterns(); if (urls.isEmpty()) { builder.addFilters(filter); } else { builder.addFilter(filter, StringUtils.toStringArray(urls)); } } public void setAddFilters(boolean addFilters) { this.addFilters = addFilters; } public boolean isAddFilters() { return this.addFilters; } public void setPrint(MockMvcPrint print) { this.print = print; } public MockMvcPrint getPrint() { return this.print; } public void setPrintOnlyOnFailure(boolean printOnlyOnFailure) { this.printOnlyOnFailure = printOnlyOnFailure; } public boolean isPrintOnlyOnFailure() { return this.printOnlyOnFailure; } /** * {@link ResultHandler} that prints {@link MvcResult} details to a given * {@link LinesWriter}. */ private static class LinesWritingResultHandler implements ResultHandler { private final LinesWriter writer; LinesWritingResultHandler(LinesWriter writer) { this.writer = writer; } @Override public void handle(MvcResult result) throws Exception { LinesPrintingResultHandler delegate = new LinesPrintingResultHandler(); delegate.handle(result); delegate.write(this.writer); } private static class LinesPrintingResultHandler extends PrintingResultHandler { protected LinesPrintingResultHandler() { super(new Printer()); } void write(LinesWriter writer) { writer.write(((Printer) getPrinter()).getLines()); } private static class Printer implements ResultValuePrinter { private final List<String> lines = new ArrayList<>(); @Override public void printHeading(String heading) { this.lines.add(""); this.lines.add(String.format("%s:", heading)); } @Override public void printValue(String label, Object value) { if (value != null && value.getClass().isArray()) { value = CollectionUtils.arrayToList(value); } this.lines.add(String.format("%17s = %s", label, value)); } List<String> getLines() { return this.lines; } } } } /** * Strategy interface to write MVC result lines. */ interface LinesWriter { void write(List<String> lines); } /** * {@link LinesWriter} used to defer writing until errors are detected. * * @see MockMvcPrintOnlyOnFailureTestExecutionListener */ static class DeferredLinesWriter implements LinesWriter { private static final String BEAN_NAME = DeferredLinesWriter.class.getName(); private final LinesWriter delegate; private final ThreadLocal<List<String>> lines = ThreadLocal.withInitial(ArrayList::new); DeferredLinesWriter(WebApplicationContext context, LinesWriter delegate) { Assert.state(context instanceof ConfigurableApplicationContext, "A ConfigurableApplicationContext is required for printOnlyOnFailure"); ((ConfigurableApplicationContext) context).getBeanFactory().registerSingleton(BEAN_NAME, this); this.delegate = delegate; } @Override public void write(List<String> lines) { this.lines.get().addAll(lines); } void writeDeferredResult() { this.delegate.write(this.lines.get()); } static DeferredLinesWriter get(ApplicationContext applicationContext) { try { return applicationContext.getBean(BEAN_NAME, DeferredLinesWriter.class); } catch (NoSuchBeanDefinitionException ex) { return null; } } void clear() { this.lines.get().clear(); } } /** * {@link LinesWriter} to output results to the log. */ private static class LoggingLinesWriter implements LinesWriter { private static final Log logger = LogFactory.getLog("org.springframework.test.web.servlet.result"); @Override public void write(List<String> lines) { if (logger.isDebugEnabled()) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); for (String line : lines) { printWriter.println(line); } logger.debug("MvcResult details:\n" + stringWriter); } } } /** * {@link LinesWriter} to output results to {@code System.out} or {@code System.err}. */ private static class SystemLinesWriter implements LinesWriter { private final MockMvcPrint print; SystemLinesWriter(MockMvcPrint print) { this.print = print; } @Override public void write(List<String> lines) { PrintStream printStream = getPrintStream(); for (String line : lines) { printStream.println(line); } } private PrintStream getPrintStream() { if (this.print == MockMvcPrint.SYSTEM_ERR) { return System.err; } return System.out; } } private static class FilterRegistrationBeans extends ServletContextInitializerBeans { FilterRegistrationBeans(ListableBeanFactory beanFactory) { super(beanFactory, FilterRegistrationBean.class, DelegatingFilterProxyRegistrationBean.class); } @Override protected void addAdaptableBeans(ListableBeanFactory beanFactory) { addAsRegistrationBean(beanFactory, Filter.class, new FilterRegistrationBeanAdapter()); } private static class FilterRegistrationBeanAdapter implements RegistrationBeanAdapter<Filter> { @Override public RegistrationBean createRegistrationBean(String name, Filter source, int totalNumberOfSourceBeans) { FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>(source); bean.setName(name); return bean; } } } }
/* * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing; import sun.awt.AWTAccessor; import javax.swing.plaf.LayerUI; import javax.swing.border.Border; import javax.accessibility.*; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.security.AccessController; import java.security.PrivilegedAction; /** * {@code JLayer} is a universal decorator for Swing components * which enables you to implement various advanced painting effects as well as * receive notifications of all {@code AWTEvent}s generated within its borders. * <p> * {@code JLayer} delegates the handling of painting and input events to a * {@link LayerUI} object, which performs the actual decoration. * <p> * The custom painting implemented in the {@code LayerUI} and events notification * work for the JLayer itself and all its subcomponents. * This combination enables you to enrich existing components * by adding new advanced functionality such as temporary locking of a hierarchy, * data tips for compound components, enhanced mouse scrolling etc and so on. * <p> * {@code JLayer} is a good solution if you only need to do custom painting * over compound component or catch input events from its subcomponents. * <pre> * import javax.swing.*; * import javax.swing.plaf.LayerUI; * import java.awt.*; * * public class JLayerSample { * * private static JLayer&lt;JComponent&gt; createLayer() { * // This custom layerUI will fill the layer with translucent green * // and print out all mouseMotion events generated within its borders * LayerUI&lt;JComponent&gt; layerUI = new LayerUI&lt;JComponent&gt;() { * * public void paint(Graphics g, JComponent c) { * // paint the layer as is * super.paint(g, c); * // fill it with the translucent green * g.setColor(new Color(0, 128, 0, 128)); * g.fillRect(0, 0, c.getWidth(), c.getHeight()); * } * * public void installUI(JComponent c) { * super.installUI(c); * // enable mouse motion events for the layer's subcomponents * ((JLayer) c).setLayerEventMask(AWTEvent.MOUSE_MOTION_EVENT_MASK); * } * * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * // reset the layer event mask * ((JLayer) c).setLayerEventMask(0); * } * * // overridden method which catches MouseMotion events * public void eventDispatched(AWTEvent e, JLayer&lt;? extends JComponent&gt; l) { * System.out.println("AWTEvent detected: " + e); * } * }; * // create a component to be decorated with the layer * JPanel panel = new JPanel(); * panel.add(new JButton("JButton")); * * // create the layer for the panel using our custom layerUI * return new JLayer&lt;JComponent&gt;(panel, layerUI); * } * * private static void createAndShowGUI() { * final JFrame frame = new JFrame(); * frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); * * // work with the layer as with any other Swing component * frame.add(createLayer()); * * frame.setSize(200, 200); * frame.setLocationRelativeTo(null); * frame.setVisible(true); * } * * public static void main(String[] args) throws Exception { * SwingUtilities.invokeAndWait(new Runnable() { * public void run() { * createAndShowGUI(); * } * }); * } * } * </pre> * * <b>Note:</b> {@code JLayer} doesn't support the following methods: * <ul> * <li>{@link Container#add(Component)}</li> * <li>{@link Container#add(String, Component)}</li> * <li>{@link Container#add(Component, int)}</li> * <li>{@link Container#add(Component, Object)}</li> * <li>{@link Container#add(Component, Object, int)}</li> * </ul> * using any of of them will cause {@code UnsupportedOperationException} to be thrown, * to add a component to {@code JLayer} * use {@link #setView(Component)} or {@link #setGlassPane(JPanel)}. * * @param <V> the type of {@code JLayer}'s view component * * @see #JLayer(Component) * @see #setView(Component) * @see #getView() * @see LayerUI * @see #JLayer(Component, LayerUI) * @see #setUI(LayerUI) * @see #getUI() * @since 1.7 * * @author Alexander Potochkin */ public final class JLayer<V extends Component> extends JComponent implements Scrollable, PropertyChangeListener, Accessible { private V view; // this field is necessary because JComponent.ui is transient // when layerUI is serializable private LayerUI<? super V> layerUI; private JPanel glassPane; private long eventMask; private transient boolean isPainting; private transient boolean isPaintingImmediately; private static final LayerEventController eventController = new LayerEventController(); /** * Creates a new {@code JLayer} object with a {@code null} view component * and default {@link LayerUI}. * * @see #setView * @see #setUI */ public JLayer() { this(null); } /** * Creates a new {@code JLayer} object * with default {@link LayerUI}. * * @param view the component to be decorated by this {@code JLayer} * * @see #setUI */ public JLayer(V view) { this(view, new LayerUI<V>()); } /** * Creates a new {@code JLayer} object with the specified view component * and {@link LayerUI} object. * * @param view the component to be decorated * @param ui the {@link LayerUI} delegate * to be used by this {@code JLayer} */ public JLayer(V view, LayerUI<V> ui) { setGlassPane(createGlassPane()); setView(view); setUI(ui); } /** * Returns the {@code JLayer}'s view component or {@code null}. * <br>This is a bound property. * * @return the {@code JLayer}'s view component * or {@code null} if none exists * * @see #setView(Component) */ public V getView() { return view; } /** * Sets the {@code JLayer}'s view component, which can be {@code null}. * <br>This is a bound property. * * @param view the view component for this {@code JLayer} * * @see #getView() */ public void setView(V view) { Component oldView = getView(); if (oldView != null) { super.remove(oldView); } if (view != null) { super.addImpl(view, null, getComponentCount()); } this.view = view; firePropertyChange("view", oldView, view); revalidate(); repaint(); } /** * Sets the {@link LayerUI} which will perform painting * and receive input events for this {@code JLayer}. * * @param ui the {@link LayerUI} for this {@code JLayer} */ public void setUI(LayerUI<? super V> ui) { this.layerUI = ui; super.setUI(ui); } /** * Returns the {@link LayerUI} for this {@code JLayer}. * * @return the {@code LayerUI} for this {@code JLayer} */ public LayerUI<? super V> getUI() { return layerUI; } /** * Returns the {@code JLayer}'s glassPane component or {@code null}. * <br>This is a bound property. * * @return the {@code JLayer}'s glassPane component * or {@code null} if none exists * * @see #setGlassPane(JPanel) */ public JPanel getGlassPane() { return glassPane; } /** * Sets the {@code JLayer}'s glassPane component, which can be {@code null}. * <br>This is a bound property. * * @param glassPane the glassPane component of this {@code JLayer} * * @see #getGlassPane() */ public void setGlassPane(JPanel glassPane) { Component oldGlassPane = getGlassPane(); boolean isGlassPaneVisible = false; if (oldGlassPane != null) { isGlassPaneVisible = oldGlassPane.isVisible(); super.remove(oldGlassPane); } if (glassPane != null) { AWTAccessor.getComponentAccessor().setMixingCutoutShape(glassPane, new Rectangle()); glassPane.setVisible(isGlassPaneVisible); super.addImpl(glassPane, null, 0); } this.glassPane = glassPane; firePropertyChange("glassPane", oldGlassPane, glassPane); revalidate(); repaint(); } /** * Called by the constructor methods to create a default {@code glassPane}. * By default this method creates a new JPanel with visibility set to true * and opacity set to false. * * @return the default {@code glassPane} */ public JPanel createGlassPane() { return new DefaultLayerGlassPane(); } /** * Sets the layout manager for this container. This method is * overridden to prevent the layout manager from being set. * <p>Note: If {@code mgr} is non-{@code null}, this * method will throw an exception as layout managers are not supported on * a {@code JLayer}. * * @param mgr the specified layout manager * @exception IllegalArgumentException this method is not supported */ public void setLayout(LayoutManager mgr) { if (mgr != null) { throw new IllegalArgumentException("JLayer.setLayout() not supported"); } } /** * A non-{@code null} border, or non-zero insets, isn't supported, to prevent the geometry * of this component from becoming complex enough to inhibit * subclassing of {@code LayerUI} class. To create a {@code JLayer} with a border, * add it to a {@code JPanel} that has a border. * <p>Note: If {@code border} is non-{@code null}, this * method will throw an exception as borders are not supported on * a {@code JLayer}. * * @param border the {@code Border} to set * @exception IllegalArgumentException this method is not supported */ public void setBorder(Border border) { if (border != null) { throw new IllegalArgumentException("JLayer.setBorder() not supported"); } } /** * This method is not supported by {@code JLayer} * and always throws {@code UnsupportedOperationException} * * @throws UnsupportedOperationException this method is not supported * * @see #setView(Component) * @see #setGlassPane(JPanel) */ protected void addImpl(Component comp, Object constraints, int index) { throw new UnsupportedOperationException( "Adding components to JLayer is not supported, " + "use setView() or setGlassPane() instead"); } /** * {@inheritDoc} */ public void remove(Component comp) { if (comp == null) { super.remove(comp); } else if (comp == getView()) { setView(null); } else if (comp == getGlassPane()) { setGlassPane(null); } else { super.remove(comp); } } /** * {@inheritDoc} */ public void removeAll() { if (view != null) { setView(null); } if (glassPane != null) { setGlassPane(null); } } /** * Always returns {@code true} to cause painting to originate from {@code JLayer}, * or one of its ancestors. * * @return true * @see JComponent#isPaintingOrigin() */ protected boolean isPaintingOrigin() { return true; } /** * Delegates its functionality to the * {@link LayerUI#paintImmediately(int, int, int, int, JLayer)} method, * if {@code LayerUI} is set. * * @param x the x value of the region to be painted * @param y the y value of the region to be painted * @param w the width of the region to be painted * @param h the height of the region to be painted */ public void paintImmediately(int x, int y, int w, int h) { if (!isPaintingImmediately && getUI() != null) { isPaintingImmediately = true; try { getUI().paintImmediately(x, y, w, h, this); } finally { isPaintingImmediately = false; } } else { super.paintImmediately(x, y, w, h); } } /** * Delegates all painting to the {@link LayerUI} object. * * @param g the {@code Graphics} to render to */ public void paint(Graphics g) { if (!isPainting) { isPainting = true; try { super.paintComponent(g); } finally { isPainting = false; } } else { super.paint(g); } } /** * This method is empty, because all painting is done by * {@link #paint(Graphics)} and * {@link LayerUI#update(Graphics, JComponent)} methods */ protected void paintComponent(Graphics g) { } /** * The {@code JLayer} overrides the default implementation of * this method (in {@code JComponent}) to return {@code false}. * This ensures * that the drawing machinery will call the {@code JLayer}'s * {@code paint} * implementation rather than messaging the {@code JLayer}'s * children directly. * * @return false */ public boolean isOptimizedDrawingEnabled() { return false; } /** * {@inheritDoc} */ public void propertyChange(PropertyChangeEvent evt) { if (getUI() != null) { getUI().applyPropertyChange(evt, this); } } /** * Enables the events from JLayer and <b>all its descendants</b> * defined by the specified event mask parameter * to be delivered to the * {@link LayerUI#eventDispatched(AWTEvent, JLayer)} method. * <p> * Events are delivered provided that {@code LayerUI} is set * for this {@code JLayer} and the {@code JLayer} * is displayable. * <p> * The following example shows how to correctly use this method * in the {@code LayerUI} implementations: * <pre> * public void installUI(JComponent c) { * super.installUI(c); * JLayer l = (JLayer) c; * // this LayerUI will receive only key and focus events * l.setLayerEventMask(AWTEvent.KEY_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK); * } * * public void uninstallUI(JComponent c) { * super.uninstallUI(c); * JLayer l = (JLayer) c; * // JLayer must be returned to its initial state * l.setLayerEventMask(0); * } * </pre> * * By default {@code JLayer} receives no events and its event mask is {@code 0}. * * @param layerEventMask the bitmask of event types to receive * * @see #getLayerEventMask() * @see LayerUI#eventDispatched(AWTEvent, JLayer) * @see Component#isDisplayable() */ public void setLayerEventMask(long layerEventMask) { long oldEventMask = getLayerEventMask(); this.eventMask = layerEventMask; firePropertyChange("layerEventMask", oldEventMask, layerEventMask); if (layerEventMask != oldEventMask) { disableEvents(oldEventMask); enableEvents(eventMask); if (isDisplayable()) { eventController.updateAWTEventListener( oldEventMask, layerEventMask); } } } /** * Returns the bitmap of event mask to receive by this {@code JLayer} * and its {@code LayerUI}. * <p> * It means that {@link LayerUI#eventDispatched(AWTEvent, JLayer)} method * will only receive events that match the event mask. * <p> * By default {@code JLayer} receives no events. * * @return the bitmask of event types to receive for this {@code JLayer} */ public long getLayerEventMask() { return eventMask; } /** * Delegates its functionality to the {@link LayerUI#updateUI(JLayer)} method, * if {@code LayerUI} is set. */ public void updateUI() { if (getUI() != null) { getUI().updateUI(this); } } /** * Returns the preferred size of the viewport for a view component. * <p> * If the view component of this layer implements {@link Scrollable}, this method delegates its * implementation to the view component. * * @return the preferred size of the viewport for a view component * * @see Scrollable */ public Dimension getPreferredScrollableViewportSize() { if (getView() instanceof Scrollable) { return ((Scrollable)getView()).getPreferredScrollableViewportSize(); } return getPreferredSize(); } /** * Returns a scroll increment, which is required for components * that display logical rows or columns in order to completely expose * one block of rows or columns, depending on the value of orientation. * <p> * If the view component of this layer implements {@link Scrollable}, this method delegates its * implementation to the view component. * * @return the "block" increment for scrolling in the specified direction * * @see Scrollable */ public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { if (getView() instanceof Scrollable) { return ((Scrollable)getView()).getScrollableBlockIncrement(visibleRect, orientation, direction); } return (orientation == SwingConstants.VERTICAL) ? visibleRect.height : visibleRect.width; } /** * Returns {@code false} to indicate that the height of the viewport does not * determine the height of the layer, unless the preferred height * of the layer is smaller than the height of the viewport. * <p> * If the view component of this layer implements {@link Scrollable}, this method delegates its * implementation to the view component. * * @return whether the layer should track the height of the viewport * * @see Scrollable */ public boolean getScrollableTracksViewportHeight() { if (getView() instanceof Scrollable) { return ((Scrollable)getView()).getScrollableTracksViewportHeight(); } return false; } /** * Returns {@code false} to indicate that the width of the viewport does not * determine the width of the layer, unless the preferred width * of the layer is smaller than the width of the viewport. * <p> * If the view component of this layer implements {@link Scrollable}, this method delegates its * implementation to the view component. * * @return whether the layer should track the width of the viewport * * @see Scrollable */ public boolean getScrollableTracksViewportWidth() { if (getView() instanceof Scrollable) { return ((Scrollable)getView()).getScrollableTracksViewportWidth(); } return false; } /** * Returns a scroll increment, which is required for components * that display logical rows or columns in order to completely expose * one new row or column, depending on the value of orientation. * Ideally, components should handle a partially exposed row or column * by returning the distance required to completely expose the item. * <p> * Scrolling containers, like {@code JScrollPane}, will use this method * each time the user requests a unit scroll. * <p> * If the view component of this layer implements {@link Scrollable}, this method delegates its * implementation to the view component. * * @return The "unit" increment for scrolling in the specified direction. * This value should always be positive. * * @see Scrollable */ public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { if (getView() instanceof Scrollable) { return ((Scrollable) getView()).getScrollableUnitIncrement( visibleRect, orientation, direction); } return 1; } private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); if (layerUI != null) { setUI(layerUI); } if (eventMask != 0) { eventController.updateAWTEventListener(0, eventMask); } } /** * {@inheritDoc} */ public void addNotify() { super.addNotify(); eventController.updateAWTEventListener(0, eventMask); } /** * {@inheritDoc} */ public void removeNotify() { super.removeNotify(); eventController.updateAWTEventListener(eventMask, 0); } /** * Delegates its functionality to the {@link LayerUI#doLayout(JLayer)} method, * if {@code LayerUI} is set. */ public void doLayout() { if (getUI() != null) { getUI().doLayout(this); } } /** * Gets the AccessibleContext associated with this {@code JLayer}. * * @return the AccessibleContext associated with this {@code JLayer}. */ public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJComponent() { public AccessibleRole getAccessibleRole() { return AccessibleRole.PANEL; } }; } return accessibleContext; } /** * static AWTEventListener to be shared with all AbstractLayerUIs */ private static class LayerEventController implements AWTEventListener { private ArrayList<Long> layerMaskList = new ArrayList<Long>(); private long currentEventMask; private static final long ACCEPTED_EVENTS = AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.CONTAINER_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK | AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.INPUT_METHOD_EVENT_MASK | AWTEvent.HIERARCHY_EVENT_MASK | AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK; @SuppressWarnings("unchecked") public void eventDispatched(AWTEvent event) { Object source = event.getSource(); if (source instanceof Component) { Component component = (Component) source; while (component != null) { if (component instanceof JLayer) { JLayer l = (JLayer) component; LayerUI ui = l.getUI(); if (ui != null && isEventEnabled(l.getLayerEventMask(), event.getID()) && (!(event instanceof InputEvent) || !((InputEvent)event).isConsumed())) { ui.eventDispatched(event, l); } } component = component.getParent(); } } } private void updateAWTEventListener(long oldEventMask, long newEventMask) { if (oldEventMask != 0) { layerMaskList.remove(oldEventMask); } if (newEventMask != 0) { layerMaskList.add(newEventMask); } long combinedMask = 0; for (Long mask : layerMaskList) { combinedMask |= mask; } // filter out all unaccepted events combinedMask &= ACCEPTED_EVENTS; if (combinedMask == 0) { removeAWTEventListener(); } else if (getCurrentEventMask() != combinedMask) { removeAWTEventListener(); addAWTEventListener(combinedMask); } currentEventMask = combinedMask; } private long getCurrentEventMask() { return currentEventMask; } private void addAWTEventListener(final long eventMask) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { Toolkit.getDefaultToolkit(). addAWTEventListener(LayerEventController.this, eventMask); return null; } }); } private void removeAWTEventListener() { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { Toolkit.getDefaultToolkit(). removeAWTEventListener(LayerEventController.this); return null; } }); } private boolean isEventEnabled(long eventMask, int id) { return (((eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 && id >= ComponentEvent.COMPONENT_FIRST && id <= ComponentEvent.COMPONENT_LAST) || ((eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 && id >= ContainerEvent.CONTAINER_FIRST && id <= ContainerEvent.CONTAINER_LAST) || ((eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 && id >= FocusEvent.FOCUS_FIRST && id <= FocusEvent.FOCUS_LAST) || ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 && id >= KeyEvent.KEY_FIRST && id <= KeyEvent.KEY_LAST) || ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 && id == MouseEvent.MOUSE_WHEEL) || ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 && (id == MouseEvent.MOUSE_MOVED || id == MouseEvent.MOUSE_DRAGGED)) || ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 && id != MouseEvent.MOUSE_MOVED && id != MouseEvent.MOUSE_DRAGGED && id != MouseEvent.MOUSE_WHEEL && id >= MouseEvent.MOUSE_FIRST && id <= MouseEvent.MOUSE_LAST) || ((eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 && id >= InputMethodEvent.INPUT_METHOD_FIRST && id <= InputMethodEvent.INPUT_METHOD_LAST) || ((eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 && id == HierarchyEvent.HIERARCHY_CHANGED) || ((eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 && (id == HierarchyEvent.ANCESTOR_MOVED || id == HierarchyEvent.ANCESTOR_RESIZED))); } } /** * The default glassPane for the {@link JLayer}. * It is a subclass of {@code JPanel} which is non opaque by default. */ private static class DefaultLayerGlassPane extends JPanel { /** * Creates a new {@link DefaultLayerGlassPane} */ public DefaultLayerGlassPane() { setOpaque(false); } /** * First, implementation of this method iterates through * glassPane's child components and returns {@code true} * if any of them is visible and contains passed x,y point. * After that it checks if no mouseListeners is attached to this component * and no mouse cursor is set, then it returns {@code false}, * otherwise calls the super implementation of this method. * * @param x the <i>x</i> coordinate of the point * @param y the <i>y</i> coordinate of the point * @return true if this component logically contains x,y */ public boolean contains(int x, int y) { for (int i = 0; i < getComponentCount(); i++) { Component c = getComponent(i); Point point = SwingUtilities.convertPoint(this, new Point(x, y), c); if(c.isVisible() && c.contains(point)){ return true; } } if (getMouseListeners().length == 0 && getMouseMotionListeners().length == 0 && getMouseWheelListeners().length == 0 && !isCursorSet()) { return false; } return super.contains(x, y); } } }
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library 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 Lesser General Public License for more * details. */ package org.oep.core.dossiermgt.model; import com.liferay.portal.kernel.lar.StagedModelType; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.model.ModelWrapper; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * <p> * This class is a wrapper for {@link DocFile}. * </p> * * @author trungdk * @see DocFile * @generated */ public class DocFileWrapper implements DocFile, ModelWrapper<DocFile> { public DocFileWrapper(DocFile docFile) { _docFile = docFile; } @Override public Class<?> getModelClass() { return DocFile.class; } @Override public String getModelClassName() { return DocFile.class.getName(); } @Override public Map<String, Object> getModelAttributes() { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("uuid", getUuid()); attributes.put("docFileId", getDocFileId()); attributes.put("userId", getUserId()); attributes.put("groupId", getGroupId()); attributes.put("companyId", getCompanyId()); attributes.put("createDate", getCreateDate()); attributes.put("modifiedDate", getModifiedDate()); attributes.put("dossierId", getDossierId()); attributes.put("dossierDocId", getDossierDocId()); attributes.put("docTemplateId", getDocTemplateId()); attributes.put("docFileVersionId", getDocFileVersionId()); attributes.put("docFileName", getDocFileName()); attributes.put("docFileType", getDocFileType()); attributes.put("verifyStatus", getVerifyStatus()); attributes.put("note", getNote()); attributes.put("approveBy", getApproveBy()); attributes.put("approveDate", getApproveDate()); attributes.put("premier", getPremier()); return attributes; } @Override public void setModelAttributes(Map<String, Object> attributes) { String uuid = (String)attributes.get("uuid"); if (uuid != null) { setUuid(uuid); } Long docFileId = (Long)attributes.get("docFileId"); if (docFileId != null) { setDocFileId(docFileId); } Long userId = (Long)attributes.get("userId"); if (userId != null) { setUserId(userId); } Long groupId = (Long)attributes.get("groupId"); if (groupId != null) { setGroupId(groupId); } Long companyId = (Long)attributes.get("companyId"); if (companyId != null) { setCompanyId(companyId); } Date createDate = (Date)attributes.get("createDate"); if (createDate != null) { setCreateDate(createDate); } Date modifiedDate = (Date)attributes.get("modifiedDate"); if (modifiedDate != null) { setModifiedDate(modifiedDate); } Long dossierId = (Long)attributes.get("dossierId"); if (dossierId != null) { setDossierId(dossierId); } Long dossierDocId = (Long)attributes.get("dossierDocId"); if (dossierDocId != null) { setDossierDocId(dossierDocId); } Long docTemplateId = (Long)attributes.get("docTemplateId"); if (docTemplateId != null) { setDocTemplateId(docTemplateId); } Long docFileVersionId = (Long)attributes.get("docFileVersionId"); if (docFileVersionId != null) { setDocFileVersionId(docFileVersionId); } String docFileName = (String)attributes.get("docFileName"); if (docFileName != null) { setDocFileName(docFileName); } Long docFileType = (Long)attributes.get("docFileType"); if (docFileType != null) { setDocFileType(docFileType); } Integer verifyStatus = (Integer)attributes.get("verifyStatus"); if (verifyStatus != null) { setVerifyStatus(verifyStatus); } String note = (String)attributes.get("note"); if (note != null) { setNote(note); } String approveBy = (String)attributes.get("approveBy"); if (approveBy != null) { setApproveBy(approveBy); } Date approveDate = (Date)attributes.get("approveDate"); if (approveDate != null) { setApproveDate(approveDate); } Integer premier = (Integer)attributes.get("premier"); if (premier != null) { setPremier(premier); } } /** * Returns the primary key of this doc file. * * @return the primary key of this doc file */ @Override public long getPrimaryKey() { return _docFile.getPrimaryKey(); } /** * Sets the primary key of this doc file. * * @param primaryKey the primary key of this doc file */ @Override public void setPrimaryKey(long primaryKey) { _docFile.setPrimaryKey(primaryKey); } /** * Returns the uuid of this doc file. * * @return the uuid of this doc file */ @Override public java.lang.String getUuid() { return _docFile.getUuid(); } /** * Sets the uuid of this doc file. * * @param uuid the uuid of this doc file */ @Override public void setUuid(java.lang.String uuid) { _docFile.setUuid(uuid); } /** * Returns the doc file ID of this doc file. * * @return the doc file ID of this doc file */ @Override public long getDocFileId() { return _docFile.getDocFileId(); } /** * Sets the doc file ID of this doc file. * * @param docFileId the doc file ID of this doc file */ @Override public void setDocFileId(long docFileId) { _docFile.setDocFileId(docFileId); } /** * Returns the user ID of this doc file. * * @return the user ID of this doc file */ @Override public long getUserId() { return _docFile.getUserId(); } /** * Sets the user ID of this doc file. * * @param userId the user ID of this doc file */ @Override public void setUserId(long userId) { _docFile.setUserId(userId); } /** * Returns the user uuid of this doc file. * * @return the user uuid of this doc file * @throws SystemException if a system exception occurred */ @Override public java.lang.String getUserUuid() throws com.liferay.portal.kernel.exception.SystemException { return _docFile.getUserUuid(); } /** * Sets the user uuid of this doc file. * * @param userUuid the user uuid of this doc file */ @Override public void setUserUuid(java.lang.String userUuid) { _docFile.setUserUuid(userUuid); } /** * Returns the group ID of this doc file. * * @return the group ID of this doc file */ @Override public long getGroupId() { return _docFile.getGroupId(); } /** * Sets the group ID of this doc file. * * @param groupId the group ID of this doc file */ @Override public void setGroupId(long groupId) { _docFile.setGroupId(groupId); } /** * Returns the company ID of this doc file. * * @return the company ID of this doc file */ @Override public long getCompanyId() { return _docFile.getCompanyId(); } /** * Sets the company ID of this doc file. * * @param companyId the company ID of this doc file */ @Override public void setCompanyId(long companyId) { _docFile.setCompanyId(companyId); } /** * Returns the create date of this doc file. * * @return the create date of this doc file */ @Override public java.util.Date getCreateDate() { return _docFile.getCreateDate(); } /** * Sets the create date of this doc file. * * @param createDate the create date of this doc file */ @Override public void setCreateDate(java.util.Date createDate) { _docFile.setCreateDate(createDate); } /** * Returns the modified date of this doc file. * * @return the modified date of this doc file */ @Override public java.util.Date getModifiedDate() { return _docFile.getModifiedDate(); } /** * Sets the modified date of this doc file. * * @param modifiedDate the modified date of this doc file */ @Override public void setModifiedDate(java.util.Date modifiedDate) { _docFile.setModifiedDate(modifiedDate); } /** * Returns the dossier ID of this doc file. * * @return the dossier ID of this doc file */ @Override public long getDossierId() { return _docFile.getDossierId(); } /** * Sets the dossier ID of this doc file. * * @param dossierId the dossier ID of this doc file */ @Override public void setDossierId(long dossierId) { _docFile.setDossierId(dossierId); } /** * Returns the dossier doc ID of this doc file. * * @return the dossier doc ID of this doc file */ @Override public long getDossierDocId() { return _docFile.getDossierDocId(); } /** * Sets the dossier doc ID of this doc file. * * @param dossierDocId the dossier doc ID of this doc file */ @Override public void setDossierDocId(long dossierDocId) { _docFile.setDossierDocId(dossierDocId); } /** * Returns the doc template ID of this doc file. * * @return the doc template ID of this doc file */ @Override public long getDocTemplateId() { return _docFile.getDocTemplateId(); } /** * Sets the doc template ID of this doc file. * * @param docTemplateId the doc template ID of this doc file */ @Override public void setDocTemplateId(long docTemplateId) { _docFile.setDocTemplateId(docTemplateId); } /** * Returns the doc file version ID of this doc file. * * @return the doc file version ID of this doc file */ @Override public long getDocFileVersionId() { return _docFile.getDocFileVersionId(); } /** * Sets the doc file version ID of this doc file. * * @param docFileVersionId the doc file version ID of this doc file */ @Override public void setDocFileVersionId(long docFileVersionId) { _docFile.setDocFileVersionId(docFileVersionId); } /** * Returns the doc file name of this doc file. * * @return the doc file name of this doc file */ @Override public java.lang.String getDocFileName() { return _docFile.getDocFileName(); } /** * Sets the doc file name of this doc file. * * @param docFileName the doc file name of this doc file */ @Override public void setDocFileName(java.lang.String docFileName) { _docFile.setDocFileName(docFileName); } /** * Returns the doc file type of this doc file. * * @return the doc file type of this doc file */ @Override public long getDocFileType() { return _docFile.getDocFileType(); } /** * Sets the doc file type of this doc file. * * @param docFileType the doc file type of this doc file */ @Override public void setDocFileType(long docFileType) { _docFile.setDocFileType(docFileType); } /** * Returns the verify status of this doc file. * * @return the verify status of this doc file */ @Override public int getVerifyStatus() { return _docFile.getVerifyStatus(); } /** * Sets the verify status of this doc file. * * @param verifyStatus the verify status of this doc file */ @Override public void setVerifyStatus(int verifyStatus) { _docFile.setVerifyStatus(verifyStatus); } /** * Returns the note of this doc file. * * @return the note of this doc file */ @Override public java.lang.String getNote() { return _docFile.getNote(); } /** * Sets the note of this doc file. * * @param note the note of this doc file */ @Override public void setNote(java.lang.String note) { _docFile.setNote(note); } /** * Returns the approve by of this doc file. * * @return the approve by of this doc file */ @Override public java.lang.String getApproveBy() { return _docFile.getApproveBy(); } /** * Sets the approve by of this doc file. * * @param approveBy the approve by of this doc file */ @Override public void setApproveBy(java.lang.String approveBy) { _docFile.setApproveBy(approveBy); } /** * Returns the approve date of this doc file. * * @return the approve date of this doc file */ @Override public java.util.Date getApproveDate() { return _docFile.getApproveDate(); } /** * Sets the approve date of this doc file. * * @param approveDate the approve date of this doc file */ @Override public void setApproveDate(java.util.Date approveDate) { _docFile.setApproveDate(approveDate); } /** * Returns the premier of this doc file. * * @return the premier of this doc file */ @Override public int getPremier() { return _docFile.getPremier(); } /** * Sets the premier of this doc file. * * @param premier the premier of this doc file */ @Override public void setPremier(int premier) { _docFile.setPremier(premier); } @Override public boolean isNew() { return _docFile.isNew(); } @Override public void setNew(boolean n) { _docFile.setNew(n); } @Override public boolean isCachedModel() { return _docFile.isCachedModel(); } @Override public void setCachedModel(boolean cachedModel) { _docFile.setCachedModel(cachedModel); } @Override public boolean isEscapedModel() { return _docFile.isEscapedModel(); } @Override public java.io.Serializable getPrimaryKeyObj() { return _docFile.getPrimaryKeyObj(); } @Override public void setPrimaryKeyObj(java.io.Serializable primaryKeyObj) { _docFile.setPrimaryKeyObj(primaryKeyObj); } @Override public com.liferay.portlet.expando.model.ExpandoBridge getExpandoBridge() { return _docFile.getExpandoBridge(); } @Override public void setExpandoBridgeAttributes( com.liferay.portal.model.BaseModel<?> baseModel) { _docFile.setExpandoBridgeAttributes(baseModel); } @Override public void setExpandoBridgeAttributes( com.liferay.portlet.expando.model.ExpandoBridge expandoBridge) { _docFile.setExpandoBridgeAttributes(expandoBridge); } @Override public void setExpandoBridgeAttributes( com.liferay.portal.service.ServiceContext serviceContext) { _docFile.setExpandoBridgeAttributes(serviceContext); } @Override public java.lang.Object clone() { return new DocFileWrapper((DocFile)_docFile.clone()); } @Override public int compareTo(org.oep.core.dossiermgt.model.DocFile docFile) { return _docFile.compareTo(docFile); } @Override public int hashCode() { return _docFile.hashCode(); } @Override public com.liferay.portal.model.CacheModel<org.oep.core.dossiermgt.model.DocFile> toCacheModel() { return _docFile.toCacheModel(); } @Override public org.oep.core.dossiermgt.model.DocFile toEscapedModel() { return new DocFileWrapper(_docFile.toEscapedModel()); } @Override public org.oep.core.dossiermgt.model.DocFile toUnescapedModel() { return new DocFileWrapper(_docFile.toUnescapedModel()); } @Override public java.lang.String toString() { return _docFile.toString(); } @Override public java.lang.String toXmlString() { return _docFile.toXmlString(); } @Override public void persist() throws com.liferay.portal.kernel.exception.SystemException { _docFile.persist(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof DocFileWrapper)) { return false; } DocFileWrapper docFileWrapper = (DocFileWrapper)obj; if (Validator.equals(_docFile, docFileWrapper._docFile)) { return true; } return false; } @Override public StagedModelType getStagedModelType() { return _docFile.getStagedModelType(); } /** * @deprecated As of 6.1.0, replaced by {@link #getWrappedModel} */ public DocFile getWrappedDocFile() { return _docFile; } @Override public DocFile getWrappedModel() { return _docFile; } @Override public void resetOriginalValues() { _docFile.resetOriginalValues(); } private DocFile _docFile; }
/* Copyright M-Gate Labs 2007 */ /** <p> <b>Block Input/Output Class</b> </p> <p> Used to read and write flash files at the TAG level. Useful for editing flash content. </p> */ package com.mgatelabs.swftools.support.swf.io; import com.mgatelabs.swftools.support.swf.objects.FMovie; import com.mgatelabs.swftools.support.swf.objects.FRect; import com.mgatelabs.swftools.support.swf.tags.TBlock; import com.mgatelabs.swftools.support.swf.tags.Tag; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Vector; public class BlockIO { private BitInput bi; private BitOutput bo; private BitLibrary bl; private TypeReader myTypeReader; private TypeWriter myTypeWriter; public Object[] readFlash(File target) throws Exception { try { bi = new BitInput(new FileInputStream(target)); bl = new BitLibrary(bi); } catch (Exception e) { return null; } String signature = (char) bl.ui8() + "" + (char) bl.ui8() + (char) bl.ui8(); FMovie myObject = null; long uncompressedSize = 0; if (signature.equals("CWS")) { int version = (int) bl.ui8(); uncompressedSize = bl.ui32(); bi.useCompressedStream(); myTypeReader = new TypeReader(bl, bi, version); FRect movieRect = myTypeReader.rect(); float frameRate = (bl.ui16() / 256.0f); long frameCount = bl.ui16(); myObject = new FMovie(signature, version, uncompressedSize, movieRect, frameRate, frameCount); } else { int version = (int) bl.ui8(); uncompressedSize = bl.ui32(); myTypeReader = new TypeReader(bl, bi, version); myObject = new FMovie(signature, version, uncompressedSize, myTypeReader.rect(), (bl.ui16() / 256.0f), bl.ui16()); } // Read Blocks Object[] objects = new Object[2]; objects[0] = myObject; objects[1] = readBlocks(uncompressedSize); bi.close(); bi = null; bl = null; return objects; } //////////////////////////////////////////////////////////////////////////// public Vector readBlocks(long size) throws Exception { Tag aTag = null; TBlock tblock = null; Vector results = new Vector(); long startByte = 0; long endByte = 0; while (bi.bitsRead < size) { aTag = myTypeReader.tag(); startByte = bi.bitsRead; endByte = startByte + aTag.length; tblock = new TBlock(aTag.id, aTag.length); byte[] data = bi.readBytes2((int) aTag.length); tblock.setData(data); results.add(tblock); } return results; } //////////////////////////////////////////////////////////////////////////// public boolean writeFlash(File target, FMovie aMovie, Vector data, boolean compress) throws Exception { try { bo = new BitOutput(new FileOutputStream(target)); myTypeWriter = new TypeWriter(bo, aMovie.getVersion()); } catch (Exception e) { return false; } // Write Signiture if (compress) { bo.writeByte('C'); bo.writeByte('W'); bo.writeByte('S'); } else { bo.writeByte('F'); bo.writeByte('W'); bo.writeByte('S'); } // Version bo.ui8(aMovie.getVersion()); // Size bo.ui32(determineFlashSize(aMovie, data)); if (compress) { bo.useCompression(); } myTypeWriter.rect(aMovie.getRect()); bo.ui16((long) (aMovie.getFrameRate() * 256)); bo.ui16(aMovie.getFrameCount()); for (int x = 0; x < data.size(); x++) { TBlock aBlock = (TBlock) data.get(x); myTypeWriter.tag(aBlock.getId(), aBlock.getData()); } bo.close(); return true; } //////////////////////////////////////////////////////////////////////////// /** * Flash Movies are picky about their file size field, so it must be known beforehand. */ public long determineFlashSize(FMovie aMovie, Vector blocks) { long size = 3; size += 1; size += 4; size += myTypeWriter._rect(aMovie.getRect()); size += 2; size += 2; for (int x = 0; x < blocks.size(); x++) { TBlock aBlock = (TBlock) blocks.get(x); size += aBlock.getData().length + (aBlock.getData().length > 62 ? 6 : 2); } return size; } //////////////////////////////////////////////////////////////////////////// public TBlock readBlock(File target, FMovie aMovie) throws Exception { try { bi = new BitInput(new FileInputStream(target)); bl = new BitLibrary(bi); myTypeReader = new TypeReader(bl, bi, aMovie.getVersion()); } catch (Exception e) { return null; } Tag aTag = myTypeReader.tag(); TBlock tblock = new TBlock(aTag.id, aTag.length); byte[] data = bi.readBytes2((int) aTag.length); tblock.setData(data); bi.close(); return tblock; } //////////////////////////////////////////////////////////////////////////// public boolean writeBlock(File target, FMovie aMovie, TBlock aBlock) throws Exception { try { bo = new BitOutput(new FileOutputStream(target)); myTypeWriter = new TypeWriter(bo, aMovie.getVersion()); } catch (Exception e) { return false; } myTypeWriter.tag(aBlock.getId(), aBlock.getData()); bo.close(); return true; } //////////////////////////////////////////////////////////////////////////// public boolean writeData(File target, FMovie aMovie, TBlock aBlock) throws Exception { try { bo = new BitOutput(new FileOutputStream(target)); myTypeWriter = new TypeWriter(bo, aMovie.getVersion()); } catch (Exception e) { return false; } bo.writeBytes(aBlock.getData()); bo.close(); return true; } //////////////////////////////////////////////////////////////////////////// }
/** * 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.yarn.server.resourcemanager.scheduler.capacity; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.StringTokenizer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.QueueState; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; import org.apache.hadoop.yarn.security.AccessType; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSchedulerConfiguration; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import com.google.common.collect.ImmutableSet; public class CapacitySchedulerConfiguration extends ReservationSchedulerConfiguration { private static final Log LOG = LogFactory.getLog(CapacitySchedulerConfiguration.class); private static final String CS_CONFIGURATION_FILE = "capacity-scheduler.xml"; @Private public static final String PREFIX = "yarn.scheduler.capacity."; @Private public static final String DOT = "."; @Private public static final String MAXIMUM_APPLICATIONS_SUFFIX = "maximum-applications"; @Private public static final String MAXIMUM_SYSTEM_APPLICATIONS = PREFIX + MAXIMUM_APPLICATIONS_SUFFIX; @Private public static final String MAXIMUM_AM_RESOURCE_SUFFIX = "maximum-am-resource-percent"; @Private public static final String MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT = PREFIX + MAXIMUM_AM_RESOURCE_SUFFIX; @Private public static final String QUEUES = "queues"; @Private public static final String CAPACITY = "capacity"; @Private public static final String MAXIMUM_CAPACITY = "maximum-capacity"; @Private public static final String USER_LIMIT = "minimum-user-limit-percent"; @Private public static final String USER_LIMIT_FACTOR = "user-limit-factor"; @Private public static final String STATE = "state"; @Private public static final String ACCESSIBLE_NODE_LABELS = "accessible-node-labels"; @Private public static final String DEFAULT_NODE_LABEL_EXPRESSION = "default-node-label-expression"; public static final String RESERVE_CONT_LOOK_ALL_NODES = PREFIX + "reservations-continue-look-all-nodes"; @Private public static final boolean DEFAULT_RESERVE_CONT_LOOK_ALL_NODES = true; @Private public static final String MAXIMUM_ALLOCATION_MB = "maximum-allocation-mb"; @Private public static final String MAXIMUM_ALLOCATION_VCORES = "maximum-allocation-vcores"; @Private public static final int DEFAULT_MAXIMUM_SYSTEM_APPLICATIIONS = 10000; @Private public static final float DEFAULT_MAXIMUM_APPLICATIONMASTERS_RESOURCE_PERCENT = 0.1f; @Private public static final float UNDEFINED = -1; @Private public static final float MINIMUM_CAPACITY_VALUE = 0; @Private public static final float MAXIMUM_CAPACITY_VALUE = 100; @Private public static final float DEFAULT_MAXIMUM_CAPACITY_VALUE = -1.0f; @Private public static final int DEFAULT_USER_LIMIT = 100; @Private public static final float DEFAULT_USER_LIMIT_FACTOR = 1.0f; @Private public static final String ALL_ACL = "*"; @Private public static final String NONE_ACL = " "; @Private public static final String ENABLE_USER_METRICS = PREFIX +"user-metrics.enable"; @Private public static final boolean DEFAULT_ENABLE_USER_METRICS = false; /** ResourceComparator for scheduling. */ @Private public static final String RESOURCE_CALCULATOR_CLASS = PREFIX + "resource-calculator"; @Private public static final Class<? extends ResourceCalculator> DEFAULT_RESOURCE_CALCULATOR_CLASS = DefaultResourceCalculator.class; @Private public static final String ROOT = "root"; @Private public static final String NODE_LOCALITY_DELAY = PREFIX + "node-locality-delay"; @Private public static final int DEFAULT_NODE_LOCALITY_DELAY = -1; @Private public static final String SCHEDULE_ASYNCHRONOUSLY_PREFIX = PREFIX + "schedule-asynchronously"; @Private public static final String SCHEDULE_ASYNCHRONOUSLY_ENABLE = SCHEDULE_ASYNCHRONOUSLY_PREFIX + ".enable"; @Private public static final boolean DEFAULT_SCHEDULE_ASYNCHRONOUSLY_ENABLE = false; @Private public static final String QUEUE_MAPPING = PREFIX + "queue-mappings"; @Private public static final String ENABLE_QUEUE_MAPPING_OVERRIDE = QUEUE_MAPPING + "-override.enable"; @Private public static final boolean DEFAULT_ENABLE_QUEUE_MAPPING_OVERRIDE = false; @Private public static final String QUEUE_PREEMPTION_DISABLED = "disable_preemption"; @Private public static class QueueMapping { public enum MappingType { USER("u"), GROUP("g"); private final String type; private MappingType(String type) { this.type = type; } public String toString() { return type; } }; MappingType type; String source; String queue; public QueueMapping(MappingType type, String source, String queue) { this.type = type; this.source = source; this.queue = queue; } } @Private public static final String AVERAGE_CAPACITY = "average-capacity"; @Private public static final String IS_RESERVABLE = "reservable"; @Private public static final String RESERVATION_WINDOW = "reservation-window"; @Private public static final String INSTANTANEOUS_MAX_CAPACITY = "instantaneous-max-capacity"; @Private public static final String RESERVATION_ADMISSION_POLICY = "reservation-policy"; @Private public static final String RESERVATION_AGENT_NAME = "reservation-agent"; @Private public static final String RESERVATION_SHOW_RESERVATION_AS_QUEUE = "show-reservations-as-queues"; @Private public static final String RESERVATION_PLANNER_NAME = "reservation-planner"; @Private public static final String RESERVATION_MOVE_ON_EXPIRY = "reservation-move-on-expiry"; @Private public static final String RESERVATION_ENFORCEMENT_WINDOW = "reservation-enforcement-window"; public CapacitySchedulerConfiguration() { this(new Configuration()); } public CapacitySchedulerConfiguration(Configuration configuration) { this(configuration, true); } public CapacitySchedulerConfiguration(Configuration configuration, boolean useLocalConfigurationProvider) { super(configuration); if (useLocalConfigurationProvider) { addResource(CS_CONFIGURATION_FILE); } } static String getQueuePrefix(String queue) { String queueName = PREFIX + queue + DOT; return queueName; } private String getNodeLabelPrefix(String queue, String label) { if (label.equals(CommonNodeLabelsManager.NO_LABEL)) { return getQueuePrefix(queue); } return getQueuePrefix(queue) + ACCESSIBLE_NODE_LABELS + DOT + label + DOT; } public int getMaximumSystemApplications() { int maxApplications = getInt(MAXIMUM_SYSTEM_APPLICATIONS, DEFAULT_MAXIMUM_SYSTEM_APPLICATIIONS); return maxApplications; } public float getMaximumApplicationMasterResourcePercent() { return getFloat(MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT, DEFAULT_MAXIMUM_APPLICATIONMASTERS_RESOURCE_PERCENT); } /** * Get the maximum applications per queue setting. * @param queue name of the queue * @return setting specified or -1 if not set */ public int getMaximumApplicationsPerQueue(String queue) { int maxApplicationsPerQueue = getInt(getQueuePrefix(queue) + MAXIMUM_APPLICATIONS_SUFFIX, (int)UNDEFINED); return maxApplicationsPerQueue; } /** * Get the maximum am resource percent per queue setting. * @param queue name of the queue * @return per queue setting or defaults to the global am-resource-percent * setting if per queue setting not present */ public float getMaximumApplicationMasterResourcePerQueuePercent(String queue) { return getFloat(getQueuePrefix(queue) + MAXIMUM_AM_RESOURCE_SUFFIX, getMaximumApplicationMasterResourcePercent()); } public float getNonLabeledQueueCapacity(String queue) { float capacity = queue.equals("root") ? 100.0f : getFloat( getQueuePrefix(queue) + CAPACITY, UNDEFINED); if (capacity < MINIMUM_CAPACITY_VALUE || capacity > MAXIMUM_CAPACITY_VALUE) { throw new IllegalArgumentException("Illegal " + "capacity of " + capacity + " for queue " + queue); } LOG.debug("CSConf - getCapacity: queuePrefix=" + getQueuePrefix(queue) + ", capacity=" + capacity); return capacity; } public void setCapacity(String queue, float capacity) { if (queue.equals("root")) { throw new IllegalArgumentException( "Cannot set capacity, root queue has a fixed capacity of 100.0f"); } setFloat(getQueuePrefix(queue) + CAPACITY, capacity); LOG.debug("CSConf - setCapacity: queuePrefix=" + getQueuePrefix(queue) + ", capacity=" + capacity); } public float getNonLabeledQueueMaximumCapacity(String queue) { float maxCapacity = getFloat(getQueuePrefix(queue) + MAXIMUM_CAPACITY, MAXIMUM_CAPACITY_VALUE); maxCapacity = (maxCapacity == DEFAULT_MAXIMUM_CAPACITY_VALUE) ? MAXIMUM_CAPACITY_VALUE : maxCapacity; return maxCapacity; } public void setMaximumCapacity(String queue, float maxCapacity) { if (maxCapacity > MAXIMUM_CAPACITY_VALUE) { throw new IllegalArgumentException("Illegal " + "maximum-capacity of " + maxCapacity + " for queue " + queue); } setFloat(getQueuePrefix(queue) + MAXIMUM_CAPACITY, maxCapacity); LOG.debug("CSConf - setMaxCapacity: queuePrefix=" + getQueuePrefix(queue) + ", maxCapacity=" + maxCapacity); } public void setCapacityByLabel(String queue, String label, float capacity) { setFloat(getNodeLabelPrefix(queue, label) + CAPACITY, capacity); } public void setMaximumCapacityByLabel(String queue, String label, float capacity) { setFloat(getNodeLabelPrefix(queue, label) + MAXIMUM_CAPACITY, capacity); } public int getUserLimit(String queue) { int userLimit = getInt(getQueuePrefix(queue) + USER_LIMIT, DEFAULT_USER_LIMIT); return userLimit; } public void setUserLimit(String queue, int userLimit) { setInt(getQueuePrefix(queue) + USER_LIMIT, userLimit); LOG.debug("here setUserLimit: queuePrefix=" + getQueuePrefix(queue) + ", userLimit=" + getUserLimit(queue)); } public float getUserLimitFactor(String queue) { float userLimitFactor = getFloat(getQueuePrefix(queue) + USER_LIMIT_FACTOR, DEFAULT_USER_LIMIT_FACTOR); return userLimitFactor; } public void setUserLimitFactor(String queue, float userLimitFactor) { setFloat(getQueuePrefix(queue) + USER_LIMIT_FACTOR, userLimitFactor); } public QueueState getState(String queue) { String state = get(getQueuePrefix(queue) + STATE); return (state != null) ? QueueState.valueOf(StringUtils.toUpperCase(state)) : QueueState.RUNNING; } public void setAccessibleNodeLabels(String queue, Set<String> labels) { if (labels == null) { return; } String str = StringUtils.join(",", labels); set(getQueuePrefix(queue) + ACCESSIBLE_NODE_LABELS, str); } public Set<String> getAccessibleNodeLabels(String queue) { String accessibleLabelStr = get(getQueuePrefix(queue) + ACCESSIBLE_NODE_LABELS); // When accessible-label is null, if (accessibleLabelStr == null) { // Only return null when queue is not ROOT if (!queue.equals(ROOT)) { return null; } } else { // print a warning when accessibleNodeLabel specified in config and queue // is ROOT if (queue.equals(ROOT)) { LOG.warn("Accessible node labels for root queue will be ignored," + " it will be automatically set to \"*\"."); } } // always return ANY for queue root if (queue.equals(ROOT)) { return ImmutableSet.of(RMNodeLabelsManager.ANY); } // In other cases, split the accessibleLabelStr by "," Set<String> set = new HashSet<String>(); for (String str : accessibleLabelStr.split(",")) { if (!str.trim().isEmpty()) { set.add(str.trim()); } } // if labels contains "*", only keep ANY behind if (set.contains(RMNodeLabelsManager.ANY)) { set.clear(); set.add(RMNodeLabelsManager.ANY); } return Collections.unmodifiableSet(set); } private float internalGetLabeledQueueCapacity(String queue, String label, String suffix, float defaultValue) { String capacityPropertyName = getNodeLabelPrefix(queue, label) + suffix; float capacity = getFloat(capacityPropertyName, defaultValue); if (capacity < MINIMUM_CAPACITY_VALUE || capacity > MAXIMUM_CAPACITY_VALUE) { throw new IllegalArgumentException("Illegal capacity of " + capacity + " for node-label=" + label + " in queue=" + queue + ", valid capacity should in range of [0, 100]."); } if (LOG.isDebugEnabled()) { LOG.debug("CSConf - getCapacityOfLabel: prefix=" + getNodeLabelPrefix(queue, label) + ", capacity=" + capacity); } return capacity; } public float getLabeledQueueCapacity(String queue, String label) { return internalGetLabeledQueueCapacity(queue, label, CAPACITY, 0f); } public float getLabeledQueueMaximumCapacity(String queue, String label) { return internalGetLabeledQueueCapacity(queue, label, MAXIMUM_CAPACITY, 100f); } public String getDefaultNodeLabelExpression(String queue) { return get(getQueuePrefix(queue) + DEFAULT_NODE_LABEL_EXPRESSION); } public void setDefaultNodeLabelExpression(String queue, String exp) { set(getQueuePrefix(queue) + DEFAULT_NODE_LABEL_EXPRESSION, exp); } /* * Returns whether we should continue to look at all heart beating nodes even * after the reservation limit was hit. The node heart beating in could * satisfy the request thus could be a better pick then waiting for the * reservation to be fullfilled. This config is refreshable. */ public boolean getReservationContinueLook() { return getBoolean(RESERVE_CONT_LOOK_ALL_NODES, DEFAULT_RESERVE_CONT_LOOK_ALL_NODES); } private static String getAclKey(QueueACL acl) { return "acl_" + StringUtils.toLowerCase(acl.toString()); } public AccessControlList getAcl(String queue, QueueACL acl) { String queuePrefix = getQueuePrefix(queue); // The root queue defaults to all access if not defined // Sub queues inherit access if not defined String defaultAcl = queue.equals(ROOT) ? ALL_ACL : NONE_ACL; String aclString = get(queuePrefix + getAclKey(acl), defaultAcl); return new AccessControlList(aclString); } public void setAcl(String queue, QueueACL acl, String aclString) { String queuePrefix = getQueuePrefix(queue); set(queuePrefix + getAclKey(acl), aclString); } public Map<AccessType, AccessControlList> getAcls(String queue) { Map<AccessType, AccessControlList> acls = new HashMap<AccessType, AccessControlList>(); for (QueueACL acl : QueueACL.values()) { acls.put(SchedulerUtils.toAccessType(acl), getAcl(queue, acl)); } return acls; } public void setAcls(String queue, Map<QueueACL, AccessControlList> acls) { for (Map.Entry<QueueACL, AccessControlList> e : acls.entrySet()) { setAcl(queue, e.getKey(), e.getValue().getAclString()); } } public String[] getQueues(String queue) { LOG.debug("CSConf - getQueues called for: queuePrefix=" + getQueuePrefix(queue)); String[] queues = getStrings(getQueuePrefix(queue) + QUEUES); List<String> trimmedQueueNames = new ArrayList<String>(); if (null != queues) { for (String s : queues) { trimmedQueueNames.add(s.trim()); } queues = trimmedQueueNames.toArray(new String[0]); } LOG.debug("CSConf - getQueues: queuePrefix=" + getQueuePrefix(queue) + ", queues=" + ((queues == null) ? "" : StringUtils.arrayToString(queues))); return queues; } public void setQueues(String queue, String[] subQueues) { set(getQueuePrefix(queue) + QUEUES, StringUtils.arrayToString(subQueues)); LOG.debug("CSConf - setQueues: qPrefix=" + getQueuePrefix(queue) + ", queues=" + StringUtils.arrayToString(subQueues)); } public Resource getMinimumAllocation() { int minimumMemory = getInt( YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB); int minimumCores = getInt( YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES); return Resources.createResource(minimumMemory, minimumCores); } public Resource getMaximumAllocation() { int maximumMemory = getInt( YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB); int maximumCores = getInt( YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES); return Resources.createResource(maximumMemory, maximumCores); } /** * Get the per queue setting for the maximum limit to allocate to * each container request. * * @param queue * name of the queue * @return setting specified per queue else falls back to the cluster setting */ public Resource getMaximumAllocationPerQueue(String queue) { String queuePrefix = getQueuePrefix(queue); int maxAllocationMbPerQueue = getInt(queuePrefix + MAXIMUM_ALLOCATION_MB, (int)UNDEFINED); int maxAllocationVcoresPerQueue = getInt( queuePrefix + MAXIMUM_ALLOCATION_VCORES, (int)UNDEFINED); if (LOG.isDebugEnabled()) { LOG.debug("max alloc mb per queue for " + queue + " is " + maxAllocationMbPerQueue); LOG.debug("max alloc vcores per queue for " + queue + " is " + maxAllocationVcoresPerQueue); } Resource clusterMax = getMaximumAllocation(); if (maxAllocationMbPerQueue == (int)UNDEFINED) { LOG.info("max alloc mb per queue for " + queue + " is undefined"); maxAllocationMbPerQueue = clusterMax.getMemory(); } if (maxAllocationVcoresPerQueue == (int)UNDEFINED) { LOG.info("max alloc vcore per queue for " + queue + " is undefined"); maxAllocationVcoresPerQueue = clusterMax.getVirtualCores(); } Resource result = Resources.createResource(maxAllocationMbPerQueue, maxAllocationVcoresPerQueue); if (maxAllocationMbPerQueue > clusterMax.getMemory() || maxAllocationVcoresPerQueue > clusterMax.getVirtualCores()) { throw new IllegalArgumentException( "Queue maximum allocation cannot be larger than the cluster setting" + " for queue " + queue + " max allocation per queue: " + result + " cluster setting: " + clusterMax); } return result; } public boolean getEnableUserMetrics() { return getBoolean(ENABLE_USER_METRICS, DEFAULT_ENABLE_USER_METRICS); } public int getNodeLocalityDelay() { int delay = getInt(NODE_LOCALITY_DELAY, DEFAULT_NODE_LOCALITY_DELAY); return (delay == DEFAULT_NODE_LOCALITY_DELAY) ? 0 : delay; } public ResourceCalculator getResourceCalculator() { return ReflectionUtils.newInstance( getClass( RESOURCE_CALCULATOR_CLASS, DEFAULT_RESOURCE_CALCULATOR_CLASS, ResourceCalculator.class), this); } public boolean getUsePortForNodeName() { return getBoolean(YarnConfiguration.RM_SCHEDULER_INCLUDE_PORT_IN_NODE_NAME, YarnConfiguration.DEFAULT_RM_SCHEDULER_USE_PORT_FOR_NODE_NAME); } public void setResourceComparator( Class<? extends ResourceCalculator> resourceCalculatorClass) { setClass( RESOURCE_CALCULATOR_CLASS, resourceCalculatorClass, ResourceCalculator.class); } public boolean getScheduleAynschronously() { return getBoolean(SCHEDULE_ASYNCHRONOUSLY_ENABLE, DEFAULT_SCHEDULE_ASYNCHRONOUSLY_ENABLE); } public void setScheduleAynschronously(boolean async) { setBoolean(SCHEDULE_ASYNCHRONOUSLY_ENABLE, async); } public boolean getOverrideWithQueueMappings() { return getBoolean(ENABLE_QUEUE_MAPPING_OVERRIDE, DEFAULT_ENABLE_QUEUE_MAPPING_OVERRIDE); } /** * Returns a collection of strings, trimming leading and trailing whitespeace * on each value * * @param str * String to parse * @param delim * delimiter to separate the values * @return Collection of parsed elements. */ private static Collection<String> getTrimmedStringCollection(String str, String delim) { List<String> values = new ArrayList<String>(); if (str == null) return values; StringTokenizer tokenizer = new StringTokenizer(str, delim); while (tokenizer.hasMoreTokens()) { String next = tokenizer.nextToken(); if (next == null || next.trim().isEmpty()) { continue; } values.add(next.trim()); } return values; } /** * Get user/group mappings to queues. * * @return user/groups mappings or null on illegal configs */ public List<QueueMapping> getQueueMappings() { List<QueueMapping> mappings = new ArrayList<CapacitySchedulerConfiguration.QueueMapping>(); Collection<String> mappingsString = getTrimmedStringCollection(QUEUE_MAPPING); for (String mappingValue : mappingsString) { String[] mapping = getTrimmedStringCollection(mappingValue, ":") .toArray(new String[] {}); if (mapping.length != 3 || mapping[1].length() == 0 || mapping[2].length() == 0) { throw new IllegalArgumentException( "Illegal queue mapping " + mappingValue); } QueueMapping m; try { QueueMapping.MappingType mappingType; if (mapping[0].equals("u")) { mappingType = QueueMapping.MappingType.USER; } else if (mapping[0].equals("g")) { mappingType = QueueMapping.MappingType.GROUP; } else { throw new IllegalArgumentException( "unknown mapping prefix " + mapping[0]); } m = new QueueMapping( mappingType, mapping[1], mapping[2]); } catch (Throwable t) { throw new IllegalArgumentException( "Illegal queue mapping " + mappingValue); } if (m != null) { mappings.add(m); } } return mappings; } public boolean isReservable(String queue) { boolean isReservable = getBoolean(getQueuePrefix(queue) + IS_RESERVABLE, false); return isReservable; } public void setReservable(String queue, boolean isReservable) { setBoolean(getQueuePrefix(queue) + IS_RESERVABLE, isReservable); LOG.debug("here setReservableQueue: queuePrefix=" + getQueuePrefix(queue) + ", isReservableQueue=" + isReservable(queue)); } @Override public long getReservationWindow(String queue) { long reservationWindow = getLong(getQueuePrefix(queue) + RESERVATION_WINDOW, DEFAULT_RESERVATION_WINDOW); return reservationWindow; } @Override public float getAverageCapacity(String queue) { float avgCapacity = getFloat(getQueuePrefix(queue) + AVERAGE_CAPACITY, MAXIMUM_CAPACITY_VALUE); return avgCapacity; } @Override public float getInstantaneousMaxCapacity(String queue) { float instMaxCapacity = getFloat(getQueuePrefix(queue) + INSTANTANEOUS_MAX_CAPACITY, MAXIMUM_CAPACITY_VALUE); return instMaxCapacity; } public void setInstantaneousMaxCapacity(String queue, float instMaxCapacity) { setFloat(getQueuePrefix(queue) + INSTANTANEOUS_MAX_CAPACITY, instMaxCapacity); } public void setReservationWindow(String queue, long reservationWindow) { setLong(getQueuePrefix(queue) + RESERVATION_WINDOW, reservationWindow); } public void setAverageCapacity(String queue, float avgCapacity) { setFloat(getQueuePrefix(queue) + AVERAGE_CAPACITY, avgCapacity); } @Override public String getReservationAdmissionPolicy(String queue) { String reservationPolicy = get(getQueuePrefix(queue) + RESERVATION_ADMISSION_POLICY, DEFAULT_RESERVATION_ADMISSION_POLICY); return reservationPolicy; } public void setReservationAdmissionPolicy(String queue, String reservationPolicy) { set(getQueuePrefix(queue) + RESERVATION_ADMISSION_POLICY, reservationPolicy); } @Override public String getReservationAgent(String queue) { String reservationAgent = get(getQueuePrefix(queue) + RESERVATION_AGENT_NAME, DEFAULT_RESERVATION_AGENT_NAME); return reservationAgent; } public void setReservationAgent(String queue, String reservationPolicy) { set(getQueuePrefix(queue) + RESERVATION_AGENT_NAME, reservationPolicy); } @Override public boolean getShowReservationAsQueues(String queuePath) { boolean showReservationAsQueues = getBoolean(getQueuePrefix(queuePath) + RESERVATION_SHOW_RESERVATION_AS_QUEUE, DEFAULT_SHOW_RESERVATIONS_AS_QUEUES); return showReservationAsQueues; } @Override public String getReplanner(String queue) { String replanner = get(getQueuePrefix(queue) + RESERVATION_PLANNER_NAME, DEFAULT_RESERVATION_PLANNER_NAME); return replanner; } @Override public boolean getMoveOnExpiry(String queue) { boolean killOnExpiry = getBoolean(getQueuePrefix(queue) + RESERVATION_MOVE_ON_EXPIRY, DEFAULT_RESERVATION_MOVE_ON_EXPIRY); return killOnExpiry; } @Override public long getEnforcementWindow(String queue) { long enforcementWindow = getLong(getQueuePrefix(queue) + RESERVATION_ENFORCEMENT_WINDOW, DEFAULT_RESERVATION_ENFORCEMENT_WINDOW); return enforcementWindow; } /** * Sets the <em>disable_preemption</em> property in order to indicate * whether or not container preemption will be disabled for the specified * queue. * * @param queue queue path * @param preemptionDisabled true if preemption is disabled on queue */ public void setPreemptionDisabled(String queue, boolean preemptionDisabled) { setBoolean(getQueuePrefix(queue) + QUEUE_PREEMPTION_DISABLED, preemptionDisabled); } /** * Indicates whether preemption is disabled on the specified queue. * * @param queue queue path to query * @param defaultVal used as default if the <em>disable_preemption</em> * is not set in the configuration * @return true if preemption is disabled on <em>queue</em>, false otherwise */ public boolean getPreemptionDisabled(String queue, boolean defaultVal) { boolean preemptionDisabled = getBoolean(getQueuePrefix(queue) + QUEUE_PREEMPTION_DISABLED, defaultVal); return preemptionDisabled; } /** * Get configured node labels in a given queuePath */ public Set<String> getConfiguredNodeLabels(String queuePath) { Set<String> configuredNodeLabels = new HashSet<String>(); Entry<String, String> e = null; Iterator<Entry<String, String>> iter = iterator(); while (iter.hasNext()) { e = iter.next(); String key = e.getKey(); if (key.startsWith(getQueuePrefix(queuePath) + ACCESSIBLE_NODE_LABELS + DOT)) { // Find <label-name> in // <queue-path>.accessible-node-labels.<label-name>.property int labelStartIdx = key.indexOf(ACCESSIBLE_NODE_LABELS) + ACCESSIBLE_NODE_LABELS.length() + 1; int labelEndIndx = key.indexOf('.', labelStartIdx); String labelName = key.substring(labelStartIdx, labelEndIndx); configuredNodeLabels.add(labelName); } } // always add NO_LABEL configuredNodeLabels.add(RMNodeLabelsManager.NO_LABEL); return configuredNodeLabels; } }
/* * Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.governance.api.common.dataobjects; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMText; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.governance.api.common.util.ApproveItemBean; import org.wso2.carbon.governance.api.common.util.CheckListItemBean; import org.wso2.carbon.governance.api.exception.GovernanceException; import org.wso2.carbon.governance.api.util.GovernanceConstants; import org.wso2.carbon.governance.api.util.GovernanceUtils; import org.wso2.carbon.registry.core.Association; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import javax.xml.namespace.QName; import java.util.*; /** * Governance Artifact abstract class, This is overwritten by Endpoint, Policy, Schema, Service, * WSDL, People classes. This keeps common methods shared by all the governance artifacts */ @SuppressWarnings("unused") public abstract class GovernanceArtifactImpl implements GovernanceArtifact { private static final Log log = LogFactory.getLog(GovernanceArtifactImpl.class); private String id; private String path; private Registry registry; // associated registry private String lcName; private String lcState; private String artifactPath; public String getLcName() { return lcName; } public void setLcName(String lcName) { this.lcName = lcName; } public String getLcState() { return lcState; } public void setLcState(String lcState) { this.lcState = lcState; } public String getArtifactPath() { return artifactPath; } public void setArtifactPath(String artifactPath) { this.artifactPath = artifactPath; } /** * Map of attributes associated with this governance artifact. */ protected Map<String, List<String>> attributes = new HashMap<String, List<String>>(); /** * Construct a governance artifact object from the path and the id. * * @param id the id */ public GovernanceArtifactImpl(String id) { this.id = id; } /** * Construct a governance artifact. The default constructor. */ public GovernanceArtifactImpl() { // the default constructor } /** * Copy constructor used for cloning. * * @param artifact the object to be copied. */ protected GovernanceArtifactImpl(GovernanceArtifactImpl artifact) { if (artifact != null) { this.attributes = artifact.attributes; this.lcName = artifact.lcName; this.lcState = artifact.lcState; // if (artifact.checkListItemBeans != null) { // this.checkListItemBeans = Arrays.copyOf(artifact.checkListItemBeans, artifact.checkListItemBeans.length); // } // if (artifact.approveItemBeans != null) { // this.approveItemBeans = Arrays.copyOf(artifact.approveItemBeans, artifact.approveItemBeans.length); // } this.artifactPath = artifact.artifactPath; try { associateRegistry(artifact.getAssociatedRegistry()); } catch (GovernanceException ignored) { } setId(artifact.getId()); } } /** * Constructor accepting resource identifier and the XML content. * * @param id the resource identifier. * @param contentElement an XML element containing the content. * @throws GovernanceException if the construction fails. */ public GovernanceArtifactImpl(String id, OMElement contentElement) throws GovernanceException { this(id); serializeToAttributes(contentElement, null); } // Method to serialize attributes. private void serializeToAttributes(OMElement contentElement, String parentAttributeName) throws GovernanceException { Iterator childIt = contentElement.getChildren(); if (childIt.hasNext()) { while (childIt.hasNext()) { Object childObj = childIt.next(); if (childObj instanceof OMElement) { OMElement childElement = (OMElement) childObj; String elementName = childElement.getLocalName(); String attributeName = (parentAttributeName == null ? "" : parentAttributeName + "_") + elementName; serializeToAttributes(childElement, attributeName); } else if (childObj instanceof OMText) { OMText childText = (OMText) childObj; if (childText.getNextOMSibling() == null && childText.getPreviousOMSibling() == null) { // if it is only child, we consider it is a value. String textValue = childText.getText(); addAttribute(parentAttributeName, textValue); } } } } else { if(contentElement != null && !contentElement.getChildElements().hasNext()){ addAttribute(parentAttributeName, null); } } } public static GovernanceArtifactImpl create(final Registry registry, final String artifactId) throws GovernanceException { return new GovernanceArtifactImpl(artifactId) { { associateRegistry(registry); } public QName getQName() { return null; } }; } public static GovernanceArtifactImpl create(final Registry registry, final String artifactId, final OMElement content) throws GovernanceException { return new GovernanceArtifactImpl(artifactId, content) { { associateRegistry(registry); } public QName getQName() { return null; } }; } /** * Returns the id of the artifact * * @return the id */ @Override public String getId() { return id; } /** * Set the id * * @param id the id */ @Override public void setId(String id) { this.id = id; } /** * Returns the path of the artifact, need to save the artifact before * getting the path. * * @return here we return the path of the artifact. * @throws GovernanceException if an error occurred. */ @Override public String getPath() throws GovernanceException { if (path == null) { path = GovernanceUtils.getArtifactPath(registry, id); } return path; } /** * Returns the name of the lifecycle associated with this artifact. * * @return the name of the lifecycle associated with this artifact. * @throws GovernanceException if an error occurred. */ @Override public String getLifecycleName() throws GovernanceException { String path = getPath(); if (path != null) { try { if (!registry.resourceExists(path)) { String msg = "The artifact is not added to the registry. Please add the artifact " + "before reading lifecycle information."; log.error(msg); throw new GovernanceException(msg); } return registry.get(path).getProperty("registry.LC.name"); } catch (RegistryException e) { String msg = "Error in obtaining lifecycle name for the artifact. id: " + id + ", path: " + path + "."; log.error(msg, e); throw new GovernanceException(msg, e); } } return null; } /** * Associates the named lifecycle with the artifact * * @param name the name of the lifecycle to be associated with this artifact. * @throws GovernanceException if an error occurred. */ @Override public void attachLifecycle(String name) throws GovernanceException { lcName = getLifecycleName(); try { if (name == null) { GovernanceUtils.removeAspect(path, lcName, registry); return; } if (!name.equals(lcName)) { if (lcName != null) { GovernanceUtils.removeAspect(path, lcName, registry); } registry.associateAspect(path, name); } } catch (RegistryException e) { String msg = "Error in associating lifecycle for the artifact. id: " + id + ", path: " + path + "."; log.error(msg, e); throw new GovernanceException(msg, e); } } /** * De-associate lifecycle associated with the artifact * * @throws GovernanceException if an error occurred. */ public void detachLifecycle() throws GovernanceException { String lifecycleName = getLifecycleName(); if (lifecycleName == null) { throw new GovernanceException("No lifecycle associated with the artifact"); } try { GovernanceUtils.removeAspect(path, lifecycleName, registry); lcName = null; lcState = null; } catch (RegistryException e) { String msg = "Error in de-associating lifecycle for the artifact. id: " + id + ", path: " + path + "."; log.error(msg, e); throw new GovernanceException(msg, e); } } /** * Returns the state of the lifecycle associated with this artifact. * * @return the state of the lifecycle associated with this artifact. * @throws GovernanceException if an error occurred. */ @Override public String getLifecycleState() throws GovernanceException { String path = getPath(); if (path != null) { try { if (!registry.resourceExists(path)) { String msg = "The artifact is not added to the registry. Please add the artifact " + "before reading lifecycle information."; log.error(msg); throw new GovernanceException(msg); } Resource resource = registry.get(path); for (Object object : resource.getProperties().keySet()) { String property = (String) object; if (property.startsWith("registry.lifecycle.") && property.endsWith(".state")) { lcState = resource.getProperty(property); return lcState; } } } catch (RegistryException e) { String msg = "Error in obtaining lifecycle state for the artifact. id: " + id + ", path: " + path + "."; log.error(msg, e); throw new GovernanceException(msg, e); } } return null; } /** * update the path after moving the resource. * * @throws GovernanceException if an error occurred. */ public void updatePath() throws GovernanceException { path = GovernanceUtils.getArtifactPath(registry, id); } /** * update the path after moving the resource. * * @param artifactId * @throws GovernanceException if an error occurred. */ public void updatePath(String artifactId) throws GovernanceException { path = GovernanceUtils.getArtifactPath(registry, artifactId); } /** * Create a version of the artifact. * * @throws GovernanceException throws if the operation failed. */ public void createVersion() throws GovernanceException { checkRegistryResourceAssociation(); try { if (!registry.resourceExists(path)) { String msg = "The artifact is not added to the registry. Please add the artifact " + "before creating versions."; log.error(msg); throw new GovernanceException(msg); } registry.createVersion(path); } catch (RegistryException e) { String msg = "Error in creating a version for the artifact. id: " + id + ", path: " + path + "."; log.error(msg, e); throw new GovernanceException(msg, e); } } /** * Associate a registry, this is mostly used by the artifact manager when creating the * artifact. * * @param registry the registry. * @throws GovernanceException throws if the operation failed. */ public void associateRegistry(Registry registry) throws GovernanceException { this.registry = registry; } /** * Adding an attribute to the artifact. The artifact should be saved to get effect the change. * In the case of a single-valued attribute, this method will set or replace the existing * attribute with the provided value. In the case of a multi-valued attribute, this method will * append the provided value to the existing list. * * @param key the key. * @param value the value. * @throws GovernanceException throws if the operation failed. */ @Override public void addAttribute(String key, String value) throws GovernanceException { List<String> values = attributes.get(key); if (values == null) { values = new ArrayList<String>(); attributes.put(key, values); } values.add(value); } /** * Set/Update an attribute with multiple values. The artifact should be saved to get effect the * change. * * @param key the key * @param newValues the value * @throws GovernanceException throws if the operation failed. */ @Override public void setAttributes(String key, String[] newValues) throws GovernanceException { List<String> values = new ArrayList<String>(); values.addAll(Arrays.asList(newValues)); attributes.put(key, values); } /** * Set/Update an attribute with a single value. The artifact should be saved to get effect the * change. This method will replace the existing attribute with the provided value. In the case * of a multi-valued attribute this will remove all existing values. If you want to append the * provided value to a list values of a multi-valued attribute, use the addAttribute method * instead. * * @param key the key * @param newValue the value * @throws GovernanceException throws if the operation failed. */ @Override public void setAttribute(String key, String newValue) throws GovernanceException { List<String> values = new ArrayList<String>(); values.add(newValue); attributes.put(key, values); } /** * Returns the attribute of a given key. * * @param key the key * @return the value of the attribute, if there are more than one attribute for the key this * returns the first value. * @throws GovernanceException throws if the operation failed. */ @Override public String getAttribute(String key) throws GovernanceException { List<String> values = attributes.get(key); if (values == null || values.size() == 0) { return null; } return values.get(0); } /** * Returns the available attribute keys * * @return an array of attribute keys. * @throws GovernanceException throws if the operation failed. */ @Override public String[] getAttributeKeys() throws GovernanceException { Set<String> attributeKeys = attributes.keySet(); if (attributeKeys == null) { return null; } return attributeKeys.toArray(new String[attributeKeys.size()]); } /** * Returns the attribute values for a key. * * @param key the key. * @return attribute values for the key. * @throws GovernanceException throws if the operation failed. */ @Override public String[] getAttributes(String key) throws GovernanceException { List<String> values = attributes.get(key); if (values == null) { return null; //TODO: This should return String[0] } return values.toArray(new String[values.size()]); } /** * Remove attribute with the given key. The artifact should be saved to get effect the change. * * @param key the key * @throws GovernanceException throws if the operation failed. */ @Override public void removeAttribute(String key) throws GovernanceException { attributes.remove(key); } /** * Get dependencies of an artifacts. The artifacts should be saved, before calling this method. * * @return an array of dependencies of this artifact. * @throws GovernanceException throws if the operation failed. */ @Override public GovernanceArtifact[] getDependencies() throws GovernanceException { checkRegistryResourceAssociation(); // uses the path from the getter to make sure the used overloaded method String path = getPath(); List<GovernanceArtifact> governanceArtifacts = new ArrayList<GovernanceArtifact>(); try { Association[] associations = registry.getAssociations(path, GovernanceConstants.DEPENDS); for (Association association : associations) { String destinationPath = association.getDestinationPath(); if (!destinationPath.equals(path)) { GovernanceArtifact governanceArtifact = GovernanceUtils.retrieveGovernanceArtifactByPath(registry, destinationPath); governanceArtifacts.add(governanceArtifact); } } } catch (RegistryException e) { String msg = "Error in getting dependencies from the artifact. id: " + id + ", path: " + path + "."; log.error(msg, e); throw new GovernanceException(msg, e); } return governanceArtifacts.toArray(new GovernanceArtifact[governanceArtifacts.size()]); } /** * Get dependents of an artifact. The artifacts should be saved, before calling this method. * * @return an array of artifacts that is dependent on this artifact. * @throws GovernanceException throws if the operation failed. */ @Override public GovernanceArtifact[] getDependents() throws GovernanceException { checkRegistryResourceAssociation(); // uses the path from the getter to make sure the used overloaded method String path = getPath(); List<GovernanceArtifact> governanceArtifacts = new ArrayList<GovernanceArtifact>(); try { Association[] associations = registry.getAssociations(path, GovernanceConstants.USED_BY); for (Association association : associations) { String destinationPath = association.getDestinationPath(); if (!destinationPath.equals(path)) { GovernanceArtifact governanceArtifact = GovernanceUtils.retrieveGovernanceArtifactByPath(registry, destinationPath); governanceArtifacts.add(governanceArtifact); } } } catch (RegistryException e) { String msg = "Error in getting dependents from the artifact. id: " + id + ", path: " + path + "."; log.error(msg, e); throw new GovernanceException(msg, e); } return governanceArtifacts.toArray(new GovernanceArtifact[governanceArtifacts.size()]); } /** * Get all lifecycle actions for the current state of the lifecycle * * @return Action set which can be invoked * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public String[] getAllLifecycleActions() throws GovernanceException { String lifecycleName = getLifecycleName(); try { return registry.getAspectActions(path, lifecycleName); } catch (RegistryException e) { String lifecycleState = getLifecycleState(); String msg = "Error while retrieving the lifecycle actions " + "for lifecycle: " + lifecycleName + " in lifecycle state: " + lifecycleState; throw new GovernanceException(msg, e); } } /** * Invoke lifecycle action * * @param action lifecycle action tobe invoked * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public void invokeAction(String action) throws GovernanceException { invokeAction(action, new HashMap<String, String>()); } /** * Invoke lifecycle action * * @param action lifecycle action tobe invoked * @param parameters extra parameters needed when promoting * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public void invokeAction(String action, Map<String, String> parameters) throws GovernanceException { Resource artifactResource = getArtifactResource(); CheckListItemBean[] checkListItemBeans = GovernanceUtils.getAllCheckListItemBeans(artifactResource, this); try { if (checkListItemBeans != null) { for (CheckListItemBean checkListItemBean : checkListItemBeans) { parameters.put(checkListItemBean.getOrder() + ".item", checkListItemBean.getValue().toString()); } } registry.invokeAspect(getArtifactPath(), getLcName(), action, parameters); } catch (RegistryException e) { String msg = "Invoking lifecycle action \"" + action + "\" failed"; log.error(msg, e); throw new GovernanceException(msg, e); } } /** * Retrieve name set of the checklist items * * @return Checklist item name set * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public String[] getAllCheckListItemNames() throws GovernanceException { Resource artifactResource = getArtifactResource(); CheckListItemBean[] checkListItemBeans = GovernanceUtils.getAllCheckListItemBeans(artifactResource, this); if (checkListItemBeans == null) { throw new GovernanceException("No checklist item found for the lifecycle: " + getLcName() + " lifecycle state: " + getLcState() + " in the artifact " + getQName().getLocalPart()); } String[] checkListItemNames = new String[checkListItemBeans.length]; for (CheckListItemBean checkListItemBean : checkListItemBeans) { checkListItemNames[checkListItemBean.getOrder()] = checkListItemBean.getName(); } return checkListItemNames; } /** * Check the checklist item * * @param order order of the checklist item need to checked * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public void checkLCItem(int order) throws GovernanceException { Resource artifactResource = getArtifactResource(); CheckListItemBean[] checkListItemBeans = GovernanceUtils.getAllCheckListItemBeans(artifactResource, this); if (checkListItemBeans == null || order < 0 || order >= checkListItemBeans.length) { throw new GovernanceException("Invalid check list item."); } else if (checkListItemBeans[order].getValue()) { throw new GovernanceException("lifecycle checklist item \"" + checkListItemBeans[order].getName() + "\" already checked"); } try { setCheckListItemValue(order, true, checkListItemBeans); } catch (RegistryException e) { String msg = "Checking LC item failed for check list item " + checkListItemBeans[order].getName(); log.error(msg, e); throw new GovernanceException(msg, e); } } /** * Check whether the given ordered lifecycle checklist item is checked or not * * @param order order of the checklist item need to unchecked * @return whether the given ordered lifecycle checklist item is checked or not * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public boolean isLCItemChecked(int order) throws GovernanceException { Resource artifactResource = getArtifactResource(); CheckListItemBean[] checkListItemBeans = GovernanceUtils.getAllCheckListItemBeans(artifactResource, this); if (checkListItemBeans == null || order < 0 || order >= checkListItemBeans.length) { throw new GovernanceException("Invalid check list item."); } return checkListItemBeans[order].getValue(); } /** * Un-check the checklist item * * @param order order of the checklist item need to unchecked * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public void uncheckLCItem(int order) throws GovernanceException { Resource artifactResource = getArtifactResource(); CheckListItemBean[] checkListItemBeans = GovernanceUtils.getAllCheckListItemBeans(artifactResource, this); if (checkListItemBeans == null || order < 0 || order >= checkListItemBeans.length) { throw new GovernanceException("Invalid check list item."); } else if (!checkListItemBeans[order].getValue()) { throw new GovernanceException("lifecycle checklist item \"" + checkListItemBeans[order].getName() + "\" not checked"); } try { setCheckListItemValue(order, false, checkListItemBeans); } catch (RegistryException e) { String msg = "Unchecking LC item failed for check list item: " + checkListItemBeans[order].getName(); log.error(msg, e); throw new GovernanceException(msg, e); } } /** * Set the checklist item value * * @param order order of the checklist item * @param value value of the checklist item * @throws RegistryException throws if the operation failed. */ private void setCheckListItemValue(int order, boolean value, CheckListItemBean[] checkListItemBeans) throws RegistryException { checkListItemBeans[order].setValue(value); Map<String, String> parameters = new HashMap<String, String>(); if (checkListItemBeans != null) { for (CheckListItemBean checkListItemBean : checkListItemBeans) { parameters.put(checkListItemBean.getOrder() + ".item", checkListItemBean.getValue().toString()); } } registry.invokeAspect(getArtifactPath(), getLcName(), "itemClick", parameters); } /** * Retrieve action set which need votes * * @return Action set which can vote * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public String[] getAllVotingItems() throws GovernanceException { Resource artifactResource = getArtifactResource(); ApproveItemBean[] approveItemBeans = GovernanceUtils. getAllApproveItemBeans(((UserRegistry) registry).getUserName(), artifactResource, this); if (approveItemBeans == null) { throw new GovernanceException("No voting event found for the lifecycle: " + getLcName() + " in lifecycle state: " + getLcState() + " of the artifact " + getQName().getLocalPart()); } String[] votingItems = new String[approveItemBeans.length]; for (ApproveItemBean approveItemBean : approveItemBeans) { votingItems[approveItemBean.getOrder()] = approveItemBean.getName(); } return votingItems; } /** * Vote for an action * * @param order order of the action which need to be voted * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public void vote(int order) throws GovernanceException { Resource artifactResource = getArtifactResource(); ApproveItemBean[] approveItemBeans = GovernanceUtils. getAllApproveItemBeans(((UserRegistry) registry).getUserName(), artifactResource, this); if (approveItemBeans == null || order < 0 || order >= approveItemBeans.length) { throw new GovernanceException("Invalid voting action selected"); } else if (approveItemBeans[order].getValue()) { throw new GovernanceException("Already voted for the action " + approveItemBeans[order].getName()); } try { setVotingItemValue(order, true, approveItemBeans); } catch (RegistryException e) { String msg = "Voting failed for action " + approveItemBeans[order].getName(); log.error(msg, e); throw new GovernanceException(msg, e); } } /** * Check whether the current user voted for given order event * * @param order order of the action which need to be voted * @return whether the current user voted for the given order event * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public boolean isVoted(int order) throws GovernanceException { Resource artifactResource = getArtifactResource(); ApproveItemBean[] approveItemBeans = GovernanceUtils. getAllApproveItemBeans(((UserRegistry) registry).getUserName(), artifactResource, this); if (approveItemBeans == null || order < 0 || order >= approveItemBeans.length) { throw new GovernanceException("Invalid voting action selected"); } return approveItemBeans[order].getValue(); } /** * Unvote for an action * * @param order order of the action which need to be unvoted * @throws org.wso2.carbon.governance.api.exception.GovernanceException * throws if the operation failed. */ public void unvote(int order) throws GovernanceException { Resource artifactResource = getArtifactResource(); ApproveItemBean[] approveItemBeans = GovernanceUtils. getAllApproveItemBeans(((UserRegistry) registry).getUserName(), artifactResource, this); if (approveItemBeans == null || order < 0 || order >= approveItemBeans.length) { throw new GovernanceException("Invalid voting action selected"); } else if (!approveItemBeans[order].getValue()) { throw new GovernanceException("Not voted for the action \"" + approveItemBeans[order].getName() + "\""); } try { setVotingItemValue(order, false, approveItemBeans); } catch (RegistryException e) { String msg = "Unvoting failed for action \"" + approveItemBeans[order].getName() + "\""; log.error(msg, e); throw new GovernanceException(msg, e); } } /** * Set the approval value * * @param order order of the approve event * @param value value of the approve * @throws RegistryException throws if the operation failed. */ private void setVotingItemValue(int order, boolean value, ApproveItemBean[] approveItemBeans) throws RegistryException { approveItemBeans[order].setValue(value); Map<String, String> parameters = new HashMap<String, String>(); for (ApproveItemBean approveItemBean : approveItemBeans) { parameters.put(approveItemBean.getOrder() + ".vote", approveItemBean.getValue().toString()); } registry.invokeAspect(getArtifactPath(), getLcName(), "voteClick", parameters); } /** * Attach the current artifact to an another artifact. Both the artifacts should be saved, * before calling this method. This method will two generic artifact types. There are specific * methods * * @param attachedToArtifact the artifact the current artifact is attached to * @throws GovernanceException throws if the operation failed. */ protected void attach(GovernanceArtifact attachedToArtifact) throws GovernanceException { checkRegistryResourceAssociation(); // uses the path from the getter to make sure the used overloaded method String path = getPath(); String attachedToArtifactPath = attachedToArtifact.getPath(); if (attachedToArtifactPath == null) { String msg = "'Attached to artifact' is not associated with a registry path."; log.error(msg); throw new GovernanceException(msg); } try { registry.addAssociation(attachedToArtifactPath, path, GovernanceConstants.USED_BY); registry.addAssociation(path, attachedToArtifactPath, GovernanceConstants.DEPENDS); } catch (RegistryException e) { String msg = "Error in attaching the artifact. source id: " + id + ", path: " + path + ", target id: " + attachedToArtifact.getId() + ", path:" + attachedToArtifactPath + ", attachment type: " + attachedToArtifact.getClass().getName() + "."; log.error(msg, e); throw new GovernanceException(msg, e); } } /** * Detach the current artifact from the provided artifact. Both the artifacts should be saved, * before calling this method. * * @param artifactId the artifact id of the attached artifact * @throws GovernanceException throws if the operation failed. */ protected void detach(String artifactId) throws GovernanceException { checkRegistryResourceAssociation(); // uses the path from the getter to make sure the used overloaded method String path = getPath(); String artifactPath = GovernanceUtils.getArtifactPath(registry, artifactId); if (artifactPath == null) { String msg = "Attached to artifact is not associated with a registry path."; log.error(msg); throw new GovernanceException(msg); } try { registry.removeAssociation(path, artifactPath, GovernanceConstants.DEPENDS); registry.removeAssociation(artifactPath, path, GovernanceConstants.USED_BY); } catch (RegistryException e) { String msg = "Error in detaching the artifact. source id: " + id + ", path: " + path + ", target id: " + artifactId + ", target path:" + artifactPath + "."; log.error(msg, e); throw new GovernanceException(msg, e); } } /** * Validate the resource is associated with a registry * * @throws GovernanceException if the resource is not associated with a registry. */ protected void checkRegistryResourceAssociation() throws GovernanceException { // uses the path from the getter to make sure the used overloaded method String path = getPath(); if (registry == null) { String msg = "A registry is not associated with the artifact."; log.error(msg); throw new GovernanceException(msg); } if (path == null) { String msg = "A path is not associated with the artifact."; log.error(msg); throw new GovernanceException(msg); } if (id == null) { String msg = "An id is not associated with the artifact."; log.error(msg); throw new GovernanceException(msg); } } /** * Returns the associated registry to the artifact. * * @return the associated registry */ protected Registry getAssociatedRegistry() { return registry; } /** * Get the resource related to this artifact * * @return resource related to this artifact * @throws GovernanceException if there is no resource related to the artifact in the registry */ private Resource getArtifactResource() throws GovernanceException { Resource artifactResource; try { return registry.get(artifactPath); } catch (RegistryException e) { String msg = "Artifact resource \"" + getQName().getLocalPart() + "\" not found in the registry"; throw new GovernanceException(); } } }
/* 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.security.zynamics.binnavi.disassembly.Modules; 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 com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableList; import com.google.security.zynamics.binnavi.Database.Exceptions.CPartialLoadException; import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntDeleteException; import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntLoadDataException; import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException; import com.google.security.zynamics.binnavi.Database.Exceptions.LoadCancelledException; import com.google.security.zynamics.binnavi.Database.MockClasses.MockSqlProvider; import com.google.security.zynamics.binnavi.Exceptions.MaybeNullException; import com.google.security.zynamics.binnavi.Tagging.CTag; import com.google.security.zynamics.binnavi.Tagging.TagType; import com.google.security.zynamics.binnavi.debug.models.trace.TraceList; import com.google.security.zynamics.binnavi.disassembly.CCallgraph; import com.google.security.zynamics.binnavi.disassembly.ICallgraphView; import com.google.security.zynamics.binnavi.disassembly.IFlowgraphView; import com.google.security.zynamics.binnavi.disassembly.INaviFunction; import com.google.security.zynamics.binnavi.disassembly.MockView; import com.google.security.zynamics.binnavi.disassembly.types.ExpensiveBaseTest; import com.google.security.zynamics.binnavi.disassembly.types.SectionContainer; import com.google.security.zynamics.binnavi.disassembly.types.SectionContainerBackend; import com.google.security.zynamics.binnavi.disassembly.types.TypeInstanceContainer; import com.google.security.zynamics.binnavi.disassembly.types.TypeInstanceContainerBackend; import com.google.security.zynamics.binnavi.disassembly.views.CView; import com.google.security.zynamics.binnavi.disassembly.views.CViewFilter; import com.google.security.zynamics.binnavi.disassembly.views.INaviView; import com.google.security.zynamics.zylib.disassembly.CAddress; import com.google.security.zynamics.zylib.disassembly.IAddress; import com.google.security.zynamics.zylib.disassembly.ViewType; import com.google.security.zynamics.zylib.general.ListenerProvider; import com.google.security.zynamics.zylib.general.Pair; import com.google.security.zynamics.zylib.types.lists.FilledList; import com.google.security.zynamics.zylib.types.lists.IFilledList; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Test class for all tests related to the module content. */ @RunWith(JUnit4.class) public class CPostgreSQLModuleContentTest extends ExpensiveBaseTest { @Test public void testAddView() throws CouldntLoadDataException, LoadCancelledException, CPartialLoadException, CouldntSaveDataException { final CModule module = (CModule) getDatabase().getContent().getModules().get(0); module.load(); final CModuleContent moduleContent1 = module.getContent(); assertNotNull(moduleContent1); final CView view = moduleContent1.getViewContainer().createView("name", "desc"); final CView view2 = (CView) moduleContent1.getViewContainer().getViews().get(1); assertNotNull(view); assertNotNull(view2); view2.load(); view2.getContent() .createFunctionNode(module.getContent().getFunctionContainer().getFunctions().get(0)); view2.getConfiguration().setDescription("foobar"); view2.getConfiguration().setName("barfoo"); try { moduleContent1.getViewContainer().createView(null, null); fail(); } catch (final NullPointerException e) { } try { moduleContent1.getViewContainer().createView("name", null); fail(); } catch (final NullPointerException e) { } try { moduleContent1.close(); moduleContent1.getViewContainer().createView("name", "desc"); fail(); } catch (final IllegalStateException e) { } } @Test public void testCModuleContentConstructor() throws LoadCancelledException, CouldntLoadDataException { final CModule module = (CModule) getDatabase().getContent().getModules().get(0); module.load(); final ListenerProvider<IModuleListener> listeners = new ListenerProvider<IModuleListener>(); final CCallgraph callgraph = module.getContent().getNativeCallgraph(); final IFilledList<INaviFunction> functions = new FilledList<INaviFunction>(); functions.add(module.getContent().getFunctionContainer().getFunctions().get(0)); final ICallgraphView nativeCallgraph = module.getContent().getViewContainer().getNativeCallgraphView(); final ImmutableList<IFlowgraphView> nativeFlowgraphs = module.getContent().getViewContainer().getNativeFlowgraphViews(); final List<INaviView> customViews = new ArrayList<INaviView>(); final ImmutableBiMap<INaviView, INaviFunction> viewFunctionMap = new ImmutableBiMap.Builder<INaviView, INaviFunction>().build(); new Pair<HashMap<INaviView, INaviFunction>, HashMap<INaviFunction, INaviView>>(null, null); final IFilledList<TraceList> traces = new FilledList<TraceList>(); final SectionContainer sections = new SectionContainer(new SectionContainerBackend(getProvider(), module)); final TypeInstanceContainer instances = new TypeInstanceContainer( new TypeInstanceContainerBackend(getProvider(), module, module.getTypeManager(), sections), getProvider()); final CModuleContent moduleContent1 = new CModuleContent( module, getProvider(), listeners, callgraph, functions, nativeCallgraph, nativeFlowgraphs, customViews, viewFunctionMap, traces, sections, instances); assertNotNull(moduleContent1); try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( null, null, null, null, null, null, null, null, null, null, sections, instances); fail(); } catch (final NullPointerException e) { } try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( module, null, null, null, null, null, null, null, null, null, null, null); fail(); } catch (final NullPointerException e) { } try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( module, getProvider(), null, null, null, null, null, null, null, null, null, null); fail(); } catch (final NullPointerException e) { } try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( module, getProvider(), listeners, null, null, null, null, null, null, null, null, null); fail(); } catch (final NullPointerException e) { } try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( module, getProvider(), listeners, callgraph, null, null, null, null, null, null, null, null); fail(); } catch (final NullPointerException e) { } try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( module, getProvider(), listeners, callgraph, functions, null, null, null, null, null, null, null); fail(); } catch (final NullPointerException e) { } try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( module, getProvider(), listeners, callgraph, functions, nativeCallgraph, null, null, null, null, null, null); fail(); } catch (final NullPointerException e) { } try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( module, getProvider(), listeners, callgraph, functions, nativeCallgraph, nativeFlowgraphs, null, null, null, null, null); fail(); } catch (final NullPointerException e) { } try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( module, getProvider(), listeners, callgraph, functions, nativeCallgraph, nativeFlowgraphs, customViews, null, null, null, null); fail(); } catch (final NullPointerException e) { } try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( module, getProvider(), listeners, callgraph, functions, nativeCallgraph, nativeFlowgraphs, customViews, viewFunctionMap, null, null, null); fail(); } catch (final NullPointerException e) { } try { @SuppressWarnings("unused") final CModuleContent moduleContent = new CModuleContent( module, getProvider(), listeners, callgraph, functions, nativeCallgraph, nativeFlowgraphs, customViews, viewFunctionMap, traces, null, null); fail(); } catch (final NullPointerException e) { } } @Test public void testCreateTrace() throws LoadCancelledException, CouldntLoadDataException, CouldntSaveDataException { final CModule module = (CModule) getDatabase().getContent().getModules().get(0); module.load(); final CModuleContent moduleContent1 = module.getContent(); assertNotNull(moduleContent1); final TraceList trace = moduleContent1.getTraceContainer().createTrace("name", "desc"); assertNotNull(trace); try { moduleContent1.getTraceContainer().createTrace(null, null); fail(); } catch (final NullPointerException e) { } try { moduleContent1.getTraceContainer().createTrace("name", null); fail(); } catch (final NullPointerException e) { } try { moduleContent1.close(); moduleContent1.getTraceContainer().createTrace("name2", "desc2"); fail(); } catch (final IllegalStateException e) { } } @Test public void testDeleteTrace() throws LoadCancelledException, CouldntLoadDataException, CouldntSaveDataException, CouldntDeleteException { final CModule module = (CModule) getDatabase().getContent().getModules().get(0); module.load(); final CModuleContent moduleContent1 = module.getContent(); assertNotNull(moduleContent1); final CView view = moduleContent1.getViewContainer().createView("name", "desc"); assertNotNull(view); final TraceList trace = moduleContent1.getTraceContainer().createTrace("name2", "desc2"); assertNotNull(trace); moduleContent1.getTraceContainer().deleteTrace(trace); try { moduleContent1.getTraceContainer().deleteTrace(null); } catch (final NullPointerException e) { } } @Test public void testDeleteView() throws LoadCancelledException, CouldntLoadDataException, CouldntDeleteException { final CModule module = (CModule) getDatabase().getContent().getModules().get(0); module.load(); final CModuleContent moduleContent1 = module.getContent(); assertNotNull(moduleContent1); final CView view = moduleContent1.getViewContainer().createView("name", "desc"); assertNotNull(view); try { moduleContent1.getViewContainer().deleteView(null); fail(); } catch (final NullPointerException e) { } assertEquals(1, moduleContent1.getViewContainer().getCustomViewCount()); moduleContent1.getViewContainer().deleteView(view); assertEquals(0, moduleContent1.getViewContainer().getCustomViewCount()); try { moduleContent1.getViewContainer().deleteView(view); fail(); } catch (final IllegalArgumentException e) { } try { moduleContent1.getViewContainer().deleteView(null); fail(); } catch (final NullPointerException e) { } CView nativeView = null; for (final INaviView view1 : module.getContent().getViewContainer().getViews()) { if (view1.getType() == ViewType.Native) { nativeView = (CView) view1; } } try { moduleContent1.getViewContainer().deleteView(nativeView); fail(); } catch (final IllegalStateException e) { } try { moduleContent1.close(); moduleContent1.getViewContainer().deleteView(view); fail(); } catch (final IllegalStateException e) { } } @Test public void testGetFunction1() throws LoadCancelledException, CouldntLoadDataException { final CModule module = (CModule) getDatabase().getContent().getModules().get(0); module.load(); final CModuleContent moduleContent = module.getContent(); try { moduleContent.getFunctionContainer().getFunction((IAddress) null); fail(); } catch (final NullPointerException e) { } moduleContent.getFunctionContainer().getFunction(new CAddress(0x12345)); module.close(); try { moduleContent.getFunctionContainer().getFunction(new CAddress(0x12345)); fail(); } catch (final IllegalStateException e) { } } @Test public void testGetFunction2() throws LoadCancelledException, CouldntLoadDataException { final CModule module = (CModule) getDatabase().getContent().getModules().get(0); module.load(); final CModuleContent moduleContent = module.getContent(); try { moduleContent.getViewContainer().getFunction((INaviView) null); fail(); } catch (final NullPointerException e) { } moduleContent.getViewContainer() .getFunction(module.getContent().getViewContainer().getViews().get(0)); module.close(); try { moduleContent.getViewContainer() .getFunction(module.getContent().getViewContainer().getViews().get(0)); fail(); } catch (final IllegalStateException e) { } } @Test public void testGetFunction3() throws LoadCancelledException, CouldntLoadDataException, MaybeNullException { final CModule module = (CModule) getDatabase().getContent().getModules().get(0); module.load(); final CModuleContent moduleContent = module.getContent(); try { moduleContent.getFunctionContainer().getFunction((String) null); fail(); } catch (final NullPointerException e) { } moduleContent.getFunctionContainer() .getFunction(module.getContent().getFunctionContainer().getFunctions().get(0).getName()); module.close(); try { moduleContent.getFunctionContainer() .getFunction(module.getContent().getFunctionContainer().getFunctions().get(0).getName()); fail(); } catch (final IllegalStateException e) { } } @Test public void testGetFunctions() throws LoadCancelledException, CouldntLoadDataException { final CModule module = (CModule) getDatabase().getContent().getModules().get(0); module.load(); final CModuleContent moduleContent = module.getContent(); moduleContent.getFunctionContainer().getFunctionCount(); assertNotNull(moduleContent.getFunctionContainer().getFunctions()); module.close(); try { moduleContent.getFunctionContainer().getFunctions(); fail(); } catch (final IllegalStateException e) { } final CModule module1 = (CModule) getDatabase().getContent().getModules().get(0); module1.load(); @SuppressWarnings("unused") final CModuleContent moduleContent1 = module.getContent(); } @Test public void testGetNativeCallGraph() throws LoadCancelledException, CouldntLoadDataException { final CModule module2 = (CModule) getDatabase().getContent().getModules().get(0); module2.load(); final CModuleContent moduleContent2 = module2.getContent(); assertNotNull(moduleContent2.getNativeCallgraph()); module2.close(); try { moduleContent2.getViewContainer().getNativeCallgraphView(); fail(); } catch (final IllegalStateException e) { } } @Test public void testGetNativeCallgraphView() throws LoadCancelledException, CouldntLoadDataException { final CModule module3 = (CModule) getDatabase().getContent().getModules().get(0); module3.load(); final CModuleContent moduleContent3 = module3.getContent(); assertNotNull(moduleContent3.getViewContainer().getNativeCallgraphView()); module3.close(); try { moduleContent3.getViewContainer().getNativeFlowgraphViews(); fail(); } catch (final IllegalStateException e) { } } @Test public void testGetNativeFlowgraphViews() throws LoadCancelledException, CouldntLoadDataException { final CModule module4 = (CModule) getDatabase().getContent().getModules().get(0); module4.load(); final CModuleContent moduleContent4 = module4.getContent(); assertNotNull(moduleContent4.getViewContainer().getNativeFlowgraphViews().get(0)); module4.close(); try { CViewFilter.getTaggedViews(moduleContent4.getViewContainer().getViews()); fail(); } catch (final IllegalStateException e) { } } @Test public void testGetTaggedViews1() throws LoadCancelledException, CouldntLoadDataException { final CModule module5 = (CModule) getDatabase().getContent().getModules().get(0); module5.load(); final CModuleContent moduleContent5 = module5.getContent(); CViewFilter.getTaggedViews(moduleContent5.getViewContainer().getViews()); try { CViewFilter.getTaggedViews(moduleContent5.getViewContainer().getViews(), null); } catch (final IllegalArgumentException e) { } try { CViewFilter.getTaggedViews(moduleContent5.getViewContainer().getViews(), new CTag(0, "foo", "bar", TagType.NODE_TAG, new MockSqlProvider())); } catch (final IllegalArgumentException e) { } module5.close(); } @Test public void testGetTraceCount() throws LoadCancelledException, CouldntLoadDataException { final CModule module6 = (CModule) getDatabase().getContent().getModules().get(0); module6.load(); final CModuleContent moduleContent6 = module6.getContent(); moduleContent6.getTraceContainer().getTraceCount(); module6.close(); try { moduleContent6.getTraceContainer().getTraceCount(); fail(); } catch (final IllegalStateException e) { } } @Test public void testGetTraces() throws LoadCancelledException, CouldntLoadDataException { final CModule module6 = (CModule) getDatabase().getContent().getModules().get(0); module6.load(); final CModuleContent moduleContent6 = module6.getContent(); assertNotNull(moduleContent6.getTraceContainer().getTraces()); module6.close(); try { moduleContent6.getTraceContainer().getTraces(); fail(); } catch (final IllegalStateException e) { } } @Test public void testGetUserCallGrapViews() throws LoadCancelledException, CouldntLoadDataException { final CModule module6 = (CModule) getDatabase().getContent().getModules().get(0); module6.load(); final CModuleContent moduleContent6 = module6.getContent(); assertNotNull(CViewFilter.getCallgraphViews(moduleContent6.getViewContainer().getUserViews())); module6.close(); try { CViewFilter.getCallgraphViews(moduleContent6.getViewContainer().getUserViews()); } catch (final IllegalStateException e) { } } @Test public void testGetUserFlowGrapViews() throws LoadCancelledException, CouldntLoadDataException { final CModule module6 = (CModule) getDatabase().getContent().getModules().get(0); module6.load(); final CModuleContent moduleContent6 = module6.getContent(); assertNotNull( CViewFilter.getFlowgraphViewCount(moduleContent6.getViewContainer().getUserViews())); module6.close(); try { CViewFilter.getFlowgraphViewCount(moduleContent6.getViewContainer().getUserViews()); } catch (final IllegalStateException e) { } } @Test public void testGetUserMixedgraphViews() throws LoadCancelledException, CouldntLoadDataException { final CModule module6 = (CModule) getDatabase().getContent().getModules().get(0); module6.load(); final CModuleContent moduleContent6 = module6.getContent(); assertNotNull( CViewFilter.getMixedgraphViewCount(moduleContent6.getViewContainer().getUserViews())); module6.close(); try { CViewFilter.getMixedgraphViewCount(moduleContent6.getViewContainer().getUserViews()); } catch (final IllegalStateException e) { } } @Test public void testGetUserViews() throws LoadCancelledException, CouldntLoadDataException { final CModule module6 = (CModule) getDatabase().getContent().getModules().get(0); module6.load(); final CModuleContent moduleContent6 = module6.getContent(); assertNotNull(moduleContent6.getViewContainer().getUserViews()); module6.close(); try { moduleContent6.getViewContainer().getUserViews(); } catch (final IllegalStateException e) { } } @Test public void testGetView() throws LoadCancelledException, CouldntLoadDataException { final CModule module6 = (CModule) getDatabase().getContent().getModules().get(0); try { module6.load(); } catch (final CouldntLoadDataException e1) { try { module6.initialize(); } catch (final CouldntSaveDataException e) { } } finally { module6.load(); } final CModuleContent moduleContent6 = module6.getContent(); assertNotNull(moduleContent6.getViewContainer() .getView(module6.getContent().getFunctionContainer().getFunctions().get(0))); try { moduleContent6.getViewContainer().getView((INaviFunction) null); fail(); } catch (final NullPointerException e) { } module6.close(); try { moduleContent6.getViewContainer() .getView(module6.getContent().getFunctionContainer().getFunctions().get(0)); fail(); } catch (final IllegalStateException e) { } } @Test public void testGetViews() throws LoadCancelledException, CouldntLoadDataException { final CModule module6 = (CModule) getDatabase().getContent().getModules().get(0); module6.load(); final CModuleContent moduleContent6 = module6.getContent(); assertNotNull(moduleContent6.getViewContainer().getViews()); module6.close(); try { moduleContent6.getViewContainer().getViews(); } catch (final IllegalStateException e) { } } @Test public void testHasView() throws LoadCancelledException, CouldntLoadDataException { final CModule module6 = (CModule) getDatabase().getContent().getModules().get(0); module6.load(); final CModuleContent moduleContent6 = module6.getContent(); assertTrue(moduleContent6.getViewContainer() .hasView(module6.getContent().getViewContainer().getViews().get(0))); try { moduleContent6.getViewContainer().hasView(null); fail(); } catch (final NullPointerException e) { } try { moduleContent6.getViewContainer().hasView(new MockView()); fail(); } catch (final IllegalArgumentException e) { } module6.close(); try { moduleContent6.getViewContainer().getViews(); fail(); } catch (final IllegalStateException e) { } } }
/* * Copyright 2012 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.service; import static org.eclipse.jgit.treewalk.filter.TreeFilter.ANY_DIFF; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.DateTools; import org.apache.lucene.document.DateTools.Resolution; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.MultiReader; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.search.highlight.Fragmenter; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.InvalidTokenOffsetsException; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.search.highlight.SimpleSpanFragmenter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import org.eclipse.jgit.diff.DiffEntry.ChangeType; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryCache.FileKey; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.treewalk.EmptyTreeIterator; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.util.FS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.gitblit.Constants.SearchObjectType; import com.gitblit.IStoredSettings; import com.gitblit.Keys; import com.gitblit.manager.IRepositoryManager; import com.gitblit.models.PathModel.PathChangeModel; import com.gitblit.models.RefModel; import com.gitblit.models.RepositoryModel; import com.gitblit.models.SearchResult; import com.gitblit.utils.ArrayUtils; import com.gitblit.utils.JGitUtils; import com.gitblit.utils.StringUtils; /** * The Lucene service handles indexing and searching repositories. * * @author James Moger * */ public class LuceneService implements Runnable { private static final int INDEX_VERSION = 5; private static final String FIELD_OBJECT_TYPE = "type"; private static final String FIELD_PATH = "path"; private static final String FIELD_COMMIT = "commit"; private static final String FIELD_BRANCH = "branch"; private static final String FIELD_SUMMARY = "summary"; private static final String FIELD_CONTENT = "content"; private static final String FIELD_AUTHOR = "author"; private static final String FIELD_COMMITTER = "committer"; private static final String FIELD_DATE = "date"; private static final String FIELD_TAG = "tag"; private static final String CONF_FILE = "lucene.conf"; private static final String LUCENE_DIR = "lucene"; private static final String CONF_INDEX = "index"; private static final String CONF_VERSION = "version"; private static final String CONF_ALIAS = "aliases"; private static final String CONF_BRANCH = "branches"; private static final Version LUCENE_VERSION = Version.LUCENE_46; private final Logger logger = LoggerFactory.getLogger(LuceneService.class); private final IStoredSettings storedSettings; private final IRepositoryManager repositoryManager; private final File repositoriesFolder; private final Map<String, IndexSearcher> searchers = new ConcurrentHashMap<String, IndexSearcher>(); private final Map<String, IndexWriter> writers = new ConcurrentHashMap<String, IndexWriter>(); private final String luceneIgnoreExtensions = "7z arc arj bin bmp dll doc docx exe gif gz jar jpg lib lzh odg odf odt pdf ppt png so swf xcf xls xlsx zip"; private Set<String> excludedExtensions; public LuceneService( IStoredSettings settings, IRepositoryManager repositoryManager) { this.storedSettings = settings; this.repositoryManager = repositoryManager; this.repositoriesFolder = repositoryManager.getRepositoriesFolder(); String exts = luceneIgnoreExtensions; if (settings != null) { exts = settings.getString(Keys.web.luceneIgnoreExtensions, exts); } excludedExtensions = new TreeSet<String>(StringUtils.getStringsFromValue(exts)); } /** * Run is executed by the Gitblit executor service. Because this is called * by an executor service, calls will queue - i.e. there can never be * concurrent execution of repository index updates. */ @Override public void run() { if (!storedSettings.getBoolean(Keys.web.allowLuceneIndexing, true)) { // Lucene indexing is disabled return; } // reload the excluded extensions String exts = storedSettings.getString(Keys.web.luceneIgnoreExtensions, luceneIgnoreExtensions); excludedExtensions = new TreeSet<String>(StringUtils.getStringsFromValue(exts)); if (repositoryManager.isCollectingGarbage()) { // busy collecting garbage, try again later return; } for (String repositoryName: repositoryManager.getRepositoryList()) { RepositoryModel model = repositoryManager.getRepositoryModel(repositoryName); if (model.hasCommits && !ArrayUtils.isEmpty(model.indexedBranches)) { Repository repository = repositoryManager.getRepository(model.name); if (repository == null) { if (repositoryManager.isCollectingGarbage(model.name)) { logger.info(MessageFormat.format("Skipping Lucene index of {0}, busy garbage collecting", repositoryName)); } continue; } index(model, repository); repository.close(); System.gc(); } } } /** * Synchronously indexes a repository. This may build a complete index of a * repository or it may update an existing index. * * @param displayName * the name of the repository * @param repository * the repository object */ private void index(RepositoryModel model, Repository repository) { try { if (shouldReindex(repository)) { // (re)build the entire index IndexResult result = reindex(model, repository); if (result.success) { if (result.commitCount > 0) { String msg = "Built {0} Lucene index from {1} commits and {2} files across {3} branches in {4} secs"; logger.info(MessageFormat.format(msg, model.name, result.commitCount, result.blobCount, result.branchCount, result.duration())); } } else { String msg = "Could not build {0} Lucene index!"; logger.error(MessageFormat.format(msg, model.name)); } } else { // update the index with latest commits IndexResult result = updateIndex(model, repository); if (result.success) { if (result.commitCount > 0) { String msg = "Updated {0} Lucene index with {1} commits and {2} files across {3} branches in {4} secs"; logger.info(MessageFormat.format(msg, model.name, result.commitCount, result.blobCount, result.branchCount, result.duration())); } } else { String msg = "Could not update {0} Lucene index!"; logger.error(MessageFormat.format(msg, model.name)); } } } catch (Throwable t) { logger.error(MessageFormat.format("Lucene indexing failure for {0}", model.name), t); } } /** * Close the writer/searcher objects for a repository. * * @param repositoryName */ public synchronized void close(String repositoryName) { try { IndexSearcher searcher = searchers.remove(repositoryName); if (searcher != null) { searcher.getIndexReader().close(); } } catch (Exception e) { logger.error("Failed to close index searcher for " + repositoryName, e); } try { IndexWriter writer = writers.remove(repositoryName); if (writer != null) { writer.close(); } } catch (Exception e) { logger.error("Failed to close index writer for " + repositoryName, e); } } /** * Close all Lucene indexers. * */ public synchronized void close() { // close all writers for (String writer : writers.keySet()) { try { writers.get(writer).close(true); } catch (Throwable t) { logger.error("Failed to close Lucene writer for " + writer, t); } } writers.clear(); // close all searchers for (String searcher : searchers.keySet()) { try { searchers.get(searcher).getIndexReader().close(); } catch (Throwable t) { logger.error("Failed to close Lucene searcher for " + searcher, t); } } searchers.clear(); } /** * Deletes the Lucene index for the specified repository. * * @param repositoryName * @return true, if successful */ public boolean deleteIndex(String repositoryName) { try { // close any open writer/searcher close(repositoryName); // delete the index folder File repositoryFolder = FileKey.resolve(new File(repositoriesFolder, repositoryName), FS.DETECTED); File luceneIndex = new File(repositoryFolder, LUCENE_DIR); if (luceneIndex.exists()) { org.eclipse.jgit.util.FileUtils.delete(luceneIndex, org.eclipse.jgit.util.FileUtils.RECURSIVE); } // delete the config file File luceneConfig = new File(repositoryFolder, CONF_FILE); if (luceneConfig.exists()) { luceneConfig.delete(); } return true; } catch (IOException e) { throw new RuntimeException(e); } } /** * Returns the author for the commit, if this information is available. * * @param commit * @return an author or unknown */ private String getAuthor(RevCommit commit) { String name = "unknown"; try { name = commit.getAuthorIdent().getName(); if (StringUtils.isEmpty(name)) { name = commit.getAuthorIdent().getEmailAddress(); } } catch (NullPointerException n) { } return name; } /** * Returns the committer for the commit, if this information is available. * * @param commit * @return an committer or unknown */ private String getCommitter(RevCommit commit) { String name = "unknown"; try { name = commit.getCommitterIdent().getName(); if (StringUtils.isEmpty(name)) { name = commit.getCommitterIdent().getEmailAddress(); } } catch (NullPointerException n) { } return name; } /** * Get the tree associated with the given commit. * * @param walk * @param commit * @return tree * @throws IOException */ private RevTree getTree(final RevWalk walk, final RevCommit commit) throws IOException { final RevTree tree = commit.getTree(); if (tree != null) { return tree; } walk.parseHeaders(commit); return commit.getTree(); } /** * Construct a keyname from the branch. * * @param branchName * @return a keyname appropriate for the Git config file format */ private String getBranchKey(String branchName) { return StringUtils.getSHA1(branchName); } /** * Returns the Lucene configuration for the specified repository. * * @param repository * @return a config object */ private FileBasedConfig getConfig(Repository repository) { File file = new File(repository.getDirectory(), CONF_FILE); FileBasedConfig config = new FileBasedConfig(file, FS.detect()); return config; } /** * Reads the Lucene config file for the repository to check the index * version. If the index version is different, then rebuild the repository * index. * * @param repository * @return true of the on-disk index format is different than INDEX_VERSION */ private boolean shouldReindex(Repository repository) { try { FileBasedConfig config = getConfig(repository); config.load(); int indexVersion = config.getInt(CONF_INDEX, CONF_VERSION, 0); // reindex if versions do not match return indexVersion != INDEX_VERSION; } catch (Throwable t) { } return true; } /** * This completely indexes the repository and will destroy any existing * index. * * @param repositoryName * @param repository * @return IndexResult */ public IndexResult reindex(RepositoryModel model, Repository repository) { IndexResult result = new IndexResult(); if (!deleteIndex(model.name)) { return result; } try { String [] encodings = storedSettings.getStrings(Keys.web.blobEncodings).toArray(new String[0]); FileBasedConfig config = getConfig(repository); Set<String> indexedCommits = new TreeSet<String>(); IndexWriter writer = getIndexWriter(model.name); // build a quick lookup of tags Map<String, List<String>> tags = new HashMap<String, List<String>>(); for (RefModel tag : JGitUtils.getTags(repository, false, -1)) { if (!tag.isAnnotatedTag()) { // skip non-annotated tags continue; } if (!tags.containsKey(tag.getObjectId().getName())) { tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>()); } tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName); } ObjectReader reader = repository.newObjectReader(); // get the local branches List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1); // sort them by most recently updated Collections.sort(branches, new Comparator<RefModel>() { @Override public int compare(RefModel ref1, RefModel ref2) { return ref2.getDate().compareTo(ref1.getDate()); } }); // reorder default branch to first position RefModel defaultBranch = null; ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository); for (RefModel branch : branches) { if (branch.getObjectId().equals(defaultBranchId)) { defaultBranch = branch; break; } } branches.remove(defaultBranch); branches.add(0, defaultBranch); // walk through each branch for (RefModel branch : branches) { boolean indexBranch = false; if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH) && branch.equals(defaultBranch)) { // indexing "default" branch indexBranch = true; } else if (branch.getName().startsWith(com.gitblit.Constants.R_META)) { // skip internal meta branches indexBranch = false; } else { // normal explicit branch check indexBranch = model.indexedBranches.contains(branch.getName()); } // if this branch is not specifically indexed then skip if (!indexBranch) { continue; } String branchName = branch.getName(); RevWalk revWalk = new RevWalk(reader); RevCommit tip = revWalk.parseCommit(branch.getObjectId()); String tipId = tip.getId().getName(); String keyName = getBranchKey(branchName); config.setString(CONF_ALIAS, null, keyName, branchName); config.setString(CONF_BRANCH, null, keyName, tipId); // index the blob contents of the tree TreeWalk treeWalk = new TreeWalk(repository); treeWalk.addTree(tip.getTree()); treeWalk.setRecursive(true); Map<String, ObjectId> paths = new TreeMap<String, ObjectId>(); while (treeWalk.next()) { // ensure path is not in a submodule if (treeWalk.getFileMode(0) != FileMode.GITLINK) { paths.put(treeWalk.getPathString(), treeWalk.getObjectId(0)); } } ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] tmp = new byte[32767]; RevWalk commitWalk = new RevWalk(reader); commitWalk.markStart(tip); RevCommit commit; while ((paths.size() > 0) && (commit = commitWalk.next()) != null) { TreeWalk diffWalk = new TreeWalk(reader); int parentCount = commit.getParentCount(); switch (parentCount) { case 0: diffWalk.addTree(new EmptyTreeIterator()); break; case 1: diffWalk.addTree(getTree(commitWalk, commit.getParent(0))); break; default: // skip merge commits continue; } diffWalk.addTree(getTree(commitWalk, commit)); diffWalk.setFilter(ANY_DIFF); diffWalk.setRecursive(true); while ((paths.size() > 0) && diffWalk.next()) { String path = diffWalk.getPathString(); if (!paths.containsKey(path)) { continue; } // remove path from set ObjectId blobId = paths.remove(path); result.blobCount++; // index the blob metadata String blobAuthor = getAuthor(commit); String blobCommitter = getCommitter(commit); String blobDate = DateTools.timeToString(commit.getCommitTime() * 1000L, Resolution.MINUTE); Document doc = new Document(); doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.blob.name(), StringField.TYPE_STORED)); doc.add(new Field(FIELD_BRANCH, branchName, TextField.TYPE_STORED)); doc.add(new Field(FIELD_COMMIT, commit.getName(), TextField.TYPE_STORED)); doc.add(new Field(FIELD_PATH, path, TextField.TYPE_STORED)); doc.add(new Field(FIELD_DATE, blobDate, StringField.TYPE_STORED)); doc.add(new Field(FIELD_AUTHOR, blobAuthor, TextField.TYPE_STORED)); doc.add(new Field(FIELD_COMMITTER, blobCommitter, TextField.TYPE_STORED)); // determine extension to compare to the extension // blacklist String ext = null; String name = path.toLowerCase(); if (name.indexOf('.') > -1) { ext = name.substring(name.lastIndexOf('.') + 1); } // index the blob content if (StringUtils.isEmpty(ext) || !excludedExtensions.contains(ext)) { ObjectLoader ldr = repository.open(blobId, Constants.OBJ_BLOB); InputStream in = ldr.openStream(); int n; while ((n = in.read(tmp)) > 0) { os.write(tmp, 0, n); } in.close(); byte[] content = os.toByteArray(); String str = StringUtils.decodeString(content, encodings); doc.add(new Field(FIELD_CONTENT, str, TextField.TYPE_STORED)); os.reset(); } // add the blob to the index writer.addDocument(doc); } } os.close(); // index the tip commit object if (indexedCommits.add(tipId)) { Document doc = createDocument(tip, tags.get(tipId)); doc.add(new Field(FIELD_BRANCH, branchName, TextField.TYPE_STORED)); writer.addDocument(doc); result.commitCount += 1; result.branchCount += 1; } // traverse the log and index the previous commit objects RevWalk historyWalk = new RevWalk(reader); historyWalk.markStart(historyWalk.parseCommit(tip.getId())); RevCommit rev; while ((rev = historyWalk.next()) != null) { String hash = rev.getId().getName(); if (indexedCommits.add(hash)) { Document doc = createDocument(rev, tags.get(hash)); doc.add(new Field(FIELD_BRANCH, branchName, TextField.TYPE_STORED)); writer.addDocument(doc); result.commitCount += 1; } } } // finished reader.release(); // commit all changes and reset the searcher config.setInt(CONF_INDEX, null, CONF_VERSION, INDEX_VERSION); config.save(); writer.commit(); resetIndexSearcher(model.name); result.success(); } catch (Exception e) { logger.error("Exception while reindexing " + model.name, e); } return result; } /** * Incrementally update the index with the specified commit for the * repository. * * @param repositoryName * @param repository * @param branch * the fully qualified branch name (e.g. refs/heads/master) * @param commit * @return true, if successful */ private IndexResult index(String repositoryName, Repository repository, String branch, RevCommit commit) { IndexResult result = new IndexResult(); try { String [] encodings = storedSettings.getStrings(Keys.web.blobEncodings).toArray(new String[0]); List<PathChangeModel> changedPaths = JGitUtils.getFilesInCommit(repository, commit); String revDate = DateTools.timeToString(commit.getCommitTime() * 1000L, Resolution.MINUTE); IndexWriter writer = getIndexWriter(repositoryName); for (PathChangeModel path : changedPaths) { if (path.isSubmodule()) { continue; } // delete the indexed blob deleteBlob(repositoryName, branch, path.name); // re-index the blob if (!ChangeType.DELETE.equals(path.changeType)) { result.blobCount++; Document doc = new Document(); doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.blob.name(), StringField.TYPE_STORED)); doc.add(new Field(FIELD_BRANCH, branch, TextField.TYPE_STORED)); doc.add(new Field(FIELD_COMMIT, commit.getName(), TextField.TYPE_STORED)); doc.add(new Field(FIELD_PATH, path.path, TextField.TYPE_STORED)); doc.add(new Field(FIELD_DATE, revDate, StringField.TYPE_STORED)); doc.add(new Field(FIELD_AUTHOR, getAuthor(commit), TextField.TYPE_STORED)); doc.add(new Field(FIELD_COMMITTER, getCommitter(commit), TextField.TYPE_STORED)); // determine extension to compare to the extension // blacklist String ext = null; String name = path.name.toLowerCase(); if (name.indexOf('.') > -1) { ext = name.substring(name.lastIndexOf('.') + 1); } if (StringUtils.isEmpty(ext) || !excludedExtensions.contains(ext)) { // read the blob content String str = JGitUtils.getStringContent(repository, commit.getTree(), path.path, encodings); if (str != null) { doc.add(new Field(FIELD_CONTENT, str, TextField.TYPE_STORED)); writer.addDocument(doc); } } } } writer.commit(); // get any annotated commit tags List<String> commitTags = new ArrayList<String>(); for (RefModel ref : JGitUtils.getTags(repository, false, -1)) { if (ref.isAnnotatedTag() && ref.getReferencedObjectId().equals(commit.getId())) { commitTags.add(ref.displayName); } } // create and write the Lucene document Document doc = createDocument(commit, commitTags); doc.add(new Field(FIELD_BRANCH, branch, TextField.TYPE_STORED)); result.commitCount++; result.success = index(repositoryName, doc); } catch (Exception e) { logger.error(MessageFormat.format("Exception while indexing commit {0} in {1}", commit.getId().getName(), repositoryName), e); } return result; } /** * Delete a blob from the specified branch of the repository index. * * @param repositoryName * @param branch * @param path * @throws Exception * @return true, if deleted, false if no record was deleted */ public boolean deleteBlob(String repositoryName, String branch, String path) throws Exception { String pattern = MessageFormat.format("{0}:'{'0} AND {1}:\"'{'1'}'\" AND {2}:\"'{'2'}'\"", FIELD_OBJECT_TYPE, FIELD_BRANCH, FIELD_PATH); String q = MessageFormat.format(pattern, SearchObjectType.blob.name(), branch, path); BooleanQuery query = new BooleanQuery(); StandardAnalyzer analyzer = new StandardAnalyzer(LUCENE_VERSION); QueryParser qp = new QueryParser(LUCENE_VERSION, FIELD_SUMMARY, analyzer); query.add(qp.parse(q), Occur.MUST); IndexWriter writer = getIndexWriter(repositoryName); int numDocsBefore = writer.numDocs(); writer.deleteDocuments(query); writer.commit(); int numDocsAfter = writer.numDocs(); if (numDocsBefore == numDocsAfter) { logger.debug(MessageFormat.format("no records found to delete {0}", query.toString())); return false; } else { logger.debug(MessageFormat.format("deleted {0} records with {1}", numDocsBefore - numDocsAfter, query.toString())); return true; } } /** * Updates a repository index incrementally from the last indexed commits. * * @param model * @param repository * @return IndexResult */ private IndexResult updateIndex(RepositoryModel model, Repository repository) { IndexResult result = new IndexResult(); try { FileBasedConfig config = getConfig(repository); config.load(); // build a quick lookup of annotated tags Map<String, List<String>> tags = new HashMap<String, List<String>>(); for (RefModel tag : JGitUtils.getTags(repository, false, -1)) { if (!tag.isAnnotatedTag()) { // skip non-annotated tags continue; } if (!tags.containsKey(tag.getObjectId().getName())) { tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>()); } tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName); } // detect branch deletion // first assume all branches are deleted and then remove each // existing branch from deletedBranches during indexing Set<String> deletedBranches = new TreeSet<String>(); for (String alias : config.getNames(CONF_ALIAS)) { String branch = config.getString(CONF_ALIAS, null, alias); deletedBranches.add(branch); } // get the local branches List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1); // sort them by most recently updated Collections.sort(branches, new Comparator<RefModel>() { @Override public int compare(RefModel ref1, RefModel ref2) { return ref2.getDate().compareTo(ref1.getDate()); } }); // reorder default branch to first position RefModel defaultBranch = null; ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository); for (RefModel branch : branches) { if (branch.getObjectId().equals(defaultBranchId)) { defaultBranch = branch; break; } } branches.remove(defaultBranch); branches.add(0, defaultBranch); // walk through each branches for (RefModel branch : branches) { String branchName = branch.getName(); boolean indexBranch = false; if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH) && branch.equals(defaultBranch)) { // indexing "default" branch indexBranch = true; } else if (branch.getName().startsWith(com.gitblit.Constants.R_META)) { // ignore internal meta branches indexBranch = false; } else { // normal explicit branch check indexBranch = model.indexedBranches.contains(branch.getName()); } // if this branch is not specifically indexed then skip if (!indexBranch) { continue; } // remove this branch from the deletedBranches set deletedBranches.remove(branchName); // determine last commit String keyName = getBranchKey(branchName); String lastCommit = config.getString(CONF_BRANCH, null, keyName); List<RevCommit> revs; if (StringUtils.isEmpty(lastCommit)) { // new branch/unindexed branch, get all commits on branch revs = JGitUtils.getRevLog(repository, branchName, 0, -1); } else { // pre-existing branch, get changes since last commit revs = JGitUtils.getRevLog(repository, lastCommit, branchName); } if (revs.size() > 0) { result.branchCount += 1; } // reverse the list of commits so we start with the first commit Collections.reverse(revs); for (RevCommit commit : revs) { // index a commit result.add(index(model.name, repository, branchName, commit)); } // update the config config.setInt(CONF_INDEX, null, CONF_VERSION, INDEX_VERSION); config.setString(CONF_ALIAS, null, keyName, branchName); config.setString(CONF_BRANCH, null, keyName, branch.getObjectId().getName()); config.save(); } // the deletedBranches set will normally be empty by this point // unless a branch really was deleted and no longer exists if (deletedBranches.size() > 0) { for (String branch : deletedBranches) { IndexWriter writer = getIndexWriter(model.name); writer.deleteDocuments(new Term(FIELD_BRANCH, branch)); writer.commit(); } } result.success = true; } catch (Throwable t) { logger.error(MessageFormat.format("Exception while updating {0} Lucene index", model.name), t); } return result; } /** * Creates a Lucene document for a commit * * @param commit * @param tags * @return a Lucene document */ private Document createDocument(RevCommit commit, List<String> tags) { Document doc = new Document(); doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.commit.name(), StringField.TYPE_STORED)); doc.add(new Field(FIELD_COMMIT, commit.getName(), TextField.TYPE_STORED)); doc.add(new Field(FIELD_DATE, DateTools.timeToString(commit.getCommitTime() * 1000L, Resolution.MINUTE), StringField.TYPE_STORED)); doc.add(new Field(FIELD_AUTHOR, getAuthor(commit), TextField.TYPE_STORED)); doc.add(new Field(FIELD_COMMITTER, getCommitter(commit), TextField.TYPE_STORED)); doc.add(new Field(FIELD_SUMMARY, commit.getShortMessage(), TextField.TYPE_STORED)); doc.add(new Field(FIELD_CONTENT, commit.getFullMessage(), TextField.TYPE_STORED)); if (!ArrayUtils.isEmpty(tags)) { doc.add(new Field(FIELD_TAG, StringUtils.flattenStrings(tags), TextField.TYPE_STORED)); } return doc; } /** * Incrementally index an object for the repository. * * @param repositoryName * @param doc * @return true, if successful */ private boolean index(String repositoryName, Document doc) { try { IndexWriter writer = getIndexWriter(repositoryName); writer.addDocument(doc); writer.commit(); resetIndexSearcher(repositoryName); return true; } catch (Exception e) { logger.error(MessageFormat.format("Exception while incrementally updating {0} Lucene index", repositoryName), e); } return false; } private SearchResult createSearchResult(Document doc, float score, int hitId, int totalHits) throws ParseException { SearchResult result = new SearchResult(); result.hitId = hitId; result.totalHits = totalHits; result.score = score; result.date = DateTools.stringToDate(doc.get(FIELD_DATE)); result.summary = doc.get(FIELD_SUMMARY); result.author = doc.get(FIELD_AUTHOR); result.committer = doc.get(FIELD_COMMITTER); result.type = SearchObjectType.fromName(doc.get(FIELD_OBJECT_TYPE)); result.branch = doc.get(FIELD_BRANCH); result.commitId = doc.get(FIELD_COMMIT); result.path = doc.get(FIELD_PATH); if (doc.get(FIELD_TAG) != null) { result.tags = StringUtils.getStringsFromValue(doc.get(FIELD_TAG)); } return result; } private synchronized void resetIndexSearcher(String repository) throws IOException { IndexSearcher searcher = searchers.remove(repository); if (searcher != null) { searcher.getIndexReader().close(); } } /** * Gets an index searcher for the repository. * * @param repository * @return * @throws IOException */ private IndexSearcher getIndexSearcher(String repository) throws IOException { IndexSearcher searcher = searchers.get(repository); if (searcher == null) { IndexWriter writer = getIndexWriter(repository); searcher = new IndexSearcher(DirectoryReader.open(writer, true)); searchers.put(repository, searcher); } return searcher; } /** * Gets an index writer for the repository. The index will be created if it * does not already exist or if forceCreate is specified. * * @param repository * @return an IndexWriter * @throws IOException */ private IndexWriter getIndexWriter(String repository) throws IOException { IndexWriter indexWriter = writers.get(repository); File repositoryFolder = FileKey.resolve(new File(repositoriesFolder, repository), FS.DETECTED); File indexFolder = new File(repositoryFolder, LUCENE_DIR); Directory directory = FSDirectory.open(indexFolder); if (indexWriter == null) { if (!indexFolder.exists()) { indexFolder.mkdirs(); } StandardAnalyzer analyzer = new StandardAnalyzer(LUCENE_VERSION); IndexWriterConfig config = new IndexWriterConfig(LUCENE_VERSION, analyzer); config.setOpenMode(OpenMode.CREATE_OR_APPEND); indexWriter = new IndexWriter(directory, config); writers.put(repository, indexWriter); } return indexWriter; } /** * Searches the specified repositories for the given text or query * * @param text * if the text is null or empty, null is returned * @param page * the page number to retrieve. page is 1-indexed. * @param pageSize * the number of elements to return for this page * @param repositories * a list of repositories to search. if no repositories are * specified null is returned. * @return a list of SearchResults in order from highest to the lowest score * */ public List<SearchResult> search(String text, int page, int pageSize, List<String> repositories) { if (ArrayUtils.isEmpty(repositories)) { return null; } return search(text, page, pageSize, repositories.toArray(new String[0])); } /** * Searches the specified repositories for the given text or query * * @param text * if the text is null or empty, null is returned * @param page * the page number to retrieve. page is 1-indexed. * @param pageSize * the number of elements to return for this page * @param repositories * a list of repositories to search. if no repositories are * specified null is returned. * @return a list of SearchResults in order from highest to the lowest score * */ public List<SearchResult> search(String text, int page, int pageSize, String... repositories) { if (StringUtils.isEmpty(text)) { return null; } if (ArrayUtils.isEmpty(repositories)) { return null; } Set<SearchResult> results = new LinkedHashSet<SearchResult>(); StandardAnalyzer analyzer = new StandardAnalyzer(LUCENE_VERSION); try { // default search checks summary and content BooleanQuery query = new BooleanQuery(); QueryParser qp; qp = new QueryParser(LUCENE_VERSION, FIELD_SUMMARY, analyzer); qp.setAllowLeadingWildcard(true); query.add(qp.parse(text), Occur.SHOULD); qp = new QueryParser(LUCENE_VERSION, FIELD_CONTENT, analyzer); qp.setAllowLeadingWildcard(true); query.add(qp.parse(text), Occur.SHOULD); IndexSearcher searcher; if (repositories.length == 1) { // single repository search searcher = getIndexSearcher(repositories[0]); } else { // multiple repository search List<IndexReader> readers = new ArrayList<IndexReader>(); for (String repository : repositories) { IndexSearcher repositoryIndex = getIndexSearcher(repository); readers.add(repositoryIndex.getIndexReader()); } IndexReader[] rdrs = readers.toArray(new IndexReader[readers.size()]); MultiSourceReader reader = new MultiSourceReader(rdrs); searcher = new IndexSearcher(reader); } Query rewrittenQuery = searcher.rewrite(query); logger.debug(rewrittenQuery.toString()); TopScoreDocCollector collector = TopScoreDocCollector.create(5000, true); searcher.search(rewrittenQuery, collector); int offset = Math.max(0, (page - 1) * pageSize); ScoreDoc[] hits = collector.topDocs(offset, pageSize).scoreDocs; int totalHits = collector.getTotalHits(); for (int i = 0; i < hits.length; i++) { int docId = hits[i].doc; Document doc = searcher.doc(docId); SearchResult result = createSearchResult(doc, hits[i].score, offset + i + 1, totalHits); if (repositories.length == 1) { // single repository search result.repository = repositories[0]; } else { // multi-repository search MultiSourceReader reader = (MultiSourceReader) searcher.getIndexReader(); int index = reader.getSourceIndex(docId); result.repository = repositories[index]; } String content = doc.get(FIELD_CONTENT); result.fragment = getHighlightedFragment(analyzer, query, content, result); results.add(result); } } catch (Exception e) { logger.error(MessageFormat.format("Exception while searching for {0}", text), e); } return new ArrayList<SearchResult>(results); } /** * * @param analyzer * @param query * @param content * @param result * @return * @throws IOException * @throws InvalidTokenOffsetsException */ private String getHighlightedFragment(Analyzer analyzer, Query query, String content, SearchResult result) throws IOException, InvalidTokenOffsetsException { if (content == null) { content = ""; } int fragmentLength = SearchObjectType.commit == result.type ? 512 : 150; QueryScorer scorer = new QueryScorer(query, "content"); Fragmenter fragmenter = new SimpleSpanFragmenter(scorer, fragmentLength); // use an artificial delimiter for the token String termTag = "!!--["; String termTagEnd = "]--!!"; SimpleHTMLFormatter formatter = new SimpleHTMLFormatter(termTag, termTagEnd); Highlighter highlighter = new Highlighter(formatter, scorer); highlighter.setTextFragmenter(fragmenter); String [] fragments = highlighter.getBestFragments(analyzer, "content", content, 3); if (ArrayUtils.isEmpty(fragments)) { if (SearchObjectType.blob == result.type) { return ""; } // clip commit message String fragment = content; if (fragment.length() > fragmentLength) { fragment = fragment.substring(0, fragmentLength) + "..."; } return "<pre class=\"text\">" + StringUtils.escapeForHtml(fragment, true) + "</pre>"; } // make sure we have unique fragments Set<String> uniqueFragments = new LinkedHashSet<String>(); for (String fragment : fragments) { uniqueFragments.add(fragment); } fragments = uniqueFragments.toArray(new String[uniqueFragments.size()]); StringBuilder sb = new StringBuilder(); for (int i = 0, len = fragments.length; i < len; i++) { String fragment = fragments[i]; String tag = "<pre class=\"text\">"; // resurrect the raw fragment from removing the artificial delimiters String raw = fragment.replace(termTag, "").replace(termTagEnd, ""); // determine position of the raw fragment in the content int pos = content.indexOf(raw); // restore complete first line of fragment int c = pos; while (c > 0) { c--; if (content.charAt(c) == '\n') { break; } } if (c > 0) { // inject leading chunk of first fragment line fragment = content.substring(c + 1, pos) + fragment; } if (SearchObjectType.blob == result.type) { // count lines as offset into the content for this fragment int line = Math.max(1, StringUtils.countLines(content.substring(0, pos))); // create fragment tag with line number and language String lang = ""; String ext = StringUtils.getFileExtension(result.path).toLowerCase(); if (!StringUtils.isEmpty(ext)) { // maintain leading space! lang = " lang-" + ext; } tag = MessageFormat.format("<pre class=\"prettyprint linenums:{0,number,0}{1}\">", line, lang); } sb.append(tag); // replace the artificial delimiter with html tags String html = StringUtils.escapeForHtml(fragment, false); html = html.replace(termTag, "<span class=\"highlight\">").replace(termTagEnd, "</span>"); sb.append(html); sb.append("</pre>"); if (i < len - 1) { sb.append("<span class=\"ellipses\">...</span><br/>"); } } return sb.toString(); } /** * Simple class to track the results of an index update. */ private class IndexResult { long startTime = System.currentTimeMillis(); long endTime = startTime; boolean success; int branchCount; int commitCount; int blobCount; void add(IndexResult result) { this.branchCount += result.branchCount; this.commitCount += result.commitCount; this.blobCount += result.blobCount; } void success() { success = true; endTime = System.currentTimeMillis(); } float duration() { return (endTime - startTime)/1000f; } } /** * Custom subclass of MultiReader to identify the source index for a given * doc id. This would not be necessary of there was a public method to * obtain this information. * */ private class MultiSourceReader extends MultiReader { MultiSourceReader(IndexReader [] readers) { super(readers, false); } int getSourceIndex(int docId) { int index = -1; try { index = super.readerIndex(docId); } catch (Exception e) { logger.error("Error getting source index", e); } return index; } } }
// Copyright 2016 The Bazel Authors. 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.devtools.build.skyframe; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableMap; import com.google.devtools.build.lib.collect.nestedset.NestedSetVisitor; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.EventHandler; import com.google.devtools.build.lib.util.Preconditions; import com.google.devtools.build.skyframe.MemoizingEvaluator.EmittedEventState; import com.google.devtools.build.skyframe.QueryableGraph.Reason; import java.util.Map; import java.util.concurrent.ForkJoinPool; import javax.annotation.Nullable; /** * Context object holding sufficient information for {@link SkyFunctionEnvironment} to perform its * duties. Shared among all {@link SkyFunctionEnvironment} instances, which should regard this * object as a read-only collection of data. * * <p>Also used during cycle detection. */ class ParallelEvaluatorContext { enum EnqueueParentBehavior { ENQUEUE, SIGNAL, NO_ACTION } private final QueryableGraph graph; private final Version graphVersion; private final ImmutableMap<SkyFunctionName, ? extends SkyFunction> skyFunctions; private final EventHandler reporter; private final NestedSetVisitor<TaggedEvents> replayingNestedSetEventVisitor; private final boolean keepGoing; private final boolean storeErrorsAlongsideValues; private final DirtyTrackingProgressReceiver progressReceiver; private final EventFilter storedEventFilter; /** * The visitor managing the thread pool. Used to enqueue parents when an entry is finished, and, * during testing, to block until an exception is thrown if a node builder requests that. * Initialized after construction to avoid the overhead of the caller's creating a threadpool in * cases where it is not needed. */ private final Supplier<NodeEntryVisitor> visitorSupplier; ParallelEvaluatorContext( QueryableGraph graph, Version graphVersion, ImmutableMap<SkyFunctionName, ? extends SkyFunction> skyFunctions, EventHandler reporter, EmittedEventState emittedEventState, boolean keepGoing, boolean storeErrorsAlongsideValues, final DirtyTrackingProgressReceiver progressReceiver, EventFilter storedEventFilter, final Function<SkyKey, Runnable> runnableMaker, final int threadCount) { this.graph = graph; this.graphVersion = graphVersion; this.skyFunctions = skyFunctions; this.reporter = reporter; this.replayingNestedSetEventVisitor = new NestedSetVisitor<>(new NestedSetEventReceiver(reporter), emittedEventState); this.keepGoing = keepGoing; this.storeErrorsAlongsideValues = storeErrorsAlongsideValues; this.progressReceiver = Preconditions.checkNotNull(progressReceiver); this.storedEventFilter = storedEventFilter; visitorSupplier = Suppliers.memoize( new Supplier<NodeEntryVisitor>() { @Override public NodeEntryVisitor get() { return new NodeEntryVisitor( threadCount, progressReceiver, runnableMaker); } }); } ParallelEvaluatorContext( QueryableGraph graph, Version graphVersion, ImmutableMap<SkyFunctionName, ? extends SkyFunction> skyFunctions, EventHandler reporter, EmittedEventState emittedEventState, boolean keepGoing, boolean storeErrorsAlongsideValues, final DirtyTrackingProgressReceiver progressReceiver, EventFilter storedEventFilter, final Function<SkyKey, Runnable> runnableMaker, final ForkJoinPool forkJoinPool) { this.graph = graph; this.graphVersion = graphVersion; this.skyFunctions = skyFunctions; this.reporter = reporter; this.replayingNestedSetEventVisitor = new NestedSetVisitor<>(new NestedSetEventReceiver(reporter), emittedEventState); this.keepGoing = keepGoing; this.storeErrorsAlongsideValues = storeErrorsAlongsideValues; this.progressReceiver = Preconditions.checkNotNull(progressReceiver); this.storedEventFilter = storedEventFilter; visitorSupplier = Suppliers.memoize( new Supplier<NodeEntryVisitor>() { @Override public NodeEntryVisitor get() { return new NodeEntryVisitor( forkJoinPool, progressReceiver, runnableMaker); } }); } Map<SkyKey, ? extends NodeEntry> getBatchValues( @Nullable SkyKey parent, Reason reason, Iterable<SkyKey> keys) throws InterruptedException { return graph.getBatch(parent, reason, keys); } /** * Signals all parents that this node is finished. If {@code enqueueParents} is true, also * enqueues any parents that are ready. Otherwise, this indicates that we are building this node * after the main build aborted, so skip any parents that are already done (that can happen with * cycles). */ void signalValuesAndEnqueueIfReady( SkyKey skyKey, Iterable<SkyKey> keys, Version version, EnqueueParentBehavior enqueueParents) throws InterruptedException { // No fields of the entry are needed here, since we're just enqueuing for evaluation, but more // importantly, these hints are not respected for not-done nodes. If they are, we may need to // alter this hint. Map<SkyKey, ? extends NodeEntry> batch = graph.getBatch(skyKey, Reason.SIGNAL_DEP, keys); switch (enqueueParents) { case ENQUEUE: for (SkyKey key : keys) { NodeEntry entry = Preconditions.checkNotNull(batch.get(key), key); if (entry.signalDep(version)) { getVisitor().enqueueEvaluation(key); } } return; case SIGNAL: for (SkyKey key : keys) { NodeEntry entry = Preconditions.checkNotNull(batch.get(key), key); if (!entry.isDone()) { // In cycles, we can have parents that are already done. entry.signalDep(version); } } return; case NO_ACTION: return; default: throw new IllegalStateException(enqueueParents + ", " + skyKey); } } QueryableGraph getGraph() { return graph; } Version getGraphVersion() { return graphVersion; } boolean keepGoing() { return keepGoing; } NodeEntryVisitor getVisitor() { return visitorSupplier.get(); } DirtyTrackingProgressReceiver getProgressReceiver() { return progressReceiver; } NestedSetVisitor<TaggedEvents> getReplayingNestedSetEventVisitor() { return replayingNestedSetEventVisitor; } EventHandler getReporter() { return reporter; } ImmutableMap<SkyFunctionName, ? extends SkyFunction> getSkyFunctions() { return skyFunctions; } EventFilter getStoredEventFilter() { return storedEventFilter; } boolean storeErrorsAlongsideValues() { return storeErrorsAlongsideValues; } /** Receives the events from the NestedSet and delegates to the reporter. */ private static class NestedSetEventReceiver implements NestedSetVisitor.Receiver<TaggedEvents> { private final EventHandler reporter; public NestedSetEventReceiver(EventHandler reporter) { this.reporter = reporter; } @Override public void accept(TaggedEvents events) { String tag = events.getTag(); for (Event e : events.getEvents()) { reporter.handle(e.withTag(tag)); } } } }
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2015 The Billing Project, LLC * * The Billing Project 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.ning.billing.recurly.model; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.joda.time.DateTime; @XmlRootElement(name = "transaction") public class Transaction extends AbstractTransaction { @XmlElement(name = "account") private Account account; @XmlElement(name = "invoice") private Invoice invoice; @XmlElement(name = "subscription") private String subscription; @XmlElement(name = "uuid") private String uuid; @XmlElement(name = "tax_in_cents") private Integer taxInCents; @XmlElement(name = "currency") private String currency; @XmlElement(name = "description") private String description; @XmlElement(name = "source") private String source; @XmlElement(name = "recurring") private Boolean recurring; @XmlElement(name = "created_at") private DateTime createdAt; @XmlElement(name = "details") private TransactionDetails details; @XmlElement(name = "payment_method") private String paymentMethod; @XmlElement(name = "collected_at") private DateTime collectedAt; public Account getAccount() { if (account != null && account.getCreatedAt() == null) { account = fetch(account, Account.class); } return account; } public void setAccount(final Account account) { this.account = account; } public Invoice getInvoice() { if (invoice != null && invoice.getCreatedAt() == null) { invoice = fetch(invoice, Invoice.class); } return invoice; } public void setInvoice(final Invoice invoice) { this.invoice = invoice; } public String getSubscription() { return subscription; } public void setSubscription(final Object subscription) { this.subscription = stringOrNull(subscription); } public String getUuid() { return uuid; } public void setUuid(final Object uuid) { this.uuid = stringOrNull(uuid); } public Integer getTaxInCents() { return taxInCents; } public void setTaxInCents(final Object taxInCents) { this.taxInCents = integerOrNull(taxInCents); } public String getCurrency() { return currency; } public void setCurrency(final Object currency) { this.currency = stringOrNull(currency); } public String getDescription() { return description; } public void setDescription(final Object description) { this.description = stringOrNull(description); } public String getSource() { return source; } public void setSource(final Object source) { this.source = stringOrNull(source); } public Boolean getRecurring() { return recurring; } public void setRecurring(final Object recurring) { this.recurring = booleanOrNull(recurring); } public DateTime getCreatedAt() { return createdAt; } public void setCreatedAt(final Object createdAt) { this.createdAt = dateTimeOrNull(createdAt); } public TransactionDetails getDetails() { return details; } public void setDetails(final TransactionDetails details) { this.details = details; } public String getPaymentMethod() { return paymentMethod; } public void setPaymentMethod(final Object paymentMethod) { this.paymentMethod = stringOrNull(paymentMethod); } public DateTime getCollectedAt() { return collectedAt; } public void setCollectedAt(final Object collectedAt) { this.collectedAt = dateTimeOrNull(collectedAt); } @Override public String toString() { final StringBuilder sb = new StringBuilder("Transaction{"); sb.append("account=").append(account); sb.append(", invoice=").append(invoice); sb.append(", subscription='").append(subscription).append('\''); sb.append(", uuid='").append(uuid).append('\''); sb.append(", taxInCents=").append(taxInCents); sb.append(", currency='").append(currency).append('\''); sb.append(", description='").append(description).append('\''); sb.append(", source='").append(source).append('\''); sb.append(", recurring=").append(recurring); sb.append(", createdAt=").append(createdAt); sb.append(", details=").append(details); sb.append(", paymentMethod=").append(paymentMethod); sb.append(", collectedAt=").append(collectedAt); sb.append('}'); return sb.toString(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } final Transaction that = (Transaction) o; if (account != null ? !account.equals(that.account) : that.account != null) { return false; } if (createdAt != null ? !createdAt.equals(that.createdAt) : that.createdAt != null) { return false; } if (currency != null ? !currency.equals(that.currency) : that.currency != null) { return false; } if (description != null ? !description.equals(that.description) : that.description != null) { return false; } if (details != null ? !details.equals(that.details) : that.details != null) { return false; } if (invoice != null ? !invoice.equals(that.invoice) : that.invoice != null) { return false; } if (recurring != null ? !recurring.equals(that.recurring) : that.recurring != null) { return false; } if (source != null ? !source.equals(that.source) : that.source != null) { return false; } if (subscription != null ? !subscription.equals(that.subscription) : that.subscription != null) { return false; } if (taxInCents != null ? !taxInCents.equals(that.taxInCents) : that.taxInCents != null) { return false; } if (uuid != null ? !uuid.equals(that.uuid) : that.uuid != null) { return false; } if (paymentMethod != null ? !paymentMethod.equals(that.paymentMethod) : that.paymentMethod != null) { return false; } if (collectedAt != null ? !collectedAt.equals(that.collectedAt) : that.collectedAt != null) { return false; } return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (account != null ? account.hashCode() : 0); result = 31 * result + (invoice != null ? invoice.hashCode() : 0); result = 31 * result + (subscription != null ? subscription.hashCode() : 0); result = 31 * result + (uuid != null ? uuid.hashCode() : 0); result = 31 * result + (taxInCents != null ? taxInCents.hashCode() : 0); result = 31 * result + (currency != null ? currency.hashCode() : 0); result = 31 * result + (description != null ? description.hashCode() : 0); result = 31 * result + (source != null ? source.hashCode() : 0); result = 31 * result + (recurring != null ? recurring.hashCode() : 0); result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0); result = 31 * result + (details != null ? details.hashCode() : 0); return result; } }
/* * Copyright 2014 The Closure Compiler 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.javascript.jscomp; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Ordering; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.JSTypeExpression; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Prints a JSDocInfo, used for preserving type annotations in ES6 transpilation. * */ public final class JSDocInfoPrinter { public static String print(JSDocInfo info) { boolean multiline = false; List<String> parts = new ArrayList<>(); // order: // export|public|private|package|protected // const // dict|struct|unrestricted // constructor|interface|record // extends // implements // this // param // return // throws // template // override // type|define|typedef|enum // suppress // deprecated parts.add("/**"); if (info.isExport()) { parts.add("@export"); } else if (info.getVisibility() != null && info.getVisibility() != Visibility.INHERITED) { parts.add("@" + info.getVisibility().toString().toLowerCase()); } if (info.isConstant() && !info.isDefine()) { parts.add("@const"); } if (info.makesDicts()) { parts.add("@dict"); } if (info.makesStructs()) { parts.add("@struct"); } if (info.makesUnrestricted()) { parts.add("@unrestricted "); } if (info.isConstructor()) { parts.add("@constructor"); } if (info.isInterface() && !info.usesImplicitMatch()) { parts.add("@interface"); } if (info.isInterface() && info.usesImplicitMatch()) { parts.add("@record"); } if (info.hasBaseType()) { multiline = true; Node typeNode = stripBang(info.getBaseType().getRoot()); parts.add(buildAnnotationWithType("extends", typeNode)); } for (JSTypeExpression type : info.getExtendedInterfaces()) { multiline = true; Node typeNode = stripBang(type.getRoot()); parts.add(buildAnnotationWithType("extends", typeNode)); } for (JSTypeExpression type : info.getImplementedInterfaces()) { multiline = true; Node typeNode = stripBang(type.getRoot()); parts.add(buildAnnotationWithType("implements", typeNode)); } if (info.hasThisType()) { multiline = true; Node typeNode = stripBang(info.getThisType().getRoot()); parts.add(buildAnnotationWithType("this", typeNode)); } if (info.getParameterCount() > 0) { multiline = true; for (String name : info.getParameterNames()) { parts.add("@param " + buildParamType(name, info.getParameterType(name))); } } if (info.hasReturnType()) { multiline = true; parts.add(buildAnnotationWithType("return", info.getReturnType())); } if (!info.getThrownTypes().isEmpty()) { parts.add(buildAnnotationWithType("throws", info.getThrownTypes().get(0))); } ImmutableList<String> names = info.getTemplateTypeNames(); if (!names.isEmpty()) { parts.add("@template " + Joiner.on(',').join(names)); multiline = true; } if (info.isOverride()) { parts.add("@override"); } if (info.hasType() && !info.isDefine()) { if (info.isInlineType()) { parts.add(typeNode(info.getType().getRoot())); } else { parts.add(buildAnnotationWithType("type", info.getType())); } } if (info.isDefine()) { parts.add(buildAnnotationWithType("define", info.getType())); } if (info.hasTypedefType()) { parts.add(buildAnnotationWithType("typedef", info.getTypedefType())); } if (info.hasEnumParameterType()) { parts.add(buildAnnotationWithType("enum", info.getEnumParameterType())); } Set<String> suppressions = info.getSuppressions(); if (!suppressions.isEmpty()) { // Print suppressions in sorted order to avoid non-deterministic output. String[] arr = suppressions.toArray(new String[0]); Arrays.sort(arr, Ordering.<String>natural()); parts.add("@suppress {" + Joiner.on(',').join(arr) + "}"); multiline = true; } if (info.isDeprecated()) { parts.add("@deprecated " + info.getDeprecationReason()); multiline = true; } parts.add("*/"); StringBuilder sb = new StringBuilder(); if (multiline) { Joiner.on("\n ").appendTo(sb, parts); } else { Joiner.on(" ").appendTo(sb, parts); } sb.append((multiline) ? "\n" : " "); return sb.toString(); } private static Node stripBang(Node typeNode) { if (typeNode.getType() == Token.BANG) { typeNode = typeNode.getFirstChild(); } return typeNode; } private static String buildAnnotationWithType(String annotation, JSTypeExpression type) { return buildAnnotationWithType(annotation, type.getRoot()); } private static String buildAnnotationWithType(String annotation, Node type) { StringBuilder sb = new StringBuilder(); sb.append("@"); sb.append(annotation); sb.append(" {"); appendTypeNode(sb, type); sb.append("}"); return sb.toString(); } private static String buildParamType(String name, JSTypeExpression type) { if (type != null) { return "{" + typeNode(type.getRoot()) + "} " + name; } else { return name; } } private static String typeNode(Node typeNode) { StringBuilder sb = new StringBuilder(); appendTypeNode(sb, typeNode); return sb.toString(); } private static void appendTypeNode(StringBuilder sb, Node typeNode) { if (typeNode.getType() == Token.BANG) { sb.append("!"); appendTypeNode(sb, typeNode.getFirstChild()); } else if (typeNode.getType() == Token.EQUALS) { appendTypeNode(sb, typeNode.getFirstChild()); sb.append("="); } else if (typeNode.getType() == Token.PIPE) { sb.append("("); for (int i = 0; i < typeNode.getChildCount() - 1; i++) { appendTypeNode(sb, typeNode.getChildAtIndex(i)); sb.append("|"); } appendTypeNode(sb, typeNode.getLastChild()); sb.append(")"); } else if (typeNode.getType() == Token.ELLIPSIS) { sb.append("..."); if (typeNode.hasChildren()) { appendTypeNode(sb, typeNode.getFirstChild()); } } else if (typeNode.getType() == Token.STAR) { sb.append("*"); } else if (typeNode.getType() == Token.QMARK) { sb.append("?"); if (typeNode.hasChildren()) { appendTypeNode(sb, typeNode.getFirstChild()); } } else if (typeNode.isFunction()) { appendFunctionNode(sb, typeNode); } else if (typeNode.getType() == Token.LC) { sb.append("{"); Node lb = typeNode.getFirstChild(); for (int i = 0; i < lb.getChildCount() - 1; i++) { Node colon = lb.getChildAtIndex(i); if (colon.hasChildren()) { sb.append(colon.getFirstChild().getString()).append(":"); appendTypeNode(sb, colon.getLastChild()); } else { sb.append(colon.getString()); } sb.append(","); } Node lastColon = lb.getLastChild(); if (lastColon.hasChildren()) { sb.append(lastColon.getFirstChild().getString()).append(":"); appendTypeNode(sb, lastColon.getLastChild()); } else { sb.append(lastColon.getString()); } sb.append("}"); } else if (typeNode.getType() == Token.VOID) { sb.append("void"); } else { if (typeNode.hasChildren()) { sb.append(typeNode.getString()) .append("<"); Node child = typeNode.getFirstChild(); appendTypeNode(sb, child.getFirstChild()); for (int i = 1; i < child.getChildCount(); i++) { sb.append(","); appendTypeNode(sb, child.getChildAtIndex(i)); } sb.append(">"); } else { sb.append(typeNode.getString()); } } } private static void appendFunctionNode(StringBuilder sb, Node function) { boolean hasNewOrThis = false; sb.append("function("); Node first = function.getFirstChild(); if (first.isNew()) { sb.append("new:"); appendTypeNode(sb, first.getFirstChild()); hasNewOrThis = true; } else if (first.isThis()) { sb.append("this:"); appendTypeNode(sb, first.getFirstChild()); hasNewOrThis = true; } else if (first.isEmpty()) { sb.append(")"); return; } else if (!first.isParamList()) { sb.append("):"); appendTypeNode(sb, first); return; } Node paramList = null; if (first.isParamList()) { paramList = first; } else if (first.getNext().isParamList()) { paramList = first.getNext(); } if (paramList != null) { boolean firstParam = true; for (Node param : paramList.children()) { if (!firstParam || hasNewOrThis) { sb.append(","); } appendTypeNode(sb, param); firstParam = false; } } sb.append(")"); Node returnType = function.getLastChild(); if (!returnType.isEmpty()) { sb.append(":"); appendTypeNode(sb, returnType); } } }
package org.kuali.kpme.edo.api.dossier; import java.io.Serializable; import java.util.Collection; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.kuali.rice.core.api.CoreConstants; import org.kuali.rice.core.api.mo.AbstractDataTransferObject; import org.kuali.rice.core.api.mo.ModelBuilder; import org.w3c.dom.Element; @XmlRootElement(name = EdoDossierDocumentInfo.Constants.ROOT_ELEMENT_NAME) @XmlAccessorType(XmlAccessType.NONE) @XmlType(name = EdoDossierDocumentInfo.Constants.TYPE_NAME, propOrder = { EdoDossierDocumentInfo.Elements.DOCUMENT_TYPE_NAME, EdoDossierDocumentInfo.Elements.EDO_DOCUMENT_ID, EdoDossierDocumentInfo.Elements.PRINCIPAL_ID, EdoDossierDocumentInfo.Elements.DOCUMENT_STATUS, EdoDossierDocumentInfo.Elements.EDO_DOSSIER_ID, CoreConstants.CommonElements.VERSION_NUMBER, CoreConstants.CommonElements.OBJECT_ID, CoreConstants.CommonElements.FUTURE_ELEMENTS }) public final class EdoDossierDocumentInfo extends AbstractDataTransferObject implements EdoDossierDocumentInfoContract { @XmlElement(name = Elements.DOCUMENT_TYPE_NAME, required = false) private final String documentTypeName; @XmlElement(name = Elements.EDO_DOCUMENT_ID, required = false) private final String edoDocumentId; @XmlElement(name = Elements.PRINCIPAL_ID, required = false) private final String principalId; @XmlElement(name = Elements.DOCUMENT_STATUS, required = false) private final String documentStatus; @XmlElement(name = Elements.EDO_DOSSIER_ID, required = false) private final String edoDossierId; @XmlElement(name = CoreConstants.CommonElements.VERSION_NUMBER, required = false) private final Long versionNumber; @XmlElement(name = CoreConstants.CommonElements.OBJECT_ID, required = false) private final String objectId; @SuppressWarnings("unused") @XmlAnyElement private final Collection<Element> _futureElements = null; /** * Private constructor used only by JAXB. * */ private EdoDossierDocumentInfo() { this.documentTypeName = null; this.edoDocumentId = null; this.principalId = null; this.documentStatus = null; this.edoDossierId = null; this.versionNumber = null; this.objectId = null; } private EdoDossierDocumentInfo(Builder builder) { this.documentTypeName = builder.getDocumentTypeName(); this.edoDocumentId = builder.getEdoDocumentId(); this.principalId = builder.getPrincipalId(); this.documentStatus = builder.getDocumentStatus(); this.edoDossierId = builder.getEdoDossierId(); this.versionNumber = builder.getVersionNumber(); this.objectId = builder.getObjectId(); } @Override public String getDocumentTypeName() { return this.documentTypeName; } @Override public String getEdoDocumentId() { return this.edoDocumentId; } @Override public String getPrincipalId() { return this.principalId; } @Override public String getDocumentStatus() { return this.documentStatus; } @Override public String getEdoDossierId() { return this.edoDossierId; } @Override public Long getVersionNumber() { return this.versionNumber; } @Override public String getObjectId() { return this.objectId; } /** * A builder which can be used to construct {@link EdoDossierDocumentInfo} instances. Enforces the constraints of the {@link EdoDossierDocumentInfoContract}. * */ public final static class Builder implements Serializable, EdoDossierDocumentInfoContract, ModelBuilder { private String documentTypeName; private String edoDocumentId; private String principalId; private String documentStatus; private String edoDossierId; private Long versionNumber; private String objectId; private Builder() { // TODO modify this constructor as needed to pass any required values and invoke the appropriate 'setter' methods } public static Builder create() { // TODO modify as needed to pass any required values and add them to the signature of the 'create' method return new Builder(); } public static Builder create(EdoDossierDocumentInfoContract contract) { if (contract == null) { throw new IllegalArgumentException("contract was null"); } // TODO if create() is modified to accept required parameters, this will need to be modified Builder builder = create(); builder.setDocumentTypeName(contract.getDocumentTypeName()); builder.setEdoDocumentId(contract.getEdoDocumentId()); builder.setPrincipalId(contract.getPrincipalId()); builder.setDocumentStatus(contract.getDocumentStatus()); builder.setEdoDossierId(contract.getEdoDossierId()); builder.setVersionNumber(contract.getVersionNumber()); builder.setObjectId(contract.getObjectId()); return builder; } public EdoDossierDocumentInfo build() { return new EdoDossierDocumentInfo(this); } @Override public String getDocumentTypeName() { return this.documentTypeName; } @Override public String getEdoDocumentId() { return this.edoDocumentId; } @Override public String getPrincipalId() { return this.principalId; } @Override public String getDocumentStatus() { return this.documentStatus; } @Override public String getEdoDossierId() { return this.edoDossierId; } @Override public Long getVersionNumber() { return this.versionNumber; } @Override public String getObjectId() { return this.objectId; } public void setDocumentTypeName(String documentTypeName) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.documentTypeName = documentTypeName; } public void setEdoDocumentId(String edoDocumentId) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.edoDocumentId = edoDocumentId; } public void setPrincipalId(String principalId) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.principalId = principalId; } public void setDocumentStatus(String documentStatus) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.documentStatus = documentStatus; } public void setEdoDossierId(String edoDossierId) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.edoDossierId = edoDossierId; } public void setVersionNumber(Long versionNumber) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.versionNumber = versionNumber; } public void setObjectId(String objectId) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.objectId = objectId; } } /** * Defines some internal constants used on this class. * */ static class Constants { final static String ROOT_ELEMENT_NAME = "edoDossierDocumentInfo"; final static String TYPE_NAME = "EdoDossierDocumentInfoType"; } /** * A private class which exposes constants which define the XML element names to use when this object is marshalled to XML. * */ static class Elements { final static String DOCUMENT_TYPE_NAME = "documentTypeName"; final static String EDO_DOCUMENT_ID = "edoDocumentId"; final static String PRINCIPAL_ID = "principalId"; final static String DOCUMENT_STATUS = "documentStatus"; final static String EDO_DOSSIER_ID = "edoDossierId"; } }
// 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.cloud.api.commands; import java.util.List; import org.apache.log4j.Logger; import com.cloud.api.ApiConstants; import com.cloud.api.BaseAsyncCreateCmd; import com.cloud.api.BaseCmd; import com.cloud.api.IdentityMapper; import com.cloud.api.Implementation; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.LoadBalancerResponse; import com.cloud.async.AsyncJob; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; import com.cloud.network.Network; import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.net.NetUtils; @Implementation(description="Creates a load balancer rule", responseObject=LoadBalancerResponse.class) public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements LoadBalancer */{ public static final Logger s_logger = Logger.getLogger(CreateLoadBalancerRuleCmd.class.getName()); private static final String s_name = "createloadbalancerruleresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.ALGORITHM, type=CommandType.STRING, required=true, description="load balancer algorithm (source, roundrobin, leastconn)") private String algorithm; @Parameter(name=ApiConstants.DESCRIPTION, type=CommandType.STRING, description="the description of the load balancer rule", length=4096) private String description; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="name of the load balancer rule") private String loadBalancerRuleName; @Parameter(name=ApiConstants.PRIVATE_PORT, type=CommandType.INTEGER, required=true, description="the private port of the private ip address/virtual machine where the network traffic will be load balanced to") private Integer privatePort; @IdentityMapper(entityTableName="user_ip_address") @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, description="public ip address id from where the network traffic will be load balanced from") private Long publicIpId; @IdentityMapper(entityTableName="data_center") @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=false, description="zone where the load balancer is going to be created. This parameter is required when LB service provider is ElasticLoadBalancerVm") private Long zoneId; @Parameter(name=ApiConstants.PUBLIC_PORT, type=CommandType.INTEGER, required=true, description="the public port from where the network traffic will be load balanced from") private Integer publicPort; @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. Has value true by default") private Boolean openFirewall; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the load balancer. Must be used with the domainId parameter.") private String accountName; @IdentityMapper(entityTableName="domain") @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the load balancer") private Long domainId; @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List<String> cidrlist; @IdentityMapper(entityTableName="networks") @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="The guest network this rule will be created for") private Long networkId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public String getAlgorithm() { return algorithm; } public String getDescription() { return description; } public String getLoadBalancerRuleName() { return loadBalancerRuleName; } public Integer getPrivatePort() { return privatePort; } public String getEntityTable() { return "firewall_rules"; } public Long getSourceIpAddressId() { if (publicIpId != null) { IpAddress ipAddr = _networkService.getIp(publicIpId); if (ipAddr == null || !ipAddr.readyToUse()) { throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id " + ipAddr.getId()); } } else if (getEntityId() != null) { LoadBalancer rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); return rule.getSourceIpAddressId(); } return publicIpId; } public Long getNetworkId() { if (networkId != null) { return networkId; } Long zoneId = getZoneId(); if (zoneId == null) { Long ipId = getSourceIpAddressId(); if (ipId == null) { throw new InvalidParameterValueException("Either networkId or zoneId or publicIpId has to be specified"); } } if (zoneId != null) { DataCenter zone = _configService.getZone(zoneId); if (zone.getNetworkType() == NetworkType.Advanced) { List<? extends Network> networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId())); if (networks.size() == 0) { String domain = _domainService.getDomain(getDomainId()).getName(); throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName()); } if (networks.size() < 1) { throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); } else if (networks.size() > 1) { throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); } return networks.get(0).getId(); } else { Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId); if (defaultGuestNetwork == null) { throw new InvalidParameterValueException("Unable to find a default Guest network for account " + getAccountName() + " in domain id=" + getDomainId()); } else { return defaultGuestNetwork.getId(); } } } else { IpAddress ipAddr = _networkService.getIp(publicIpId); return ipAddr.getAssociatedWithNetworkId(); } } public Integer getPublicPort() { return publicPort; } public String getName() { return loadBalancerRuleName; } public Boolean getOpenFirewall() { if (openFirewall != null) { return openFirewall; } else { return true; } } public List<String> getSourceCidrList() { if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); } return null; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public void execute() throws ResourceAllocationException, ResourceUnavailableException { UserContext callerContext = UserContext.current(); boolean success = true; LoadBalancer rule = null; try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); if (getOpenFirewall()) { success = success && _firewallService.applyFirewallRules(getSourceIpAddressId(), callerContext.getCaller()); } // State might be different after the rule is applied, so get new object here rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); LoadBalancerResponse lbResponse = new LoadBalancerResponse(); if (rule != null) { lbResponse = _responseGenerator.createLoadBalancerResponse(rule); setResponseObject(lbResponse); } lbResponse.setResponseName(getCommandName()); } catch (Exception ex) { s_logger.warn("Failed to create LB rule due to exception ", ex); }finally { if (!success || rule == null) { if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } // no need to apply the rule on the backend as it exists in the db only _lbService.deleteLoadBalancerRule(getEntityId(), false); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create load balancer rule"); } } } @Override public void create() { //cidr list parameter is deprecated if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); } try { LoadBalancer result = _lbService.createLoadBalancerRule(this, getOpenFirewall()); this.setEntityId(result.getId()); } catch (NetworkRuleConflictException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } catch (InsufficientAddressCapacityException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, e.getMessage()); } } public Integer getSourcePortStart() { return publicPort.intValue(); } public Integer getSourcePortEnd() { return publicPort.intValue(); } public String getProtocol() { return NetUtils.TCP_PROTO; } public long getAccountId() { if (publicIpId != null) return _networkService.getIp(getSourceIpAddressId()).getAccountId(); Account account = null; if ((domainId != null) && (accountName != null)) { account = _responseGenerator.findAccountByNameDomain(accountName, domainId); if (account != null) { return account.getId(); } else { throw new InvalidParameterValueException("Unable to find account " + account + " in domain id=" + domainId); } } else { throw new InvalidParameterValueException("Can't define IP owner. Either specify account/domainId or ipAddressId"); } } public long getDomainId() { if (publicIpId != null) return _networkService.getIp(getSourceIpAddressId()).getDomainId(); if (domainId != null) { return domainId; } return UserContext.current().getCaller().getDomainId(); } public int getDefaultPortStart() { return privatePort.intValue(); } public int getDefaultPortEnd() { return privatePort.intValue(); } @Override public long getEntityOwnerId() { return getAccountId(); } public String getAccountName() { return accountName; } public Long getZoneId() { return zoneId; } public void setPublicIpId(Long publicIpId) { this.publicIpId = publicIpId; } @Override public String getEventType() { return EventTypes.EVENT_LOAD_BALANCER_CREATE; } @Override public String getEventDescription() { return "creating load balancer: " + getName() + " account: " + getAccountName(); } public String getXid() { /*FIXME*/ return null; } public void setSourceIpAddressId(Long ipId) { this.publicIpId = ipId; } @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } }
package de.gw.auto.controller; import java.security.Principal; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.itextpdf.text.DocumentException; import de.gw.auto.domain.Kraftstoffsorte; import de.gw.auto.domain.Land; import de.gw.auto.domain.Ort; import de.gw.auto.domain.Tank; import de.gw.auto.domain.Tanken; import de.gw.auto.repository.UserRepository; import de.gw.auto.service.RegisteredUser; import de.gw.auto.service.implementation.StammdatenService; import de.gw.auto.service.implementation.TankenService; import de.gw.auto.view.ViewName; import de.gw.auto.view.model.HeaderModel; import de.gw.auto.view.model.NewLandOrCity; import de.gw.auto.view.model.NewTanken; import de.gw.auto.view.model.TankenViewModel; import de.gw.auto.view.model.helper.NewTankenModelHelper; import de.gw.auto.view.model.helper.TankenModelHelper; @Controller @RequestMapping("user/tanken") @Secured("ROLE_USER") public class TankenController extends ControllerHelper { @Autowired private TankenModelHelper tankenHelper; @Autowired private TankenService tankenService; @Autowired private UserRepository userRepository; @Autowired private StammdatenService stammdatenService; @Autowired private NewTankenModelHelper newTankenModelHelper; @RequestMapping(value = "/show", method = RequestMethod.GET) public String show( @ModelAttribute("tankenView") TankenViewModel tankenView, Principal principal, Model model, HttpServletRequest request, @RequestParam(value = "page", defaultValue = "0") int page) { RegisteredUser user = giveRegisteredUser(principal); if (user.getCurrentAuto() == null) { return "redirect:/user/auto/new"; } if (user.getCurrentAuto().getTankfuellungen().isEmpty()) { return "redirect:/user/tanken/new"; } tankenView = this.tankenHelper.prepareTankViewModel(tankenView, user.getCurrentAuto(), page); model.addAttribute("tankenView", tankenView); return "tanken/table :: tankenTable"; } @RequestMapping(value = "/new", method = RequestMethod.GET) public String prepareNew( NewTanken newTanken, BindingResult bindingResult, Model model, Principal principal) { RegisteredUser user = giveRegisteredUser(principal); newTankenModelHelper.prepare(newTanken, user.getCurrentAuto()); model.addAttribute(newTanken); return "tanken/new :: newTankenModal"; } @RequestMapping(value = "/save", method = RequestMethod.POST) public String saveTankfuellung(@Valid NewTanken newTanken, BindingResult bindingResult, Model model, Principal principal, RedirectAttributes redirectAttributes) { if (bindingResult.hasErrors()) { RegisteredUser user = giveRegisteredUser(principal); newTankenModelHelper.prepare(newTanken, user.getCurrentAuto()); model.addAttribute(newTanken); return "tanken/new"; } RegisteredUser user = giveRegisteredUser(principal); Kraftstoffsorte kraftstoffsorte = stammdatenService .getKraftstoffsorte(newTanken.getUserKraftstoffsorte()); Land l = stammdatenService.getLand(newTanken.getLandId()); Tank t = stammdatenService.getTankstand(newTanken.getTankId()); Ort o = null; if (newTanken.getOrtId() > 0) { o = l.getOrt(newTanken.getOrtId()); } Tanken tanken = new Tanken(newTanken.getKmStand(), l, o, t, newTanken.getKosten(), user.getCurrentAuto(), newTanken.getDatum(), newTanken.getLiter(), newTanken.getPreisProLiter(), kraftstoffsorte); tankenService.save(tanken, user); return ViewName.REDIRECT_ROOT_USER_SHOW; } @RequestMapping(value = "addLand", method = RequestMethod.POST) @ResponseBody public int addLand(@RequestBody NewLandOrCity land) { if (!StringUtils.isBlank(land.getText())) { for (Land l : stammdatenService.getLaender()) { if (l.getName().equalsIgnoreCase(land.getText())) { return l.getId(); } } Land lSave = stammdatenService.saveLand(new Land(land.getText())); return lSave.getId(); } return 0; } @RequestMapping(value = "addOrt", method = RequestMethod.POST) @ResponseBody public int addOrt(@RequestBody NewLandOrCity ort) { if (ort.getParent() > 0l) { if (!ort.getText().trim().isEmpty()) { Land l = stammdatenService.getLand((int) ort.getParent()); for (Ort o : l.getOrte()) { if (o.getOrt().equalsIgnoreCase(ort.getText())) { return o.getId(); } } l.addOrt(new Ort(ort.getText())); stammdatenService.saveLand(l); for (Ort o : l.getOrte()) { if (o.getOrt().equalsIgnoreCase(ort.getText())) { return o.getId(); } } } } return 0; } @RequestMapping(value = "downloadEmptyTanken", method = RequestMethod.GET, produces = "application/pdf") public ResponseEntity<byte[]> downloadEmptyTanken(Model model, Principal principal) throws DocumentException { RegisteredUser user = giveRegisteredUser(principal); if (user == null) { return null; } return new ResponseEntity<byte[]>(tankenHelper.createEmptyPDF(user .getCurrentAuto()), HttpStatus.CREATED); } @RequestMapping(value = "/downloadTanken", method = RequestMethod.GET, produces = "application/pdf") public ResponseEntity<byte[]> download( @ModelAttribute("tankenView") TankenViewModel tankenView, BindingResult bindingResult, Model model, Principal principal) throws DocumentException { if (bindingResult.hasErrors()) { return null; } RegisteredUser user = giveRegisteredUser(principal); if (user == null) { return null; } return new ResponseEntity<byte[]>(tankenHelper.createPDF(user .getCurrentAuto()), HttpStatus.CREATED); } @RequestMapping(value="delete", method=RequestMethod.POST) public String delete(@RequestParam("id")long id, Principal principal) { if (id==0) { return null; } RegisteredUser user = giveRegisteredUser(principal); if (user == null) { return null; } tankenService.delete(id); return ViewName.REDIRECT_ROOT_USER_SHOW; } }
/* * 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.util; import android.content.Context; import android.graphics.Bitmap; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLngBounds; import com.google.maps.android.geojson.GeoJsonFeature; import com.google.maps.android.geojson.GeoJsonLayer; import com.google.maps.android.geojson.GeoJsonPointStyle; import com.google.maps.android.ui.IconGenerator; import com.google.samples.apps.iosched.lib.R; import com.google.samples.apps.iosched.map.util.MarkerModel; import com.jakewharton.disklrucache.DiskLruCache; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.Locale; import static com.google.samples.apps.iosched.util.LogUtils.LOGD; import static com.google.samples.apps.iosched.util.LogUtils.LOGE; public class MapUtils { private static final String ICON_RESOURCE_PREFIX = "map_marker_"; private static final String TILE_PATH = "maptiles"; private static final String TAG = LogUtils.makeLogTag(MapUtils.class); private static final String TYPE_ICON_PREFIX = "ICON_"; /** * Returns the room type for a {@link com.google.samples.apps.iosched.map.util.MarkerModel} * for a given String. */ public static int detectMarkerType(String markerType) { if (TextUtils.isEmpty(markerType)) { return MarkerModel.TYPE_INACTIVE; } String tags = markerType.toUpperCase(Locale.US); if (tags.contains("SESSION")) { return MarkerModel.TYPE_SESSION; } else if (tags.contains("PLAIN")) { return MarkerModel.TYPE_PLAIN; } else if (tags.contains("LABEL")) { return MarkerModel.TYPE_LABEL; } else if (tags.contains("CODELAB")) { return MarkerModel.TYPE_CODELAB; } else if (tags.contains("SANDBOX")) { return MarkerModel.TYPE_SANDBOX; } else if (tags.startsWith(TYPE_ICON_PREFIX)) { return MarkerModel.TYPE_ICON; } else if (tags.contains("OFFICEHOURS")) { return MarkerModel.TYPE_OFFICEHOURS; } else if (tags.contains("MISC")) { return MarkerModel.TYPE_MISC; } else if (tags.contains("CHAT")) { return MarkerModel.TYPE_CHAT; } else if (tags.contains("FIRSTSESSION")) { return MarkerModel.TYPE_FIRSTSESSION; } else if (tags.contains("INACTIVE")) { return MarkerModel.TYPE_INACTIVE; } return MarkerModel.TYPE_INACTIVE; // default } /** * True if the info details for this room type should only contain a title and optional * subtitle. */ public static boolean hasInfoTitleOnly(int markerType) { return markerType == MarkerModel.TYPE_PLAIN || markerType == MarkerModel.TYPE_OFFICEHOURS || markerType == MarkerModel.TYPE_MISC || markerType == MarkerModel.TYPE_SANDBOX || markerType == MarkerModel.TYPE_ICON || markerType == MarkerModel.TYPE_CODELAB; } /** * True if the info details for this room type contain a title and a list of sessions. */ public static boolean hasInfoSessionList(int markerType) { return markerType == MarkerModel.TYPE_SESSION; } /** * True if the info details for this room type contain a title and the description from the * first scheduled session. */ public static boolean hasInfoFirstDescriptionOnly(int markerType) { return markerType == MarkerModel.TYPE_FIRSTSESSION; } /** * True if the info details for this room type contain a title and a list of sessions, with * each row prefixed with the icon for this room. */ public static boolean hasInfoSessionListIcons(int markerType) { return markerType == MarkerModel.TYPE_CHAT; } /** * True if the marker for this feature should be changed to a generic "active" marker when * clicked, and changed back to the generic marker when deselected. */ public static boolean useActiveMarker(int type) { return type != MarkerModel.TYPE_ICON && type != MarkerModel.TYPE_LABEL; } /** * Creates a GeoJsonPointStyle for a session. * * @param title Id to be embedded as the title */ public static GeoJsonPointStyle createPinMarker(@NonNull Context context, String title) { final BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap( UIUtils.drawableToBitmap(context, R.drawable.map_marker_unselected)); GeoJsonPointStyle pointStyle = new GeoJsonPointStyle(); pointStyle.setTitle(title); pointStyle.setIcon(icon); pointStyle.setVisible(false); pointStyle.setAnchor(0.5f, 0.85526f); return pointStyle; } /** * Creates a new IconGenerator for labels on the map. */ private static IconGenerator getLabelIconGenerator(Context c) { IconGenerator iconFactory = new IconGenerator(c); iconFactory.setTextAppearance(R.style.TextApparance_Map_Label); iconFactory.setBackground(null); return iconFactory; } /** * Creates a GeoJsonPointStyle for a label. * * @param iconFactory Reusable IconFactory * @param title Id to be embedded as the title * @param label Text to be shown on the label */ private static GeoJsonPointStyle createLabelMarker(IconGenerator iconFactory, String title, String label) { final BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(label)); GeoJsonPointStyle pointStyle = new GeoJsonPointStyle(); pointStyle.setAnchor(0.5f, 0.5f); pointStyle.setTitle(title); pointStyle.setIcon(icon); pointStyle.setVisible(false); return pointStyle; } /** * Creates a GeoJsonPointStyle for an icon. The icon is selected * in {@link #getDrawableForIconType(Context, String)} and anchored * at the bottom center for the location. When isActive is set to true, the icon is tinted. */ private static GeoJsonPointStyle createIconMarker(final String iconType, final String title, boolean isActive, Context context) { final Bitmap iconBitmap = getIconMarkerBitmap(context, iconType, isActive); final BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(iconBitmap); GeoJsonPointStyle pointStyle = new GeoJsonPointStyle(); pointStyle.setTitle(title); pointStyle.setVisible(false); pointStyle.setIcon(icon); pointStyle.setAnchor(0.5f, 1f); return pointStyle; } /** * Loads the marker icon for this ICON_TYPE marker. * <p> * If isActive is set, the marker is tinted. See {@link UIUtils#tintBitmap(Bitmap, int)}. */ public static Bitmap getIconMarkerBitmap(Context context, String iconType, boolean isActive) { final int iconResource = getDrawableForIconType(context, iconType); if (iconResource < 1) { // Not a valid icon type. return null; } Bitmap iconBitmap = UIUtils.drawableToBitmap(context, iconResource); if (isActive) { iconBitmap = UIUtils.tintBitmap(iconBitmap, ContextCompat.getColor(context, R.color.map_active_icon_tint)); } return iconBitmap; } /** * Returns the drawable resource id for an icon marker. The resource name is generated by * prefixing #ICON_RESOURCE_PREFIX to the icon type in lower case. Returns 0 if no resource with * this name exists. */ public static @DrawableRes int getDrawableForIconType(@NonNull Context context, @NonNull String iconType) { if (iconType == null || !iconType.startsWith(TYPE_ICON_PREFIX)) { return 0; } // Return the ID of the resource that matches the iconType name. // If no resources matches this name, returns 0. //noinspection DefaultLocale return context.getResources().getIdentifier(ICON_RESOURCE_PREFIX + iconType.toLowerCase(), "drawable", context.getPackageName()); } private static String[] mapTileAssets; /** * Returns true if the given tile file exists as a local asset. */ public static boolean hasTileAsset(Context context, String filename) { //cache the list of available files if (mapTileAssets == null) { try { mapTileAssets = context.getAssets().list("maptiles"); } catch (IOException e) { // no assets mapTileAssets = new String[0]; } } // search for given filename for (String s : mapTileAssets) { if (s.equals(filename)) { return true; } } return false; } /** * Copy the file from the assets to the map tiles directory if it was * shipped with the APK. */ public static boolean copyTileAsset(Context context, String filename) { if (!hasTileAsset(context, filename)) { // file does not exist as asset return false; } // copy file from asset to internal storage try { InputStream is = context.getAssets().open(TILE_PATH + File.separator + filename); File f = getTileFile(context, filename); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[1024]; int dataSize; while ((dataSize = is.read(buffer)) > 0) { os.write(buffer, 0, dataSize); } os.close(); } catch (IOException e) { return false; } return true; } /** * Return a {@link File} pointing to the storage location for map tiles. */ public static File getTileFile(Context context, String filename) { File folder = new File(context.getFilesDir(), TILE_PATH); if (!folder.exists()) { folder.mkdirs(); } return new File(folder, filename); } public static void removeUnusedTiles(Context mContext, final ArrayList<String> usedTiles) { // remove all files are stored in the tile path but are not used File folder = new File(mContext.getFilesDir(), TILE_PATH); File[] unused = folder.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { return !usedTiles.contains(filename); } }); if (unused != null) { for (File f : unused) { f.delete(); } } } public static boolean hasTile(Context mContext, String filename) { return getTileFile(mContext, filename).exists(); } private static final int MAX_DISK_CACHE_BYTES = 1024 * 1024 * 2; // 2MB public static DiskLruCache openDiskCache(Context c) { File cacheDir = new File(c.getCacheDir(), "tiles"); try { return DiskLruCache.open(cacheDir, 1, 3, MAX_DISK_CACHE_BYTES); } catch (IOException e) { LOGE(TAG, "Couldn't open disk cache."); } return null; } public static void clearDiskCache(Context c) { DiskLruCache cache = openDiskCache(c); if (cache != null) { try { LOGD(TAG, "Clearing map tile disk cache"); cache.delete(); cache.close(); } catch (IOException e) { // ignore } } } /** * Checks whether two LatLngBounds intersect. * * @return true if the given bounds intersect. */ public static boolean boundsIntersect(LatLngBounds first, LatLngBounds second) { // First check if the latitudes are not intersecting. if (first.northeast.latitude < second.southwest.latitude || first.southwest.latitude > second.northeast.latitude) { return false; } // Next, check if the longitudes are not intersecting. if (first.northeast.longitude < second.southwest.longitude || first.southwest.longitude > second.northeast.longitude) { return false; } // Both latitude and longitude are intersecting. return true; } public static GeoJsonLayer processGeoJson(Context context, GoogleMap mMap, JSONObject j) { GeoJsonLayer layer = new GeoJsonLayer(mMap, j); Iterator<GeoJsonFeature> iterator = layer.getFeatures().iterator(); final IconGenerator labelIconGenerator = MapUtils.getLabelIconGenerator(context); while (iterator.hasNext()) { GeoJsonFeature feature = iterator.next(); // get data final String id = feature.getProperty("id"); final String typeString = feature.getProperty("type"); final int type = MapUtils.detectMarkerType(typeString); final String label = feature.getProperty("title"); GeoJsonPointStyle pointStyle = new GeoJsonPointStyle(); if (type == MarkerModel.TYPE_LABEL) { // Label markers contain the label as its icon pointStyle = MapUtils.createLabelMarker(labelIconGenerator, id, label); } else if (type == MarkerModel.TYPE_ICON) { // An icon marker is mapped to a drawable based on its full type name pointStyle = MapUtils.createIconMarker(typeString, id, false, context); } else if (type != MarkerModel.TYPE_INACTIVE) { // All other markers (that are not inactive) contain a pin icon pointStyle = MapUtils.createPinMarker(context, id); } // If the marker is invalid (e.g. the icon does not exist), remove it from the map. if (pointStyle == null) { iterator.remove(); } else { pointStyle.setVisible(true); feature.setPointStyle(pointStyle); } } return layer; } }
package com.algotrado.mt4.tal.strategy.check.pattern; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.reflections.Reflections; import org.reflections.scanners.ResourcesScanner; import org.reflections.scanners.SubTypesScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.reflections.util.FilterBuilder; import com.algotrado.mt4.impl.Pattern; import com.algotrado.mt4.tal.patterns.range.RangePattern; import com.algotrado.mt4.tal.strategy.Strategy; public class DoubleReversalPatternStrategy extends Strategy { private static final int MAX_NUM_OF_CANDLES_BETWEEN_PATTERNS = 30; private static List<Pattern> reversalPatterns; static { reversalPatterns = new ArrayList<Pattern>(); List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>(); classLoadersList.add(ClasspathHelper.getContextClassLoader()); classLoadersList.add(ClasspathHelper.getStaticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScanners(new SubTypesScanner(/*false *//* don't exclude Object.class */), new ResourcesScanner()) .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0]))) .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.algotrado.mt4.tal.patterns.reversal")))); Set<Class<? extends Pattern>> classes = reflections.getSubTypesOf(Pattern.class); for (Class<? extends Pattern> currClass : classes) { try { reversalPatterns.add(currClass.getConstructor(new Class<?> [0]).newInstance(new Object[0])); } catch (NoSuchMethodException | SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(classes); System.out.println(reversalPatterns); } @Override public boolean isLongStrategyPattern(SingleCandleBarData[] candles, int index, double pipsValue) { if (index < 20) { return false; } boolean isFirstReversalPattern = false; boolean isLastReversalPattern = false; boolean isLastReversalPatternCandleTouch2LowerBands = false; boolean isLastReversalPatternCandleTouch1LowerBand = false; double lastPatternLow = 0, lastPatternRSI = 0; int numOfCandlesInLastPattern = 0; for (Pattern reversal : reversalPatterns) { if (reversal.isBullishReversalPattern(candles, index, pipsValue)) { lastPatternLow = reversal.getPatternLow(candles, index, pipsValue); lastPatternRSI = candles[index].getRsi(); numOfCandlesInLastPattern = reversal.getNumOfCandlesInPattern(); for (int i = 0; i < numOfCandlesInLastPattern; i++) { if (candles[index - i].getRsi() < lastPatternRSI) { lastPatternRSI = candles[index - i].getRsi(); } if (!isLastReversalPatternCandleTouch2LowerBands && candles[index - i].getLow() <= candles[index - i].getLower10Bollinger() && candles[index - i].getLow() <= candles[index - i].getLower20Bollinger()) { isLastReversalPatternCandleTouch2LowerBands = true; } else if ((candles[index - i].getLow() <= candles[index - i].getLower10Bollinger()) || (candles[index - i].getLow() <= candles[index - i].getLower20Bollinger())) { isLastReversalPatternCandleTouch1LowerBand = true; isLastReversalPatternCandleTouch2LowerBands = true; } } isLastReversalPattern = (lastPatternRSI > 30) && isLastReversalPatternCandleTouch2LowerBands && isLastReversalPatternCandleTouch1LowerBand; break; } } if (!isLastReversalPattern) { return false; } // first pattern double firstPatternLow, firstPatternRSI; int numOfCandlesInFirstPattern = 0; boolean isFirstReversalPatternCandleTouch2LowerBands = false; boolean isFirstReversalPatternCandleTouch1LowerBand = false; int numOfIllegalFirstPatterns = 0; for (int j = numOfCandlesInLastPattern; index - j >= 20 && j <= MAX_NUM_OF_CANDLES_BETWEEN_PATTERNS; j++) { for (Pattern reversal : reversalPatterns) { if (reversal.isBullishReversalPattern(candles, index - j, pipsValue)) { firstPatternLow = reversal.getPatternLow(candles, index - j, pipsValue); firstPatternRSI = candles[index].getRsi(); numOfCandlesInFirstPattern = reversal.getNumOfCandlesInPattern(); for (int i = 0; (i < numOfCandlesInFirstPattern) && ((index - j - i) >= 0); i++) { if (candles[index - j - i].getRsi() < firstPatternRSI) { firstPatternRSI = candles[index - j - i].getRsi(); } if (!isFirstReversalPatternCandleTouch2LowerBands && candles[index - j - i].getLow() <= candles[index - j - i].getLower10Bollinger() && candles[index - j - i].getLow() <= candles[index - j - i].getLower20Bollinger()) { isFirstReversalPatternCandleTouch2LowerBands = true; } else if (candles[index - j - i].getLow() <= candles[index - j - i].getLower10Bollinger() || candles[index - j - i].getLow() <= candles[index - j - i].getLower20Bollinger()) { isFirstReversalPatternCandleTouch1LowerBand = true; isFirstReversalPatternCandleTouch2LowerBands = true; } // } isFirstReversalPattern = (firstPatternRSI < 30) && ((firstPatternLow <= lastPatternLow) || (Math.abs(firstPatternLow - lastPatternLow) <= 5 * pipsValue)) && isFirstReversalPatternCandleTouch2LowerBands && isFirstReversalPatternCandleTouch1LowerBand; if (isFirstReversalPattern) { System.out.println("isFirstReversalPattern: RSI First Pattern = " + firstPatternRSI); System.out.println(" = " + firstPatternRSI); } if (!isFirstReversalPattern && isFirstReversalPatternCandleTouch2LowerBands && isFirstReversalPatternCandleTouch1LowerBand) { numOfIllegalFirstPatterns++; } if ((numOfIllegalFirstPatterns > 3 && !isFirstReversalPattern) || (!isFirstReversalPattern && !((firstPatternLow <= lastPatternLow) || (Math.abs(firstPatternLow - lastPatternLow) <= 5 * pipsValue))) ) { return false; } break; } } if (isFirstReversalPattern) { break; } } //look for previous long pattern on Lower bands and check for RSI Values. return isFirstReversalPattern; } @Override public boolean isShortStrategyPattern(SingleCandleBarData[] candles, int index, double pipsValue) { if (index < 20) { return false; } boolean isFirstReversalPattern = false; boolean isLastReversalPattern = false; boolean isLastReversalPatternCandleTouch2HigherBands = false; boolean isLastReversalPatternCandleTouch1HigherBand = false; double lastPatternHigh = 0, lastPatternRSI = 0; int numOfCandlesInLastPattern = 0; for (Pattern reversal : reversalPatterns) { if (reversal.isBearishReversalPattern(candles, index, pipsValue)) { lastPatternHigh = reversal.getPatternHigh(candles, index, pipsValue); lastPatternRSI = candles[index].getRsi(); numOfCandlesInLastPattern = reversal.getNumOfCandlesInPattern(); for (int i = 0; i < numOfCandlesInLastPattern; i++) { if (candles[index - i].getRsi() > lastPatternRSI) { lastPatternRSI = candles[index - i].getRsi(); } if (!isLastReversalPatternCandleTouch2HigherBands && candles[index - i].getHigh() >= candles[index - i].getHigher10Bollinger() && candles[index - i].getHigh() >= candles[index - i].getHigher20Bollinger()) { isLastReversalPatternCandleTouch2HigherBands = true; } else if ((candles[index - i].getHigh() >= candles[index - i].getHigher10Bollinger()) || (candles[index - i].getHigh() >= candles[index - i].getHigher20Bollinger())) { isLastReversalPatternCandleTouch1HigherBand = true; isLastReversalPatternCandleTouch2HigherBands = true; } } isLastReversalPattern = (lastPatternRSI < 70) && isLastReversalPatternCandleTouch2HigherBands && isLastReversalPatternCandleTouch1HigherBand; break; } } if (!isLastReversalPattern) { return false; } // first pattern double firstPatternHigh, firstPatternRSI; int numOfCandlesInFirstPattern = 0; boolean isFirstReversalPatternCandleTouch2HigherBands = false; boolean isFirstReversalPatternCandleTouch1HigherBand = false; int numOfIllegalFirstPatterns = 0; for (int j = numOfCandlesInLastPattern; index - j >= 20 && j <= MAX_NUM_OF_CANDLES_BETWEEN_PATTERNS; j++) { for (Pattern reversal : reversalPatterns) { if (reversal.isBearishReversalPattern(candles, index - j, pipsValue)) { firstPatternHigh = reversal.getPatternHigh(candles, index - j, pipsValue); firstPatternRSI = candles[index].getRsi(); numOfCandlesInFirstPattern = reversal.getNumOfCandlesInPattern(); for (int i = 0; (i < numOfCandlesInFirstPattern) && ((index - j - i) >= 0); i++) { if (candles[index - j - i].getRsi() > firstPatternRSI) { firstPatternRSI = candles[index - j - i].getRsi(); } if (!isFirstReversalPatternCandleTouch2HigherBands && candles[index - j - i].getHigh() >= candles[index - j - i].getHigher10Bollinger() && candles[index - j - i].getHigh() >= candles[index - j - i].getHigher20Bollinger()) { isFirstReversalPatternCandleTouch2HigherBands = true; } else if (candles[index - j - i].getHigh() >= candles[index - j - i].getHigher10Bollinger() || candles[index - j - i].getHigh() >= candles[index - j - i].getHigher20Bollinger()) { isFirstReversalPatternCandleTouch1HigherBand = true; isFirstReversalPatternCandleTouch2HigherBands = true; } // } isFirstReversalPattern = (firstPatternRSI > 70) && ((firstPatternHigh >= lastPatternHigh) || (Math.abs(firstPatternHigh - lastPatternHigh) <= 5 * pipsValue)) && isFirstReversalPatternCandleTouch2HigherBands && isFirstReversalPatternCandleTouch1HigherBand; if (isFirstReversalPattern) { System.out.println("isFirstReversalPattern: RSI First Pattern = " + firstPatternRSI); System.out.println(" = " + firstPatternRSI); } if (!isFirstReversalPattern && isFirstReversalPatternCandleTouch2HigherBands && isFirstReversalPatternCandleTouch1HigherBand) { numOfIllegalFirstPatterns++; } if ((numOfIllegalFirstPatterns > 3 && !isFirstReversalPattern) || (!isFirstReversalPattern && !((firstPatternHigh >= lastPatternHigh) || (Math.abs(firstPatternHigh - lastPatternHigh) <= 5 * pipsValue))) ) { return false; } break; } } if (isFirstReversalPattern) { break; } } //look for previous long pattern on Higher bands and check for RSI Values. return isFirstReversalPattern; } }
package stroom.config.global.impl; import stroom.config.common.UriFactory; import stroom.config.global.shared.ConfigProperty; import stroom.config.global.shared.ConfigPropertyValidationException; import stroom.config.global.shared.GlobalConfigCriteria; import stroom.config.global.shared.GlobalConfigResource; import stroom.config.global.shared.ListConfigResponse; import stroom.config.global.shared.OverrideValue; import stroom.event.logging.api.StroomEventLoggingService; import stroom.event.logging.api.StroomEventLoggingUtil; import stroom.event.logging.rs.api.AutoLogged; import stroom.event.logging.rs.api.AutoLogged.OperationType; import stroom.node.api.NodeInfo; import stroom.node.api.NodeService; import stroom.ui.config.shared.UiConfig; import stroom.util.logging.LambdaLogger; import stroom.util.logging.LambdaLoggerFactory; import stroom.util.logging.LogUtil; import stroom.util.rest.RestUtil; import stroom.util.shared.PropertyPath; import stroom.util.shared.ResourcePaths; import com.codahale.metrics.annotation.Timed; import com.google.common.base.Strings; import event.logging.ComplexLoggedOutcome; import event.logging.Query; import event.logging.SearchEventAction; import event.logging.UpdateEventAction; import java.math.BigInteger; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Provider; import javax.ws.rs.NotFoundException; import javax.ws.rs.client.Entity; import javax.ws.rs.client.SyncInvoker; import javax.ws.rs.core.GenericType; @AutoLogged public class GlobalConfigResourceImpl implements GlobalConfigResource { private static final LambdaLogger LOGGER = LambdaLoggerFactory.getLogger(GlobalConfigResourceImpl.class); private final Provider<StroomEventLoggingService> stroomEventLoggingServiceProvider; private final Provider<GlobalConfigService> globalConfigServiceProvider; private final Provider<NodeService> nodeServiceProvider; private final Provider<UiConfig> uiConfig; private final Provider<UriFactory> uriFactory; private final Provider<NodeInfo> nodeInfoProvider; @Inject GlobalConfigResourceImpl(final Provider<StroomEventLoggingService> stroomEventLoggingServiceProvider, final Provider<GlobalConfigService> globalConfigServiceProvider, final Provider<NodeService> nodeServiceProvider, final Provider<UiConfig> uiConfig, final Provider<UriFactory> uriFactory, final Provider<NodeInfo> nodeInfoProvider) { this.stroomEventLoggingServiceProvider = stroomEventLoggingServiceProvider; this.globalConfigServiceProvider = Objects.requireNonNull(globalConfigServiceProvider); this.nodeServiceProvider = Objects.requireNonNull(nodeServiceProvider); this.uiConfig = uiConfig; this.uriFactory = uriFactory; this.nodeInfoProvider = nodeInfoProvider; } @AutoLogged(OperationType.MANUALLY_LOGGED) @Timed @Override public ListConfigResponse list(final GlobalConfigCriteria criteria) { return listWithLogging(criteria); } private ListConfigResponse listWithoutLogging(final GlobalConfigCriteria criteria) { final ListConfigResponse list = globalConfigServiceProvider.get().list(criteria); List<ConfigProperty> values = list.getValues(); values = values.stream() .map(this::sanitise) .collect(Collectors.toList()); return new ListConfigResponse( values, list.getPageResponse(), nodeInfoProvider.get().getThisNodeName(), list.getQualifiedFilterInput()); } private ListConfigResponse listWithLogging(final GlobalConfigCriteria criteria) { LOGGER.debug("list called for {}", criteria); final StroomEventLoggingService eventLoggingService = stroomEventLoggingServiceProvider.get(); return eventLoggingService.loggedWorkBuilder() .withTypeId(StroomEventLoggingUtil.buildTypeId(this, "list")) .withDescription("List filtered configuration properties") .withDefaultEventAction(SearchEventAction.builder() .withQuery(buildRawQuery(criteria.getQuickFilterInput())) .build()) .withComplexLoggedResult(searchEventAction -> { // Do the work final ListConfigResponse sanitisedResult = listWithoutLogging(criteria); // Ignore the previous searchEventAction as it didn't have anything useful on it final SearchEventAction newSearchEventAction = SearchEventAction.builder() .withQuery(buildRawQuery(sanitisedResult.getQualifiedFilterInput())) .withResultPage(StroomEventLoggingUtil.createResultPage(sanitisedResult)) .withTotalResults(BigInteger.valueOf(sanitisedResult.size())) .build(); return ComplexLoggedOutcome.success(sanitisedResult, newSearchEventAction); }) .getResultAndLog(); } // logging handled by initial call to list() on ui node. Don't want to log the call to each node @AutoLogged(OperationType.UNLOGGED) @Timed @Override public ListConfigResponse listByNode(final String nodeName, final GlobalConfigCriteria criteria) { LOGGER.debug("listByNode called for node: {}, criteria: {}", nodeName, criteria); return nodeServiceProvider.get().remoteRestResult( nodeName, ListConfigResponse.class, () -> ResourcePaths.buildAuthenticatedApiPath( GlobalConfigResource.BASE_PATH, GlobalConfigResource.NODE_PROPERTIES_SUB_PATH, nodeName), () -> listWithoutLogging(criteria), builder -> builder.post(Entity.json(criteria))); } @Timed @Override public ConfigProperty getPropertyByName(final String propertyPath) { RestUtil.requireNonNull(propertyPath, "propertyPath not supplied"); Optional<ConfigProperty> optConfigProperty = globalConfigServiceProvider.get().fetch( PropertyPath.fromPathString(propertyPath)); optConfigProperty = sanitise(optConfigProperty); return optConfigProperty.orElseThrow(NotFoundException::new); } @Timed public OverrideValue<String> getYamlValueByName(final String propertyPath) { RestUtil.requireNonNull(propertyPath, "propertyPath not supplied"); Optional<ConfigProperty> optConfigProperty = globalConfigServiceProvider.get().fetch( PropertyPath.fromPathString(propertyPath)); optConfigProperty = sanitise(optConfigProperty); return optConfigProperty .map(ConfigProperty::getYamlOverrideValue) .orElseThrow(() -> new NotFoundException(LogUtil.message("Property {} not found", propertyPath))); } private Optional<ConfigProperty> sanitise(final Optional<ConfigProperty> optionalConfigProperty) { return optionalConfigProperty.map(this::sanitise); } private ConfigProperty sanitise(final ConfigProperty configProperty) { if (configProperty.isPassword()) { configProperty.setDefaultValue(null); if (configProperty.getDatabaseOverrideValue().isHasOverride()) { configProperty.setDatabaseOverrideValue(OverrideValue.withNullValue(String.class)); } else { configProperty.setDatabaseOverrideValue(OverrideValue.unSet(String.class)); } if (configProperty.getYamlOverrideValue().isHasOverride()) { configProperty.setYamlOverrideValue(OverrideValue.withNullValue(String.class)); } else { configProperty.setYamlOverrideValue(OverrideValue.unSet(String.class)); } } return configProperty; } @Timed @Override public OverrideValue<String> getYamlValueByNodeAndName(final String propertyPath, final String nodeName) { RestUtil.requireNonNull(propertyPath, "propertyName not supplied"); RestUtil.requireNonNull(nodeName, "nodeName not supplied"); return nodeServiceProvider.get().remoteRestResult( nodeName, () -> ResourcePaths.buildAuthenticatedApiPath( GlobalConfigResource.BASE_PATH, GlobalConfigResource.CLUSTER_PROPERTIES_SUB_PATH, propertyPath, GlobalConfigResource.YAML_OVERRIDE_VALUE_SUB_PATH, nodeName), () -> getYamlValueByName(propertyPath), SyncInvoker::get, response -> response.readEntity(new GenericType<OverrideValue<String>>() { })); } @Timed @Override public ConfigProperty create(final ConfigProperty configProperty) { RestUtil.requireNonNull(configProperty, "configProperty not supplied"); RestUtil.requireNonNull(configProperty.getName(), "configProperty name cannot be null"); try { return globalConfigServiceProvider.get().update(configProperty); } catch (ConfigPropertyValidationException e) { throw RestUtil.badRequest(e); } } @AutoLogged(OperationType.MANUALLY_LOGGED) @Timed @Override public ConfigProperty update(final String propertyName, final ConfigProperty configProperty) { RestUtil.requireNonNull(propertyName, "propertyName not supplied"); RestUtil.requireNonNull(configProperty, "configProperty not supplied"); if (!propertyName.equals(configProperty.getNameAsString())) { throw RestUtil.badRequest(LogUtil.message("Property names don't match, {} & {}", propertyName, configProperty.getNameAsString())); } try { final GlobalConfigService globalConfigService = globalConfigServiceProvider.get(); final StroomEventLoggingService stroomEventLoggingService = stroomEventLoggingServiceProvider.get(); return stroomEventLoggingService.loggedWorkBuilder() .withTypeId(StroomEventLoggingUtil.buildTypeId(this, "update")) .withDescription("Updating property " + configProperty.getNameAsString()) .withDefaultEventAction(UpdateEventAction.builder() .withAfter(stroomEventLoggingService.convertToMulti(() -> configProperty)) .build()) .withComplexLoggedResult(eventAction -> { // Do the update final ConfigProperty persistedProperty = globalConfigService.update(configProperty); return ComplexLoggedOutcome.success( persistedProperty, stroomEventLoggingService.buildUpdateEventAction( () -> { if (configProperty.getId() == null) { return null; } return globalConfigService.fetch(configProperty.getId()) .orElse(null); }, () -> persistedProperty)); }) .getResultAndLog(); } catch (ConfigPropertyValidationException e) { throw RestUtil.badRequest(e); } } @AutoLogged(OperationType.UNLOGGED) // Called constantly by UI code not user. No need to log. @Timed @Override public UiConfig fetchUiConfig() { return uiConfig.get(); } private Query buildRawQuery(final String userInput) { return Strings.isNullOrEmpty(userInput) ? new Query() : Query.builder() .withRaw("Configuration property matches \"" + Objects.requireNonNullElse(userInput, "") + "\"") .build(); } }
/* * 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.druid.query.aggregation.last; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import org.apache.druid.collections.SerializablePair; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.java.util.common.UOE; import org.apache.druid.query.aggregation.AggregateCombiner; import org.apache.druid.query.aggregation.Aggregator; import org.apache.druid.query.aggregation.AggregatorFactory; import org.apache.druid.query.aggregation.AggregatorUtil; import org.apache.druid.query.aggregation.BufferAggregator; import org.apache.druid.query.aggregation.first.LongFirstAggregatorFactory; import org.apache.druid.query.monomorphicprocessing.RuntimeShapeInspector; import org.apache.druid.segment.BaseLongColumnValueSelector; import org.apache.druid.segment.ColumnSelectorFactory; import org.apache.druid.segment.ColumnValueSelector; import org.apache.druid.segment.NilColumnValueSelector; import org.apache.druid.segment.column.ColumnHolder; import javax.annotation.Nullable; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; public class LongLastAggregatorFactory extends AggregatorFactory { private static final Aggregator NIL_AGGREGATOR = new LongLastAggregator( NilColumnValueSelector.instance(), NilColumnValueSelector.instance() ) { @Override public void aggregate() { // no-op } }; private static final BufferAggregator NIL_BUFFER_AGGREGATOR = new LongLastBufferAggregator( NilColumnValueSelector.instance(), NilColumnValueSelector.instance() ) { @Override public void aggregate(ByteBuffer buf, int position) { // no-op } }; private final String fieldName; private final String name; @JsonCreator public LongLastAggregatorFactory( @JsonProperty("name") String name, @JsonProperty("fieldName") final String fieldName ) { Preconditions.checkNotNull(name, "Must have a valid, non-null aggregator name"); Preconditions.checkNotNull(fieldName, "Must have a valid, non-null fieldName"); this.name = name; this.fieldName = fieldName; } @Override public Aggregator factorize(ColumnSelectorFactory metricFactory) { final BaseLongColumnValueSelector valueSelector = metricFactory.makeColumnValueSelector(fieldName); if (valueSelector instanceof NilColumnValueSelector) { return NIL_AGGREGATOR; } else { return new LongLastAggregator( metricFactory.makeColumnValueSelector(ColumnHolder.TIME_COLUMN_NAME), valueSelector ); } } @Override public BufferAggregator factorizeBuffered(ColumnSelectorFactory metricFactory) { final BaseLongColumnValueSelector valueSelector = metricFactory.makeColumnValueSelector(fieldName); if (valueSelector instanceof NilColumnValueSelector) { return NIL_BUFFER_AGGREGATOR; } else { return new LongLastBufferAggregator( metricFactory.makeColumnValueSelector(ColumnHolder.TIME_COLUMN_NAME), valueSelector ); } } @Override public Comparator getComparator() { return LongFirstAggregatorFactory.VALUE_COMPARATOR; } @Override @Nullable public Object combine(@Nullable Object lhs, @Nullable Object rhs) { if (rhs == null) { return lhs; } if (lhs == null) { return rhs; } Long leftTime = ((SerializablePair<Long, Long>) lhs).lhs; Long rightTime = ((SerializablePair<Long, Long>) rhs).lhs; if (leftTime >= rightTime) { return lhs; } else { return rhs; } } @Override public AggregateCombiner makeAggregateCombiner() { throw new UOE("LongLastAggregatorFactory is not supported during ingestion for rollup"); } @Override public AggregatorFactory getCombiningFactory() { return new LongLastAggregatorFactory(name, name) { @Override public Aggregator factorize(ColumnSelectorFactory metricFactory) { final ColumnValueSelector<SerializablePair<Long, Long>> selector = metricFactory.makeColumnValueSelector(name); return new LongLastAggregator(null, null) { @Override public void aggregate() { SerializablePair<Long, Long> pair = selector.getObject(); if (pair.lhs >= lastTime) { lastTime = pair.lhs; if (pair.rhs != null) { lastValue = pair.rhs; rhsNull = false; } else { rhsNull = true; } } } }; } @Override public BufferAggregator factorizeBuffered(ColumnSelectorFactory metricFactory) { final ColumnValueSelector<SerializablePair<Long, Long>> selector = metricFactory.makeColumnValueSelector(name); return new LongLastBufferAggregator(null, null) { @Override public void putValue(ByteBuffer buf, int position) { SerializablePair<Long, Long> pair = selector.getObject(); buf.putLong(position, pair.rhs); } @Override public void aggregate(ByteBuffer buf, int position) { SerializablePair<Long, Long> pair = selector.getObject(); long lastTime = buf.getLong(position); if (pair.lhs >= lastTime) { if (pair.rhs != null) { updateTimeWithValue(buf, position, pair.lhs); } else { updateTimeWithNull(buf, position, pair.lhs); } } } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("selector", selector); } }; } }; } @Override public List<AggregatorFactory> getRequiredColumns() { return Collections.singletonList(new LongLastAggregatorFactory(fieldName, fieldName)); } @Override public Object deserialize(Object object) { Map map = (Map) object; if (map.get("rhs") == null) { return new SerializablePair<>(((Number) map.get("lhs")).longValue(), null); } return new SerializablePair<>(((Number) map.get("lhs")).longValue(), ((Number) map.get("rhs")).longValue()); } @Override @Nullable public Object finalizeComputation(@Nullable Object object) { return object == null ? null : ((SerializablePair<Long, Long>) object).rhs; } @Override @JsonProperty public String getName() { return name; } @JsonProperty public String getFieldName() { return fieldName; } @Override public List<String> requiredFields() { return Arrays.asList(ColumnHolder.TIME_COLUMN_NAME, fieldName); } @Override public byte[] getCacheKey() { byte[] fieldNameBytes = StringUtils.toUtf8(fieldName); return ByteBuffer.allocate(1 + fieldNameBytes.length) .put(AggregatorUtil.LONG_LAST_CACHE_TYPE_ID) .put(fieldNameBytes) .array(); } @Override public String getTypeName() { // if we don't pretend to be a primitive, group by v1 gets sad and doesn't work because no complex type serde return "long"; } @Override public int getMaxIntermediateSize() { // timestamp, is null, value return Long.BYTES + Byte.BYTES + Long.BYTES; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LongLastAggregatorFactory that = (LongLastAggregatorFactory) o; return name.equals(that.name) && fieldName.equals(that.fieldName); } @Override public int hashCode() { return Objects.hash(name, fieldName); } @Override public String toString() { return "LongLastAggregatorFactory{" + "name='" + name + '\'' + ", fieldName='" + fieldName + '\'' + '}'; } }
/* * 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.accumulo.test; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.IOException; import java.util.Map.Entry; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.TreeSet; import org.apache.accumulo.core.cli.ClientOpts; import org.apache.accumulo.core.client.Accumulo; import org.apache.accumulo.core.client.AccumuloClient; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.MutationsRejectedException; import org.apache.accumulo.core.client.TableExistsException; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.client.security.SecurityErrorCode; import org.apache.accumulo.core.clientImpl.ClientContext; import org.apache.accumulo.core.conf.ClientProperty; import org.apache.accumulo.core.conf.DefaultConfiguration; import org.apache.accumulo.core.crypto.CryptoServiceFactory; import org.apache.accumulo.core.data.ConstraintViolationSummary; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.TabletId; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.file.FileOperations; import org.apache.accumulo.core.file.FileSKVWriter; import org.apache.accumulo.core.file.rfile.RFile; import org.apache.accumulo.core.security.Authorizations; import org.apache.accumulo.core.security.ColumnVisibility; import org.apache.accumulo.core.util.FastFormat; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.Text; import com.beust.jcommander.Parameter; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; public class TestIngest { public static final Authorizations AUTHS = new Authorizations("L1", "L2", "G1", "GROUP2"); public static class IngestParams { public Properties clientProps = new Properties(); public String tableName = "test_ingest"; public boolean createTable = false; public int numsplits = 1; public int startRow = 0; public int rows = 100000; public int cols = 1; public Integer random = null; public int dataSize = 1000; public boolean delete = false; public long timestamp = -1; public String outputFile = null; public int stride; public String columnFamily = "colf"; public ColumnVisibility columnVisibility = new ColumnVisibility(); public IngestParams(Properties props) { clientProps = props; } public IngestParams(Properties props, String table) { this(props); tableName = table; } public IngestParams(Properties props, String table, int rows) { this(props, table); this.rows = rows; } } public static class Opts extends ClientOpts { @Parameter(names = "--table", description = "table to use") String tableName = "test_ingest"; @Parameter(names = "--createTable") boolean createTable = false; @Parameter(names = "--splits", description = "the number of splits to use when creating the table") int numsplits = 1; @Parameter(names = "--start", description = "the starting row number") int startRow = 0; @Parameter(names = "--rows", description = "the number of rows to ingest") int rows = 100000; @Parameter(names = "--cols", description = "the number of columns to ingest per row") int cols = 1; @Parameter(names = "--random", description = "insert random rows and use" + " the given number to seed the psuedo-random number generator") Integer random = null; @Parameter(names = "--size", description = "the size of the value to ingest") int dataSize = 1000; @Parameter(names = "--delete", description = "delete values instead of inserting them") boolean delete = false; @Parameter(names = {"-ts", "--timestamp"}, description = "timestamp to use for all values") long timestamp = -1; @Parameter(names = "--rfile", description = "generate data into a file that can be imported") String outputFile = null; @Parameter(names = "--stride", description = "the difference between successive row ids") int stride; @Parameter(names = {"-cf", "--columnFamily"}, description = "place columns in this column family") String columnFamily = "colf"; @Parameter(names = {"-cv", "--columnVisibility"}, description = "place columns in this column family", converter = VisibilityConverter.class) ColumnVisibility columnVisibility = new ColumnVisibility(); protected void populateIngestPrams(IngestParams params) { params.createTable = createTable; params.numsplits = numsplits; params.startRow = startRow; params.rows = rows; params.cols = cols; params.random = random; params.dataSize = dataSize; params.delete = delete; params.timestamp = timestamp; params.outputFile = outputFile; params.stride = stride; params.columnFamily = columnFamily; params.columnVisibility = columnVisibility; } public IngestParams getIngestPrams() { IngestParams params = new IngestParams(getClientProps(), tableName); populateIngestPrams(params); return params; } } public static void createTable(AccumuloClient client, IngestParams params) throws AccumuloException, AccumuloSecurityException, TableExistsException { if (params.createTable) { TreeSet<Text> splits = getSplitPoints(params.startRow, params.startRow + params.rows, params.numsplits); if (!client.tableOperations().exists(params.tableName)) { client.tableOperations().create(params.tableName); } try { client.tableOperations().addSplits(params.tableName, splits); } catch (TableNotFoundException ex) { // unlikely throw new RuntimeException(ex); } } } public static TreeSet<Text> getSplitPoints(long start, long end, long numsplits) { long splitSize = (end - start) / numsplits; long pos = start + splitSize; TreeSet<Text> splits = new TreeSet<>(); while (pos < end) { splits.add(new Text(String.format("row_%010d", pos))); pos += splitSize; } return splits; } public static byte[][] generateValues(int dataSize) { byte[][] bytevals = new byte[10][]; byte[] letters = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}; for (int i = 0; i < 10; i++) { bytevals[i] = new byte[dataSize]; for (int j = 0; j < dataSize; j++) { bytevals[i][j] = letters[i]; } } return bytevals; } private static byte[] ROW_PREFIX = "row_".getBytes(UTF_8); private static byte[] COL_PREFIX = "col_".getBytes(UTF_8); public static Text generateRow(int rowid, int startRow) { return new Text(FastFormat.toZeroPaddedString(rowid + startRow, 10, 10, ROW_PREFIX)); } public static byte[] genRandomValue(Random random, byte[] dest, int seed, int row, int col) { random.setSeed((row ^ seed) ^ col); random.nextBytes(dest); toPrintableChars(dest); return dest; } public static void toPrintableChars(byte[] dest) { // transform to printable chars for (int i = 0; i < dest.length; i++) { dest[i] = (byte) (((0xff & dest[i]) % 92) + ' '); } } public static void main(String[] args) throws Exception { Opts opts = new Opts(); opts.parseArgs(TestIngest.class.getSimpleName(), args); try (AccumuloClient client = Accumulo.newClient().from(opts.getClientProps()).build()) { ingest(client, opts.getIngestPrams()); } } @SuppressFBWarnings(value = "PREDICTABLE_RANDOM", justification = "predictable random is okay for testing") public static void ingest(AccumuloClient accumuloClient, FileSystem fs, IngestParams params) throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException, MutationsRejectedException, TableExistsException { long stopTime; byte[][] bytevals = generateValues(params.dataSize); byte[] randomValue = new byte[params.dataSize]; Random random = new Random(); long bytesWritten = 0; createTable(accumuloClient, params); BatchWriter bw = null; FileSKVWriter writer = null; if (params.outputFile != null) { ClientContext cc = (ClientContext) accumuloClient; writer = FileOperations.getInstance().newWriterBuilder() .forFile(params.outputFile + "." + RFile.EXTENSION, fs, cc.getHadoopConf(), CryptoServiceFactory.newDefaultInstance()) .withTableConfiguration(DefaultConfiguration.getInstance()).build(); writer.startDefaultLocalityGroup(); } else { bw = accumuloClient.createBatchWriter(params.tableName); String principal = ClientProperty.AUTH_PRINCIPAL.getValue(params.clientProps); accumuloClient.securityOperations().changeUserAuthorizations(principal, AUTHS); } Text labBA = new Text(params.columnVisibility.getExpression()); long startTime = System.currentTimeMillis(); for (int i = 0; i < params.rows; i++) { int rowid; if (params.stride > 0) { rowid = ((i % params.stride) * (params.rows / params.stride)) + (i / params.stride); } else { rowid = i; } Text row = generateRow(rowid, params.startRow); Mutation m = new Mutation(row); for (int j = 0; j < params.cols; j++) { Text colf = new Text(params.columnFamily); Text colq = new Text(FastFormat.toZeroPaddedString(j, 7, 10, COL_PREFIX)); if (writer != null) { Key key = new Key(row, colf, colq, labBA); if (params.timestamp >= 0) { key.setTimestamp(params.timestamp); } else { key.setTimestamp(startTime); } if (params.delete) { key.setDeleted(true); } else { key.setDeleted(false); } bytesWritten += key.getSize(); if (params.delete) { writer.append(key, new Value(new byte[0])); } else { byte[] value; if (params.random != null) { value = genRandomValue(random, randomValue, params.random, rowid + params.startRow, j); } else { value = bytevals[j % bytevals.length]; } Value v = new Value(value); writer.append(key, v); bytesWritten += v.getSize(); } } else { Key key = new Key(row, colf, colq, labBA); bytesWritten += key.getSize(); if (params.delete) { if (params.timestamp >= 0) { m.putDelete(colf, colq, params.columnVisibility, params.timestamp); } else { m.putDelete(colf, colq, params.columnVisibility); } } else { byte[] value; if (params.random != null) { value = genRandomValue(random, randomValue, params.random, rowid + params.startRow, j); } else { value = bytevals[j % bytevals.length]; } bytesWritten += value.length; if (params.timestamp >= 0) { m.put(colf, colq, params.columnVisibility, params.timestamp, new Value(value, true)); } else { m.put(colf, colq, params.columnVisibility, new Value(value, true)); } } } } if (bw != null) { bw.addMutation(m); } } if (writer != null) { writer.close(); } else if (bw != null) { try { bw.close(); } catch (MutationsRejectedException e) { if (!e.getSecurityErrorCodes().isEmpty()) { for (Entry<TabletId,Set<SecurityErrorCode>> entry : e.getSecurityErrorCodes() .entrySet()) { System.err.println("ERROR : Not authorized to write to : " + entry.getKey() + " due to " + entry.getValue()); } } if (!e.getConstraintViolationSummaries().isEmpty()) { for (ConstraintViolationSummary cvs : e.getConstraintViolationSummaries()) { System.err.println("ERROR : Constraint violates : " + cvs); } } throw e; } } stopTime = System.currentTimeMillis(); int totalValues = params.rows * params.cols; double elapsed = (stopTime - startTime) / 1000.0; System.out.printf( "%,12d records written | %,8d records/sec | %,12d bytes written" + " | %,8d bytes/sec | %6.3f secs %n", totalValues, (int) (totalValues / elapsed), bytesWritten, (int) (bytesWritten / elapsed), elapsed); } public static void ingest(AccumuloClient c, IngestParams params) throws MutationsRejectedException, IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException, TableExistsException { ClientContext cc = (ClientContext) c; ingest(c, FileSystem.get(cc.getHadoopConf()), params); } }
/** */ package gluemodel.CIM.IEC61970.Informative.EnergyScheduling.impl; import gluemodel.CIM.IEC61970.Informative.EnergyScheduling.CurtailmentProfile; import gluemodel.CIM.IEC61970.Informative.EnergyScheduling.EnergySchedulingPackage; import gluemodel.CIM.IEC61970.Informative.EnergyScheduling.EnergyTransaction; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Curtailment Profile</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link gluemodel.CIM.IEC61970.Informative.EnergyScheduling.impl.CurtailmentProfileImpl#getEnergyTransaction <em>Energy Transaction</em>}</li> * </ul> * * @generated */ public class CurtailmentProfileImpl extends ProfileImpl implements CurtailmentProfile { /** * The cached value of the '{@link #getEnergyTransaction() <em>Energy Transaction</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEnergyTransaction() * @generated * @ordered */ protected EnergyTransaction energyTransaction; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CurtailmentProfileImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return EnergySchedulingPackage.Literals.CURTAILMENT_PROFILE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EnergyTransaction getEnergyTransaction() { if (energyTransaction != null && energyTransaction.eIsProxy()) { InternalEObject oldEnergyTransaction = (InternalEObject)energyTransaction; energyTransaction = (EnergyTransaction)eResolveProxy(oldEnergyTransaction); if (energyTransaction != oldEnergyTransaction) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, EnergySchedulingPackage.CURTAILMENT_PROFILE__ENERGY_TRANSACTION, oldEnergyTransaction, energyTransaction)); } } return energyTransaction; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EnergyTransaction basicGetEnergyTransaction() { return energyTransaction; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetEnergyTransaction(EnergyTransaction newEnergyTransaction, NotificationChain msgs) { EnergyTransaction oldEnergyTransaction = energyTransaction; energyTransaction = newEnergyTransaction; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, EnergySchedulingPackage.CURTAILMENT_PROFILE__ENERGY_TRANSACTION, oldEnergyTransaction, newEnergyTransaction); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEnergyTransaction(EnergyTransaction newEnergyTransaction) { if (newEnergyTransaction != energyTransaction) { NotificationChain msgs = null; if (energyTransaction != null) msgs = ((InternalEObject)energyTransaction).eInverseRemove(this, EnergySchedulingPackage.ENERGY_TRANSACTION__CURTAILMENT_PROFILES, EnergyTransaction.class, msgs); if (newEnergyTransaction != null) msgs = ((InternalEObject)newEnergyTransaction).eInverseAdd(this, EnergySchedulingPackage.ENERGY_TRANSACTION__CURTAILMENT_PROFILES, EnergyTransaction.class, msgs); msgs = basicSetEnergyTransaction(newEnergyTransaction, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EnergySchedulingPackage.CURTAILMENT_PROFILE__ENERGY_TRANSACTION, newEnergyTransaction, newEnergyTransaction)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case EnergySchedulingPackage.CURTAILMENT_PROFILE__ENERGY_TRANSACTION: if (energyTransaction != null) msgs = ((InternalEObject)energyTransaction).eInverseRemove(this, EnergySchedulingPackage.ENERGY_TRANSACTION__CURTAILMENT_PROFILES, EnergyTransaction.class, msgs); return basicSetEnergyTransaction((EnergyTransaction)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case EnergySchedulingPackage.CURTAILMENT_PROFILE__ENERGY_TRANSACTION: return basicSetEnergyTransaction(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case EnergySchedulingPackage.CURTAILMENT_PROFILE__ENERGY_TRANSACTION: if (resolve) return getEnergyTransaction(); return basicGetEnergyTransaction(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case EnergySchedulingPackage.CURTAILMENT_PROFILE__ENERGY_TRANSACTION: setEnergyTransaction((EnergyTransaction)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case EnergySchedulingPackage.CURTAILMENT_PROFILE__ENERGY_TRANSACTION: setEnergyTransaction((EnergyTransaction)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case EnergySchedulingPackage.CURTAILMENT_PROFILE__ENERGY_TRANSACTION: return energyTransaction != null; } return super.eIsSet(featureID); } } //CurtailmentProfileImpl
/* * Copyright 2015 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 net.kuujo.copycat.collections.state; import net.kuujo.copycat.*; import net.kuujo.copycat.io.BufferInput; import net.kuujo.copycat.io.BufferOutput; import net.kuujo.copycat.io.serializer.CopycatSerializable; import net.kuujo.copycat.io.serializer.SerializeWith; import net.kuujo.copycat.io.serializer.Serializer; import net.kuujo.copycat.raft.protocol.Command; import net.kuujo.copycat.raft.protocol.ConsistencyLevel; import net.kuujo.copycat.raft.protocol.Operation; import net.kuujo.copycat.raft.protocol.Query; import net.kuujo.copycat.util.BuilderPool; import java.util.concurrent.TimeUnit; /** * Distributed set commands. * * @author <a href="http://github.com/kuujo">Jordan Halterman</a> */ public class SetCommands { private SetCommands() { } /** * Abstract set command. */ private static abstract class SetCommand<V> implements Command<V>, CopycatSerializable { /** * Base set command builder. */ public static abstract class Builder<T extends Builder<T, U, V>, U extends SetCommand<V>, V> extends Command.Builder<T, U, V> { protected Builder(BuilderPool<T, U> pool) { super(pool); } } } /** * Abstract set query. */ private static abstract class SetQuery<V> implements Query<V>, CopycatSerializable { protected ConsistencyLevel consistency = ConsistencyLevel.LINEARIZABLE_LEASE; @Override public ConsistencyLevel consistency() { return consistency; } @Override public void writeObject(BufferOutput buffer, Serializer serializer) { buffer.writeByte(consistency.ordinal()); } @Override public void readObject(BufferInput buffer, Serializer serializer) { consistency = ConsistencyLevel.values()[buffer.readByte()]; } /** * Base set query builder. */ public static abstract class Builder<T extends Builder<T, U, V>, U extends SetQuery<V>, V> extends Query.Builder<T, U, V> { protected Builder(BuilderPool<T, U> pool) { super(pool); } /** * Sets the query consistency level. * * @param consistency The query consistency level. * @return The query builder. */ @SuppressWarnings("unchecked") public T withConsistency(ConsistencyLevel consistency) { query.consistency = consistency; return (T) this; } } } /** * Abstract value command. */ private static abstract class ValueCommand<V> extends SetCommand<V> { protected int value; /** * Returns the value. */ public int value() { return value; } @Override public void writeObject(BufferOutput buffer, Serializer serializer) { serializer.writeObject(value, buffer); } @Override public void readObject(BufferInput buffer, Serializer serializer) { value = serializer.readObject(buffer); } /** * Base key command builder. */ public static abstract class Builder<T extends Builder<T, U, V>, U extends ValueCommand<V>, V> extends SetCommand.Builder<T, U, V> { protected Builder(BuilderPool<T, U> pool) { super(pool); } /** * Sets the command value. * * @param value The command value * @return The command builder. */ @SuppressWarnings("unchecked") public T withValue(int value) { command.value = value; return (T) this; } } } /** * Abstract value query. */ private static abstract class ValueQuery<V> extends SetQuery<V> { protected int value; /** * Returns the value. */ public int value() { return value; } @Override public void writeObject(BufferOutput buffer, Serializer serializer) { super.writeObject(buffer, serializer); serializer.writeObject(value, buffer); } @Override public void readObject(BufferInput buffer, Serializer serializer) { super.readObject(buffer, serializer); value = serializer.readObject(buffer); } /** * Base value query builder. */ public static abstract class Builder<T extends Builder<T, U, V>, U extends ValueQuery<V>, V> extends SetQuery.Builder<T, U, V> { protected Builder(BuilderPool<T, U> pool) { super(pool); } /** * Sets the query value. * * @param value The query value * @return The query builder. */ @SuppressWarnings("unchecked") public T withValue(int value) { query.value = value; return (T) this; } } } /** * Contains value command. */ @SerializeWith(id=450) public static class Contains extends ValueQuery<Boolean> { /** * Returns a builder for this command. */ public static Builder builder() { return Operation.builder(Builder.class, Builder::new); } /** * Contains key builder. */ public static class Builder extends ValueQuery.Builder<Builder, Contains, Boolean> { public Builder(BuilderPool<Builder, Contains> pool) { super(pool); } @Override protected Contains create() { return new Contains(); } } } /** * TTL command. */ public static abstract class TtlCommand<V> extends ValueCommand<V> { protected long ttl; protected PersistenceMode mode = PersistenceMode.PERSISTENT; /** * Returns the time to live in milliseconds. * * @return The time to live in milliseconds. */ public long ttl() { return ttl; } /** * Returns the persistence mode. * * @return The persistence mode. */ public PersistenceMode mode() { return mode; } @Override public void writeObject(BufferOutput buffer, Serializer serializer) { super.writeObject(buffer, serializer); buffer.writeByte(mode.ordinal()).writeLong(ttl); } @Override public void readObject(BufferInput buffer, Serializer serializer) { super.readObject(buffer, serializer); mode = PersistenceMode.values()[buffer.readByte()]; ttl = buffer.readLong(); } /** * TTL command builder. */ public static abstract class Builder<T extends Builder<T, U, V>, U extends TtlCommand<V>, V> extends ValueCommand.Builder<T, U, V> { protected Builder(BuilderPool<T, U> pool) { super(pool); } /** * Sets the time to live. * * @param ttl The time to live in milliseconds.. * @return The command builder. */ public Builder withTtl(long ttl) { command.ttl = ttl; return this; } /** * Sets the time to live. * * @param ttl The time to live. * @param unit The time to live unit. * @return The command builder. */ public Builder withTtl(long ttl, TimeUnit unit) { command.ttl = unit.toMillis(ttl); return this; } /** * Sets the persistence mode. * * @param mode The persistence mode. * @return The command builder. */ public Builder withPersistence(PersistenceMode mode) { command.mode = mode; return this; } } } /** * Add command. */ @SerializeWith(id=451) public static class Add extends TtlCommand<Boolean> { /** * Returns a builder for this command. */ public static Builder builder() { return Operation.builder(Builder.class, Builder::new); } /** * Add command builder. */ public static class Builder extends TtlCommand.Builder<Builder, Add, Boolean> { public Builder(BuilderPool<Builder, Add> pool) { super(pool); } @Override protected Add create() { return new Add(); } } } /** * Remove command. */ @SerializeWith(id=452) public static class Remove extends ValueCommand<Boolean> { /** * Returns a builder for this command. */ public static Builder builder() { return Operation.builder(Builder.class, Builder::new); } /** * Remove command builder. */ public static class Builder extends ValueCommand.Builder<Builder, Remove, Boolean> { public Builder(BuilderPool<Builder, Remove> pool) { super(pool); } @Override protected Remove create() { return new Remove(); } } } /** * Size query. */ @SerializeWith(id=453) public static class Size extends SetQuery<Integer> { /** * Returns a builder for this query. */ public static Builder builder() { return Operation.builder(Builder.class, Builder::new); } /** * Size query builder. */ public static class Builder extends SetQuery.Builder<Builder, Size, Integer> { public Builder(BuilderPool<Builder, Size> pool) { super(pool); } @Override protected Size create() { return new Size(); } } } /** * Is empty query. */ @SerializeWith(id=454) public static class IsEmpty extends SetQuery<Boolean> { /** * Returns a builder for this query. */ public static Builder builder() { return Operation.builder(Builder.class, Builder::new); } /** * Is empty query builder. */ public static class Builder extends SetQuery.Builder<Builder, IsEmpty, Boolean> { public Builder(BuilderPool<Builder, IsEmpty> pool) { super(pool); } @Override protected IsEmpty create() { return new IsEmpty(); } } } /** * Clear command. */ @SerializeWith(id=455) public static class Clear extends SetCommand<Void> { /** * Returns a builder for this command. */ public static Builder builder() { return Operation.builder(Builder.class, Builder::new); } @Override public void writeObject(BufferOutput buffer, Serializer serializer) { } @Override public void readObject(BufferInput buffer, Serializer serializer) { } /** * Get command builder. */ public static class Builder extends SetCommand.Builder<Builder, Clear, Void> { public Builder(BuilderPool<Builder, Clear> pool) { super(pool); } @Override protected Clear create() { return new Clear(); } } } }
package uristqwerty.CraftGuide.dump; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriter; import javax.imageio.stream.FileImageOutputStream; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import uristqwerty.CraftGuide.CraftGuideLog; import uristqwerty.CraftGuide.GuiCraftGuide; import uristqwerty.CraftGuide.Pair; import uristqwerty.CraftGuide.Recipe; import uristqwerty.CraftGuide.api.CraftGuideRecipe; import uristqwerty.CraftGuide.api.ItemSlot; import uristqwerty.CraftGuide.api.Slot; import uristqwerty.CraftGuide.client.ui.GuiRenderer; import uristqwerty.CraftGuide.itemtype.ItemType; import uristqwerty.gui_craftguide.rendering.RendererBase; import uristqwerty.gui_craftguide.rendering.TexturedRect; @SuppressWarnings("deprecation") public class HTMLExport { private static boolean testRequested = false; public static void test() { testRequested = true; } public static void maybeTest() { if(testRequested) { doTest(); testRequested = false; } } public static void doTest() { Map<ItemType, List<CraftGuideRecipe>> recipes = GuiCraftGuide.getInstance().getRecipeCache().getAllRecipes(); List<CraftGuideRecipe> tableRecipes = recipes.get(ItemType.getInstance(new ItemStack(Blocks.CRAFTING_TABLE))); try { File dir = new File("CraftGuide-export-test"); dir.mkdirs(); HTMLExport html = new HTMLExport(dir); Random rnd = new Random(); for(int i = 0; i < 5; i++) { CraftGuideRecipe recipe = tableRecipes.get(rnd.nextInt(tableRecipes.size())); if(recipe instanceof Recipe) { html.writeRecipe((Recipe) recipe); } } html.finish(); } catch (IOException | LWJGLException e) { CraftGuideLog.log(e, "Could not output recipe test", true); } } private File directory; private BufferedWriter htmlOut; private HashMap<Pair<TexturedRect,TexturedRect>, Integer> recipeCSSIndices = new HashMap<>(); private int nextRecipeCSSIndex = 0; public HTMLExport(File dir) throws IOException { directory = dir; htmlOut = new BufferedWriter(new FileWriter(new File(dir, "index.html"))); writeHeader(); } private void writeHeader() throws IOException { htmlOut.write("<!DOCTYPE html><html><head><meta charset='UTF-8'><link href='recipe_export.css' rel='stylesheet'></head><body>\n"); } private void writeFooter() throws IOException { htmlOut.write("</body></html>"); } private void finish() throws IOException, LWJGLException { CraftGuideLog.checkGlError(); writeFooter(); htmlOut.close(); Minecraft mc = Minecraft.getMinecraft(); mc.getFramebuffer().unbindFramebuffer(); GL11.glColorMask(true, true, true, false); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(false); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, mc.displayWidth, mc.displayHeight, 0.0D, 1000.0D, 3000.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -2000.0F); GL11.glViewport(0, 0, mc.displayWidth, mc.displayHeight); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glDisable(GL11.GL_BLEND); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glEnable(GL11.GL_COLOR_MATERIAL); ScaledResolution scaledresolution = new ScaledResolution(mc); int guiScale = scaledresolution.getScaleFactor(); GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, scaledresolution.getScaledWidth_double(), scaledresolution.getScaledHeight_double(), 0.0D, 1000.0D, 3000.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -2000.0F); try(BufferedWriter cssOut = new BufferedWriter(new FileWriter(new File(directory, "recipe_export.css")))) { cssOut.write(".r{position:relative;top:0px;left:0px}\n"); CraftGuideLog.checkGlError(); for(Entry<Pair<TexturedRect, TexturedRect>, Integer> entry: recipeCSSIndices.entrySet()) { String prefix = "r" + entry.getValue(); TexturedRect bg = entry.getKey().first; TexturedRect bgSel = entry.getKey().second; cssOut.write("." + prefix + "{width:" + (bg.width*guiScale) + "px;height:" + (bg.height*guiScale) + "px;background:url('" + prefix + "-bg.png');}\n"); cssOut.write("." + prefix + ":hover{width:" + (bgSel.width*guiScale) + "px;height:" + (bgSel.height*guiScale) + "px;background:url('" + prefix + "-bgh.png');}\n"); renderToImage(bg, new File(directory, prefix + "-bg.png"), scaledresolution.getScaleFactor()); renderToImage(bgSel, new File(directory, prefix + "-bgh.png"), scaledresolution.getScaleFactor()); } } GL11.glDepthMask(true); GL11.glColorMask(true, true, true, true); mc.getFramebuffer().bindFramebuffer(true); CraftGuideLog.checkGlError(); } private void renderToImage(TexturedRect tex, File file, int guiScale) throws IOException, LWJGLException { CraftGuideLog.checkGlError(); int windowHeight = Minecraft.getMinecraft().displayHeight; int width = tex.width * guiScale; int height = tex.height * guiScale; ByteBuffer buffer = ByteBuffer.allocateDirect(width * height * 4); GuiRenderer renderer = (GuiRenderer)RendererBase.instance; // GL11.glDisable(GL11.GL_STENCIL_TEST); CraftGuideLog.checkGlError(); tex.render(renderer, -tex.x, -tex.y); CraftGuideLog.checkGlError(); boolean front = false; if(front ) { GL11.glReadBuffer(GL11.GL_FRONT); Display.swapBuffers(); CraftGuideLog.checkGlError(); } else { GL11.glReadBuffer(GL11.GL_BACK); } GL11.glFinish(); GL11.glReadPixels(0, windowHeight - height, width, height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer); CraftGuideLog.checkGlError(); BufferedImage frame = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { int rgba = buffer.getInt((x + (height - y - 1)*width) * 4); int argb = (rgba >>> 8) | ((0xff ^ rgba) << 24); frame.setRGB(x, y, argb); } } ImageWriter writer = findPngWriter(); try { try(FileImageOutputStream output = new FileImageOutputStream(file)) { writer.setOutput(output); writer.write(new IIOImage(frame, null, null)); } } finally { writer.dispose(); } CraftGuideLog.checkGlError(); } private void writeRecipe(Recipe recipe) throws IOException { htmlOut.write("<div class='r " + recipeCSS(recipe) + "'>"); Slot[] slots = recipe.getSlotData(); Object[] items = recipe.getItems(); for(int i = 0; i < slots.length; i++) { if(slots[i] instanceof ItemSlot) { ItemSlot slot = (ItemSlot)slots[i]; ItemStack item = slotItem(slot, items[i]); String divClasses = (slot.drawBackground? "slot " : "") + "i " + itemCSS(item); htmlOut.write("<div class='" + divClasses + "' style='top:" + slot.y + "px;left:" + slot.x + "px'></div>"); } } htmlOut.write("</div>\n"); } private String itemCSS(ItemStack item) { // TODO Auto-generated method stub return "ni"; } private ItemStack slotItem(ItemSlot slot, Object object) { // TODO Auto-generated method stub return null; } private String recipeCSS(Recipe recipe) { Pair<TexturedRect, TexturedRect> key = new Pair<>((TexturedRect)recipe.background, (TexturedRect)recipe.backgroundSelected); Integer index = recipeCSSIndices.get(key); if(index == null) { index = nextRecipeCSSIndex++; recipeCSSIndices.put(key, index); } return "r" + index; } public static void outputItemIcon(ItemStack stack, File dest) { // IItemRenderer renderer = MinecraftForgeClient.getItemRenderer(stack, ItemRenderType.INVENTORY); // Item item = stack.getItem(); // Block block = Block.getBlockFromItem(item); // boolean renderAsBlock = stack.getItemSpriteNumber() == 0 && item instanceof ItemBlock && RenderBlocks.renderItemIn3d(block.getRenderType()); // IIcon icon = stack.getIconIndex(); // // if(renderer == null && !renderAsBlock && icon instanceof TextureAtlasSprite && ((TextureAtlasSprite)icon).getFrameCount() > 1) // { // // TODO: Read frame data from TextureAtlasSprite, rescale, output GIF // } // else // { // // TODO: Render to texture, copy pixels into spritesheet PNG. // } } // public static void old_test() // { // try // { // //// TextureMap textureMap = (TextureMap)Minecraft.getMinecraft().getTextureManager().getTexture(TextureMap.locationItemsTexture); //// TextureAtlasSprite test_icon = (TextureAtlasSprite)textureMap.registerIcon("craftguide:palette-extension-test-icon"); //"craftguide:palette-extension-test-icon" //// Minecraft.getMinecraft().refreshResources(); // TextureAtlasSprite test_icon = (TextureAtlasSprite) CraftGuide.itemCraftGuide.getIconFromDamage(0); // //test_icon = (TextureAtlasSprite) Blocks.flowing_lava.getIcon(0, 0); // int frames = test_icon.getFrameCount(); // // //GL11.glGetTexImage(target, level, format, type, pixels); // // if(frames > 0) // { // ImageWriter writer = findGifWriter(); // FileImageOutputStream output = new FileImageOutputStream(new File("test.gif")); // writer.setOutput(output); // writer.prepareWriteSequence(null); // // CraftGuideLog.log("Writing animated icon " + test_icon.getIconName() + ": " + test_icon.getIconWidth() + "*" + test_icon.getIconHeight() + "px with " + frames + " frames"); // for(int i = 0; i < frames; i++) // { // int width = test_icon.getIconWidth(); // int height = test_icon.getIconHeight(); // BufferedImage frame = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // int[][] pix = test_icon.getFrameTextureData(i); // for(int x = 0; x < width; x++) // { // for(int y = 0; y < height; y++) // { // frame.setRGB(x, y, pix[0][x*width+y]); // } // } // writer.writeToSequence(new IIOImage(frame, null, null), null); // } // // writer.endWriteSequence(); // writer.dispose(); // } // else // { // CraftGuideLog.log("Writing icon " + test_icon.getIconName() + ": " + test_icon.getIconWidth() + "*" + test_icon.getIconHeight() + "px"); // int width = test_icon.getIconWidth(); // int height = test_icon.getIconHeight(); // BufferedImage frame = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // } // // } // catch (IOException e) // { // CraftGuideLog.log(e); // } // } // @SuppressWarnings("unused") private static ImageWriter findGifWriter() { Iterator<ImageWriter> i = ImageIO.getImageWritersByFormatName("gif"); while(i.hasNext()) { ImageWriter w = i.next(); if(w.canWriteSequence()) return w; } return null; } private static ImageWriter findPngWriter() { Iterator<ImageWriter> i = ImageIO.getImageWritersByFormatName("png"); while(i.hasNext()) { ImageWriter w = i.next(); return w; } 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.qpid.jms.discovery; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import java.net.URI; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.JMSException; import org.apache.qpid.jms.JmsConnection; import org.apache.qpid.jms.JmsConnectionFactory; import org.apache.qpid.jms.JmsConnectionListener; import org.apache.qpid.jms.message.JmsInboundMessageDispatch; import org.apache.qpid.jms.provider.discovery.DiscoveryProviderFactory; import org.apache.qpid.jms.support.AmqpTestSupport; import org.apache.qpid.jms.support.MulticastTestSupport; import org.apache.qpid.jms.support.MulticastTestSupport.MulticastSupportResult; import org.apache.qpid.jms.support.Wait; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Test that a Broker using AMQP can be discovered and JMS operations can be performed. */ public class JmsAmqpDiscoveryTest extends AmqpTestSupport implements JmsConnectionListener { private static final Logger LOG = LoggerFactory.getLogger(JmsAmqpDiscoveryTest.class); private static boolean multicastWorking = false; private static String networkInterface = null; static { MulticastSupportResult msr = MulticastTestSupport.checkMulticastWorking(); multicastWorking = msr.isMulticastWorking(); networkInterface = msr.getNetworkInterface(); } private CountDownLatch connected; private CountDownLatch interrupted; private CountDownLatch restored; private JmsConnection jmsConnection; @Override @Before public void setUp() throws Exception { // Check assumptions *before* trying to start // the broker, which may fail otherwise assumeTrue("Multicast does not seem to be working, skip!", multicastWorking); super.setUp(); connected = new CountDownLatch(1); interrupted = new CountDownLatch(1); restored = new CountDownLatch(1); } @Test(timeout=10000) public void testFailureToDiscoverLeadsToConnectionFailure() throws Exception { // We are using a different group to ensure failure, // but shut down the broker anyway. stopPrimaryBroker(); try { createFailingConnection(); fail("Should have failed to connect"); } catch (JMSException jmse) { // expected } } @Test(timeout=30000) public void testRunningBrokerIsDiscovered() throws Exception { connection = createConnection(); connection.start(); assertTrue("connection never connected.", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return jmsConnection.isConnected(); } })); } @Test(timeout=30000) public void testConnectionFailsWhenBrokerGoesDown() throws Exception { connection = createConnection(); connection.start(); assertTrue("connection never connected.", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return jmsConnection.isConnected(); } })); LOG.info("Connection established, stopping broker."); stopPrimaryBroker(); assertTrue("Interrupted event never fired", interrupted.await(10, TimeUnit.SECONDS)); } @Test(timeout=30000) public void testConnectionRestoresAfterBrokerRestarted() throws Exception { connection = createConnection(); connection.start(); assertTrue("connection never connected.", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return jmsConnection.isConnected(); } })); stopPrimaryBroker(); assertTrue(interrupted.await(10, TimeUnit.SECONDS)); startPrimaryBroker(); assertTrue(restored.await(10, TimeUnit.SECONDS)); } @Test(timeout=30000) public void testDiscoversAndReconnectsToSecondaryBroker() throws Exception { connection = createConnection(); connection.start(); assertTrue("connection never connected.", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return jmsConnection.isConnected(); } })); startNewBroker(); stopPrimaryBroker(); assertTrue(interrupted.await(10, TimeUnit.SECONDS)); assertTrue(restored.await(10, TimeUnit.SECONDS)); } @Override protected boolean isAmqpDiscovery() { return true; } @Override protected String getDiscoveryNetworkInterface() { return networkInterface; } protected Connection createFailingConnection() throws JMSException { String discoveryPrefix = DiscoveryProviderFactory.DISCOVERY_OPTION_PREFIX; JmsConnectionFactory factory = new JmsConnectionFactory( "discovery:(multicast://default?group=altGroup)?" + discoveryPrefix + "startupMaxReconnectAttempts=10" + "&" + discoveryPrefix +"maxReconnectDelay=100"); connection = factory.createConnection(); jmsConnection = (JmsConnection) connection; jmsConnection.addConnectionListener(this); jmsConnection.start(); return connection; } protected Connection createConnection() throws Exception { String discoveryPrefix = DiscoveryProviderFactory.DISCOVERY_OPTION_PREFIX; JmsConnectionFactory factory = new JmsConnectionFactory( "discovery:(multicast://default)?" + discoveryPrefix + "startupMaxReconnectAttempts=25" + "&" + discoveryPrefix +"maxReconnectDelay=500"); connection = factory.createConnection(); jmsConnection = (JmsConnection) connection; jmsConnection.addConnectionListener(this); return connection; } @Override public void onConnectionFailure(Throwable error) { LOG.info("Connection reported failover: {}", error.getMessage()); } @Override public void onConnectionEstablished(URI remoteURI) { LOG.info("Connection reports established. Connected to -> {}", remoteURI); connected.countDown(); } @Override public void onConnectionInterrupted(URI remoteURI) { LOG.info("Connection reports interrupted. Lost connection to -> {}", remoteURI); interrupted.countDown(); } @Override public void onConnectionRestored(URI remoteURI) { LOG.info("Connection reports restored. Connected to -> {}", remoteURI); restored.countDown(); } @Override public void onInboundMessage(JmsInboundMessageDispatch envelope) { } }
/* * Copyright (c) 2014, Andreas P. Koenzen <akc at apkc.net> * 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. * * 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. */ package net.apkc.quary.config; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import net.apkc.esxp.exceptions.AttributeNotFoundException; import net.apkc.esxp.exceptions.ParserNotInitializedException; import net.apkc.esxp.exceptions.TagNotFoundException; import net.apkc.esxp.processor.Processor; import net.apkc.esxp.walker.DOMWalker; import net.apkc.esxp.walker.DOMWalkerFactory; import net.apkc.quary.definitions.index.IndexDefinition; import net.apkc.quary.definitions.index.IndexDefinitionField; import net.apkc.quary.docs.QuaryDocument; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * Custom XML processor for the application. * * @author Andreas P. Koenzen <akc at apkc.net> * @version 0.1 * @see <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton Pattern</a> */ class XMLProcessor { private static final Logger LOG = Logger.getLogger(XMLProcessor.class.getName()); private static final XMLProcessor _INSTANCE = new XMLProcessor(); private final byte WALKER = DOMWalkerFactory.STACK_DOM_WALKER; private final boolean STRICT_MODE = false; private Processor processor = Processor.newBuild(); private Document doc; private NodeList nodes; static XMLProcessor getInstance() { return _INSTANCE; } private XMLProcessor() { } /** * Configure this XML processor. * * @param xml The XML document to parse. * @param schemaString The schema used to validate the XML, if null skip. * @param rootNode The root node of the XML. * * @return This instance. */ XMLProcessor configure(InputStream xmlStream, InputStream schemaStream, String rootNode) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); if (schemaStream != null) { // Validate the XML file againts our default schema. SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(schemaStream)); dbFactory.setSchema(schema); } // Configure to Focus on Content. dbFactory.setValidating(false); dbFactory.setNamespaceAware(true); dbFactory.setCoalescing(true); dbFactory.setExpandEntityReferences(true); dbFactory.setIgnoringComments(true); dbFactory.setIgnoringElementContentWhitespace(true); // Create a DOM document. DocumentBuilder builder = dbFactory.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException e) throws SAXException { LOG.warn("DOM Warning: " + e.toString(), e); } @Override public void error(SAXParseException e) throws SAXException { LOG.error("DOM Error: " + e.toString(), e); } @Override public void fatalError(SAXParseException e) throws SAXException { LOG.fatal("DOM Fatal: " + e.toString(), e); throw e; } }); doc = builder.parse(new InputSource(xmlStream)); // Create document doc.getDocumentElement().normalize(); // Configure nodes = doc.getElementsByTagName(rootNode); } catch (ParserConfigurationException | SAXException | IOException ex) { System.err.println("Error configuring processor. Error: " + ex.toString()); } return this; } /** * Method for extracting all declared fields inside a definition document. * * @return A list containing definition objects. * * @throws ParserNotInitializedException If the processor could not be started. */ List<IndexDefinitionField> getFields() throws ParserNotInitializedException { if (nodes == null) { throw new ParserNotInitializedException("Parser was not started!"); } List<IndexDefinitionField> list = new ArrayList<>(); IndexDefinitionField df = IndexDefinitionField.newBuild(); try { DOMWalker mainParser = DOMWalkerFactory.getWalker(WALKER).configure(nodes.item(0), DOMWalker.ELEMENT_NODES); while (mainParser.hasNext()) { Node n1 = mainParser.nextNode(); switch (n1.getNodeName()) { // If its a node with sub-nodes. case "field": // Node with sub-nodes. DOMWalker subParser1 = DOMWalkerFactory.getWalker(WALKER).configure(n1, DOMWalker.ELEMENT_NODES); while (subParser1.hasNext()) { Node n2 = subParser1.nextNode(); switch (n2.getNodeName()) { case "analyzer": df.setAnalyzer(processor.getNodeValue(n2, STRICT_MODE)); break; case "boost": df.setFieldBoost(processor.getNodeValue(n2, STRICT_MODE)); break; case "docvaluetype": df.setDocValueType(processor.getNodeValue(n2, STRICT_MODE)); break; case "indexed": df.addFieldProperty(IndexDefinitionField.OptionID.INDEXED, processor.getNodeValue(n2, STRICT_MODE).equals("1")); break; case "indexoptions": df.setIndexOptions(processor.getNodeValue(n2, STRICT_MODE)); break; case "numericprecisionstep": df.setNumericPrecisionStep(processor.getNodeValue(n2, STRICT_MODE)); break; case "numerictype": df.setNumericType(processor.getNodeValue(n2, STRICT_MODE)); break; case "omitnorms": df.addFieldProperty(IndexDefinitionField.OptionID.OMIT_NORMS, processor.getNodeValue(n2, STRICT_MODE).equals("1")); break; case "stored": df.addFieldProperty(IndexDefinitionField.OptionID.STORED, processor.getNodeValue(n2, STRICT_MODE).equals("1")); break; case "storetermvectoroffset": df.addFieldProperty(IndexDefinitionField.OptionID.STORE_TERM_VECTOR_OFFSETS, processor.getNodeValue(n2, STRICT_MODE).equals("1")); break; case "storetermvectorpayloads": df.addFieldProperty(IndexDefinitionField.OptionID.STORE_TERM_VECTOR_PAYLOADS, processor.getNodeValue(n2, STRICT_MODE).equals("1")); break; case "storetermvectorpositions": df.addFieldProperty(IndexDefinitionField.OptionID.STORE_TERM_VECTOR_POSITIONS, processor.getNodeValue(n2, STRICT_MODE).equals("1")); break; case "storetermvectors": df.addFieldProperty(IndexDefinitionField.OptionID.STORE_TERM_VECTORS, processor.getNodeValue(n2, STRICT_MODE).equals("1")); break; case "tokenized": df.addFieldProperty(IndexDefinitionField.OptionID.TOKENIZED, processor.getNodeValue(n2, STRICT_MODE).equals("1")); break; case "value": df.setFieldName(processor.getNodeValue(n2, STRICT_MODE)); break; case "contentencoding": df.setContentEncoding(processor.getNodeValue(n2, STRICT_MODE)); break; case "searchable": df.setSearchable(processor.getNodeValue(n2, STRICT_MODE).equals("1")); break; } } break; } if (!df.isEmpty()) { list.add(df); df = IndexDefinitionField.newBuild(); } } } catch (Exception e) { LOG.error("Error parsing DOM tree. Error: " + e.toString(), e); } return list; } QuaryDocument buildQuaryDocument(IndexDefinition definition) throws ParserNotInitializedException { if (nodes == null) { throw new ParserNotInitializedException("Parser was not started!"); } QuaryDocument quaryDoc = QuaryDocument.newBuild(); try { DOMWalker mainParser = DOMWalkerFactory.getWalker(WALKER).configure(nodes.item(0), DOMWalker.ELEMENT_NODES); while (mainParser.hasNext()) { Node n1 = mainParser.nextNode(); for (IndexDefinitionField field : definition.getFields()) { if (field.getFieldName().equalsIgnoreCase(n1.getNodeName())) { // We found a match. Load the field into the document! quaryDoc.add(field.getFieldName(), processor.getNodeValue(n1, STRICT_MODE)); } } } } catch (Exception e) { LOG.error("Error parsing DOM tree. Error: " + e.toString(), e); } return quaryDoc; } /** * Shortcut method to extract the value of a tag. * * @param rootNode The root node. * @param tag The name of the tag to extract. * * @return The value of the tag. * * @throws ParserNotInitializedException If the processor could not be started. * @throws TagNotFoundException If the tag does not exists. */ String getTagValue(String rootNode, String tag) throws ParserNotInitializedException, TagNotFoundException { if (nodes == null) { throw new ParserNotInitializedException("Parser was not started!"); } return processor.searchTagValue(doc, rootNode, tag, STRICT_MODE); } /** * Shortcut method to extract the attribute of a tag. * * @param rootNode The root node. * @param tag The name of the tag. * @param attributeName The name of the attribute. * * @return The value of the attribute. * * @throws ParserNotInitializedException If the processor could not be started. * @throws TagNotFoundException If the tag does not exists. * @throws AttributeNotFoundException If the attribute does not exists. */ String getTagAttribute(String rootNode, String tag, String attributeName) throws ParserNotInitializedException, TagNotFoundException, AttributeNotFoundException { if (nodes == null) { throw new ParserNotInitializedException("Parser was not started!"); } return processor.searchTagAttributeValue(doc, rootNode, tag, attributeName, STRICT_MODE); } }
/* * Copyright 2011 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.devtools.j2objc.translate; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.devtools.j2objc.ast.Block; import com.google.devtools.j2objc.ast.ClassInstanceCreation; import com.google.devtools.j2objc.ast.Expression; import com.google.devtools.j2objc.ast.MethodDeclaration; import com.google.devtools.j2objc.ast.MethodInvocation; import com.google.devtools.j2objc.ast.ReturnStatement; import com.google.devtools.j2objc.ast.SimpleName; import com.google.devtools.j2objc.ast.SingleVariableDeclaration; import com.google.devtools.j2objc.ast.Statement; import com.google.devtools.j2objc.ast.StringLiteral; import com.google.devtools.j2objc.ast.SuperMethodInvocation; import com.google.devtools.j2objc.ast.TreeUtil; import com.google.devtools.j2objc.ast.TreeVisitor; import com.google.devtools.j2objc.ast.Type; import com.google.devtools.j2objc.ast.TypeDeclaration; import com.google.devtools.j2objc.types.GeneratedMethodBinding; import com.google.devtools.j2objc.types.GeneratedVariableBinding; import com.google.devtools.j2objc.types.IOSMethod; import com.google.devtools.j2objc.types.IOSMethodBinding; import com.google.devtools.j2objc.types.IOSParameter; import com.google.devtools.j2objc.types.JavaMethod; import com.google.devtools.j2objc.types.Types; import com.google.devtools.j2objc.util.BindingUtil; import com.google.devtools.j2objc.util.ErrorUtil; import com.google.devtools.j2objc.util.NameTable; import com.google.j2objc.annotations.ObjectiveCName; import org.eclipse.jdt.core.dom.IAnnotationBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.Modifier; import java.util.List; import java.util.Map; /** * Translates method invocations and overridden methods from Java core types to * iOS equivalents. For example, <code>object.toString()</code> becomes * <code>[object description]</code>. Since many methods don't have direct * equivalents, other code replaces the method invocation. If the replacement * code is too lengthy, though, a call to an emulation library is substituted to * prevent code bloat. * * @author Tom Ball */ public class JavaToIOSMethodTranslator extends TreeVisitor { private Map<IMethodBinding, JavaMethod> descriptions = Maps.newLinkedHashMap(); private List<IMethodBinding> overridableMethods = Lists.newArrayList(); private List<IMethodBinding> mappedMethods = Lists.newArrayList(); private final ITypeBinding javaLangCloneable; private final Map<String, IOSMethod> methodMappings; private static final Function<String, IOSMethod> IOS_METHOD_FROM_STRING = new Function<String, IOSMethod>() { public IOSMethod apply(String value) { return IOSMethod.create(value); } }; public JavaToIOSMethodTranslator(Map<String, String> methodMappings) { this.methodMappings = Maps.newHashMap(Maps.transformValues(methodMappings, IOS_METHOD_FROM_STRING)); loadTargetMethods(Types.resolveJavaType("java.lang.Object")); loadTargetMethods(Types.resolveJavaType("java.lang.Class")); loadTargetMethods(Types.resolveJavaType("java.lang.String")); loadTargetMethods(Types.resolveJavaType("java.lang.Number")); loadCharSequenceMethods(); javaLangCloneable = Types.resolveJavaType("java.lang.Cloneable"); } private void loadTargetMethods(ITypeBinding clazz) { for (IMethodBinding method : clazz.getDeclaredMethods()) { if (method.isConstructor() && Types.isJavaObjectType(method.getDeclaringClass())) { continue; // No mapping needed for new Object(); } if (method.getName().equals("clone")) { continue; } // track all non-final public, protected and package-private methods int mods = method.getModifiers(); if (!Modifier.isPrivate(mods)) { if (!Modifier.isFinal(mods)) { overridableMethods.add(method); } mappedMethods.add(method); addDescription(method); } } } private void loadCharSequenceMethods() { ITypeBinding charSequence = Types.resolveJavaType("java.lang.CharSequence"); for (IMethodBinding method : charSequence.getDeclaredMethods()) { if (method.getName().equals("length")) { overridableMethods.add(0, method); NameTable.rename(method, "sequenceLength"); mappedMethods.add(method); addDescription(method); } else if (method.getName().equals("subSequence")) { overridableMethods.add(0, method); NameTable.rename(method, "subSequenceFrom"); mappedMethods.add(method); addDescription(method); } } } @Override public boolean visit(MethodDeclaration node) { // See if method has been directly mapped. IMethodBinding binding = node.getMethodBinding(); JavaMethod desc = getDescription(binding); if (desc != null) { mapMethod(node, binding, methodMappings.get(desc.getKey())); return true; } // See if an overrideable superclass method has been mapped. for (IMethodBinding overridable : overridableMethods) { if (!binding.isConstructor() && (binding.isEqualTo(overridable) || binding.overrides(overridable))) { JavaMethod md = getDescription(overridable); if (md == null) { continue; } String key = md.getKey(); IOSMethod iosMethod = methodMappings.get(key); if (iosMethod != null) { mapMethod(node, binding, iosMethod); } return true; } } return true; } private void mapMethod(MethodDeclaration node, IMethodBinding binding, IOSMethod iosMethod) { IOSMethodBinding iosBinding = IOSMethodBinding.newMappedMethod(iosMethod, binding); node.setName(new SimpleName(iosBinding)); node.setMethodBinding(iosBinding); // Map parameters, if any. List<SingleVariableDeclaration> parameters = node.getParameters(); int n = parameters.size(); if (n > 0) { List<IOSParameter> iosArgs = iosMethod.getParameters(); assert n == iosArgs.size() || iosMethod.isVarArgs(); for (int i = 0; i < n; i++) { ITypeBinding newParamType = Types.resolveIOSType(iosArgs.get(i).getType()); if (newParamType != null) { parameters.get(i).setType(Type.newType(newParamType)); } } } } @Override public boolean visit(ClassInstanceCreation node) { // translate any embedded method invocations if (node.getExpression() != null) { node.getExpression().accept(this); } for (Expression e : node.getArguments()) { e.accept(this); } if (node.getAnonymousClassDeclaration() != null) { node.getAnonymousClassDeclaration().accept(this); } IMethodBinding binding = node.getMethodBinding(); JavaMethod md = descriptions.get(binding); if (md != null) { assert !node.hasRetainedResult(); String key = md.getKey(); if (key.equals("java.lang.String.String(Ljava/lang/String;)V")) { // Special case: replace new String(constant) to constant (avoid clang warning). Expression arg = node.getArguments().get(0); if (arg instanceof StringLiteral) { node.replaceWith(arg.copy()); return false; } } IOSMethod iosMethod = methodMappings.get(key); if (iosMethod != null) { IOSMethodBinding methodBinding = IOSMethodBinding.newMappedMethod(iosMethod, binding); MethodInvocation newInvocation = new MethodInvocation(methodBinding, new SimpleName(Types.resolveIOSType(iosMethod.getDeclaringClass()))); // Set parameters. copyInvocationArguments(null, node.getArguments(), newInvocation.getArguments()); node.replaceWith(newInvocation); } else { ErrorUtil.error(node, createMissingMethodMessage(binding)); } } return true; } @Override public void endVisit(TypeDeclaration node) { // If this type implements Cloneable but its parent doesn't, add a // copyWithZone: method that calls clone(). ITypeBinding type = node.getTypeBinding(); if (type.isAssignmentCompatible(javaLangCloneable)) { ITypeBinding superclass = type.getSuperclass(); if (superclass == null || !superclass.isAssignmentCompatible(javaLangCloneable)) { addCopyWithZoneMethod(node); } } } @Override public void endVisit(MethodInvocation node) { IMethodBinding binding = node.getMethodBinding(); JavaMethod md = getDescription(binding); if (md == null && !binding.getName().equals("clone")) { // never map clone() IVariableBinding receiver = node.getExpression() != null ? TreeUtil.getVariableBinding(node.getExpression()) : null; ITypeBinding clazz = receiver != null ? receiver.getType() : binding.getDeclaringClass(); if (clazz != null && !clazz.isArray()) { for (IMethodBinding method : descriptions.keySet()) { if (binding.isSubsignature(method) && clazz.isAssignmentCompatible(method.getDeclaringClass())) { md = descriptions.get(method); break; } } } } if (md != null) { String key = md.getKey(); IOSMethod iosMethod = methodMappings.get(key); if (iosMethod == null) { ErrorUtil.error(node, createMissingMethodMessage(binding)); return; } IOSMethodBinding newBinding = IOSMethodBinding.newMappedMethod(iosMethod, binding); node.setMethodBinding(newBinding); NameTable.rename(binding, iosMethod.getName()); if (node.getExpression() instanceof SimpleName) { SimpleName expr = (SimpleName) node.getExpression(); if (expr.getIdentifier().equals(binding.getDeclaringClass().getName()) || expr.getIdentifier().equals(binding.getDeclaringClass().getQualifiedName())) { NameTable.rename(binding.getDeclaringClass(), iosMethod.getDeclaringClass()); } } } else { // Not mapped, check if it overrides a mapped method. for (IMethodBinding methodBinding : mappedMethods) { if (binding.overrides(methodBinding)) { JavaMethod desc = getDescription(methodBinding); if (desc != null) { IOSMethod iosMethod = methodMappings.get(desc.getKey()); if (iosMethod != null) { IOSMethodBinding newBinding = IOSMethodBinding.newMappedMethod(iosMethod, binding); node.setMethodBinding(newBinding); break; } } } } } return; } private void copyInvocationArguments(Expression receiver, List<Expression> oldArgs, List<Expression> newArgs) { // set the receiver as the first argument if (receiver != null) { Expression delegate = receiver.copy(); delegate.accept(this); newArgs.add(delegate); } // copy remaining arguments for (Expression oldArg : oldArgs) { newArgs.add(oldArg.copy()); } } @Override public boolean visit(SuperMethodInvocation node) { // translate any embedded method invocations for (Expression e : node.getArguments()) { e.accept(this); } IMethodBinding binding = node.getMethodBinding(); JavaMethod md = getDescription(binding); if (md != null) { String key = md.getKey(); IOSMethod iosMethod = methodMappings.get(key); if (iosMethod == null) { // Method has same name as a mapped method's, but it's ignored since // it doesn't override it. return super.visit(node); } IOSMethodBinding newBinding = IOSMethodBinding.newMappedMethod(iosMethod, binding); node.setMethodBinding(newBinding); } else { // Not mapped, check if it overrides a mapped method. for (IMethodBinding methodBinding : mappedMethods) { if (binding.overrides(methodBinding)) { JavaMethod desc = getDescription(methodBinding); if (desc != null) { IOSMethod iosMethod = methodMappings.get(desc.getKey()); if (iosMethod != null) { IOSMethodBinding newBinding = IOSMethodBinding.newMappedMethod(iosMethod, binding); node.setMethodBinding(newBinding); } } } } } return true; } private JavaMethod getDescription(IMethodBinding binding) { if (descriptions.containsKey(binding)) { return descriptions.get(binding); } return addDescription(binding); } private JavaMethod addDescription(IMethodBinding binding) { JavaMethod desc = JavaMethod.getJavaMethod(binding); if (desc != null) { if (methodMappings.containsKey(desc.getKey())) { descriptions.put(binding, desc); return desc; } String objcName = getObjectiveCNameValue(binding); if (objcName != null) { try { String signature = String.format("%s %s", binding.getDeclaringClass().getName(), objcName); IOSMethod method = IOSMethod.create(signature); methodMappings.put(desc.getKey(), method); } catch (IllegalArgumentException e) { ErrorUtil.error("invalid Objective-C method name: " + objcName); } descriptions.put(binding, desc); return desc; } } return null; // binding isn't mapped. } /** * Returns ObjectiveCName value, or null if method is not annotated. * <p> * This method warns if source attempts to specify an overridden method * that doesn't have the same ObjectiveCName value. This prevents * developers from accidentally breaking polymorphic methods. * * @return the ObjectiveCName value, or null if not annotated or when * a warning is reported. */ private static String getObjectiveCNameValue(IMethodBinding method) { IAnnotationBinding annotation = BindingUtil.getAnnotation(method, ObjectiveCName.class); if (annotation != null) { String selector = (String) BindingUtil.getAnnotationValue(annotation, "value"); if (BindingUtil.getAnnotation(method, Override.class) != null) { // Check that overridden method has same Objective-C name. IMethodBinding superMethod = BindingUtil.getOriginalMethodBinding(method); if (superMethod != method.getMethodDeclaration()) { IAnnotationBinding superAnnotation = BindingUtil.getAnnotation(superMethod, ObjectiveCName.class); if (superAnnotation == null) { ErrorUtil.warning("ObjectiveCName(" + selector + ") set on overridden method that is not also renamed."); return null; } else { String superSelector = (String) BindingUtil.getAnnotationValue(superAnnotation, "value"); if (!selector.equals(superSelector)) { ErrorUtil.warning("Conflicting Objective-C names set for " + method + ", which overrides " + superMethod); return null; } } } } return selector; } return null; } /** * Explicitly walk block statement lists, to work around a bug in * ASTNode.visitChildren that skips list members. */ @Override public boolean visit(Block node) { for (Statement s : node.getStatements()) { s.accept(this); } return false; } private String createMissingMethodMessage(IMethodBinding binding) { StringBuilder sb = new StringBuilder("Internal error: "); sb.append(binding.getDeclaringClass().getName()); if (!binding.isConstructor()) { sb.append('.'); sb.append(binding.getName()); } sb.append('('); ITypeBinding[] args = binding.getParameterTypes(); int nargs = args.length; for (int i = 0; i < nargs; i++) { sb.append(args[i].getName()); if (i + 1 < nargs) { sb.append(','); } } sb.append(") not mapped"); return sb.toString(); } private MethodInvocation makeCloneInvocation(ITypeBinding declaringClass) { GeneratedMethodBinding cloneBinding = GeneratedMethodBinding.newMethod( "clone", 0, Types.resolveIOSType("NSObject"), declaringClass); return new MethodInvocation(cloneBinding, null); } private void addCopyWithZoneMethod(TypeDeclaration node) { // Create copyWithZone: method. ITypeBinding type = node.getTypeBinding().getTypeDeclaration(); IOSMethod iosMethod = IOSMethod.create("id copyWithZone:(NSZone *)zone"); IOSMethodBinding binding = IOSMethodBinding.newMethod( iosMethod, Modifier.PUBLIC, Types.resolveIOSType("id"), type); MethodDeclaration cloneMethod = new MethodDeclaration(binding); // Add NSZone *zone parameter. GeneratedVariableBinding zoneBinding = new GeneratedVariableBinding( "zone", 0, Types.resolveIOSType("NSZone"), false, true, binding.getDeclaringClass(), binding); binding.addParameter(zoneBinding.getType()); cloneMethod.getParameters().add(new SingleVariableDeclaration(zoneBinding)); Block block = new Block(); cloneMethod.setBody(block); MethodInvocation cloneInvocation = makeCloneInvocation(type); block.getStatements().add(new ReturnStatement(cloneInvocation)); node.getBodyDeclarations().add(cloneMethod); } }
/* * Copyright 2010-2012 Luca Garulli (l.garulli(at)orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.enterprise.channel.binary; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.*; import com.orientechnologies.common.io.OIOException; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OContextConfiguration; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.id.OClusterPosition; import com.orientechnologies.orient.core.id.OClusterPositionFactory; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.serialization.OBinaryProtocol; import com.orientechnologies.orient.core.version.ODistributedVersion; import com.orientechnologies.orient.core.version.ORecordVersion; import com.orientechnologies.orient.core.version.OVersionFactory; import com.orientechnologies.orient.enterprise.channel.OChannel; public abstract class OChannelBinary extends OChannel { private static final int MAX_LENGTH_DEBUG = 150; public DataInputStream in; public DataOutputStream out; private final int maxChunkSize; protected final boolean debug; private final byte[] buffer; public OChannelBinary(final Socket iSocket, final OContextConfiguration iConfig) throws IOException { super(iSocket, iConfig); maxChunkSize = iConfig.getValueAsInteger(OGlobalConfiguration.NETWORK_BINARY_MAX_CONTENT_LENGTH); debug = iConfig.getValueAsBoolean(OGlobalConfiguration.NETWORK_BINARY_DEBUG); buffer = new byte[maxChunkSize]; if (debug) OLogManager.instance().info(this, "%s - Connected", socket.getRemoteSocketAddress()); } public byte readByte() throws IOException { updateMetricReceivedBytes(OBinaryProtocol.SIZE_BYTE); if (debug) { OLogManager.instance().info(this, "%s - Reading byte (1 byte)...", socket.getRemoteSocketAddress()); final byte value = in.readByte(); OLogManager.instance().info(this, "%s - Read byte: %d", socket.getRemoteSocketAddress(), (int) value); return value; } return in.readByte(); } public int readInt() throws IOException { updateMetricReceivedBytes(OBinaryProtocol.SIZE_INT); if (debug) { OLogManager.instance().info(this, "%s - Reading int (4 bytes)...", socket.getRemoteSocketAddress()); final int value = in.readInt(); OLogManager.instance().info(this, "%s - Read int: %d", socket.getRemoteSocketAddress(), value); return value; } return in.readInt(); } public long readLong() throws IOException { updateMetricReceivedBytes(OBinaryProtocol.SIZE_LONG); if (debug) { OLogManager.instance().info(this, "%s - Reading long (8 bytes)...", socket.getRemoteSocketAddress()); final long value = in.readLong(); OLogManager.instance().info(this, "%s - Read long: %d", socket.getRemoteSocketAddress(), value); return value; } return in.readLong(); } public short readShort() throws IOException { updateMetricReceivedBytes(OBinaryProtocol.SIZE_SHORT); if (debug) { OLogManager.instance().info(this, "%s - Reading short (2 bytes)...", socket.getRemoteSocketAddress()); final short value = in.readShort(); OLogManager.instance().info(this, "%s - Read short: %d", socket.getRemoteSocketAddress(), value); return value; } return in.readShort(); } public String readString() throws IOException { if (debug) { OLogManager.instance().info(this, "%s - Reading string (4+N bytes)...", socket.getRemoteSocketAddress()); final int len = in.readInt(); if (len < 0) return null; // REUSE STATIC BUFFER? final byte[] tmp = new byte[len]; in.readFully(tmp); updateMetricReceivedBytes(OBinaryProtocol.SIZE_INT + len); final String value = new String(tmp); OLogManager.instance().info(this, "%s - Read string: %s", socket.getRemoteSocketAddress(), value); return value; } final int len = in.readInt(); if (len < 0) return null; final byte[] tmp = new byte[len]; in.readFully(tmp); updateMetricReceivedBytes(OBinaryProtocol.SIZE_INT + len); return new String(tmp); } public byte[] readBytes() throws IOException { if (debug) OLogManager.instance().info(this, "%s - Reading chunk of bytes. Reading chunk length as int (4 bytes)...", socket.getRemoteSocketAddress()); final int len = in.readInt(); updateMetricReceivedBytes(OBinaryProtocol.SIZE_INT + len); if (debug) OLogManager.instance().info(this, "%s - Read chunk lenght: %d", socket.getRemoteSocketAddress(), len); if (len < 0) return null; if (debug) OLogManager.instance().info(this, "%s - Reading %d bytes...", socket.getRemoteSocketAddress(), len); // REUSE STATIC BUFFER? final byte[] tmp = new byte[len]; in.readFully(tmp); if (debug) OLogManager.instance().info(this, "%s - Read %d bytes: %s", socket.getRemoteSocketAddress(), len, new String(tmp)); return tmp; } public List<String> readStringList() throws IOException { if (debug) OLogManager.instance().info(this, "%s - Reading string list. Reading string list items as int (4 bytes)...", socket.getRemoteSocketAddress()); final int items = in.readInt(); updateMetricReceivedBytes(OBinaryProtocol.SIZE_INT); if (debug) OLogManager.instance().info(this, "%s - Read string list items: %d", socket.getRemoteSocketAddress(), items); if (items < 0) return null; List<String> result = new ArrayList<String>(); for (int i = 0; i < items; ++i) result.add(readString()); if (debug) OLogManager.instance().info(this, "%s - Read string list with %d items: %d", socket.getRemoteSocketAddress(), items); return result; } public Set<String> readStringSet() throws IOException { if (debug) OLogManager.instance().info(this, "%s - Reading string set. Reading string set items as int (4 bytes)...", socket.getRemoteSocketAddress()); int items = in.readInt(); updateMetricReceivedBytes(OBinaryProtocol.SIZE_INT); if (debug) OLogManager.instance().info(this, "%s - Read string set items: %d", socket.getRemoteSocketAddress(), items); if (items < 0) return null; Set<String> result = new HashSet<String>(); for (int i = 0; i < items; ++i) result.add(readString()); if (debug) OLogManager.instance().info(this, "%s - Read string set with %d items: %d", socket.getRemoteSocketAddress(), items, result); return result; } public ORecordId readRID() throws IOException { final int clusterId = readShort(); final OClusterPosition clusterPosition = readClusterPosition(); return new ORecordId(clusterId, clusterPosition); } public OClusterPosition readClusterPosition() throws IOException { final int serializedSize = OClusterPositionFactory.INSTANCE.getSerializedSize(); if (debug) OLogManager.instance().info(this, "%s - Reading cluster position (%d bytes)....", socket.getRemoteSocketAddress(), serializedSize); final OClusterPosition clusterPosition = OClusterPositionFactory.INSTANCE.fromStream((InputStream) in); updateMetricReceivedBytes(serializedSize); if (debug) OLogManager.instance().info(this, "%s - Read cluster position: %s", socket.getRemoteSocketAddress(), clusterPosition); return clusterPosition; } public OChannelBinary writeClusterPosition(final OClusterPosition clusterPosition) throws IOException { final int serializedSize = OClusterPositionFactory.INSTANCE.getSerializedSize(); if (debug) OLogManager.instance().info(this, "%s - Writing cluster position (%d bytes) : %s....", socket.getRemoteSocketAddress(), serializedSize, clusterPosition); out.write(clusterPosition.toStream()); updateMetricTransmittedBytes(serializedSize); return this; } public ORecordVersion readVersion() throws IOException { if (OVersionFactory.instance().isDistributed()) { final int recordVersion = readInt(); final long timestamp = readLong(); final long macAddress = readLong(); return OVersionFactory.instance().createDistributedVersion(recordVersion, timestamp, macAddress); } else { final ORecordVersion version = OVersionFactory.instance().createVersion(); version.setCounter(readInt()); return version; } } public OChannelBinary writeByte(final byte iContent) throws IOException { if (debug) OLogManager.instance().info(this, "%s - Writing byte (1 byte): %d", socket.getRemoteSocketAddress(), iContent); out.write(iContent); updateMetricTransmittedBytes(OBinaryProtocol.SIZE_BYTE); return this; } public OChannelBinary writeInt(final int iContent) throws IOException { if (debug) OLogManager.instance().info(this, "%s - Writing int (4 bytes): %d", socket.getRemoteSocketAddress(), iContent); out.writeInt(iContent); updateMetricTransmittedBytes(OBinaryProtocol.SIZE_INT); return this; } public OChannelBinary writeLong(final long iContent) throws IOException { if (debug) OLogManager.instance().info(this, "%s - Writing long (8 bytes): %d", socket.getRemoteSocketAddress(), iContent); out.writeLong(iContent); updateMetricTransmittedBytes(OBinaryProtocol.SIZE_LONG); return this; } public OChannelBinary writeShort(final short iContent) throws IOException { if (debug) OLogManager.instance().info(this, "%s - Writing short (2 bytes): %d", socket.getRemoteSocketAddress(), iContent); out.writeShort(iContent); updateMetricTransmittedBytes(OBinaryProtocol.SIZE_SHORT); return this; } public OChannelBinary writeString(final String iContent) throws IOException { if (debug) OLogManager.instance().info(this, "%s - Writing string (4+%d=%d bytes): %s", socket.getRemoteSocketAddress(), iContent != null ? iContent.length() : 0, iContent != null ? iContent.length() + 4 : 4, iContent); if (iContent == null) { out.writeInt(-1); updateMetricTransmittedBytes(OBinaryProtocol.SIZE_INT); } else { final byte[] buffer = iContent.getBytes(); out.writeInt(buffer.length); out.write(buffer, 0, buffer.length); updateMetricTransmittedBytes(OBinaryProtocol.SIZE_INT + buffer.length); } return this; } public OChannelBinary writeBytes(final byte[] iContent) throws IOException { return writeBytes(iContent, iContent != null ? iContent.length : 0); } public OChannelBinary writeBytes(final byte[] iContent, final int iLength) throws IOException { if (debug) OLogManager.instance().info(this, "%s - Writing bytes (4+%d=%d bytes): %s", socket.getRemoteSocketAddress(), iLength, iLength + 4, Arrays.toString(iContent)); if (iContent == null) { out.writeInt(-1); updateMetricTransmittedBytes(OBinaryProtocol.SIZE_INT); } else { out.writeInt(iLength); out.write(iContent, 0, iLength); updateMetricTransmittedBytes(OBinaryProtocol.SIZE_INT + iLength); } return this; } public OChannelBinary writeCollectionString(final Collection<String> iCollection) throws IOException { if (debug) OLogManager.instance().info(this, "%s - Writing strings (4+%d=%d items): %s", socket.getRemoteSocketAddress(), iCollection != null ? iCollection.size() : 0, iCollection != null ? iCollection.size() + 4 : 4, iCollection.toString()); updateMetricTransmittedBytes(OBinaryProtocol.SIZE_INT); if (iCollection == null) writeInt(-1); else { writeInt(iCollection.size()); for (String s : iCollection) writeString(s); } return this; } public void writeRID(final ORID iRID) throws IOException { writeShort((short) iRID.getClusterId()); writeClusterPosition(iRID.getClusterPosition()); } public void writeVersion(final ORecordVersion version) throws IOException { if (version instanceof ODistributedVersion) { final ODistributedVersion v = (ODistributedVersion) version; writeInt(v.getCounter()); writeLong(v.getTimestamp()); writeLong(v.getMacAddress()); } else { // Usual serialization writeInt(version.getCounter()); } } public void clearInput() throws IOException { if (in == null) return; final StringBuilder dirtyBuffer = new StringBuilder(MAX_LENGTH_DEBUG); int i = 0; while (in.available() > 0) { char c = (char) in.read(); ++i; if (dirtyBuffer.length() < MAX_LENGTH_DEBUG) dirtyBuffer.append(c); } updateMetricReceivedBytes(i); OLogManager.instance().error( this, "Received unread response from " + socket.getRemoteSocketAddress() + " probably corrupted data from the network connection. Cleared dirty data in the buffer (" + i + " bytes): [" + dirtyBuffer + (i > dirtyBuffer.length() ? "..." : "") + "]", OIOException.class); } @Override public void flush() throws IOException { if (debug) OLogManager.instance().info(this, "%s - Flush", socket.getRemoteSocketAddress()); updateMetricFlushes(); super.flush(); out.flush(); } @Override public void close() { if (debug) OLogManager.instance().info(this, "%s - Closing socket...", socket.getRemoteSocketAddress()); try { if (in != null) in.close(); } catch (IOException e) { } try { if (out != null) out.close(); } catch (IOException e) { } super.close(); } public byte[] getBuffer() { return buffer; } public int getMaxChunkSize() { return maxChunkSize; } }
/** * Copyright (c) 2016-present, RxJava Contributors. * * 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 io.reactivex.observers; import org.junit.Test; import java.util.ArrayList; import java.util.List; import io.reactivex.Maybe; import io.reactivex.TestHelper; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; import io.reactivex.exceptions.TestException; import io.reactivex.internal.util.EndConsumerHelper; import io.reactivex.plugins.RxJavaPlugins; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class ResourceMaybeObserverTest { static final class TestResourceMaybeObserver<T> extends ResourceMaybeObserver<T> { T value; final List<Throwable> errors = new ArrayList<Throwable>(); int complete; int start; @Override protected void onStart() { super.onStart(); start++; } @Override public void onSuccess(final T value) { this.value = value; dispose(); } @Override public void onComplete() { complete++; dispose(); } @Override public void onError(Throwable e) { errors.add(e); dispose(); } } @Test(expected = NullPointerException.class) public void nullResource() { TestResourceMaybeObserver<Integer> rmo = new TestResourceMaybeObserver<Integer>(); rmo.add(null); } @Test public void addResources() { TestResourceMaybeObserver<Integer> rmo = new TestResourceMaybeObserver<Integer>(); assertFalse(rmo.isDisposed()); Disposable d = Disposables.empty(); rmo.add(d); assertFalse(d.isDisposed()); rmo.dispose(); assertTrue(rmo.isDisposed()); assertTrue(d.isDisposed()); rmo.dispose(); assertTrue(rmo.isDisposed()); assertTrue(d.isDisposed()); } @Test public void onCompleteCleansUp() { TestResourceMaybeObserver<Integer> rmo = new TestResourceMaybeObserver<Integer>(); assertFalse(rmo.isDisposed()); Disposable d = Disposables.empty(); rmo.add(d); assertFalse(d.isDisposed()); rmo.onComplete(); assertTrue(rmo.isDisposed()); assertTrue(d.isDisposed()); } @Test public void onSuccessCleansUp() { TestResourceMaybeObserver<Integer> rmo = new TestResourceMaybeObserver<Integer>(); assertFalse(rmo.isDisposed()); Disposable d = Disposables.empty(); rmo.add(d); assertFalse(d.isDisposed()); rmo.onSuccess(1); assertTrue(rmo.isDisposed()); assertTrue(d.isDisposed()); } @Test public void onErrorCleansUp() { TestResourceMaybeObserver<Integer> rmo = new TestResourceMaybeObserver<Integer>(); assertFalse(rmo.isDisposed()); Disposable d = Disposables.empty(); rmo.add(d); assertFalse(d.isDisposed()); rmo.onError(new TestException()); assertTrue(rmo.isDisposed()); assertTrue(d.isDisposed()); } @Test public void normal() { TestResourceMaybeObserver<Integer> rmo = new TestResourceMaybeObserver<Integer>(); assertFalse(rmo.isDisposed()); assertEquals(0, rmo.start); assertNull(rmo.value); assertTrue(rmo.errors.isEmpty()); Maybe.just(1).subscribe(rmo); assertTrue(rmo.isDisposed()); assertEquals(1, rmo.start); assertEquals(Integer.valueOf(1), rmo.value); assertEquals(0, rmo.complete); assertTrue(rmo.errors.isEmpty()); } @Test public void empty() { TestResourceMaybeObserver<Integer> rmo = new TestResourceMaybeObserver<Integer>(); assertFalse(rmo.isDisposed()); assertEquals(0, rmo.start); assertNull(rmo.value); assertTrue(rmo.errors.isEmpty()); Maybe.<Integer>empty().subscribe(rmo); assertTrue(rmo.isDisposed()); assertEquals(1, rmo.start); assertNull(rmo.value); assertEquals(1, rmo.complete); assertTrue(rmo.errors.isEmpty()); } @Test public void error() { TestResourceMaybeObserver<Integer> rmo = new TestResourceMaybeObserver<Integer>(); assertFalse(rmo.isDisposed()); assertEquals(0, rmo.start); assertNull(rmo.value); assertTrue(rmo.errors.isEmpty()); final RuntimeException error = new RuntimeException("error"); Maybe.<Integer>error(error).subscribe(rmo); assertTrue(rmo.isDisposed()); assertEquals(1, rmo.start); assertNull(rmo.value); assertEquals(0, rmo.complete); assertEquals(1, rmo.errors.size()); assertTrue(rmo.errors.contains(error)); } @Test public void startOnce() { List<Throwable> error = TestHelper.trackPluginErrors(); try { TestResourceMaybeObserver<Integer> rmo = new TestResourceMaybeObserver<Integer>(); rmo.onSubscribe(Disposables.empty()); Disposable d = Disposables.empty(); rmo.onSubscribe(d); assertTrue(d.isDisposed()); assertEquals(1, rmo.start); TestHelper.assertError(error, 0, IllegalStateException.class, EndConsumerHelper.composeMessage(rmo.getClass().getName())); } finally { RxJavaPlugins.reset(); } } @Test public void dispose() { TestResourceMaybeObserver<Integer> rmo = new TestResourceMaybeObserver<Integer>(); rmo.dispose(); Disposable d = Disposables.empty(); rmo.onSubscribe(d); assertTrue(d.isDisposed()); assertEquals(0, rmo.start); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.cluster; import com.carrotsearch.hppc.ObjectContainer; import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import org.elasticsearch.Version; import org.elasticsearch.cluster.ClusterState.Custom; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.repositories.IndexId; import org.elasticsearch.snapshots.Snapshot; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Meta data about snapshots that are currently executing */ public class SnapshotsInProgress extends AbstractNamedDiffable<Custom> implements Custom { public static final String TYPE = "snapshots"; // denotes an undefined repository state id, which will happen when receiving a cluster state with // a snapshot in progress from a pre 5.2.x node public static final long UNDEFINED_REPOSITORY_STATE_ID = -2L; // the version where repository state ids were introduced private static final Version REPOSITORY_ID_INTRODUCED_VERSION = Version.V_5_2_0_UNRELEASED; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SnapshotsInProgress that = (SnapshotsInProgress) o; if (!entries.equals(that.entries)) return false; return true; } @Override public int hashCode() { return entries.hashCode(); } @Override public String toString() { StringBuilder builder = new StringBuilder("SnapshotsInProgress["); for (int i = 0; i < entries.size(); i++) { builder.append(entries.get(i).snapshot().getSnapshotId().getName()); if (i + 1 < entries.size()) { builder.append(","); } } return builder.append("]").toString(); } public static class Entry { private final State state; private final Snapshot snapshot; private final boolean includeGlobalState; private final boolean partial; private final ImmutableOpenMap<ShardId, ShardSnapshotStatus> shards; private final List<IndexId> indices; private final ImmutableOpenMap<String, List<ShardId>> waitingIndices; private final long startTime; private final long repositoryStateId; public Entry(Snapshot snapshot, boolean includeGlobalState, boolean partial, State state, List<IndexId> indices, long startTime, long repositoryStateId, ImmutableOpenMap<ShardId, ShardSnapshotStatus> shards) { this.state = state; this.snapshot = snapshot; this.includeGlobalState = includeGlobalState; this.partial = partial; this.indices = indices; this.startTime = startTime; if (shards == null) { this.shards = ImmutableOpenMap.of(); this.waitingIndices = ImmutableOpenMap.of(); } else { this.shards = shards; this.waitingIndices = findWaitingIndices(shards); } this.repositoryStateId = repositoryStateId; } public Entry(Entry entry, State state, ImmutableOpenMap<ShardId, ShardSnapshotStatus> shards) { this(entry.snapshot, entry.includeGlobalState, entry.partial, state, entry.indices, entry.startTime, entry.repositoryStateId, shards); } public Entry(Entry entry, ImmutableOpenMap<ShardId, ShardSnapshotStatus> shards) { this(entry, entry.state, shards); } public Snapshot snapshot() { return this.snapshot; } public ImmutableOpenMap<ShardId, ShardSnapshotStatus> shards() { return this.shards; } public State state() { return state; } public List<IndexId> indices() { return indices; } public ImmutableOpenMap<String, List<ShardId>> waitingIndices() { return waitingIndices; } public boolean includeGlobalState() { return includeGlobalState; } public boolean partial() { return partial; } public long startTime() { return startTime; } public long getRepositoryStateId() { return repositoryStateId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry entry = (Entry) o; if (includeGlobalState != entry.includeGlobalState) return false; if (partial != entry.partial) return false; if (startTime != entry.startTime) return false; if (!indices.equals(entry.indices)) return false; if (!shards.equals(entry.shards)) return false; if (!snapshot.equals(entry.snapshot)) return false; if (state != entry.state) return false; if (!waitingIndices.equals(entry.waitingIndices)) return false; if (repositoryStateId != entry.repositoryStateId) return false; return true; } @Override public int hashCode() { int result = state.hashCode(); result = 31 * result + snapshot.hashCode(); result = 31 * result + (includeGlobalState ? 1 : 0); result = 31 * result + (partial ? 1 : 0); result = 31 * result + shards.hashCode(); result = 31 * result + indices.hashCode(); result = 31 * result + waitingIndices.hashCode(); result = 31 * result + Long.hashCode(startTime); result = 31 * result + Long.hashCode(repositoryStateId); return result; } @Override public String toString() { return snapshot.toString(); } private ImmutableOpenMap<String, List<ShardId>> findWaitingIndices(ImmutableOpenMap<ShardId, ShardSnapshotStatus> shards) { Map<String, List<ShardId>> waitingIndicesMap = new HashMap<>(); for (ObjectObjectCursor<ShardId, ShardSnapshotStatus> entry : shards) { if (entry.value.state() == State.WAITING) { List<ShardId> waitingShards = waitingIndicesMap.get(entry.key.getIndex()); if (waitingShards == null) { waitingShards = new ArrayList<>(); waitingIndicesMap.put(entry.key.getIndexName(), waitingShards); } waitingShards.add(entry.key); } } if (waitingIndicesMap.isEmpty()) { return ImmutableOpenMap.of(); } ImmutableOpenMap.Builder<String, List<ShardId>> waitingIndicesBuilder = ImmutableOpenMap.builder(); for (Map.Entry<String, List<ShardId>> entry : waitingIndicesMap.entrySet()) { waitingIndicesBuilder.put(entry.getKey(), Collections.unmodifiableList(entry.getValue())); } return waitingIndicesBuilder.build(); } } /** * Checks if all shards in the list have completed * * @param shards list of shard statuses * @return true if all shards have completed (either successfully or failed), false otherwise */ public static boolean completed(ObjectContainer<ShardSnapshotStatus> shards) { for (ObjectCursor<ShardSnapshotStatus> status : shards) { if (status.value.state().completed() == false) { return false; } } return true; } public static class ShardSnapshotStatus { private final State state; private final String nodeId; private final String reason; public ShardSnapshotStatus(String nodeId) { this(nodeId, State.INIT); } public ShardSnapshotStatus(String nodeId, State state) { this(nodeId, state, null); } public ShardSnapshotStatus(String nodeId, State state, String reason) { this.nodeId = nodeId; this.state = state; this.reason = reason; } public ShardSnapshotStatus(StreamInput in) throws IOException { nodeId = in.readOptionalString(); state = State.fromValue(in.readByte()); reason = in.readOptionalString(); } public State state() { return state; } public String nodeId() { return nodeId; } public String reason() { return reason; } public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(nodeId); out.writeByte(state.value); out.writeOptionalString(reason); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShardSnapshotStatus status = (ShardSnapshotStatus) o; if (nodeId != null ? !nodeId.equals(status.nodeId) : status.nodeId != null) return false; if (reason != null ? !reason.equals(status.reason) : status.reason != null) return false; if (state != status.state) return false; return true; } @Override public int hashCode() { int result = state != null ? state.hashCode() : 0; result = 31 * result + (nodeId != null ? nodeId.hashCode() : 0); result = 31 * result + (reason != null ? reason.hashCode() : 0); return result; } @Override public String toString() { return "ShardSnapshotStatus[state=" + state + ", nodeId=" + nodeId + ", reason=" + reason + "]"; } } public enum State { INIT((byte) 0, false, false), STARTED((byte) 1, false, false), SUCCESS((byte) 2, true, false), FAILED((byte) 3, true, true), ABORTED((byte) 4, false, true), MISSING((byte) 5, true, true), WAITING((byte) 6, false, false); private byte value; private boolean completed; private boolean failed; State(byte value, boolean completed, boolean failed) { this.value = value; this.completed = completed; this.failed = failed; } public byte value() { return value; } public boolean completed() { return completed; } public boolean failed() { return failed; } public static State fromValue(byte value) { switch (value) { case 0: return INIT; case 1: return STARTED; case 2: return SUCCESS; case 3: return FAILED; case 4: return ABORTED; case 5: return MISSING; case 6: return WAITING; default: throw new IllegalArgumentException("No snapshot state for value [" + value + "]"); } } } private final List<Entry> entries; public SnapshotsInProgress(List<Entry> entries) { this.entries = entries; } public SnapshotsInProgress(Entry... entries) { this.entries = Arrays.asList(entries); } public List<Entry> entries() { return this.entries; } public Entry snapshot(final Snapshot snapshot) { for (Entry entry : entries) { final Snapshot curr = entry.snapshot(); if (curr.equals(snapshot)) { return entry; } } return null; } @Override public String getWriteableName() { return TYPE; } public static NamedDiff<Custom> readDiffFrom(StreamInput in) throws IOException { return readDiffFrom(Custom.class, TYPE, in); } public SnapshotsInProgress(StreamInput in) throws IOException { Entry[] entries = new Entry[in.readVInt()]; for (int i = 0; i < entries.length; i++) { Snapshot snapshot = new Snapshot(in); boolean includeGlobalState = in.readBoolean(); boolean partial = in.readBoolean(); State state = State.fromValue(in.readByte()); int indices = in.readVInt(); List<IndexId> indexBuilder = new ArrayList<>(); for (int j = 0; j < indices; j++) { indexBuilder.add(new IndexId(in.readString(), in.readString())); } long startTime = in.readLong(); ImmutableOpenMap.Builder<ShardId, ShardSnapshotStatus> builder = ImmutableOpenMap.builder(); int shards = in.readVInt(); for (int j = 0; j < shards; j++) { ShardId shardId = ShardId.readShardId(in); String nodeId = in.readOptionalString(); State shardState = State.fromValue(in.readByte()); builder.put(shardId, new ShardSnapshotStatus(nodeId, shardState)); } long repositoryStateId = UNDEFINED_REPOSITORY_STATE_ID; if (in.getVersion().onOrAfter(REPOSITORY_ID_INTRODUCED_VERSION)) { repositoryStateId = in.readLong(); } entries[i] = new Entry(snapshot, includeGlobalState, partial, state, Collections.unmodifiableList(indexBuilder), startTime, repositoryStateId, builder.build()); } this.entries = Arrays.asList(entries); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVInt(entries.size()); for (Entry entry : entries) { entry.snapshot().writeTo(out); out.writeBoolean(entry.includeGlobalState()); out.writeBoolean(entry.partial()); out.writeByte(entry.state().value()); out.writeVInt(entry.indices().size()); for (IndexId index : entry.indices()) { index.writeTo(out); } out.writeLong(entry.startTime()); out.writeVInt(entry.shards().size()); for (ObjectObjectCursor<ShardId, ShardSnapshotStatus> shardEntry : entry.shards()) { shardEntry.key.writeTo(out); out.writeOptionalString(shardEntry.value.nodeId()); out.writeByte(shardEntry.value.state().value()); } if (out.getVersion().onOrAfter(REPOSITORY_ID_INTRODUCED_VERSION)) { out.writeLong(entry.repositoryStateId); } } } private static final String REPOSITORY = "repository"; private static final String SNAPSHOTS = "snapshots"; private static final String SNAPSHOT = "snapshot"; private static final String UUID = "uuid"; private static final String INCLUDE_GLOBAL_STATE = "include_global_state"; private static final String PARTIAL = "partial"; private static final String STATE = "state"; private static final String INDICES = "indices"; private static final String START_TIME_MILLIS = "start_time_millis"; private static final String START_TIME = "start_time"; private static final String REPOSITORY_STATE_ID = "repository_state_id"; private static final String SHARDS = "shards"; private static final String INDEX = "index"; private static final String SHARD = "shard"; private static final String NODE = "node"; @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startArray(SNAPSHOTS); for (Entry entry : entries) { toXContent(entry, builder, params); } builder.endArray(); return builder; } public void toXContent(Entry entry, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field(REPOSITORY, entry.snapshot().getRepository()); builder.field(SNAPSHOT, entry.snapshot().getSnapshotId().getName()); builder.field(UUID, entry.snapshot().getSnapshotId().getUUID()); builder.field(INCLUDE_GLOBAL_STATE, entry.includeGlobalState()); builder.field(PARTIAL, entry.partial()); builder.field(STATE, entry.state()); builder.startArray(INDICES); { for (IndexId index : entry.indices()) { index.toXContent(builder, params); } } builder.endArray(); builder.timeValueField(START_TIME_MILLIS, START_TIME, entry.startTime()); builder.field(REPOSITORY_STATE_ID, entry.getRepositoryStateId()); builder.startArray(SHARDS); { for (ObjectObjectCursor<ShardId, ShardSnapshotStatus> shardEntry : entry.shards) { ShardId shardId = shardEntry.key; ShardSnapshotStatus status = shardEntry.value; builder.startObject(); { builder.field(INDEX, shardId.getIndex()); builder.field(SHARD, shardId.getId()); builder.field(STATE, status.state()); builder.field(NODE, status.nodeId()); } builder.endObject(); } } builder.endArray(); builder.endObject(); } }
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.emitter.graphite; import com.codahale.metrics.graphite.Graphite; import com.codahale.metrics.graphite.GraphiteSender; import com.codahale.metrics.graphite.PickledGraphite; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.metamx.emitter.core.Emitter; import com.metamx.emitter.core.Event; import com.metamx.emitter.service.AlertEvent; import com.metamx.emitter.service.ServiceMetricEvent; import io.druid.java.util.common.ISE; import io.druid.java.util.common.logger.Logger; import io.druid.server.log.EmittingRequestLogger; import java.io.IOException; import java.net.SocketException; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Pattern; public class GraphiteEmitter implements Emitter { private static Logger log = new Logger(GraphiteEmitter.class); private final DruidToGraphiteEventConverter graphiteEventConverter; private final GraphiteEmitterConfig graphiteEmitterConfig; private final List<Emitter> alertEmitters; private final List<Emitter> requestLogEmitters; private final AtomicBoolean started = new AtomicBoolean(false); private final LinkedBlockingQueue<GraphiteEvent> eventsQueue; private static final long FLUSH_TIMEOUT = 60000; // default flush wait 1 min private final ScheduledExecutorService exec = Executors.newScheduledThreadPool(2, new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("GraphiteEmitter-%s") .build()); // Thread pool of two in order to schedule flush runnable private AtomicLong countLostEvents = new AtomicLong(0); public GraphiteEmitter( GraphiteEmitterConfig graphiteEmitterConfig, List<Emitter> alertEmitters, List<Emitter> requestLogEmitters ) { this.alertEmitters = alertEmitters; this.requestLogEmitters = requestLogEmitters; this.graphiteEmitterConfig = graphiteEmitterConfig; this.graphiteEventConverter = graphiteEmitterConfig.getDruidToGraphiteEventConverter(); this.eventsQueue = new LinkedBlockingQueue(graphiteEmitterConfig.getMaxQueueSize()); } @Override public void start() { log.info("Starting Graphite Emitter."); synchronized (started) { if (!started.get()) { exec.scheduleAtFixedRate( new ConsumerRunnable(), graphiteEmitterConfig.getFlushPeriod(), graphiteEmitterConfig.getFlushPeriod(), TimeUnit.MILLISECONDS ); started.set(true); } } } @Override public void emit(Event event) { if (!started.get()) { throw new ISE("WTF emit was called while service is not started yet"); } if (event instanceof ServiceMetricEvent) { final GraphiteEvent graphiteEvent = graphiteEventConverter.druidEventToGraphite((ServiceMetricEvent) event); if (graphiteEvent == null) { return; } try { final boolean isSuccessful = eventsQueue.offer( graphiteEvent, graphiteEmitterConfig.getEmitWaitTime(), TimeUnit.MILLISECONDS ); if (!isSuccessful) { if (countLostEvents.getAndIncrement() % 1000 == 0) { log.error( "Lost total of [%s] events because of emitter queue is full. Please increase the capacity or/and the consumer frequency", countLostEvents.get() ); } } } catch (InterruptedException e) { log.error(e, "got interrupted with message [%s]", e.getMessage()); Thread.currentThread().interrupt(); } } else if (event instanceof EmittingRequestLogger.RequestLogEvent) { for (Emitter emitter : requestLogEmitters) { emitter.emit(event); } } else if (!alertEmitters.isEmpty() && event instanceof AlertEvent) { for (Emitter emitter : alertEmitters) { emitter.emit(event); } } else if (event instanceof AlertEvent) { AlertEvent alertEvent = (AlertEvent) event; log.error( "The following alert is dropped, description is [%s], severity is [%s]", alertEvent.getDescription(), alertEvent.getSeverity() ); } else { log.error("unknown event type [%s]", event.getClass()); } } private class ConsumerRunnable implements Runnable { private final GraphiteSender graphite; public ConsumerRunnable() { if (graphiteEmitterConfig.getProtocol().equals(GraphiteEmitterConfig.PLAINTEXT_PROTOCOL)) { graphite = new Graphite( graphiteEmitterConfig.getHostname(), graphiteEmitterConfig.getPort() ); } else { graphite = new PickledGraphite( graphiteEmitterConfig.getHostname(), graphiteEmitterConfig.getPort(), graphiteEmitterConfig.getBatchSize() ); } log.info("Using %s protocol.", graphiteEmitterConfig.getProtocol()); } @Override public void run() { try { if (!graphite.isConnected()) { log.info("trying to connect to graphite server"); graphite.connect(); } while (eventsQueue.size() > 0 && !exec.isShutdown()) { try { final GraphiteEvent graphiteEvent = eventsQueue.poll( graphiteEmitterConfig.getWaitForEventTime(), TimeUnit.MILLISECONDS ); if (graphiteEvent != null) { log.debug( "sent [%s] with value [%s] and time [%s]", graphiteEvent.getEventPath(), graphiteEvent.getValue(), graphiteEvent.getTimestamp() ); graphite.send( graphiteEvent.getEventPath(), graphiteEvent.getValue(), graphiteEvent.getTimestamp() ); } } catch (InterruptedException | IOException e) { log.error(e, e.getMessage()); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); break; } else if (e instanceof SocketException) { // This is antagonistic to general Closeable contract in Java, // it is needed to allow re-connection in case of the socket is closed due long period of inactivity graphite.close(); log.warn("Trying to re-connect to graphite server"); graphite.connect(); } } } } catch (Exception e) { log.error(e, e.getMessage()); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } } } @Override public void flush() throws IOException { if (started.get()) { Future future = exec.schedule(new ConsumerRunnable(), 0, TimeUnit.MILLISECONDS); try { future.get(FLUSH_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { if (e instanceof InterruptedException) { throw new RuntimeException("interrupted flushing elements from queue", e); } log.error(e, e.getMessage()); } } } @Override public void close() throws IOException { flush(); started.set(false); exec.shutdown(); } protected static String sanitize(String namespace) { return sanitize(namespace, false); } protected static String sanitize(String namespace, Boolean replaceSlashToDot) { Pattern DOT_OR_WHITESPACE = Pattern.compile("[\\s]+|[.]+"); String sanitizedNamespace = DOT_OR_WHITESPACE.matcher(namespace).replaceAll("_"); if (replaceSlashToDot) { sanitizedNamespace = sanitizedNamespace.replace("/", "."); } return sanitizedNamespace; } }
/* * 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.felix.ipojo.test.scenarios.configuration; import java.util.Properties; import org.apache.felix.ipojo.ComponentInstance; import org.apache.felix.ipojo.junit4osgi.OSGiTestCase; import org.apache.felix.ipojo.test.scenarios.configuration.service.FooService; import org.apache.felix.ipojo.test.scenarios.util.Utils; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; public class UpdatedNoArgMethodAndManagedService extends OSGiTestCase { /** * Instance where the ManagedServicePID is provided by the component type. */ ComponentInstance instance1; /** * Instance where the ManagedServicePID is provided by the instance. */ ComponentInstance instance2; /** * Instance without configuration. */ ComponentInstance instance3; public void setUp() { String type = "CONFIG-FooProviderType-4Updated2"; Properties p = new Properties(); p.put("instance.name","instance"); p.put("foo", "foo"); p.put("bar", "2"); p.put("baz", "baz"); instance1 = Utils.getComponentInstance(getContext(), type, p); assertEquals("instance1 created", ComponentInstance.VALID,instance1.getState()); type = "CONFIG-FooProviderType-3Updated2"; Properties p1 = new Properties(); p1.put("instance.name","instance-2"); p1.put("foo", "foo"); p1.put("bar", "2"); p1.put("baz", "baz"); p1.put("managed.service.pid", "instance"); instance2 = Utils.getComponentInstance(getContext(), type, p1); type = "CONFIG-FooProviderType-3Updated2"; Properties p2 = new Properties(); p2.put("instance.name","instance-3"); p2.put("managed.service.pid", "instance-3"); instance3 = Utils.getComponentInstance(getContext(), type, p2); } public void tearDown() { instance1.dispose(); instance2.dispose(); instance3.dispose(); instance1 = null; instance2 = null; instance3 = null; } public void testStaticInstance1() { ServiceReference fooRef = Utils.getServiceReferenceByName(getContext(), FooService.class.getName(), instance1.getInstanceName()); assertNotNull("Check FS availability", fooRef); String fooP = (String) fooRef.getProperty("foo"); Integer barP = (Integer) fooRef.getProperty("bar"); String bazP = (String) fooRef.getProperty("baz"); assertEquals("Check foo equality -1", fooP, "foo"); assertEquals("Check bar equality -1", barP, new Integer(2)); assertEquals("Check baz equality -1", bazP, "baz"); ServiceReference msRef = Utils.getServiceReferenceByPID(getContext(), ManagedService.class.getName(), "FooProvider-3"); assertNotNull("Check ManagedServiceFactory availability", msRef); // Configuration of baz Properties conf = new Properties(); conf.put("baz", "zab"); conf.put("bar", new Integer(2)); conf.put("foo", "foo"); ManagedService ms = (ManagedService) getContext().getService(msRef); try { ms.updated(conf); } catch (ConfigurationException e) { fail("Configuration Exception : " + e); } // Re-check props fooRef = Utils.getServiceReferenceByName(getContext(), FooService.class.getName(), instance1.getInstanceName()); fooP = (String) fooRef.getProperty("foo"); barP = (Integer) fooRef.getProperty("bar"); bazP = (String) fooRef.getProperty("baz"); assertEquals("Check foo equality -2", fooP, "foo"); assertEquals("Check bar equality -2", barP, new Integer(2)); assertEquals("Check baz equality -2", bazP, "zab"); // Get Service FooService fs = (FooService) context.getService(fooRef); Integer updated = (Integer) fs.fooProps().get("updated"); assertEquals("Check updated", 1, updated.intValue()); context.ungetService(fooRef); getContext().ungetService(msRef); } public void testStaticInstance2() { ServiceReference fooRef = Utils.getServiceReferenceByName(getContext(), FooService.class.getName(), instance2.getInstanceName()); assertNotNull("Check FS availability", fooRef); String fooP = (String) fooRef.getProperty("foo"); Integer barP = (Integer) fooRef.getProperty("bar"); String bazP = (String) fooRef.getProperty("baz"); assertEquals("Check foo equality -1", fooP, "foo"); assertEquals("Check bar equality -1", barP, new Integer(2)); assertEquals("Check baz equality -1", bazP, "baz"); ServiceReference msRef = Utils.getServiceReferenceByPID(getContext(), ManagedService.class.getName(), "instance"); assertNotNull("Check ManagedService availability", msRef); // Configuration of baz Properties conf = new Properties(); conf.put("baz", "zab"); conf.put("bar", new Integer(2)); conf.put("foo", "foo"); ManagedService ms = (ManagedService) getContext().getService(msRef); try { ms.updated(conf); } catch (ConfigurationException e) { fail("Configuration Exception : " + e); } // Recheck props fooRef = Utils.getServiceReferenceByName(getContext(), FooService.class.getName(), instance2.getInstanceName()); fooP = (String) fooRef.getProperty("foo"); barP = (Integer) fooRef.getProperty("bar"); bazP = (String) fooRef.getProperty("baz"); assertEquals("Check foo equality -2", fooP, "foo"); assertEquals("Check bar equality -2", barP, new Integer(2)); assertEquals("Check baz equality -2", bazP, "zab"); // Get Service FooService fs = (FooService) context.getService(fooRef); Integer updated = (Integer) fs.fooProps().get("updated"); assertEquals("Check updated", 1, updated.intValue()); conf.put("baz", "zab2"); conf.put("foo", "oof2"); conf.put("bar", new Integer(0)); ms = (ManagedService) getContext().getService(msRef); try { ms.updated(conf); } catch (ConfigurationException e) { fail("Configuration Exception : " + e); } updated = (Integer) fs.fooProps().get("updated"); assertEquals("Check updated -2", 2, updated.intValue()); getContext().ungetService(fooRef); getContext().ungetService(msRef); } public void testDynamicInstance1() { ServiceReference fooRef = Utils.getServiceReferenceByName(getContext(), FooService.class.getName(), instance1.getInstanceName()); assertNotNull("Check FS availability", fooRef); String fooP = (String) fooRef.getProperty("foo"); Integer barP = (Integer) fooRef.getProperty("bar"); String bazP = (String) fooRef.getProperty("baz"); assertEquals("Check foo equality", fooP, "foo"); assertEquals("Check bar equality", barP, new Integer(2)); assertEquals("Check baz equality", bazP, "baz"); ServiceReference msRef = Utils.getServiceReferenceByPID(getContext(), ManagedService.class.getName(), "FooProvider-3"); assertNotNull("Check ManagedServiceFactory availability", msRef); // Configuration of baz Properties conf = new Properties(); conf.put("baz", "zab"); conf.put("foo", "oof"); conf.put("bar", new Integer(0)); ManagedService ms = (ManagedService) getContext().getService(msRef); try { ms.updated(conf); } catch (ConfigurationException e) { fail("Configuration Exception : " + e); } // Re-check props fooRef = Utils.getServiceReferenceByName(getContext(), FooService.class.getName(), instance1.getInstanceName()); fooP = (String) fooRef.getProperty("foo"); barP = (Integer) fooRef.getProperty("bar"); bazP = (String) fooRef.getProperty("baz"); assertEquals("Check foo equality", fooP, "oof"); assertEquals("Check bar equality", barP, new Integer(0)); assertEquals("Check baz equality", bazP, "zab"); // Check field value FooService fs = (FooService) getContext().getService(fooRef); Properties p = fs.fooProps(); fooP = (String) p.get("foo"); barP = (Integer) p.get("bar"); assertEquals("Check foo field equality", fooP, "oof"); assertEquals("Check bar field equality", barP, new Integer(0)); Integer updated = (Integer) fs.fooProps().get("updated"); assertEquals("Check updated -1", 1, updated.intValue()); conf.put("baz", "zab2"); conf.put("foo", "oof2"); conf.put("bar", new Integer(0)); ms = (ManagedService) getContext().getService(msRef); try { ms.updated(conf); } catch (ConfigurationException e) { fail("Configuration Exception : " + e); } updated = (Integer) fs.fooProps().get("updated"); assertEquals("Check updated -2", 2, updated.intValue()); getContext().ungetService(fooRef); getContext().ungetService(msRef); } public void testDynamicInstance2() { ServiceReference fooRef = Utils.getServiceReferenceByName(getContext(), FooService.class.getName(), instance2.getInstanceName()); assertNotNull("Check FS availability", fooRef); String fooP = (String) fooRef.getProperty("foo"); Integer barP = (Integer) fooRef.getProperty("bar"); String bazP = (String) fooRef.getProperty("baz"); assertEquals("Check foo equality", fooP, "foo"); assertEquals("Check bar equality", barP, new Integer(2)); assertEquals("Check baz equality", bazP, "baz"); ServiceReference msRef = Utils.getServiceReferenceByPID(getContext(), ManagedService.class.getName(), "instance"); assertNotNull("Check ManagedServiceFactory availability", msRef); // Configuration of baz Properties conf = new Properties(); conf.put("baz", "zab"); conf.put("foo", "oof"); conf.put("bar", new Integer(0)); ManagedService ms = (ManagedService) getContext().getService(msRef); try { ms.updated(conf); } catch (ConfigurationException e) { fail("Configuration Exception : " + e); } // Recheck props fooRef = Utils.getServiceReferenceByName(getContext(), FooService.class.getName(), instance2.getInstanceName()); fooP = (String) fooRef.getProperty("foo"); barP = (Integer) fooRef.getProperty("bar"); bazP = (String) fooRef.getProperty("baz"); assertEquals("Check foo equality", fooP, "oof"); assertEquals("Check bar equality", barP, new Integer(0)); assertEquals("Check baz equality", bazP, "zab"); // Check field value FooService fs = (FooService) getContext().getService(fooRef); Properties p = fs.fooProps(); fooP = (String) p.get("foo"); barP = (Integer) p.get("bar"); assertEquals("Check foo field equality", fooP, "oof"); assertEquals("Check bar field equality", barP, new Integer(0)); Integer updated = (Integer) fs.fooProps().get("updated"); assertEquals("Check updated", 1, updated.intValue()); conf.put("baz", "zab2"); conf.put("foo", "oof2"); conf.put("bar", new Integer(0)); ms = (ManagedService) getContext().getService(msRef); try { ms.updated(conf); } catch (ConfigurationException e) { fail("Configuration Exception : " + e); } updated = (Integer) fs.fooProps().get("updated"); assertEquals("Check updated -2", 2, updated.intValue()); getContext().ungetService(fooRef); getContext().ungetService(msRef); } }