repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
edduarte/near-neighbor-search
src/main/java/com/edduarte/similarity/converter/SetToSignatureConverter.java
3657
/* * Copyright 2017 Eduardo Duarte * * 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.edduarte.similarity.converter; import java.math.BigDecimal; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Function; /** * Processor class to retrieve shingles of length k. * * @author Eduardo Duarte (<a href="mailto:hi@edduarte.com">hi@edduarte.com</a>) * @version 0.0.1 * @since 0.0.1 */ public final class SetToSignatureConverter implements Function<Collection<? extends Number>, Callable<int[]>> { /** * Random coefficient "a" for the random hash functions */ private final int[] a; /** * Random coefficient "b" for the random hash functions */ private final int[] b; /** * Expected maximum size of the sets to test. This will be the size of the hash signatures. */ private final int n; /** * Size of min hashes that will be stored and compared to find the similarity index */ private final int sigSize; /** * Initializes hashing functions to compute MinHash signatures for sets that could have a maximum * count calculate 'n' elements with a given signature size. */ public SetToSignatureConverter(int n, int sigSize) { this.n = n; this.sigSize = sigSize; SecureRandom r = new SecureRandom(); this.a = new int[sigSize]; this.b = new int[sigSize]; for (int i = 0; i < sigSize; i++) { a[i] = 1 + r.nextInt(this.n - 1); b[i] = r.nextInt(this.n); } } @Override public Callable<int[]> apply(Collection<? extends Number> c) { List<BigDecimal> list = new ArrayList<>(); for (Number number : c) { if (number instanceof Double) { list.add(BigDecimal.valueOf(number.doubleValue())); } else { list.add(BigDecimal.valueOf(number.longValue())); } } list.sort(Comparator.naturalOrder()); return new HashCallable(n, sigSize, a, b, list); } private static class HashCallable implements Callable<int[]> { private static final int LARGE_PRIME = 433494437; private final int n; private final int sigSize; private final int[] a; private final int[] b; private final List<? extends Number> sortedList; private HashCallable( int n, int sigSize, int[] a, int[] b, List<? extends Number> sortedList) { this.n = n; this.sigSize = sigSize; this.a = a; this.b = b; this.sortedList = sortedList; } @Override public int[] call() { int[] signature = new int[sigSize]; for (int i = 0; i < sigSize; i++) { signature[i] = Integer.MAX_VALUE; } for (final Number x : sortedList) { for (int i = 0; i < sigSize; i++) { signature[i] = Math.min(signature[i], universalHashing(i, x)); } } return signature; } private int universalHashing(int i, Number x) { return (int) ((a[i] * x.longValue() + b[i]) % LARGE_PRIME) % n; } } }
apache-2.0
googleapis/java-bigquery
samples/snippets/src/main/java/com/example/bigquery/QueryExternalSheetsTemp.java
4205
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.bigquery; // [START bigquery_query_external_sheets_temp] import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.BigQueryOptions; import com.google.cloud.bigquery.ExternalTableDefinition; import com.google.cloud.bigquery.Field; import com.google.cloud.bigquery.GoogleSheetsOptions; import com.google.cloud.bigquery.QueryJobConfiguration; import com.google.cloud.bigquery.Schema; import com.google.cloud.bigquery.StandardSQLTypeName; import com.google.cloud.bigquery.TableResult; import com.google.common.collect.ImmutableSet; import java.io.IOException; // Sample to queries an external data source using a temporary table public class QueryExternalSheetsTemp { public static void main(String[] args) { // TODO(developer): Replace these variables before running the sample. String tableName = "MY_TABLE_NAME"; String sourceUri = "https://docs.google.com/spreadsheets/d/1i_QCL-7HcSyUZmIbP9E6lO_T5u3HnpLe7dnpHaijg_E/edit?usp=sharing"; Schema schema = Schema.of( Field.of("name", StandardSQLTypeName.STRING), Field.of("post_abbr", StandardSQLTypeName.STRING)); String query = String.format("SELECT * FROM %s WHERE name LIKE 'W%%'", tableName); queryExternalSheetsTemp(tableName, sourceUri, schema, query); } public static void queryExternalSheetsTemp( String tableName, String sourceUri, Schema schema, String query) { try { // Create credentials with Drive & BigQuery API scopes. // Both APIs must be enabled for your project before running this code. // [START bigquery_auth_drive_scope] GoogleCredentials credentials = ServiceAccountCredentials.getApplicationDefault() .createScoped( ImmutableSet.of( "https://www.googleapis.com/auth/bigquery", "https://www.googleapis.com/auth/drive")); // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. BigQuery bigquery = BigQueryOptions.newBuilder().setCredentials(credentials).build().getService(); // [END bigquery_auth_drive_scope] // Skip header row in the file. GoogleSheetsOptions sheetsOptions = GoogleSheetsOptions.newBuilder() .setSkipLeadingRows(1) // Optionally skip header row. .setRange("us-states!A20:B49") // Optionally set range of the sheet to query from. .build(); // Configure the external data source and query job. ExternalTableDefinition externalTable = ExternalTableDefinition.newBuilder(sourceUri, sheetsOptions).setSchema(schema).build(); QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(query) .addTableDefinition(tableName, externalTable) .build(); // Example query to find states starting with 'W' TableResult results = bigquery.query(queryConfig); results .iterateAll() .forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString()))); System.out.println("Query on external temporary table performed successfully."); } catch (BigQueryException | InterruptedException | IOException e) { System.out.println("Query not performed \n" + e.toString()); } } } // [END bigquery_query_external_sheets_temp]
apache-2.0
bgamecho/arduino2android
src/org/egokituz/arduino2android/TestApplication.java
11546
/** * */ package org.egokituz.arduino2android; import java.util.ArrayList; import java.util.HashMap; import org.egokituz.arduino2android.activities.SettingsActivity; import org.egokituz.arduino2android.models.BatteryData; import org.egokituz.arduino2android.models.CPUData; import org.egokituz.arduino2android.models.TestData; import org.egokituz.arduino2android.models.TestError; import org.egokituz.arduino2android.models.TestEvent; import org.egokituz.arduino2android.models.TestStatistics; import android.annotation.SuppressLint; import android.app.Application; import android.content.Context; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.util.Log; import android.widget.Toast; /** * Core class of the app. Manages the creation and start of all the other components or modules * of the app. * <br> * Acts as a central point of control: all the communication between components goes through this class, * much like in the "Listener" pattern. Each component communicates its messages to the main Application, * and this in turn propagates that message to the other components. * * @author Xabier Gardeazabal * */ public class TestApplication extends Application { public final static String TAG = "TestApplication"; // Tag to identify this class' messages in the console or LogCat //TODO REQUEST_ENABLE_BT is a request code that we provide (It's really just a number that you provide for onActivityResult) public static final int REQUEST_ENABLE_BT = 1; public static final int MESSAGE_DATA_READ = 2; public static final int MESSAGE_BATTERY_STATE_CHANGED = 4; public static final int MESSAGE_CPU_USAGE = 5; public static final int MESSAGE_PING_READ = 6; public static final int MESSAGE_ERROR_READING = 7; public static final int MESSAGE_BT_EVENT = 8; public static final int MESSAGE_PREFERENCE_CHANGED = 9; //// Module threads /////////////////// private BTManagerThread m_BTManager_thread; private BatteryMonitorThread m_BatteryMonitor_thread; private LoggerThread m_Logger_thread; private CPUMonitorThread m_cpuMonitor_thread; public StatisticsThread m_statistics_thread; public boolean m_finishApp; // Flag for managing activity termination private HashMap<String, Integer> m_testPlanParameters; // Used to store current plan settings private ArrayList<Handler> m_dataListeners = new ArrayList<Handler>();; private Context m_AppContext; @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); m_AppContext = getApplicationContext(); // set flags m_finishApp = false; // set and start the thread handler if(!m_handlerThread.isAlive()) m_handlerThread.start(); // Initialize the local handler createHandler(); // Instantiate the different modules required for a test. Note that the modules are not started, only created. m_BatteryMonitor_thread = new BatteryMonitorThread(m_AppContext, mainAppHandler); m_cpuMonitor_thread = new CPUMonitorThread(m_AppContext, mainAppHandler); m_Logger_thread = new LoggerThread(m_AppContext, mainAppHandler); m_statistics_thread = new StatisticsThread(m_AppContext, mainAppHandler); // start running the module threads startModuleThreads(); // register the data listeners registerTestDataListener(m_Logger_thread.loggerThreadHandler); registerTestDataListener(m_statistics_thread.statisticsThreadHandler); } /** * Starts the module threads if they are not already started */ private void startModuleThreads(){ // Start the logger thread if(!m_Logger_thread.isAlive()) m_Logger_thread.start(); //Start the Battery monitoring modules' thread if(!m_BatteryMonitor_thread.isAlive()) m_BatteryMonitor_thread.start(); // Start the CPU monitoring module if(!m_cpuMonitor_thread.isAlive()) m_cpuMonitor_thread.start(); // Start the statistics monitor module if(!m_statistics_thread.isAlive()) m_statistics_thread.start(); // Instantiate the Bluetooth Manager thread try { m_BTManager_thread = new BTManagerThread(m_AppContext, mainAppHandler); } catch (Exception e) { e.printStackTrace(); // show a small message shortly (a Toast) Toast.makeText(m_AppContext, "Could not start the BT manager", Toast.LENGTH_SHORT).show(); } } @Override protected void finalize() throws Throwable { super.finalize(); Log.v(TAG, "finalize()"); //Finalize threads if(!m_finishApp){ m_BTManager_thread.finalize(); m_BatteryMonitor_thread.finalize(); m_cpuMonitor_thread.finalize(); m_Logger_thread.finalize(); //Shut down the HandlerThread m_handlerThread.quit(); } m_finishApp = true; } /** * <p>Retrieves the current test parapemeters from the app's preferences, * notifies the logger to begin its work, sends the test parameters to the * BluetoothManager module, and finally starts said module. */ public void beginTest(){ // Retrieve the test parameters from the app's settings/preferences m_testPlanParameters = (HashMap<String, Integer>) SettingsActivity.getCurrentPreferences(m_AppContext); // Tell the logger that a new Test has begun //NOT ANYMORE: a new log folder may be created with the new parameters m_Logger_thread.loggerThreadHandler.obtainMessage(LoggerThread.MESSAGE_NEW_TEST, m_testPlanParameters).sendToTarget(); // send the test parameters to the BluetoothManager-thread // Set the Bluetooth Manager's plan with the selected parameters Message sendMsg; sendMsg = m_BTManager_thread.btHandler.obtainMessage(BTManagerThread.MESSAGE_SET_SCENARIO,m_testPlanParameters); sendMsg.sendToTarget(); // Begin a new test if(m_BTManager_thread.isAlive()){ m_BTManager_thread.finalize(); try { m_BTManager_thread.join(); m_BTManager_thread = new BTManagerThread(m_AppContext, mainAppHandler); } catch (Exception e) { e.printStackTrace(); } } m_BTManager_thread.start(); } /** * Stops the ongoing test in a safe way */ public void stopTest() { // Stop ongoing test modules m_BTManager_thread.finalize(); } /** * Thread container for the handler of this application. <br> * {@link HandlerThread}: Class for starting a new thread that has a looper. * The looper can then be used to create handler classes. */ private HandlerThread m_handlerThread = new HandlerThread("MyHandlerThread"); public Handler mainAppHandler; /** * Creates and initialized the local handler. It also registers it on a HandlerThread's looper. */ private void createHandler(){ mainAppHandler = new Handler(m_handlerThread.getLooper()) { @SuppressWarnings("unchecked") @SuppressLint("NewApi") @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_PING_READ: // Message received from a running Arduino Thread // This message implies that 99 well formed PING messages were read by an Arduino Thread ArrayList<TestData> pingQueue = (ArrayList<TestData>) msg.obj; communicateToDataListeners(TestData.DATA_PING, pingQueue); // write to log file //m_Logger_thread.m_logHandler.obtainMessage(LoggerThread.MESSAGE_PING, pingQueue).sendToTarget(); break; case MESSAGE_DATA_READ: // Message received from a running Arduino Thread // This message implies that 99 well formed DATA messages were read by an Arduino Thread ArrayList<TestData> dataQueue = (ArrayList<TestData>) msg.obj; communicateToDataListeners(TestData.DATA_STRESS, dataQueue); //m_Logger_thread.m_logHandler.obtainMessage(LoggerThread.MESSAGE_WRITE_DATA, dataQueue).sendToTarget(); break; case MESSAGE_BATTERY_STATE_CHANGED: // Message received from the Battery-Monitor Thread // This message implies that the Battery percentage has changed /* Float batteryLoad = (Float) msg.obj; timestamp = msg.getData().getLong("TIMESTAMP"); // call the Logger to write the battery load sendMsg = timestamp+" "+batteryLoad; m_Logger_thread.m_logHandler.obtainMessage(LoggerThread.MESSAGE_WRITE_BATTERY, sendMsg).sendToTarget(); */ BatteryData battery = (BatteryData) msg.obj; communicateToDataListeners(TestData.DATA_BATTERY, battery); //m_Logger_thread.m_logHandler.obtainMessage(LoggerThread.MESSAGE_WRITE_BATTERY, battery).sendToTarget(); //m_dataListener.obtainMessage(TestData.DATA_BATTERY, battery).sendToTarget(); break; case MESSAGE_CPU_USAGE: // Message received from a running Arduino Thread // This message implies that a malformed message has been read by an Arduino Thread /* Float cpu = (Float) msg.obj; timestamp = msg.getData().getLong("TIMESTAMP"); // call the Logger to write the battery load sendMsg = timestamp+" "+cpu; m_Logger_thread.m_logHandler.obtainMessage(LoggerThread.MESSAGE_CPU, sendMsg).sendToTarget(); */ // send data to the ChartFragment CPUData cpu = (CPUData) msg.obj; communicateToDataListeners(TestData.DATA_CPU, cpu); //m_Logger_thread.m_logHandler.obtainMessage(LoggerThread.MESSAGE_CPU, data).sendToTarget(); //m_dataListener.obtainMessage(TestData.DATA_CPU, data).sendToTarget(); break; case MESSAGE_ERROR_READING: // Message received from the CPU-Monitor Thread // This message implies that the CPU usage has changed TestError error = (TestError) msg.obj; communicateToDataListeners(TestData.DATA_ERROR, error); // write to log file //m_Logger_thread.m_logHandler.obtainMessage(LoggerThread.MESSAGE_ERROR, error).sendToTarget(); break; case MESSAGE_BT_EVENT: // Message received from the CPU-Monitor Thread // This message implies that the CPU usage has changed TestEvent event = (TestEvent) msg.obj; communicateToDataListeners(TestData.DATA_EVENT, event); // write to log file //m_Logger_thread.m_logHandler.obtainMessage(LoggerThread.MESSAGE_EVENT, event).sendToTarget(); int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(m_AppContext, event.toString(), duration); toast.show(); break; case TestData.DATA_STATISTIC: TestStatistics statistics = (TestStatistics) msg.obj; communicateToDataListeners(TestData.DATA_STATISTIC, statistics); break; } } }; } /** * @return the m_BTManager */ public BTManagerThread getBTManager() { return m_BTManager_thread; } /** * @return the m_BatteryMonitor */ public BatteryMonitorThread getBatteryMonitor() { return m_BatteryMonitor_thread; } /** * @return the m_Logger */ public LoggerThread getLogger() { return m_Logger_thread; } /** * @return the m_cpuMonitor */ public CPUMonitorThread getCPUMonitor() { return m_cpuMonitor_thread; } public void registerTestDataListener(Handler h){ m_dataListeners.add(h); } private void communicateToDataListeners(int what, Object o){ for(Handler h : m_dataListeners){ h.obtainMessage(what, o).sendToTarget(); } } public boolean isTestOngoing(){ if(m_BTManager_thread != null) return m_BTManager_thread.isAlive(); return false; } }
apache-2.0
AdaptiveMe/adaptive-arp-api-lib-java
src/main/java/me/adaptive/arp/api/IOS.java
1843
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:carlos@adaptive.me> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:ferran.vila.conesa@gmail.com> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ package me.adaptive.arp.api; import java.io.Serializable; /** Interface for Managing the OS operations @author Carlos Lozano Diez @since v2.0 @version 1.0 */ public interface IOS extends IBaseSystem, Serializable { /** Returns the OSInfo for the current operating system. @return OSInfo with name, version and vendor of the OS. @since v2.0 */ OSInfo getOSInfo(); } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
Activiti/Activiti
activiti-api/activiti-api-process-model/src/main/java/org/activiti/api/process/runtime/events/ProcessCancelledEvent.java
898
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * 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.activiti.api.process.runtime.events; import org.activiti.api.process.model.ProcessInstance; import org.activiti.api.process.model.events.ProcessRuntimeEvent; public interface ProcessCancelledEvent extends ProcessRuntimeEvent<ProcessInstance> { String getCause(); }
apache-2.0
wangsongpeng/jdk-src
src/main/java/com/sun/corba/se/PortableActivationIDL/LocatorHolder.java
892
package com.sun.corba.se.PortableActivationIDL; /** * com/sun/corba/se/PortableActivationIDL/LocatorHolder.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from /HUDSON3/workspace/8-2-build-linux-amd64/jdk8u121/8372/corba/src/share/classes/com/sun/corba/se/PortableActivationIDL/activation.idl * Monday, December 12, 2016 4:37:46 PM PST */ public final class LocatorHolder implements org.omg.CORBA.portable.Streamable { public Locator value = null; public LocatorHolder () { } public LocatorHolder (Locator initialValue) { value = initialValue; } public void _read (org.omg.CORBA.portable.InputStream i) { value = LocatorHelper.read (i); } public void _write (org.omg.CORBA.portable.OutputStream o) { LocatorHelper.write (o, value); } public org.omg.CORBA.TypeCode _type () { return LocatorHelper.type (); } }
apache-2.0
jexp/idea2
plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EclipseClasspathWriter.java
19699
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * User: anna * Date: 11-Nov-2008 */ package org.jetbrains.idea.eclipse.conversion; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PathMacroManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.impl.ProjectRootManagerImpl; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.CharFilter; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.ex.http.HttpFileSystem; import com.intellij.pom.java.LanguageLevel; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.eclipse.EclipseXml; import org.jetbrains.idea.eclipse.IdeaXml; import java.io.File; import java.util.ArrayList; import java.util.List; public class EclipseClasspathWriter { private ModifiableRootModel myModel; public EclipseClasspathWriter(final ModifiableRootModel model) { myModel = model; } public void writeClasspath(Element classpathElement, @Nullable Element oldRoot) throws ConversionException { for (OrderEntry orderEntry : myModel.getOrderEntries()) { createClasspathEntry(orderEntry, classpathElement, oldRoot); } @NonNls String outputPath = "bin"; if (myModel.getContentEntries().length == 1) { final VirtualFile contentRoot = myModel.getContentEntries()[0].getFile(); final VirtualFile output = myModel.getModuleExtension(CompilerModuleExtension.class).getCompilerOutputPath(); if (contentRoot != null && output != null && VfsUtil.isAncestor(contentRoot, output, false)) { outputPath = getRelativePath(output.getUrl()); } else if (output == null) { outputPath = getRelativePath(myModel.getModuleExtension(CompilerModuleExtension.class).getCompilerOutputUrl()); } } final Element orderEntry = addOrderEntry(EclipseXml.OUTPUT_KIND, outputPath, classpathElement, oldRoot); setAttributeIfAbsent(orderEntry, EclipseXml.PATH_ATTR, EclipseXml.BIN_DIR); } private void createClasspathEntry(OrderEntry entry, Element classpathRoot, Element oldRoot) throws ConversionException { if (entry instanceof ModuleSourceOrderEntry) { final ContentEntry[] entries = ((ModuleSourceOrderEntry)entry).getRootModel().getContentEntries(); if (entries.length > 0) { final ContentEntry contentEntry = entries[0]; for (SourceFolder sourceFolder : contentEntry.getSourceFolders()) { addOrderEntry(EclipseXml.SRC_KIND, getRelativePath(sourceFolder.getUrl()), classpathRoot, oldRoot); } } } else if (entry instanceof ModuleOrderEntry) { Element orderEntry = addOrderEntry(EclipseXml.SRC_KIND, "/" + ((ModuleOrderEntry)entry).getModuleName(), classpathRoot, oldRoot); setAttributeIfAbsent(orderEntry, EclipseXml.COMBINEACCESSRULES_ATTR, EclipseXml.FALSE_VALUE); setExported(orderEntry, ((ExportableOrderEntry)entry)); } else if (entry instanceof LibraryOrderEntry) { final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)entry; final String libraryName = libraryOrderEntry.getLibraryName(); if (libraryOrderEntry.isModuleLevel()) { final String[] files = libraryOrderEntry.getUrls(OrderRootType.CLASSES); if (files.length > 0) { if (libraryName != null && libraryName.contains(IdeaXml.JUNIT) && Comparing.strEqual(files[0], EclipseClasspathReader.getJunitClsUrl(libraryName.contains("4")))) { final Element orderEntry = addOrderEntry(EclipseXml.CON_KIND, EclipseXml.JUNIT_CONTAINER + "/" + libraryName.substring(IdeaXml.JUNIT.length()), classpathRoot, oldRoot); setExported(orderEntry, libraryOrderEntry); } else { final Project project = myModel.getModule().getProject(); final String[] kind = new String[]{EclipseXml.LIB_KIND}; String relativeClassPath = getRelativePath(files[0], kind); final String[] srcFiles = libraryOrderEntry.getUrls(OrderRootType.SOURCES); final String relativePath; if (srcFiles.length == 0) { relativePath = null; } else { final String[] srcKind = new String[1]; final boolean replaceVarsInSrc = Comparing.strEqual(kind[0], EclipseXml.VAR_KIND); relativePath = getRelativePath(srcFiles[srcFiles.length - 1], srcKind, replaceVarsInSrc, project, getContentRoot()); if (replaceVarsInSrc && srcKind[0] == null) { kind[0] = EclipseXml.LIB_KIND; relativeClassPath = getRelativePath(files[0], kind, false, project, getContentRoot()); } } final Element orderEntry = addOrderEntry(kind[0], relativeClassPath, classpathRoot, oldRoot); setOrRemoveAttribute(orderEntry, EclipseXml.SOURCEPATH_ATTR, relativePath); //clear javadocs before write new final List children = new ArrayList(orderEntry.getChildren(EclipseXml.ATTRIBUTES_TAG)); for (Object o : children) { ((Element)o).detach(); } final String[] docUrls = libraryOrderEntry.getUrls(JavadocOrderRootType.getInstance()); for (final String docUrl : docUrls) { setJavadocPath(orderEntry, docUrl); } setExported(orderEntry, libraryOrderEntry); } } } else { final Element orderEntry; if (Comparing.strEqual(libraryName, IdeaXml.ECLIPSE_LIBRARY)) { orderEntry = addOrderEntry(EclipseXml.CON_KIND, EclipseXml.ECLIPSE_PLATFORM, classpathRoot, oldRoot); } else { orderEntry = addOrderEntry(EclipseXml.CON_KIND, EclipseXml.USER_LIBRARY + "/" + libraryName, classpathRoot, oldRoot); } setExported(orderEntry, libraryOrderEntry); } } else if (entry instanceof JdkOrderEntry) { if (entry instanceof InheritedJdkOrderEntry) { addOrderEntry(EclipseXml.CON_KIND, EclipseXml.JRE_CONTAINER, classpathRoot, oldRoot); } else { final Sdk jdk = ((JdkOrderEntry)entry).getJdk(); String jdkLink; if (jdk == null) { jdkLink = EclipseXml.JRE_CONTAINER; } else { jdkLink = EclipseXml.JRE_CONTAINER; if (jdk.getSdkType() instanceof JavaSdkType) { jdkLink += EclipseXml.JAVA_SDK_TYPE; } jdkLink += "/" + jdk.getName(); } addOrderEntry(EclipseXml.CON_KIND, jdkLink, classpathRoot, oldRoot); } } else { throw new ConversionException("Unknown EclipseProjectModel.ClasspathEntry: " + entry.getClass()); } } private String getRelativePath(String srcFile, String[] kind) { return getRelativePath(srcFile, kind, true, myModel.getModule().getProject(), getContentRoot()); } private String getRelativePath(String url) { return getRelativePath(url, new String[1]); } public static String getRelativePath(final String url, String[] kind, boolean replaceVars, final Project project, final VirtualFile contentRoot) { final VirtualFile projectBaseDir = contentRoot != null ? contentRoot.getParent() : project.getBaseDir(); assert projectBaseDir != null; VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url); if (file != null) { if (file.getFileSystem() instanceof JarFileSystem) { file = JarFileSystem.getInstance().getVirtualFileForJar(file); } assert file != null; if (contentRoot != null) { if (VfsUtil.isAncestor(contentRoot, file, false)) { return VfsUtil.getRelativePath(file, contentRoot, '/'); } else { final Module module = ModuleUtil.findModuleForFile(file, project); if (module != null) { final VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots(); for (VirtualFile otherRoot : contentRoots) { if (VfsUtil.isAncestor(otherRoot, file, false)) { return "/" + module.getName() + "/" + VfsUtil.getRelativePath(file, otherRoot, '/'); } } } } } if (VfsUtil.isAncestor(projectBaseDir, file, false)) { return "/" + VfsUtil.getRelativePath(file, projectBaseDir, '/'); } else { return replaceVars ? stripIDEASpecificPrefix(url, kind) : ProjectRootManagerImpl.extractLocalPath(url); } } else { if (contentRoot != null) { final String rootUrl = contentRoot.getUrl(); if (url.startsWith(rootUrl) && url.length() > rootUrl.length()) { return url.substring(rootUrl.length() + 1); //without leading / } } final String projectUrl = projectBaseDir.getUrl(); if (url.startsWith(projectUrl)) { return url.substring(projectUrl.length()); //leading / } return replaceVars ? stripIDEASpecificPrefix(url, kind) : ProjectRootManagerImpl.extractLocalPath(url); } } @Nullable private VirtualFile getContentRoot() { final ContentEntry[] entries = myModel.getContentEntries(); if (entries.length > 0) { return entries[0].getFile(); } return null; } private void setJavadocPath(final Element element, String javadocPath) { if (javadocPath != null) { Element child = new Element(EclipseXml.ATTRIBUTES_TAG); element.addContent(child); Element attrElement = child.getChild(EclipseXml.ATTRIBUTE_TAG); if (attrElement == null) { attrElement = new Element(EclipseXml.ATTRIBUTE_TAG); child.addContent(attrElement); } attrElement.setAttribute("name", "javadoc_location"); final String protocol = VirtualFileManager.extractProtocol(javadocPath); if (!Comparing.strEqual(protocol, HttpFileSystem.getInstance().getProtocol())) { final String path = VfsUtil.urlToPath(javadocPath); final VirtualFile contentRoot = getContentRoot(); final VirtualFile baseDir = contentRoot != null ? contentRoot.getParent() : myModel.getProject().getBaseDir(); if (Comparing.strEqual(protocol, JarFileSystem.getInstance().getProtocol())) { final VirtualFile javadocFile = JarFileSystem.getInstance().getVirtualFileForJar(VirtualFileManager.getInstance().findFileByUrl(javadocPath)); if (javadocFile != null && VfsUtil.isAncestor(baseDir, javadocFile, false)) { if (javadocPath.indexOf(JarFileSystem.JAR_SEPARATOR) == -1) { javadocPath = StringUtil.trimEnd(javadocPath, "/") + JarFileSystem.JAR_SEPARATOR; } javadocPath = EclipseXml.JAR_PREFIX + EclipseXml.PLATFORM_PROTOCOL + "resource/" + VfsUtil.getRelativePath(javadocFile, baseDir, '/') + javadocPath.substring(javadocFile.getUrl().length() - 1); } else { javadocPath = EclipseXml.JAR_PREFIX + EclipseXml.FILE_PROTOCOL + StringUtil.trimStart(path, "/"); } } else if (new File(path).exists()) { javadocPath = EclipseXml.FILE_PROTOCOL + StringUtil.trimStart(path, "/"); } } attrElement.setAttribute("value", javadocPath); } } private static String stripIDEASpecificPrefix(String path, String[] kind) { String stripped = StringUtil .strip(ProjectRootManagerImpl.extractLocalPath(PathMacroManager.getInstance(ApplicationManager.getApplication()).collapsePath(path)), new CharFilter() { public boolean accept(final char ch) { return ch != '$'; } }); boolean leaveLeadingSlash = false; if (!Comparing.strEqual(stripped, ProjectRootManagerImpl.extractLocalPath(path))) { leaveLeadingSlash = kind[0] == null; kind[0] = EclipseXml.VAR_KIND; } return (leaveLeadingSlash ? "/" : "") + stripped; } public boolean writeIDEASpecificClasspath(final Element root) throws WriteExternalException { boolean isModified = false; final CompilerModuleExtension compilerModuleExtension = myModel.getModuleExtension(CompilerModuleExtension.class); if (compilerModuleExtension.getCompilerOutputPathForTests() != null) { final Element pathElement = new Element(IdeaXml.OUTPUT_TEST_TAG); pathElement.setAttribute(IdeaXml.URL_ATTR, compilerModuleExtension.getCompilerOutputUrlForTests()); root.addContent(pathElement); isModified = true; } if (compilerModuleExtension.isCompilerOutputPathInherited()) { root.setAttribute(IdeaXml.INHERIT_COMPILER_OUTPUT_ATTR, String.valueOf(true)); isModified = true; } if (compilerModuleExtension.isExcludeOutput()) { root.addContent(new Element(IdeaXml.EXCLUDE_OUTPUT_TAG)); isModified = true; } final LanguageLevelModuleExtension languageLevelModuleExtension = myModel.getModuleExtension(LanguageLevelModuleExtension.class); final LanguageLevel languageLevel = languageLevelModuleExtension.getLanguageLevel(); if (languageLevel != null) { languageLevelModuleExtension.writeExternal(root); isModified = true; } for (ContentEntry entry : myModel.getContentEntries()) { final Element contentEntryElement = new Element(IdeaXml.CONTENT_ENTRY_TAG); contentEntryElement.setAttribute(IdeaXml.URL_ATTR, entry.getUrl()); root.addContent(contentEntryElement); for (SourceFolder sourceFolder : entry.getSourceFolders()) { if (sourceFolder.isTestSource()) { Element element = new Element(IdeaXml.TEST_FOLDER_TAG); contentEntryElement.addContent(element); element.setAttribute(IdeaXml.URL_ATTR, sourceFolder.getUrl()); isModified = true; } } final VirtualFile entryFile = entry.getFile(); for (ExcludeFolder excludeFolder : entry.getExcludeFolders()) { final String exludeFolderUrl = excludeFolder.getUrl(); final VirtualFile excludeFile = excludeFolder.getFile(); if (entryFile == null || excludeFile == null || VfsUtil.isAncestor(entryFile, excludeFile, false)) { Element element = new Element(IdeaXml.EXCLUDE_FOLDER_TAG); contentEntryElement.addContent(element); element.setAttribute(IdeaXml.URL_ATTR, exludeFolderUrl); isModified = true; } } } for (OrderEntry entry : myModel.getOrderEntries()) { if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).isModuleLevel()) { final Element element = new Element("lib"); element.setAttribute("name", entry.getPresentableName()); final DependencyScope scope = ((LibraryOrderEntry)entry).getScope(); element.setAttribute("scope", scope.name()); final String[] urls = entry.getUrls(OrderRootType.SOURCES); if (urls.length > 1) { for (int i = 0; i < urls.length - 1; i++) { Element srcElement = new Element("srcroot"); srcElement.setAttribute("url", urls[i]); element.addContent(srcElement); } } for (String srcUrl : entry.getUrls(OrderRootType.SOURCES)) { appendModuleRelatedRoot(element, srcUrl, "relative-module-src"); } for (String classesUrl : entry.getUrls(OrderRootType.CLASSES)) { appendModuleRelatedRoot(element, classesUrl, "relative-module-cls"); } if (!element.getChildren().isEmpty() || !scope.equals(DependencyScope.COMPILE)) root.addContent(element); } } PathMacroManager.getInstance(myModel.getModule()).collapsePaths(root); return isModified; } private boolean appendModuleRelatedRoot(Element element, String classesUrl, final String rootMame) { VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(classesUrl); if (file != null) { if (file.getFileSystem() instanceof JarFileSystem) { file = JarFileSystem.getInstance().getVirtualFileForJar(file); assert file != null; } final Module module = ModuleUtil.findModuleForFile(file, myModel.getProject()); if (module != null && module != myModel.getModule()) { final VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots(); if (contentRoots.length > 0 && VfsUtil.isAncestor(contentRoots[0], file, false)) { final Element clsElement = new Element(rootMame); clsElement.setAttribute("project-related", PathMacroManager.getInstance(module.getProject()).collapsePath(classesUrl)); element.addContent(clsElement); return true; } } } return false; } private static Element addOrderEntry(String kind, String path, Element classpathRoot, Element oldRoot) { if (oldRoot != null) { for (Object o : oldRoot.getChildren(EclipseXml.CLASSPATHENTRY_TAG)) { final Element oldChild = (Element)o; final String oldKind = oldChild.getAttributeValue(EclipseXml.KIND_ATTR); final String oldPath = oldChild.getAttributeValue(EclipseXml.PATH_ATTR); if (Comparing.strEqual(kind, oldKind) && Comparing.strEqual(path, oldPath)) { final Element element = (Element)oldChild.clone(); classpathRoot.addContent(element); return element; } } } Element orderEntry = new Element(EclipseXml.CLASSPATHENTRY_TAG); orderEntry.setAttribute(EclipseXml.KIND_ATTR, kind); if (path != null) { orderEntry.setAttribute(EclipseXml.PATH_ATTR, path); } classpathRoot.addContent(orderEntry); return orderEntry; } private static void setExported(Element orderEntry, ExportableOrderEntry dependency) { setOrRemoveAttribute(orderEntry, EclipseXml.EXPORTED_ATTR, dependency.isExported() ? EclipseXml.TRUE_VALUE : null); } private static void setOrRemoveAttribute(Element element, String name, String value) { if (value != null) { element.setAttribute(name, value); } else { element.removeAttribute(name); } } private static void setAttributeIfAbsent(Element element, String name, String value) { if (element.getAttribute(name) == null) { element.setAttribute(name, value); } } }
apache-2.0
r1912697476/LoveYou
LoveYou/app/src/main/java/com/rao/loveyou/libraary/getui/GetTuiIntentService.java
1759
package com.rao.loveyou.libraary.getui; import android.content.Context; import android.content.Intent; import android.util.Log; import com.igexin.sdk.GTIntentService; import com.igexin.sdk.message.GTCmdMessage; import com.igexin.sdk.message.GTTransmitMessage; import com.rao.loveyou.app.App; import com.rao.loveyou.ui.activity.FuLiActivity; /** * @auther rjl * @time 2017/9/18. * @descr */ public class GetTuiIntentService extends GTIntentService { private static final String TAG = "GetTuiIntentService"; @Override public void onReceiveServicePid(Context context, int i) { Log.i(TAG, "onReceiveServicePid: "+i); } @Override public void onReceiveClientId(Context context, String s) { Log.i(TAG, "onReceiveClientId: "+s); } @Override public void onReceiveMessageData(Context context, GTTransmitMessage gtTransmitMessage) { Log.i(TAG, "onReceiveMessageData: ------------"); byte[] payload = gtTransmitMessage.getPayload(); if (null ==payload){ Log.e(TAG, "onReceiveMessageData: payload is null" + payload.length); }else { Log.i(TAG, "onReceiveMessageData: "+new String(payload)); Intent intent = new Intent(); intent.setClass(App.getApplication(), FuLiActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); App.getApplication().startActivity(intent); } } @Override public void onReceiveOnlineState(Context context, boolean b) { Log.i(TAG, "onReceiveOnlineState: "+b); } @Override public void onReceiveCommandResult(Context context, GTCmdMessage gtCmdMessage) { Log.i(TAG, "onReceiveCommandResult: "+gtCmdMessage.toString()); } }
apache-2.0
lookout/clouddriver
clouddriver-ecs/src/main/java/com/netflix/spinnaker/clouddriver/ecs/controllers/EcsImagesController.java
2182
/* * Copyright 2017 Lookout, 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.netflix.spinnaker.clouddriver.ecs.controllers; import com.netflix.spinnaker.clouddriver.ecs.model.EcsDockerImage; import com.netflix.spinnaker.clouddriver.ecs.provider.view.ImageRepositoryProvider; import org.springframework.beans.factory.annotation.Autowired; 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.RestController; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("/ecs/images") public class EcsImagesController { private final List<ImageRepositoryProvider> imageRepositoryProviders; @Autowired public EcsImagesController(List<ImageRepositoryProvider> imageRepositoryProviders) { this.imageRepositoryProviders = imageRepositoryProviders; } @RequestMapping(value = "/find", method = RequestMethod.GET) public List<EcsDockerImage> findImage(@RequestParam("q") String dockerImageUrl, HttpServletRequest request) { for (ImageRepositoryProvider provider : imageRepositoryProviders) { if (provider.handles(dockerImageUrl)) { return provider.findImage(dockerImageUrl); } } throw new Error("The URL is not support by any of the providers. Currently enabled and supported providers are: " + imageRepositoryProviders.stream(). map(ImageRepositoryProvider::getRepositoryName). collect(Collectors.joining(", ")) + "."); } }
apache-2.0
googleinterns/step100-2020
capstone/src/main/java/com/google/sps/search/servlets/SearchResultsServlet.java
4831
package com.google.sps.search.servlets; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.Filter; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.sps.Objects.User; import com.google.sps.error.ErrorHandler; import com.google.sps.graph.Dijkstra; import com.google.sps.graph.UserEdge; import com.google.sps.graph.UserVertex; import com.google.sps.servlets.AuthenticatedServlet; import com.google.sps.servlets.ServletHelper; @WebServlet("/search-results") public class SearchResultsServlet extends AuthenticatedServlet { private static final double COMPLETE_MATCH = 10; @Override public void doGet(String userId, HttpServletRequest request, HttpServletResponse response) throws IOException { String names = request.getParameter("names"); String searchString = request.getParameter("searchString"); String[] namesSplit = names.split(","); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); List<User> users = this.getUserSuggestions(namesSplit, searchString, datastore, response); ServletHelper.write(response, users, "application/json"); } private List<User> getUserSuggestions( String[] namesSplit, String searchString, DatastoreService datastore, HttpServletResponse response) throws IOException { List<User> users = new ArrayList<User>(); Map<User, Double> namesScore = new LinkedHashMap<User, Double>(); UserService userService = UserServiceFactory.getUserService(); String userId = ""; if (userService.isUserLoggedIn()) { userId = userService.getCurrentUser().getUserId(); } for (String name : namesSplit) { Filter propertyFilter = new FilterPredicate("fullName", FilterOperator.EQUAL, name.toUpperCase()); Query query = new Query("User").setFilter(propertyFilter); PreparedQuery pq = datastore.prepare(query); for (Entity result : pq.asIterable()) { try { users.add(User.fromEntity(result)); namesScore = this.runDijkstra(namesScore, userId, searchString, User.fromEntity(result)); } catch (EntityNotFoundException e) { ErrorHandler.sendError(response, "Entity not found."); } } } return this.sortUsers(namesScore); } private Map<User, Double> runDijkstra( Map<User, Double> namesScore, String currUserId, String searchString, User destUser) { Dijkstra<UserVertex, UserEdge> dijkstra = new Dijkstra<UserVertex, UserEdge>(); UserVertex srcVertex = new UserVertex(currUserId); UserVertex destVertex = new UserVertex(destUser.getUserId()); double distance = dijkstra.runDijkstra(srcVertex, destVertex).getDistance(); if (!namesScore.containsKey(destUser)) { namesScore.put(destUser, 1 / distance); } // If search string is a complete match with result name, increment score String destUserName = destUser.getFirstName() + " " + destUser.getLastName(); if (searchString.toUpperCase().equals(destUserName.toUpperCase())) { namesScore.put(destUser, namesScore.get(destUser) + COMPLETE_MATCH); } return namesScore; } private List<User> sortUsers(Map<User, Double> namesScore) { List<User> sortedUsers = new ArrayList<User>(); List<Map.Entry<User, Double>> entries = new ArrayList<Map.Entry<User, Double>>(namesScore.entrySet()); Collections.sort( entries, new Comparator<Map.Entry<User, Double>>() { @Override public int compare(Map.Entry<User, Double> a, Map.Entry<User, Double> b) { return Double.compare(b.getValue(), a.getValue()); } }); for (Map.Entry<User, Double> entry : entries) { sortedUsers.add(entry.getKey()); } return sortedUsers; } @Override public void doPost(String userId, HttpServletRequest request, HttpServletResponse response) throws IOException { // TODO Auto-generated method stub } }
apache-2.0
dgrlucky/Awesome
library/src/main/java/com/library/http/okhttp/callback/BitmapCallback.java
412
package com.library.http.okhttp.callback; import java.io.IOException; import okhttp3.Response; import android.graphics.Bitmap; import android.graphics.BitmapFactory; public abstract class BitmapCallback extends Callback<Bitmap> { @Override public Bitmap parseNetworkResponse(Response response) throws IOException { return BitmapFactory.decodeStream(response.body().byteStream()); } }
apache-2.0
OpenGamma/Strata
modules/pricer/src/main/java/com/opengamma/strata/pricer/capfloor/SabrIborCapletFloorletVolatilityCalibrator.java
14199
/* * Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.pricer.capfloor; import static com.opengamma.strata.math.impl.linearalgebra.DecompositionFactory.SV_COMMONS; import static com.opengamma.strata.math.impl.matrix.MatrixAlgebraFactory.OG_ALGEBRA; import java.time.LocalDate; import java.time.Period; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.function.Function; import com.google.common.collect.ImmutableList; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.currency.Currency; import com.opengamma.strata.basics.index.IborIndex; import com.opengamma.strata.collect.ArgChecker; import com.opengamma.strata.collect.array.DoubleArray; import com.opengamma.strata.collect.array.DoubleMatrix; import com.opengamma.strata.market.curve.Curve; import com.opengamma.strata.market.curve.CurveMetadata; import com.opengamma.strata.market.curve.CurveName; import com.opengamma.strata.market.param.CurrencyParameterSensitivities; import com.opengamma.strata.market.sensitivity.PointSensitivities; import com.opengamma.strata.market.surface.Surface; import com.opengamma.strata.market.surface.SurfaceMetadata; import com.opengamma.strata.math.impl.minimization.DoubleRangeLimitTransform; import com.opengamma.strata.math.impl.minimization.NonLinearTransformFunction; import com.opengamma.strata.math.impl.minimization.ParameterLimitsTransform; import com.opengamma.strata.math.impl.minimization.ParameterLimitsTransform.LimitType; import com.opengamma.strata.math.impl.minimization.SingleRangeLimitTransform; import com.opengamma.strata.math.impl.minimization.UncoupledParameterTransforms; import com.opengamma.strata.math.impl.statistics.leastsquare.LeastSquareResults; import com.opengamma.strata.math.impl.statistics.leastsquare.LeastSquareResultsWithTransform; import com.opengamma.strata.math.impl.statistics.leastsquare.NonLinearLeastSquare; import com.opengamma.strata.pricer.model.SabrParameters; import com.opengamma.strata.pricer.option.RawOptionData; import com.opengamma.strata.pricer.rate.RatesProvider; import com.opengamma.strata.product.capfloor.ResolvedIborCapFloorLeg; /** * Caplet volatilities calibration to cap volatilities based on SABR model. * <p> * The SABR parameters are represented by {@code NodalCurve}. * The node positions on the individual curves are flexible * and defined in {@code SabrIborCapletFloorletVolatilityCalibrationDefinition}. * The resulting volatilities object will be {@link SabrParametersIborCapletFloorletVolatilities}. * <p> * The calibration to SABR is computed once the option volatility date is converted to prices. * Thus the error values in {@code RawOptionData} are applied in the price space rather than the volatility space. */ public class SabrIborCapletFloorletVolatilityCalibrator extends IborCapletFloorletVolatilityCalibrator { /** * Default implementation. */ public static final SabrIborCapletFloorletVolatilityCalibrator DEFAULT = of( VolatilityIborCapFloorLegPricer.DEFAULT, SabrIborCapFloorLegPricer.DEFAULT, 1.0e-10, ReferenceData.standard()); /** * Transformation for SABR parameters. */ private static final ParameterLimitsTransform[] TRANSFORMS; /** * SABR parameter range. */ private static final double RHO_LIMIT = 0.999; static { TRANSFORMS = new ParameterLimitsTransform[4]; TRANSFORMS[0] = new SingleRangeLimitTransform(0.0, LimitType.GREATER_THAN); // alpha > 0 TRANSFORMS[1] = new DoubleRangeLimitTransform(0.0, 1.0); // 0 <= beta <= 1 TRANSFORMS[2] = new DoubleRangeLimitTransform(-RHO_LIMIT, RHO_LIMIT); // -1 <= rho <= 1 TRANSFORMS[3] = new DoubleRangeLimitTransform(0.001d, 2.50d); // nu > 0 and limit on Nu to avoid numerical instability in formula for large nu. } /** * The nonlinear least square solver. */ private final NonLinearLeastSquare solver; /** * SABR pricer for cap/floor leg. */ private final SabrIborCapFloorLegPricer sabrPricer; //------------------------------------------------------------------------- /** * Creates an instance. * <p> * The epsilon is the parameter used in {@link NonLinearLeastSquare}, where the iteration stops when certain * quantities are smaller than this parameter. * * @param pricer the cap pricer * @param sabrPricer the SABR cap pricer * @param epsilon the epsilon parameter * @param referenceData the reference data * @return the instance */ public static SabrIborCapletFloorletVolatilityCalibrator of( VolatilityIborCapFloorLegPricer pricer, SabrIborCapFloorLegPricer sabrPricer, double epsilon, ReferenceData referenceData) { NonLinearLeastSquare solver = new NonLinearLeastSquare(SV_COMMONS, OG_ALGEBRA, epsilon); return new SabrIborCapletFloorletVolatilityCalibrator(pricer, sabrPricer, solver, referenceData); } // private constructor private SabrIborCapletFloorletVolatilityCalibrator( VolatilityIborCapFloorLegPricer pricer, SabrIborCapFloorLegPricer sabrPricer, NonLinearLeastSquare solver, ReferenceData referenceData) { super(pricer, referenceData); this.sabrPricer = ArgChecker.notNull(sabrPricer, "sabrPricer"); this.solver = ArgChecker.notNull(solver, "solver"); } //------------------------------------------------------------------------- @Override public IborCapletFloorletVolatilityCalibrationResult calibrate( IborCapletFloorletVolatilityDefinition definition, ZonedDateTime calibrationDateTime, RawOptionData capFloorData, RatesProvider ratesProvider) { ArgChecker.isTrue(ratesProvider.getValuationDate().equals(calibrationDateTime.toLocalDate()), "valuationDate of ratesProvider should be coherent to calibrationDateTime"); ArgChecker.isTrue(definition instanceof SabrIborCapletFloorletVolatilityCalibrationDefinition, "definition should be SabrIborCapletFloorletVolatilityCalibrationDefinition"); SabrIborCapletFloorletVolatilityCalibrationDefinition sabrDefinition = (SabrIborCapletFloorletVolatilityCalibrationDefinition) definition; // unpack cap data, create node caps IborIndex index = sabrDefinition.getIndex(); LocalDate calibrationDate = calibrationDateTime.toLocalDate(); LocalDate baseDate = index.getEffectiveDateOffset().adjust(calibrationDate, getReferenceData()); LocalDate startDate = baseDate.plus(index.getTenor()); Function<Surface, IborCapletFloorletVolatilities> volatilitiesFunction = volatilitiesFunction( sabrDefinition, calibrationDateTime, capFloorData); SurfaceMetadata metadata = sabrDefinition.createMetadata(capFloorData); List<Period> expiries = capFloorData.getExpiries(); DoubleArray strikes = capFloorData.getStrikes(); int nExpiries = expiries.size(); List<Double> timeList = new ArrayList<>(); List<Double> strikeList = new ArrayList<>(); List<Double> volList = new ArrayList<>(); List<ResolvedIborCapFloorLeg> capList = new ArrayList<>(); List<Double> priceList = new ArrayList<>(); List<Double> errorList = new ArrayList<>(); DoubleMatrix errorMatrix = capFloorData.getError().orElse(DoubleMatrix.filled(nExpiries, strikes.size(), 1d)); int[] startIndex = new int[nExpiries + 1]; for (int i = 0; i < nExpiries; ++i) { LocalDate endDate = baseDate.plus(expiries.get(i)); DoubleArray volatilityForTime = capFloorData.getData().row(i); DoubleArray errorForTime = errorMatrix.row(i); reduceRawData(sabrDefinition, ratesProvider, capFloorData.getStrikes(), volatilityForTime, errorForTime, startDate, endDate, metadata, volatilitiesFunction, timeList, strikeList, volList, capList, priceList, errorList); startIndex[i + 1] = volList.size(); ArgChecker.isTrue(startIndex[i + 1] > startIndex[i], "no valid option data for {}", expiries.get(i)); } // create initial caplet vol surface List<CurveMetadata> metadataList = sabrDefinition.createSabrParameterMetadata(); DoubleArray initialValues = sabrDefinition.createFullInitialValues(); List<Curve> curveList = sabrDefinition.createSabrParameterCurve(metadataList, initialValues); SabrParameters sabrParamsInitial = SabrParameters.of( curveList.get(0), curveList.get(1), curveList.get(2), curveList.get(3), sabrDefinition.getShiftCurve(), sabrDefinition.getSabrVolatilityFormula()); SabrParametersIborCapletFloorletVolatilities vols = SabrParametersIborCapletFloorletVolatilities.of( sabrDefinition.getName(), index, calibrationDateTime, sabrParamsInitial); // solve least square UncoupledParameterTransforms transform = new UncoupledParameterTransforms( initialValues, sabrDefinition.createFullTransform(TRANSFORMS), new BitSet()); Function<DoubleArray, DoubleArray> valueFunction = createPriceFunction( sabrDefinition, ratesProvider, vols, capList, priceList); Function<DoubleArray, DoubleMatrix> jacobianFunction = createJacobianFunction( sabrDefinition, ratesProvider, vols, capList, priceList, index.getCurrency()); NonLinearTransformFunction transFunc = new NonLinearTransformFunction(valueFunction, jacobianFunction, transform); LeastSquareResults res = solver.solve( DoubleArray.filled(priceList.size(), 1d), DoubleArray.copyOf(errorList), transFunc.getFittingFunction(), transFunc.getFittingJacobian(), transform.transform(initialValues)); LeastSquareResultsWithTransform resTransform = new LeastSquareResultsWithTransform(res, transform); vols = updateParameters(sabrDefinition, vols, resTransform.getModelParameters()); return IborCapletFloorletVolatilityCalibrationResult.ofLeastSquare(vols, res.getChiSq()); } // price function private Function<DoubleArray, DoubleArray> createPriceFunction( SabrIborCapletFloorletVolatilityCalibrationDefinition sabrDefinition, RatesProvider ratesProvider, SabrParametersIborCapletFloorletVolatilities volatilities, List<ResolvedIborCapFloorLeg> capList, List<Double> priceList) { Function<DoubleArray, DoubleArray> priceFunction = new Function<DoubleArray, DoubleArray>() { @Override public DoubleArray apply(DoubleArray x) { SabrParametersIborCapletFloorletVolatilities volsNew = updateParameters(sabrDefinition, volatilities, x); return DoubleArray.of(capList.size(), n -> sabrPricer.presentValue(capList.get(n), ratesProvider, volsNew).getAmount() / priceList.get(n)); } }; return priceFunction; } // node sensitivity function private Function<DoubleArray, DoubleMatrix> createJacobianFunction( SabrIborCapletFloorletVolatilityCalibrationDefinition sabrDefinition, RatesProvider ratesProvider, SabrParametersIborCapletFloorletVolatilities volatilities, List<ResolvedIborCapFloorLeg> capList, List<Double> priceList, Currency currency) { int nCaps = capList.size(); SabrParameters sabrParams = volatilities.getParameters(); CurveName alphaName = sabrParams.getAlphaCurve().getName(); CurveName betaName = sabrParams.getBetaCurve().getName(); CurveName rhoName = sabrParams.getRhoCurve().getName(); CurveName nuName = sabrParams.getNuCurve().getName(); Function<DoubleArray, DoubleMatrix> jacobianFunction = new Function<DoubleArray, DoubleMatrix>() { @Override public DoubleMatrix apply(DoubleArray x) { SabrParametersIborCapletFloorletVolatilities volsNew = updateParameters(sabrDefinition, volatilities, x); double[][] jacobian = new double[nCaps][]; for (int i = 0; i < nCaps; ++i) { PointSensitivities point = sabrPricer.presentValueSensitivityModelParamsSabr(capList.get(i), ratesProvider, volsNew).build(); CurrencyParameterSensitivities sensi = volsNew.parameterSensitivity(point); double targetPriceInv = 1d / priceList.get(i); DoubleArray sensitivities = sensi.getSensitivity(alphaName, currency).getSensitivity(); if (sabrDefinition.getBetaCurve().isPresent()) { // beta fixed sensitivities = sensitivities.concat(sensi.getSensitivity(rhoName, currency).getSensitivity()); } else { // rho fixed sensitivities = sensitivities.concat(sensi.getSensitivity(betaName, currency).getSensitivity()); } jacobian[i] = sensitivities.concat(sensi.getSensitivity(nuName, currency).getSensitivity()) .multipliedBy(targetPriceInv) .toArray(); } return DoubleMatrix.ofUnsafe(jacobian); } }; return jacobianFunction; } // update vols private SabrParametersIborCapletFloorletVolatilities updateParameters( SabrIborCapletFloorletVolatilityCalibrationDefinition sabrDefinition, SabrParametersIborCapletFloorletVolatilities volatilities, DoubleArray newValues) { SabrParameters sabrParams = volatilities.getParameters(); CurveMetadata alphaMetadata = sabrParams.getAlphaCurve().getMetadata(); CurveMetadata betaMetadata = sabrParams.getBetaCurve().getMetadata(); CurveMetadata rhoMetadata = sabrParams.getRhoCurve().getMetadata(); CurveMetadata nuMetadata = sabrParams.getNuCurve().getMetadata(); List<Curve> newCurveList = sabrDefinition.createSabrParameterCurve( ImmutableList.of(alphaMetadata, betaMetadata, rhoMetadata, nuMetadata), newValues); SabrParameters newSabrParams = SabrParameters.of( newCurveList.get(0), newCurveList.get(1), newCurveList.get(2), newCurveList.get(3), sabrDefinition.getShiftCurve(), sabrDefinition.getSabrVolatilityFormula()); SabrParametersIborCapletFloorletVolatilities newVols = SabrParametersIborCapletFloorletVolatilities.of( volatilities.getName(), volatilities.getIndex(), volatilities.getValuationDateTime(), newSabrParams); return newVols; } }
apache-2.0
hbs/warp10-platform
warp10/src/main/java/io/warp10/worf/TokenDump.java
2479
// // Copyright 2018 SenX S.A.S. // // 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.warp10.worf; import io.warp10.WarpConfig; import io.warp10.script.MemoryWarpScriptStack; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; public class TokenDump extends TokenGen { public static void main(String[] args) throws Exception { TokenDump instance = new TokenDump(); instance.usage(args); instance.parse(args); instance.process(args); } @Override public void usage(String[] args) { if (args.length < 3) { System.err.println("Usage: TokenDump config ... in out"); System.exit(-1); } } @Override public void process(String[] args) throws Exception { PrintWriter pw = new PrintWriter(System.out); if (!"-".equals(args[args.length - 1])) { pw = new PrintWriter(new FileWriter(args[args.length - 1])); } MemoryWarpScriptStack stack = new MemoryWarpScriptStack(null, null, WarpConfig.getProperties()); stack.maxLimits(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = null; if ("-".equals(args[args.length - 2])) { in = System.in; } else { in = new FileInputStream(args[args.length - 2]); } BufferedReader br = new BufferedReader(new InputStreamReader(in)); boolean json = null != System.getProperty("json"); while (true) { String line = br.readLine(); if ("".equals(line)) { break; } stack.clear(); stack.push(line); stack.exec("TOKENDUMP"); if (json) { stack.exec("->JSON"); } else { stack.exec("SNAPSHOT"); } pw.println(stack.pop().toString()); pw.flush(); } br.close(); pw.flush(); pw.close(); } }
apache-2.0
floodlight/loxigen-artifacts
openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver15/OFAsyncConfigPropPortStatusMasterVer15.java
8170
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver15; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import io.netty.buffer.ByteBuf; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFAsyncConfigPropPortStatusMasterVer15 implements OFAsyncConfigPropPortStatusMaster { private static final Logger logger = LoggerFactory.getLogger(OFAsyncConfigPropPortStatusMasterVer15.class); // version: 1.5 final static byte WIRE_VERSION = 6; final static int LENGTH = 8; private final static long DEFAULT_MASK = 0x0L; // OF message fields private final long mask; // // Immutable default instance final static OFAsyncConfigPropPortStatusMasterVer15 DEFAULT = new OFAsyncConfigPropPortStatusMasterVer15( DEFAULT_MASK ); // package private constructor - used by readers, builders, and factory OFAsyncConfigPropPortStatusMasterVer15(long mask) { this.mask = U32.normalize(mask); } // Accessors for OF message fields @Override public int getType() { return 0x3; } @Override public long getMask() { return mask; } @Override public OFVersion getVersion() { return OFVersion.OF_15; } public OFAsyncConfigPropPortStatusMaster.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFAsyncConfigPropPortStatusMaster.Builder { final OFAsyncConfigPropPortStatusMasterVer15 parentMessage; // OF message fields private boolean maskSet; private long mask; BuilderWithParent(OFAsyncConfigPropPortStatusMasterVer15 parentMessage) { this.parentMessage = parentMessage; } @Override public int getType() { return 0x3; } @Override public long getMask() { return mask; } @Override public OFAsyncConfigPropPortStatusMaster.Builder setMask(long mask) { this.mask = mask; this.maskSet = true; return this; } @Override public OFVersion getVersion() { return OFVersion.OF_15; } @Override public OFAsyncConfigPropPortStatusMaster build() { long mask = this.maskSet ? this.mask : parentMessage.mask; // return new OFAsyncConfigPropPortStatusMasterVer15( mask ); } } static class Builder implements OFAsyncConfigPropPortStatusMaster.Builder { // OF message fields private boolean maskSet; private long mask; @Override public int getType() { return 0x3; } @Override public long getMask() { return mask; } @Override public OFAsyncConfigPropPortStatusMaster.Builder setMask(long mask) { this.mask = mask; this.maskSet = true; return this; } @Override public OFVersion getVersion() { return OFVersion.OF_15; } // @Override public OFAsyncConfigPropPortStatusMaster build() { long mask = this.maskSet ? this.mask : DEFAULT_MASK; return new OFAsyncConfigPropPortStatusMasterVer15( mask ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFAsyncConfigPropPortStatusMaster> { @Override public OFAsyncConfigPropPortStatusMaster readFrom(ByteBuf bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property type == 0x3 short type = bb.readShort(); if(type != (short) 0x3) throw new OFParseError("Wrong type: Expected=0x3(0x3), got="+type); int length = U16.f(bb.readShort()); if(length != 8) throw new OFParseError("Wrong length: Expected=8(8), got="+length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); long mask = U32.f(bb.readInt()); OFAsyncConfigPropPortStatusMasterVer15 asyncConfigPropPortStatusMasterVer15 = new OFAsyncConfigPropPortStatusMasterVer15( mask ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", asyncConfigPropPortStatusMasterVer15); return asyncConfigPropPortStatusMasterVer15; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFAsyncConfigPropPortStatusMasterVer15Funnel FUNNEL = new OFAsyncConfigPropPortStatusMasterVer15Funnel(); static class OFAsyncConfigPropPortStatusMasterVer15Funnel implements Funnel<OFAsyncConfigPropPortStatusMasterVer15> { private static final long serialVersionUID = 1L; @Override public void funnel(OFAsyncConfigPropPortStatusMasterVer15 message, PrimitiveSink sink) { // fixed value property type = 0x3 sink.putShort((short) 0x3); // fixed value property length = 8 sink.putShort((short) 0x8); sink.putLong(message.mask); } } public void writeTo(ByteBuf bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFAsyncConfigPropPortStatusMasterVer15> { @Override public void write(ByteBuf bb, OFAsyncConfigPropPortStatusMasterVer15 message) { // fixed value property type = 0x3 bb.writeShort((short) 0x3); // fixed value property length = 8 bb.writeShort((short) 0x8); bb.writeInt(U32.t(message.mask)); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFAsyncConfigPropPortStatusMasterVer15("); b.append("mask=").append(mask); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFAsyncConfigPropPortStatusMasterVer15 other = (OFAsyncConfigPropPortStatusMasterVer15) obj; if( mask != other.mask) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (int) (mask ^ (mask >>> 32)); return result; } }
apache-2.0
nikom1337/dockhand
src/main/java/com/thecookiezen/bussiness/deployment/boundary/DeploymentUnitRepository.java
300
package com.thecookiezen.bussiness.deployment.boundary; import com.thecookiezen.bussiness.deployment.entity.DeploymentUnit; import java.util.Collection; public interface DeploymentUnitRepository { DeploymentUnit save(DeploymentUnit deploymentUnit); Collection<DeploymentUnit> getAll(); }
apache-2.0
DariusX/camel
components/camel-pubnub/src/test/java/org/apache/camel/component/pubnub/example/PubNubSensor2Example.java
5621
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.pubnub.example; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import com.pubnub.api.models.consumer.pubsub.PNMessageResult; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.pubnub.PubNubConstants; import org.apache.camel.main.Main; import static org.apache.camel.component.pubnub.PubNubConstants.OPERATION; import static org.apache.camel.component.pubnub.PubNubConstants.UUID; import static org.apache.camel.component.pubnub.example.PubNubExampleConstants.PUBNUB_PUBLISH_KEY; import static org.apache.camel.component.pubnub.example.PubNubExampleConstants.PUBNUB_SUBSCRIBE_KEY; public final class PubNubSensor2Example { private PubNubSensor2Example() { } public static void main(String[] args) throws Exception { Main main = new Main(); main.configure().addRoutesBuilder(new PubsubRoute()); main.configure().addRoutesBuilder(new SimulatedDeviceEventGeneratorRoute()); main.run(); } static class SimulatedDeviceEventGeneratorRoute extends RouteBuilder { private final String deviceEP = "pubnub:iot?uuid=device2&publishKey=" + PUBNUB_PUBLISH_KEY + "&subscribeKey=" + PUBNUB_SUBSCRIBE_KEY; private final String devicePrivateEP = "pubnub:device2private?uuid=device2&publishKey=" + PUBNUB_PUBLISH_KEY + "&subscribeKey=" + PUBNUB_SUBSCRIBE_KEY; @Override public void configure() throws Exception { from("timer:device2").routeId("device-event-route") .bean(PubNubSensor2Example.EventGeneratorBean.class, "getRandomEvent('device2')") .to(deviceEP); from(devicePrivateEP) .routeId("device-unicast-route") .log("Message from master to device2 : ${body}"); } } static class PubsubRoute extends RouteBuilder { private static String masterEP = "pubnub:iot?uuid=master&subscribeKey=" + PUBNUB_SUBSCRIBE_KEY + "&publishKey=" + PUBNUB_PUBLISH_KEY; private static Map<String, String> devices = new ConcurrentHashMap<>(); @Override public void configure() throws Exception { from(masterEP) .routeId("master-route") .bean(PubNubSensor2Example.PubsubRoute.DataProcessorBean.class, "doSomethingInteresting(${body})") .log("${body} headers : ${headers}").to("mock:result"); //TODO Could remote control device to turn on/off sensor measurement from("timer:master?delay=15000&period=5000").routeId("unicast2device-route") .setHeader(PubNubConstants.CHANNEL, method(PubNubSensor2Example.PubsubRoute.DataProcessorBean.class, "getUnicastChannelOfDevice()")) .setBody(constant("Hello device")) .to(masterEP); } public static class DataProcessorBean { @EndpointInject("pubnub:iot?uuid=master&subscribeKey=" + PUBNUB_SUBSCRIBE_KEY) private static ProducerTemplate template; public static String getUnicastChannelOfDevice() { // just get the first channel return devices.values().iterator().next(); } public static void doSomethingInteresting(PNMessageResult message) { String deviceUUID; deviceUUID = message.getPublisher(); if (devices.get(deviceUUID) == null) { Map<String, Object> headers = new HashMap<>(); headers.put(OPERATION, "WHERENOW"); headers.put(UUID, deviceUUID); @SuppressWarnings("unchecked") java.util.List<String> channels = (java.util.List<String>) template.requestBodyAndHeaders(null, headers); devices.put(deviceUUID, channels.get(0)); } } } } static class DeviceWeatherInfo { private String device; private int humidity; private int temperature; DeviceWeatherInfo(String device) { Random rand = new Random(); this.device = device; this.humidity = rand.nextInt(100); this.temperature = rand.nextInt(40); } public String getDevice() { return device; } public int getHumidity() { return humidity; } public int getTemperature() { return temperature; } } public static class EventGeneratorBean { public static DeviceWeatherInfo getRandomEvent(String device) { return new DeviceWeatherInfo(device); } } }
apache-2.0
aifargonos/elk-reasoner
elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/tracing/package-info.java
997
/** * Interfaces and classes implementing the tracing functionality: storing the information how each conclusion was produced so that inference results can be explained. */ /** * @author Pavel Klinov * * pavel.klinov@uni-ulm.de */ package org.semanticweb.elk.reasoner.tracing; /* * #%L * ELK Reasoner * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2011 - 2014 Department of Computer Science, University of Oxford * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */
apache-2.0
delebash/orientdb-parent
commons/src/main/java/com/orientechnologies/common/serialization/types/OCharSerializer.java
3175
/* * 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.common.serialization.types; import com.orientechnologies.common.directmemory.ODirectMemoryPointer; import com.orientechnologies.common.serialization.OBinaryConverter; import com.orientechnologies.common.serialization.OBinaryConverterFactory; import java.nio.ByteOrder; /** * @author ibershadskiy <a href="mailto:ibersh20@gmail.com">Ilya Bershadskiy</a> * @since 18.01.12 */ public class OCharSerializer implements OBinarySerializer<Character> { private static final OBinaryConverter BINARY_CONVERTER = OBinaryConverterFactory.getConverter(); /** * size of char value in bytes */ public static final int CHAR_SIZE = 2; public static OCharSerializer INSTANCE = new OCharSerializer(); public static final byte ID = 3; public int getObjectSize(final Character object, Object... hints) { return CHAR_SIZE; } public void serialize(final Character object, final byte[] stream, final int startPosition, Object... hints) { stream[startPosition] = (byte) (object >>> 8); stream[startPosition + 1] = (byte) (object.charValue()); } public Character deserialize(final byte[] stream, final int startPosition) { return (char) (((stream[startPosition] & 0xFF) << 8) + (stream[startPosition + 1] & 0xFF)); } public int getObjectSize(final byte[] stream, final int startPosition) { return CHAR_SIZE; } public byte getId() { return ID; } public int getObjectSizeNative(byte[] stream, int startPosition) { return CHAR_SIZE; } public void serializeNative(Character object, byte[] stream, int startPosition, Object... hints) { BINARY_CONVERTER.putChar(stream, startPosition, object, ByteOrder.nativeOrder()); } public Character deserializeNative(byte[] stream, int startPosition) { return BINARY_CONVERTER.getChar(stream, startPosition, ByteOrder.nativeOrder()); } @Override public void serializeInDirectMemory(Character object, ODirectMemoryPointer pointer, long offset, Object... hints) { pointer.setChar(offset, object); } @Override public Character deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) { return pointer.getChar(offset); } @Override public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) { return CHAR_SIZE; } public boolean isFixedLength() { return true; } public int getFixedLength() { return CHAR_SIZE; } @Override public Character preprocess(Character value, Object... hints) { return value; } }
apache-2.0
titze/axmlparser
src/axmlprinter/ManifestData.java
10393
package axmlprinter; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.xml.sax.Attributes; /** * Class containing the manifest info obtained during the parsing. */ public final class ManifestData implements Serializable { /** * Value returned by {@link #getMinSdkVersion()} when the value of the * minSdkVersion attribute in the manifest is a codename and not an integer * value. */ public final static int MIN_SDK_CODENAME = 0; /** * Value returned by {@link #getGlEsVersion()} when there are no * <uses-feature> node with the attribute glEsVersion set. */ public final static int GL_ES_VERSION_NOT_SET = -1; /** Application package */ String mPackage; /** Application version Code, null if the attribute is not present. */ Integer mVersionCode = null; /** List of all activities */ final ArrayList<Activity> mActivities = new ArrayList<Activity>(); /** Launcher activity */ Activity mLauncherActivity = null; /** list of process names declared by the manifest */ Set<String> mProcesses = null; /** debuggable attribute value. If null, the attribute is not present. */ Boolean mDebuggable = null; /** API level requirement. if null the attribute was not present. */ private String mMinSdkVersionString = null; /** * API level requirement. Default is 1 even if missing. If value is a * codename, then it'll be 0 instead. */ private int mMinSdkVersion = 1; private int mTargetSdkVersion = 0; /** List of all instrumentations declared by the manifest */ final ArrayList<Instrumentation> mInstrumentations = new ArrayList<Instrumentation>(); /** List of all libraries in use declared by the manifest */ final ArrayList<UsesLibrary> mLibraries = new ArrayList<UsesLibrary>(); /** List of all feature in use declared by the manifest */ final ArrayList<UsesFeature> mFeatures = new ArrayList<UsesFeature>(); /** hash of all Services providers receivers to SPRNODE **/ final HashMap<String, List<SRPNode>> mSRPToNode = new HashMap<String, List<SRPNode>>(); SupportsScreens mSupportsScreensFromManifest; SupportsScreens mSupportsScreensValues; UsesConfiguration mUsesConfiguration; private Set<String> mUsesPermissions = new HashSet<String>(); private Set<String> mPermissions = new HashSet<String>(); /** * Returns the package defined in the manifest, if found. * * @return The package name or null if not found. */ public String getPackage() { return mPackage; } /** * Returns the versionCode value defined in the manifest, if found, null * otherwise. * * @return the versionCode or null if not found. */ public Integer getVersionCode() { return mVersionCode; } /** * Returns the list of activities found in the manifest. * * @return An array of fully qualified class names, or empty if no activity * were found. */ public Activity[] getActivities() { // System.out.println("I was asked for activities"); mActivities.toArray(new Activity[mActivities.size()]); return mActivities.toArray(new Activity[mActivities.size()]); } /** * Returns the list of activities found in the manifest containing an * IntentFilter * * @return An array of fully qualified class names, or empty if no activity * were found. */ public Activity[] getActivitiesWithIntentFilters() { List<Activity> ret = new ArrayList<Activity>(); for (Activity act : mActivities) { List<IntentFilter> intentFilter = act.getIntentFilters(); if (intentFilter.size() > 0) { ret.add(act); } } return ret.toArray(new Activity[ret.size()]); } /** * Returns the name of one activity found in the manifest, that is * configured to show up in the HOME screen. * * @return the fully qualified name of a HOME activity or null if none were * found. */ public Activity getLauncherActivity() { return mLauncherActivity; } /** * Returns the list of process names declared by the manifest. */ public String[] getProcesses() { if (mProcesses != null) { return mProcesses.toArray(new String[mProcesses.size()]); } return new String[0]; } /** * Returns the <code>debuggable</code> attribute value or null if it is not * set. */ public Boolean getDebuggable() { return mDebuggable; } /** * Returns the <code>minSdkVersion</code> attribute, or null if it's not * set. */ public String getMinSdkVersionString() { return mMinSdkVersionString; } /** * Sets the value of the <code>minSdkVersion</code> attribute. * * @param minSdkVersion * the string value of the attribute in the manifest. */ public void setMinSdkVersionString(String minSdkVersion) { mMinSdkVersionString = minSdkVersion; if (mMinSdkVersionString != null) { try { mMinSdkVersion = Integer.parseInt(mMinSdkVersionString); } catch (NumberFormatException e) { mMinSdkVersion = MIN_SDK_CODENAME; } } } /** * Returns the <code>minSdkVersion</code> attribute, or 0 if it's not set or * is a codename. * * @see #getMinSdkVersionString() */ public int getMinSdkVersion() { return mMinSdkVersion; } /** * Sets the value of the <code>minSdkVersion</code> attribute. * * @param targetSdkVersion * the string value of the attribute in the manifest. */ public void setTargetSdkVersionString(String targetSdkVersion) { if (targetSdkVersion != null) { try { mTargetSdkVersion = Integer.parseInt(targetSdkVersion); } catch (NumberFormatException e) { // keep the value at 0. } } } /** * Returns the <code>targetSdkVersion</code> attribute, or the same value as * {@link #getMinSdkVersion()} if it was not set in the manifest. */ public int getTargetSdkVersion() { if (mTargetSdkVersion == 0) { return getMinSdkVersion(); } return mTargetSdkVersion; } /** * Returns the list of instrumentations found in the manifest. * * @return An array of {@link Instrumentation}, or empty if no * instrumentations were found. */ public Instrumentation[] getInstrumentations() { return mInstrumentations.toArray(new Instrumentation[mInstrumentations.size()]); } /** * Returns the list of libraries in use found in the manifest. * * @return An array of {@link UsesLibrary} objects, or empty if no libraries * were found. */ public UsesLibrary[] getUsesLibraries() { return mLibraries.toArray(new UsesLibrary[mLibraries.size()]); } /** * Returns the list of features in use found in the manifest. * * @return An array of {@link UsesFeature} objects, or empty if no libraries * were found. */ public UsesFeature[] getUsesFeatures() { return mFeatures.toArray(new UsesFeature[mFeatures.size()]); } /** * Returns the glEsVersion from a <uses-feature> or * {@link #GL_ES_VERSION_NOT_SET} if not set. */ public int getGlEsVersion() { for (UsesFeature feature : mFeatures) { if (feature.mGlEsVersion > 0) { return feature.mGlEsVersion; } } return GL_ES_VERSION_NOT_SET; } /** * Returns the {@link SupportsScreens} object representing the * <code>supports-screens</code> node, or null if the node doesn't exist at * all. Some values in the {@link SupportsScreens} instance maybe null, * indicating that they were not present in the manifest. To get an instance * that contains the values, as seen by the Android platform when the app is * running, use {@link #getSupportsScreensValues()}. */ public SupportsScreens getSupportsScreensFromManifest() { return mSupportsScreensFromManifest; } /** * Returns an always non-null instance of {@link SupportsScreens} that's * been initialized with the default values, and the values from the * manifest. The default values depends on the manifest values for * minSdkVersion and targetSdkVersion. */ public synchronized SupportsScreens getSupportsScreensValues() { if (mSupportsScreensValues == null) { if (mSupportsScreensFromManifest == null) { mSupportsScreensValues = SupportsScreens.getDefaultValues(getTargetSdkVersion()); } else { // get a SupportsScreen that replace the missing values with // default values. mSupportsScreensValues = mSupportsScreensFromManifest.resolveSupportsScreensValues(getTargetSdkVersion()); } } return mSupportsScreensValues; } /** * Returns the {@link UsesConfiguration} object representing the * <code>uses-configuration</code> node, or null if the node doesn't exist * at all. */ public UsesConfiguration getUsesConfiguration() { return mUsesConfiguration; } void addProcessName(String processName) { if (mProcesses == null) { mProcesses = new TreeSet<String>(); } if (processName.startsWith(":")) { mProcesses.add(mPackage + processName); } else { mProcesses.add(processName); } } /** * Add a uses-permission attribute * * @param attributeValue */ public void addUsesPermission(String attributeValue) { mUsesPermissions.add(attributeValue); } /** * Returns a list of all permissions required by the app via * uses-permission. */ public Set<String> getUsesPermissions() { return mUsesPermissions; } /** * Returns a list of the permissions which are listed in the manifest * * @return The set of permissions in the the manifest as a set of strings */ public Set<String> getPermissions() { return mPermissions; } /** * Adds a new permission to the set of permissions of this app * * @param mPermissions * The permission to be added. */ public void addPermissions(String mPermissions) { this.mPermissions.add(mPermissions); } public HashMap<String, List<SRPNode>> getSRPToNodeHash() { return mSRPToNode; } public List<SRPNode> getServices() { List<SRPNode> srvs = mSRPToNode.get(SdkConstants.CLASS_SERVICE); return srvs != null ? srvs : new ArrayList<SRPNode>(); } public List<SRPNode> getReceivers() { List<SRPNode> rcvrs = mSRPToNode.get(SdkConstants.CLASS_BROADCASTRECEIVER); return rcvrs != null ? rcvrs : new ArrayList<SRPNode>(); } public List<SRPNode> getProviders() { List<SRPNode> prvdrs = mSRPToNode.get(SdkConstants.CLASS_CONTENTPROVIDER); return prvdrs != null ? prvdrs : new ArrayList<SRPNode>(); } }
apache-2.0
dragonflyor/AndroidDemo_Base
08_03_音乐播放器/src/com/xiaozhe/musicplayer/MusicService.java
625
package com.xiaozhe.musicplayer; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; public class MusicService extends Service { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return new MusicController(); } public void play(){ System.out.println("²¥·ÅÒôÀÖ"); } public void pause(){ System.out.println("ÔÝÍ£²¥·Å"); } class MusicController extends Binder implements MusicInterface{ public void play(){ MusicService.this.play(); } public void pause(){ MusicService.this.pause(); } } }
apache-2.0
pilhuhn/hawkular-android-client
src/main/java/org/hawkular/client/android/util/Uris.java
1872
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.hawkular.client.android.util; import android.net.Uri; import android.support.annotation.NonNull; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; public final class Uris { private Uris() { } @NonNull public static URI getUriFromString(@NonNull String uri) { try { return new URI(uri); } catch (URISyntaxException e) { throw new RuntimeException(e); } } @NonNull public static URI getUri(@NonNull String path) { Uri uri = new Uri.Builder() .appendPath(path) .build(); return Uris.getUriFromString(uri.toString()); } @NonNull public static URI getUri(@NonNull String path, @NonNull Map<String, String> parameters) { Uri.Builder uriBuilder = new Uri.Builder(); uriBuilder.appendPath(path); for (String parameterKey : parameters.keySet()) { String parameterValue = parameters.get(parameterKey); uriBuilder.appendQueryParameter(parameterKey, parameterValue); } Uri uri = uriBuilder.build(); return Uris.getUriFromString(uri.toString()); } }
apache-2.0
heinigger/utils
thirdParty/applibrary/src/main/java/com/yw/fastviewlibrary/view/ProgressView.java
1704
package com.yw.fastviewlibrary.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; /** * Created by heinigger on 2017/4/26. */ public class ProgressView extends View { private Paint mPaint; //进度的颜色 private int mProgressColor = Color.RED; //默认的颜色 private int defaultColor = Color.DKGRAY; private int progress = 50; private int TOTALSIZE = 100; public ProgressView(Context context) { this(context, null); } public ProgressView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ProgressView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); iniPaint(); } private void iniPaint() { mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setColor(defaultColor); } public void setProgress(int progress) { this.progress = progress; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPaint.setColor(defaultColor); canvas.drawRoundRect(new RectF(0, 0, getWidth(), getMeasuredHeight()), getMeasuredWidth() / 2, getMeasuredWidth() / 2, mPaint); mPaint.setColor(mProgressColor); canvas.drawRoundRect(new RectF(0, 0, getWidth() * (progress / (float) TOTALSIZE), getMeasuredHeight()), getMeasuredWidth() / 2, getMeasuredWidth() / 2, mPaint); } }
apache-2.0
ManGroup/Demo
SUN/src/com/sun/app/process/admin/sys/UploadProcess.java
4239
package com.sun.app.process.admin.sys; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.UUID; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.FileCopyUtils; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.sun.app.process.BaseProcess; import com.sun.core.util.CommonUtil; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class UploadProcess extends BaseProcess { private String uploadPath; // 0:不建目录 1:按天存入目录 2:按月存入目录 private String dirType = "1"; public void setUploadPath(String uploadPath) { this.uploadPath = uploadPath; } public void setDirType(String dirType) { this.dirType = dirType; } @Override public HashMap<String, Object> execute(HttpServletRequest request, HttpServletResponse response, HashMap<String, Object> model) throws Exception { // TODO Auto-generated method stub String method = request.getMethod(); if (method == "POST") { doPost(request, response, model); } model.put("method", method); return model; } public HashMap<String, Object> doPost(HttpServletRequest request, HttpServletResponse response, HashMap<String, Object> model) throws Exception { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartRequest.getFile("file"); /* 获取文件上传路径名称 */ String fileNameLong = file.getOriginalFilename(); String contentType = file.getContentType(); if (!contentType.equals("image/jpg") && !contentType.equals("image/png") && !contentType.equals("image/jpeg") && !contentType.equals("image/gif") && !contentType.equals("image/pjpeg") && !contentType.equals("application/x-shockwave-flash") && !contentType.equals("image/jpeg")) { model.put("fileName", "上传格式错误"); model.put("attachmentPath", "/themes/default/images/fengmian.jpg"); return model; } /* 获取文件扩展名 */ /* 索引加1的效果是只取xxx.jpg的jpg */ String extensionName = fileNameLong.substring(fileNameLong .lastIndexOf(".") + 1); String newFileName = ""; /* 获取文件上传存储的相当路径 */ String realBaseDir = request.getSession().getServletContext() .getRealPath(uploadPath); File baseFile = new File(realBaseDir); if (!baseFile.exists()) { baseFile.mkdir(); } // 0:不建目录, 1:按天存入目录, 2:按月存入目录, 3:按扩展名存目录.建议使用按天存. String fileFolder = ""; if (dirType.equalsIgnoreCase("1")) fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date()); ; if (dirType.equalsIgnoreCase("2")) fileFolder = new SimpleDateFormat("yyyyMM").format(new Date()); /* 文件存储的相对路径 */ String saveDirPath = uploadPath + fileFolder + "/"; /* 文件存储在容器中的绝对路径 */ String saveFilePath = request.getSession().getServletContext() .getRealPath("") + saveDirPath; /* 构建文件目录以及目录文件 */ File fileDir = new File(saveFilePath); if (!fileDir.exists()) { fileDir.mkdirs(); } /* 重命名文件 */ String filename = UUID.randomUUID().toString(); File savefile = new File(saveFilePath + filename.substring(0, 7) + "." + extensionName); // 这个地方根据项目的不一样,需要做一些特别的定制。 newFileName = saveDirPath + filename.substring(0, 7) + "." + extensionName; try { FileCopyUtils.copy(file.getBytes(), savefile); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } model.put("fileName", saveDirPath + savefile.getName()); model.put("attachmentPath", newFileName); return model; } }
apache-2.0
IllusionRom-deprecated/android_platform_tools_idea
platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsLogUiProperties.java
2918
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.data; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.vcs.log.VcsLogSettings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; /** * Stores UI configuration based on user activity and preferences. * Differs from {@link VcsLogSettings} in the fact, that these settings have no representation in the UI settings, * and have insignificant effect to the logic of the log, they are just gracefully remember what user prefers to see in the UI. */ @State(name = "Vcs.Log.UiProperties", storages = {@Storage(file = StoragePathMacros.WORKSPACE_FILE)}) public class VcsLogUiProperties implements PersistentStateComponent<VcsLogUiProperties.State> { private static final int RECENTLY_FILTERED_USERS_AMOUNT = 5; private State myState = new State(); public static class State { public boolean SHOW_DETAILS = false; public Deque<String> RECENTLY_FILTERED_USERS = new ArrayDeque<String>(); } @Nullable @Override public State getState() { return myState; } @Override public void loadState(State state) { myState = state; } /** * Returns true if the details pane (which shows commit meta-data, such as the full commit message, commit date, all references, etc.) * should be visible when the log is loaded; returns false if it should be hidden by default. */ public boolean isShowDetails() { return myState.SHOW_DETAILS; } public void setShowDetails(boolean showDetails) { myState.SHOW_DETAILS = showDetails; } public void addRecentlyFilteredUser(@NotNull String username) { if (myState.RECENTLY_FILTERED_USERS.contains(username)) { return; } myState.RECENTLY_FILTERED_USERS.addFirst(username); if (myState.RECENTLY_FILTERED_USERS.size() > RECENTLY_FILTERED_USERS_AMOUNT) { myState.RECENTLY_FILTERED_USERS.removeLast(); } } @NotNull public List<String> getRecentlyFilteredUsers() { return new ArrayList<String>(myState.RECENTLY_FILTERED_USERS); } }
apache-2.0
bricket/bricket
bricket-core/src/main/java/org/bricket/plugin/mail/web/MailserverPageParameterDefinition.java
1008
/** * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bricket.plugin.mail.web; import org.bricket.web.BricketPageParameterDefinition; /** * @author Ingo Renner * @author Henning Teek */ public final class MailserverPageParameterDefinition implements BricketPageParameterDefinition { public static final String MAILSERVER_PAGE_PARAMETER = "mid"; private MailserverPageParameterDefinition() { super(); } }
apache-2.0
hazendaz/assertj-core
src/test/java/org/assertj/core/api/atomic/long_/AtomicLongAssert_doesNotHaveValue_Test.java
1851
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.api.atomic.long_; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.error.ShouldNotContainValue.shouldNotContainValue; import static org.assertj.core.util.FailureMessages.actualIsNull; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Test; class AtomicLongAssert_doesNotHaveValue_Test { @Test void should_pass_when_actual_does_not_have_the_expected_value() { AtomicLong actual = new AtomicLong(123L); assertThat(actual).doesNotHaveValue(456L); } @Test void should_fail_when_actual_has_the_expected_value() { long value = 123L; AtomicLong actual = new AtomicLong(value); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(actual).doesNotHaveValue(value)) .withMessage(shouldNotContainValue(actual, value).create()); } @Test void should_fail_when_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->{ AtomicLong actual = null; assertThat(actual).doesNotHaveValue(1234L); }).withMessage(actualIsNull()); } }
apache-2.0
nagyist/marketcetera
trunk/util/src/test/java/org/marketcetera/util/misc/CollectionUtilsTest.java
1991
package org.marketcetera.util.misc; import java.util.Arrays; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.math.NumberUtils; import org.junit.Test; import org.marketcetera.util.test.TestCaseBase; import static org.junit.Assert.*; /** * @author tlerios@marketcetera.com * @since 0.6.0 * @version $Id: CollectionUtilsTest.java 16154 2012-07-14 16:34:05Z colin $ */ /* $License$ */ public class CollectionUtilsTest extends TestCaseBase { @Test public void getLastNonNull() { assertNull(CollectionUtils.getLastNonNull(null)); assertNull(CollectionUtils.getLastNonNull (Arrays.asList(new Integer[] {}))); assertNull(CollectionUtils.getLastNonNull (Arrays.asList(new Integer[] {null}))); assertEquals(NumberUtils.INTEGER_ONE,CollectionUtils.getLastNonNull (Arrays.asList(1))); assertEquals(NumberUtils.INTEGER_ONE,CollectionUtils.getLastNonNull (Arrays.asList(2,null,1,null))); assertEquals(NumberUtils.INTEGER_ONE,CollectionUtils.getLastNonNull (Arrays.asList(2,null,null,1))); assertEquals(NumberUtils.INTEGER_ONE,CollectionUtils.getLastNonNull (Arrays.asList(1,null,null))); } @Test public void toArray() { assertNull(CollectionUtils.toArray(null)); assertArrayEquals (ArrayUtils.EMPTY_INT_ARRAY, CollectionUtils.toArray(Arrays.asList(new Integer[] {}))); assertArrayEquals (ArrayUtils.EMPTY_INT_ARRAY, CollectionUtils.toArray(Arrays.asList(new Integer[] {null}))); assertArrayEquals (new int[] {1}, CollectionUtils.toArray(Arrays.asList(1))); assertArrayEquals (new int[] {1,2}, CollectionUtils.toArray(Arrays.asList(null,1,null,2,null))); } }
apache-2.0
LayneMobile/Proxy
proxy-generator/src/main/java/com/laynemobile/proxy/model/output/DefaultTypeElementStub.java
2958
/* * Copyright 2016 Layne Mobile, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.laynemobile.proxy.model.output; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.laynemobile.proxy.Util; import com.squareup.javapoet.ClassName; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import sourcerer.processor.Env; public class DefaultTypeElementStub implements TypeElementStub { private final String packageName; private final String className; private final String qualifiedName; private final ClassName typeName; protected DefaultTypeElementStub(String packageName, String className) { ClassName typeName = Util.typeName(packageName, className); this.packageName = packageName; this.className = className; this.qualifiedName = Util.qualifiedName(typeName); this.typeName = typeName; } public static TypeElementStub create(String packageName, String className) { return new DefaultTypeElementStub(packageName, className); } @Override public final String packageName() { return packageName; } @Override public final String className() { return className; } @Override public final String qualifiedName() { return qualifiedName; } @Override public final ClassName typeName() { return typeName; } @Override public TypeElement element(Env env) { return env.elements().getTypeElement(qualifiedName); } @Override public boolean elementExists(Env env) { TypeMirror type; TypeElement element = element(env); if (element != null && (type = element.asType()) != null) { return type.getKind() != TypeKind.ERROR; } return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DefaultTypeElementStub)) return false; DefaultTypeElementStub that = (DefaultTypeElementStub) o; return Objects.equal(qualifiedName, that.qualifiedName); } @Override public int hashCode() { return Objects.hashCode(qualifiedName); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("qualifiedName", qualifiedName) .toString(); } }
apache-2.0
obra/rei_toei
android/src/com/urbtek/phonegap/SpeechRecognizer.java
9156
/** * SpeechRecognizer.java * Speech Recognition PhoneGap plugin (Android) * * @author Colin Turner * @author Guillaume Charhon * * Copyright (c) 2011, Colin Turner, Guillaume Charhon * * MIT Licensed */ package com.urbtek.phonegap; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import org.apache.cordova.*; import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult.Status; import android.util.Log; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.speech.RecognizerIntent; class HintReceiver extends BroadcastReceiver { com.urbtek.phonegap.SpeechRecognizer speechRecognizer; String callBackId = ""; @Override public void onReceive(Context context, Intent intent) { if (getResultCode() != Activity.RESULT_OK) { return; } // the list of supported languages. ArrayList<CharSequence> hints = getResultExtras(true).getCharSequenceArrayList(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES); // Convert the map to json JSONArray languageArray = new JSONArray(hints); PluginResult result = new PluginResult(PluginResult.Status.OK, languageArray); result.setKeepCallback(false); //speechRecognizer.callbackId = ""; speechRecognizer.success(result, ""); } public void setSpeechRecognizer(SpeechRecognizer speechRecognizer){ this.speechRecognizer = speechRecognizer; } public void setCallBackId(String id){ this.callBackId = id; } } /** * Style and such borrowed from the TTS and PhoneListener plugins */ public class SpeechRecognizer extends Plugin { private static final String LOG_TAG = SpeechRecognizer.class.getSimpleName(); public static final String ACTION_INIT = "init"; public static final String ACTION_SPEECH_RECOGNIZE = "startRecognize"; public static final String NOT_PRESENT_MESSAGE = "Speech recognition is not present or enabled"; public String callbackId = ""; private boolean recognizerPresent = false; /* (non-Javadoc) * @see com.phonegap.api.Plugin#execute(java.lang.String, org.json.JSONArray, java.lang.String) */ @Override public PluginResult execute(String action, JSONArray args, String callbackId) { // Dispatcher if (ACTION_INIT.equals(action)) { // init if (doInit()) return new PluginResult(Status.OK); else return new PluginResult(Status.ERROR, NOT_PRESENT_MESSAGE); } else if (ACTION_SPEECH_RECOGNIZE.equals(action)) { // recognize speech if (!recognizerPresent) { return new PluginResult(PluginResult.Status.ERROR, NOT_PRESENT_MESSAGE); } if (!this.callbackId.isEmpty()) { return new PluginResult(PluginResult.Status.ERROR, "Speech recognition is in progress."); } this.callbackId = callbackId; startSpeechRecognitionActivity(args); PluginResult res = new PluginResult(Status.NO_RESULT); res.setKeepCallback(true); return res; } else if("getSupportedLanguages".equals(action)){ // save the call back id //this.callbackId = callbackId; // Get the list of supported languages getSupportedLanguages(); // wait for the intent callback PluginResult res = new PluginResult(Status.NO_RESULT); res.setKeepCallback(true); return res; } else { // Invalid action String res = "Unknown action: " + action; return new PluginResult(PluginResult.Status.INVALID_ACTION, res); } } /** * Request the supported languages */ private void getSupportedLanguages() { // Create and launch get languages intent Intent intent = new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS); HintReceiver hintReceiver = new HintReceiver(); hintReceiver.setSpeechRecognizer(this); //hintReceiver.setCallBackId(this.callbackId); ((DroidGap)this.ctx).getApplicationContext().sendOrderedBroadcast(intent, null, hintReceiver, null, Activity.RESULT_OK, null, null); } /** * Initialize the speech recognizer by checking if one exists. */ private boolean doInit() { this.recognizerPresent = isSpeechRecognizerPresent(); return this.recognizerPresent; } /** * Checks if a recognizer is present on this device */ private boolean isSpeechRecognizerPresent() { PackageManager pm = ((DroidGap)this.ctx).getPackageManager(); List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); return !activities.isEmpty(); } /** * Fire an intent to start the speech recognition activity. * * @param args Argument array with the following string args: [req code][number of matches][prompt string] */ private void startSpeechRecognitionActivity(JSONArray args) { int reqCode = 42; //Hitchhiker? int maxMatches = 0; String prompt = ""; String language = ""; try { if (args.length() > 0) { // Request code - passed back to the caller on a successful operation String temp = args.getString(0); reqCode = Integer.parseInt(temp); } if (args.length() > 1) { // Maximum number of matches, 0 means the recognizer decides String temp = args.getString(1); maxMatches = Integer.parseInt(temp); } if (args.length() > 2) { // Optional text prompt prompt = args.getString(2); } if (args.length() > 3){ // Optional language specified language = args.getString(3); } } catch (Exception e) { Log.e(LOG_TAG, String.format("startSpeechRecognitionActivity exception: %s", e.toString())); } Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); // If specific language if(!language.equals("")){ intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language); } if (maxMatches > 0) intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxMatches); if (!(prompt.length() == 0)) intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt); ((DroidGap)this.ctx).startActivityForResult(this, intent, reqCode); } /** * Handle the results from the recognition activity. */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { // Fill the list view with the strings the recognizer thought it could have heard ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); speechResults(requestCode, matches); } else if(resultCode == Activity.RESULT_CANCELED){ // cancelled by user speechFailure("Cancelled"); } else { speechFailure("Unknown error"); } super.onActivityResult(requestCode, resultCode, data); } private void speechResults(int requestCode, ArrayList<String> matches) { boolean firstValue = true; StringBuilder sb = new StringBuilder(); sb.append("{\"speechMatches\": {"); sb.append("\"requestCode\": "); sb.append(Integer.toString(requestCode)); sb.append(", \"speechMatch\": ["); Iterator<String> iterator = matches.iterator(); while(iterator.hasNext()) { String match = iterator.next(); if (firstValue == false) sb.append(", "); firstValue = false; sb.append(JSONObject.quote(match)); } sb.append("]}}"); PluginResult result = new PluginResult(PluginResult.Status.OK, sb.toString()); result.setKeepCallback(false); this.success(result, this.callbackId); this.callbackId = ""; } private void speechFailure(String message) { PluginResult result = new PluginResult(PluginResult.Status.ERROR, message); result.setKeepCallback(false); this.error(result, this.callbackId); this.callbackId = ""; } }
apache-2.0
stupidlittleboy/myprojectforsmu
src/com/shmtu/myprojectforsmu/entity/CustomerInfo.java
74
package com.shmtu.myprojectforsmu.entity; public class CustomerInfo { }
apache-2.0
tteofili/jackrabbit-oak
oak-core/src/main/java/org/apache/jackrabbit/oak/spi/state/AbstractNodeState.java
8768
/* * 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.jackrabbit.oak.spi.state; import org.apache.jackrabbit.oak.api.PropertyState; import com.google.common.base.Function; import com.google.common.collect.Iterables; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nonnull; /** * Abstract base class for {@link NodeState} implementations. * This base class contains default implementations of the * {@link #equals(Object)} and {@link #hashCode()} methods based on * the implemented interface. * <p> * This class also implements trivial (and potentially very slow) versions of * the {@link #getProperty(String)} and {@link #getPropertyCount()} methods * based on {@link #getProperties()}. The {@link #getChildNode(String)} and * {@link #getChildNodeCount()} methods are similarly implemented based on * {@link #getChildNodeEntries()}. Subclasses should normally * override these method with a more efficient alternatives. */ public abstract class AbstractNodeState implements NodeState { @Override public PropertyState getProperty(String name) { for (PropertyState property : getProperties()) { if (name.equals(property.getName())) { return property; } } return null; } @Override public long getPropertyCount() { return count(getProperties()); } @Override public boolean hasChildNode(String name) { return getChildNode(name) != null; } @Override public NodeState getChildNode(String name) { for (ChildNodeEntry entry : getChildNodeEntries()) { if (name.equals(entry.getName())) { return entry.getNodeState(); } } return null; } @Override public long getChildNodeCount() { return count(getChildNodeEntries()); } @Override public Iterable<String> getChildNodeNames() { return Iterables.transform( getChildNodeEntries(), new Function<ChildNodeEntry, String>() { @Override public String apply(ChildNodeEntry input) { return input.getName(); } }); } @Override public Iterable<? extends ChildNodeEntry> getChildNodeEntries() { return Iterables.transform( getChildNodeNames(), new Function<String, ChildNodeEntry>() { @Override public ChildNodeEntry apply(final String input) { return new AbstractChildNodeEntry() { @Override @Nonnull public String getName() { return input; } @Override @Nonnull public NodeState getNodeState() { return getChildNode(input); } }; } }); } /** * Generic default comparison algorithm that simply walks through the * property and child node lists of the given base state and compares * the entries one by one with corresponding ones (if any) in this state. */ @Override public void compareAgainstBaseState(NodeState base, NodeStateDiff diff) { Set<String> baseProperties = new HashSet<String>(); for (PropertyState beforeProperty : base.getProperties()) { String name = beforeProperty.getName(); PropertyState afterProperty = getProperty(name); if (afterProperty == null) { diff.propertyDeleted(beforeProperty); } else { baseProperties.add(name); if (!beforeProperty.equals(afterProperty)) { diff.propertyChanged(beforeProperty, afterProperty); } } } for (PropertyState afterProperty : getProperties()) { if (!baseProperties.contains(afterProperty.getName())) { diff.propertyAdded(afterProperty); } } Set<String> baseChildNodes = new HashSet<String>(); for (ChildNodeEntry beforeCNE : base.getChildNodeEntries()) { String name = beforeCNE.getName(); NodeState beforeChild = beforeCNE.getNodeState(); NodeState afterChild = getChildNode(name); if (afterChild == null) { diff.childNodeDeleted(name, beforeChild); } else { baseChildNodes.add(name); if (!beforeChild.equals(afterChild)) { diff.childNodeChanged(name, beforeChild, afterChild); } } } for (ChildNodeEntry afterChild : getChildNodeEntries()) { String name = afterChild.getName(); if (!baseChildNodes.contains(name)) { diff.childNodeAdded(name, afterChild.getNodeState()); } } } /** * Returns a string representation of this child node entry. * * @return string representation */ public String toString() { StringBuilder builder = new StringBuilder("{"); AtomicBoolean first = new AtomicBoolean(true); for (PropertyState property : getProperties()) { if (!first.getAndSet(false)) { builder.append(','); } builder.append(' ').append(property); } for (ChildNodeEntry entry : getChildNodeEntries()) { if (!first.getAndSet(false)) { builder.append(','); } builder.append(' ').append(entry); } builder.append(" }"); return builder.toString(); } /** * Checks whether the given object is equal to this one. Two node states * are considered equal if all their properties and child nodes match, * regardless of ordering. Subclasses may override this method with a * more efficient equality check if one is available. * * @param that target of the comparison * @return {@code true} if the objects are equal, * {@code false} otherwise */ @Override public boolean equals(Object that) { if (this == that) { return true; } else if (that == null || !(that instanceof NodeState)) { return false; } NodeState other = (NodeState) that; if (getPropertyCount() != other.getPropertyCount() || getChildNodeCount() != other.getChildNodeCount()) { return false; } for (PropertyState property : getProperties()) { if (!property.equals(other.getProperty(property.getName()))) { return false; } } // TODO inefficient unless there are very few child nodes for (ChildNodeEntry entry : getChildNodeEntries()) { if (!entry.getNodeState().equals( other.getChildNode(entry.getName()))) { return false; } } return true; } /** * Returns a hash code that's compatible with how the * {@link #equals(Object)} method is implemented. The current * implementation simply returns zero for everything since * {@link NodeState} instances are not intended for use as hash keys. * * @return hash code */ @Override public int hashCode() { return 0; } //-----------------------------------------------------------< private >-- private static long count(Iterable<?> iterable) { long n = 0; Iterator<?> iterator = iterable.iterator(); while (iterator.hasNext()) { iterator.next(); n++; } return n; } }
apache-2.0
missioncommand/mil-sym-java
service/mil-sym-service/src/main/java/sec/web/renderer/utils/ImagingUtils.java
7564
package sec.web.renderer.utils; import ArmyC2.C2SD.Utilities.MilStdAttributes; import ArmyC2.C2SD.Utilities.SymbolUtilities; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; import java.awt.Color; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import sec.web.renderer.SECRenderer; import sec.web.renderer.utilities.JavaRendererUtilities; import sec.web.renderer.utilities.PNGInfo; @SuppressWarnings("unused") public class ImagingUtils { private static final Logger LOGGER = Logger.getLogger(ImagingUtils.class.getName()); private static SECRenderer sr = SECRenderer.getInstance(); private static IoUtilities io = new IoUtilities(); private ArrayList<String> previousPluginContent; public ImagingUtils() { //sr.matchSECWebRendererAppletDefaultRendererSettings(); this.previousPluginContent = sr.getListOfLoadedPlugins(); } public static HashMap<String, String> getURLParameters(HttpServletRequest request) { Enumeration<String> paramNames = request.getParameterNames(); HashMap<String, String> params = new HashMap<String, String>(); while (paramNames.hasMoreElements()) { String key = (String) paramNames.nextElement(); String val = request.getParameter(key); if(val != null && val.equals("") == false) { if(val.toLowerCase().contains("script>")) { val=""; } params.put(key.toUpperCase(), val); } // LOGGER.log(Level.INFO, "PROCESSING\nkey: "+key + "\tValue: " + val); } return params; } public static byte[] getMilStd2525Png(String url, String queryString) { String symbolID = url.substring(url.lastIndexOf("/")); if (queryString != null || "".equals(queryString)) { symbolID += "?" + queryString; } PNGInfo pngInfo = sr.getMilStdSymbolImageFromURL(symbolID); byte[] pngResponse = (pngInfo == null) ? null : pngInfo.getImageAsByteArray(); return pngResponse; } public static byte[] getMilStd2525PngBytes(String symbolId, Map<String, String> symbolInfoMap) { Boolean icon = false; if(symbolInfoMap.containsKey("ICON")) { if(Boolean.parseBoolean(symbolInfoMap.get("ICON"))==true) icon = true; } int eWidth = -1; int eHeight = -1; int ecX = -1; int ecY = -1; int buffer = -1; if(symbolInfoMap.containsKey("EWIDTH")) { eWidth = Math.round(Float.parseFloat(symbolInfoMap.get("EWIDTH"))); } if(symbolInfoMap.containsKey("EHEIGHT")) { eHeight = Math.round(Float.parseFloat(symbolInfoMap.get("EHEIGHT"))); } if(symbolInfoMap.containsKey("ECENTERX")) { ecX = Math.round(Float.parseFloat(symbolInfoMap.get("ECENTERX"))); } if(symbolInfoMap.containsKey("ECENTERY")) { ecY = Math.round(Float.parseFloat(symbolInfoMap.get("ECENTERY"))); } if(symbolInfoMap.containsKey("BUFFER")) { buffer = Integer.parseInt(symbolInfoMap.get("BUFFER")); } PNGInfo pngInfo = getMilStd2525Png(symbolId, symbolInfoMap); if(icon) pngInfo = pngInfo.squareImage(); else if(eWidth > 0 && eHeight > 0 && ecX >= 0 && ecY >= 0 && buffer > 0) { pngInfo = pngInfo.fitImage(eWidth, eHeight, ecX, ecY, buffer); } else { pngInfo = processImageModifiers(symbolInfoMap, pngInfo); } Boolean meta = false; String tempModifierVal = null; if (symbolInfoMap.containsKey("META")) { tempModifierVal = symbolInfoMap.get("META"); if (tempModifierVal != null && tempModifierVal.toLowerCase().equals("true") == true) { meta = true; } } byte[] pngResponse = null; if (meta) { pngResponse = (pngInfo == null) ? null : pngInfo.getImageAsByteArrayWithMetaInfo(); } else { pngResponse = (pngInfo == null) ? null : pngInfo.getImageAsByteArray(); } return pngResponse; } /** * * @param symbolId * @param symbolInfoMap * @return */ public static PNGInfo getMilStd2525Png(String symbolId, Map<String, String> symbolInfoMap) { Boolean icon = false; if(symbolInfoMap.containsKey("ICON")) { if(Boolean.parseBoolean(symbolInfoMap.get("ICON"))==true) icon = true; } if(icon) { //strip unwanted modifiers symbolInfoMap = JavaRendererUtilities.parseIconParameters(symbolId, symbolInfoMap); symbolId = JavaRendererUtilities.sanitizeSymbolID(symbolId); } PNGInfo pngInfo = sr.getSymbolImage(symbolId, symbolInfoMap); return pngInfo; } /** * @param symbolInfoMap * @param pngInfo * @return */ private static PNGInfo processImageModifiers(Map<String, String> symbolInfoMap, PNGInfo pngInfo) { String tempModifierVal = null; if (symbolInfoMap.containsKey("CENTER")) { tempModifierVal = symbolInfoMap.get("CENTER"); if (tempModifierVal != null && tempModifierVal.toLowerCase().equals("true") == true) { pngInfo = pngInfo.centerImage(); } } else if (symbolInfoMap.containsKey("SQUARE")) { tempModifierVal = symbolInfoMap.get("SQUARE"); if (tempModifierVal != null && tempModifierVal.toLowerCase().equals("true") == true) { pngInfo = pngInfo.squareImage(); } } return pngInfo; } public static byte[] getKml(String url, String symbolId, HashMap<String, String> symbolInfoMap) { String kmlInfo = sr.getSymbolImageKML(url, symbolId, symbolInfoMap); byte[] kmlBytes = null; try { kmlBytes = kmlInfo.getBytes("UTF-8"); } catch(UnsupportedEncodingException uee) { kmlBytes = kmlInfo.getBytes(); } return kmlBytes; } public static String getKmlString(String url, String symbolId, HashMap<String, String> symbolInfoMap) { return sr.getSymbolImageKML(url, symbolId, symbolInfoMap); } public static void reloadPlugins() { ImagingUtils iUtils = new ImagingUtils(); ArrayList<String> latestPluginContent = io.getPlugins(); if (!iUtils.getPreviousPluginContent().equals(latestPluginContent)) { File f = new File(io.loadCurrentWorkingDirectory()); sr.loadPluginsFromDirectory(f); sr.refreshPlugins(); } } public ArrayList<String> getPreviousPluginContent() { return previousPluginContent; } public void setPreviousPluginContent(ArrayList<String> newContent) { this.previousPluginContent = newContent; } }
apache-2.0
JLUIT/ITJob
src/com/job/bean/CompanyMsg.java
1985
package com.job.bean; public class CompanyMsg { private String job_name; private String company_name; private String experience; private String site; private String company_size; private String salary; private String company_property; private String send_date; public CompanyMsg(String job_name, String company_name, String experience, String site, String company_size, String salary, String company_property, String send_date) { super(); this.job_name = job_name; this.company_name = company_name; this.experience = experience; this.site = site; this.company_size = company_size; this.salary = salary; this.company_property = company_property; this.send_date = send_date; } public CompanyMsg() { super(); } public String getJob_name() { return job_name; } public void setJob_name(String job_name) { this.job_name = job_name; } public String getCompany_name() { return company_name; } public void setCompany_name(String company_name) { this.company_name = company_name; } public String getExperience() { return experience; } public void setExperience(String experience) { this.experience = experience; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getCompany_size() { return company_size; } public void setCompany_size(String company_size) { this.company_size = company_size; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } public String getSend_date() { return send_date; } public void setSend_date(String send_date) { this.send_date = send_date; } public String getCompany_property() { return company_property; } public void setCompany_property(String company_property) { this.company_property = company_property; } }
apache-2.0
mwjmurphy/Axel-Framework
axel-mapping/src/main/java/org/xmlactions/mapping/xml_to_bean/PopulateClassFromXml.java
11618
package org.xmlactions.mapping.xml_to_bean; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Properties; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.beanutils.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmlactions.action.config.IExecContext; import org.xmlactions.action.config.NoPersistenceExecContext; import org.xmlactions.common.io.ResourceUtils; import org.xmlactions.common.xml.XMLAttribute; import org.xmlactions.common.xml.XMLObject; import org.xmlactions.mapping.KeyValue; import org.xmlactions.mapping.Populator; public class PopulateClassFromXml { private static final Logger log = LoggerFactory.getLogger(PopulateClassFromXml.class); private boolean strict = false; /** * Will ignore a conversion to a decimal, bigint if the conversion caused a * ConversionException and the value is empty. */ private boolean ignoreErrorWithEmptyValues = true; private XmlToBean xmlToBean; private static String actionPropertiesFilename = "/config/xml_to_bean.properties"; public Object mapXmlToBean(String definitionXmlFile, String xml) { try { IExecContext execContext = new NoPersistenceExecContext(null, null); execContext.addActions(getActionProperties()); XmlToBean xmlToBean = MapXmlToBeanUtils.createMappingBean(execContext, definitionXmlFile); return mapXmlToBean(xmlToBean,xml); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage() + "\nUsing Mapping File [" + definitionXmlFile + "]", e); } } public Object mapXmlToBean(XmlToBean xmlToBean, String xml) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException, IllegalArgumentException, NoSuchFieldException { XMLObject xo = new XMLObject().mapXMLCharToXMLObject(xml); return mapXmlToBean(xmlToBean, xo); } /** * * @param map * - mappings of xml entity names to classes and bean properties * to class type handlers. * @param xo * - the xml * @return * @throws ClassNotFoundException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws SecurityException */ public Object mapXmlToBean(XmlToBean xmlToBean, XMLObject xo) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException, IllegalArgumentException, NoSuchFieldException { this.xmlToBean = xmlToBean; log.warn("xo.getContent():" + xo.getContent()); Bean bean = xmlToBean.getBean(xo.getElementName()); Object object = bean.getClassAsObject(); if (bean.getText() != null) { setProperty(bean, object, bean.getText().getName(), xo.getContent(), xo); } for (XMLAttribute att : xo.getAttributes()) { setProperty(bean, object, att.getKey(), att.getValue(), xo); } for (XMLObject child : xo.getChildren()) { createAction(bean, object, child); } return object; } public Object createAction(Bean parentBean, Object parentObject, XMLObject xo) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException, IllegalArgumentException, NoSuchFieldException { try { Bean childBean; childBean = xmlToBean.getBean(xo.getElementName()); Object object = null; if (childBean.getClas().equals(String.class.getCanonicalName())) { object = xo.getContent(); } else { object = childBean.getClassAsObject(); } setProperty(parentBean, parentObject, xo.getElementName(), object, xo); if (childBean.getText() != null) { setProperty(childBean, object, childBean.getText().getName(), xo.getContent(), xo); } for (XMLAttribute att : xo.getAttributes()) { setProperty(childBean, object, att.getKey(), att.getValue(), xo); } for (XMLObject child : xo.getChildren()) { // createAction(execContext, child, actionMapName); createAction(childBean, object, child); } return object; } catch (Exception ex){ throw new IllegalArgumentException(ex.getMessage()+"\nwhile processing:" + xo.mapXMLObject2XML(xo), ex); } } public void setProperty(Bean bean, Object object, String propertyName, Object value, XMLObject xo) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException, InstantiationException, SecurityException, IllegalArgumentException, NoSuchFieldException { Property property = Property.getProperty(bean.getProperties(), propertyName); String fieldName; if (property == null) { fieldName = propertyName; setProperty(object, propertyName, value, fieldName, xo); } else { fieldName = property.getName(); if (property.getPopulator() != null || property.getPopulator_ref() != null) { // we have a populator. Object populatorObject = property.getPopulator(xmlToBean); if (populatorObject instanceof Populator) { Populator populator = (Populator) populatorObject; useAction(populator.getClas(), populator.getKeyvalues(), object, fieldName, value, xo); } else { useAction("" + populatorObject, null, object, fieldName, value, xo); } } else { setProperty(object, propertyName, value, fieldName, xo); } } } private void setProperty(Object object, String propertyName, Object value, String fieldName, XMLObject xo) throws InvocationTargetException, NoSuchMethodException, NoSuchFieldException, IllegalAccessException { PropertyDescriptor pd = null; try { pd = findPropertyDescriptor(object, fieldName); if (pd != null) { BeanUtils.setProperty(object, fieldName, value); } else { Class<?> c = object.getClass(); Field field = c.getDeclaredField(fieldName); ConvertUtilsBean cub = new ConvertUtilsBean(); Object converted = cub.convert(value, field.getType()); field.set(object, converted); } } catch (ConversionException ex) { if (ignoreErrorWithEmptyValues == true && (value == null || ("" + value).length() == 0)) { // carry on processing, ignore because we have an empty value } else { throw new ConversionException("Unable to set property [" + propertyName + "] on bean [" + object.getClass().getName() + "] with value of [" + value + "] error:" + ex.getMessage(), ex); } } catch (NoSuchFieldException ex) { if (strict == true) { throw ex; } else { // log.warn(object.getClass().getName() + // " has no such field [" + propertyName + "]:" + // ex.getMessage()); } } catch (IllegalAccessException ex) { throw new IllegalAccessException("Unable to set property [" + propertyName + "] on bean [" + object.getClass().getName() + "] with value of [" + value + "] error:" + ex.getMessage()); } catch (IllegalArgumentException ex) { if (pd != null) { try { // try and match up a populator. Class<?> obj = pd.getPropertyType(); log.debug("obj:" + obj); if (obj != null) { if (List.class.getName().equals(obj.getName())) { useAction(PopulatorArrayList.class.getName(), null, object, fieldName, value, xo); } } } catch (Exception ex_ignore) { // ignore this, we'll throw the original exception throw ex; } } else { throw ex; } } } public static PropertyDescriptor findPropertyDescriptor(Object object, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyDescriptor pd = null; PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(object); for (PropertyDescriptor p : pds) { if (p.getName().equals(name)) { pd = p; break; } } if (pd != null) { log.debug("PropertyDescriptor [" + name + "] - " + " Name:" + pd.getName() + " DisplayName:" + pd.getDisplayName() + " ShortDescription:" + pd.getShortDescription() + " PropertyType:" + pd.getPropertyType() + " ReadMethod:" + pd.getReadMethod() + " WriteMethod:" + pd.getWriteMethod() + " Value:" + pd.getValue(name)); // } else { // log.error("PropertyDescriptor [" + name + // "] - not found in class [" + object.getClass().getName() + "]"); } return pd; } private void useAction(String actionName, List<KeyValue> keyvalues, Object object, String propertyName, Object value, XMLObject xo) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException, IllegalArgumentException, NoSuchFieldException { log.debug(actionName + " - " + object + propertyName + " - " + value); Class clas = Class.forName(actionName); Object p = clas.newInstance(); if (!(p instanceof PopulateClassFromXmlInterface)) { throw new InstantiationException(actionName + " does not implement " + PopulateClassFromXmlInterface.class.getSimpleName()); } PopulateClassFromXmlInterface pc = (PopulateClassFromXmlInterface) p; pc.performAction(keyvalues, object, propertyName, value, xo); } private static Properties getActionProperties() { try { InputStream is = ResourceUtils.getResourceURL(actionPropertiesFilename).openStream(); Properties actionProperties = new Properties(); actionProperties.load(is); is.close(); return actionProperties; } catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); } } }
apache-2.0
psiroky/dashbuilder
dashbuilder-client/dashbuilder-renderers/dashbuilder-renderer-default/src/main/java/org/dashbuilder/renderer/client/metric/AbstractMetricDisplayer.java
6853
/** * Copyright (C) 2015 JBoss 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.dashbuilder.renderer.client.metric; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import org.dashbuilder.common.client.StringUtils; import org.dashbuilder.dataset.ColumnType; import org.dashbuilder.dataset.DataSet; import org.dashbuilder.dataset.DataSetLookupConstraints; import org.dashbuilder.dataset.client.DataSetReadyCallback; import org.dashbuilder.dataset.client.DataSetClientServiceError; import org.dashbuilder.displayer.DisplayerAttributeDef; import org.dashbuilder.displayer.DisplayerAttributeGroupDef; import org.dashbuilder.displayer.DisplayerConstraints; import org.dashbuilder.displayer.client.AbstractDisplayer; import org.dashbuilder.renderer.client.resources.i18n.CommonConstants; import org.dashbuilder.renderer.client.resources.i18n.MetricConstants; public abstract class AbstractMetricDisplayer extends AbstractDisplayer { protected FlowPanel panel = new FlowPanel(); protected DataSet dataSet = null; public AbstractMetricDisplayer() { initWidget(panel); } @Override public DisplayerConstraints createDisplayerConstraints() { DataSetLookupConstraints lookupConstraints = new DataSetLookupConstraints() .setGroupAllowed(false) .setMaxColumns(1) .setMinColumns(1) .setFunctionRequired(true) .setExtraColumnsAllowed(false) .setColumnsTitle(MetricConstants.INSTANCE.metricDisplayer_columnsTitle()) .setColumnTypes(new ColumnType[] { ColumnType.NUMBER}); return new DisplayerConstraints(lookupConstraints) .supportsAttribute(DisplayerAttributeDef.TYPE) .supportsAttribute(DisplayerAttributeDef.RENDERER) .supportsAttribute(DisplayerAttributeGroupDef.COLUMNS_GROUP) .supportsAttribute(DisplayerAttributeGroupDef.FILTER_GROUP) .supportsAttribute(DisplayerAttributeGroupDef.REFRESH_GROUP) .supportsAttribute(DisplayerAttributeGroupDef.GENERAL_GROUP) .supportsAttribute(DisplayerAttributeDef.CHART_WIDTH) .supportsAttribute(DisplayerAttributeDef.CHART_HEIGHT) .supportsAttribute(DisplayerAttributeDef.CHART_BGCOLOR) .supportsAttribute(DisplayerAttributeGroupDef.CHART_MARGIN_GROUP); } @Override public void draw() { if (!isDrawn()) { if ( displayerSettings == null ) { displayMessage( CommonConstants.INSTANCE.error() + CommonConstants.INSTANCE.error_settings_unset() ); } else if ( dataSetHandler == null ) { displayMessage(CommonConstants.INSTANCE.error() + CommonConstants.INSTANCE.error_handler_unset()); } else { try { String initMsg = MetricConstants.INSTANCE.metricDisplayer_initializing(); displayMessage(initMsg + " ..."); dataSetHandler.lookupDataSet(new DataSetReadyCallback() { public void callback(DataSet result) { dataSet = result; Widget w = createMetricWidget(); panel.clear(); panel.add(w); // Set the id of the container panel so that the displayer can be easily located // by testing tools for instance. String id = getDisplayerId(); if (!StringUtils.isBlank(id)) { panel.getElement().setId(id); } // Draw done afterDraw(); } public void notFound() { displayMessage(CommonConstants.INSTANCE.error() + CommonConstants.INSTANCE.error_dataset_notfound()); } @Override public boolean onError(final DataSetClientServiceError error) { afterError(AbstractMetricDisplayer.this, error); return false; } }); } catch ( Exception e ) { displayMessage(CommonConstants.INSTANCE.error() + e.getMessage() ); } } } } @Override public void redraw() { if (!isDrawn()) { draw(); } else { try { dataSetHandler.lookupDataSet(new DataSetReadyCallback() { public void callback(DataSet result) { dataSet = result; updateMetricWidget(); // Redraw done afterRedraw(); } public void notFound() { displayMessage(CommonConstants.INSTANCE.error() + CommonConstants.INSTANCE.error_dataset_notfound()); } @Override public boolean onError(final DataSetClientServiceError error) { afterError(AbstractMetricDisplayer.this, error); return false; } }); } catch ( Exception e ) { displayMessage(CommonConstants.INSTANCE.error() + e.getMessage() ); } } } @Override public void close() { panel.clear(); // Close done afterClose(); } /** * Clear the current display and show a notification message. */ public void displayMessage(String msg) { panel.clear(); Label label = new Label(); panel.add(label); label.setText(msg); } /** * Create the widget for displaying the metric */ protected abstract Widget createMetricWidget(); /** * Update the existing metric widget with the latest value */ protected abstract void updateMetricWidget(); }
apache-2.0
Carrol666/progr4test
addressbook-selenium-tests/src/com/example/tests/TestBase.java
2260
package com.example.tests; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Random; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import com.example.fw.ApplicationManager; import static com.example.tests.GroupDataGeneration.generateRandomGroups; import static com.example.tests.ContactDataGeneration.generateRandomContacts; public class TestBase { protected static ApplicationManager app; private int checkFrequency; private int checkCounter; @BeforeTest public void setUp() throws Exception { String configFile = System.getProperty("configFile, application.properties"); Properties properties = new Properties(); properties.load(new FileReader(new File(configFile))); app = new ApplicationManager(properties); checkCounter = 0; checkFrequency = Integer.parseInt(properties.getProperty("check.frequency", "0")); } protected boolean wantToCheck() { checkCounter++; if (checkCounter > checkFrequency) { checkCounter = 0; return true; } else { return false; } } @AfterTest public void tearDown() throws Exception { app.stop(); } @DataProvider public Iterator<Object[]> randomValidGroupGenerator() { return wrapGroupsToDataProvider(generateRandomGroups(5)).iterator(); } public static List<Object[]> wrapGroupsToDataProvider(List<GroupData> groups) { List<Object[]> list = new ArrayList<Object[]>(); for (GroupData group: groups) { list.add(new Object[]{group}); } return list; } @DataProvider public Iterator<Object[]> randomValidContactGenerator() { return wrapContactsToDataProvider(generateRandomContacts(5)).iterator(); } public static List<Object[]> wrapContactsToDataProvider(List<ContactData> contacts) { List<Object[]> list = new ArrayList<Object[]>(); for (ContactData contact: contacts) { list.add(new Object[]{contact}); } return list; } public static String generateRandomString() { Random rnd = new Random(); if (rnd.nextInt(3) == 0) { return ""; } else { return "test" + rnd.nextInt(); } } }
apache-2.0
jesuino/droolsjbpm-integration
kie-server-parent/kie-server-services/kie-server-services-common/src/test/java/org/kie/server/services/impl/AbstractKieServerImplTest.java
30711
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * 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.kie.server.services.impl; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.assertj.core.api.Assertions; import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.KieModule; import org.kie.scanner.KieMavenRepository; import org.kie.server.api.KieServerConstants; import org.kie.server.api.KieServerEnvironment; import org.kie.server.api.commands.CommandScript; import org.kie.server.api.commands.CreateContainerCommand; import org.kie.server.api.commands.DisposeContainerCommand; import org.kie.server.api.commands.UpdateReleaseIdCommand; import org.kie.server.api.commands.UpdateScannerCommand; import org.kie.server.api.marshalling.MarshallingFormat; import org.kie.server.api.model.KieContainerResource; import org.kie.server.api.model.KieContainerResourceFilter; import org.kie.server.api.model.KieContainerResourceList; import org.kie.server.api.model.KieContainerStatus; import org.kie.server.api.model.KieScannerResource; import org.kie.server.api.model.KieScannerStatus; import org.kie.server.api.model.KieServerCommand; import org.kie.server.api.model.KieServerInfo; import org.kie.server.api.model.KieServerMode; import org.kie.server.api.model.KieServiceResponse; import org.kie.server.api.model.Message; import org.kie.server.api.model.ReleaseId; import org.kie.server.api.model.ServiceResponse; import org.kie.server.api.model.ServiceResponsesList; import org.kie.server.api.model.Severity; import org.kie.server.controller.api.KieServerController; import org.kie.server.controller.api.model.KieServerSetup; import org.kie.server.services.api.KieContainerInstance; import org.kie.server.services.api.KieControllerNotConnectedException; import org.kie.server.services.api.KieServerExtension; import org.kie.server.services.api.KieServerRegistry; import org.kie.server.services.api.SupportedTransports; import org.kie.server.services.impl.controller.DefaultRestControllerImpl; import org.kie.server.services.impl.storage.KieServerState; import org.kie.server.services.impl.storage.KieServerStateRepository; import org.kie.server.services.impl.storage.file.KieServerStateFileRepository; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public abstract class AbstractKieServerImplTest { static final File REPOSITORY_DIR = new File("target/repository-dir"); static final String KIE_SERVER_ID = "kie-server-impl-test"; static final String GROUP_ID = "org.kie.server.test"; static final String PRODUCTION_MODE_VERSION = "1.0.0.Final"; static final String DEVELOPMENT_MODE_VERSION = "1.0.0-SNAPSHOT"; protected KieServerMode mode; protected String testVersion; protected KieServerImpl kieServer; protected org.kie.api.builder.ReleaseId releaseId; protected String origServerId = null; protected List<KieServerExtension> extensions; abstract KieServerMode getTestMode(); @Before public void setupKieServerImpl() throws Exception { extensions = new ArrayList<>(); mode = getTestMode(); testVersion = getVersion(mode); origServerId = KieServerEnvironment.getServerId(); System.setProperty(KieServerConstants.KIE_SERVER_MODE, mode.name()); System.setProperty(KieServerConstants.KIE_SERVER_ID, KIE_SERVER_ID); KieServerEnvironment.setServerId(KIE_SERVER_ID); FileUtils.deleteDirectory(REPOSITORY_DIR); FileUtils.forceMkdir(REPOSITORY_DIR); kieServer = new KieServerImpl(new KieServerStateFileRepository(REPOSITORY_DIR)) { @Override public List<KieServerExtension> getServerExtensions() { return extensions; } }; kieServer.init(); } protected String getVersion(KieServerMode mode) { return mode.equals(KieServerMode.DEVELOPMENT) ? DEVELOPMENT_MODE_VERSION : PRODUCTION_MODE_VERSION; } @After public void cleanUp() { if (kieServer != null) { kieServer.destroy(); } KieServerEnvironment.setServerId(origServerId); } @Test public void testCheckMode() { assertSame(mode, kieServer.getInfo().getResult().getMode()); } @Test public void testReadinessCheck() { assertTrue(kieServer.isKieServerReady()); } @Test(timeout=10000) public void testReadinessCheckDelayedStart() throws Exception { CountDownLatch latch = new CountDownLatch(1); CountDownLatch startedlatch = new CountDownLatch(1); kieServer.destroy(); kieServer = delayedKieServer(latch, startedlatch); assertFalse(kieServer.isKieServerReady()); latch.countDown(); startedlatch.await(); assertTrue(kieServer.isKieServerReady()); } @Test public void testHealthCheck() { List<Message> healthMessages = kieServer.healthCheck(false); assertEquals(healthMessages.size(), 0); } @Test public void testHealthCheckWithReport() { List<Message> healthMessages = kieServer.healthCheck(true); assertEquals(healthMessages.size(), 2); Message header = healthMessages.get(0); assertEquals(Severity.INFO, header.getSeverity()); assertEquals(2, header.getMessages().size()); Message footer = healthMessages.get(1); assertEquals(Severity.INFO, footer.getSeverity()); assertEquals(1, footer.getMessages().size()); } @Test(timeout=10000) public void testHealthCheckDelayedStart() throws Exception { CountDownLatch latch = new CountDownLatch(1); CountDownLatch startedlatch = new CountDownLatch(1); kieServer.destroy(); kieServer = delayedKieServer(latch, startedlatch); assertFalse(kieServer.isKieServerReady()); List<Message> healthMessages = kieServer.healthCheck(false); assertEquals(healthMessages.size(), 1); Message notReady = healthMessages.get(0); assertEquals(Severity.ERROR, notReady.getSeverity()); assertEquals(1, notReady.getMessages().size()); latch.countDown(); startedlatch.await(); assertTrue(kieServer.isKieServerReady()); healthMessages = kieServer.healthCheck(false); assertEquals(healthMessages.size(), 0); } @Test public void testHealthCheckFailedContainer() { kieServer.destroy(); kieServer = new KieServerImpl(new KieServerStateFileRepository(REPOSITORY_DIR)) { @Override protected List<KieContainerInstanceImpl> getContainers() { List<KieContainerInstanceImpl> containers = new ArrayList<>(); KieContainerInstanceImpl container = new KieContainerInstanceImpl("test", KieContainerStatus.FAILED); containers.add(container); return containers; } }; kieServer.init(); List<Message> healthMessages = kieServer.healthCheck(false); assertEquals(healthMessages.size(), 1); Message failedContainer = healthMessages.get(0); assertEquals(Severity.WARN, failedContainer.getSeverity()); assertEquals(1, failedContainer.getMessages().size()); assertEquals("KIE Container 'test' is in FAILED state", failedContainer.getMessages().iterator().next()); } @Test public void testHealthCheckFailedContainerManagementDisabled() { System.setProperty(KieServerConstants.KIE_SERVER_MGMT_API_DISABLED, "true"); kieServer.destroy(); kieServer = new KieServerImpl(new KieServerStateFileRepository(REPOSITORY_DIR)) { @Override protected List<KieContainerInstanceImpl> getContainers() { List<KieContainerInstanceImpl> containers = new ArrayList<>(); KieContainerInstanceImpl container = new KieContainerInstanceImpl("test", KieContainerStatus.FAILED); containers.add(container); return containers; } }; kieServer.init(); List<Message> healthMessages = kieServer.healthCheck(false); assertEquals(1, healthMessages.size()); Message failedContainer = healthMessages.get(0); assertEquals(Severity.ERROR, failedContainer.getSeverity()); assertEquals(1, failedContainer.getMessages().size()); assertEquals("KIE Container 'test' is in FAILED state", failedContainer.getMessages().iterator().next()); System.clearProperty(KieServerConstants.KIE_SERVER_MGMT_API_DISABLED); } @Test public void testHealthCheckFailedExtension() { extensions.add(new KieServerExtension() { @Override public List<Message> healthCheck(boolean report) { List<Message> messages = KieServerExtension.super.healthCheck(report); messages.add(new Message(Severity.ERROR, "TEST extension is unhealthy")); return messages; } @Override public void updateContainer(String id, KieContainerInstance kieContainerInstance, Map<String, Object> parameters) { } @Override public boolean isUpdateContainerAllowed(String id, KieContainerInstance kieContainerInstance, Map<String, Object> parameters) { return false; } @Override public boolean isInitialized() { return true; } @Override public boolean isActive() { return true; } @Override public void init(KieServerImpl kieServer, KieServerRegistry registry) { } @Override public Integer getStartOrder() { return 10; } @Override public List<Object> getServices() { return null; } @Override public String getImplementedCapability() { return "TEST"; } @Override public String getExtensionName() { return "TEST"; } @Override public <T> T getAppComponents(Class<T> serviceType) { return null; } @Override public List<Object> getAppComponents(SupportedTransports type) { return null; } @Override public void disposeContainer(String id, KieContainerInstance kieContainerInstance, Map<String, Object> parameters) { } @Override public void destroy(KieServerImpl kieServer, KieServerRegistry registry) { } @Override public void createContainer(String id, KieContainerInstance kieContainerInstance, Map<String, Object> parameters) { } }); kieServer.init(); List<Message> healthMessages = kieServer.healthCheck(false); assertEquals(healthMessages.size(), 1); Message failedContainer = healthMessages.get(0); assertEquals(Severity.ERROR, failedContainer.getSeverity()); assertEquals(1, failedContainer.getMessages().size()); assertEquals("TEST extension is unhealthy", failedContainer.getMessages().iterator().next()); } @Test public void testManagementDisabledDefault() { assertNull(kieServer.checkAccessability()); } @Test public void testManagementDisabledConfigured() { System.setProperty(KieServerConstants.KIE_SERVER_MGMT_API_DISABLED, "true"); try { kieServer.destroy(); kieServer = new KieServerImpl(new KieServerStateFileRepository(REPOSITORY_DIR)); kieServer.init(); ServiceResponse<?> forbidden = kieServer.checkAccessability(); assertForbiddenResponse(forbidden); } finally { System.clearProperty(KieServerConstants.KIE_SERVER_MGMT_API_DISABLED); } } @Test public void testManagementDisabledConfiguredViaCommandService() { System.setProperty(KieServerConstants.KIE_SERVER_MGMT_API_DISABLED, "true"); try { kieServer.destroy(); kieServer = new KieServerImpl(new KieServerStateFileRepository(REPOSITORY_DIR)); kieServer.init(); KieContainerCommandServiceImpl commandService = new KieContainerCommandServiceImpl(kieServer, kieServer.getServerRegistry()); List<KieServerCommand> commands = new ArrayList<>(); commands.add(new CreateContainerCommand()); commands.add(new DisposeContainerCommand()); commands.add(new UpdateScannerCommand()); commands.add(new UpdateReleaseIdCommand()); CommandScript commandScript = new CommandScript(commands); ServiceResponsesList responseList = commandService.executeScript(commandScript, MarshallingFormat.JAXB, null); assertNotNull(responseList); List<ServiceResponse<?>> responses = responseList.getResponses(); assertEquals(4, responses.size()); for (ServiceResponse<?> forbidden : responses) { assertForbiddenResponse(forbidden); } } finally { System.clearProperty(KieServerConstants.KIE_SERVER_MGMT_API_DISABLED); } } @Test // https://issues.jboss.org/browse/RHBPMS-4087 public void testPersistScannerState() { String containerId = "persist-scanner-state"; createEmptyKjar(containerId); // create the container and update the scanner KieContainerResource kieContainerResource = new KieContainerResource(containerId, new ReleaseId(releaseId)); kieServer.createContainer(containerId, kieContainerResource); KieScannerResource kieScannerResource = new KieScannerResource(KieScannerStatus.STARTED, 20000L); kieServer.updateScanner(containerId, kieScannerResource); KieServerStateRepository stateRepository = new KieServerStateFileRepository(REPOSITORY_DIR); KieServerState state = stateRepository.load(KIE_SERVER_ID); Set<KieContainerResource> containers = state.getContainers(); Assertions.assertThat(containers).hasSize(1); KieContainerResource container = containers.iterator().next(); Assertions.assertThat(container.getScanner()).isEqualTo(kieScannerResource); KieScannerResource updatedKieScannerResource = new KieScannerResource(KieScannerStatus.DISPOSED); kieServer.updateScanner(containerId, updatedKieScannerResource); // create new state repository instance to avoid caching via 'knownStates' // this simulates the server restart (since the status is loaded from filesystem after restart) stateRepository = new KieServerStateFileRepository(REPOSITORY_DIR); state = stateRepository.load(KIE_SERVER_ID); containers = state.getContainers(); Assertions.assertThat(containers).hasSize(1); container = containers.iterator().next(); Assertions.assertThat(container.getScanner()).isEqualTo(updatedKieScannerResource); kieServer.disposeContainer(containerId); } @Test // https://issues.jboss.org/browse/JBPM-5288 public void testCreateScannerWhenCreatingContainer() { String containerId = "scanner-state-when-creating-container"; createEmptyKjar(containerId); // create the container (provide scanner info as well) KieContainerResource kieContainerResource = new KieContainerResource(containerId, new ReleaseId(releaseId)); KieScannerResource kieScannerResource = new KieScannerResource(KieScannerStatus.STARTED, 20000L); kieContainerResource.setScanner(kieScannerResource); ServiceResponse<KieContainerResource> createResponse = kieServer.createContainer(containerId, kieContainerResource); Assertions.assertThat(createResponse.getType()).isEqualTo(ServiceResponse.ResponseType.SUCCESS); Assertions.assertThat(createResponse.getResult().getScanner()).isEqualTo(kieScannerResource); ServiceResponse<KieContainerResource> getResponse = kieServer.getContainerInfo(containerId); Assertions.assertThat(getResponse.getType()).isEqualTo(ServiceResponse.ResponseType.SUCCESS); Assertions.assertThat(getResponse.getResult().getScanner()).isEqualTo(kieScannerResource); kieServer.disposeContainer(containerId); } @Test public void testCreateContainerValidationNullContainer() { String containerId = "container-to-create"; createEmptyKjar(containerId); ServiceResponse<KieContainerResource> createResponse = kieServer.createContainer(containerId, null); Assertions.assertThat(createResponse.getType()).isEqualTo(ServiceResponse.ResponseType.FAILURE); } @Test public void testCreateContainerValidationNullRelease() { String containerId = "container-to-create"; createEmptyKjar(containerId); // create the container (provide scanner info as well) KieContainerResource kieContainerResource = new KieContainerResource(containerId, null); KieScannerResource kieScannerResource = new KieScannerResource(KieScannerStatus.STARTED, 20000L); kieContainerResource.setScanner(kieScannerResource); ServiceResponse<KieContainerResource> createResponse = kieServer.createContainer(containerId, kieContainerResource); Assertions.assertThat(createResponse.getType()).isEqualTo(ServiceResponse.ResponseType.FAILURE); } @Test public void testUpdateContainer() { KieServerExtension extension = mock(KieServerExtension.class); when(extension.isUpdateContainerAllowed(any(), any(), any())).thenReturn(true); extensions.add(extension); String containerId = "container-to-update"; startContainerToUpdate(containerId, getVersion(mode)); ServiceResponse<ReleaseId> updateResponse = kieServer.updateContainerReleaseId(containerId, new ReleaseId(releaseId), true); Assertions.assertThat(updateResponse.getType()).isEqualTo(ServiceResponse.ResponseType.SUCCESS); verify(extension).isUpdateContainerAllowed(anyString(), any(), any()); verify(extension).updateContainer(any(), any(), any()); kieServer.disposeContainer(containerId); } @Test public void testUpdateContainerWithExtensionNotAllowing() { KieServerExtension extension = mock(KieServerExtension.class); when(extension.isUpdateContainerAllowed(any(), any(), any())).thenReturn(false); extensions.add(extension); String containerId = "container-to-update"; startContainerToUpdate(containerId, getVersion(mode)); ServiceResponse<ReleaseId> updateResponse = kieServer.updateContainerReleaseId(containerId, new ReleaseId(this.releaseId), true); Assertions.assertThat(updateResponse.getType()).isEqualTo(ServiceResponse.ResponseType.FAILURE); verify(extension).isUpdateContainerAllowed(anyString(), any(), any()); verify(extension, never()).updateContainer(any(), any(), any()); kieServer.disposeContainer(containerId); } @Test public void testUpdateContainerWithNullReleaseID() { KieServerExtension extension = mock(KieServerExtension.class); when(extension.isUpdateContainerAllowed(any(), any(), any())).thenReturn(false); extensions.add(extension); String containerId = "container-to-update"; startContainerToUpdate(containerId, getVersion(mode)); ServiceResponse<ReleaseId> updateResponse = kieServer.updateContainerReleaseId(containerId, null, true); Assertions.assertThat(updateResponse.getType()).isEqualTo(ServiceResponse.ResponseType.FAILURE); verify(extension, never()).isUpdateContainerAllowed(anyString(), any(), any()); verify(extension, never()).updateContainer(any(), any(), any()); kieServer.disposeContainer(containerId); } protected void startContainerToUpdate(String containerId, String version) { createEmptyKjar(containerId, version); ReleaseId releaseId = new ReleaseId(this.releaseId); // create the container (provide scanner info as well) KieContainerResource kieContainerResource = new KieContainerResource(containerId, releaseId); KieScannerResource kieScannerResource = new KieScannerResource(KieScannerStatus.STARTED, 20000L); kieContainerResource.setScanner(kieScannerResource); ServiceResponse<KieContainerResource> createResponse = kieServer.createContainer(containerId, kieContainerResource); Assertions.assertThat(createResponse.getType()).isEqualTo(ServiceResponse.ResponseType.SUCCESS); Assertions.assertThat(createResponse.getResult().getScanner()).isEqualTo(kieScannerResource); ServiceResponse<KieContainerResource> getResponse = kieServer.getContainerInfo(containerId); Assertions.assertThat(getResponse.getType()).isEqualTo(ServiceResponse.ResponseType.SUCCESS); Assertions.assertThat(getResponse.getResult().getScanner()).isEqualTo(kieScannerResource); } @Test public void testExecutorPropertiesInStateRepository() { KieServerStateFileRepository stateRepository = new KieServerStateFileRepository(REPOSITORY_DIR); KieServerState state = stateRepository.load(KIE_SERVER_ID); String executorInterval = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_INTERVAL); String executorRetries = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_RETRIES); String executorPool = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_POOL); String executorTimeUnit = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_TIME_UNIT); String executorJMSQueue = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_JMS_QUEUE); String executorDisabled = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_DISABLED); assertNull(executorInterval); assertNull(executorRetries); assertNull(executorPool); assertNull(executorTimeUnit); assertNull(executorJMSQueue); assertNull(executorDisabled); try { System.setProperty(KieServerConstants.CFG_EXECUTOR_INTERVAL, "4"); System.setProperty(KieServerConstants.CFG_EXECUTOR_RETRIES, "7"); System.setProperty(KieServerConstants.CFG_EXECUTOR_POOL, "11"); System.setProperty(KieServerConstants.CFG_EXECUTOR_TIME_UNIT, "HOURS"); System.setProperty(KieServerConstants.CFG_EXECUTOR_JMS_QUEUE, "queue/MY.OWN.QUEUE"); System.setProperty(KieServerConstants.CFG_EXECUTOR_DISABLED, "true"); stateRepository.clearCache(); state = stateRepository.load(KIE_SERVER_ID); executorInterval = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_INTERVAL); executorRetries = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_RETRIES); executorPool = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_POOL); executorTimeUnit = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_TIME_UNIT); executorJMSQueue = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_JMS_QUEUE); executorDisabled = state.getConfiguration().getConfigItemValue(KieServerConstants.CFG_EXECUTOR_DISABLED); assertNotNull(executorInterval); assertNotNull(executorRetries); assertNotNull(executorPool); assertNotNull(executorTimeUnit); assertNotNull(executorJMSQueue); assertNotNull(executorDisabled); assertEquals("4", executorInterval); assertEquals("7", executorRetries); assertEquals("11", executorPool); assertEquals("HOURS", executorTimeUnit); assertEquals("queue/MY.OWN.QUEUE", executorJMSQueue); assertEquals("true", executorDisabled); } finally { System.clearProperty(KieServerConstants.CFG_EXECUTOR_INTERVAL); System.clearProperty(KieServerConstants.CFG_EXECUTOR_RETRIES); System.clearProperty(KieServerConstants.CFG_EXECUTOR_POOL); System.clearProperty(KieServerConstants.CFG_EXECUTOR_TIME_UNIT); System.clearProperty(KieServerConstants.CFG_EXECUTOR_JMS_QUEUE); System.clearProperty(KieServerConstants.CFG_EXECUTOR_DISABLED); } } protected KieServerImpl delayedKieServer(CountDownLatch latch, CountDownLatch startedlatch) { KieServerImpl server = new KieServerImpl(new KieServerStateFileRepository(REPOSITORY_DIR)) { @Override public void markAsReady() { super.markAsReady(); startedlatch.countDown(); } @Override public KieServerController getController() { return new DefaultRestControllerImpl(getServerRegistry()) { @Override public KieServerSetup connect(KieServerInfo serverInfo) { try { if (latch.await(10, TimeUnit.MILLISECONDS)) { return new KieServerSetup(); } throw new KieControllerNotConnectedException("Unable to connect to any controller"); } catch (InterruptedException e) { throw new KieControllerNotConnectedException("Unable to connect to any controller"); } } }; } }; server.init(); return server; } protected void assertForbiddenResponse(ServiceResponse<?> forbidden) { assertNotNull(forbidden); assertEquals(KieServiceResponse.ResponseType.FAILURE, forbidden.getType()); assertEquals("KIE Server management api is disabled", forbidden.getMsg()); } protected void assertReleaseIds(String containerId, ReleaseId configuredReleaseId, ReleaseId resolvedReleaseId, long timeoutMillis) throws InterruptedException { long timeSpentWaiting = 0; while (timeSpentWaiting < timeoutMillis) { ServiceResponse<KieContainerResourceList> listResponse = kieServer.listContainers(KieContainerResourceFilter.ACCEPT_ALL); Assertions.assertThat(listResponse.getType()).isEqualTo(ServiceResponse.ResponseType.SUCCESS); List<KieContainerResource> containers = listResponse.getResult().getContainers(); for (KieContainerResource container : containers) { if (configuredReleaseId.equals(container.getReleaseId()) && resolvedReleaseId.equals(container.getResolvedReleaseId())) { return; } } Thread.sleep(200); timeSpentWaiting += 200L; } Assertions.fail("Waiting too long for container " + containerId + " to have expected releaseIds updated! " + "expected: releaseId=" + configuredReleaseId + ", resolvedReleaseId=" + resolvedReleaseId); } protected void createEmptyKjar(String artifactId) { createEmptyKjar(artifactId, testVersion); } protected void createEmptyKjar(String artifactId, String version) { // create empty kjar; content does not matter KieServices kieServices = KieServices.Factory.get(); KieFileSystem kfs = kieServices.newKieFileSystem(); releaseId = kieServices.newReleaseId(GROUP_ID, artifactId, version); KieModule kieModule = kieServices.newKieBuilder(kfs ).buildAll().getKieModule(); KieMavenRepository.getKieMavenRepository().installArtifact(releaseId, (InternalKieModule)kieModule, createPomFile(artifactId, version ) ); kieServices.getRepository().addKieModule(kieModule); } protected File createPomFile(String artifactId, String version) { String pomContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n" + " <modelVersion>4.0.0</modelVersion>\n" + "\n" + " <groupId>org.kie.server.test</groupId>\n" + " <artifactId>" + artifactId + "</artifactId>\n" + " <version>" + version + "</version>\n" + " <packaging>pom</packaging>\n" + "</project>"; try { File file = new File("target/" + artifactId + "-1.0.0.Final.pom"); FileUtils.write(file, pomContent); return file; } catch (IOException e) { throw new RuntimeException(e); } } }
apache-2.0
timofeysie/catechis
src/org/catechis/dto/WordFilter.java
2556
package org.catechis.dto; /* Copyright 2006 Timothy Curchod 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. */ /** *<p>This object is an include/exclude filter object to hold properties to limit * a list of words returned. *<p>If properties are not null, then they should be filtered. */ public class WordFilter { private String type; private String category; private int start_index; private String min_max_range; private String[] categories; private int number_of_words; private String exclude_time; // Unimplemented properties private String date_from_present; private String from_date; private String until_date; private String exclude_recently_failed_date; private String include_recently_passed_date; private String exclude_recently_tested_date; private boolean randomize_list; public void setType(String _type) { type = _type; } public String getType() { return type; } public void setCategory(String _category) { category = _category; } public String getCategory() { return category; } public void setStartIndex(int _start_index) { start_index = _start_index; } public int getStartIndex() { return start_index; } public void setMinMaxRange(String _min_max_range) { this.min_max_range = _min_max_range; } public String getMinMaxRange() { return this.min_max_range; } //Methods to access the entire indexed property array public String[] getCategories() { return categories; } public void setCategories(String[] _categories) { categories = _categories; } //Methods to access individual values public String getCategories(int index) { return categories[index]; } public void setCategories(int index, String _categories) { categories[index] = _categories; } public void setNumberOfWords(int _number_of_words) { number_of_words = _number_of_words; } public int getNumberOfWords() { return number_of_words; } public void setExcludeTime(String _exclude_time) { exclude_time = _exclude_time; } public String getExcludeTime() { return exclude_time; } }
apache-2.0
hibersap/hibersap
hibersap-core/src/main/java/org/hibersap/annotations/Bapi.java
1256
/* * Copyright (c) 2008-2019 akquinet tech@spree GmbH * * This file is part of Hibersap. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this software 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.hibersap.annotations; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Maps a Java class to a remote function module (or BAPI) in SAP. * * @author Carsten Erker */ @Retention(RUNTIME) @Target(value = TYPE) @Inherited public @interface Bapi { /** * The name of a SAP remote function module, e.g. BAPI_FLIGHT_GETLIST. * * @return The function name. */ String value(); }
apache-2.0
pjain1/druid
services/src/main/java/org/apache/druid/cli/CliBroker.java
7394
/* * 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.cli; import com.google.common.collect.ImmutableList; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.name.Names; import io.airlift.airline.Command; import org.apache.druid.client.BrokerSegmentWatcherConfig; import org.apache.druid.client.BrokerServerView; import org.apache.druid.client.CachingClusteredClient; import org.apache.druid.client.HttpServerInventoryViewResource; import org.apache.druid.client.TimelineServerView; import org.apache.druid.client.cache.CacheConfig; import org.apache.druid.client.selector.CustomTierSelectorStrategyConfig; import org.apache.druid.client.selector.ServerSelectorStrategy; import org.apache.druid.client.selector.TierSelectorStrategy; import org.apache.druid.discovery.DataNodeService; import org.apache.druid.discovery.LookupNodeService; import org.apache.druid.discovery.NodeRole; import org.apache.druid.guice.CacheModule; import org.apache.druid.guice.DruidProcessingModule; import org.apache.druid.guice.Jerseys; import org.apache.druid.guice.JoinableFactoryModule; import org.apache.druid.guice.JsonConfigProvider; import org.apache.druid.guice.LazySingleton; import org.apache.druid.guice.LifecycleModule; import org.apache.druid.guice.ManageLifecycle; import org.apache.druid.guice.QueryRunnerFactoryModule; import org.apache.druid.guice.QueryableModule; import org.apache.druid.guice.SegmentWranglerModule; import org.apache.druid.guice.ServerTypeConfig; import org.apache.druid.java.util.common.logger.Logger; import org.apache.druid.query.QuerySegmentWalker; import org.apache.druid.query.RetryQueryRunnerConfig; import org.apache.druid.query.lookup.LookupModule; import org.apache.druid.server.BrokerQueryResource; import org.apache.druid.server.ClientInfoResource; import org.apache.druid.server.ClientQuerySegmentWalker; import org.apache.druid.server.ResponseContextConfig; import org.apache.druid.server.SegmentManager; import org.apache.druid.server.coordination.ServerType; import org.apache.druid.server.coordination.ZkCoordinator; import org.apache.druid.server.http.BrokerResource; import org.apache.druid.server.http.HistoricalResource; import org.apache.druid.server.http.SegmentListerResource; import org.apache.druid.server.http.SelfDiscoveryResource; import org.apache.druid.server.initialization.jetty.JettyServerInitializer; import org.apache.druid.server.metrics.QueryCountStatsProvider; import org.apache.druid.server.router.TieredBrokerConfig; import org.apache.druid.sql.guice.SqlModule; import org.apache.druid.timeline.PruneLastCompactionState; import org.apache.druid.timeline.PruneLoadSpec; import org.eclipse.jetty.server.Server; import java.util.List; @Command( name = "broker", description = "Runs a broker node, see https://druid.apache.org/docs/latest/Broker.html for a description" ) public class CliBroker extends ServerRunnable { private static final Logger log = new Logger(CliBroker.class); public CliBroker() { super(log); } @Override protected List<? extends Module> getModules() { return ImmutableList.of( new DruidProcessingModule(), new QueryableModule(), new QueryRunnerFactoryModule(), new SegmentWranglerModule(), new JoinableFactoryModule(), binder -> { binder.bindConstant().annotatedWith(Names.named("serviceName")).to( TieredBrokerConfig.DEFAULT_BROKER_SERVICE_NAME ); binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8082); binder.bindConstant().annotatedWith(Names.named("tlsServicePort")).to(8282); binder.bindConstant().annotatedWith(PruneLoadSpec.class).to(true); binder.bindConstant().annotatedWith(PruneLastCompactionState.class).to(true); binder.bind(ResponseContextConfig.class).toInstance(ResponseContextConfig.newConfig(false)); binder.bind(CachingClusteredClient.class).in(LazySingleton.class); LifecycleModule.register(binder, BrokerServerView.class); binder.bind(TimelineServerView.class).to(BrokerServerView.class).in(LazySingleton.class); JsonConfigProvider.bind(binder, "druid.broker.cache", CacheConfig.class); binder.install(new CacheModule()); JsonConfigProvider.bind(binder, "druid.broker.select", TierSelectorStrategy.class); JsonConfigProvider.bind(binder, "druid.broker.select.tier.custom", CustomTierSelectorStrategyConfig.class); JsonConfigProvider.bind(binder, "druid.broker.balancer", ServerSelectorStrategy.class); JsonConfigProvider.bind(binder, "druid.broker.retryPolicy", RetryQueryRunnerConfig.class); JsonConfigProvider.bind(binder, "druid.broker.segment", BrokerSegmentWatcherConfig.class); binder.bind(QuerySegmentWalker.class).to(ClientQuerySegmentWalker.class).in(LazySingleton.class); binder.bind(JettyServerInitializer.class).to(QueryJettyServerInitializer.class).in(LazySingleton.class); binder.bind(BrokerQueryResource.class).in(LazySingleton.class); Jerseys.addResource(binder, BrokerQueryResource.class); binder.bind(QueryCountStatsProvider.class).to(BrokerQueryResource.class).in(LazySingleton.class); Jerseys.addResource(binder, BrokerResource.class); Jerseys.addResource(binder, ClientInfoResource.class); LifecycleModule.register(binder, BrokerQueryResource.class); Jerseys.addResource(binder, HttpServerInventoryViewResource.class); LifecycleModule.register(binder, Server.class); binder.bind(SegmentManager.class).in(LazySingleton.class); binder.bind(ZkCoordinator.class).in(ManageLifecycle.class); binder.bind(ServerTypeConfig.class).toInstance(new ServerTypeConfig(ServerType.BROKER)); Jerseys.addResource(binder, HistoricalResource.class); Jerseys.addResource(binder, SegmentListerResource.class); LifecycleModule.register(binder, ZkCoordinator.class); bindNodeRoleAndAnnouncer( binder, DiscoverySideEffectsProvider .builder(NodeRole.BROKER) .serviceClasses(ImmutableList.of(DataNodeService.class, LookupNodeService.class)) .useLegacyAnnouncer(true) .build() ); Jerseys.addResource(binder, SelfDiscoveryResource.class); LifecycleModule.registerKey(binder, Key.get(SelfDiscoveryResource.class)); }, new LookupModule(), new SqlModule() ); } }
apache-2.0
jgallimore/axis-with-mods
src/org/apache/axis/encoding/ser/BeanDeserializer.java
24253
/* * Copyright 2001-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.axis.encoding.ser; import org.apache.axis.Constants; import org.apache.axis.components.logger.LogFactory; import org.apache.axis.description.ElementDesc; import org.apache.axis.description.FieldDesc; import org.apache.axis.description.TypeDesc; import org.apache.axis.encoding.ConstructorTarget; import org.apache.axis.encoding.DeserializationContext; import org.apache.axis.encoding.Deserializer; import org.apache.axis.encoding.DeserializerImpl; import org.apache.axis.encoding.Target; import org.apache.axis.encoding.TypeMapping; import org.apache.axis.message.MessageElement; import org.apache.axis.message.SOAPHandler; import org.apache.axis.soap.SOAPConstants; import org.apache.axis.utils.BeanPropertyDescriptor; import org.apache.axis.utils.Messages; import org.apache.commons.logging.Log; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import java.io.CharArrayWriter; import java.io.Serializable; import java.lang.reflect.Constructor; import java.util.Map; /** * General purpose deserializer for an arbitrary java bean. * * @author Sam Ruby <rubys@us.ibm.com> * @author Rich Scheuerle <scheu@us.ibm.com> * @author Tom Jordahl <tomj@macromedia.com> */ public class BeanDeserializer extends DeserializerImpl implements Serializable { protected static Log log = LogFactory.getLog(BeanDeserializer.class.getName()); private final CharArrayWriter val = new CharArrayWriter(); QName xmlType; Class javaType; protected Map propertyMap = null; protected QName prevQName; /** * Constructor if no default constructor */ protected Constructor constructorToUse = null; /** * Constructor Target object to use (if constructorToUse != null) */ protected Target constructorTarget = null; /** Type metadata about this class for XML deserialization */ protected TypeDesc typeDesc = null; // This counter is updated to deal with deserialize collection properties protected int collectionIndex = -1; protected SimpleDeserializer cacheStringDSer = null; protected QName cacheXMLType = null; // Construct BeanSerializer for the indicated class/qname public BeanDeserializer(Class javaType, QName xmlType) { this(javaType, xmlType, TypeDesc.getTypeDescForClass(javaType)); } // Construct BeanDeserializer for the indicated class/qname and meta Data public BeanDeserializer(Class javaType, QName xmlType, TypeDesc typeDesc ) { this(javaType, xmlType, typeDesc, BeanDeserializerFactory.getProperties(javaType, typeDesc)); } // Construct BeanDeserializer for the indicated class/qname and meta Data public BeanDeserializer(Class javaType, QName xmlType, TypeDesc typeDesc, Map propertyMap ) { this.xmlType = xmlType; this.javaType = javaType; this.typeDesc = typeDesc; this.propertyMap = propertyMap; // create a value try { value=javaType.newInstance(); } catch (Exception e) { // Don't process the exception at this point. // This is defered until the call to startElement // which will throw the exception. } } /** * startElement * * The ONLY reason that this method is overridden is so that * the object value can be set or a reasonable exception is thrown * indicating that the object cannot be created. This is done * at this point so that it occurs BEFORE href/id processing. * @param namespace is the namespace of the element * @param localName is the name of the element * @param prefix is the prefix of the element * @param attributes are the attributes on the element...used to get the * type * @param context is the DeserializationContext */ public void startElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { // Create the bean object if it was not already // created in the constructor. if (value == null) { try { value=javaType.newInstance(); } catch (Exception e) { // Use first found constructor. // Note : the right way is to use XML mapping information // for example JSR 109's constructor-parameter-order Constructor[] constructors = javaType.getConstructors(); if (constructors.length > 0) { constructorToUse = constructors[0]; } // Failed to create an object if no constructor if (constructorToUse == null) { throw new SAXException(Messages.getMessage("cantCreateBean00", javaType.getName(), e.toString())); } } } // Invoke super.startElement to do the href/id processing. super.startElement(namespace, localName, prefix, attributes, context); } /** * Deserializer interface called on each child element encountered in * the XML stream. * @param namespace is the namespace of the child element * @param localName is the local name of the child element * @param prefix is the prefix used on the name of the child element * @param attributes are the attributes of the child element * @param context is the deserialization context. * @return is a Deserializer to use to deserialize a child (must be * a derived class of SOAPHandler) or null if no deserialization should * be performed. */ public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { handleMixedContent(); BeanPropertyDescriptor propDesc = null; FieldDesc fieldDesc = null; SOAPConstants soapConstants = context.getSOAPConstants(); String encodingStyle = context.getEncodingStyle(); boolean isEncoded = Constants.isSOAP_ENC(encodingStyle); QName elemQName = new QName(namespace, localName); // The collectionIndex needs to be reset for Beans with multiple arrays if ((prevQName == null) || (!prevQName.equals(elemQName))) { collectionIndex = -1; } boolean isArray = false; QName itemQName = null; if (typeDesc != null) { // Lookup the name appropriately (assuming an unqualified // name for SOAP encoding, using the namespace otherwise) String fieldName = typeDesc.getFieldNameForElement(elemQName, isEncoded); propDesc = (BeanPropertyDescriptor)propertyMap.get(fieldName); fieldDesc = typeDesc.getFieldByName(fieldName); if (fieldDesc != null) { ElementDesc element = (ElementDesc)fieldDesc; isArray = element.isMaxOccursUnbounded(); itemQName = element.getItemQName(); } } if (propDesc == null) { // look for a field by this name. propDesc = (BeanPropertyDescriptor) propertyMap.get(localName); } // try and see if this is an xsd:any namespace="##any" element before // reporting a problem if (propDesc == null || (((prevQName != null) && prevQName.equals(elemQName) && !(propDesc.isIndexed()||isArray) && getAnyPropertyDesc() != null ))) { // try to put unknown elements into a SOAPElement property, if // appropriate prevQName = elemQName; propDesc = getAnyPropertyDesc(); if (propDesc != null) { try { MessageElement [] curElements = (MessageElement[])propDesc.get(value); int length = 0; if (curElements != null) { length = curElements.length; } MessageElement [] newElements = new MessageElement[length + 1]; if (curElements != null) { System.arraycopy(curElements, 0, newElements, 0, length); } MessageElement thisEl = context.getCurElement(); newElements[length] = thisEl; propDesc.set(value, newElements); // if this is the first pass through the MessageContexts // make sure that the correct any element is set, // that is the child of the current MessageElement, however // on the first pass this child has not been set yet, so // defer it to the child SOAPHandler if (!localName.equals(thisEl.getName())) { return new SOAPHandler(newElements, length); } return new SOAPHandler(); } catch (Exception e) { throw new SAXException(e); } } } if (propDesc == null) { //@TODO: No such field. Throwing exception here makes code not backwards compatible. //log.warn("No such field in client code: " + javaType.getName() + "/" + localName); // throw new SAXException( // Messages.getMessage("badElem00", javaType.getName(), // localName)); return null; } prevQName = elemQName; // Get the child's xsi:type if available QName childXMLType = context.getTypeFromAttributes(namespace, localName, attributes); String href = attributes.getValue(soapConstants.getAttrHref()); Class fieldType = propDesc.getType(); // If no xsi:type or href, check the meta-data for the field if (childXMLType == null && fieldDesc != null && href == null) { childXMLType = fieldDesc.getXmlType(); if (itemQName != null) { // This is actually a wrapped literal array and should be // deserialized with the ArrayDeserializer childXMLType = Constants.SOAP_ARRAY; fieldType = propDesc.getActualType(); } else { childXMLType = fieldDesc.getXmlType(); } } // Get Deserializer for child, default to using DeserializerImpl Deserializer dSer = getDeserializer(childXMLType, fieldType, href, context); // It is an error if the dSer is not found - the only case where we // wouldn't have a deserializer at this point is when we're trying // to deserialize something we have no clue about (no good xsi:type, // no good metadata). if (dSer == null) { dSer = context.getDeserializerForClass(propDesc.getType()); } // Fastpath nil checks... if (context.isNil(attributes)) { if (propDesc != null && (propDesc.isIndexed()||isArray)) { if (!((dSer != null) && (dSer instanceof ArrayDeserializer))) { collectionIndex++; dSer.registerValueTarget(new BeanPropertyTarget(value, propDesc, collectionIndex)); addChildDeserializer(dSer); return (SOAPHandler)dSer; } } return null; } if (dSer == null) { throw new SAXException(Messages.getMessage("noDeser00", childXMLType.toString())); } if (constructorToUse != null) { if (constructorTarget == null) { constructorTarget = new ConstructorTarget(constructorToUse, this); } dSer.registerValueTarget(constructorTarget); } else if (propDesc.isWriteable()) { // If this is an indexed property, and the deserializer we found // was NOT the ArrayDeserializer, this is a non-SOAP array: // <bean> // <field>value1</field> // <field>value2</field> // ... // In this case, we want to use the collectionIndex and make sure // the deserialized value for the child element goes into the // right place in the collection. // Register value target if ((itemQName != null || propDesc.isIndexed() || isArray) && !(dSer instanceof ArrayDeserializer)) { collectionIndex++; dSer.registerValueTarget(new BeanPropertyTarget(value, propDesc, collectionIndex)); } else { // If we're here, the element maps to a single field value, // whether that be a "basic" type or an array, so use the // normal (non-indexed) BeanPropertyTarget form. collectionIndex = -1; dSer.registerValueTarget(new BeanPropertyTarget(value, propDesc)); } } // Let the framework know that we need this deserializer to complete // for the bean to complete. addChildDeserializer(dSer); return (SOAPHandler)dSer; } /** * Get a BeanPropertyDescriptor which indicates where we should * put extensibility elements (i.e. XML which falls under the * auspices of an &lt;xsd:any&gt; declaration in the schema) * * @return an appropriate BeanPropertyDescriptor, or null */ public BeanPropertyDescriptor getAnyPropertyDesc() { if (typeDesc == null) return null; return typeDesc.getAnyDesc(); } /** * Set the bean properties that correspond to element attributes. * * This method is invoked after startElement when the element requires * deserialization (i.e. the element is not an href and the value is not * nil.) * @param namespace is the namespace of the element * @param localName is the name of the element * @param prefix is the prefix of the element * @param attributes are the attributes on the element...used to get the * type * @param context is the DeserializationContext */ public void onStartElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { // The value should have been created or assigned already. // This code may no longer be needed. if (value == null && constructorToUse == null) { // create a value try { value=javaType.newInstance(); } catch (Exception e) { throw new SAXException(Messages.getMessage("cantCreateBean00", javaType.getName(), e.toString())); } } // If no type description meta data, there are no attributes, // so we are done. if (typeDesc == null) return; // loop through the attributes and set bean properties that // correspond to attributes for (int i=0; i < attributes.getLength(); i++) { QName attrQName = new QName(attributes.getURI(i), attributes.getLocalName(i)); String fieldName = typeDesc.getFieldNameForAttribute(attrQName); if (fieldName == null) continue; FieldDesc fieldDesc = typeDesc.getFieldByName(fieldName); // look for the attribute property BeanPropertyDescriptor bpd = (BeanPropertyDescriptor) propertyMap.get(fieldName); if (bpd != null) { if (constructorToUse == null) { // check only if default constructor if (!bpd.isWriteable() || bpd.isIndexed()) continue ; } // Get the Deserializer for the attribute Deserializer dSer = getDeserializer(fieldDesc.getXmlType(), bpd.getType(), null, context); if (dSer == null) { dSer = context.getDeserializerForClass(bpd.getType()); // The java type is an array, but the context didn't // know that we are an attribute. Better stick with // simple types.. if (dSer instanceof ArrayDeserializer) { SimpleListDeserializerFactory factory = new SimpleListDeserializerFactory(bpd.getType(), fieldDesc.getXmlType()); dSer = (Deserializer) factory.getDeserializerAs(dSer.getMechanismType()); } } if (dSer == null) throw new SAXException( Messages.getMessage("unregistered00", bpd.getType().toString())); if (! (dSer instanceof SimpleDeserializer)) throw new SAXException( Messages.getMessage("AttrNotSimpleType00", bpd.getName(), bpd.getType().toString())); // Success! Create an object from the string and set // it in the bean try { dSer.onStartElement(namespace, localName, prefix, attributes, context); Object val = ((SimpleDeserializer)dSer). makeValue(attributes.getValue(i)); if (constructorToUse == null) { bpd.set(value, val); } else { // add value for our constructor if (constructorTarget == null) { constructorTarget = new ConstructorTarget(constructorToUse, this); } constructorTarget.set(val); } } catch (Exception e) { throw new SAXException(e); } } // if } // attribute loop } /** * Get the Deserializer for the attribute or child element. * @param xmlType QName of the attribute/child element or null if not known. * @param javaType Class of the corresponding property * @param href String is the value of the href attribute, which is used * to determine whether the child element is complete or an * href to another element. * @param context DeserializationContext * @return Deserializer or null if not found. */ protected Deserializer getDeserializer(QName xmlType, Class javaType, String href, DeserializationContext context) { if (javaType.isArray()) { context.setDestinationClass(javaType); } // See if we have a cached deserializer if (cacheStringDSer != null) { if (String.class.equals(javaType) && href == null && (cacheXMLType == null && xmlType == null || cacheXMLType != null && cacheXMLType.equals(xmlType))) { cacheStringDSer.reset(); return cacheStringDSer; } } Deserializer dSer = null; if (xmlType != null && href == null) { // Use the xmlType to get the deserializer. dSer = context.getDeserializerForType(xmlType); } else { // If the xmlType is not set, get a default xmlType TypeMapping tm = context.getTypeMapping(); QName defaultXMLType = tm.getTypeQName(javaType); // If there is not href, then get the deserializer // using the javaType and default XMLType, // If there is an href, the create the generic // DeserializerImpl and set its default type (the // default type is used if the href'd element does // not have an xsi:type. if (href == null) { dSer = context.getDeserializer(javaType, defaultXMLType); } else { dSer = new DeserializerImpl(); context.setDestinationClass(javaType); dSer.setDefaultType(defaultXMLType); } } if (javaType.equals(String.class) && dSer instanceof SimpleDeserializer) { cacheStringDSer = (SimpleDeserializer) dSer; cacheXMLType = xmlType; } return dSer; } public void characters(char[] chars, int start, int end) throws SAXException { val.write(chars, start, end); } public void onEndElement(String namespace, String localName, DeserializationContext context) throws SAXException { handleMixedContent(); } protected void handleMixedContent() throws SAXException { BeanPropertyDescriptor propDesc = getAnyPropertyDesc(); if (propDesc == null || val.size() == 0) { return; } String textValue = val.toString().trim(); val.reset(); if (textValue.length() == 0) { return; } try { MessageElement[] curElements = (MessageElement[]) propDesc.get(value); int length = 0; if (curElements != null) { length = curElements.length; } MessageElement[] newElements = new MessageElement[length + 1]; if (curElements != null) { System.arraycopy(curElements, 0, newElements, 0, length); } MessageElement thisEl = new MessageElement(new org.apache.axis.message.Text(textValue)); newElements[length] = thisEl; propDesc.set(value, newElements); } catch (Exception e) { throw new SAXException(e); } } }
apache-2.0
FINRAOS/herd
herd-code/herd-core/src/main/java/org/finra/herd/core/helper/ConfigurationHelper.java
11983
/* * Copyright 2015 herd 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.finra.herd.core.helper; import java.math.BigDecimal; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomBooleanEditor; import org.springframework.core.convert.ConversionFailedException; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.finra.herd.model.dto.ConfigurationValue; /** * A helper for {@link ConfigurationValue}. Mainly used to facilitate access to current application's {@link Environment} object. */ @Component public class ConfigurationHelper { private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationHelper.class); @Autowired private Environment environment; /** * Calls {@link #getProperty(ConfigurationValue, Class, Environment)} using String targetType. * * @param configurationValue {@link ConfigurationValue} * @param environment {@link Environment} * * @return String value */ public static String getProperty(ConfigurationValue configurationValue, Environment environment) { return getProperty(configurationValue, String.class, environment); } /** * Wrapper for {@link Environment#getProperty(String, Class, Object)} using the given {@link ConfigurationValue} as the key and default value. Optionally, * uses the configured default value if the property is not found in the environment. The configured default value must be of the same class, or must be a * sub-class of the given targetType. * * @param <T> The return type * @param configurationValue The {@link ConfigurationValue} with property key and default value. * @param targetType The returned object's type * @param environment The {@link Environment} containing the property * * @return The property value */ public static <T> T getProperty(ConfigurationValue configurationValue, Class<T> targetType, Environment environment) { /* * Parameter validation */ if (configurationValue == null) { throw new IllegalStateException("configurationValue is required"); } if (targetType == null) { throw new IllegalStateException("targetType is required"); } String key = configurationValue.getKey(); Object genericDefaultValue = configurationValue.getDefaultValue(); /* * Assert that the targetType is of the correct type. */ if (genericDefaultValue != null && !targetType.isAssignableFrom(genericDefaultValue.getClass())) { throw new IllegalStateException( "targetType \"" + targetType + "\" is not assignable from the default value of type \"" + genericDefaultValue.getClass() + "\" for configuration value \"" + configurationValue + "\"."); } @SuppressWarnings("unchecked") T defaultValue = (T) genericDefaultValue; T value = defaultValue; try { value = environment.getProperty(key, targetType, defaultValue); } catch (ConversionFailedException conversionFailedException) { /* * If the environment value is not convertible into the targetType, catch it and log a warning. * Return the default value. */ LOGGER.warn( "Error converting environment property with key '" + key + "' and value '" + environment.getProperty(key) + "' into a '" + targetType + "'.", conversionFailedException); } return value; } /** * Gets a property value as a {@link BigDecimal}. * * @param configurationValue the {@link BigDecimal} configuration value * * @return the {@link BigDecimal} property value */ public BigDecimal getBigDecimalRequiredProperty(ConfigurationValue configurationValue) { return getBigDecimalRequiredProperty(configurationValue, environment); } /** * Gets a property value as a {@link BigDecimal}. * * @param configurationValue the {@link BigDecimal} configuration value * @param environment the environment containing the property * * @return the {@link BigDecimal} property value */ public BigDecimal getBigDecimalRequiredProperty(ConfigurationValue configurationValue, Environment environment) { String bigDecimalStringValue = getRequiredProperty(configurationValue, environment); BigDecimal bigDecimalValue = null; try { // Converts the string value to BigDecimal bigDecimalValue = new BigDecimal(bigDecimalStringValue); } catch (NumberFormatException numberFormatException) { logErrorAndThrowIllegalStateException(configurationValue, "BigDecimal", bigDecimalStringValue, numberFormatException); } return bigDecimalValue; } /** * Gets a property value as a boolean. * * @param configurationValue the boolean configuration value * * @return the boolean property value */ public Boolean getBooleanProperty(ConfigurationValue configurationValue) { return getBooleanProperty(configurationValue, environment); } /** * Gets a property value as a boolean. * * @param configurationValue the boolean configuration value * @param environment the environment containing the property * * @return the boolean property value */ public Boolean getBooleanProperty(ConfigurationValue configurationValue, Environment environment) { String booleanStringValue = getProperty(configurationValue, environment); // Use custom boolean editor without allowed empty strings to convert the value of the argument to a boolean value. CustomBooleanEditor customBooleanEditor = new CustomBooleanEditor(false); try { customBooleanEditor.setAsText(booleanStringValue); } catch (IllegalArgumentException e) { logErrorAndThrowIllegalStateException(configurationValue, "boolean", booleanStringValue, e); } // Return the boolean value. return (Boolean) customBooleanEditor.getValue(); } /** * Gets a property value as {@link BigDecimal}. Additionally it ensures that the property value is not negative. * * @param configurationValue the {@link BigDecimal} configuration value * * @return the non-negative {@link BigDecimal} property value */ public BigDecimal getNonNegativeBigDecimalRequiredProperty(ConfigurationValue configurationValue) { return getNonNegativeBigDecimalRequiredProperty(configurationValue, environment); } /** * Gets a property value as {@link BigDecimal}. Additionally it ensures that the property value is not negative. * * @param configurationValue the {@link BigDecimal} configuration value * @param environment the environment containing the property * * @return the non-negative {@link BigDecimal} property value */ public BigDecimal getNonNegativeBigDecimalRequiredProperty(ConfigurationValue configurationValue, Environment environment) { final BigDecimal nonNegativeBigDecimalPropertyValue = getBigDecimalRequiredProperty(configurationValue, environment); if (nonNegativeBigDecimalPropertyValue.signum() == -1) { throw new IllegalStateException(String .format("Configuration \"%s\" has an invalid non-negative BigDecimal value: \"%s\".", configurationValue.getKey(), nonNegativeBigDecimalPropertyValue)); } return nonNegativeBigDecimalPropertyValue; } /** * Calls {@link #getProperty(ConfigurationValue, Class)} where the target type is {@link String}. * * @param configurationValue {@link ConfigurationValue} * * @return The string value */ public String getProperty(ConfigurationValue configurationValue) { return getProperty(configurationValue, String.class); } /** * Calls {@link #getProperty(ConfigurationValue, Class, Environment)} * * @param configurationValue The {@link ConfigurationValue} * @param targetType The return type * * @return The property value */ public <T> T getProperty(ConfigurationValue configurationValue, Class<T> targetType) { return getProperty(configurationValue, targetType, environment); } /** * Will return all configuration value types as a string. * * @param configurationValue {@link ConfigurationValue} * * @return String value */ public String getPropertyAsString(ConfigurationValue configurationValue) { return environment .getProperty(configurationValue.getKey(), configurationValue.getDefaultValue() == null ? "" : configurationValue.getDefaultValue().toString()); } /** * Gets a property value and validates that it is not blank or null. * * @param configurationValue {@link ConfigurationValue} * * @return the string value */ public String getRequiredProperty(ConfigurationValue configurationValue) { return getRequiredProperty(configurationValue, environment); } /** * Gets a property value and validates that it is not blank or null. * * @param configurationValue {@link ConfigurationValue} * @param environment the environment containing the property * * @return the string value */ public String getRequiredProperty(ConfigurationValue configurationValue, Environment environment) { String property = getProperty(configurationValue, String.class, environment); if (StringUtils.isBlank(property)) { throw new IllegalStateException(String.format("Configuration \"%s\" must have a value.", configurationValue.getKey())); } return property; } /** * Logs the error message, and then throws {@link IllegalStateException} * * @param configurationValue - {@link ConfigurationValue} * @param targetTypeName - the name of the data type we want to convert the configuration value to(boolean, BigDecimal...etc) * @param stringValue - the configuration value in string type * @param exception - the exception thrown when converting the configuration value from string type to the target data type */ private void logErrorAndThrowIllegalStateException(ConfigurationValue configurationValue, String targetTypeName, String stringValue, Exception exception) { // Create an invalid state exception. IllegalStateException illegalStateException = new IllegalStateException( String.format("Configuration \"%s\" has an invalid %s value: \"%s\".", configurationValue.getKey(), targetTypeName, stringValue), exception); // Log the exception. LOGGER.error(illegalStateException.getMessage(), illegalStateException); // This will produce a 500 HTTP status code error. throw illegalStateException; } }
apache-2.0
thomasdarimont/spring-boot-cdi-instance-example
src/main/java/demo/greet/CountryStyleGreeter.java
168
package demo.greet; @CountryStyle public class CountryStyleGreeter implements Greeter { @Override public String greet(String name) { return "Howdy " + name; } }
apache-2.0
gpanther/fastutil-guava-tests
src/test/java/net/greypanther/fastutil/generated/DoubleCollectionsTest.java
58068
package net.greypanther.fastutil.generated; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import com.google.common.collect.Iterables; import com.google.common.collect.testing.ListTestSuiteBuilder; import com.google.common.collect.testing.MapTestSuiteBuilder; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.SetTestSuiteBuilder; import com.google.common.collect.testing.SortedMapTestSuiteBuilder; import com.google.common.collect.testing.SortedSetTestSuiteBuilder; import com.google.common.collect.testing.TestListGenerator; import com.google.common.collect.testing.TestSetGenerator; import com.google.common.collect.testing.TestSortedSetGenerator; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.features.ListFeature; import com.google.common.collect.testing.features.MapFeature; import com.google.common.collect.testing.features.SetFeature; import it.unimi.dsi.fastutil.BigList; import it.unimi.dsi.fastutil.BigListIterator; import it.unimi.dsi.fastutil.doubles.DoubleAVLTreeSet; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.doubles.DoubleArraySet; import it.unimi.dsi.fastutil.doubles.DoubleBigArrayBigList; import it.unimi.dsi.fastutil.doubles.DoubleBigListIterator; import it.unimi.dsi.fastutil.doubles.DoubleBigLists; import it.unimi.dsi.fastutil.doubles.DoubleHash; import it.unimi.dsi.fastutil.doubles.DoubleLinkedOpenCustomHashSet; import it.unimi.dsi.fastutil.doubles.DoubleLinkedOpenHashSet; import it.unimi.dsi.fastutil.doubles.DoubleLists; import it.unimi.dsi.fastutil.doubles.DoubleOpenHashSet; import it.unimi.dsi.fastutil.doubles.DoubleOpenHashBigSet; import it.unimi.dsi.fastutil.doubles.DoubleRBTreeSet; import it.unimi.dsi.fastutil.doubles.DoubleSets; import it.unimi.dsi.fastutil.doubles.DoubleSortedSets; import it.unimi.dsi.fastutil.doubles.Double2ShortArrayMap; import it.unimi.dsi.fastutil.doubles.Double2ShortLinkedOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2ShortMap; import it.unimi.dsi.fastutil.doubles.Double2ShortMaps; import it.unimi.dsi.fastutil.doubles.Double2ShortOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2ShortAVLTreeMap; import it.unimi.dsi.fastutil.doubles.Double2ShortRBTreeMap; import it.unimi.dsi.fastutil.doubles.Double2ShortSortedMap; import it.unimi.dsi.fastutil.doubles.Double2ShortSortedMaps; import it.unimi.dsi.fastutil.doubles.Double2ReferenceArrayMap; import it.unimi.dsi.fastutil.doubles.Double2ReferenceLinkedOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2ReferenceMap; import it.unimi.dsi.fastutil.doubles.Double2ReferenceMaps; import it.unimi.dsi.fastutil.doubles.Double2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2ReferenceAVLTreeMap; import it.unimi.dsi.fastutil.doubles.Double2ReferenceRBTreeMap; import it.unimi.dsi.fastutil.doubles.Double2ReferenceSortedMap; import it.unimi.dsi.fastutil.doubles.Double2ReferenceSortedMaps; import it.unimi.dsi.fastutil.doubles.Double2IntArrayMap; import it.unimi.dsi.fastutil.doubles.Double2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2IntMap; import it.unimi.dsi.fastutil.doubles.Double2IntMaps; import it.unimi.dsi.fastutil.doubles.Double2IntOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2IntAVLTreeMap; import it.unimi.dsi.fastutil.doubles.Double2IntRBTreeMap; import it.unimi.dsi.fastutil.doubles.Double2IntSortedMap; import it.unimi.dsi.fastutil.doubles.Double2IntSortedMaps; import it.unimi.dsi.fastutil.doubles.Double2DoubleArrayMap; import it.unimi.dsi.fastutil.doubles.Double2DoubleLinkedOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2DoubleMap; import it.unimi.dsi.fastutil.doubles.Double2DoubleMaps; import it.unimi.dsi.fastutil.doubles.Double2DoubleOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2DoubleAVLTreeMap; import it.unimi.dsi.fastutil.doubles.Double2DoubleRBTreeMap; import it.unimi.dsi.fastutil.doubles.Double2DoubleSortedMap; import it.unimi.dsi.fastutil.doubles.Double2DoubleSortedMaps; import it.unimi.dsi.fastutil.doubles.Double2FloatArrayMap; import it.unimi.dsi.fastutil.doubles.Double2FloatLinkedOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2FloatMap; import it.unimi.dsi.fastutil.doubles.Double2FloatMaps; import it.unimi.dsi.fastutil.doubles.Double2FloatOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2FloatAVLTreeMap; import it.unimi.dsi.fastutil.doubles.Double2FloatRBTreeMap; import it.unimi.dsi.fastutil.doubles.Double2FloatSortedMap; import it.unimi.dsi.fastutil.doubles.Double2FloatSortedMaps; import it.unimi.dsi.fastutil.doubles.Double2LongArrayMap; import it.unimi.dsi.fastutil.doubles.Double2LongLinkedOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2LongMap; import it.unimi.dsi.fastutil.doubles.Double2LongMaps; import it.unimi.dsi.fastutil.doubles.Double2LongOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2LongAVLTreeMap; import it.unimi.dsi.fastutil.doubles.Double2LongRBTreeMap; import it.unimi.dsi.fastutil.doubles.Double2LongSortedMap; import it.unimi.dsi.fastutil.doubles.Double2LongSortedMaps; import it.unimi.dsi.fastutil.doubles.Double2CharArrayMap; import it.unimi.dsi.fastutil.doubles.Double2CharLinkedOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2CharMap; import it.unimi.dsi.fastutil.doubles.Double2CharMaps; import it.unimi.dsi.fastutil.doubles.Double2CharOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2CharAVLTreeMap; import it.unimi.dsi.fastutil.doubles.Double2CharRBTreeMap; import it.unimi.dsi.fastutil.doubles.Double2CharSortedMap; import it.unimi.dsi.fastutil.doubles.Double2CharSortedMaps; import it.unimi.dsi.fastutil.doubles.Double2ObjectArrayMap; import it.unimi.dsi.fastutil.doubles.Double2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2ObjectMap; import it.unimi.dsi.fastutil.doubles.Double2ObjectMaps; import it.unimi.dsi.fastutil.doubles.Double2ObjectOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2ObjectAVLTreeMap; import it.unimi.dsi.fastutil.doubles.Double2ObjectRBTreeMap; import it.unimi.dsi.fastutil.doubles.Double2ObjectSortedMap; import it.unimi.dsi.fastutil.doubles.Double2ObjectSortedMaps; import it.unimi.dsi.fastutil.doubles.Double2ByteArrayMap; import it.unimi.dsi.fastutil.doubles.Double2ByteLinkedOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2ByteMap; import it.unimi.dsi.fastutil.doubles.Double2ByteMaps; import it.unimi.dsi.fastutil.doubles.Double2ByteOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2ByteAVLTreeMap; import it.unimi.dsi.fastutil.doubles.Double2ByteRBTreeMap; import it.unimi.dsi.fastutil.doubles.Double2ByteSortedMap; import it.unimi.dsi.fastutil.doubles.Double2ByteSortedMaps; import junit.framework.TestSuite; @RunWith(Enclosed.class) public final class DoubleCollectionsTest { private static final boolean RUN_ARRAYMAP_TESTS = System.getProperties().containsKey("runArrayMapTests"); private static final boolean RUN_ARRAYSET_TESTS = System.getProperties().containsKey("runArraySetTests"); public static final class PriorityQueue { @Test @Ignore public void testPriorityQueue() { fail("guava-testlib has no tests for priority queues"); } } public static final class Stack { @Test @Ignore public void testStack() { fail("guava-testlib has no tests for stacks"); } } public static final class Lists { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("DoubleCollectionsTests.Lists"); suite.addTest(getDoubleArrayListTests()); suite.addTest(getSynchronizedDoubleArrayListTests()); suite.addTest(getUnmodifiableDoubleArrayListTests()); suite.addTest(getSingletonDoubleListTests()); suite.addTest(getEmptyDoubleListTests()); return suite; } private static junit.framework.Test getDoubleArrayListTests() { return getGeneralDoubleListTests("DoubleArrayList", c -> new DoubleArrayList(c), Modifiable.MUTABLE); } private static junit.framework.Test getSynchronizedDoubleArrayListTests() { return getGeneralDoubleListTests("SynchronizedDoubleArrayList", c -> DoubleLists.synchronize(new DoubleArrayList(c)), Modifiable.MUTABLE); } private static junit.framework.Test getUnmodifiableDoubleArrayListTests() { return getGeneralDoubleListTests("UnmodifiableDoubleArrayList", c -> DoubleLists.unmodifiable(new DoubleArrayList(c)), Modifiable.IMMUTABLE); } private static junit.framework.Test getSingletonDoubleListTests() { final class Generator extends DoubleGeneratorBase implements TestListGenerator<Double> { @Override public List<Double> create(Object... elements) { Double value = Iterables.getOnlyElement(arrayToCollection(elements)); return DoubleLists.singleton(value); } } return ListTestSuiteBuilder.using(new Generator()).named("DoubleSingletonList") .withFeatures(CollectionSize.ONE, CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS) .createTestSuite(); } private static junit.framework.Test getEmptyDoubleListTests() { final class Generator extends DoubleGeneratorBase implements TestListGenerator<Double> { @Override public List<Double> create(Object... elements) { assertEquals(0, elements.length); return DoubleLists.EMPTY_LIST; } } return ListTestSuiteBuilder.using(new Generator()).named("DoubleEmptyList") .withFeatures(CollectionSize.ZERO, CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS) .createTestSuite(); } } public static final class BigLists { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("DoubleCollectionsTests.BigLists"); suite.addTest(getDoubleBigArrayBigListTests()); suite.addTest(getSynchronizedDoubleBigArrayBigListTests()); suite.addTest(getUnmodifiableDoubleBigArrayBigListTests()); suite.addTest(getSingletonDoubleBigListTests()); suite.addTest(getEmptyDoubleBigListTests()); return suite; } private static junit.framework.Test getDoubleBigArrayBigListTests() { return getGeneralDoubleListTests("DoubleBigArrayBigList", c -> new DoubleBigList2ListAdapter(new DoubleBigArrayBigList(c.iterator())), Modifiable.MUTABLE); } private static junit.framework.Test getSynchronizedDoubleBigArrayBigListTests() { return getGeneralDoubleListTests("SynchronizedDoubleBigArrayBigList", c -> new DoubleBigList2ListAdapter( DoubleBigLists.synchronize(new DoubleBigArrayBigList(c.iterator()))), Modifiable.MUTABLE); } private static junit.framework.Test getUnmodifiableDoubleBigArrayBigListTests() { return getGeneralDoubleListTests("UnmodifiableDoubleBigArrayBigList", c -> new DoubleBigList2ListAdapter( DoubleBigLists.unmodifiable(new DoubleBigArrayBigList(c.iterator()))), Modifiable.IMMUTABLE); } private static junit.framework.Test getSingletonDoubleBigListTests() { final class Generator extends DoubleGeneratorBase implements TestListGenerator<Double> { @Override public List<Double> create(Object... elements) { Double value = Iterables.getOnlyElement(arrayToCollection(elements)); return new DoubleBigList2ListAdapter(DoubleBigLists.singleton(value)); } } return ListTestSuiteBuilder.using(new Generator()).named("SingletonDoubleBigList") .withFeatures(CollectionSize.ONE, CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS) .createTestSuite(); } private static junit.framework.Test getEmptyDoubleBigListTests() { final class Generator extends DoubleGeneratorBase implements TestListGenerator<Double> { @Override public List<Double> create(Object... elements) { assertEquals(0, elements.length); return new DoubleBigList2ListAdapter(DoubleBigLists.EMPTY_BIG_LIST); } } return ListTestSuiteBuilder.using(new Generator()).named("EmptyDoubleBigList") .withFeatures(CollectionSize.ZERO, CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS) .createTestSuite(); } @SuppressWarnings("serial") private static final class DoubleBigList2ListAdapter extends BigList2ListAdapter<Double> { private DoubleBigList2ListAdapter(BigList<Double> bigList) { super(bigList); } @Override public List<Double> subList(int fromIndex, int toIndex) { return new DoubleBigList2ListAdapter(bigList.subList(fromIndex, toIndex)); } @Override void bigListIteratorSet(BigListIterator<Double> bigListIterator, Double e) { ((DoubleBigListIterator) bigListIterator).set(e); } @Override void bigListIteratorAdd(BigListIterator<Double> bigListIterator, Double e) { ((DoubleBigListIterator) bigListIterator).add(e); } } } public static final class Sets { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("DoubleCollectionsTests.Sets"); if (RUN_ARRAYSET_TESTS) { suite.addTest(getDoubleArraySetTests()); suite.addTest(getSynchronizedDoubleArraySetTests()); suite.addTest(getUnmodifiableDoubleArraySetTests()); } suite.addTest(getDoubleOpenHashSetTests()); suite.addTest(getSynchronizedDoubleOpenHashSetTests()); suite.addTest(getUnmodifiableDoubleOpenHashSetTests()); suite.addTest(getDoubleOpenHashBigSetTests()); suite.addTest(getLinkedOpenHashSetTests()); suite.addTest(getLinkedOpenCustomHashSetTests()); suite.addTest(getSingletonDoubleSetTests()); suite.addTest(getEmptyDoubleSetTests()); return suite; } private static junit.framework.Test getDoubleArraySetTests() { return getGeneralDoubleSetTests("DoubleArraySet", c -> new DoubleArraySet(c), Modifiable.MUTABLE); } private static junit.framework.Test getSynchronizedDoubleArraySetTests() { return getGeneralDoubleSetTests("SynchronizedDoubleArraySet", c -> DoubleSets.synchronize(new DoubleArraySet(c)), Modifiable.MUTABLE); } private static junit.framework.Test getUnmodifiableDoubleArraySetTests() { return getGeneralDoubleSetTests("UnmodifiableDoubleArraySet", c -> DoubleSets.unmodifiable(new DoubleArraySet(c)), Modifiable.IMMUTABLE); } private static junit.framework.Test getDoubleOpenHashSetTests() { return getGeneralDoubleSetTests("DoubleOpenHashSet", c -> new DoubleOpenHashSet(c), Modifiable.MUTABLE); } private static junit.framework.Test getSynchronizedDoubleOpenHashSetTests() { return getGeneralDoubleSetTests("DoubleOpenHashSet", c -> DoubleSets.synchronize(new DoubleOpenHashSet(c)), Modifiable.MUTABLE); } private static junit.framework.Test getUnmodifiableDoubleOpenHashSetTests() { return getGeneralDoubleSetTests("DoubleOpenHashSet", c -> DoubleSets.unmodifiable(new DoubleOpenHashSet(c)), Modifiable.IMMUTABLE); } private static junit.framework.Test getDoubleOpenHashBigSetTests() { return getGeneralDoubleSetTests("DoubleOpenHashBigSet", c -> new DoubleOpenHashBigSet(c), Modifiable.MUTABLE); } private static junit.framework.Test getLinkedOpenHashSetTests() { return getGeneralDoubleSetTests("DoubleLinkedOpenHashSet", c -> new DoubleLinkedOpenHashSet(c), Modifiable.MUTABLE); } private static junit.framework.Test getLinkedOpenCustomHashSetTests() { @SuppressWarnings("serial") final class HashStrategy implements DoubleHash.Strategy, java.io.Serializable { @Override public int hashCode(double e) { return Double.hashCode(e); } @Override public boolean equals(double a, double b) { return a == b; } } return getGeneralDoubleSetTests("DoubleLinkedOpenCustomHashSet", c -> new DoubleLinkedOpenCustomHashSet(c, new HashStrategy()), Modifiable.MUTABLE); } private static junit.framework.Test getGeneralDoubleSetTests(String testSuiteName, Function<Collection<Double>, Set<Double>> generator, Modifiable modifiable) { final class Generator extends DoubleGeneratorBase implements TestSetGenerator<Double> { @Override public Set<Double> create(Object... elements) { return generator.apply(arrayToCollection(elements)); } } List<Feature<?>> testSuiteFeatures = new ArrayList<>(4); testSuiteFeatures.add(CollectionSize.ANY); testSuiteFeatures.add(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); testSuiteFeatures.add(CollectionFeature.NON_STANDARD_TOSTRING); switch (modifiable) { case IMMUTABLE: break; case MUTABLE: testSuiteFeatures.add(SetFeature.GENERAL_PURPOSE); break; default: throw new IllegalArgumentException(modifiable.toString()); } return SetTestSuiteBuilder.using(new Generator()).named(testSuiteName) .withFeatures(testSuiteFeatures).createTestSuite(); } private static junit.framework.Test getSingletonDoubleSetTests() { final class Generator extends DoubleGeneratorBase implements TestSetGenerator<Double> { @Override public Set<Double> create(Object... elements) { Double value = Iterables.getOnlyElement(arrayToCollection(elements)); return DoubleSets.singleton(value); } } return SetTestSuiteBuilder.using(new Generator()).named("DoubleSingletonSet") .withFeatures(CollectionSize.ONE, CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS, CollectionFeature.NON_STANDARD_TOSTRING) .createTestSuite(); } private static junit.framework.Test getEmptyDoubleSetTests() { final class Generator extends DoubleGeneratorBase implements TestSetGenerator<Double> { @Override public Set<Double> create(Object... elements) { assertEquals(0, elements.length); return DoubleSets.EMPTY_SET; } } return SetTestSuiteBuilder.using(new Generator()).named("DoubleEmptySet") .withFeatures(CollectionSize.ZERO, CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS, CollectionFeature.NON_STANDARD_TOSTRING) .createTestSuite(); } } public static final class SortedSets { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("DoubleCollectionsTests.SortedSets"); suite.addTest(getAVLTreeSetTests()); suite.addTest(getRBTreeSetTests()); suite.addTest(getSynchronizedRBTreeSetTests()); suite.addTest(getUnmodifiableRBTreeSetTests()); suite.addTest(getSingletonDoubleSortedSetTests()); suite.addTest(getEmptyDoubleSortedSetTests()); return suite; } private static junit.framework.Test getAVLTreeSetTests() { return getGeneralDoubleSortedSetTests("DoubleAVLTreeSet", c -> new DoubleAVLTreeSet(c), Modifiable.MUTABLE, Ordering.SORTED); } private static junit.framework.Test getRBTreeSetTests() { return getGeneralDoubleSortedSetTests("DoubleRBTreeSet", c -> new DoubleRBTreeSet(c), Modifiable.MUTABLE, Ordering.SORTED); } private static junit.framework.Test getSynchronizedRBTreeSetTests() { return getGeneralDoubleSortedSetTests("DoubleRBTreeSet", c -> DoubleSortedSets.synchronize(new DoubleRBTreeSet(c)), Modifiable.MUTABLE, Ordering.SORTED); } private static junit.framework.Test getUnmodifiableRBTreeSetTests() { return getGeneralDoubleSortedSetTests("DoubleRBTreeSet", c -> DoubleSortedSets.unmodifiable(new DoubleRBTreeSet(c)), Modifiable.IMMUTABLE, Ordering.SORTED); } private static junit.framework.Test getGeneralDoubleSortedSetTests(String testSuiteName, Function<Collection<Double>, SortedSet<Double>> generator, Modifiable modifiable, Ordering ordering) { List<Feature<?>> testSuiteFeatures = new ArrayList<>(7); testSuiteFeatures.add(CollectionSize.ANY); testSuiteFeatures.add(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); testSuiteFeatures.add(CollectionFeature.KNOWN_ORDER); testSuiteFeatures.add(CollectionFeature.SUBSET_VIEW); testSuiteFeatures.add(CollectionFeature.DESCENDING_VIEW); testSuiteFeatures.add(CollectionFeature.NON_STANDARD_TOSTRING); switch (modifiable) { case IMMUTABLE: break; case MUTABLE: testSuiteFeatures.add(SetFeature.GENERAL_PURPOSE); break; default: throw new IllegalArgumentException(modifiable.toString()); } return SortedSetTestSuiteBuilder.using(new DoubleSortedSetGenerator(ordering, generator)) .named(testSuiteName).withFeatures(testSuiteFeatures).createTestSuite(); } private static junit.framework.Test getSingletonDoubleSortedSetTests() { return SortedSetTestSuiteBuilder.using(new DoubleSortedSetGenerator(Ordering.SORTED, c -> { Double value = Iterables.getOnlyElement(c); return DoubleSortedSets.singleton(value); })).named("DoubleSingletonSortedSet") .withFeatures(CollectionSize.ONE, CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS, CollectionFeature.KNOWN_ORDER, CollectionFeature.SUBSET_VIEW, CollectionFeature.DESCENDING_VIEW, CollectionFeature.NON_STANDARD_TOSTRING) .createTestSuite(); } private static junit.framework.Test getEmptyDoubleSortedSetTests() { return SortedSetTestSuiteBuilder.using(new DoubleSortedSetGenerator(Ordering.SORTED, c -> { assertTrue(c.isEmpty()); return DoubleSortedSets.EMPTY_SET; })).named("DoubleSingletonSortedSet") .withFeatures(CollectionSize.ZERO, CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS, CollectionFeature.KNOWN_ORDER, CollectionFeature.SUBSET_VIEW, CollectionFeature.DESCENDING_VIEW, CollectionFeature.NON_STANDARD_TOSTRING) .createTestSuite(); } private static class DoubleSortedSetGenerator extends DoubleGeneratorBase implements TestSortedSetGenerator<Double> { private final Function<Collection<Double>, SortedSet<Double>> generator; DoubleSortedSetGenerator(Ordering ordering, Function<Collection<Double>, SortedSet<Double>> generator) { super(TestSampleValues.DOUBLE_SAMPLE_ELEMENTS_FOR_SORTED, ordering); this.generator = generator; } @Override public SortedSet<Double> create(Object... elements) { return generator.apply(arrayToCollection(elements)); } @Override public Double belowSamplesLesser() { return TestSampleValues.DOUBLES_FOR_SORTED[0]; } @Override public Double belowSamplesGreater() { return TestSampleValues.DOUBLES_FOR_SORTED[1]; } @Override public Double aboveSamplesLesser() { return TestSampleValues.DOUBLES_FOR_SORTED[7]; } @Override public Double aboveSamplesGreater() { return TestSampleValues.DOUBLES_FOR_SORTED[8]; } } } public static final class FastutilDouble2ShortMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.Maps"); if (RUN_ARRAYMAP_TESTS) { suite.addTest(getMapTests(Short.class, Double2ShortArrayMap::new, TestSampleValues.SHORT_SAMPLE_ELEMENTS)); suite.addTest(getSynchronizedArrayMapTests(Short.class, Double2ShortArrayMap::new, m -> Double2ShortMaps.synchronize((Double2ShortMap) m), TestSampleValues.SHORT_SAMPLE_ELEMENTS)); suite.addTest(getUnmodifiableArrayMapTests(Short.class, Double2ShortArrayMap::new, m -> Double2ShortMaps.unmodifiable((Double2ShortMap) m), TestSampleValues.SHORT_SAMPLE_ELEMENTS)); } suite.addTest(getMapTests(Short.class, Double2ShortOpenHashMap::new, TestSampleValues.SHORT_SAMPLE_ELEMENTS)); // Not really a sorted set? suite.addTest(getMapTests(Short.class, Double2ShortLinkedOpenHashMap::new, TestSampleValues.SHORT_SAMPLE_ELEMENTS)); suite.addTest(getSingletonMapTests(Short.class, Double2ShortMaps::singleton, TestSampleValues.SHORT_SAMPLE_ELEMENTS)); suite.addTest(getEmptyMapTests(Short.class, Double2ShortMaps.EMPTY_MAP, TestSampleValues.SHORT_SAMPLE_ELEMENTS)); return suite; } } public static final class FastutilDouble2ShortSortedMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.SortedMaps"); suite.addTest(getSortedMapTests(Short.class, Double2ShortAVLTreeMap::new, TestSampleValues.SHORTS_FOR_SORTED)); suite.addTest(getSortedMapTests(Short.class, Double2ShortRBTreeMap::new, TestSampleValues.SHORTS_FOR_SORTED)); suite.addTest(getSynchronizedRBTreeMapTests(Short.class, Double2ShortRBTreeMap::new, m -> Double2ShortSortedMaps.synchronize((Double2ShortSortedMap) m), TestSampleValues.SHORTS_FOR_SORTED)); suite.addTest(getUnmodifiableRBTreeMapTests(Short.class, Double2ShortRBTreeMap::new, m -> Double2ShortSortedMaps.unmodifiable((Double2ShortSortedMap) m), TestSampleValues.SHORTS_FOR_SORTED)); // Bugs? // suite.addTest(getSingletonSortedMapTests(Short.class, Double2ShortSortedMaps::singleton, // TestSampleValues.SHORTS_FOR_SORTED)); // suite.addTest(getEmptySortedMapTests(Short.class, Double2ShortSortedMaps.EMPTY_MAP, // TestSampleValues.SHORTS_FOR_SORTED)); return suite; } } public static final class FastutilDouble2ReferenceMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.Maps"); if (RUN_ARRAYMAP_TESTS) { suite.addTest(getMapTests(String.class, Double2ReferenceArrayMap::new, TestSampleValues.REFERENCE_SAMPLE_ELEMENTS)); suite.addTest(getSynchronizedArrayMapTests(String.class, Double2ReferenceArrayMap::new, m -> Double2ReferenceMaps.synchronize((Double2ReferenceMap<String>) m), TestSampleValues.REFERENCE_SAMPLE_ELEMENTS)); suite.addTest(getUnmodifiableArrayMapTests(String.class, Double2ReferenceArrayMap::new, m -> Double2ReferenceMaps.unmodifiable((Double2ReferenceMap<String>) m), TestSampleValues.REFERENCE_SAMPLE_ELEMENTS)); } suite.addTest(getMapTests(String.class, Double2ReferenceOpenHashMap::new, TestSampleValues.REFERENCE_SAMPLE_ELEMENTS)); // Not really a sorted set? suite.addTest(getMapTests(String.class, Double2ReferenceLinkedOpenHashMap::new, TestSampleValues.REFERENCE_SAMPLE_ELEMENTS)); suite.addTest(getSingletonMapTests(String.class, Double2ReferenceMaps::singleton, TestSampleValues.REFERENCE_SAMPLE_ELEMENTS)); suite.addTest(getEmptyMapTests(String.class, Double2ReferenceMaps.emptyMap(), TestSampleValues.REFERENCE_SAMPLE_ELEMENTS)); return suite; } } public static final class FastutilDouble2ReferenceSortedMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.SortedMaps"); suite.addTest(getSortedMapTests(String.class, Double2ReferenceAVLTreeMap::new, TestSampleValues.REFERENCES_FOR_SORTED)); suite.addTest(getSortedMapTests(String.class, Double2ReferenceRBTreeMap::new, TestSampleValues.REFERENCES_FOR_SORTED)); suite.addTest(getSynchronizedRBTreeMapTests(String.class, Double2ReferenceRBTreeMap::new, m -> Double2ReferenceSortedMaps.synchronize((Double2ReferenceSortedMap<String>) m), TestSampleValues.REFERENCES_FOR_SORTED)); suite.addTest(getUnmodifiableRBTreeMapTests(String.class, Double2ReferenceRBTreeMap::new, m -> Double2ReferenceSortedMaps.unmodifiable((Double2ReferenceSortedMap<String>) m), TestSampleValues.REFERENCES_FOR_SORTED)); // Bugs? // suite.addTest(getSingletonSortedMapTests(String.class, // Double2ReferenceSortedMaps::singleton, // TestSampleValues.REFERENCES_FOR_SORTED)); // suite.addTest(getEmptySortedMapTests(String.class, Double2ReferenceSortedMaps.EMPTY_MAP, // TestSampleValues.REFERENCES_FOR_SORTED)); return suite; } } public static final class FastutilDouble2IntMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.Maps"); if (RUN_ARRAYMAP_TESTS) { suite.addTest(getMapTests(Integer.class, Double2IntArrayMap::new, TestSampleValues.INT_SAMPLE_ELEMENTS)); suite.addTest(getSynchronizedArrayMapTests(Integer.class, Double2IntArrayMap::new, m -> Double2IntMaps.synchronize((Double2IntMap) m), TestSampleValues.INT_SAMPLE_ELEMENTS)); suite.addTest(getUnmodifiableArrayMapTests(Integer.class, Double2IntArrayMap::new, m -> Double2IntMaps.unmodifiable((Double2IntMap) m), TestSampleValues.INT_SAMPLE_ELEMENTS)); } suite.addTest(getMapTests(Integer.class, Double2IntOpenHashMap::new, TestSampleValues.INT_SAMPLE_ELEMENTS)); // Not really a sorted set? suite.addTest(getMapTests(Integer.class, Double2IntLinkedOpenHashMap::new, TestSampleValues.INT_SAMPLE_ELEMENTS)); suite.addTest(getSingletonMapTests(Integer.class, Double2IntMaps::singleton, TestSampleValues.INT_SAMPLE_ELEMENTS)); suite.addTest(getEmptyMapTests(Integer.class, Double2IntMaps.EMPTY_MAP, TestSampleValues.INT_SAMPLE_ELEMENTS)); return suite; } } public static final class FastutilDouble2IntSortedMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.SortedMaps"); suite.addTest(getSortedMapTests(Integer.class, Double2IntAVLTreeMap::new, TestSampleValues.INTS_FOR_SORTED)); suite.addTest(getSortedMapTests(Integer.class, Double2IntRBTreeMap::new, TestSampleValues.INTS_FOR_SORTED)); suite.addTest(getSynchronizedRBTreeMapTests(Integer.class, Double2IntRBTreeMap::new, m -> Double2IntSortedMaps.synchronize((Double2IntSortedMap) m), TestSampleValues.INTS_FOR_SORTED)); suite.addTest(getUnmodifiableRBTreeMapTests(Integer.class, Double2IntRBTreeMap::new, m -> Double2IntSortedMaps.unmodifiable((Double2IntSortedMap) m), TestSampleValues.INTS_FOR_SORTED)); // Bugs? // suite.addTest(getSingletonSortedMapTests(Integer.class, Double2IntSortedMaps::singleton, // TestSampleValues.INTS_FOR_SORTED)); // suite.addTest(getEmptySortedMapTests(Integer.class, Double2IntSortedMaps.EMPTY_MAP, // TestSampleValues.INTS_FOR_SORTED)); return suite; } } public static final class FastutilDouble2DoubleMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.Maps"); if (RUN_ARRAYMAP_TESTS) { suite.addTest(getMapTests(Double.class, Double2DoubleArrayMap::new, TestSampleValues.DOUBLE_SAMPLE_ELEMENTS)); suite.addTest(getSynchronizedArrayMapTests(Double.class, Double2DoubleArrayMap::new, m -> Double2DoubleMaps.synchronize((Double2DoubleMap) m), TestSampleValues.DOUBLE_SAMPLE_ELEMENTS)); suite.addTest(getUnmodifiableArrayMapTests(Double.class, Double2DoubleArrayMap::new, m -> Double2DoubleMaps.unmodifiable((Double2DoubleMap) m), TestSampleValues.DOUBLE_SAMPLE_ELEMENTS)); } suite.addTest(getMapTests(Double.class, Double2DoubleOpenHashMap::new, TestSampleValues.DOUBLE_SAMPLE_ELEMENTS)); // Not really a sorted set? suite.addTest(getMapTests(Double.class, Double2DoubleLinkedOpenHashMap::new, TestSampleValues.DOUBLE_SAMPLE_ELEMENTS)); suite.addTest(getSingletonMapTests(Double.class, Double2DoubleMaps::singleton, TestSampleValues.DOUBLE_SAMPLE_ELEMENTS)); suite.addTest(getEmptyMapTests(Double.class, Double2DoubleMaps.EMPTY_MAP, TestSampleValues.DOUBLE_SAMPLE_ELEMENTS)); return suite; } } public static final class FastutilDouble2DoubleSortedMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.SortedMaps"); suite.addTest(getSortedMapTests(Double.class, Double2DoubleAVLTreeMap::new, TestSampleValues.DOUBLES_FOR_SORTED)); suite.addTest(getSortedMapTests(Double.class, Double2DoubleRBTreeMap::new, TestSampleValues.DOUBLES_FOR_SORTED)); suite.addTest(getSynchronizedRBTreeMapTests(Double.class, Double2DoubleRBTreeMap::new, m -> Double2DoubleSortedMaps.synchronize((Double2DoubleSortedMap) m), TestSampleValues.DOUBLES_FOR_SORTED)); suite.addTest(getUnmodifiableRBTreeMapTests(Double.class, Double2DoubleRBTreeMap::new, m -> Double2DoubleSortedMaps.unmodifiable((Double2DoubleSortedMap) m), TestSampleValues.DOUBLES_FOR_SORTED)); // Bugs? // suite.addTest(getSingletonSortedMapTests(Double.class, Double2DoubleSortedMaps::singleton, // TestSampleValues.DOUBLES_FOR_SORTED)); // suite.addTest(getEmptySortedMapTests(Double.class, Double2DoubleSortedMaps.EMPTY_MAP, // TestSampleValues.DOUBLES_FOR_SORTED)); return suite; } } public static final class FastutilDouble2FloatMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.Maps"); if (RUN_ARRAYMAP_TESTS) { suite.addTest(getMapTests(Float.class, Double2FloatArrayMap::new, TestSampleValues.FLOAT_SAMPLE_ELEMENTS)); suite.addTest(getSynchronizedArrayMapTests(Float.class, Double2FloatArrayMap::new, m -> Double2FloatMaps.synchronize((Double2FloatMap) m), TestSampleValues.FLOAT_SAMPLE_ELEMENTS)); suite.addTest(getUnmodifiableArrayMapTests(Float.class, Double2FloatArrayMap::new, m -> Double2FloatMaps.unmodifiable((Double2FloatMap) m), TestSampleValues.FLOAT_SAMPLE_ELEMENTS)); } suite.addTest(getMapTests(Float.class, Double2FloatOpenHashMap::new, TestSampleValues.FLOAT_SAMPLE_ELEMENTS)); // Not really a sorted set? suite.addTest(getMapTests(Float.class, Double2FloatLinkedOpenHashMap::new, TestSampleValues.FLOAT_SAMPLE_ELEMENTS)); suite.addTest(getSingletonMapTests(Float.class, Double2FloatMaps::singleton, TestSampleValues.FLOAT_SAMPLE_ELEMENTS)); suite.addTest(getEmptyMapTests(Float.class, Double2FloatMaps.EMPTY_MAP, TestSampleValues.FLOAT_SAMPLE_ELEMENTS)); return suite; } } public static final class FastutilDouble2FloatSortedMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.SortedMaps"); suite.addTest(getSortedMapTests(Float.class, Double2FloatAVLTreeMap::new, TestSampleValues.FLOATS_FOR_SORTED)); suite.addTest(getSortedMapTests(Float.class, Double2FloatRBTreeMap::new, TestSampleValues.FLOATS_FOR_SORTED)); suite.addTest(getSynchronizedRBTreeMapTests(Float.class, Double2FloatRBTreeMap::new, m -> Double2FloatSortedMaps.synchronize((Double2FloatSortedMap) m), TestSampleValues.FLOATS_FOR_SORTED)); suite.addTest(getUnmodifiableRBTreeMapTests(Float.class, Double2FloatRBTreeMap::new, m -> Double2FloatSortedMaps.unmodifiable((Double2FloatSortedMap) m), TestSampleValues.FLOATS_FOR_SORTED)); // Bugs? // suite.addTest(getSingletonSortedMapTests(Float.class, Double2FloatSortedMaps::singleton, // TestSampleValues.FLOATS_FOR_SORTED)); // suite.addTest(getEmptySortedMapTests(Float.class, Double2FloatSortedMaps.EMPTY_MAP, // TestSampleValues.FLOATS_FOR_SORTED)); return suite; } } public static final class FastutilDouble2LongMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.Maps"); if (RUN_ARRAYMAP_TESTS) { suite.addTest(getMapTests(Long.class, Double2LongArrayMap::new, TestSampleValues.LONG_SAMPLE_ELEMENTS)); suite.addTest(getSynchronizedArrayMapTests(Long.class, Double2LongArrayMap::new, m -> Double2LongMaps.synchronize((Double2LongMap) m), TestSampleValues.LONG_SAMPLE_ELEMENTS)); suite.addTest(getUnmodifiableArrayMapTests(Long.class, Double2LongArrayMap::new, m -> Double2LongMaps.unmodifiable((Double2LongMap) m), TestSampleValues.LONG_SAMPLE_ELEMENTS)); } suite.addTest(getMapTests(Long.class, Double2LongOpenHashMap::new, TestSampleValues.LONG_SAMPLE_ELEMENTS)); // Not really a sorted set? suite.addTest(getMapTests(Long.class, Double2LongLinkedOpenHashMap::new, TestSampleValues.LONG_SAMPLE_ELEMENTS)); suite.addTest(getSingletonMapTests(Long.class, Double2LongMaps::singleton, TestSampleValues.LONG_SAMPLE_ELEMENTS)); suite.addTest(getEmptyMapTests(Long.class, Double2LongMaps.EMPTY_MAP, TestSampleValues.LONG_SAMPLE_ELEMENTS)); return suite; } } public static final class FastutilDouble2LongSortedMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.SortedMaps"); suite.addTest(getSortedMapTests(Long.class, Double2LongAVLTreeMap::new, TestSampleValues.LONGS_FOR_SORTED)); suite.addTest(getSortedMapTests(Long.class, Double2LongRBTreeMap::new, TestSampleValues.LONGS_FOR_SORTED)); suite.addTest(getSynchronizedRBTreeMapTests(Long.class, Double2LongRBTreeMap::new, m -> Double2LongSortedMaps.synchronize((Double2LongSortedMap) m), TestSampleValues.LONGS_FOR_SORTED)); suite.addTest(getUnmodifiableRBTreeMapTests(Long.class, Double2LongRBTreeMap::new, m -> Double2LongSortedMaps.unmodifiable((Double2LongSortedMap) m), TestSampleValues.LONGS_FOR_SORTED)); // Bugs? // suite.addTest(getSingletonSortedMapTests(Long.class, Double2LongSortedMaps::singleton, // TestSampleValues.LONGS_FOR_SORTED)); // suite.addTest(getEmptySortedMapTests(Long.class, Double2LongSortedMaps.EMPTY_MAP, // TestSampleValues.LONGS_FOR_SORTED)); return suite; } } public static final class FastutilDouble2CharMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.Maps"); if (RUN_ARRAYMAP_TESTS) { suite.addTest(getMapTests(Character.class, Double2CharArrayMap::new, TestSampleValues.CHAR_SAMPLE_ELEMENTS)); suite.addTest(getSynchronizedArrayMapTests(Character.class, Double2CharArrayMap::new, m -> Double2CharMaps.synchronize((Double2CharMap) m), TestSampleValues.CHAR_SAMPLE_ELEMENTS)); suite.addTest(getUnmodifiableArrayMapTests(Character.class, Double2CharArrayMap::new, m -> Double2CharMaps.unmodifiable((Double2CharMap) m), TestSampleValues.CHAR_SAMPLE_ELEMENTS)); } suite.addTest(getMapTests(Character.class, Double2CharOpenHashMap::new, TestSampleValues.CHAR_SAMPLE_ELEMENTS)); // Not really a sorted set? suite.addTest(getMapTests(Character.class, Double2CharLinkedOpenHashMap::new, TestSampleValues.CHAR_SAMPLE_ELEMENTS)); suite.addTest(getSingletonMapTests(Character.class, Double2CharMaps::singleton, TestSampleValues.CHAR_SAMPLE_ELEMENTS)); suite.addTest(getEmptyMapTests(Character.class, Double2CharMaps.EMPTY_MAP, TestSampleValues.CHAR_SAMPLE_ELEMENTS)); return suite; } } public static final class FastutilDouble2CharSortedMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.SortedMaps"); suite.addTest(getSortedMapTests(Character.class, Double2CharAVLTreeMap::new, TestSampleValues.CHARS_FOR_SORTED)); suite.addTest(getSortedMapTests(Character.class, Double2CharRBTreeMap::new, TestSampleValues.CHARS_FOR_SORTED)); suite.addTest(getSynchronizedRBTreeMapTests(Character.class, Double2CharRBTreeMap::new, m -> Double2CharSortedMaps.synchronize((Double2CharSortedMap) m), TestSampleValues.CHARS_FOR_SORTED)); suite.addTest(getUnmodifiableRBTreeMapTests(Character.class, Double2CharRBTreeMap::new, m -> Double2CharSortedMaps.unmodifiable((Double2CharSortedMap) m), TestSampleValues.CHARS_FOR_SORTED)); // Bugs? // suite.addTest(getSingletonSortedMapTests(Character.class, Double2CharSortedMaps::singleton, // TestSampleValues.CHARS_FOR_SORTED)); // suite.addTest(getEmptySortedMapTests(Character.class, Double2CharSortedMaps.EMPTY_MAP, // TestSampleValues.CHARS_FOR_SORTED)); return suite; } } public static final class FastutilDouble2ObjectMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.Maps"); if (RUN_ARRAYMAP_TESTS) { suite.addTest(getMapTests(String.class, Double2ObjectArrayMap::new, TestSampleValues.OBJECT_SAMPLE_ELEMENTS)); suite.addTest(getSynchronizedArrayMapTests(String.class, Double2ObjectArrayMap::new, m -> Double2ObjectMaps.synchronize((Double2ObjectMap<String>) m), TestSampleValues.OBJECT_SAMPLE_ELEMENTS)); suite.addTest(getUnmodifiableArrayMapTests(String.class, Double2ObjectArrayMap::new, m -> Double2ObjectMaps.unmodifiable((Double2ObjectMap<String>) m), TestSampleValues.OBJECT_SAMPLE_ELEMENTS)); } suite.addTest(getMapTests(String.class, Double2ObjectOpenHashMap::new, TestSampleValues.OBJECT_SAMPLE_ELEMENTS)); // Not really a sorted set? suite.addTest(getMapTests(String.class, Double2ObjectLinkedOpenHashMap::new, TestSampleValues.OBJECT_SAMPLE_ELEMENTS)); suite.addTest(getSingletonMapTests(String.class, Double2ObjectMaps::singleton, TestSampleValues.OBJECT_SAMPLE_ELEMENTS)); suite.addTest(getEmptyMapTests(String.class, Double2ObjectMaps.emptyMap(), TestSampleValues.OBJECT_SAMPLE_ELEMENTS)); return suite; } } public static final class FastutilDouble2ObjectSortedMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.SortedMaps"); suite.addTest(getSortedMapTests(String.class, Double2ObjectAVLTreeMap::new, TestSampleValues.OBJECTS_FOR_SORTED)); suite.addTest(getSortedMapTests(String.class, Double2ObjectRBTreeMap::new, TestSampleValues.OBJECTS_FOR_SORTED)); suite.addTest(getSynchronizedRBTreeMapTests(String.class, Double2ObjectRBTreeMap::new, m -> Double2ObjectSortedMaps.synchronize((Double2ObjectSortedMap<String>) m), TestSampleValues.OBJECTS_FOR_SORTED)); suite.addTest(getUnmodifiableRBTreeMapTests(String.class, Double2ObjectRBTreeMap::new, m -> Double2ObjectSortedMaps.unmodifiable((Double2ObjectSortedMap<String>) m), TestSampleValues.OBJECTS_FOR_SORTED)); // Bugs? // suite.addTest(getSingletonSortedMapTests(String.class, Double2ObjectSortedMaps::singleton, // TestSampleValues.OBJECTS_FOR_SORTED)); // suite.addTest(getEmptySortedMapTests(String.class, Double2ObjectSortedMaps.EMPTY_MAP, // TestSampleValues.OBJECTS_FOR_SORTED)); return suite; } } public static final class FastutilDouble2ByteMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.Maps"); if (RUN_ARRAYMAP_TESTS) { suite.addTest(getMapTests(Byte.class, Double2ByteArrayMap::new, TestSampleValues.BYTE_SAMPLE_ELEMENTS)); suite.addTest(getSynchronizedArrayMapTests(Byte.class, Double2ByteArrayMap::new, m -> Double2ByteMaps.synchronize((Double2ByteMap) m), TestSampleValues.BYTE_SAMPLE_ELEMENTS)); suite.addTest(getUnmodifiableArrayMapTests(Byte.class, Double2ByteArrayMap::new, m -> Double2ByteMaps.unmodifiable((Double2ByteMap) m), TestSampleValues.BYTE_SAMPLE_ELEMENTS)); } suite.addTest(getMapTests(Byte.class, Double2ByteOpenHashMap::new, TestSampleValues.BYTE_SAMPLE_ELEMENTS)); // Not really a sorted set? suite.addTest(getMapTests(Byte.class, Double2ByteLinkedOpenHashMap::new, TestSampleValues.BYTE_SAMPLE_ELEMENTS)); suite.addTest(getSingletonMapTests(Byte.class, Double2ByteMaps::singleton, TestSampleValues.BYTE_SAMPLE_ELEMENTS)); suite.addTest(getEmptyMapTests(Byte.class, Double2ByteMaps.EMPTY_MAP, TestSampleValues.BYTE_SAMPLE_ELEMENTS)); return suite; } } public static final class FastutilDouble2ByteSortedMaps { public static junit.framework.Test suite() { TestSuite suite = new TestSuite("Double2ByteMaps.SortedMaps"); suite.addTest(getSortedMapTests(Byte.class, Double2ByteAVLTreeMap::new, TestSampleValues.BYTES_FOR_SORTED)); suite.addTest(getSortedMapTests(Byte.class, Double2ByteRBTreeMap::new, TestSampleValues.BYTES_FOR_SORTED)); suite.addTest(getSynchronizedRBTreeMapTests(Byte.class, Double2ByteRBTreeMap::new, m -> Double2ByteSortedMaps.synchronize((Double2ByteSortedMap) m), TestSampleValues.BYTES_FOR_SORTED)); suite.addTest(getUnmodifiableRBTreeMapTests(Byte.class, Double2ByteRBTreeMap::new, m -> Double2ByteSortedMaps.unmodifiable((Double2ByteSortedMap) m), TestSampleValues.BYTES_FOR_SORTED)); // Bugs? // suite.addTest(getSingletonSortedMapTests(Byte.class, Double2ByteSortedMaps::singleton, // TestSampleValues.BYTES_FOR_SORTED)); // suite.addTest(getEmptySortedMapTests(Byte.class, Double2ByteSortedMaps.EMPTY_MAP, // TestSampleValues.BYTES_FOR_SORTED)); return suite; } } private static abstract class DoubleGeneratorBase extends TestContainerGeneratorBase<Double> { DoubleGeneratorBase() { this(TestSampleValues.DOUBLE_SAMPLE_ELEMENTS, Ordering.UNSORTED_OR_INSERTION_ORDER); } DoubleGeneratorBase(SampleElements<Double> sampleElements, Ordering ordering) { super(Double.class, sampleElements, ordering); } } private static junit.framework.Test getGeneralDoubleListTests(String testSuiteName, Function<Collection<Double>, List<Double>> generator, Modifiable modifiable) { final class Generator extends DoubleGeneratorBase implements TestListGenerator<Double> { @Override public List<Double> create(Object... elements) { return generator.apply(arrayToCollection(elements)); } } List<Feature<?>> testSuiteFeatures = new ArrayList<>(3); testSuiteFeatures.add(CollectionSize.ANY); testSuiteFeatures.add(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); switch (modifiable) { case IMMUTABLE: break; case MUTABLE: testSuiteFeatures.add(ListFeature.GENERAL_PURPOSE); break; default: throw new IllegalArgumentException(modifiable.toString()); } return ListTestSuiteBuilder.using(new Generator()).named(testSuiteName) .withFeatures(testSuiteFeatures).createTestSuite(); } private static <V> junit.framework.Test getMapTests(Class<V> clazzV, Supplier<Map<Double, V>> mapFactory, SampleElements<V> valueSampleElements) { String testSuiteName = mapFactory.get().getClass().getSimpleName(); return getGeneralMapTests(clazzV, m -> { Map<Double, V> map = mapFactory.get(); map.putAll(m); return map; } , testSuiteName, valueSampleElements, Modifiable.MUTABLE); } private static <V> junit.framework.Test getSynchronizedArrayMapTests(Class<V> clazzV, Supplier<Map<Double, V>> mapFactory, Function<Map<Double, V>, Map<Double, V>> syncrhonizeWrapper, SampleElements<V> valueSampleElements) { String testSuiteName = mapFactory.get().getClass().getSimpleName(); return getGeneralMapTests(clazzV, m -> { Map<Double, V> map = mapFactory.get(); map.putAll(m); map = syncrhonizeWrapper.apply(map); return map; } , testSuiteName, valueSampleElements, Modifiable.MUTABLE); } private static <V> junit.framework.Test getUnmodifiableArrayMapTests(Class<V> clazzV, Supplier<Map<Double, V>> mapFactory, Function<Map<Double, V>, Map<Double, V>> unmodifiableWrapper, SampleElements<V> valueSampleElements) { String testSuiteName = mapFactory.get().getClass().getSimpleName(); return getGeneralMapTests(clazzV, m -> { Map<Double, V> map = mapFactory.get(); map.putAll(m); map = unmodifiableWrapper.apply(map); return map; } , testSuiteName, valueSampleElements, Modifiable.IMMUTABLE); } private static <V> junit.framework.Test getGeneralMapTests(Class<V> clazzV, Function<Map<Double, V>, Map<Double, V>> mapFactory, String testSuiteName, SampleElements<V> valueSampleElements, Modifiable modifiable) { List<Feature<?>> testSuiteFeatures = new ArrayList<>(5); testSuiteFeatures.add(CollectionSize.ANY); testSuiteFeatures.add(CollectionFeature.SERIALIZABLE); testSuiteFeatures.add(CollectionFeature.NON_STANDARD_TOSTRING); testSuiteFeatures.add(CollectionFeature.REMOVE_OPERATIONS); switch (modifiable) { case IMMUTABLE: break; case MUTABLE: testSuiteFeatures.add(MapFeature.GENERAL_PURPOSE); break; default: throw new IllegalArgumentException(modifiable.toString()); } return MapTestSuiteBuilder .using(new DoubleMapGenerator<V>(clazzV, mapFactory, valueSampleElements)) .named(testSuiteName).withFeatures(testSuiteFeatures).createTestSuite(); } private static <V> junit.framework.Test getSingletonMapTests(Class<V> clazzV, BiFunction<Double, V, Map<Double, V>> singletonMapFactory, SampleElements<V> valueSampleElements) { String testSuiteName = clazzV.getSimpleName() + "SingletonMap"; return MapTestSuiteBuilder.using(new DoubleMapGenerator<V>(clazzV, map -> { Map.Entry<Double, V> entry = Iterables.getOnlyElement(map.entrySet()); return singletonMapFactory.apply(entry.getKey(), entry.getValue()); } , valueSampleElements)).named(testSuiteName).withFeatures(CollectionSize.ONE, CollectionFeature.SERIALIZABLE, CollectionFeature.NON_STANDARD_TOSTRING).createTestSuite(); } private static <V> junit.framework.Test getEmptyMapTests(Class<V> clazzV, Map<Double, V> emptyMap, SampleElements<V> valueSampleElements) { String testSuiteName = clazzV.getSimpleName() + "EmptyMap"; return MapTestSuiteBuilder.using(new DoubleMapGenerator<V>(clazzV, map -> { assertEquals(0, map.size()); return emptyMap; } , valueSampleElements)).named(testSuiteName).withFeatures(CollectionSize.ZERO, CollectionFeature.SERIALIZABLE, CollectionFeature.NON_STANDARD_TOSTRING).createTestSuite(); } private static <V> junit.framework.Test getSortedMapTests(Class<V> clazzV, Supplier<SortedMap<Double, V>> sortedMapFactory, V[] valueSampleElements) { String testSuiteName = sortedMapFactory.get().getClass().getSimpleName(); return getGeneralSortedMapTests(clazzV, m -> { SortedMap<Double, V> map = sortedMapFactory.get(); map.putAll(m); return map; } , testSuiteName, valueSampleElements, Modifiable.MUTABLE); } private static <V> junit.framework.Test getSynchronizedRBTreeMapTests(Class<V> clazzV, Supplier<SortedMap<Double, V>> sortedMapFactory, Function<SortedMap<Double, V>, SortedMap<Double, V>> synchronziedWrapper, V[] valueSampleElements) { String testSuiteName = "Synchronized" + sortedMapFactory.get().getClass().getSimpleName(); return getGeneralSortedMapTests(clazzV, m -> { SortedMap<Double, V> map = sortedMapFactory.get(); map.putAll(m); return synchronziedWrapper.apply(map); } , testSuiteName, valueSampleElements, Modifiable.MUTABLE); } private static <V> junit.framework.Test getUnmodifiableRBTreeMapTests(Class<V> clazzV, Supplier<SortedMap<Double, V>> sortedMapFactory, Function<SortedMap<Double, V>, SortedMap<Double, V>> unmodifiableWrapper, V[] valueSampleElements) { String testSuiteName = "Unmodifiable" + sortedMapFactory.get().getClass().getSimpleName(); return getGeneralSortedMapTests(clazzV, m -> { SortedMap<Double, V> map = sortedMapFactory.get(); map.putAll(m); return unmodifiableWrapper.apply(map); } , testSuiteName, valueSampleElements, Modifiable.IMMUTABLE); } private static <V> junit.framework.Test getGeneralSortedMapTests(Class<V> clazzV, Function<Map<Double, V>, SortedMap<Double, V>> mapFactory, String testSuiteName, V[] valueSampleElements, Modifiable modifiable) { List<Feature<?>> testSuiteFeatures = new ArrayList<>(8); testSuiteFeatures.add(CollectionSize.ANY); testSuiteFeatures.add(CollectionFeature.SERIALIZABLE); testSuiteFeatures.add(CollectionFeature.NON_STANDARD_TOSTRING); testSuiteFeatures.add(CollectionFeature.KNOWN_ORDER); testSuiteFeatures.add(CollectionFeature.SUBSET_VIEW); testSuiteFeatures.add(CollectionFeature.DESCENDING_VIEW); switch (modifiable) { case IMMUTABLE: break; case MUTABLE: testSuiteFeatures.add(MapFeature.GENERAL_PURPOSE); break; default: throw new IllegalArgumentException(modifiable.toString()); } return SortedMapTestSuiteBuilder .using(new DoubleSortedMapGenerator<V>(clazzV, mapFactory, valueSampleElements)) .named(testSuiteName).withFeatures(testSuiteFeatures).createTestSuite(); } @SuppressWarnings("unused") private static <V> junit.framework.Test getSingletonSortedMapTests(Class<V> clazzV, BiFunction<Double, V, SortedMap<Double, V>> singletonSortedMapFactory, V[] valueSampleElements) { String testSuiteName = clazzV.getSimpleName() + "SingletonSortedMap"; return SortedMapTestSuiteBuilder.using(new DoubleSortedMapGenerator<V>(clazzV, map -> { Map.Entry<Double, V> entry = Iterables.getOnlyElement(map.entrySet()); return singletonSortedMapFactory.apply(entry.getKey(), entry.getValue()); } , valueSampleElements)).named(testSuiteName) .withFeatures(CollectionSize.ONE, CollectionFeature.SERIALIZABLE).createTestSuite(); } @SuppressWarnings("unused") private static <V> junit.framework.Test getEmptySortedMapTests(Class<V> clazzV, SortedMap<Double, V> emptyMap, V[] valueSampleElements) { String testSuiteName = clazzV.getSimpleName() + "EmptySortedMap"; return SortedMapTestSuiteBuilder.using(new DoubleSortedMapGenerator<V>(clazzV, map -> { assertEquals(0, map.size()); return emptyMap; } , valueSampleElements)).named(testSuiteName) .withFeatures(CollectionSize.ZERO, CollectionFeature.SERIALIZABLE).createTestSuite(); } private static final class DoubleMapGenerator<V> extends TestMapGeneratorBase<Double, V> { private final Function<Map<Double, V>, Map<Double, V>> mapFactory; protected DoubleMapGenerator(Class<V> clazzV, Function<Map<Double, V>, Map<Double, V>> mapFactory, SampleElements<V> valueSampleElements) { this(clazzV, mapFactory, valueSampleElements, Ordering.UNSORTED_OR_INSERTION_ORDER); } protected DoubleMapGenerator(Class<V> clazzV, Function<Map<Double, V>, Map<Double, V>> mapFactory, SampleElements<V> valueSampleElements, Ordering ordering) { super(Double.class, clazzV, TestSampleValues.DOUBLE_SAMPLE_ELEMENTS, valueSampleElements, ordering); this.mapFactory = mapFactory; } @Override public Map<Double, V> create(Object... elements) { return mapFactory.apply(arrayToMap(elements)); } } private static final class DoubleSortedMapGenerator<V> extends TestSortedMapGeneratorBase<Double, V> { private final Function<Map<Double, V>, SortedMap<Double, V>> mapFactory; protected DoubleSortedMapGenerator(Class<V> clazzV, Function<Map<Double, V>, SortedMap<Double, V>> mapFactory, V[] valueSampleElements) { this(clazzV, mapFactory, valueSampleElements, Ordering.UNSORTED_OR_INSERTION_ORDER); } protected DoubleSortedMapGenerator(Class<V> clazzV, Function<Map<Double, V>, SortedMap<Double, V>> mapFactory, V[] valueSampleElements, Ordering ordering) { super(Double.class, clazzV, TestSampleValues.DOUBLES_FOR_SORTED, valueSampleElements, ordering); this.mapFactory = mapFactory; } @Override public SortedMap<Double, V> create(Object... elements) { return mapFactory.apply(arrayToMap(elements)); } } }
apache-2.0
chat-sdk/chat-sdk-android
chat-sdk-core-ui/src/main/java/sdk/chat/ui/utils/InfiniteToast.java
1075
package sdk.chat.ui.utils; import android.content.Context; import android.widget.Toast; import java.util.concurrent.TimeUnit; import io.reactivex.Observable; import sdk.guru.common.RX; import io.reactivex.disposables.Disposable; /** * Created by ben on 9/28/17. */ public class InfiniteToast { Disposable disposable = null; Toast toast; String text; public InfiniteToast (final Context context,final int resId, boolean flash) { disposable = Observable.interval(0, flash ? 2500 : 2000, TimeUnit.MILLISECONDS).observeOn(RX.main()).subscribe(aLong -> { toast = Toast.makeText(context, resId, Toast.LENGTH_SHORT); if (text != null) { toast.setText(text); } toast.show(); }); } public void cancel () { if(disposable != null) { disposable.dispose(); } } public void setText (String text) { this.text = text; toast.setText(text); } public void hide () { toast.cancel(); cancel(); } }
apache-2.0
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_5410.java
151
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_5410 { }
apache-2.0
jvasileff/ceylon-spec
src/com/redhat/ceylon/compiler/typechecker/analyzer/DefaultTypeArgVisitor.java
1188
package com.redhat.ceylon.compiler.typechecker.analyzer; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.model.typechecker.model.ProducedType; import com.redhat.ceylon.model.typechecker.model.TypeParameter; /** * Detects recursive default type arguments * * @author Gavin King * */ public class DefaultTypeArgVisitor extends Visitor { @Override public void visit(Tree.TypeParameterDeclaration that) { Tree.TypeSpecifier ts = that.getTypeSpecifier(); if (ts!=null) { TypeParameter tpd = that.getDeclarationModel(); ProducedType dta = tpd.getDefaultTypeArgument(); if (dta!=null) { try { if (dta.involvesDeclaration(tpd.getDeclaration())) { tpd.setDefaultTypeArgument(null); } } catch (RuntimeException re) { ts.addError("undecidable default type argument"); tpd.setDefaultTypeArgument(null); } } } super.visit(that); } }
apache-2.0
vic-ita/RAW
RAW/src/raw/dht/implementations/DefaultRoutingTable.java
9548
/******************************************************************************* * Copyright 2017 Vincenzo-Maria Cappelleri <vincenzo.cappelleri@gmail.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 raw.dht.implementations; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Random; import raw.dht.Bucket; import raw.dht.DhtConstants; import raw.dht.DhtID; import raw.dht.DhtNode; import raw.dht.DhtNodeExtended; import raw.dht.KBucket; import raw.dht.RoutingTable; import raw.dht.implementations.exceptions.IncoherentTransactionException; import raw.dht.implementations.exceptions.IncompleteNodeExtendedException; import raw.dht.implementations.utils.DhtNodeAddressBookFile; import raw.dht.implementations.utils.DhtUtils; import raw.logger.Log; /** * Default implementation of {@link RoutingTable}. * * @author vic * */ public class DefaultRoutingTable implements RoutingTable { private DhtNode myNode; private InternalNode routingTreeRoot; private DefaultDhtCore myCore; private Log log; /** * Constructs a new {@link RoutingTable} given the * the {@link DhtNode} identifier of the node owning such * a table. * * @param myNode the {@link DhtNode} of this node * @param owner a {@link DefaultDhtCore} owning this {@link RoutingTable} */ public DefaultRoutingTable(DhtNode myNode, DefaultDhtCore owner) { this.myNode = myNode; routingTreeRoot = new InternalNode(this.myNode.getID()); myCore = owner; log = Log.getLogger(); } /* (non-Javadoc) * @see raw.dht.RoutingTable#findClosest(raw.dht.DhtID) */ @Override public Collection<DhtNodeExtended> findClosest(DhtID searchedID) { log.verboseDebug("Searching for "+searchedID); String id = DhtUtils.convertIdToBinaryString(searchedID); int neededNodes = DhtConstants.ALPHA_SIZE; Collection<DhtNodeExtended> foundNodes = recursivelyGatherNodes(routingTreeRoot, id, neededNodes); log.verboseDebug("Found a list of "+foundNodes.size()+" nodes."); return foundNodes; } private Collection<DhtNodeExtended> recursivelyGatherNodes(Bucket routingTableNode, String id, int neededNodes){ if(routingTableNode instanceof KBucket){ Collection<DhtNodeExtended> returnable = ((KBucket)routingTableNode).getNodes(neededNodes); HashMap<DhtNodeExtended, Boolean> stillValid = myCore.areCorrectlyOld(returnable); returnable = new ArrayList<DhtNodeExtended>(); for(Entry<DhtNodeExtended, Boolean> entry: stillValid.entrySet()){ if(entry.getValue()){ returnable.add(entry.getKey()); } else { removeNode(entry.getKey()); // update the routing table removing now invalid nodes } } // return ((KBucket)routingTableNode).getNodes(neededNodes); return returnable; } if(routingTableNode instanceof MyNode){ List<DhtNodeExtended> list = new ArrayList<DhtNodeExtended>(); // list.add(myNode); DhtNodeExtended updatedMyNode; try { updatedMyNode = myCore.getNodeExtended(); list.add(updatedMyNode); } catch (IncoherentTransactionException | IncompleteNodeExtendedException e) { log.exception(e); } return list; } InternalNode currentNode = (InternalNode) routingTableNode; Bucket primaryNode; Bucket fallbackNode; if(id.charAt(0) == '0'){ primaryNode = currentNode.getZeroChild(); fallbackNode = currentNode.getOneChild(); } else { primaryNode = currentNode.getOneChild(); fallbackNode = currentNode.getZeroChild(); } String remainingId = id.substring(1); HashSet<DhtNodeExtended> nodes = new HashSet<>(recursivelyGatherNodes(primaryNode, remainingId, neededNodes)); if(nodes.size() == neededNodes){ return nodes; } int stillNeeded = neededNodes - nodes.size(); HashSet<DhtNodeExtended> moreNodes = new HashSet<>(recursivelyGatherNodes(fallbackNode, remainingId, stillNeeded)); nodes.addAll(moreNodes); return nodes; } /* (non-Javadoc) * @see raw.dht.RoutingTable#randomNode() */ @Override public DhtNodeExtended randomNode() { Collection<DhtNodeExtended> nodes = getFullSetOfNodes(true); if(nodes == null || nodes.size() == 0){ return null; } int i = (new Random()).nextInt(nodes.size()); return (DhtNodeExtended) nodes.toArray()[i]; } /* (non-Javadoc) * @see raw.dht.RoutingTable#insertNode(raw.dht.DhtNode) */ @Override public boolean insertNode(DhtNodeExtended node) { KBucket bucket = findExactBucket(node); if(bucket == null){ return false; } bucket.insertNode(node); return true; } private KBucket findExactBucket(DhtNode node){ String id = DhtUtils.convertIdToBinaryString(node.getID()); Bucket current = routingTreeRoot; while (current instanceof InternalNode && !(current instanceof MyNode)) { if(id.charAt(0) == '0'){ current = ((InternalNode)current).getZeroChild(); } else { current = ((InternalNode)current).getOneChild(); } id = id.substring(1); } if(current instanceof MyNode){ return null; } return (KBucket) current; } /* (non-Javadoc) * @see raw.dht.RoutingTable#removeNode(raw.dht.DhtNode) */ @Override public boolean removeNode(DhtNodeExtended node) { KBucket bucket = findExactBucket(node); if(bucket == null){ return false; } return bucket.deleteNode(node); } private class InternalNode implements Bucket{ private Bucket zeroChild; private Bucket oneChild; public InternalNode() { // void constructor } public InternalNode(DhtID id) { String myId = DhtUtils.convertIdToBinaryString(id); init(myId); } public InternalNode(String remainingId) { init(remainingId); } private void init(String remainingId){ if(remainingId.length() == 1){ if(remainingId.charAt(0) == '0'){ zeroChild = new MyNode(); oneChild = new DefaultKBucket(); } else { zeroChild = new DefaultKBucket(); oneChild = new MyNode(); } } else { if(remainingId.charAt(0) == '0'){ zeroChild = new InternalNode(remainingId.substring(1)); oneChild = new DefaultKBucket(); } else { zeroChild = new DefaultKBucket(); oneChild = new InternalNode(remainingId.substring(1)); } } } public Bucket getZeroChild() { return zeroChild; } public Bucket getOneChild() { return oneChild; } } private class MyNode extends InternalNode{ } /* (non-Javadoc) * @see raw.dht.RoutingTable#getFullSetOfNodes() */ @Override public Collection<DhtNodeExtended> getFullSetOfNodes(boolean askNewNodes) { log.verboseDebug("Beginning collection of all nodes."); Collection<DhtNodeExtended> nodes = recursiveGetAllNodes(routingTreeRoot); log.verboseDebug("Recursion done. Returning. ("+nodes+")"); if(((nodes == null || nodes.size() < 5) && askNewNodes)){ //FIXME 5 is a rather arbitrary choice... log.verboseDebug("No node retrieved. Getting a new set of nodes."); DhtNodeAddressBookFile addressBook = new DhtNodeAddressBookFile(); Collection<DhtNodeExtended> newNodes = addressBook.retrieveFromNodesInfoServers(); for(DhtNodeExtended node : newNodes){ insertNode(node); } log.verboseDebug("Re-Beginning collection of all nodes."); nodes = recursiveGetAllNodes(routingTreeRoot); log.verboseDebug("Recursion done. Returning. ("+nodes+")"); } return nodes; // return recursiveGetAllNodes(routingTreeRoot); } private Collection<DhtNodeExtended> recursiveGetAllNodes(Bucket tableNode){ if(tableNode instanceof KBucket){ Collection<DhtNodeExtended> allNodes = ((KBucket)tableNode).getAllNodes(); HashMap<DhtNodeExtended, Boolean> stillValid = myCore.areCorrectlyOld(allNodes); allNodes = new ArrayList<DhtNodeExtended>(); for(Entry<DhtNodeExtended, Boolean> entry: stillValid.entrySet()){ if(entry.getValue()){ allNodes.add(entry.getKey()); } else { removeNode(entry.getKey()); // update the routing table removing now invalid nodes } } return ((KBucket)tableNode).getAllNodes(); } if(tableNode instanceof MyNode){ return null; } if(tableNode instanceof InternalNode){ InternalNode thisNode = (InternalNode) tableNode; Collection<DhtNodeExtended> nodes0 = recursiveGetAllNodes(thisNode.getZeroChild()); Collection<DhtNodeExtended> nodes1 = recursiveGetAllNodes(thisNode.getOneChild()); HashSet<DhtNodeExtended> fullSet = new HashSet<>(); if(nodes0 != null && nodes0.size() > 0){ fullSet.addAll(nodes0); } if(nodes1 != null && nodes1.size() > 0){ fullSet.addAll(nodes1); } if(fullSet.size() > 0){ return fullSet; } } return null; } /* (non-Javadoc) * @see raw.dht.RoutingTable#isPresentInTable(raw.dht.DhtNode) */ @Override public boolean isPresentInTable(DhtNodeExtended node) { KBucket bucket = findExactBucket(node); if(bucket == null){ return true; } return bucket.contains(node); } }
apache-2.0
hnccfr/ccfrweb
basecore/src/com/hundsun/network/gates/wulin/biz/domain/query/AuctionMulitBidProjectQuery.java
3329
/* */ package com.hundsun.network.gates.wulin.biz.domain.query; /* */ /* */ import com.hundsun.network.gates.luosi.common.enums.EnumActiveStatus; /* */ import com.hundsun.network.gates.luosi.common.enums.EnumMulitBidOrderProperty; /* */ import com.hundsun.network.gates.luosi.common.enums.EnumProjectStatus; /* */ import com.hundsun.network.gates.luosi.common.enums.EnumTradingType; /* */ import com.hundsun.network.gates.luosi.common.page.Pagination; /* */ import com.hundsun.network.gates.wulin.biz.domain.auction.AuctionMulitBidProject; /* */ import java.util.List; /* */ /* */ public class AuctionMulitBidProjectQuery extends Pagination<AuctionMulitBidProject> /* */ { /* */ private static final long serialVersionUID = -5341124239492296289L; /* */ private String projectCode; /* */ private String reviewer; /* */ private EnumMulitBidOrderProperty reviewerKey; /* */ private EnumMulitBidOrderProperty bidStartTimeKey; /* */ private EnumTradingType tradingType; /* */ private List<EnumProjectStatus> projectStatus; /* */ private EnumActiveStatus reviewed; /* */ /* */ public String getProjectCode() /* */ { /* 53 */ return this.projectCode; /* */ } /* */ /* */ public void setProjectCode(String projectCode) { /* 57 */ this.projectCode = projectCode; /* */ } /* */ /* */ public String getReviewer() { /* 61 */ return this.reviewer; /* */ } /* */ /* */ public void setReviewer(String reviewer) { /* 65 */ this.reviewer = reviewer; /* */ } /* */ /* */ public EnumMulitBidOrderProperty getReviewerKey() { /* 69 */ return this.reviewerKey; /* */ } /* */ /* */ public void setReviewerKey(EnumMulitBidOrderProperty reviewerKey) { /* 73 */ this.reviewerKey = reviewerKey; /* */ } /* */ /* */ public EnumTradingType getTradingType() { /* 77 */ return this.tradingType; /* */ } /* */ /* */ public void setTradingType(EnumTradingType tradingType) { /* 81 */ this.tradingType = tradingType; /* */ } /* */ /* */ public EnumMulitBidOrderProperty getBidStartTimeKey() { /* 85 */ return this.bidStartTimeKey; /* */ } /* */ /* */ public void setBidStartTimeKey(EnumMulitBidOrderProperty bidStartTimeKey) { /* 89 */ this.bidStartTimeKey = bidStartTimeKey; /* */ } /* */ /* */ public List<EnumProjectStatus> getProjectStatus() { /* 93 */ return this.projectStatus; /* */ } /* */ /* */ public void setProjectStatus(List<EnumProjectStatus> projectStatus) { /* 97 */ this.projectStatus = projectStatus; /* */ } /* */ /* */ public EnumActiveStatus getReviewed() { /* 101 */ return this.reviewed; /* */ } /* */ /* */ public void setReviewed(EnumActiveStatus reviewed) { /* 105 */ this.reviewed = reviewed; /* */ } /* */ } /* Location: E:\__安装归档\linquan-20161112\deploy16\wulin\webroot\WEB-INF\classes\ * Qualified Name: com.hundsun.network.gates.wulin.biz.domain.query.AuctionMulitBidProjectQuery * JD-Core Version: 0.6.0 */
apache-2.0
ufoscout/java-sample-projects
jetty9-embedded-spring4noxml/src/main/java/ufo/jetty9/config/web/SpringDispatcherConfig.java
655
/* * 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 ufo.jetty9.config.web; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * * @author ufo */ @Configuration @EnableWebMvc public class SpringDispatcherConfig extends WebMvcConfigurerAdapter { public SpringDispatcherConfig() { System.out.println("SpringDispatcherConfig Started"); } }
apache-2.0
ibissource/iaf
cmis/src/test/java/nl/nn/adapterframework/extensions/cmis/CmisHttpInvokerTest.java
4143
package nl.nn.adapterframework.extensions.cmis; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.io.IOException; import java.io.OutputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.chemistry.opencmis.client.bindings.spi.BindingSession; import org.apache.chemistry.opencmis.client.bindings.spi.http.Output; import org.apache.chemistry.opencmis.client.bindings.spi.http.Response; import org.apache.chemistry.opencmis.commons.SessionParameter; import org.apache.chemistry.opencmis.commons.impl.UrlBuilder; import org.apache.http.HttpHost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.protocol.HttpContext; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import nl.nn.adapterframework.http.HttpResponseMock; import nl.nn.adapterframework.testutil.TestAssertions; import nl.nn.adapterframework.testutil.TestFileUtils; import nl.nn.credentialprovider.util.Misc; public class CmisHttpInvokerTest extends Mockito { @Mock private BindingSession session; @Before public void setup() { MockitoAnnotations.initMocks(this); when(session.get(eq(SessionParameter.USER_AGENT), anyString())).thenReturn("Mockito mock-agent"); } private CmisHttpInvoker createInvoker() { return new CmisHttpInvoker() { @Override protected CmisHttpSender createSender() { try { CmisHttpSender sender = spy(super.createSender()); CloseableHttpClient httpClient = mock(CloseableHttpClient.class); //Mock all requests when(httpClient.execute(any(HttpHost.class), any(HttpRequestBase.class), any(HttpContext.class))).thenAnswer(new HttpResponseMock()); when(sender.getHttpClient()).thenReturn(httpClient); return sender; } catch (Throwable t) { t.printStackTrace(); fail(t.getMessage()); throw new IllegalStateException(t); } } }; } private Output createOutputFromFile(String file) throws IOException { URL url = TestFileUtils.getTestFileURL(file); assertNotNull("unable to find test file", url); return new Output() { @Override public void write(OutputStream out) throws Exception { Misc.streamToStream(url.openStream(), out); } }; } private void assertResponse(String string, Response response) throws IOException { String result = Misc.streamToString(response.getStream()); String expected = TestFileUtils.getTestFile(string); assertNotNull("cannot find test file", expected); TestAssertions.assertEqualsIgnoreCRLF(expected, result); } @Test public void testGet() throws Exception { CmisHttpInvoker invoker = createInvoker(); UrlBuilder url = new UrlBuilder("https://dummy.url.com"); Response response = invoker.invokeGET(url, session); assertResponse("/HttpInvokerResponse/simpleGet.txt", response); } @Test public void testPost() throws Exception { CmisHttpInvoker invoker = createInvoker(); UrlBuilder url = new UrlBuilder("https://dummy.url.com"); Output writer = createOutputFromFile("/HttpInvokerRequest/postMessage.txt"); Response response = invoker.invokePOST(url, "text/plain", writer, session); assertResponse("/HttpInvokerResponse/simplePost.txt", response); } @Test public void testPut() throws Exception { CmisHttpInvoker invoker = createInvoker(); UrlBuilder url = new UrlBuilder("https://dummy.url.com"); Output writer = createOutputFromFile("/HttpInvokerRequest/putMessage.txt"); Map<String, String> headers = new HashMap<>(); headers.put("test-header", "test-value"); Response response = invoker.invokePUT(url, "text/plain", headers, writer, session); assertResponse("/HttpInvokerResponse/simplePut.txt", response); } @Test public void testDelete() throws Exception { CmisHttpInvoker invoker = createInvoker(); UrlBuilder url = new UrlBuilder("https://dummy.url.com"); Response response = invoker.invokeDELETE(url, session); assertResponse("/HttpInvokerResponse/simpleDelete.txt", response); } }
apache-2.0
ExplorViz/ExplorViz
src/explorviz/shared/usertracking/records/application/ComponentOpenRecord.java
275
package explorviz.shared.usertracking.records.application; import explorviz.shared.model.Component; public class ComponentOpenRecord extends ComponentRecord { protected ComponentOpenRecord() { } public ComponentOpenRecord(final Component compo) { super(compo); } }
apache-2.0
manyurij/java_study
gge-tests/src/test/java/ru/stqa/pft/gge/appmanager/GeneratorHelperUGD.java
3984
package ru.stqa.pft.gge.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import ru.stqa.pft.gge.model.GeneratorData; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * Created by manuhin on 21.04.2016. */ public class GeneratorHelperUGD extends HelperBase { public GeneratorHelperUGD(WebDriver wd, Properties properties) { super(wd); this.properties = properties; //wd.manage().window().maximize(); } private Properties properties; public List<GeneratorData> GenParamUGD(int i, boolean isProdServer, String loginUser, String baseUrl, String listVitrinasUrl) throws InterruptedException { List<WebElement> mainMenu; List<WebElement> vitrinas; List <GeneratorData> listRazd = new ArrayList<>(); String xpathRazdelStart = "(//*[@id='PortalTree']/li)"; String xpathRazdelEnd = ""; String xpathMenuStart = "(//*[@id='PortalTree']/li"; String xpathMenuIn = "/ul/li/a)"; String xpathMenuEnd = ""; String xpathSubmenuStart = "(//*[@id='PortalTree']/li"; String xpathSubmenuIn1 = "/ul/li"; String xpathSubmenuIn2 = "/a/../ul/li/a)"; String xpathSubmenuEnd = ""; //Раздел for (int r = 1; r <= i; r++){ waitLoadPage(isProdServer); String xpath1 = xpathRazdelStart + "["+ r +"]" + xpathRazdelEnd; String nameRazd = wd.findElement(By.xpath(xpath1)).getText(); int nameRazdNum = nameRazd.indexOf("\n"); if (nameRazdNum == -1) { continue; } nameRazd = nameRazd.substring(0, nameRazdNum); String xpathMenu = xpathMenuStart + "["+ r +"]" + xpathMenuIn + xpathMenuEnd; mainMenu = wd.findElements(By.xpath(xpathMenu)); int amountMenu = mainMenu.size(); //Меню for(int m = 1; m <= amountMenu; m++) { waitLoadPage(isProdServer); String xpath2 = xpathMenuStart + "[" + r + "]" + xpathMenuIn + "["+ m +"]" + xpathMenuEnd; String nameMenu = wd.findElement(By.xpath(xpath2)).getText(); String menuID = wd.findElement(By.xpath(xpath2)).getAttribute("id"); String xpathVitrinas = xpathSubmenuStart + "[" + r + "]" + xpathSubmenuIn1 + "["+ m +"]" + xpathSubmenuIn2 + xpathSubmenuEnd; vitrinas = wd.findElements(By.xpath(xpathVitrinas)); //Витрина int amountSubMenu = vitrinas.size(); if (amountSubMenu == 0) { GeneratorData generatorData = new GeneratorData() .withRazdelName(nameRazd).withRazdelXpath(xpath1) .withMenuName(nameMenu).withMenuXpath(xpath2) .withVitrinaName(nameMenu).withVitrinaXpath(xpath2) .withVitrinaID(menuID) .withLoginUser(loginUser).withBaseUrl(baseUrl) .withListVitrinasUrl(listVitrinasUrl); listRazd.add(generatorData); } else { for(int s = 1; s <= amountSubMenu; s++){ String xpath3 = xpathSubmenuStart + "[" + r + "]" + xpathSubmenuIn1 + "["+ m +"]" + xpathSubmenuIn2 + "[" + s + "]" + xpathSubmenuEnd; String nameSub = wd.findElement(By.xpath(xpath3)).getText(); String vitrinaID = wd.findElement(By.xpath(xpath3)).getAttribute("id"); GeneratorData generatorData = new GeneratorData() .withRazdelName(nameRazd).withRazdelXpath(xpath1) .withMenuName(nameMenu).withMenuXpath(xpath2) .withVitrinaName(nameSub).withVitrinaXpath(xpath3) .withVitrinaID(vitrinaID) .withLoginUser(loginUser).withBaseUrl(baseUrl) .withListVitrinasUrl(listVitrinasUrl); listRazd.add(generatorData); } } } } return listRazd; } }
apache-2.0
inbloom/csv2xml
src/org/slc/sli/sample/entities/InterchangeMasterSchedule.java
3824
/* * Copyright 2012 Shared Learning Collaborative, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.04.20 at 03:09:04 PM EDT // package org.slc.sli.sample.entities; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice maxOccurs="unbounded"> * &lt;element name="CourseOffering" type="{http://ed-fi.org/0100}CourseOffering"/> * &lt;element name="Section" type="{http://ed-fi.org/0100}Section"/> * &lt;element name="BellSchedule" type="{http://ed-fi.org/0100}BellSchedule"/> * &lt;element name="MeetingTime" type="{http://ed-fi.org/0100}MeetingTime"/> * &lt;/choice> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "courseOfferingOrSectionOrBellSchedule" }) @XmlRootElement(name = "InterchangeMasterSchedule") public class InterchangeMasterSchedule { @XmlElements({ @XmlElement(name = "MeetingTime", type = MeetingTime.class), @XmlElement(name = "Section", type = Section.class), @XmlElement(name = "BellSchedule", type = BellSchedule.class), @XmlElement(name = "CourseOffering", type = CourseOffering.class) }) protected List<ComplexObjectType> courseOfferingOrSectionOrBellSchedule; /** * Gets the value of the courseOfferingOrSectionOrBellSchedule property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the courseOfferingOrSectionOrBellSchedule property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCourseOfferingOrSectionOrBellSchedule().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MeetingTime } * {@link Section } * {@link BellSchedule } * {@link CourseOffering } * * */ public List<ComplexObjectType> getCourseOfferingOrSectionOrBellSchedule() { if (courseOfferingOrSectionOrBellSchedule == null) { courseOfferingOrSectionOrBellSchedule = new ArrayList<ComplexObjectType>(); } return this.courseOfferingOrSectionOrBellSchedule; } }
apache-2.0
zarub2k/cloudroid
app/src/main/java/com/cloudskol/cloudroid/spotify/SpotifyAsyncTask.java
926
package com.cloudskol.cloudroid.spotify; import android.os.AsyncTask; import android.util.Log; import com.cloudskol.cloudroid.common.CloudroidException; /** * @author tham */ public class SpotifyAsyncTask extends AsyncTask<String, Void, String> { private final String LOG_TAG = SpotifyAsyncTask.class.getSimpleName(); @Override protected String doInBackground(String... params) { if (params.length <= 0) { return null; } String moviesJsonString = null; String path = params[0]; final SpotifyUrlConnector spotifyUrlConnector = new SpotifyUrlConnector(); try { moviesJsonString = spotifyUrlConnector.getJson(path); } catch (CloudroidException e) { Log.e(LOG_TAG, "Error while fetching JSON", e); return null; } Log.v(LOG_TAG, moviesJsonString); return moviesJsonString; } }
apache-2.0
apixandru/JVShot
jvshot-tray/src/main/java/com/apixandru/jvshot/tray/CloseDialogListener.java
1080
package com.apixandru.jvshot.tray; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import java.awt.Dialog; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; /** * @author Alexandru-Constantin Bledea * @since Sep 11, 2016 */ final class CloseDialogListener implements PopupMenuListener, WindowFocusListener { private final Dialog dialog; public CloseDialogListener(Dialog dialog) { this.dialog = dialog; } @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { closeDialog(); } @Override public void popupMenuCanceled(PopupMenuEvent e) { closeDialog(); } @Override public void windowGainedFocus(WindowEvent e) { } @Override public void windowLostFocus(WindowEvent e) { closeDialog(); } private void closeDialog() { if (dialog.isVisible()) { dialog.setVisible(false); } } }
apache-2.0
Carbonado/CarbonadoDirmi
src/main/java/com/amazon/carbonado/repo/dirmi/ProcedureRequest.java
9400
/* * Copyright 2010-2012 Amazon Technologies, Inc. or its affiliates. * Amazon, Amazon.com and Carbonado are trademarks or registered trademarks * of Amazon Technologies, 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. * 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.amazon.carbonado.repo.dirmi; import java.io.IOException; import java.util.Collection; import org.cojen.dirmi.Pipe; import com.amazon.carbonado.RepositoryException; import com.amazon.carbonado.Storable; import com.amazon.carbonado.Storage; import com.amazon.carbonado.capability.RemoteProcedure; /** * * * @author Brian S O'Neill */ class ProcedureRequest<R, D> implements RemoteProcedure.Request<R, D>, ProcedureOpCodes { private static final int RECEIVING = 0, READY_TO_SEND = 1, SENDING = 2, CLOSED = 3; private final RemoteProcedureExecutorServer mProcedureExecutor; private final Pipe mPipe; private final RemoteTransaction mTxn; private int mState; private Storage mCurrentStorage; ProcedureRequest(RemoteProcedureExecutorServer executor, Pipe pipe, RemoteTransaction txn) { mProcedureExecutor = executor; mPipe = pipe; mTxn = txn; } @Override public synchronized D receive() throws RepositoryException { if (mState != RECEIVING) { return null; } return receive0(); } @Override public synchronized int receiveInto(Collection<? super D> c) throws RepositoryException { if (c == null) { throw new IllegalArgumentException("Collection cannot be null"); } int amount = 0; if (mState == RECEIVING) { D data; while ((data = receive0()) != null) { c.add(data); amount++; } } return amount; } private D receive0() throws RepositoryException { try { byte op = mPipe.readByte(); switch (op) { case OP_TERMINATOR: mState = READY_TO_SEND; return null; case OP_SERIALIZABLE: try { return (D) mPipe.readObject(); } catch (Throwable e) { throw cleanup(e); } case OP_THROWABLE: throw cleanup(mPipe.readThrowable()); case OP_STORABLE_NEW_TYPE: try { Class type = (Class) mPipe.readObject(); mCurrentStorage = mProcedureExecutor.mRepositoryServer.mRepository.storageFor(type); } catch (Throwable e) { throw cleanup(e); } // Fall through to next case... case OP_STORABLE_EXISTING_TYPE: try { Storable s = mCurrentStorage.prepare(); s.readFrom(mPipe.getInputStream()); return (D) s; } catch (Throwable e) { throw cleanup(e); } default: throw cleanup(new RepositoryException("Procedure call protocol error: " + op)); } } catch (IOException e) { throw quickCleanup(e); } } @Override public synchronized RemoteProcedure.Reply<R> beginReply() throws IllegalStateException, RepositoryException { replyCheck(false, false, false); return new ProcedureReply<R>(mProcedureExecutor, this, mPipe); } @Override public synchronized void finish() throws IllegalStateException, RepositoryException { replyCheck(true, false, false); close(); } private void replyCheck(boolean forFinish, boolean forSilent, boolean pendingException) throws IllegalStateException, RepositoryException { if (mState != READY_TO_SEND) { if (mState == CLOSED) { if (forFinish) { return; } throw new IllegalStateException("Request is finished"); } if (mState == RECEIVING) { // Try to read terminator. receive0(); if (mState == RECEIVING) { // Send exception to client, but all remaining data must be drained. while (receive0() != null) {} if (!pendingException) { IllegalStateException ex = new IllegalStateException ("Procedure cannot reply or finish until all data has been received"); try { mPipe.writeByte(OP_THROWABLE); mPipe.writeThrowable(ex); } catch (IOException e) { // Ignore. } finally { silentClose(); } // Also throw to server, so it knows that something is broken. throw ex; } } } if (mState == SENDING) { if (forSilent) { return; } throw new IllegalStateException("Reply already begun"); } } mState = SENDING; if (mTxn != null) { // If this point is reached, then any transaction was successfully // attached and no exception was thrown. try { mPipe.writeByte(OP_START); // Flush to unblock caller which is waiting for attach // confirmation. mPipe.flush(); } catch (IOException e) { throw quickCleanup(e); } } } @Override public String toString() { return "RemoteProcedure.Request {pipe=" + mPipe + '}'; } synchronized void silentFinish() throws IllegalStateException { try { replyCheck(true, true, false); close(); } catch (RepositoryException e) { // Ignore. } } /** * @throws original cause if it cannot be written back */ synchronized void silentFinish(Throwable cause) throws IllegalStateException, Throwable { try { replyCheck(true, true, true); } catch (RepositoryException e) { // Ignore. } try { mPipe.writeByte(ProcedureOpCodes.OP_THROWABLE); mPipe.writeThrowable(cause); } catch (IOException e2) { // Pipe might still be in a reading state. throw cause; } finally { try { close(); } catch (RepositoryException e) { // Ignore. } } } synchronized void close() throws RepositoryException { if (mState != CLOSED) { mState = CLOSED; if (mTxn != null) { // Detach before writing terminator to avoid race condition // with client. It might otherwise proceed and then try to // remotely attach the transaction to a different thread. ((RemoteTransactionServer) mTxn).detach(); } try { try { mPipe.writeByte(OP_TERMINATOR); } catch (IOException e) { // Pipe might still be in a reading state. } mPipe.close(); } catch (IOException e) { throw new RepositoryException(e); } } } private synchronized void silentClose() { if (mState != CLOSED) { mState = CLOSED; if (mTxn != null) { ((RemoteTransactionServer) mTxn).detach(); } try { mPipe.close(); } catch (IOException e) { // Ignore. } } } private synchronized RepositoryException cleanup(Throwable cause) throws RepositoryException { silentClose(); throw ClientStorage.toRepositoryException(cause); } private synchronized RepositoryException quickCleanup(IOException cause) throws RepositoryException { if (mState != CLOSED) { mState = CLOSED; if (mTxn != null) { ((RemoteTransactionServer) mTxn).detach(); } } throw new RepositoryException(cause); } }
apache-2.0
adaptris/interlok
interlok-core/src/main/java/com/adaptris/core/http/oauth/AccessTokenBuilder.java
462
package com.adaptris.core.http.oauth; import java.io.IOException; import com.adaptris.core.AdaptrisMessage; import com.adaptris.core.ComponentLifecycle; import com.adaptris.core.CoreException; @FunctionalInterface public interface AccessTokenBuilder extends ComponentLifecycle { /** * Build the access token. * * @param msg the msg * @return the access token. */ AccessToken build(AdaptrisMessage msg) throws IOException, CoreException; }
apache-2.0
suninformation/ymate-platform-v2
ymate-platform-core/src/main/java/net/ymate/platform/core/persistence/AbstractFunction.java
4989
/* * Copyright 2007-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 * * 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.ymate.platform.core.persistence; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.lang3.StringUtils; /** * @author 刘镇 (suninformation@163.com) on 17/6/22 上午10:50 */ public abstract class AbstractFunction implements IFunction { private final Fields fields; private final Params params = Params.create(); private boolean flag; public AbstractFunction() { fields = Fields.create(); onBuild(); } public AbstractFunction(String funcName) { if (StringUtils.isBlank(funcName)) { throw new NullArgumentException("funcName"); } fields = Fields.create(funcName, "("); flag = true; // onBuild(); } /** * 处理函数构建过程 */ public abstract void onBuild(); public AbstractFunction field(Number param) { fields.add(param.toString()); return this; } public AbstractFunction field(Number[] params) { if (params != null && params.length > 0) { boolean has = false; for (Number param : params) { if (param != null) { if (has) { separator(); } this.fields.add(param.toString()); has = true; } } } return this; } public AbstractFunction operate(String opt, String param) { return space().field(opt).space().field(param); } public AbstractFunction separator() { fields.add(", "); return this; } public AbstractFunction space() { fields.add(StringUtils.SPACE); return this; } public AbstractFunction bracketBegin() { fields.add("("); return this; } public AbstractFunction bracketEnd() { fields.add(")"); return this; } public AbstractFunction quotes() { fields.add("'"); return this; } public AbstractFunction field(IFunction function) { fields.add(function); params.add(function.params()); return this; } public AbstractFunction field(IFunction function, String alias) { fields.add(function, alias); params.add(function.params()); return this; } public AbstractFunction fieldWS(Object... fields) { if (fields != null && fields.length > 0) { boolean has = false; for (Object field : fields) { if (field != null) { if (has) { separator(); } if (field instanceof IFunction) { this.fields.add(((IFunction) field)); this.params.add(((IFunction) field).params()); } else { this.fields.add(field.toString()); } has = true; } } } return this; } public AbstractFunction field(String param) { fields.add(param); return this; } public AbstractFunction field(String[] params) { if (params != null && params.length > 0) { boolean has = false; for (String param : params) { if (param != null) { if (has) { separator(); } this.fields.add(param); has = true; } } } return this; } public AbstractFunction field(String prefix, String field) { fields.add(prefix, field); return this; } public Fields fields() { return fields; } @Override public String build() { if (flag) { fields.add(")"); } return StringUtils.join(fields.toArray(), StringUtils.EMPTY); } @Override public Params params() { return params; } @Override public IFunction param(Object param) { params.add(param); return this; } @Override public IFunction param(Params params) { this.params.add(params); return this; } @Override public String toString() { return build(); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-cognitosync/src/main/java/com/amazonaws/services/cognitosync/model/PushSync.java
7356
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cognitosync.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Configuration options to be applied to the identity pool. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/PushSync" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PushSync implements Serializable, Cloneable, StructuredPojo { /** * <p> * List of SNS platform application ARNs that could be used by clients. * </p> */ private com.amazonaws.internal.SdkInternalList<String> applicationArns; /** * <p> * A role configured to allow Cognito to call SNS on behalf of the developer. * </p> */ private String roleArn; /** * <p> * List of SNS platform application ARNs that could be used by clients. * </p> * * @return List of SNS platform application ARNs that could be used by clients. */ public java.util.List<String> getApplicationArns() { if (applicationArns == null) { applicationArns = new com.amazonaws.internal.SdkInternalList<String>(); } return applicationArns; } /** * <p> * List of SNS platform application ARNs that could be used by clients. * </p> * * @param applicationArns * List of SNS platform application ARNs that could be used by clients. */ public void setApplicationArns(java.util.Collection<String> applicationArns) { if (applicationArns == null) { this.applicationArns = null; return; } this.applicationArns = new com.amazonaws.internal.SdkInternalList<String>(applicationArns); } /** * <p> * List of SNS platform application ARNs that could be used by clients. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setApplicationArns(java.util.Collection)} or {@link #withApplicationArns(java.util.Collection)} if you * want to override the existing values. * </p> * * @param applicationArns * List of SNS platform application ARNs that could be used by clients. * @return Returns a reference to this object so that method calls can be chained together. */ public PushSync withApplicationArns(String... applicationArns) { if (this.applicationArns == null) { setApplicationArns(new com.amazonaws.internal.SdkInternalList<String>(applicationArns.length)); } for (String ele : applicationArns) { this.applicationArns.add(ele); } return this; } /** * <p> * List of SNS platform application ARNs that could be used by clients. * </p> * * @param applicationArns * List of SNS platform application ARNs that could be used by clients. * @return Returns a reference to this object so that method calls can be chained together. */ public PushSync withApplicationArns(java.util.Collection<String> applicationArns) { setApplicationArns(applicationArns); return this; } /** * <p> * A role configured to allow Cognito to call SNS on behalf of the developer. * </p> * * @param roleArn * A role configured to allow Cognito to call SNS on behalf of the developer. */ public void setRoleArn(String roleArn) { this.roleArn = roleArn; } /** * <p> * A role configured to allow Cognito to call SNS on behalf of the developer. * </p> * * @return A role configured to allow Cognito to call SNS on behalf of the developer. */ public String getRoleArn() { return this.roleArn; } /** * <p> * A role configured to allow Cognito to call SNS on behalf of the developer. * </p> * * @param roleArn * A role configured to allow Cognito to call SNS on behalf of the developer. * @return Returns a reference to this object so that method calls can be chained together. */ public PushSync withRoleArn(String roleArn) { setRoleArn(roleArn); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getApplicationArns() != null) sb.append("ApplicationArns: ").append(getApplicationArns()).append(","); if (getRoleArn() != null) sb.append("RoleArn: ").append(getRoleArn()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PushSync == false) return false; PushSync other = (PushSync) obj; if (other.getApplicationArns() == null ^ this.getApplicationArns() == null) return false; if (other.getApplicationArns() != null && other.getApplicationArns().equals(this.getApplicationArns()) == 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 int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getApplicationArns() == null) ? 0 : getApplicationArns().hashCode()); hashCode = prime * hashCode + ((getRoleArn() == null) ? 0 : getRoleArn().hashCode()); return hashCode; } @Override public PushSync clone() { try { return (PushSync) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.cognitosync.model.transform.PushSyncMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
jydimir/Music-Player
app/src/main/java/ua/edu/cdu/fotius/lisun/musicplayer/listeners/OnAddToNewPlaylistClick.java
454
package ua.edu.cdu.fotius.lisun.musicplayer.listeners; import android.os.AsyncTask; import android.view.View; import ua.edu.cdu.fotius.lisun.musicplayer.async_tasks.AsyncTaskWithProgressBar; public class OnAddToNewPlaylistClick implements View.OnClickListener{ private AsyncTask mAsyncTask; public OnAddToNewPlaylistClick(AsyncTask asyncTask) { mAsyncTask = asyncTask; } @Override public void onClick(View v) { } }
apache-2.0
YakushevVladimir/BibleQuote-for-Android
bible/src/test/java/com/BibleQuote/domain/entity/BibleReferenceTest.java
1635
/* * Copyright (C) 2011 Scripture Software * * 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. * * Project: BibleQuote-for-Android * File: BibleReferenceTest.java * * Created by Vladimir Yakushev at 10/2017 * E-mail: ru.phoenix@gmail.com * WWW: http://www.scripturesoftware.org */ package com.BibleQuote.domain.entity; import android.net.Uri; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class BibleReferenceTest { @Test public void testParseLinkFromIntent() throws Exception { Uri link = Uri.parse("http://b-bq.eu/Exod/16_2-3/RST_Strong)"); BibleReference ref = new BibleReference(link); Assert.assertTrue(ref.getPath() != null); } }
apache-2.0
niuchangqing/soso-web
src/main/java/me/money/type/okhttp/JsonModel.java
538
package me.money.type.okhttp; import java.util.Map; import com.google.gson.internal.LinkedTreeMap; public class JsonModel { /** * 框架返回码 */ private int retcode; /** * 数据体 */ private Map<String, Object> result; public int getRetcode() { return retcode; } public void setRetcode(int retcode) { this.retcode = retcode; } public Map<String, Object> getResult() { return result; } public void setResult(Map<String, Object> result) { this.result = result; } }
apache-2.0
pfirmstone/Jini-Print-API
JiniPrint/src/main/java/net/jini/print/attribute/standard/MediaSourceFeedOrientation.java
1447
/* * Copyright 2017 peter. * * 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.jini.print.attribute.standard; import javax.print.attribute.Attribute; import javax.print.attribute.standard.OrientationRequested; import net.jini.print.attribute.CollectionSyntax; /** * * @author peter */ public class MediaSourceFeedOrientation extends CollectionSyntax implements Attribute { private final OrientationRequested orientation; public MediaSourceFeedOrientation(OrientationRequested orientation ){ this.orientation = orientation; } @Override protected Attribute[] getAttributes() { return new Attribute[]{orientation}; } @Override public Class<? extends Attribute> getCategory() { return MediaSourceFeedOrientation.class; } @Override public String getName() { return "media-source-feed-orientation"; } }
apache-2.0
roman-sd/java-a-to-z
chapter_002/src/main/java/ru/sdroman/start/Tracker.java
3753
package ru.sdroman.start; import ru.sdroman.models.Comment; import ru.sdroman.models.Item; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Class Tracker implements storage of items. */ public class Tracker { /** * random for generate id. */ private static final Random RN = new Random(); /** * ArrayList used for items. */ private List<Item> items = new ArrayList<>(); /** * add new item into the array items. * * @param item Item, item to add. * @return new item. */ public Item add(Item item) { item.setTimeCreation(new SimpleDateFormat("dd/MM/yyyy HH:mm")); item.setId(generateId()); this.items.add(item); return item; } /** * edit item into the array items. * * @param id String * @param item Item, item to edit. * @throws ItemNotFoundException Exception */ public void edit(String id, Item item) { boolean isEdit = false; for (Item current : this.items) { if (id.equals(current.getId())) { current.setName(item.getName()); current.setDescription(item.getDescription()); //current.setId(item.getId()); current.addComments(item.getComments()); isEdit = true; } } if (!isEdit) { throw new ItemNotFoundException("Item not found."); } } /** * generate new Id. * * @return String id. */ private String generateId() { return String.valueOf(System.currentTimeMillis() + RN.nextInt()); } /** * remove item into the array items. * * @param item Item, item to remove. * @throws ItemNotFoundException Exception */ public void remove(Item item) { if (!this.items.remove(item)) { throw new ItemNotFoundException("Item not found."); } } /** * find item by name in array items. * * @param name String * @return Item * @throws ItemNotFoundException Exception */ public Item findByName(String name) throws ItemNotFoundException { Item result = null; for (Item item : this.items) { if (item != null && item.getName().equals(name)) { result = item; } } if (result != null) { return result; } else { throw new ItemNotFoundException("Item not found."); } } /** * find item by id in array items. * * @param id int * @return Item * @throws ItemNotFoundException Exception */ public Item findById(String id) throws ItemNotFoundException { Item result = null; for (Item item : this.items) { if (item != null && item.getId().equals(id)) { result = item; } } if (result != null) { return result; } else { throw new ItemNotFoundException("Item not found."); } } /** * get array items. * * @return array. */ public List<Item> getAll() { return this.items; } /** * add comment to item. * * @param comment Comment * @param id String * @return item * @throws ItemNotFoundException Exception */ public Item addComment(Comment comment, String id) { try { Item item = findById(id); item.addComment(comment); return item; } catch (ItemNotFoundException inf) { throw new ItemNotFoundException("Item not found."); } } }
apache-2.0
mhhuang/hadoop-2.6.0
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationInputValidator.java
12067
/** * 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.reservation; import java.util.List; import org.apache.hadoop.yarn.api.protocolrecords.ReservationDeleteRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationSubmissionRequest; import org.apache.hadoop.yarn.api.protocolrecords.ReservationUpdateRequest; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.ReservationRequest; import org.apache.hadoop.yarn.api.records.ReservationRequestInterpreter; import org.apache.hadoop.yarn.api.records.ReservationRequests; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.ipc.RPCUtil; import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger; import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger.AuditConstants; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Queue; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.resource.Resources; public class ReservationInputValidator { private final Clock clock; /** * Utility class to validate reservation requests. */ public ReservationInputValidator(Clock clock) { this.clock = clock; } private Plan validateReservation(ReservationSystem reservationSystem, ReservationId reservationId, String auditConstant) throws YarnException { String message = ""; // check if the reservation id is valid if (reservationId == null) { message = "Missing reservation id." + " Please try again by specifying a reservation id."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } String queueName = reservationSystem.getQueueForReservation(reservationId); if (queueName == null) { message = "The specified reservation with ID: " + reservationId + " is unknown. Please try again with a valid reservation."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } // check if the associated plan is valid Plan plan = reservationSystem.getPlan(queueName); if (plan == null) { message = "The specified reservation: " + reservationId + " is not associated with any valid plan." + " Please try again with a valid reservation."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } return plan; } private void validateReservationDefinition(ReservationId reservationId, ReservationDefinition contract, Plan plan, String auditConstant) throws YarnException { String message = ""; // check if deadline is in the past if (contract == null) { message = "Missing reservation definition." + " Please try again by specifying a reservation definition."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } if (contract.getDeadline() <= clock.getTime()) { message = "The specified deadline: " + contract.getDeadline() + " is the past. Please try again with deadline in the future."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } // Check if at least one RR has been specified ReservationRequests resReqs = contract.getReservationRequests(); if (resReqs == null) { message = "No resources have been specified to reserve." + "Please try again by specifying the resources to reserve."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } List<ReservationRequest> resReq = resReqs.getReservationResources(); if (resReq == null || resReq.isEmpty()) { message = "No resources have been specified to reserve." + " Please try again by specifying the resources to reserve."; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } // compute minimum duration and max gang size long minDuration = 0; Resource maxGangSize = Resource.newInstance(0, 0); ReservationRequestInterpreter type = contract.getReservationRequests().getInterpreter(); for (ReservationRequest rr : resReq) { if (type == ReservationRequestInterpreter.R_ALL || type == ReservationRequestInterpreter.R_ANY) { minDuration = Math.max(minDuration, rr.getDuration()); } else { minDuration += rr.getDuration(); } maxGangSize = Resources.max(plan.getResourceCalculator(), plan.getTotalCapacity(), maxGangSize, Resources.multiply(rr.getCapability(), rr.getConcurrency())); } /** Amber code starts here. The following is commented out.*/ // verify the allocation is possible (skip for ANY) //if (contract.getDeadline() - contract.getArrival() < minDuration // && type != ReservationRequestInterpreter.R_ANY) { // message = // "The time difference (" // + (contract.getDeadline() - contract.getArrival()) // + ") between arrival (" + contract.getArrival() + ") " // + "and deadline (" + contract.getDeadline() + ") must " // + " be greater or equal to the minimum resource duration (" // + minDuration + ")"; // RMAuditLogger.logFailure("UNKNOWN", auditConstant, // "validate reservation input definition", "ClientRMService", message); // throw RPCUtil.getRemoteException(message); //} /** Amber code ends here. The above is commented out.*/ // check that the largest gang does not exceed the inventory available // capacity (skip for ANY) //if (Resources.greaterThan(plan.getResourceCalculator(), /** Amber code starts here. A line */ if (Resources.rsrvGreaterThan(plan.getResourceCalculator(), plan.getTotalCapacity(), maxGangSize, plan.getTotalCapacity()) && type != ReservationRequestInterpreter.R_ANY) { message = "The size of the largest gang in the reservation refinition (" + maxGangSize + ") exceed the capacity available (" + plan.getTotalCapacity() + " )"; RMAuditLogger.logFailure("UNKNOWN", auditConstant, "validate reservation input definition", "ClientRMService", message); throw RPCUtil.getRemoteException(message); } } /** * Quick validation on the input to check some obvious fail conditions (fail * fast) the input and returns the appropriate {@link Plan} associated with * the specified {@link Queue} or throws an exception message illustrating the * details of any validation check failures * * @param reservationSystem the {@link ReservationSystem} to validate against * @param request the {@link ReservationSubmissionRequest} defining the * resources required over time for the request * @param reservationId the {@link ReservationId} associated with the current * request * @return the {@link Plan} to submit the request to * @throws YarnException */ public Plan validateReservationSubmissionRequest( ReservationSystem reservationSystem, ReservationSubmissionRequest request, ReservationId reservationId) throws YarnException { // Check if it is a managed queue String queueName = request.getQueue(); if (queueName == null || queueName.isEmpty()) { String errMsg = "The queue to submit is not specified." + " Please try again with a valid reservable queue."; RMAuditLogger.logFailure("UNKNOWN", AuditConstants.SUBMIT_RESERVATION_REQUEST, "validate reservation input", "ClientRMService", errMsg); throw RPCUtil.getRemoteException(errMsg); } Plan plan = reservationSystem.getPlan(queueName); if (plan == null) { String errMsg = "The specified queue: " + queueName + " is not managed by reservation system." + " Please try again with a valid reservable queue."; RMAuditLogger.logFailure("UNKNOWN", AuditConstants.SUBMIT_RESERVATION_REQUEST, "validate reservation input", "ClientRMService", errMsg); throw RPCUtil.getRemoteException(errMsg); } validateReservationDefinition(reservationId, request.getReservationDefinition(), plan, AuditConstants.SUBMIT_RESERVATION_REQUEST); return plan; } /** * Quick validation on the input to check some obvious fail conditions (fail * fast) the input and returns the appropriate {@link Plan} associated with * the specified {@link Queue} or throws an exception message illustrating the * details of any validation check failures * * @param reservationSystem the {@link ReservationSystem} to validate against * @param request the {@link ReservationUpdateRequest} defining the resources * required over time for the request * @return the {@link Plan} to submit the request to * @throws YarnException */ public Plan validateReservationUpdateRequest( ReservationSystem reservationSystem, ReservationUpdateRequest request) throws YarnException { ReservationId reservationId = request.getReservationId(); Plan plan = validateReservation(reservationSystem, reservationId, AuditConstants.UPDATE_RESERVATION_REQUEST); validateReservationDefinition(reservationId, request.getReservationDefinition(), plan, AuditConstants.UPDATE_RESERVATION_REQUEST); return plan; } /** * Quick validation on the input to check some obvious fail conditions (fail * fast) the input and returns the appropriate {@link Plan} associated with * the specified {@link Queue} or throws an exception message illustrating the * details of any validation check failures * * @param reservationSystem the {@link ReservationSystem} to validate against * @param request the {@link ReservationDeleteRequest} defining the resources * required over time for the request * @return the {@link Plan} to submit the request to * @throws YarnException */ public Plan validateReservationDeleteRequest( ReservationSystem reservationSystem, ReservationDeleteRequest request) throws YarnException { return validateReservation(reservationSystem, request.getReservationId(), AuditConstants.DELETE_RESERVATION_REQUEST); } }
apache-2.0
karaboM/lesieS
lesie-configuration/src/main/java/org/lesie/configuration/ConfigurationManager.java
828
/** * Copyright 2014 CPUT * * 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.lesie.configuration; import org.lesie.dto.response.LesieResponseDTO; public interface ConfigurationManager { public LesieResponseDTO getConfigByApplication(String appKey); }
apache-2.0
rostam/gradoop
gradoop-store/gradoop-hbase/src/test/java/org/gradoop/storage/impl/hbase/GradoopHBaseTestBase.java
8089
/* * Copyright © 2014 - 2019 Leipzig University (Database Research Group) * * 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.gradoop.storage.impl.hbase; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.gradoop.common.GradoopTestUtils; import org.gradoop.common.model.impl.pojo.Edge; import org.gradoop.common.model.impl.pojo.GraphHead; import org.gradoop.common.model.impl.pojo.Vertex; import org.gradoop.storage.config.GradoopHBaseConfig; import org.gradoop.storage.impl.hbase.factory.HBaseEPGMStoreFactory; import java.io.IOException; import java.util.Collection; import java.util.regex.Pattern; /** * Used for tests that need a HBase cluster to run. */ public class GradoopHBaseTestBase { public static final String LABEL_FORUM = "Forum"; public static final String LABEL_TAG = "Tag"; public static final String LABEL_HAS_MODERATOR = "hasModerator"; public static final String LABEL_HAS_MEMBER = "hasMember"; public static final Pattern PATTERN_GRAPH = Pattern.compile("^Com.*"); public static final Pattern PATTERN_VERTEX = Pattern.compile("^(Per|Ta).*"); public static final Pattern PATTERN_EDGE = Pattern.compile("^has.*"); public static final Pattern PATTERN_GRAPH_PROP = Pattern.compile(".*doop$"); public static final Pattern PATTERN_VERTEX_PROP = Pattern.compile(".*ve$"); public static final Pattern PATTERN_EDGE_PROP = Pattern.compile("^start..$"); public static final String PROP_AGE = "age"; public static final String PROP_CITY = "city"; public static final String PROP_INTEREST = "interest"; public static final String PROP_NAME = "name"; public static final String PROP_SINCE = "since"; public static final String PROP_STATUS = "status"; public static final String PROP_VERTEX_COUNT = "vertexCount"; private static Collection<GraphHead> socialGraphHeads; private static Collection<Vertex> socialVertices; private static Collection<Edge> socialEdges; //---------------------------------------------------------------------------- // Cluster related //---------------------------------------------------------------------------- /** * Handles the test cluster which is started for during unit testing. */ protected static HBaseTestingUtility utility; /** * Starts the mini cluster for all tests. * * @throws Exception if setting up HBase test cluster fails */ public static void setUpHBase() throws Exception { if (utility == null) { utility = new HBaseTestingUtility(HBaseConfiguration.create()); utility.startMiniCluster().waitForActiveAndReadyMaster(); } } /** * Stops the test cluster after the test. * * @throws Exception if closing HBase test cluster fails */ public static void tearDownHBase() throws Exception { if (utility != null) { utility.shutdownMiniCluster(); utility = null; } } //---------------------------------------------------------------------------- // Store handling methods //---------------------------------------------------------------------------- /** * Initializes and returns an empty graph store. * * @return empty HBase graph store */ public static HBaseEPGMStore createEmptyEPGMStore() { Configuration config = utility.getConfiguration(); HBaseEPGMStoreFactory.deleteEPGMStore(config); return HBaseEPGMStoreFactory.createOrOpenEPGMStore(config, GradoopHBaseConfig.getDefaultConfig()); } /** * Initializes and returns an empty graph store with a prefix at each table name. * * @param prefix the table prefix * @return empty HBase graph store */ public static HBaseEPGMStore createEmptyEPGMStore(String prefix) { Configuration config = utility.getConfiguration(); HBaseEPGMStoreFactory.deleteEPGMStore(config, prefix); return HBaseEPGMStoreFactory.createOrOpenEPGMStore( config, GradoopHBaseConfig.getDefaultConfig(), prefix ); } /** * Open existing EPGMStore for test purposes. If the store does not exist, a * new one will be initialized and returned. * * @return EPGMStore with vertices and edges */ public static HBaseEPGMStore openEPGMStore() { return HBaseEPGMStoreFactory.createOrOpenEPGMStore( utility.getConfiguration(), GradoopHBaseConfig.getDefaultConfig() ); } /** * Open existing EPGMStore for test purposes. If the store does not exist, a * new one will be initialized and returned. * * @param prefix the table prefix * @return EPGMStore with vertices and edges */ public static HBaseEPGMStore openEPGMStore(String prefix) { return HBaseEPGMStoreFactory.createOrOpenEPGMStore( utility.getConfiguration(), GradoopHBaseConfig.getDefaultConfig(), prefix ); } /** * Open existing EPGMStore for test purposes. If the store does not exist, a * new one will be initialized and returned. * * @param prefix the table prefix * @param gradoopHBaseConfig the gradoop HBase config to use * @return EPGMStore with vertices and edges */ public static HBaseEPGMStore openEPGMStore(String prefix, GradoopHBaseConfig gradoopHBaseConfig) { return HBaseEPGMStoreFactory.createOrOpenEPGMStore(utility.getConfiguration(), gradoopHBaseConfig, prefix); } //---------------------------------------------------------------------------- // Data generation //---------------------------------------------------------------------------- /** * Creates a collection of graph heads according to the social network test graph in * gradoop/dev-support/social-network.pdf. * * @return collection of graph heads * @throws IOException if fetching graph elements failed */ public static Collection<GraphHead> getSocialGraphHeads() throws IOException { if (socialGraphHeads == null) { socialGraphHeads = GradoopTestUtils.getSocialNetworkLoader().getGraphHeads(); } return socialGraphHeads; } /** * Creates a collection of vertices according to the social * network test graph in gradoop/dev-support/social-network.pdf. * * @return collection of vertices * @throws IOException if fetching graph elements failed */ public static Collection<Vertex> getSocialVertices() throws IOException { if (socialVertices == null) { socialVertices = GradoopTestUtils.getSocialNetworkLoader().getVertices(); } return socialVertices; } /** * Creates a collection of edges according to the social * network test graph in gradoop/dev-support/social-network.pdf. * * @return collection of edges * @throws IOException if fetching graph elements failed */ public static Collection<Edge> getSocialEdges() throws IOException { if (socialEdges == null) { socialEdges = GradoopTestUtils.getSocialNetworkLoader().getEdges(); } return socialEdges; } /** * Writes the example social graph to the HBase store and flushes it. * * @param epgmStore the store instance to write to * @throws IOException if writing to store fails */ public static void writeSocialGraphToStore(HBaseEPGMStore epgmStore) throws IOException { // write social graph to HBase for (GraphHead g : getSocialGraphHeads()) { epgmStore.writeGraphHead(g); } for (Vertex v : getSocialVertices()) { epgmStore.writeVertex(v); } for (Edge e : getSocialEdges()) { epgmStore.writeEdge(e); } epgmStore.flush(); } }
apache-2.0
edgardleal/edscript
java/src/carga/log/Logger.java
919
/** * */ package carga.log; import org.slf4j.*; /** * @author edgardleal * */ public class Logger { public static boolean isDebug = System.getenv("DEBUG") != null; private static org.slf4j.Logger l = LoggerFactory.getLogger(Logger.class); public static void debug(char text) { debug(String.valueOf(text)); } public static void debug(String text) { if (isDebug) { log(text); } } public static void debug(String pattern, Object... args) { debug(String.format(pattern, args)); } public static void log(String pattern, Object... args) { log(String.format(pattern, args)); } public static void log(String message) { l.info(message); } public static void error(Exception ex) { ex.printStackTrace(); } public static void error(String value) { error("%s", value); } public static void error(String pattern, Object... value) { l.error(String.format(pattern, value)); } }
apache-2.0
ErikWAberg/facerecognition
common/src/main/java/opencv/CameraCapture.java
6354
/* * * * Copyright 2015 Erik Wiséen Åberg * * * * 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 opencv; import com.esotericsoftware.minlog.Log; import org.bytedeco.javacv.*; import static org.bytedeco.javacpp.opencv_core.*; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Observable; import java.util.concurrent.LinkedBlockingQueue; public class CameraCapture extends Observable { private final LinkedBlockingQueue<BufferedImage> capturedImageQueue; private CanvasFrame captureCanvasFrame; private FrameGrabber cameraFrameGrabber; private double captureIntervalInSeconds = 0.5; private final CvMemStorage storage; private final Java2DFrameConverter frame2bufferedImageConverter; private WindowRenderer windowRenderer; public CameraCapture(final int prefWidth, final int prefHeight, LinkedBlockingQueue<BufferedImage> capturedImageQueue) { this.capturedImageQueue = capturedImageQueue; try { cameraFrameGrabber = FrameGrabber.createDefault(0); } catch (FrameGrabber.Exception e) { cameraFrameGrabber = new OpenCVFrameGrabber(0); } cameraFrameGrabber.setImageHeight(prefHeight); cameraFrameGrabber.setImageWidth(prefWidth); cameraFrameGrabber.setImageMode(FrameGrabber.ImageMode.GRAY); frame2bufferedImageConverter = new Java2DFrameConverter(); storage = CvMemStorage.create(); createCaptureDisplay(prefHeight, prefWidth); } /** * Sets up a CanvasFrame onto which the camera feed will be drawn. * @param prefHeight preferred window height. * @param prefWidth preferred window width. */ public void createCaptureDisplay(int prefHeight, int prefWidth) { captureCanvasFrame = new CanvasFrame("Face recognition service", CanvasFrame.getDefaultGamma() / cameraFrameGrabber.getGamma()); captureCanvasFrame.setVisible(false); captureCanvasFrame.setCanvasSize(prefWidth, prefHeight); captureCanvasFrame.setLocation(prefWidth / 4 + 30, 0); captureCanvasFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); } /** * Modify how much time is waited in between taking snapshots of the * camera feed. * @param captureIntervalInSeconds the new waiting period in seconds. */ public void setCaptureIntervalInSeconds(double captureIntervalInSeconds) { this.captureIntervalInSeconds = captureIntervalInSeconds; } /** * Invokes a SwingWorker to initiate the camera feed. */ public void startCapture() { windowRenderer = new WindowRenderer(); windowRenderer.execute(); } /** * Stop the camera feed. */ public void stopCapture() { Runnable r = new Runnable() { @Override public void run() { captureCanvasFrame.setVisible(false); windowRenderer.cancel(true); } }; if (EventQueue.isDispatchThread()) { r.run(); } else { SwingUtilities.invokeLater(r); } } /** * Start the camera capture and render the camera feed onto * the CanvasFrame. A snapshot is captured from the camera feed * every X-seconds, where X is specified by the user and * defaults to 0.5seconds. The snapshot is sent to a face recognition * service. * @throws FrameGrabber.Exception */ private void startCameraCapture() throws FrameGrabber.Exception, InterruptedException { cameraFrameGrabber.start(); org.bytedeco.javacv.Frame grabbedFrame; long timeSinceSnapshot = System.currentTimeMillis(); long fpsTime = System.currentTimeMillis(); int nGrabbedFrames = 0; long prevTime = System.currentTimeMillis(); while (captureCanvasFrame.isVisible() && (grabbedFrame = cameraFrameGrabber.grab()) != null) { IplImage iplImage = ((IplImage) grabbedFrame.opaque); cvFlip(iplImage, iplImage, 1); BufferedImage bfimg = frame2bufferedImageConverter.convert(grabbedFrame); captureCanvasFrame.showImage(bfimg); cvClearMemStorage(storage); nGrabbedFrames++; if (System.currentTimeMillis() - fpsTime > 1000) { Log.info("Capture frame rate: " + nGrabbedFrames); nGrabbedFrames = 0; fpsTime = System.currentTimeMillis(); } if (System.currentTimeMillis() - timeSinceSnapshot > ((long) (captureIntervalInSeconds * 1000))) { Log.info("Captured image size: <" + grabbedFrame.imageWidth + "x" + grabbedFrame.imageHeight + ">, Depth: " + grabbedFrame.imageDepth + ", Channels: " + grabbedFrame.imageChannels + " prev. capture(ms): " + (System.currentTimeMillis() - prevTime)); capturedImageQueue.put(bfimg); timeSinceSnapshot = System.currentTimeMillis(); prevTime = timeSinceSnapshot; } } Log.info("Camera frame grabber stopped"); cameraFrameGrabber.stop(); setChanged(); notifyObservers("STOPPED"); } /** * A SwingWorker which captures the camera feed and * renders the result to a CanvasFrame. */ private class WindowRenderer extends SwingWorker<Void, Void> { @Override public Void doInBackground() { captureCanvasFrame.setVisible(true); try { startCameraCapture(); } catch (FrameGrabber.Exception e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return null; } } }
apache-2.0
darranl/directory-shared
ldap/model/src/main/java/org/apache/directory/api/ldap/model/message/BindStatus.java
1428
/* * 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.directory.api.ldap.model.message; /** * An enum used to store the BindRequest state. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public enum BindStatus { /** * We are in Anonymous state. The user specifically required to * be anonymous **/ ANONYMOUS, /** * We have received a Simple BindRequest */ SIMPLE_AUTH_PENDING, /** * We have received a SASL BindRequest */ SASL_AUTH_PENDING, /** * The user has been authenticated */ AUTHENTICATED }
apache-2.0
pojosontheweb/selenium-utils
monte/src/main/java/org/monte/media/io/ImageInputStreamAdapter.java
6908
/* * @(#)ImageInputStreamAdapter.java 1.0 2009-12-17 * * Copyright (c) 2009 Werner Randelshofer, Goldau, Switzerland. * All rights reserved. * * You may not use, copy or modify this file, except in compliance with the * license agreement you entered into with Werner Randelshofer. * For details see accompanying license terms. */ package org.monte.media.io; import java.io.FilterInputStream; import java.io.IOException; import javax.imageio.stream.ImageInputStream; /** * ImageInputStreamAdapter. * * @author Werner Randelshofer * @version 1.0 2009-12-17 Created. */ public class ImageInputStreamAdapter extends FilterInputStream { private ImageInputStream iis; public ImageInputStreamAdapter(ImageInputStream iis) { super(null); this.iis=iis; } /** * Reads the next byte of data from this input stream. The value * byte is returned as an <code>int</code> in the range * <code>0</code> to <code>255</code>. If no byte is available * because the end of the stream has been reached, the value * <code>-1</code> is returned. This method blocks until input data * is available, the end of the stream is detected, or an exception * is thrown. * <p> * This method * simply performs <code>in.read()</code> and returns the result. * * @return the next byte of data, or <code>-1</code> if the end of the * stream is reached. * @exception java.io.IOException if an I/O error occurs. * @see java.io.FilterInputStream#in */ @Override public int read() throws IOException { return iis.read(); } /** * Reads up to <code>len</code> bytes of data from this input stream * into an array of bytes. If <code>len</code> is not zero, the method * blocks until some input is available; otherwise, no * bytes are read and <code>0</code> is returned. * <p> * This method simply performs <code>in.read(b, off, len)</code> * and returns the result. * * @param b the buffer into which the data is read. * @param off the start offset in the destination array <code>b</code> * @param len the maximum number of bytes read. * @return the total number of bytes read into the buffer, or * <code>-1</code> if there is no more data because the end of * the stream has been reached. * @exception NullPointerException If <code>b</code> is <code>null</code>. * @exception IndexOutOfBoundsException If <code>off</code> is negative, * <code>len</code> is negative, or <code>len</code> is greater than * <code>b.length - off</code> * @exception java.io.IOException if an I/O error occurs. * @see java.io.FilterInputStream#in */ @Override public int read(byte b[], int off, int len) throws IOException { return iis.read(b, off, len); } /** * {@inheritDoc} * <p> * This method simply performs <code>in.skip(n)</code>. */ @Override public long skip(long n) throws IOException { return iis.skipBytes(n); } /** * Returns an estimate of the number of bytes that can be read (or * skipped over) from this input stream without blocking by the next * caller of a method for this input stream. The next caller might be * the same thread or another thread. A single read or skip of this * many bytes will not block, but may read or skip fewer bytes. * <p> * This method returns the result of {@link #in in}.available(). * * @return an estimate of the number of bytes that can be read (or skipped * over) from this input stream without blocking. * @exception java.io.IOException if an I/O error occurs. */ @Override public int available() throws IOException { return (iis.isCached()) ? // (int)Math.min(Integer.MAX_VALUE, iis.length() - iis.getStreamPosition()) : 0; } /** * Closes this input stream and releases any system resources * associated with the stream. * This * method simply performs <code>in.close()</code>. * * @exception java.io.IOException if an I/O error occurs. * @see java.io.FilterInputStream#in */ @Override public void close() throws IOException { iis.close(); } /** * Marks the current position in this input stream. A subsequent * call to the <code>reset</code> method repositions this stream at * the last marked position so that subsequent reads re-read the same bytes. * <p> * The <code>readlimit</code> argument tells this input stream to * allow that many bytes to be read before the mark position gets * invalidated. * <p> * This method simply performs <code>in.mark(readlimit)</code>. * * @param readlimit the maximum limit of bytes that can be read before * the mark position becomes invalid. * @see java.io.FilterInputStream#in * @see java.io.FilterInputStream#reset() */ @Override public synchronized void mark(int readlimit) { iis.mark(); } /** * Repositions this stream to the position at the time the * <code>mark</code> method was last called on this input stream. * <p> * This method * simply performs <code>in.reset()</code>. * <p> * Stream marks are intended to be used in * situations where you need to read ahead a little to see what's in * the stream. Often this is most easily done by invoking some * general parser. If the stream is of the type handled by the * parse, it just chugs along happily. If the stream is not of * that type, the parser should toss an exception when it fails. * If this happens within readlimit bytes, it allows the outer * code to reset the stream and try another parser. * * @exception java.io.IOException if the stream has not been marked or if the * mark has been invalidated. * @see java.io.FilterInputStream#in * @see java.io.FilterInputStream#mark(int) */ @Override public synchronized void reset() throws IOException { iis.reset(); } /** * Tests if this input stream supports the <code>mark</code> * and <code>reset</code> methods. * This method * simply performs <code>in.markSupported()</code>. * * @return <code>true</code> if this stream type supports the * <code>mark</code> and <code>reset</code> method; * <code>false</code> otherwise. * @see java.io.FilterInputStream#in * @see java.io.InputStream#mark(int) * @see java.io.InputStream#reset() */ @Override public boolean markSupported() { return true; } }
apache-2.0
shajyhia/score-language
cloudslang-runtime/src/main/java/io/cloudslang/lang/runtime/steps/ExecutableSteps.java
8535
/* * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 */ package io.cloudslang.lang.runtime.steps; import com.hp.oo.sdk.content.annotations.Param; import io.cloudslang.lang.entities.ScoreLangConstants; import io.cloudslang.lang.runtime.bindings.InputsBinding; import io.cloudslang.lang.runtime.bindings.OutputsBinding; import io.cloudslang.lang.runtime.bindings.ResultsBinding; import io.cloudslang.lang.runtime.env.Context; import io.cloudslang.lang.runtime.env.ReturnValues; import io.cloudslang.lang.runtime.env.RunEnvironment; import io.cloudslang.lang.runtime.events.LanguageEventData; import org.apache.log4j.Logger; import io.cloudslang.lang.entities.bindings.Input; import io.cloudslang.lang.entities.bindings.Result; import io.cloudslang.lang.entities.bindings.Output; import io.cloudslang.lang.runtime.env.ParentFlowData; import org.apache.commons.lang3.tuple.Pair; import io.cloudslang.score.lang.ExecutionRuntimeServices; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import static io.cloudslang.score.api.execution.ExecutionParametersConsts.EXECUTION_RUNTIME_SERVICES; /** * User: stoneo * Date: 02/11/2014 * Time: 10:24 */ @Component public class ExecutableSteps extends AbstractSteps { public static final String ACTION_RETURN_VALUES_KEY = "actionReturnValues"; @Autowired private ResultsBinding resultsBinding; @Autowired private InputsBinding inputsBinding; @Autowired private OutputsBinding outputsBinding; private static final Logger logger = Logger.getLogger(ExecutableSteps.class); public void startExecutable(@Param(ScoreLangConstants.EXECUTABLE_INPUTS_KEY) List<Input> executableInputs, @Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv, @Param(ScoreLangConstants.USER_INPUTS_KEY) Map<String, ? extends Serializable> userInputs, @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices, @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName, @Param(ScoreLangConstants.NEXT_STEP_ID_KEY) Long nextStepId) { try { Map<String, Serializable> callArguments = runEnv.removeCallArguments(); if (userInputs != null) { callArguments.putAll(userInputs); } sendStartBindingInputsEvent(executableInputs, runEnv, executionRuntimeServices, "Pre Input binding for operation/flow", LanguageEventData.StepType.EXECUTABLE, nodeName, null); Map<String, Serializable> executableContext = inputsBinding.bindInputs(executableInputs, callArguments, runEnv.getSystemProperties()); Map<String, Serializable> actionArguments = new HashMap<>(); //todo: clone action context before updating actionArguments.putAll(executableContext); //done with the user inputs, don't want it to be available in next startExecutable steps.. if (userInputs != null) { userInputs.clear(); } //todo: hook updateCallArgumentsAndPushContextToStack(runEnv, new Context(executableContext), actionArguments); sendEndBindingInputsEvent(executableInputs, executableContext, runEnv, executionRuntimeServices, "Post Input binding for operation/flow", LanguageEventData.StepType.EXECUTABLE, nodeName); // put the next step position for the navigation runEnv.putNextStepPosition(nextStepId); runEnv.getExecutionPath().down(); } catch (RuntimeException e){ logger.error("There was an error running the start executable execution step of: \'" + nodeName + "\'.\n\tError is: " + e.getMessage()); throw new RuntimeException("Error running: \'" + nodeName + "\'.\n\t " + e.getMessage(), e); } } /** * This method is executed by the finishExecutable execution step of an operation or flow * * @param runEnv the run environment object * @param executableOutputs the operation outputs data * @param executableResults the operation results data * @param executionRuntimeServices services supplied by score engine for handling the execution */ public void finishExecutable(@Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv, @Param(ScoreLangConstants.EXECUTABLE_OUTPUTS_KEY) List<Output> executableOutputs, @Param(ScoreLangConstants.EXECUTABLE_RESULTS_KEY) List<Result> executableResults, @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices, @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName) { try { runEnv.getExecutionPath().up(); Context operationContext = runEnv.getStack().popContext(); Map<String, Serializable> operationVariables = operationContext == null ? null : operationContext.getImmutableViewOfVariables(); ReturnValues actionReturnValues = runEnv.removeReturnValues(); fireEvent(executionRuntimeServices, runEnv, ScoreLangConstants.EVENT_OUTPUT_START, "Output binding started", LanguageEventData.StepType.EXECUTABLE, nodeName, Pair.of(ScoreLangConstants.EXECUTABLE_OUTPUTS_KEY, (Serializable) executableOutputs), Pair.of(ScoreLangConstants.EXECUTABLE_RESULTS_KEY, (Serializable) executableResults), Pair.of(ACTION_RETURN_VALUES_KEY, actionReturnValues)); // Resolving the result of the operation/flow String result = resultsBinding.resolveResult(operationVariables, actionReturnValues.getOutputs(), executableResults, actionReturnValues.getResult()); Map<String, Serializable> operationReturnOutputs = outputsBinding.bindOutputs(operationVariables, actionReturnValues.getOutputs(), executableOutputs); //todo: hook ReturnValues returnValues = new ReturnValues(operationReturnOutputs, result); runEnv.putReturnValues(returnValues); fireEvent(executionRuntimeServices, runEnv, ScoreLangConstants.EVENT_OUTPUT_END, "Output binding finished", LanguageEventData.StepType.EXECUTABLE, nodeName, Pair.of(LanguageEventData.OUTPUTS, (Serializable) operationReturnOutputs), Pair.of(LanguageEventData.RESULT, returnValues.getResult())); // If we have parent flow data on the stack, we pop it and request the score engine to switch to the parent // execution plan id once it can, and we set the next position that was stored there for the use of the navigation if (!runEnv.getParentFlowStack().isEmpty()) { handleNavigationToParent(runEnv, executionRuntimeServices); } else { fireEvent(executionRuntimeServices, runEnv, ScoreLangConstants.EVENT_EXECUTION_FINISHED, "Execution finished running", LanguageEventData.StepType.EXECUTABLE, nodeName, Pair.of(LanguageEventData.RESULT, returnValues.getResult()), Pair.of(LanguageEventData.OUTPUTS, (Serializable) operationReturnOutputs)); } } catch (RuntimeException e){ logger.error("There was an error running the finish executable execution step of: \'" + nodeName + "\'.\n\tError is: " + e.getMessage()); throw new RuntimeException("Error running: \'" + nodeName + "\'.\n\t" + e.getMessage(), e); } } private void handleNavigationToParent(RunEnvironment runEnv, ExecutionRuntimeServices executionRuntimeServices) { ParentFlowData parentFlowData = runEnv.getParentFlowStack().popParentFlowData(); executionRuntimeServices.requestToChangeExecutionPlan(parentFlowData.getRunningExecutionPlanId()); runEnv.putNextStepPosition(parentFlowData.getPosition()); } }
apache-2.0
cushon/error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java
41774
/* * Copyright 2018 The Error Prone 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.errorprone.bugpatterns; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers; import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.ErrorProneFlags; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link UnusedVariable}. */ @RunWith(JUnit4.class) public class UnusedVariableTest { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(UnusedVariable.class, getClass()); private final BugCheckerRefactoringTestHelper refactoringHelper = BugCheckerRefactoringTestHelper.newInstance( new UnusedVariable(ErrorProneFlags.empty()), getClass()); @Test public void exemptedByReceiverParameter() { helper .addSourceLines( "ExemptedByReceiverParameter.java", "package unusedvars;", "public class ExemptedByReceiverParameter {", " public void test() {", " used();", " }", " private void used(ExemptedByReceiverParameter this) {", " // the receiver parameter should not be marked as unused", " }", " class Inner {", " private Inner(ExemptedByReceiverParameter ExemptedByReceiverParameter.this) {", " // the receiver parameter should not be marked as unused", " }", " }", "}") .doTest(); } @Test public void unicodeBytes() { helper .addSourceLines( "UnicodeBytes.java", "package unusedvars;", "/**", " * This file contains Unicode characters: ❁❁❁❁❁❁❁❁❁", " */", "public class UnicodeBytes {", " public void test() {", " // BUG: Diagnostic contains: is never read", " int notUsedLocal;", " String usedLocal = \"\";", " System.out.println(usedLocal);", " }", "}") .doTest(); } @Test public void unusedArray() { helper .addSourceLines( "UnusedArray.java", "package unusedvars;", "public class UnusedArray {", " private int[] ints;", " public void test() {", " ints[0] = 0;", " ints[0]++;", " ints[0]--;", " ints[0] -= 0;", " }", "}") .doTest(); } @Test public void unusedEnhancedForLoop() { refactoringHelper .addInputLines( "UnusedEnhancedForLoop.java", "package unusedvars;", "import java.util.ArrayList;", "import java.util.List;", "class UnusedEnhancedForLoop {", " public List<String> makeList(List<String> input) {", " List<String> output = new ArrayList<>();", " for (final String firstVar : input) {", " output.add(\"a string\");", " }", " return output;", " }", " public List<String> listData(List<List<String>> input) {", " List<String> output = new ArrayList<>();", " for (List<String> secondVar : input) {", " output.add(\"a string\");", " }", " return output;", " }", "}") .addOutputLines( "UnusedEnhancedForLoop.java", "package unusedvars;", "import java.util.ArrayList;", "import java.util.List;", "class UnusedEnhancedForLoop {", " public List<String> makeList(List<String> input) {", " List<String> output = new ArrayList<>();", " for (final String unused : input) {", " output.add(\"a string\");", " }", " return output;", " }", " public List<String> listData(List<List<String>> input) {", " List<String> output = new ArrayList<>();", " for (List<String> unused : input) {", " output.add(\"a string\");", " }", " return output;", " }", "}") .doTest(); } @Test public void unusedField() { helper .addSourceLines( "UnusedField.java", "package unusedvars;", "import java.util.ArrayList;", "import java.util.List;", "public class UnusedField {", " // BUG: Diagnostic contains: is never read", " private int notUsedInt;", " // BUG: Diagnostic contains: is never read", " private List<String> list = new ArrayList<>();", " public void test() {", " notUsedInt = 0;", " if (hashCode() > 0) {", " list = null;", " } else {", " list = makeList();", " }", " }", " private List<String> makeList() {", " return null;", " }", " public UnusedField(List<String> list) {", " this.list = list;", " }", " // These fields are special, and should not be flagged as unused.", " private static final long serialVersionUID = 0;", " private static final String TAG = \"UnusedFieldTestThingy\";", " @SuppressWarnings(\"unchecked\")", " // BUG: Diagnostic contains: is never read", " private long fieldWithAnn;", "}") .doTest(); } @Test public void unusedLocalVarInitialized() { helper .addSourceLines( "UnusedLocalVarInitialized.java", "package unusedvars;", "public class UnusedLocalVarInitialized {", " public void test() {", " String s = \"\";", " System.out.println(s);", " // BUG: Diagnostic contains: is never read", " int notUsed = UnusedLocalVarInitialized.setData();", " notUsed = this.hashCode();", " }", " public static int setData() {", " return 0;", " }", "}") .doTest(); } @Test public void unusedLocalVar() { helper .addSourceLines( "UnusedLocalVar.java", "package unusedvars;", "public class UnusedLocalVar {", " public void test() {", " // BUG: Diagnostic contains: is never read", " int notUsedLocal;", " notUsedLocal = 0;", " String usedLocal = \"\";", " if (usedLocal.length() == 0) {", " notUsedLocal = 10 + usedLocal.length();", " } else {", " notUsedLocal = this.calculate()", " + 1 ;", " notUsedLocal--;", " notUsedLocal += Integer.valueOf(1);", " System.out.println(usedLocal);", " }", " System.out.println(usedLocal);", " }", " int calculate() {", " return 0;", " }", "}") .doTest(); } @Test public void unusedNative() { helper .addSourceLines( "UnusedNative.java", "package unusedvars;", "public class UnusedNative {", " private int usedInNative1 = 0;", " private String usedInNative2 = \"\";", " private native void aNativeMethod();", "}") .doTest(); } @Test public void unusedParamInPrivateMethod() { helper .addSourceLines( "UnusedParamInPrivateMethod.java", "package unusedvars;", "public class UnusedParamInPrivateMethod {", " // BUG: Diagnostic contains: 'j' is never read", " private void test(int i, int j) {", " System.out.println(i);", " }", " public void main() {", " test(1, 2);", " }", "}") .doTest(); } @Test public void unuseds() { helper .addSourceLines( "Unuseds.java", "package unusedvars;", "import java.io.IOException;", "import java.io.ObjectStreamException;", "import java.util.List;", "import javax.inject.Inject;", "public class Unuseds {", " // BUG: Diagnostic contains:", " private static final String NOT_USED_CONST_STR = \"unused_test\";", " private static final String CONST_STR = \"test\";", " // BUG: Diagnostic contains:", " private int notUsed;", " private List<String> used;", " public int publicOne;", " private int[] ints;", " @Inject", " private int unusedExemptedByAnnotation;", " @Inject", " private void unusedMethodExemptedByAnnotation() {}", " void test() {", " this.notUsed = 0;", " this.notUsed++;", " this.notUsed += 0;", " // BUG: Diagnostic contains:", " int notUsedLocal;", " notUsedLocal = 10;", " int usedLocal = 0;", " if (!used.get(usedLocal).toString().equals(CONST_STR)) {", " used.add(\"test\");", " }", " // j is used", " int j = 0;", " used.get(j++);", " ints[j--]++;", " ints[1] = 0;", " // Negative case (:( data flow analysis...).", " byte[] notUsedLocalArray = new byte[]{};", " notUsedLocalArray[0] += this.used.size();", " char[] out = new char[]{};", " for (int m = 0, n = 0; m < 1; m++) {", " out[n++] = out[m];", " }", " // Negative case", " double timestamp = 0.0;", " set(timestamp += 1.0);", " int valuesIndex1 = 0;", " int valuesIndex2 = 0;", " double[][][] values = null;", " values[0][valuesIndex1][valuesIndex2] = 10;", " System.out.println(values);", " }", " public void set(double d) {}", " public void usedInMethodCall(double d) {", " List<Unuseds> notUseds = null;", " int indexInMethodCall = 0;", " // Must not be reported as unused", " notUseds.get(indexInMethodCall).publicOne = 0;", " }", " void memberSelectUpdate1() {", " List<Unuseds> l = null;", " // `u` should not be reported as unused.", " Unuseds u = getFirst(l);", " u.notUsed = 10;", " System.out.println(l);", " getFirst(l).notUsed = 100;", " }", " void memberSelectUpdate2() {", " List<Unuseds> l = null;", " // `l` should not be reported as unused.", " l.get(0).notUsed = 10;", " }", " Unuseds getFirst(List<Unuseds> l) {", " return l.get(0);", " }", " // Negative case. Must not report.", " private int usedCount = 0;", " int incCounter() {", " return usedCount += 2;", " }", " // For testing the lack of NPE on return statement.", " public void returnNothing() {", " return;", " }", " // Negative case. Must not report.", " public void testUsedArray() {", " ints[0] = 0;", " ints[0]++;", " ints[0]--;", " ints[0] -= 0;", " }", " @SuppressWarnings({\"deprecation\", \"unused\"})", " class UsesSuppressWarning {", " private int f1;", " private void test1() {", " int local;", " }", " }", "}") .doTest(); } @Test public void refactoring() { refactoringHelper .addInputLines( "Unuseds.java", "package unusedvars;", "public class Unuseds {", " private static final String NOT_USED_CONST_STR = \"unused_test\";", " private static final String CONST_STR = \"test\";", " private int notUsed;", " public int publicOne;", " void test() {", " this.notUsed = 0;", " this.notUsed++;", " this.notUsed += 0;", " int notUsedLocal;", " notUsedLocal = 10;", " System.out.println(CONST_STR);", " }", "}") .addOutputLines( "Unuseds.java", "package unusedvars;", "public class Unuseds {", " private static final String CONST_STR = \"test\";", " public int publicOne;", " void test() {", " System.out.println(CONST_STR);", " }", "}") .doTest(); } @Test public void overridableMethods() { helper .addSourceLines( "Unuseds.java", "package unusedvars;", "public class Unuseds {", " // BUG: Diagnostic contains: The parameter 'j' is never read", " private int usedPrivateMethodWithUnusedParam(int i, int j) {", " return i * 2;", " }", " int a = usedPrivateMethodWithUnusedParam(1, 2);", " // In the following three cases, parameters should not be reported as unused,", " // because methods are non-private.", " public void publicMethodWithUnusedParam(int i, int j) {}", " public void protectedMethodWithUnusedParam(int i, int j) {}", " public void packageMethodWithUnusedParam(int i, int j) {}", "}") .doTest(); } @Test public void exemptedByName() { helper .addSourceLines( "Unuseds.java", "package unusedvars;", "class ExemptedByName {", " private int unused;", " private int unusedInt;", " private static final int UNUSED_CONSTANT = 5;", " private int ignored;", "}") .doTest(); } @Test public void suppressions() { helper .addSourceLines( "Unuseds.java", "package unusedvars;", "class Suppressed {", " @SuppressWarnings({\"deprecation\", \"unused\"})", " class UsesSuppressWarning {", " private int f1;", " private void test1() {", " int local;", " }", " @SuppressWarnings(value = \"unused\")", " private void test2() {", " int local;", " }", " }", "}") .doTest(); } @Test public void unusedStaticField() { helper .addSourceLines( "UnusedStaticField.java", "package unusedvars;", "import java.util.ArrayList;", "import java.util.List;", "public class UnusedStaticField {", " // BUG: Diagnostic contains: is never read", " private static final List<String> DATA = new ArrayList<>();", "}") .doTest(); } @Test public void unusedStaticPrivate() { helper .addSourceLines( "UnusedStaticPrivate.java", "package unusedvars;", "public class UnusedStaticPrivate {", " // BUG: Diagnostic contains: is never read", " private static final String NOT_USED_CONST_STR = \"unused_test\";", " static final String CONST_STR = \"test\";", "}") .doTest(); } @Test public void unusedTryResource() { helper .addSourceLines( "UnusedTryResource.java", "package unusedvars;", "public class UnusedTryResource {", " public static void main(String[] args) {", " try (A a = new A()) {", " }", " }", "}", "class A implements AutoCloseable {", " public void close() {}", "}") .doTest(); } @Test public void removal_javadocsAndNonJavadocs() { refactoringHelper .addInputLines( "UnusedWithComment.java", "package unusedvars;", "public class UnusedWithComment {", " /**", " * Comment for a field */", " @SuppressWarnings(\"test\")", " private Object field;", "}") .addOutputLines( "UnusedWithComment.java", // "package unusedvars;", "public class UnusedWithComment {", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void removal_trailingComment() { refactoringHelper .addInputLines( "Test.java", "public class Test {", " public static final int A = 1; // foo", "", " private static final int B = 2;", "}") .addOutputLines( "Test.java", // "public class Test {", " public static final int A = 1; // foo", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void removal_javadocAndSingleLines() { refactoringHelper .addInputLines( "Test.java", "public class Test {", " public static final int A = 1; // foo", "", " /** Javadoc. */", " // TODO: fix", " // BUG: bug", " private static final int B = 2;", "}") .addOutputLines( "Test.java", // "public class Test {", " public static final int A = 1; // foo", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void removal_rogueBraces() { refactoringHelper .addInputLines( "Test.java", "@SuppressWarnings(\"foo\" /* { */)", "public class Test {", " private static final int A = 1;", "}") .addOutputLines( "Test.java", // "@SuppressWarnings(\"foo\" /* { */)", "public class Test {", "}") .doTest(TestMode.TEXT_MATCH); } @Test public void unusedWithComment_interspersedComments() { helper .addSourceLines( "UnusedWithComment.java", "package unusedvars;", "public class UnusedWithComment {", " private static final String foo = null, // foo", " // BUG: Diagnostic contains:", " bar = null;", " public static String foo() { return foo; }", "}") .doTest(); } @Test public void usedInLambda() { helper .addSourceLines( "UsedInLambda.java", "package unusedvars;", "import java.util.Arrays;", "import java.util.List;", "import java.util.function.Function;", "import java.util.stream.Collectors;", "/** Method parameters used in lambdas and anonymous classes */", "public class UsedInLambda {", " private Function<Integer, Integer> usedInLambda() {", " return x -> 1;", " }", " private String print(Object o) {", " return o.toString();", " }", " public List<String> print(List<Object> os) {", " return os.stream().map(this::print).collect(Collectors.toList());", " }", " public static void main(String[] args) {", " System.err.println(new UsedInLambda().usedInLambda());", " System.err.println(new UsedInLambda().print(Arrays.asList(1, 2, 3)));", " }", "}") .doTest(); } @Test public void utf8Handling() { helper .addSourceLines( "Utf8Handling.java", "package unusedvars;", "public class Utf8Handling {", " private int foo = 1;", " public void test() {", " System.out.println(\"広\");", " for (int i = 0; i < 10; ++i) {", " // BUG: Diagnostic contains: is never read", " int notUsedLocal = calculate();", " }", " System.out.println(foo);", " }", " int calculate() {", " return ++foo;", " }", "}") .doTest(); } @Test public void methodAnnotationsExemptingParameters() { helper .addSourceLines( "A.java", "package unusedvars;", "class A {", " { foo(1); }", " @B", " private static void foo(int a) {}", "}", "@interface B {}") .setArgs( ImmutableList.of("-XepOpt:Unused:methodAnnotationsExemptingParameters=unusedvars.B")) .doTest(); } @Test public void usedUnaryExpression() { helper .addSourceLines( "Test.java", "package unusedvars;", "import java.util.Map;", "import java.util.HashMap;", "public class Test {", " private int next = 1;", " private Map<String, Integer> xs = new HashMap<>();", " public int frobnicate(String s) {", " Integer x = xs.get(s);", " if (x == null) {", " x = next++;", " xs.put(s, x);", " }", " return x;", " }", "}") .doTest(); } @Test public void unusedInject() { helper .addSourceLines( "Test.java", "package unusedvars;", "import javax.inject.Inject;", "public class Test {", // Package-private @Inject fields are assumed to be only used within the class, and only // visible for performance. " // BUG: Diagnostic contains:", " @Inject Object foo;", " @Inject public Object bar;", "}") .setArgs(ImmutableList.of("-XepOpt:Unused:ReportInjectedFields")) .doTest(); } @Test public void unusedInject_notByDefault() { helper .addSourceLines( "Test.java", "package unusedvars;", "import javax.inject.Inject;", "public class Test {", " @Inject Object foo;", " @Inject public Object bar;", "}") .doTest(); } @Test public void variableKeepingSideEffects() { refactoringHelper .addInputLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " private final ImmutableList<Integer> foo = ImmutableList.of();", " void test() {", " ImmutableList<Integer> foo = ImmutableList.of();", " }", "}") .addOutputLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " { ImmutableList.of(); }", " void test() {", " ImmutableList.of();", " }", "}") .setFixChooser(FixChoosers.SECOND) .doTest(); } @Test public void variableRemovingSideEffects() { refactoringHelper .addInputLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " private final ImmutableList<Integer> foo = ImmutableList.of();", " void test() {", " ImmutableList<Integer> foo = ImmutableList.of();", " }", "}") .addOutputLines( "Test.java", "import com.google.common.collect.ImmutableList;", "class Test {", " void test() {", " }", "}") .doTest(); } @Test public void exemptedFieldsByType() { helper .addSourceLines( "Test.java", "import org.junit.rules.TestRule;", "class Test {", " private TestRule rule;", "}") .doTest(); } @Test public void findingBaseSymbol() { helper .addSourceLines( "Test.java", "class Test {", " int a;", " void test() {", " Test o = new Test();", " ((Test) o).a = 1;", " (((o))).a = 1;", " Test p = new Test();", " id(p).a = 1;", " }", " Test id(Test t) { return t; }", "}") .doTest(); } @Test public void fixPrivateMethod_usagesToo() { refactoringHelper .addInputLines( "Test.java", "class Test {", " int a = foo(1);", " private int foo(int b) {", " b = 1;", " return 1;", " }", "}") .addOutputLines( "Test.java", "class Test {", " int a = foo();", " private int foo() {", " return 1;", " }", "}") .doTest(); } @Test public void fixPrivateMethod_parameterLocations() { refactoringHelper .addInputLines( "Test.java", "class Test {", " int a = foo(1, 2, 3) + bar(1, 2, 3) + baz(1, 2, 3);", " private int foo(int a, int b, int c) { return a * b; }", " private int bar(int a, int b, int c) { return b * c; }", " private int baz(int a, int b, int c) { return a * c; }", "}") .addOutputLines( "Test.java", "class Test {", " int a = foo(1, 2) + bar(2, 3) + baz(1, 3);", " private int foo(int a, int b) { return a * b; }", " private int bar(int b, int c) { return b * c; }", " private int baz(int a, int c) { return a * c; }", "}") .doTest(); } @Test public void fixPrivateMethod_varArgs() { refactoringHelper .addInputLines( "Test.java", "class Test {", " int a = foo(1, 2, 3, 4);", " private int foo(int a, int... b) { return a; }", "}") .addOutputLines( "Test.java", "class Test {", " int a = foo(1);", " private int foo(int a) { return a; }", "}") .doTest(); } @Test public void fixPrivateMethod_varArgs_noArgs() { refactoringHelper .addInputLines( "Test.java", "class Test {", " int a = foo(1);", " private int foo(int a, int... b) { return a; }", "}") .addOutputLines( "Test.java", "class Test {", " int a = foo(1);", " private int foo(int a) { return a; }", "}") .doTest(); } @Ignore("b/118437729") @Test public void enumField() { refactoringHelper .addInputLines( "Test.java", // "enum Test {", " ONE(\"1\", 1) {};", " private String a;", " private Test(String a, int x) {", " this.a = a;", " }", " String a() {", " return a;", " }", "}") .addOutputLines( "Test.java", // "enum Test {", " ONE(\"1\") {};", " private String a;", " private Test(String a) {", " this.a = a;", " }", " String a() {", " return a;", " }", "}") .doTest(); } @Ignore("b/118437729") @Test public void onlyEnumField() { refactoringHelper .addInputLines( "Test.java", // "enum Test {", " ONE(1) {};", " private Test(int x) {", " }", "}") .addOutputLines( "Test.java", // "enum Test {", " ONE() {};", " private Test() {", " }", "}") .doTest(); } @Test public void sideEffectFix() { refactoringHelper .addInputLines( "Test.java", // "class Test {", " private static final int[] xs = new int[0];", "}") .addOutputLines( "Test.java", // "class Test {", "}") .doTest(); } @Test public void sideEffectFieldFix() { refactoringHelper .addInputLines( "Test.java", // "class Test {", " private int x = 1;", " public int a() {", " x = a();", " return 1;", " }", "}") .addOutputLines( "Test.java", // "class Test {", " public int a() {", " a();", " return 1;", " }", "}") .setFixChooser(FixChoosers.SECOND) .doTest(); } @Test public void blockFixTest() { refactoringHelper .addInputLines( "Test.java", // "class Test {", " void foo() {", " int a = 1;", " if (hashCode() > 0)", " a = 2;", " }", "}") .addOutputLines( "Test.java", // "class Test {", " void foo() {", " if (hashCode() > 0) {}", " }", "}") .doTest(); } @Test public void unusedAssignment() { helper .addSourceLines( "Test.java", "package unusedvars;", "public class Test {", " public void test() {", " Integer a = 1;", " a.hashCode();", " // BUG: Diagnostic contains: assignment to", " a = 2;", " }", "}") .doTest(); } @Test public void unusedAssignment_messages() { helper .addSourceLines( "Test.java", "package unusedvars;", "public class Test {", " public int test() {", " // BUG: Diagnostic contains: This assignment to the local variable", " int a = 1;", " a = 2;", " int b = a;", " int c = b;", " // BUG: Diagnostic contains: This assignment to the local variable", " b = 2;", " b = 3;", " return b + c;", " }", "}") .doTest(); } @Test public void unusedAssignment_nulledOut_noWarning() { helper .addSourceLines( "Test.java", "package unusedvars;", "public class Test {", " public void test() {", " Integer a = 1;", " a.hashCode();", " a = null;", " }", "}") .doTest(); } @Test public void unusedAssignment_nulledOut_thenAssignedAgain() { refactoringHelper .addInputLines( "Test.java", "package unusedvars;", "public class Test {", " public void test() {", " Integer a = 1;", " a.hashCode();", " a = null;", " a = 2;", " }", "}") .addOutputLines( "Test.java", "package unusedvars;", "public class Test {", " public void test() {", " Integer a = 1;", " a.hashCode();", " a = null;", " }", "}") .doTest(); } @Test public void unusedAssignment_initialAssignmentNull_givesWarning() { helper .addSourceLines( "Test.java", "package unusedvars;", "public class Test {", " public void test() {", " // BUG: Diagnostic contains: assignment", " Integer a = null;", " a = 1;", " a.hashCode();", " }", "}") .doTest(); } @Test public void unusedAssignmentAfterUse() { refactoringHelper .addInputLines( "Test.java", "package unusedvars;", "public class Test {", " public void test() {", " int a = 1;", " System.out.println(a);", " a = 2;", " }", "}") .addOutputLines( "Test.java", "package unusedvars;", "public class Test {", " public void test() {", " int a = 1;", " System.out.println(a);", " }", "}") .doTest(); } @Test public void unusedAssignmentWithFinalUse() { refactoringHelper .addInputLines( "Test.java", "package unusedvars;", "public class Test {", " public void test() {", " int a = 1;", " a = 2;", " a = 3;", " System.out.println(a);", " }", "}") .addOutputLines( "Test.java", "package unusedvars;", "public class Test {", " public void test() {", " int a = 3;", " System.out.println(a);", " }", "}") .doTest(); } @Test public void assignmentUsedInExpression() { helper .addSourceLines( "Test.java", "package unusedvars;", "public class Test {", " public int test() {", " int a = 1;", " a = a * 2;", " return a;", " }", "}") .doTest(); } @Test public void assignmentToParameter() { refactoringHelper .addInputLines( "Test.java", "package unusedvars;", "public class Test {", " public void test(int a) {", " a = 2;", " }", "}") .addOutputLines( "Test.java", "package unusedvars;", "public class Test {", " public void test(int a) {", " }", "}") .doTest(); } @Test public void assignmentToParameter_thenUsed() { helper .addSourceLines( "Test.java", "package unusedvars;", "public class Test {", " public int test(int a) {", " a = 2;", " return a;", " }", "}") .doTest(); } @Test public void assignmentToEnhancedForLoop() { refactoringHelper .addInputLines( "Test.java", "package unusedvars;", "public class Test {", " public void test(Iterable<Integer> as) {", " for (int a : as) {", " System.out.println(a);", " a = 2;", " }", " }", "}") .addOutputLines( "Test.java", "package unusedvars;", "public class Test {", " public void test(Iterable<Integer> as) {", " for (int a : as) {", " System.out.println(a);", " }", " }", "}") .doTest(); } @Test public void assignmentWithinForLoop() { helper .addSourceLines( "Test.java", "public class Test {", " public void test() {", " for (int a = 0; a < 10; a = a + 1) {}", " }", "}") .doTest(); } @Test public void assignmentSeparateFromDeclaration_noComplaint() { helper .addSourceLines( "Test.java", "package unusedvars;", "public class Test {", " public void test() {", " int a;", " a = 1;", " System.out.println(a);", " }", "}") .doTest(); } @Test public void unusedAssignment_negatives() { helper .addSourceLines( "Test.java", "package unusedvars;", "public class Test {", " public int frobnicate() {", " int a = 1;", " if (hashCode() == 0) {", " a = 2;", " }", " return a;", " }", "}") .doTest(); } @Test public void exemptedMethods() { helper .addSourceLines( "Unuseds.java", "package unusedvars;", "import java.io.IOException;", "import java.io.ObjectStreamException;", "public class Unuseds implements java.io.Serializable {", " private void readObject(java.io.ObjectInputStream in) throws IOException {}", " private void writeObject(java.io.ObjectOutputStream out) throws IOException {}", " private Object readResolve() {", " return null;", " }", " private void readObjectNoData() throws ObjectStreamException {}", "}") .doTest(); } @Test public void unusedReassignment_removeSideEffectsFix() { refactoringHelper .addInputLines( "Test.java", "import java.util.ArrayList;", "import java.util.Collection;", "import java.util.List;", "import static java.util.stream.Collectors.toList;", "public class Test {", " public void f(List<List<String>> lists) {", " List<String> result =", " lists.stream().collect(ArrayList::new, Collection::addAll," + " Collection::addAll);", " result = lists.stream().collect(ArrayList::new, ArrayList::addAll," + " ArrayList::addAll);", " }", "}") .addOutputLines( "Test.java", "import java.util.ArrayList;", "import java.util.Collection;", "import java.util.List;", "import static java.util.stream.Collectors.toList;", "public class Test {", " public void f(List<List<String>> lists) {", " }", "}") .setFixChooser(FixChoosers.FIRST) .doTest(); } @Test public void unusedReassignment_keepSideEffectsFix() { refactoringHelper .addInputLines( "Test.java", "import java.util.ArrayList;", "import java.util.Collection;", "import java.util.List;", "import static java.util.stream.Collectors.toList;", "public class Test {", " public void f(List<List<String>> lists) {", " List<String> result =", " lists.stream().collect(ArrayList::new, Collection::addAll," + " Collection::addAll);", " result = lists.stream().collect(ArrayList::new, ArrayList::addAll," + " ArrayList::addAll);", " }", "}") .addOutputLines( "Test.java", "import java.util.ArrayList;", "import java.util.Collection;", "import java.util.List;", "import static java.util.stream.Collectors.toList;", "public class Test {", " public void f(List<List<String>> lists) {", " lists.stream().collect(ArrayList::new, Collection::addAll, Collection::addAll);", " lists.stream().collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll);", " }", "}") .setFixChooser(FixChoosers.SECOND) .doTest(); } }
apache-2.0
iAmGio/jrfl
src/eu/iamgio/jrfl/program/commands/PluginsCommand.java
1403
package eu.iamgio.jrfl.program.commands; import eu.iamgio.jrfl.Console; import eu.iamgio.jrfl.api.JrflPlugin; import eu.iamgio.jrfl.api.commands.Command; import eu.iamgio.jrfl.api.commands.completion.PluginsTabCompletion; import eu.iamgio.jrfl.plugins.Plugins; /** * @author Gio */ public class PluginsCommand extends Command { public PluginsCommand() { super("plugins", "[Native] Shows the loaded plugins", "plugins [%plugin]"); setArgCompletion(0, new PluginsTabCompletion()); } @Override public void onCommand(String[] args) { Console console = Console.getConsole(); if(args.length == 1) { JrflPlugin plugin = Plugins.byName(args[0]); if(plugin == null) { console.sendMessage("§cInvalid plugin"); return; } console.sendMessage("§2Name: §a" + plugin.getName() + "\n§2Version: §a" + plugin.getVersion() + "\n§2Description: §a" + plugin.getDescription() + "\n§a" + plugin.getClass().getName()); } else { console.sendMessage("Plugins (" + Plugins.getPlugins().size() + "): "); for(JrflPlugin plugin : Plugins.getPlugins()) { console.sendMessage(" " + plugin.toString() + " - " + plugin.getDescription(), false); } } } }
apache-2.0
AlanCheen/Utils
utils/src/main/java/me/yifeiyuan/utils/PatternUtil.java
1254
/* * Copyright (C) 2015, 程序亦非猿 * * 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 me.yifeiyuan.utils; import android.support.annotation.NonNull; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by 程序亦非猿 on 16/1/18. */ public class PatternUtil { private PatternUtil() { //no instance throw new AssertionError("No instances."); } /** * 判断是否是手机号码 13 14 15 17 18 开头 * @param phone * @return 是否是手机号 */ public static boolean isMobile(@NonNull String phone) { Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); Matcher m = p.matcher(phone); return m.matches(); } }
apache-2.0
devcon5io/pageobjects
src/main/java/io/devcon5/pageobjects/measure/ResponseTimeRecording.java
3096
/* * Copyright 2015-2016 DevCon5 GmbH, info@devcon5.ch * * 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.devcon5.pageobjects.measure; import static org.slf4j.LoggerFactory.getLogger; import java.util.List; import java.util.Map; import io.inkstand.scribble.rules.ExternalResource; import org.slf4j.Logger; /** * JUnit Rule to record response times. Use this rule if your page object model uses the transaction support * to record response times. */ public class ResponseTimeRecording extends ExternalResource { private static final Logger LOG = getLogger(ResponseTimeRecording.class); private final ResponseTimeCollector collector = new ResponseTimeCollector(); private boolean clearGlobalTable = true; private boolean printTransactions = true; /** * Sets whether to reset the global response time table after the test. Default is true. See {@link ResponseTimes#clear()} * for more information * @param clearGlobalTable * true if table should be cleared (default) or false if not * @return * this rule */ public ResponseTimeRecording clearGlobalTable(final boolean clearGlobalTable) { this.clearGlobalTable = clearGlobalTable; return this; } /** * Sets whether to print out the recorded transactions at the end of the test. * @param printTransactions * true if the transactions should be displayed (default), false if not * @return * this rule */ public ResponseTimeRecording printTransactions(final boolean printTransactions) { this.printTransactions = printTransactions; return this; } @Override protected void beforeClass() throws Throwable { before(); } @Override protected void before() throws Throwable { collector.startCollecting(); } @Override protected void afterClass() { after(); } @Override protected void after() { collector.stopCollecting(); if(printTransactions){ LOG.info("Listing transactions"); Map<String, List<ResponseTime>> responseTimes = ResponseTimes.getResponseTimes(); for(Map.Entry<String, List<ResponseTime>> e : responseTimes.entrySet()){ LOG.info("Transaction {}", e.getKey()); for(ResponseTime rt : e.getValue()){ LOG.info("\tstart={} duration={}", rt.getStart(), rt.getDuration()); } } } if(clearGlobalTable) { ResponseTimes.clear(); } } }
apache-2.0
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/api/validation/check/entry/DescriptionCheck.java
1245
package uk.ac.ebi.embl.api.validation.check.entry; import org.apache.commons.lang3.StringUtils; import uk.ac.ebi.embl.api.entry.Entry; import uk.ac.ebi.embl.api.validation.ValidationEngineException; import uk.ac.ebi.embl.api.validation.ValidationResult; import uk.ac.ebi.embl.api.validation.ValidationScope; import uk.ac.ebi.embl.api.validation.annotation.ExcludeScope; @ExcludeScope(validationScope = {ValidationScope.ARRAYEXPRESS, ValidationScope.ASSEMBLY_CHROMOSOME, ValidationScope.ASSEMBLY_CONTIG, ValidationScope.ASSEMBLY_MASTER, ValidationScope.ASSEMBLY_SCAFFOLD, ValidationScope.ASSEMBLY_TRANSCRIPTOME, ValidationScope.NCBI, ValidationScope.NCBI_MASTER}) public class DescriptionCheck extends EntryValidationCheck { private final static String INVALID_DE_LINE = "templateInvalidDescription"; @Override public ValidationResult check(Entry entry) throws ValidationEngineException { if (entry == null) { return result; } if( entry.getDescription() == null || StringUtils.isBlank(entry.getDescription().getText()) || entry.getDescription().getText().length() < 10) { reportError(entry.getOrigin(), INVALID_DE_LINE); } return result; } }
apache-2.0
apache/incubator-systemml
src/main/java/org/apache/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java
78999
/* * 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.sysds.hops.rewrite; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Set; import org.apache.sysds.hops.AggBinaryOp; import org.apache.sysds.hops.AggUnaryOp; import org.apache.sysds.hops.BinaryOp; import org.apache.sysds.hops.DataGenOp; import org.apache.sysds.hops.Hop; import org.apache.sysds.hops.IndexingOp; import org.apache.sysds.hops.LiteralOp; import org.apache.sysds.hops.NaryOp; import org.apache.sysds.hops.OptimizerUtils; import org.apache.sysds.hops.ParameterizedBuiltinOp; import org.apache.sysds.hops.ReorgOp; import org.apache.sysds.hops.TernaryOp; import org.apache.sysds.hops.UnaryOp; import org.apache.sysds.common.Types.AggOp; import org.apache.sysds.common.Types.Direction; import org.apache.sysds.common.Types.OpOp1; import org.apache.sysds.common.Types.OpOp2; import org.apache.sysds.common.Types.OpOp3; import org.apache.sysds.common.Types.OpOpDG; import org.apache.sysds.common.Types.OpOpN; import org.apache.sysds.common.Types.ParamBuiltinOp; import org.apache.sysds.common.Types.ReOrgOp; import org.apache.sysds.parser.DataExpression; import org.apache.sysds.parser.Statement; import org.apache.sysds.common.Types.DataType; import org.apache.sysds.common.Types.ValueType; /** * Rule: Algebraic Simplifications. Simplifies binary expressions * in terms of two major purposes: (1) rewrite binary operations * to unary operations when possible (in CP this reduces the memory * estimate, in MR this allows map-only operations and hence prevents * unnecessary shuffle and sort) and (2) remove binary operations that * are in itself are unnecessary (e.g., *1 and /1). * */ public class RewriteAlgebraicSimplificationStatic extends HopRewriteRule { //valid aggregation operation types for rowOp to colOp conversions and vice versa private static final AggOp[] LOOKUP_VALID_ROW_COL_AGGREGATE = new AggOp[] { AggOp.SUM, AggOp.SUM_SQ, AggOp.MIN, AggOp.MAX, AggOp.MEAN, AggOp.VAR}; //valid binary operations for distributive and associate reorderings private static final OpOp2[] LOOKUP_VALID_DISTRIBUTIVE_BINARY = new OpOp2[] {OpOp2.PLUS, OpOp2.MINUS}; private static final OpOp2[] LOOKUP_VALID_ASSOCIATIVE_BINARY = new OpOp2[] {OpOp2.PLUS, OpOp2.MULT}; //valid binary operations for scalar operations private static final OpOp2[] LOOKUP_VALID_SCALAR_BINARY = new OpOp2[] {OpOp2.AND, OpOp2.DIV, OpOp2.EQUAL, OpOp2.GREATER, OpOp2.GREATEREQUAL, OpOp2.INTDIV, OpOp2.LESS, OpOp2.LESSEQUAL, OpOp2.LOG, OpOp2.MAX, OpOp2.MIN, OpOp2.MINUS, OpOp2.MODULUS, OpOp2.MULT, OpOp2.NOTEQUAL, OpOp2.OR, OpOp2.PLUS, OpOp2.POW}; @Override public ArrayList<Hop> rewriteHopDAGs(ArrayList<Hop> roots, ProgramRewriteStatus state) { if( roots == null ) return roots; //one pass rewrite-descend (rewrite created pattern) for( Hop h : roots ) rule_AlgebraicSimplification( h, false ); Hop.resetVisitStatus(roots, true); //one pass descend-rewrite (for rollup) for( Hop h : roots ) rule_AlgebraicSimplification( h, true ); Hop.resetVisitStatus(roots, true); return roots; } @Override public Hop rewriteHopDAG(Hop root, ProgramRewriteStatus state) { if( root == null ) return root; //one pass rewrite-descend (rewrite created pattern) rule_AlgebraicSimplification( root, false ); root.resetVisitStatus(); //one pass descend-rewrite (for rollup) rule_AlgebraicSimplification( root, true ); return root; } /** * Note: X/y -> X * 1/y would be useful because * cheaper than / and sparsesafe; however, * (1) the results would be not exactly the same (2 rounds instead of 1) and (2) it should * come before constant folding while the other simplifications should come after constant * folding. Hence, not applied yet. * * @param hop high-level operator * @param descendFirst if process children recursively first */ private void rule_AlgebraicSimplification(Hop hop, boolean descendFirst) { if(hop.isVisited()) return; //recursively process children for( int i=0; i<hop.getInput().size(); i++) { Hop hi = hop.getInput().get(i); //process childs recursively first (to allow roll-up) if( descendFirst ) rule_AlgebraicSimplification(hi, descendFirst); //see below //apply actual simplification rewrites (of childs incl checks) hi = removeUnnecessaryVectorizeOperation(hi); //e.g., matrix(1,nrow(X),ncol(X))/X -> 1/X hi = removeUnnecessaryBinaryOperation(hop, hi, i); //e.g., X*1 -> X (dep: should come after rm unnecessary vectorize) hi = fuseDatagenAndBinaryOperation(hi); //e.g., rand(min=-1,max=1)*7 -> rand(min=-7,max=7) hi = fuseDatagenAndMinusOperation(hi); //e.g., -(rand(min=-2,max=1)) -> rand(min=-1,max=2) hi = foldMultipleAppendOperations(hi); //e.g., cbind(X,cbind(Y,Z)) -> cbind(X,Y,Z) hi = simplifyBinaryToUnaryOperation(hop, hi, i); //e.g., X*X -> X^2 (pow2), X+X -> X*2, (X>0)-(X<0) -> sign(X) hi = canonicalizeMatrixMultScalarAdd(hi); //e.g., eps+U%*%t(V) -> U%*%t(V)+eps, U%*%t(V)-eps -> U%*%t(V)+(-eps) hi = simplifyCTableWithConstMatrixInputs(hi); //e.g., table(X, matrix(1,...)) -> table(X, 1) hi = removeUnnecessaryCTable(hop, hi, i); //e.g., sum(table(X, 1)) -> nrow(X) and sum(table(1, Y)) -> nrow(Y) and sum(table(X, Y)) -> nrow(X) hi = simplifyReverseOperation(hop, hi, i); //e.g., table(seq(1,nrow(X),1),seq(nrow(X),1,-1)) %*% X -> rev(X) if(OptimizerUtils.ALLOW_OPERATOR_FUSION) hi = simplifyMultiBinaryToBinaryOperation(hi); //e.g., 1-X*Y -> X 1-* Y hi = simplifyDistributiveBinaryOperation(hop, hi, i);//e.g., (X-Y*X) -> (1-Y)*X hi = simplifyBushyBinaryOperation(hop, hi, i); //e.g., (X*(Y*(Z%*%v))) -> (X*Y)*(Z%*%v) hi = simplifyUnaryAggReorgOperation(hop, hi, i); //e.g., sum(t(X)) -> sum(X) hi = removeUnnecessaryAggregates(hi); //e.g., sum(rowSums(X)) -> sum(X) hi = simplifyBinaryMatrixScalarOperation(hop, hi, i);//e.g., as.scalar(X*s) -> as.scalar(X)*s; hi = pushdownUnaryAggTransposeOperation(hop, hi, i); //e.g., colSums(t(X)) -> t(rowSums(X)) hi = pushdownCSETransposeScalarOperation(hop, hi, i);//e.g., a=t(X), b=t(X^2) -> a=t(X), b=t(X)^2 for CSE t(X) hi = pushdownSumBinaryMult(hop, hi, i); //e.g., sum(lambda*X) -> lambda*sum(X) hi = simplifyUnaryPPredOperation(hop, hi, i); //e.g., abs(ppred()) -> ppred(), others: round, ceil, floor hi = simplifyTransposedAppend(hop, hi, i); //e.g., t(cbind(t(A),t(B))) -> rbind(A,B); if(OptimizerUtils.ALLOW_OPERATOR_FUSION) hi = fuseBinarySubDAGToUnaryOperation(hop, hi, i); //e.g., X*(1-X)-> sprop(X) || 1/(1+exp(-X)) -> sigmoid(X) || X*(X>0) -> selp(X) hi = simplifyTraceMatrixMult(hop, hi, i); //e.g., trace(X%*%Y)->sum(X*t(Y)); hi = simplifySlicedMatrixMult(hop, hi, i); //e.g., (X%*%Y)[1,1] -> X[1,] %*% Y[,1]; hi = simplifyConstantSort(hop, hi, i); //e.g., order(matrix())->matrix/seq; hi = simplifyOrderedSort(hop, hi, i); //e.g., order(matrix())->seq; hi = fuseOrderOperationChain(hi); //e.g., order(order(X,2),1) -> order(X,(12)) hi = removeUnnecessaryReorgOperation(hop, hi, i); //e.g., t(t(X))->X; rev(rev(X))->X potentially introduced by other rewrites hi = removeUnnecessaryRemoveEmpty(hop, hi, i); //e.g., nrow(removeEmpty(A)) -> nnz(A) iff col vector hi = simplifyTransposeAggBinBinaryChains(hop, hi, i);//e.g., t(t(A)%*%t(B)+C) -> B%*%A+t(C) hi = simplifyReplaceZeroOperation(hop, hi, i); //e.g., X + (X==0) * s -> replace(X, 0, s) hi = removeUnnecessaryMinus(hop, hi, i); //e.g., -(-X)->X; potentially introduced by simplify binary or dyn rewrites hi = simplifyGroupedAggregate(hi); //e.g., aggregate(target=X,groups=y,fn="count") -> aggregate(target=y,groups=y,fn="count") if(OptimizerUtils.ALLOW_OPERATOR_FUSION) { hi = fuseMinusNzBinaryOperation(hop, hi, i); //e.g., X-mean*ppred(X,0,!=) -> X -nz mean hi = fuseLogNzUnaryOperation(hop, hi, i); //e.g., ppred(X,0,"!=")*log(X) -> log_nz(X) hi = fuseLogNzBinaryOperation(hop, hi, i); //e.g., ppred(X,0,"!=")*log(X,0.5) -> log_nz(X,0.5) } hi = simplifyOuterSeqExpand(hop, hi, i); //e.g., outer(v, seq(1,m), "==") -> rexpand(v, max=m, dir=row, ignore=true, cast=false) hi = simplifyBinaryComparisonChain(hop, hi, i); //e.g., outer(v1,v2,"==")==1 -> outer(v1,v2,"=="), outer(v1,v2,"==")==0 -> outer(v1,v2,"!="), hi = simplifyCumsumColOrFullAggregates(hi); //e.g., colSums(cumsum(X)) -> cumSums(X*seq(nrow(X),1)) hi = simplifyCumsumReverse(hop, hi, i); //e.g., rev(cumsum(rev(X))) -> X + colSums(X) - cumsum(X) //hi = removeUnecessaryPPred(hop, hi, i); //e.g., ppred(X,X,"==")->matrix(1,rows=nrow(X),cols=ncol(X)) //process childs recursively after rewrites (to investigate pattern newly created by rewrites) if( !descendFirst ) rule_AlgebraicSimplification(hi, descendFirst); } hop.setVisited(); } private static Hop removeUnnecessaryVectorizeOperation(Hop hi) { //applies to all binary matrix operations, if one input is unnecessarily vectorized if( hi instanceof BinaryOp && hi.getDataType()==DataType.MATRIX && ((BinaryOp)hi).supportsMatrixScalarOperations() ) { BinaryOp bop = (BinaryOp)hi; Hop left = bop.getInput().get(0); Hop right = bop.getInput().get(1); //NOTE: these rewrites of binary cell operations need to be aware that right is //potentially a vector but the result is of the size of left //TODO move to dynamic rewrites (since size dependent to account for mv binary cell and outer operations) if( !(left.getDim1()>1 && left.getDim2()==1 && right.getDim1()==1 && right.getDim2()>1) ) // no outer { //check and remove right vectorized scalar if( left.getDataType() == DataType.MATRIX && right instanceof DataGenOp ) { DataGenOp dright = (DataGenOp) right; if( dright.getOp()==OpOpDG.RAND && dright.hasConstantValue() ) { Hop drightIn = dright.getInput().get(dright.getParamIndex(DataExpression.RAND_MIN)); HopRewriteUtils.replaceChildReference(bop, dright, drightIn, 1); HopRewriteUtils.cleanupUnreferenced(dright); LOG.debug("Applied removeUnnecessaryVectorizeOperation1"); } } //check and remove left vectorized scalar else if( right.getDataType() == DataType.MATRIX && left instanceof DataGenOp ) { DataGenOp dleft = (DataGenOp) left; if( dleft.getOp()==OpOpDG.RAND && dleft.hasConstantValue() && (left.getDim2()==1 || right.getDim2()>1) && (left.getDim1()==1 || right.getDim1()>1)) { Hop dleftIn = dleft.getInput().get(dleft.getParamIndex(DataExpression.RAND_MIN)); HopRewriteUtils.replaceChildReference(bop, dleft, dleftIn, 0); HopRewriteUtils.cleanupUnreferenced(dleft); LOG.debug("Applied removeUnnecessaryVectorizeOperation2"); } } //Note: we applied this rewrite to at most one side in order to keep the //output semantically equivalent. However, future extensions might consider //to remove vectors from both side, compute the binary op on scalars and //finally feed it into a datagenop of the original dimensions. } } return hi; } /** * handle removal of unnecessary binary operations * * X/1 or X*1 or 1*X or X-0 -> X * -1*X or X*-1-> -X * * @param parent parent high-level operator * @param hi high-level operator * @param pos position * @return high-level operator */ private static Hop removeUnnecessaryBinaryOperation( Hop parent, Hop hi, int pos ) { if( hi instanceof BinaryOp ) { BinaryOp bop = (BinaryOp)hi; Hop left = bop.getInput().get(0); Hop right = bop.getInput().get(1); //X/1 or X*1 -> X if( left.getDataType()==DataType.MATRIX && right instanceof LiteralOp && ((LiteralOp)right).getDoubleValue()==1.0 ) { if( bop.getOp()==OpOp2.DIV || bop.getOp()==OpOp2.MULT ) { HopRewriteUtils.replaceChildReference(parent, bop, left, pos); hi = left; LOG.debug("Applied removeUnnecessaryBinaryOperation1 (line "+bop.getBeginLine()+")"); } } //X-0 -> X else if( left.getDataType()==DataType.MATRIX && right instanceof LiteralOp && ((LiteralOp)right).getDoubleValue()==0.0 ) { if( bop.getOp()==OpOp2.MINUS ) { HopRewriteUtils.replaceChildReference(parent, bop, left, pos); hi = left; LOG.debug("Applied removeUnnecessaryBinaryOperation2 (line "+bop.getBeginLine()+")"); } } //1*X -> X else if( right.getDataType()==DataType.MATRIX && left instanceof LiteralOp && ((LiteralOp)left).getDoubleValue()==1.0 ) { if( bop.getOp()==OpOp2.MULT ) { HopRewriteUtils.replaceChildReference(parent, bop, right, pos); hi = right; LOG.debug("Applied removeUnnecessaryBinaryOperation3 (line "+bop.getBeginLine()+")"); } } //-1*X -> -X //note: this rewrite is necessary since the new antlr parser always converts //-X to -1*X due to mechanical reasons else if( right.getDataType()==DataType.MATRIX && left instanceof LiteralOp && ((LiteralOp)left).getDoubleValue()==-1.0 ) { if( bop.getOp()==OpOp2.MULT ) { bop.setOp(OpOp2.MINUS); HopRewriteUtils.replaceChildReference(bop, left, new LiteralOp(0), 0); hi = bop; LOG.debug("Applied removeUnnecessaryBinaryOperation4 (line "+bop.getBeginLine()+")"); } } //X*-1 -> -X (see comment above) else if( left.getDataType()==DataType.MATRIX && right instanceof LiteralOp && ((LiteralOp)right).getDoubleValue()==-1.0 ) { if( bop.getOp()==OpOp2.MULT ) { bop.setOp(OpOp2.MINUS); HopRewriteUtils.removeChildReferenceByPos(bop, right, 1); HopRewriteUtils.addChildReference(bop, new LiteralOp(0), 0); hi = bop; LOG.debug("Applied removeUnnecessaryBinaryOperation5 (line "+bop.getBeginLine()+")"); } } } return hi; } /** * Handle removal of unnecessary binary operations over rand data * * rand*7 -> rand(min*7,max*7); rand+7 -> rand(min+7,max+7); rand-7 -> rand(min+(-7),max+(-7)) * 7*rand -> rand(min*7,max*7); 7+rand -> rand(min+7,max+7); * * @param hi high-order operation * @return high-level operator */ @SuppressWarnings("incomplete-switch") private static Hop fuseDatagenAndBinaryOperation( Hop hi ) { if( hi instanceof BinaryOp ) { BinaryOp bop = (BinaryOp)hi; Hop left = bop.getInput().get(0); Hop right = bop.getInput().get(1); //NOTE: rewrite not applied if more than one datagen consumer because this would lead to //the creation of multiple datagen ops and thus potentially different results if seed not specified) //left input rand and hence output matrix double, right scalar literal if( HopRewriteUtils.isDataGenOp(left, OpOpDG.RAND) && right instanceof LiteralOp && left.getParent().size()==1 ) { DataGenOp inputGen = (DataGenOp)left; Hop pdf = inputGen.getInput(DataExpression.RAND_PDF); Hop min = inputGen.getInput(DataExpression.RAND_MIN); Hop max = inputGen.getInput(DataExpression.RAND_MAX); double sval = ((LiteralOp)right).getDoubleValue(); boolean pdfUniform = pdf instanceof LiteralOp && DataExpression.RAND_PDF_UNIFORM.equals(((LiteralOp)pdf).getStringValue()); if( HopRewriteUtils.isBinary(bop, OpOp2.MULT, OpOp2.PLUS, OpOp2.MINUS, OpOp2.DIV) && min instanceof LiteralOp && max instanceof LiteralOp && pdfUniform ) { //create fused data gen operator DataGenOp gen = null; switch( bop.getOp() ) { //fuse via scale and shift case MULT: gen = HopRewriteUtils.copyDataGenOp(inputGen, sval, 0); break; case PLUS: case MINUS: gen = HopRewriteUtils.copyDataGenOp(inputGen, 1, sval * ((bop.getOp()==OpOp2.MINUS)?-1:1)); break; case DIV: gen = HopRewriteUtils.copyDataGenOp(inputGen, 1/sval, 0); break; } //rewire all parents (avoid anomalies with replicated datagen) List<Hop> parents = new ArrayList<>(bop.getParent()); for( Hop p : parents ) HopRewriteUtils.replaceChildReference(p, bop, gen); hi = gen; LOG.debug("Applied fuseDatagenAndBinaryOperation1 " + "("+bop.getFilename()+", line "+bop.getBeginLine()+")."); } } //right input rand and hence output matrix double, left scalar literal else if( right instanceof DataGenOp && ((DataGenOp)right).getOp()==OpOpDG.RAND && left instanceof LiteralOp && right.getParent().size()==1 ) { DataGenOp inputGen = (DataGenOp)right; Hop pdf = inputGen.getInput(DataExpression.RAND_PDF); Hop min = inputGen.getInput(DataExpression.RAND_MIN); Hop max = inputGen.getInput(DataExpression.RAND_MAX); double sval = ((LiteralOp)left).getDoubleValue(); boolean pdfUniform = pdf instanceof LiteralOp && DataExpression.RAND_PDF_UNIFORM.equals(((LiteralOp)pdf).getStringValue()); if( (bop.getOp()==OpOp2.MULT || bop.getOp()==OpOp2.PLUS) && min instanceof LiteralOp && max instanceof LiteralOp && pdfUniform ) { //create fused data gen operator DataGenOp gen = null; if( bop.getOp()==OpOp2.MULT ) gen = HopRewriteUtils.copyDataGenOp(inputGen, sval, 0); else { //OpOp2.PLUS gen = HopRewriteUtils.copyDataGenOp(inputGen, 1, sval); } //rewire all parents (avoid anomalies with replicated datagen) List<Hop> parents = new ArrayList<>(bop.getParent()); for( Hop p : parents ) HopRewriteUtils.replaceChildReference(p, bop, gen); hi = gen; LOG.debug("Applied fuseDatagenAndBinaryOperation2 " + "("+bop.getFilename()+", line "+bop.getBeginLine()+")."); } } //left input rand and hence output matrix double, right scalar variable else if( HopRewriteUtils.isDataGenOp(left, OpOpDG.RAND) && right.getDataType().isScalar() && left.getParent().size()==1 ) { DataGenOp gen = (DataGenOp)left; Hop min = gen.getInput(DataExpression.RAND_MIN); Hop max = gen.getInput(DataExpression.RAND_MAX); Hop pdf = gen.getInput(DataExpression.RAND_PDF); boolean pdfUniform = pdf instanceof LiteralOp && DataExpression.RAND_PDF_UNIFORM.equals(((LiteralOp)pdf).getStringValue()); if( HopRewriteUtils.isBinary(bop, OpOp2.PLUS) && HopRewriteUtils.isLiteralOfValue(min, 0) && HopRewriteUtils.isLiteralOfValue(max, 0) ) { gen.setInput(DataExpression.RAND_MIN, right, true); gen.setInput(DataExpression.RAND_MAX, right, true); //rewire all parents (avoid anomalies with replicated datagen) List<Hop> parents = new ArrayList<>(bop.getParent()); for( Hop p : parents ) HopRewriteUtils.replaceChildReference(p, bop, gen); hi = gen; LOG.debug("Applied fuseDatagenAndBinaryOperation3a " + "("+bop.getFilename()+", line "+bop.getBeginLine()+")."); } else if( HopRewriteUtils.isBinary(bop, OpOp2.MULT) && ((HopRewriteUtils.isLiteralOfValue(min, 0) && pdfUniform) || HopRewriteUtils.isLiteralOfValue(min, 1)) && HopRewriteUtils.isLiteralOfValue(max, 1) ) { if( HopRewriteUtils.isLiteralOfValue(min, 1) ) gen.setInput(DataExpression.RAND_MIN, right, true); gen.setInput(DataExpression.RAND_MAX, right, true); //rewire all parents (avoid anomalies with replicated datagen) List<Hop> parents = new ArrayList<>(bop.getParent()); for( Hop p : parents ) HopRewriteUtils.replaceChildReference(p, bop, gen); hi = gen; LOG.debug("Applied fuseDatagenAndBinaryOperation3b " + "("+bop.getFilename()+", line "+bop.getBeginLine()+")."); } } } return hi; } private static Hop fuseDatagenAndMinusOperation( Hop hi ) { if( hi instanceof BinaryOp ) { BinaryOp bop = (BinaryOp)hi; Hop left = bop.getInput().get(0); Hop right = bop.getInput().get(1); if( right instanceof DataGenOp && ((DataGenOp)right).getOp()==OpOpDG.RAND && left instanceof LiteralOp && ((LiteralOp)left).getDoubleValue()==0.0 ) { DataGenOp inputGen = (DataGenOp)right; HashMap<String,Integer> params = inputGen.getParamIndexMap(); Hop pdf = right.getInput().get(params.get(DataExpression.RAND_PDF)); int ixMin = params.get(DataExpression.RAND_MIN); int ixMax = params.get(DataExpression.RAND_MAX); Hop min = right.getInput().get(ixMin); Hop max = right.getInput().get(ixMax); //apply rewrite under additional conditions (for simplicity) if( inputGen.getParent().size()==1 && min instanceof LiteralOp && max instanceof LiteralOp && pdf instanceof LiteralOp && DataExpression.RAND_PDF_UNIFORM.equals(((LiteralOp)pdf).getStringValue()) ) { //exchange and *-1 (special case 0 stays 0 instead of -0 for consistency) double newMinVal = (((LiteralOp)max).getDoubleValue()==0)?0:(-1 * ((LiteralOp)max).getDoubleValue()); double newMaxVal = (((LiteralOp)min).getDoubleValue()==0)?0:(-1 * ((LiteralOp)min).getDoubleValue()); Hop newMin = new LiteralOp(newMinVal); Hop newMax = new LiteralOp(newMaxVal); HopRewriteUtils.removeChildReferenceByPos(inputGen, min, ixMin); HopRewriteUtils.addChildReference(inputGen, newMin, ixMin); HopRewriteUtils.removeChildReferenceByPos(inputGen, max, ixMax); HopRewriteUtils.addChildReference(inputGen, newMax, ixMax); //rewire all parents (avoid anomalies with replicated datagen) List<Hop> parents = new ArrayList<>(bop.getParent()); for( Hop p : parents ) HopRewriteUtils.replaceChildReference(p, bop, inputGen); hi = inputGen; LOG.debug("Applied fuseDatagenAndMinusOperation (line "+bop.getBeginLine()+")."); } } } return hi; } private static Hop foldMultipleAppendOperations(Hop hi) { if( hi.getDataType().isMatrix() //no string appends or frames && (HopRewriteUtils.isBinary(hi, OpOp2.CBIND, OpOp2.RBIND) || HopRewriteUtils.isNary(hi, OpOpN.CBIND, OpOpN.RBIND)) ) { OpOp2 bop = (hi instanceof BinaryOp) ? ((BinaryOp)hi).getOp() : OpOp2.valueOf(((NaryOp)hi).getOp().name()); OpOpN nop = (hi instanceof NaryOp) ? ((NaryOp)hi).getOp() : OpOpN.valueOf(((BinaryOp)hi).getOp().name()); boolean converged = false; while( !converged ) { //get first matching cbind or rbind Hop first = hi.getInput().stream() .filter(h -> HopRewriteUtils.isBinary(h, bop) || HopRewriteUtils.isNary(h, nop)) .findFirst().orElse(null); //replace current op with new nary cbind/rbind if( first != null && first.getParent().size()==1 ) { //construct new list of inputs (in original order) ArrayList<Hop> linputs = new ArrayList<>(); for(Hop in : hi.getInput()) if( in == first ) linputs.addAll(first.getInput()); else linputs.add(in); Hop hnew = HopRewriteUtils.createNary(nop, linputs.toArray(new Hop[0])); //clear dangling references HopRewriteUtils.removeAllChildReferences(hi); HopRewriteUtils.removeAllChildReferences(first); //rewire all parents (avoid anomalies with refs to hi) List<Hop> parents = new ArrayList<>(hi.getParent()); for( Hop p : parents ) HopRewriteUtils.replaceChildReference(p, hi, hnew); hi = hnew; LOG.debug("Applied foldMultipleAppendOperations (line "+hi.getBeginLine()+")."); } else { converged = true; } } } return hi; } /** * Handle simplification of binary operations (relies on previous common subexpression elimination). * At the same time this servers as a canonicalization for more complex rewrites. * * X+X -> X*2, X*X -> X^2, (X>0)-(X<0) -> sign(X) * * @param parent parent high-level operator * @param hi high-level operator * @param pos position * @return high-level operator */ private static Hop simplifyBinaryToUnaryOperation( Hop parent, Hop hi, int pos ) { if( hi instanceof BinaryOp ) { BinaryOp bop = (BinaryOp)hi; Hop left = hi.getInput().get(0); Hop right = hi.getInput().get(1); //patterns: X+X -> X*2, X*X -> X^2, if( left == right && left.getDataType()==DataType.MATRIX ) { //note: we simplify this to unary operations first (less mem and better MR plan), //however, we later compile specific LOPS for X*2 and X^2 if( bop.getOp()==OpOp2.PLUS ) //X+X -> X*2 { bop.setOp(OpOp2.MULT); HopRewriteUtils.replaceChildReference(hi, right, new LiteralOp(2), 1); LOG.debug("Applied simplifyBinaryToUnaryOperation1 (line "+hi.getBeginLine()+")."); } else if ( bop.getOp()==OpOp2.MULT ) //X*X -> X^2 { bop.setOp(OpOp2.POW); HopRewriteUtils.replaceChildReference(hi, right, new LiteralOp(2), 1); LOG.debug("Applied simplifyBinaryToUnaryOperation2 (line "+hi.getBeginLine()+")."); } } //patterns: (X>0)-(X<0) -> sign(X) else if( bop.getOp() == OpOp2.MINUS && HopRewriteUtils.isBinary(left, OpOp2.GREATER) && HopRewriteUtils.isBinary(right, OpOp2.LESS) && left.getInput().get(0) == right.getInput().get(0) && left.getInput().get(1) instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)left.getInput().get(1))==0 && right.getInput().get(1) instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)right.getInput().get(1))==0 ) { UnaryOp uop = HopRewriteUtils.createUnary(left.getInput().get(0), OpOp1.SIGN); HopRewriteUtils.replaceChildReference(parent, hi, uop, pos); HopRewriteUtils.cleanupUnreferenced(hi, left, right); hi = uop; LOG.debug("Applied simplifyBinaryToUnaryOperation3 (line "+hi.getBeginLine()+")."); } } return hi; } /** * Rewrite to canonicalize all patterns like U%*%V+eps, eps+U%*%V, and * U%*%V-eps into the common representation U%*%V+s which simplifies * subsequent rewrites (e.g., wdivmm or wcemm with epsilon). * * @param hi high-level operator * @return high-level operator */ private static Hop canonicalizeMatrixMultScalarAdd( Hop hi ) { //pattern: binary operation (+ or -) of matrix mult and scalar if( hi instanceof BinaryOp ) { BinaryOp bop = (BinaryOp)hi; Hop left = hi.getInput().get(0); Hop right = hi.getInput().get(1); //pattern: (eps + U%*%V) -> (U%*%V+eps) if( left.getDataType().isScalar() && right instanceof AggBinaryOp && bop.getOp()==OpOp2.PLUS ) { HopRewriteUtils.removeAllChildReferences(bop); HopRewriteUtils.addChildReference(bop, right, 0); HopRewriteUtils.addChildReference(bop, left, 1); LOG.debug("Applied canonicalizeMatrixMultScalarAdd1 (line "+hi.getBeginLine()+")."); } //pattern: (U%*%V - eps) -> (U%*%V + (-eps)) else if( right.getDataType().isScalar() && left instanceof AggBinaryOp && bop.getOp() == OpOp2.MINUS ) { bop.setOp(OpOp2.PLUS); HopRewriteUtils.replaceChildReference(bop, right, HopRewriteUtils.createBinaryMinus(right), 1); LOG.debug("Applied canonicalizeMatrixMultScalarAdd2 (line "+hi.getBeginLine()+")."); } } return hi; } private static Hop simplifyCTableWithConstMatrixInputs( Hop hi ) { //pattern: table(X, matrix(1,...), matrix(7, ...)) -> table(X, 1, 7) if( HopRewriteUtils.isTernary(hi, OpOp3.CTABLE) ) { //note: the first input always expected to be a matrix for( int i=1; i<hi.getInput().size(); i++ ) { Hop inCurr = hi.getInput().get(i); if( HopRewriteUtils.isDataGenOpWithConstantValue(inCurr) ) { Hop inNew = ((DataGenOp)inCurr).getInput(DataExpression.RAND_MIN); HopRewriteUtils.replaceChildReference(hi, inCurr, inNew, i); LOG.debug("Applied simplifyCTableWithConstMatrixInputs" + i + " (line "+hi.getBeginLine()+")."); } } } return hi; } private static Hop removeUnnecessaryCTable( Hop parent, Hop hi, int pos ) { if ( HopRewriteUtils.isAggUnaryOp(hi, AggOp.SUM, Direction.RowCol) && HopRewriteUtils.isTernary(hi.getInput().get(0), OpOp3.CTABLE) && HopRewriteUtils.isLiteralOfValue(hi.getInput().get(0).getInput().get(2), 1.0)) { Hop matrixInput = hi.getInput().get(0).getInput().get(0); OpOp1 opcode = matrixInput.getDim2() == 1 ? OpOp1.NROW : OpOp1.LENGTH; Hop newOpLength = new UnaryOp("tmp", DataType.SCALAR, ValueType.INT64, opcode, matrixInput); HopRewriteUtils.replaceChildReference(parent, hi, newOpLength, pos); HopRewriteUtils.cleanupUnreferenced(hi, hi.getInput().get(0)); hi = newOpLength; } return hi; } /** * NOTE: this would be by definition a dynamic rewrite; however, we apply it as a static * rewrite in order to apply it before splitting dags which would hide the table information * if dimensions are not specified. * * @param parent parent high-level operator * @param hi high-level operator * @param pos position * @return high-level operator */ private static Hop simplifyReverseOperation( Hop parent, Hop hi, int pos ) { if( hi instanceof AggBinaryOp && hi.getInput().get(0) instanceof TernaryOp ) { TernaryOp top = (TernaryOp) hi.getInput().get(0); if( top.getOp()==OpOp3.CTABLE && HopRewriteUtils.isBasic1NSequence(top.getInput().get(0)) && HopRewriteUtils.isBasicN1Sequence(top.getInput().get(1)) && top.getInput().get(0).getDim1()==top.getInput().get(1).getDim1()) { ReorgOp rop = HopRewriteUtils.createReorg(hi.getInput().get(1), ReOrgOp.REV); HopRewriteUtils.replaceChildReference(parent, hi, rop, pos); HopRewriteUtils.cleanupUnreferenced(hi, top); hi = rop; LOG.debug("Applied simplifyReverseOperation."); } } return hi; } private static Hop simplifyMultiBinaryToBinaryOperation( Hop hi ) { //pattern: 1-(X*Y) --> X 1-* Y (avoid intermediate) if( HopRewriteUtils.isBinary(hi, OpOp2.MINUS) && hi.getDataType() == DataType.MATRIX && hi.getInput().get(0) instanceof LiteralOp && HopRewriteUtils.getDoubleValueSafe((LiteralOp)hi.getInput().get(0))==1 && HopRewriteUtils.isBinary(hi.getInput().get(1), OpOp2.MULT) && hi.getInput().get(1).getParent().size() == 1 ) //single consumer { BinaryOp bop = (BinaryOp)hi; Hop left = hi.getInput().get(1).getInput().get(0); Hop right = hi.getInput().get(1).getInput().get(1); //set new binaryop type and rewire inputs bop.setOp(OpOp2.MINUS1_MULT); HopRewriteUtils.removeAllChildReferences(hi); HopRewriteUtils.addChildReference(bop, left); HopRewriteUtils.addChildReference(bop, right); LOG.debug("Applied simplifyMultiBinaryToBinaryOperation."); } return hi; } /** * (X-Y*X) -> (1-Y)*X, (Y*X-X) -> (Y-1)*X * (X+Y*X) -> (1+Y)*X, (Y*X+X) -> (Y+1)*X * * * @param parent parent high-level operator * @param hi high-level operator * @param pos position * @return high-level operator */ private static Hop simplifyDistributiveBinaryOperation( Hop parent, Hop hi, int pos ) { if( hi instanceof BinaryOp ) { BinaryOp bop = (BinaryOp)hi; Hop left = bop.getInput().get(0); Hop right = bop.getInput().get(1); //(X+Y*X) -> (1+Y)*X, (Y*X+X) -> (Y+1)*X //(X-Y*X) -> (1-Y)*X, (Y*X-X) -> (Y-1)*X boolean applied = false; if( left.getDataType()==DataType.MATRIX && right.getDataType()==DataType.MATRIX && HopRewriteUtils.isValidOp(bop.getOp(), LOOKUP_VALID_DISTRIBUTIVE_BINARY) ) { Hop X = null; Hop Y = null; if( HopRewriteUtils.isBinary(left, OpOp2.MULT) ) //(Y*X-X) -> (Y-1)*X { Hop leftC1 = left.getInput().get(0); Hop leftC2 = left.getInput().get(1); if( leftC1.getDataType()==DataType.MATRIX && leftC2.getDataType()==DataType.MATRIX && (right == leftC1 || right == leftC2) && leftC1 !=leftC2 ){ //any mult order X = right; Y = ( right == leftC1 ) ? leftC2 : leftC1; } if( X != null ){ //rewrite 'binary +/-' LiteralOp literal = new LiteralOp(1); BinaryOp plus = HopRewriteUtils.createBinary(Y, literal, bop.getOp()); BinaryOp mult = HopRewriteUtils.createBinary(plus, X, OpOp2.MULT); HopRewriteUtils.replaceChildReference(parent, hi, mult, pos); HopRewriteUtils.cleanupUnreferenced(hi, left); hi = mult; applied = true; LOG.debug("Applied simplifyDistributiveBinaryOperation1 (line "+hi.getBeginLine()+")."); } } if( !applied && HopRewriteUtils.isBinary(right, OpOp2.MULT) ) //(X-Y*X) -> (1-Y)*X { Hop rightC1 = right.getInput().get(0); Hop rightC2 = right.getInput().get(1); if( rightC1.getDataType()==DataType.MATRIX && rightC2.getDataType()==DataType.MATRIX && (left == rightC1 || left == rightC2) && rightC1 !=rightC2 ){ //any mult order X = left; Y = ( left == rightC1 ) ? rightC2 : rightC1; } if( X != null ){ //rewrite '+/- binary' LiteralOp literal = new LiteralOp(1); BinaryOp plus = HopRewriteUtils.createBinary(literal, Y, bop.getOp()); BinaryOp mult = HopRewriteUtils.createBinary(plus, X, OpOp2.MULT); HopRewriteUtils.replaceChildReference(parent, hi, mult, pos); HopRewriteUtils.cleanupUnreferenced(hi, right); hi = mult; LOG.debug("Applied simplifyDistributiveBinaryOperation2 (line "+hi.getBeginLine()+")."); } } } } return hi; } /** * (X*(Y*(Z%*%v))) -> (X*Y)*(Z%*%v) * (X+(Y+(Z%*%v))) -> (X+Y)+(Z%*%v) * * Note: Restriction ba() at leaf and root instead of data at leaf to not reorganize too * eagerly, which would loose additional rewrite potential. This rewrite has two goals * (1) enable XtwXv, and increase piggybacking potential by creating bushy trees. * * @param parent parent high-level operator * @param hi high-level operator * @param pos position * @return high-level operator */ private static Hop simplifyBushyBinaryOperation( Hop parent, Hop hi, int pos ) { if( hi instanceof BinaryOp && parent instanceof AggBinaryOp ) { BinaryOp bop = (BinaryOp)hi; Hop left = bop.getInput().get(0); Hop right = bop.getInput().get(1); OpOp2 op = bop.getOp(); if( left.getDataType()==DataType.MATRIX && right.getDataType()==DataType.MATRIX && HopRewriteUtils.isValidOp(op, LOOKUP_VALID_ASSOCIATIVE_BINARY) ) { boolean applied = false; if( right instanceof BinaryOp ) { BinaryOp bop2 = (BinaryOp)right; Hop left2 = bop2.getInput().get(0); Hop right2 = bop2.getInput().get(1); OpOp2 op2 = bop2.getOp(); if( op==op2 && right2.getDataType()==DataType.MATRIX && (right2 instanceof AggBinaryOp) ) { //(X*(Y*op()) -> (X*Y)*op() BinaryOp bop3 = HopRewriteUtils.createBinary(left, left2, op); BinaryOp bop4 = HopRewriteUtils.createBinary(bop3, right2, op); HopRewriteUtils.replaceChildReference(parent, bop, bop4, pos); HopRewriteUtils.cleanupUnreferenced(bop, bop2); hi = bop4; applied = true; LOG.debug("Applied simplifyBushyBinaryOperation1"); } } if( !applied && left instanceof BinaryOp ) { BinaryOp bop2 = (BinaryOp)left; Hop left2 = bop2.getInput().get(0); Hop right2 = bop2.getInput().get(1); OpOp2 op2 = bop2.getOp(); if( op==op2 && left2.getDataType()==DataType.MATRIX && (left2 instanceof AggBinaryOp) && (right2.getDim2() > 1 || right.getDim2() == 1) //X not vector, or Y vector && (right2.getDim1() > 1 || right.getDim1() == 1) ) //X not vector, or Y vector { //((op()*X)*Y) -> op()*(X*Y) BinaryOp bop3 = HopRewriteUtils.createBinary(right2, right, op); BinaryOp bop4 = HopRewriteUtils.createBinary(left2, bop3, op); HopRewriteUtils.replaceChildReference(parent, bop, bop4, pos); HopRewriteUtils.cleanupUnreferenced(bop, bop2); hi = bop4; LOG.debug("Applied simplifyBushyBinaryOperation2"); } } } } return hi; } private static Hop simplifyUnaryAggReorgOperation( Hop parent, Hop hi, int pos ) { if( hi instanceof AggUnaryOp && ((AggUnaryOp)hi).getDirection()==Direction.RowCol //full uagg && hi.getInput().get(0) instanceof ReorgOp ) //reorg operation { ReorgOp rop = (ReorgOp)hi.getInput().get(0); if( (rop.getOp()==ReOrgOp.TRANS || rop.getOp()==ReOrgOp.RESHAPE || rop.getOp() == ReOrgOp.REV ) //valid reorg && rop.getParent().size()==1 ) //uagg only reorg consumer { Hop input = rop.getInput().get(0); HopRewriteUtils.removeAllChildReferences(hi); HopRewriteUtils.removeAllChildReferences(rop); HopRewriteUtils.addChildReference(hi, input); LOG.debug("Applied simplifyUnaryAggReorgOperation"); } } return hi; } private static Hop removeUnnecessaryAggregates(Hop hi) { //sum(rowSums(X)) -> sum(X), sum(colSums(X)) -> sum(X) //min(rowMins(X)) -> min(X), min(colMins(X)) -> min(X) //max(rowMaxs(X)) -> max(X), max(colMaxs(X)) -> max(X) //sum(rowSums(X^2)) -> sum(X), sum(colSums(X^2)) -> sum(X) if( hi instanceof AggUnaryOp && hi.getInput().get(0) instanceof AggUnaryOp && ((AggUnaryOp)hi).getDirection()==Direction.RowCol && hi.getInput().get(0).getParent().size()==1 ) { AggUnaryOp au1 = (AggUnaryOp) hi; AggUnaryOp au2 = (AggUnaryOp) hi.getInput().get(0); if( (au1.getOp()==AggOp.SUM && (au2.getOp()==AggOp.SUM || au2.getOp()==AggOp.SUM_SQ)) || (au1.getOp()==AggOp.MIN && au2.getOp()==AggOp.MIN) || (au1.getOp()==AggOp.MAX && au2.getOp()==AggOp.MAX) ) { Hop input = au2.getInput().get(0); HopRewriteUtils.removeAllChildReferences(au2); HopRewriteUtils.replaceChildReference(au1, au2, input); if( au2.getOp() == AggOp.SUM_SQ ) au1.setOp(AggOp.SUM_SQ); LOG.debug("Applied removeUnnecessaryAggregates (line "+hi.getBeginLine()+")."); } } return hi; } private static Hop simplifyBinaryMatrixScalarOperation( Hop parent, Hop hi, int pos ) { // Note: This rewrite is not applicable for all binary operations because some of them // are undefined over scalars. We explicitly exclude potential conflicting matrix-scalar binary // operations; other operations like cbind/rbind will never occur as matrix-scalar operations. if( HopRewriteUtils.isUnary(hi, OpOp1.CAST_AS_SCALAR) && hi.getInput().get(0) instanceof BinaryOp && HopRewriteUtils.isBinary(hi.getInput().get(0), LOOKUP_VALID_SCALAR_BINARY)) { BinaryOp bin = (BinaryOp) hi.getInput().get(0); BinaryOp bout = null; //as.scalar(X*Y) -> as.scalar(X) * as.scalar(Y) if( bin.getInput().get(0).getDataType()==DataType.MATRIX && bin.getInput().get(1).getDataType()==DataType.MATRIX ) { UnaryOp cast1 = HopRewriteUtils.createUnary(bin.getInput().get(0), OpOp1.CAST_AS_SCALAR); UnaryOp cast2 = HopRewriteUtils.createUnary(bin.getInput().get(1), OpOp1.CAST_AS_SCALAR); bout = HopRewriteUtils.createBinary(cast1, cast2, bin.getOp()); } //as.scalar(X*s) -> as.scalar(X) * s else if( bin.getInput().get(0).getDataType()==DataType.MATRIX ) { UnaryOp cast = HopRewriteUtils.createUnary(bin.getInput().get(0), OpOp1.CAST_AS_SCALAR); bout = HopRewriteUtils.createBinary(cast, bin.getInput().get(1), bin.getOp()); } //as.scalar(s*X) -> s * as.scalar(X) else if ( bin.getInput().get(1).getDataType()==DataType.MATRIX ) { UnaryOp cast = HopRewriteUtils.createUnary(bin.getInput().get(1), OpOp1.CAST_AS_SCALAR); bout = HopRewriteUtils.createBinary(bin.getInput().get(0), cast, bin.getOp()); } if( bout != null ) { HopRewriteUtils.replaceChildReference(parent, hi, bout, pos); LOG.debug("Applied simplifyBinaryMatrixScalarOperation."); } } return hi; } private static Hop pushdownUnaryAggTransposeOperation( Hop parent, Hop hi, int pos ) { if( hi instanceof AggUnaryOp && hi.getParent().size()==1 && (((AggUnaryOp) hi).getDirection()==Direction.Row || ((AggUnaryOp) hi).getDirection()==Direction.Col) && HopRewriteUtils.isTransposeOperation(hi.getInput().get(0), 1) && HopRewriteUtils.isValidOp(((AggUnaryOp) hi).getOp(), LOOKUP_VALID_ROW_COL_AGGREGATE) ) { AggUnaryOp uagg = (AggUnaryOp) hi; //get input rewire existing operators (remove inner transpose) Hop input = uagg.getInput().get(0).getInput().get(0); HopRewriteUtils.removeAllChildReferences(hi.getInput().get(0)); HopRewriteUtils.removeAllChildReferences(hi); HopRewriteUtils.removeChildReferenceByPos(parent, hi, pos); //pattern 1: row-aggregate to col aggregate, e.g., rowSums(t(X))->t(colSums(X)) if( uagg.getDirection()==Direction.Row ) { uagg.setDirection(Direction.Col); LOG.debug("Applied pushdownUnaryAggTransposeOperation1 (line "+hi.getBeginLine()+")."); } //pattern 2: col-aggregate to row aggregate, e.g., colSums(t(X))->t(rowSums(X)) else if( uagg.getDirection()==Direction.Col ) { uagg.setDirection(Direction.Row); LOG.debug("Applied pushdownUnaryAggTransposeOperation2 (line "+hi.getBeginLine()+")."); } //create outer transpose operation and rewire operators HopRewriteUtils.addChildReference(uagg, input); uagg.refreshSizeInformation(); Hop trans = HopRewriteUtils.createTranspose(uagg); //incl refresh size HopRewriteUtils.addChildReference(parent, trans, pos); //by def, same size hi = trans; } return hi; } private static Hop pushdownCSETransposeScalarOperation( Hop parent, Hop hi, int pos ) { // a=t(X), b=t(X^2) -> a=t(X), b=t(X)^2 for CSE t(X) // probed at root node of b in above example // (with support for left or right scalar operations) if( HopRewriteUtils.isTransposeOperation(hi, 1) && HopRewriteUtils.isBinaryMatrixScalarOperation(hi.getInput().get(0)) && hi.getInput().get(0).getParent().size()==1) { int Xpos = hi.getInput().get(0).getInput().get(0).getDataType().isMatrix() ? 0 : 1; Hop X = hi.getInput().get(0).getInput().get(Xpos); BinaryOp binary = (BinaryOp) hi.getInput().get(0); if( HopRewriteUtils.containsTransposeOperation(X.getParent()) && !HopRewriteUtils.isValidOp(binary.getOp(), new OpOp2[]{OpOp2.MOMENT, OpOp2.QUANTILE})) { //clear existing wiring HopRewriteUtils.removeChildReferenceByPos(parent, hi, pos); HopRewriteUtils.removeChildReference(hi, binary); HopRewriteUtils.removeChildReference(binary, X); //re-wire operators HopRewriteUtils.addChildReference(parent, binary, pos); HopRewriteUtils.addChildReference(binary, hi, Xpos); HopRewriteUtils.addChildReference(hi, X); //note: common subexpression later eliminated by dedicated rewrite hi = binary; LOG.debug("Applied pushdownCSETransposeScalarOperation (line "+hi.getBeginLine()+")."); } } return hi; } private static Hop pushdownSumBinaryMult(Hop parent, Hop hi, int pos ) { //pattern: sum(lamda*X) -> lamda*sum(X) if( hi instanceof AggUnaryOp && ((AggUnaryOp)hi).getDirection()==Direction.RowCol && ((AggUnaryOp)hi).getOp()==AggOp.SUM // only one parent which is the sum && HopRewriteUtils.isBinary(hi.getInput().get(0), OpOp2.MULT, 1) && ((hi.getInput().get(0).getInput().get(0).getDataType()==DataType.SCALAR && hi.getInput().get(0).getInput().get(1).getDataType()==DataType.MATRIX) ||(hi.getInput().get(0).getInput().get(0).getDataType()==DataType.MATRIX && hi.getInput().get(0).getInput().get(1).getDataType()==DataType.SCALAR))) { Hop operand1 = hi.getInput().get(0).getInput().get(0); Hop operand2 = hi.getInput().get(0).getInput().get(1); //check which operand is the Scalar and which is the matrix Hop lamda = (operand1.getDataType()==DataType.SCALAR) ? operand1 : operand2; Hop matrix = (operand1.getDataType()==DataType.MATRIX) ? operand1 : operand2; AggUnaryOp aggOp=HopRewriteUtils.createAggUnaryOp(matrix, AggOp.SUM, Direction.RowCol); Hop bop = HopRewriteUtils.createBinary(lamda, aggOp, OpOp2.MULT); HopRewriteUtils.replaceChildReference(parent, hi, bop, pos); LOG.debug("Applied pushdownSumBinaryMult."); return bop; } return hi; } private static Hop simplifyUnaryPPredOperation( Hop parent, Hop hi, int pos ) { if( hi instanceof UnaryOp && hi.getDataType()==DataType.MATRIX //unaryop && hi.getInput().get(0) instanceof BinaryOp //binaryop - ppred && ((BinaryOp)hi.getInput().get(0)).isPPredOperation() ) { UnaryOp uop = (UnaryOp) hi; //valid unary op if( uop.getOp()==OpOp1.ABS || uop.getOp()==OpOp1.SIGN || uop.getOp()==OpOp1.CEIL || uop.getOp()==OpOp1.FLOOR || uop.getOp()==OpOp1.ROUND ) { //clear link unary-binary Hop input = uop.getInput().get(0); HopRewriteUtils.replaceChildReference(parent, hi, input, pos); HopRewriteUtils.cleanupUnreferenced(hi); hi = input; LOG.debug("Applied simplifyUnaryPPredOperation."); } } return hi; } private static Hop simplifyTransposedAppend( Hop parent, Hop hi, int pos ) { //e.g., t(cbind(t(A),t(B))) --> rbind(A,B), t(rbind(t(A),t(B))) --> cbind(A,B) if( HopRewriteUtils.isTransposeOperation(hi) //t() rooted && hi.getInput().get(0) instanceof BinaryOp && (((BinaryOp)hi.getInput().get(0)).getOp()==OpOp2.CBIND //append (cbind/rbind) || ((BinaryOp)hi.getInput().get(0)).getOp()==OpOp2.RBIND) && hi.getInput().get(0).getParent().size() == 1 ) //single consumer of append { BinaryOp bop = (BinaryOp)hi.getInput().get(0); //both inputs transpose ops, where transpose is single consumer if( HopRewriteUtils.isTransposeOperation(bop.getInput().get(0), 1) && HopRewriteUtils.isTransposeOperation(bop.getInput().get(1), 1) ) { Hop left = bop.getInput().get(0).getInput().get(0); Hop right = bop.getInput().get(1).getInput().get(0); //create new subdag (no in-place dag update to prevent anomalies with //multiple consumers during rewrite process) OpOp2 binop = (bop.getOp()==OpOp2.CBIND) ? OpOp2.RBIND : OpOp2.CBIND; BinaryOp bopnew = HopRewriteUtils.createBinary(left, right, binop); HopRewriteUtils.replaceChildReference(parent, hi, bopnew, pos); hi = bopnew; LOG.debug("Applied simplifyTransposedAppend (line "+hi.getBeginLine()+")."); } } return hi; } /** * handle simplification of more complex sub DAG to unary operation. * * X*(1-X) -> sprop(X) * (1-X)*X -> sprop(X) * 1/(1+exp(-X)) -> sigmoid(X) * * @param parent parent high-level operator * @param hi high-level operator * @param pos position */ private static Hop fuseBinarySubDAGToUnaryOperation( Hop parent, Hop hi, int pos ) { if( hi instanceof BinaryOp ) { BinaryOp bop = (BinaryOp)hi; Hop left = hi.getInput().get(0); Hop right = hi.getInput().get(1); boolean applied = false; //sample proportion (sprop) operator if( bop.getOp() == OpOp2.MULT && left.getDataType()==DataType.MATRIX && right.getDataType()==DataType.MATRIX ) { //by definition, either left or right or none applies. //note: if there are multiple consumers on the intermediate, //we follow the heuristic that redundant computation is more beneficial, //i.e., we still fuse but leave the intermediate for the other consumers if( left instanceof BinaryOp ) //(1-X)*X { BinaryOp bleft = (BinaryOp)left; Hop left1 = bleft.getInput().get(0); Hop left2 = bleft.getInput().get(1); if( left1 instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)left1)==1 && left2 == right && bleft.getOp() == OpOp2.MINUS ) { UnaryOp unary = HopRewriteUtils.createUnary(right, OpOp1.SPROP); HopRewriteUtils.replaceChildReference(parent, bop, unary, pos); HopRewriteUtils.cleanupUnreferenced(bop, left); hi = unary; applied = true; LOG.debug("Applied fuseBinarySubDAGToUnaryOperation-sprop1"); } } if( !applied && right instanceof BinaryOp ) //X*(1-X) { BinaryOp bright = (BinaryOp)right; Hop right1 = bright.getInput().get(0); Hop right2 = bright.getInput().get(1); if( right1 instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)right1)==1 && right2 == left && bright.getOp() == OpOp2.MINUS ) { UnaryOp unary = HopRewriteUtils.createUnary(left, OpOp1.SPROP); HopRewriteUtils.replaceChildReference(parent, bop, unary, pos); HopRewriteUtils.cleanupUnreferenced(bop, left); hi = unary; applied = true; LOG.debug("Applied fuseBinarySubDAGToUnaryOperation-sprop2"); } } } //sigmoid operator if( !applied && bop.getOp() == OpOp2.DIV && left.getDataType()==DataType.SCALAR && right.getDataType()==DataType.MATRIX && left instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)left)==1 && right instanceof BinaryOp) { //note: if there are multiple consumers on the intermediate, //we follow the heuristic that redundant computation is more beneficial, //i.e., we still fuse but leave the intermediate for the other consumers BinaryOp bop2 = (BinaryOp)right; Hop left2 = bop2.getInput().get(0); Hop right2 = bop2.getInput().get(1); if( bop2.getOp() == OpOp2.PLUS && left2.getDataType()==DataType.SCALAR && right2.getDataType()==DataType.MATRIX && left2 instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)left2)==1 && right2 instanceof UnaryOp) { UnaryOp uop = (UnaryOp) right2; Hop uopin = uop.getInput().get(0); if( uop.getOp()==OpOp1.EXP ) { UnaryOp unary = null; //Pattern 1: (1/(1 + exp(-X)) if( HopRewriteUtils.isBinary(uopin, OpOp2.MINUS) ) { BinaryOp bop3 = (BinaryOp) uopin; Hop left3 = bop3.getInput().get(0); Hop right3 = bop3.getInput().get(1); if( left3 instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)left3)==0 ) unary = HopRewriteUtils.createUnary(right3, OpOp1.SIGMOID); } //Pattern 2: (1/(1 + exp(X)), e.g., where -(-X) has been removed by //the 'remove unnecessary minus' rewrite --> reintroduce the minus else { BinaryOp minus = HopRewriteUtils.createBinaryMinus(uopin); unary = HopRewriteUtils.createUnary(minus, OpOp1.SIGMOID); } if( unary != null ) { HopRewriteUtils.replaceChildReference(parent, bop, unary, pos); HopRewriteUtils.cleanupUnreferenced(bop, bop2, uop); hi = unary; applied = true; LOG.debug("Applied fuseBinarySubDAGToUnaryOperation-sigmoid1"); } } } } //select positive (selp) operator (note: same initial pattern as sprop) if( !applied && bop.getOp() == OpOp2.MULT && left.getDataType()==DataType.MATRIX && right.getDataType()==DataType.MATRIX ) { //by definition, either left or right or none applies. //note: if there are multiple consumers on the intermediate tmp=(X>0), it's still beneficial //to replace the X*tmp with selp(X) due to lower memory requirements and simply sparsity propagation if( left instanceof BinaryOp ) //(X>0)*X { BinaryOp bleft = (BinaryOp)left; Hop left1 = bleft.getInput().get(0); Hop left2 = bleft.getInput().get(1); if( left2 instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)left2)==0 && left1 == right && (bleft.getOp() == OpOp2.GREATER ) ) { BinaryOp binary = HopRewriteUtils.createBinary(right, new LiteralOp(0), OpOp2.MAX); HopRewriteUtils.replaceChildReference(parent, bop, binary, pos); HopRewriteUtils.cleanupUnreferenced(bop, left); hi = binary; applied = true; LOG.debug("Applied fuseBinarySubDAGToUnaryOperation-max0a"); } } if( !applied && right instanceof BinaryOp ) //X*(X>0) { BinaryOp bright = (BinaryOp)right; Hop right1 = bright.getInput().get(0); Hop right2 = bright.getInput().get(1); if( right2 instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)right2)==0 && right1 == left && bright.getOp() == OpOp2.GREATER ) { BinaryOp binary = HopRewriteUtils.createBinary(left, new LiteralOp(0), OpOp2.MAX); HopRewriteUtils.replaceChildReference(parent, bop, binary, pos); HopRewriteUtils.cleanupUnreferenced(bop, left); hi = binary; applied= true; LOG.debug("Applied fuseBinarySubDAGToUnaryOperation-max0b"); } } } } return hi; } private static Hop simplifyTraceMatrixMult(Hop parent, Hop hi, int pos) { if( hi instanceof AggUnaryOp && ((AggUnaryOp)hi).getOp()==AggOp.TRACE ) //trace() { Hop hi2 = hi.getInput().get(0); if( HopRewriteUtils.isMatrixMultiply(hi2) ) //X%*%Y { Hop left = hi2.getInput().get(0); Hop right = hi2.getInput().get(1); //create new operators (incl refresh size inside for transpose) ReorgOp trans = HopRewriteUtils.createTranspose(right); BinaryOp mult = HopRewriteUtils.createBinary(left, trans, OpOp2.MULT); AggUnaryOp sum = HopRewriteUtils.createSum(mult); //rehang new subdag under parent node HopRewriteUtils.replaceChildReference(parent, hi, sum, pos); HopRewriteUtils.cleanupUnreferenced(hi, hi2); hi = sum; LOG.debug("Applied simplifyTraceMatrixMult"); } } return hi; } private static Hop simplifySlicedMatrixMult(Hop parent, Hop hi, int pos) { //e.g., (X%*%Y)[1,1] -> X[1,] %*% Y[,1] if( hi instanceof IndexingOp && ((IndexingOp)hi).isRowLowerEqualsUpper() && ((IndexingOp)hi).isColLowerEqualsUpper() && hi.getInput().get(0).getParent().size()==1 //rix is single mm consumer && HopRewriteUtils.isMatrixMultiply(hi.getInput().get(0)) ) { Hop mm = hi.getInput().get(0); Hop X = mm.getInput().get(0); Hop Y = mm.getInput().get(1); Hop rowExpr = hi.getInput().get(1); //rl==ru Hop colExpr = hi.getInput().get(3); //cl==cu HopRewriteUtils.removeAllChildReferences(mm); //create new indexing operations IndexingOp ix1 = new IndexingOp("tmp1", DataType.MATRIX, ValueType.FP64, X, rowExpr, rowExpr, new LiteralOp(1), HopRewriteUtils.createValueHop(X, false), true, false); ix1.setBlocksize(X.getBlocksize()); ix1.refreshSizeInformation(); IndexingOp ix2 = new IndexingOp("tmp2", DataType.MATRIX, ValueType.FP64, Y, new LiteralOp(1), HopRewriteUtils.createValueHop(Y, true), colExpr, colExpr, false, true); ix2.setBlocksize(Y.getBlocksize()); ix2.refreshSizeInformation(); //rewire matrix mult over ix1 and ix2 HopRewriteUtils.addChildReference(mm, ix1, 0); HopRewriteUtils.addChildReference(mm, ix2, 1); mm.refreshSizeInformation(); hi = mm; LOG.debug("Applied simplifySlicedMatrixMult"); } return hi; } private static Hop simplifyConstantSort(Hop parent, Hop hi, int pos) { //order(matrix(7), indexreturn=FALSE) -> matrix(7) //order(matrix(7), indexreturn=TRUE) -> seq(1,nrow(X),1) if( hi instanceof ReorgOp && ((ReorgOp)hi).getOp()==ReOrgOp.SORT ) //order { Hop hi2 = hi.getInput().get(0); if( hi2 instanceof DataGenOp && ((DataGenOp)hi2).getOp()==OpOpDG.RAND && ((DataGenOp)hi2).hasConstantValue() && hi.getInput().get(3) instanceof LiteralOp ) //known indexreturn { if( HopRewriteUtils.getBooleanValue((LiteralOp)hi.getInput().get(3)) ) { //order(matrix(7), indexreturn=TRUE) -> seq(1,nrow(X),1) Hop seq = HopRewriteUtils.createSeqDataGenOp(hi2); seq.refreshSizeInformation(); HopRewriteUtils.replaceChildReference(parent, hi, seq, pos); HopRewriteUtils.cleanupUnreferenced(hi); hi = seq; LOG.debug("Applied simplifyConstantSort1."); } else { //order(matrix(7), indexreturn=FALSE) -> matrix(7) HopRewriteUtils.replaceChildReference(parent, hi, hi2, pos); HopRewriteUtils.cleanupUnreferenced(hi); hi = hi2; LOG.debug("Applied simplifyConstantSort2."); } } } return hi; } private static Hop simplifyOrderedSort(Hop parent, Hop hi, int pos) { //order(seq(2,N+1,1), indexreturn=FALSE) -> matrix(7) //order(seq(2,N+1,1), indexreturn=TRUE) -> seq(1,N,1)/seq(N,1,-1) if( hi instanceof ReorgOp && ((ReorgOp)hi).getOp()==ReOrgOp.SORT ) //order { Hop hi2 = hi.getInput().get(0); if( hi2 instanceof DataGenOp && ((DataGenOp)hi2).getOp()==OpOpDG.SEQ ) { Hop incr = hi2.getInput().get(((DataGenOp)hi2).getParamIndex(Statement.SEQ_INCR)); //check for known ascending ordering and known indexreturn if( incr instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)incr)==1 && hi.getInput().get(2) instanceof LiteralOp //decreasing && hi.getInput().get(3) instanceof LiteralOp ) //indexreturn { if( HopRewriteUtils.getBooleanValue((LiteralOp)hi.getInput().get(3)) ) //IXRET, ASC/DESC { //order(seq(2,N+1,1), indexreturn=TRUE) -> seq(1,N,1)/seq(N,1,-1) boolean desc = HopRewriteUtils.getBooleanValue((LiteralOp)hi.getInput().get(2)); Hop seq = HopRewriteUtils.createSeqDataGenOp(hi2, !desc); seq.refreshSizeInformation(); HopRewriteUtils.replaceChildReference(parent, hi, seq, pos); HopRewriteUtils.cleanupUnreferenced(hi); hi = seq; LOG.debug("Applied simplifyOrderedSort1."); } else if( !HopRewriteUtils.getBooleanValue((LiteralOp)hi.getInput().get(2)) ) //DATA, ASC { //order(seq(2,N+1,1), indexreturn=FALSE) -> seq(2,N+1,1) HopRewriteUtils.replaceChildReference(parent, hi, hi2, pos); HopRewriteUtils.cleanupUnreferenced(hi); hi = hi2; LOG.debug("Applied simplifyOrderedSort2."); } } } } return hi; } private static Hop fuseOrderOperationChain(Hop hi) { //order(order(X,2),1) -> order(X, (12)), if( HopRewriteUtils.isReorg(hi, ReOrgOp.SORT) && hi.getInput().get(1) instanceof LiteralOp //scalar by && hi.getInput().get(2) instanceof LiteralOp //scalar desc && HopRewriteUtils.isLiteralOfValue(hi.getInput().get(3), false) ) //not ixret { LiteralOp by = (LiteralOp) hi.getInput().get(1); boolean desc = HopRewriteUtils.getBooleanValue((LiteralOp)hi.getInput().get(2)); //find chain of order operations with same desc/ixret configuration and single consumers Set<String> probe = new HashSet<>(); ArrayList<LiteralOp> byList = new ArrayList<>(); byList.add(by); probe.add(by.getStringValue()); Hop input = hi.getInput().get(0); while( HopRewriteUtils.isReorg(input, ReOrgOp.SORT) && input.getInput().get(1) instanceof LiteralOp //scalar by && !probe.contains(input.getInput().get(1).getName()) && HopRewriteUtils.isLiteralOfValue(input.getInput().get(2), desc) && HopRewriteUtils.isLiteralOfValue(hi.getInput().get(3), false) && input.getParent().size() == 1 ) { byList.add((LiteralOp)input.getInput().get(1)); probe.add(input.getInput().get(1).getName()); input = input.getInput().get(0); } //merge order chain if at least two instances if( byList.size() >= 2 ) { //create new order operations ArrayList<Hop> inputs = new ArrayList<>(); inputs.add(input); inputs.add(HopRewriteUtils.createDataGenOpByVal(byList, 1, byList.size())); inputs.add(new LiteralOp(desc)); inputs.add(new LiteralOp(false)); Hop hnew = HopRewriteUtils.createReorg(inputs, ReOrgOp.SORT); //cleanup references recursively Hop current = hi; while(current != input ) { Hop tmp = current.getInput().get(0); HopRewriteUtils.removeAllChildReferences(current); current = tmp; } //rewire all parents (avoid anomalies with replicated datagen) List<Hop> parents = new ArrayList<>(hi.getParent()); for( Hop p : parents ) HopRewriteUtils.replaceChildReference(p, hi, hnew); hi = hnew; LOG.debug("Applied fuseOrderOperationChain (line "+hi.getBeginLine()+")."); } } return hi; } /** * Patterns: t(t(A)%*%t(B)+C) -> B%*%A+t(C) * * @param parent parent high-level operator * @param hi high-level operator * @param pos position * @return high-level operator */ private static Hop simplifyTransposeAggBinBinaryChains(Hop parent, Hop hi, int pos) { if( HopRewriteUtils.isTransposeOperation(hi) && hi.getInput().get(0) instanceof BinaryOp //basic binary && ((BinaryOp)hi.getInput().get(0)).supportsMatrixScalarOperations()) { Hop left = hi.getInput().get(0).getInput().get(0); Hop C = hi.getInput().get(0).getInput().get(1); //check matrix mult and both inputs transposes w/ single consumer if( left instanceof AggBinaryOp && C.getDataType().isMatrix() && HopRewriteUtils.isTransposeOperation(left.getInput().get(0)) && left.getInput().get(0).getParent().size()==1 && HopRewriteUtils.isTransposeOperation(left.getInput().get(1)) && left.getInput().get(1).getParent().size()==1 ) { Hop A = left.getInput().get(0).getInput().get(0); Hop B = left.getInput().get(1).getInput().get(0); AggBinaryOp abop = HopRewriteUtils.createMatrixMultiply(B, A); ReorgOp rop = HopRewriteUtils.createTranspose(C); BinaryOp bop = HopRewriteUtils.createBinary(abop, rop, OpOp2.PLUS); HopRewriteUtils.replaceChildReference(parent, hi, bop, pos); hi = bop; LOG.debug("Applied simplifyTransposeAggBinBinaryChains (line "+hi.getBeginLine()+")."); } } return hi; } // Patterns: X + (X==0) * s -> replace(X, 0, s) private static Hop simplifyReplaceZeroOperation(Hop parent, Hop hi, int pos) { if( HopRewriteUtils.isBinary(hi, OpOp2.PLUS) && hi.getInput().get(0).isMatrix() && HopRewriteUtils.isBinary(hi.getInput().get(1), OpOp2.MULT) && hi.getInput().get(1).getInput().get(1).isScalar() && HopRewriteUtils.isBinaryMatrixScalar(hi.getInput().get(1).getInput().get(0), OpOp2.EQUAL, 0) && hi.getInput().get(1).getInput().get(0).getInput().contains(hi.getInput().get(0)) ) { LinkedHashMap<String, Hop> args = new LinkedHashMap<>(); args.put("target", hi.getInput().get(0)); args.put("pattern", new LiteralOp(0)); args.put("replacement", hi.getInput().get(1).getInput().get(1)); Hop replace = HopRewriteUtils.createParameterizedBuiltinOp( hi.getInput().get(0), args, ParamBuiltinOp.REPLACE); HopRewriteUtils.replaceChildReference(parent, hi, replace, pos); hi = replace; LOG.debug("Applied simplifyReplaceZeroOperation (line "+hi.getBeginLine()+")."); } return hi; } /** * Pattners: t(t(X)) -> X, rev(rev(X)) -> X * * @param parent parent high-level operator * @param hi high-level operator * @param pos position * @return high-level operator */ private static Hop removeUnnecessaryReorgOperation(Hop parent, Hop hi, int pos) { ReOrgOp[] lookup = new ReOrgOp[]{ReOrgOp.TRANS, ReOrgOp.REV}; if( hi instanceof ReorgOp && HopRewriteUtils.isValidOp(((ReorgOp)hi).getOp(), lookup) ) //first reorg { ReOrgOp firstOp = ((ReorgOp)hi).getOp(); Hop hi2 = hi.getInput().get(0); if( hi2 instanceof ReorgOp && ((ReorgOp)hi2).getOp()==firstOp ) //second reorg w/ same type { Hop hi3 = hi2.getInput().get(0); //remove unnecessary chain of t(t()) HopRewriteUtils.replaceChildReference(parent, hi, hi3, pos); HopRewriteUtils.cleanupUnreferenced(hi, hi2); hi = hi3; LOG.debug("Applied removeUnecessaryReorgOperation."); } } return hi; } /* * Eliminate RemoveEmpty for SUM, SUM_SQ, and NNZ (number of non-zeros) */ private static Hop removeUnnecessaryRemoveEmpty(Hop parent, Hop hi, int pos) { //check if SUM or SUM_SQ is computed with input rmEmpty without select vector //rewrite pattern: //sum(removeEmpty(target=X)) -> sum(X) //rowSums(removeEmpty(target=X,margin="cols")) -> rowSums(X) //colSums(removeEmpty(target=X,margin="rows")) -> colSums(X) if( (HopRewriteUtils.isSum(hi) || HopRewriteUtils.isSumSq(hi)) && HopRewriteUtils.isRemoveEmpty(hi.getInput().get(0)) && hi.getInput().get(0).getParent().size() == 1 ) { AggUnaryOp agg = (AggUnaryOp)hi; ParameterizedBuiltinOp rmEmpty = (ParameterizedBuiltinOp) hi.getInput().get(0); boolean needRmEmpty = (agg.getDirection() == Direction.Row && HopRewriteUtils.isRemoveEmpty(rmEmpty, true)) || (agg.getDirection() == Direction.Col && HopRewriteUtils.isRemoveEmpty(rmEmpty, false)); if (rmEmpty.getParameterHop("select") == null && !needRmEmpty) { Hop input = rmEmpty.getTargetHop(); if( input != null ) { HopRewriteUtils.replaceChildReference(hi, rmEmpty, input); return hi; //eliminate rmEmpty } } } //check if nrow is called on the output of removeEmpty if( HopRewriteUtils.isUnary(hi, OpOp1.NROW) && HopRewriteUtils.isRemoveEmpty(hi.getInput().get(0), true) && hi.getInput().get(0).getParent().size() == 1 ) { ParameterizedBuiltinOp rm = (ParameterizedBuiltinOp) hi.getInput().get(0); //obtain optional select vector or input if col vector //(nnz will be the same as the select vector if // the select vector is provided and it will be the same // as the input if the select vector is not provided) //NOTE: part of static rewrites despite size dependence for phase //ordering before rewrite for DAG splits after table/removeEmpty Hop input = (rm.getParameterHop("select") != null) ? rm.getParameterHop("select") : (rm.getDim2() == 1) ? rm.getTargetHop() : null; //create new expression w/o rmEmpty if applicable if( input != null ) { HopRewriteUtils.removeAllChildReferences(rm); Hop hnew = HopRewriteUtils.createComputeNnz(input); //modify dag if nnz is called on the output of removeEmpty if( hnew != null ){ HopRewriteUtils.replaceChildReference(parent, hi, hnew, pos); hi = hnew; LOG.debug("Applied removeUnnecessaryRemoveEmpty (line " + hi.getBeginLine() + ")"); } } } return hi; } private static Hop removeUnnecessaryMinus(Hop parent, Hop hi, int pos) { if( hi.getDataType() == DataType.MATRIX && hi instanceof BinaryOp && ((BinaryOp)hi).getOp()==OpOp2.MINUS //first minus && hi.getInput().get(0) instanceof LiteralOp && ((LiteralOp)hi.getInput().get(0)).getDoubleValue()==0 ) { Hop hi2 = hi.getInput().get(1); if( hi2.getDataType() == DataType.MATRIX && hi2 instanceof BinaryOp && ((BinaryOp)hi2).getOp()==OpOp2.MINUS //second minus && hi2.getInput().get(0) instanceof LiteralOp && ((LiteralOp)hi2.getInput().get(0)).getDoubleValue()==0 ) { Hop hi3 = hi2.getInput().get(1); //remove unnecessary chain of -(-()) HopRewriteUtils.replaceChildReference(parent, hi, hi3, pos); HopRewriteUtils.cleanupUnreferenced(hi, hi2); hi = hi3; LOG.debug("Applied removeUnecessaryMinus"); } } return hi; } private static Hop simplifyGroupedAggregate(Hop hi) { if( hi instanceof ParameterizedBuiltinOp && ((ParameterizedBuiltinOp)hi).getOp()==ParamBuiltinOp.GROUPEDAGG ) //aggregate { ParameterizedBuiltinOp phi = (ParameterizedBuiltinOp)hi; if( phi.isCountFunction() //aggregate(fn="count") && phi.getTargetHop().getDim2()==1 ) //only for vector { HashMap<String, Integer> params = phi.getParamIndexMap(); int ix1 = params.get(Statement.GAGG_TARGET); int ix2 = params.get(Statement.GAGG_GROUPS); //check for unnecessary memory consumption for "count" if( ix1 != ix2 && phi.getInput().get(ix1)!=phi.getInput().get(ix2) ) { Hop th = phi.getInput().get(ix1); Hop gh = phi.getInput().get(ix2); HopRewriteUtils.replaceChildReference(hi, th, gh, ix1); LOG.debug("Applied simplifyGroupedAggregateCount"); } } } return hi; } private static Hop fuseMinusNzBinaryOperation(Hop parent, Hop hi, int pos) { //pattern X - (s * ppred(X,0,!=)) -> X -nz s //note: this is done as a hop rewrite in order to significantly reduce the //memory estimate for X - tmp if X is sparse if( HopRewriteUtils.isBinary(hi, OpOp2.MINUS) && hi.getInput().get(0).getDataType()==DataType.MATRIX && hi.getInput().get(1).getDataType()==DataType.MATRIX && HopRewriteUtils.isBinary(hi.getInput().get(1), OpOp2.MULT) ) { Hop X = hi.getInput().get(0); Hop s = hi.getInput().get(1).getInput().get(0); Hop pred = hi.getInput().get(1).getInput().get(1); if( s.getDataType()==DataType.SCALAR && pred.getDataType()==DataType.MATRIX && HopRewriteUtils.isBinary(pred, OpOp2.NOTEQUAL) && pred.getInput().get(0) == X //depend on common subexpression elimination && pred.getInput().get(1) instanceof LiteralOp && HopRewriteUtils.getDoubleValueSafe((LiteralOp)pred.getInput().get(1))==0 ) { Hop hnew = HopRewriteUtils.createBinary(X, s, OpOp2.MINUS_NZ); //relink new hop into original position HopRewriteUtils.replaceChildReference(parent, hi, hnew, pos); hi = hnew; LOG.debug("Applied fuseMinusNzBinaryOperation (line "+hi.getBeginLine()+")"); } } return hi; } private static Hop fuseLogNzUnaryOperation(Hop parent, Hop hi, int pos) { //pattern ppred(X,0,"!=")*log(X) -> log_nz(X) //note: this is done as a hop rewrite in order to significantly reduce the //memory estimate and to prevent dense intermediates if X is ultra sparse if( HopRewriteUtils.isBinary(hi, OpOp2.MULT) && hi.getInput().get(0).getDataType()==DataType.MATRIX && hi.getInput().get(1).getDataType()==DataType.MATRIX && HopRewriteUtils.isUnary(hi.getInput().get(1), OpOp1.LOG) ) { Hop pred = hi.getInput().get(0); Hop X = hi.getInput().get(1).getInput().get(0); if( HopRewriteUtils.isBinary(pred, OpOp2.NOTEQUAL) && pred.getInput().get(0) == X //depend on common subexpression elimination && pred.getInput().get(1) instanceof LiteralOp && HopRewriteUtils.getDoubleValueSafe((LiteralOp)pred.getInput().get(1))==0 ) { Hop hnew = HopRewriteUtils.createUnary(X, OpOp1.LOG_NZ); //relink new hop into original position HopRewriteUtils.replaceChildReference(parent, hi, hnew, pos); hi = hnew; LOG.debug("Applied fuseLogNzUnaryOperation (line "+hi.getBeginLine()+")."); } } return hi; } private static Hop fuseLogNzBinaryOperation(Hop parent, Hop hi, int pos) { //pattern ppred(X,0,"!=")*log(X,0.5) -> log_nz(X,0.5) //note: this is done as a hop rewrite in order to significantly reduce the //memory estimate and to prevent dense intermediates if X is ultra sparse if( HopRewriteUtils.isBinary(hi, OpOp2.MULT) && hi.getInput().get(0).getDataType()==DataType.MATRIX && hi.getInput().get(1).getDataType()==DataType.MATRIX && HopRewriteUtils.isBinary(hi.getInput().get(1), OpOp2.LOG) ) { Hop pred = hi.getInput().get(0); Hop X = hi.getInput().get(1).getInput().get(0); Hop log = hi.getInput().get(1).getInput().get(1); if( HopRewriteUtils.isBinary(pred, OpOp2.NOTEQUAL) && pred.getInput().get(0) == X //depend on common subexpression elimination && pred.getInput().get(1) instanceof LiteralOp && HopRewriteUtils.getDoubleValueSafe((LiteralOp)pred.getInput().get(1))==0 ) { Hop hnew = HopRewriteUtils.createBinary(X, log, OpOp2.LOG_NZ); //relink new hop into original position HopRewriteUtils.replaceChildReference(parent, hi, hnew, pos); hi = hnew; LOG.debug("Applied fuseLogNzBinaryOperation (line "+hi.getBeginLine()+")"); } } return hi; } private static Hop simplifyOuterSeqExpand(Hop parent, Hop hi, int pos) { //pattern: outer(v, t(seq(1,m)), "==") -> rexpand(v, max=m, dir=row, ignore=true, cast=false) //note: this rewrite supports both left/right sequence if( HopRewriteUtils.isBinary(hi, OpOp2.EQUAL) && ((BinaryOp)hi).isOuter() ) { if( ( HopRewriteUtils.isTransposeOperation(hi.getInput().get(1)) //pattern a: outer(v, t(seq(1,m)), "==") && HopRewriteUtils.isBasic1NSequence(hi.getInput().get(1).getInput().get(0))) || HopRewriteUtils.isBasic1NSequence(hi.getInput().get(0))) //pattern b: outer(seq(1,m), t(v) "==") { //determine variable parameters for pattern a/b boolean isPatternB = HopRewriteUtils.isBasic1NSequence(hi.getInput().get(0)); boolean isTransposeRight = HopRewriteUtils.isTransposeOperation(hi.getInput().get(1)); Hop trgt = isPatternB ? (isTransposeRight ? hi.getInput().get(1).getInput().get(0) : //get v from t(v) HopRewriteUtils.createTranspose(hi.getInput().get(1)) ) : //create v via t(v') hi.getInput().get(0); //get v directly Hop seq = isPatternB ? hi.getInput().get(0) : hi.getInput().get(1).getInput().get(0); String direction = HopRewriteUtils.isBasic1NSequence(hi.getInput().get(0)) ? "rows" : "cols"; //setup input parameter hops LinkedHashMap<String,Hop> inputargs = new LinkedHashMap<>(); inputargs.put("target", trgt); inputargs.put("max", HopRewriteUtils.getBasic1NSequenceMax(seq)); inputargs.put("dir", new LiteralOp(direction)); inputargs.put("ignore", new LiteralOp(true)); inputargs.put("cast", new LiteralOp(false)); //create new hop ParameterizedBuiltinOp pbop = HopRewriteUtils .createParameterizedBuiltinOp(trgt, inputargs, ParamBuiltinOp.REXPAND); //relink new hop into original position HopRewriteUtils.replaceChildReference(parent, hi, pbop, pos); hi = pbop; LOG.debug("Applied simplifyOuterSeqExpand (line "+hi.getBeginLine()+")"); } } return hi; } private static Hop simplifyBinaryComparisonChain(Hop parent, Hop hi, int pos) { if( HopRewriteUtils.isBinaryPPred(hi) && HopRewriteUtils.isLiteralOfValue(hi.getInput().get(1), 0d, 1d) && HopRewriteUtils.isBinaryPPred(hi.getInput().get(0)) ) { BinaryOp bop = (BinaryOp) hi; BinaryOp bop2 = (BinaryOp) hi.getInput().get(0); boolean one = HopRewriteUtils.isLiteralOfValue(hi.getInput().get(1), 1); //pattern: outer(v1,v2,"!=") == 1 -> outer(v1,v2,"!=") if( (one && bop.getOp() == OpOp2.EQUAL) || (!one && bop.getOp() == OpOp2.NOTEQUAL) ) { HopRewriteUtils.replaceChildReference(parent, bop, bop2, pos); HopRewriteUtils.cleanupUnreferenced(bop); hi = bop2; LOG.debug("Applied simplifyBinaryComparisonChain1 (line "+hi.getBeginLine()+")"); } //pattern: outer(v1,v2,"!=") == 0 -> outer(v1,v2,"==") else if( !one && bop.getOp() == OpOp2.EQUAL ) { OpOp2 optr = bop2.getComplementPPredOperation(); BinaryOp tmp = HopRewriteUtils.createBinary(bop2.getInput().get(0), bop2.getInput().get(1), optr, bop2.isOuter()); HopRewriteUtils.replaceChildReference(parent, bop, tmp, pos); HopRewriteUtils.cleanupUnreferenced(bop, bop2); hi = tmp; LOG.debug("Applied simplifyBinaryComparisonChain0 (line "+hi.getBeginLine()+")"); } } return hi; } private static Hop simplifyCumsumColOrFullAggregates(Hop hi) { //pattern: colSums(cumsum(X)) -> cumSums(X*seq(nrow(X),1)) if( (HopRewriteUtils.isAggUnaryOp(hi, AggOp.SUM, Direction.Col) || HopRewriteUtils.isAggUnaryOp(hi, AggOp.SUM, Direction.RowCol)) && HopRewriteUtils.isUnary(hi.getInput().get(0), OpOp1.CUMSUM) && hi.getInput().get(0).getParent().size()==1) { Hop cumsumX = hi.getInput().get(0); Hop X = cumsumX.getInput().get(0); Hop mult = HopRewriteUtils.createBinary(X, HopRewriteUtils.createSeqDataGenOp(X, false), OpOp2.MULT); HopRewriteUtils.replaceChildReference(hi, cumsumX, mult); HopRewriteUtils.removeAllChildReferences(cumsumX); LOG.debug("Applied simplifyCumsumColOrFullAggregates (line "+hi.getBeginLine()+")"); } return hi; } private static Hop simplifyCumsumReverse(Hop parent, Hop hi, int pos) { //pattern: rev(cumsum(rev(X))) -> X + colSums(X) - cumsum(X) if( HopRewriteUtils.isReorg(hi, ReOrgOp.REV) && HopRewriteUtils.isUnary(hi.getInput().get(0), OpOp1.CUMSUM) && hi.getInput().get(0).getParent().size()==1 && HopRewriteUtils.isReorg(hi.getInput().get(0).getInput().get(0), ReOrgOp.REV) && hi.getInput().get(0).getInput().get(0).getParent().size()==1) { Hop cumsumX = hi.getInput().get(0); Hop revX = cumsumX.getInput().get(0); Hop X = revX.getInput().get(0); Hop plus = HopRewriteUtils.createBinary(X, HopRewriteUtils .createAggUnaryOp(X, AggOp.SUM, Direction.Col), OpOp2.PLUS); Hop minus = HopRewriteUtils.createBinary(plus, HopRewriteUtils.createUnary(X, OpOp1.CUMSUM), OpOp2.MINUS); HopRewriteUtils.replaceChildReference(parent, hi, minus, pos); HopRewriteUtils.cleanupUnreferenced(hi, cumsumX, revX); hi = minus; LOG.debug("Applied simplifyCumsumReverse (line "+hi.getBeginLine()+")"); } return hi; } /** * NOTE: currently disabled since this rewrite is INVALID in the * presence of NaNs (because (NaN!=NaN) is true). * * @param parent parent high-level operator * @param hi high-level operator * @param pos position * @return high-level operator */ @SuppressWarnings("unused") private static Hop removeUnecessaryPPred(Hop parent, Hop hi, int pos) { if( hi instanceof BinaryOp ) { BinaryOp bop = (BinaryOp)hi; Hop left = bop.getInput().get(0); Hop right = bop.getInput().get(1); Hop datagen = null; //ppred(X,X,"==") -> matrix(1, rows=nrow(X),cols=nrow(Y)) if( left==right && bop.getOp()==OpOp2.EQUAL || bop.getOp()==OpOp2.GREATEREQUAL || bop.getOp()==OpOp2.LESSEQUAL ) datagen = HopRewriteUtils.createDataGenOp(left, 1); //ppred(X,X,"!=") -> matrix(0, rows=nrow(X),cols=nrow(Y)) if( left==right && bop.getOp()==OpOp2.NOTEQUAL || bop.getOp()==OpOp2.GREATER || bop.getOp()==OpOp2.LESS ) datagen = HopRewriteUtils.createDataGenOp(left, 0); if( datagen != null ) { HopRewriteUtils.replaceChildReference(parent, hi, datagen, pos); hi = datagen; } } return hi; } }
apache-2.0
ottogroup/SPQR
spqr-repository/src/main/java/com/ottogroup/bi/spqr/repository/ComponentDescriptor.java
2784
/** * Copyright 2014 Otto (GmbH & Co KG) * * 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.ottogroup.bi.spqr.repository; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonProperty; import com.ottogroup.bi.spqr.pipeline.component.MicroPipelineComponentType; /** * Asap component description as extracted from classes annotated as {@link AsapComponent} * @author mnxfst * @since Oct 29, 2014 * */ public class ComponentDescriptor implements Serializable { private static final long serialVersionUID = -1649046223771601278L; @JsonProperty ( value = "componentClass", required = true ) private String componentClass = null; @JsonProperty ( value = "type", required = true ) private MicroPipelineComponentType type = null; @JsonProperty ( value = "name", required = true ) private String name = null; @JsonProperty ( value = "version", required = true ) private String version = null; @JsonProperty ( value = "description", required = true ) private String description = null; /** * Default constructor */ public ComponentDescriptor() { } /** * Initializes the descriptor using the provided input * @param componentClass * @param type * @param name * @param version * @param description */ public ComponentDescriptor(final String componentClass, final MicroPipelineComponentType type, final String name, final String version, final String description) { this.componentClass = componentClass; this.type = type; this.name = name; this.version = version; this.description = description; } public String getComponentClass() { return componentClass; } public void setComponentClass(String componentClass) { this.componentClass = componentClass; } public MicroPipelineComponentType getType() { return type; } public void setType(MicroPipelineComponentType type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
apache-2.0
TranscendComputing/TopStackCore
src/com/msi/tough/engine/aws/elasticache/ParameterGroup.java
3353
/* * TopStack (c) Copyright 2012-2013 Transcend Computing, 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.msi.tough.engine.aws.elasticache; import java.util.List; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.msi.tough.cf.AccountType; import com.msi.tough.cf.CFType; import com.msi.tough.cf.elasticache.ParameterGroupType; import com.msi.tough.core.HibernateUtil; import com.msi.tough.core.HibernateUtil.Operation; import com.msi.tough.engine.core.BaseProvider; import com.msi.tough.engine.core.CallStruct; import com.msi.tough.engine.resource.Resource; import com.msi.tough.model.elasticache.CacheClusterBean; import com.msi.tough.model.elasticache.CacheParameterGroupBean; import com.msi.tough.utils.EcacheUtil; import com.msi.tough.utils.ElasticacheFaults; public class ParameterGroup extends BaseProvider { private static final Logger logger = LoggerFactory .getLogger(CacheCluster.class.getName()); public static String TYPE = "AWS::Elasticache::ParameterGroup"; @Override public CFType create0(final CallStruct call) throws Exception { final AccountType ac = call.getAc(); final String name = call.getName(); final String cacheParameterGroupFamily = (String) call .getProperty("CacheParameterGroupFamily"); final String description = (String) call.getProperty("Description"); HibernateUtil.withNewSession(new Operation<CacheParameterGroupBean>() { @Override public CacheParameterGroupBean ex(final Session s, final Object... args) throws Exception { final CacheParameterGroupBean cacheParameterGroup = EcacheUtil .createParameterGroup(s, ac.getId(), cacheParameterGroupFamily, name, description); return cacheParameterGroup; } }); final ParameterGroupType ret = new ParameterGroupType(); ret.setName(name); return ret; } @Override public Resource delete0(final CallStruct call) throws Exception { super.delete0(call); final AccountType ac = call.getAc(); final String name = call.getPhysicalId(); HibernateUtil.withNewSession(new Operation<Object>() { @Override public Object ex(final Session s, final Object... args) throws Exception { final CacheParameterGroupBean pgrp = EcacheUtil .getCacheParameterGroupBean(s, ac.getId(), name); final List<CacheClusterBean> ccbs = EcacheUtil .selectCacheClusterBean(s, ac.getId(), null); boolean used = false; for (final CacheClusterBean ccb : ccbs) { if (ccb.getParameterGroupId() == pgrp.getId()) { used = true; break; } } if (used) { throw ElasticacheFaults.InvalidCacheParameterGroupState(); } EcacheUtil.deleteParameterGroupBean(s, ac.getId(), name); return null; } }); logger.debug("ParameterGroup deleted " + name); return null; } }
apache-2.0
johanpoirier/Thermonitor
Thermonitor/src/main/java/com/jops/android/thermonitor/service/ThermonitorController.java
2020
package com.jops.android.thermonitor.service; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.SystemClock; import com.jops.android.thermonitor.C; import com.jops.android.thermonitor.SharedPreferencesCompat; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.SystemService; @EBean(scope = EBean.Scope.Singleton) public class ThermonitorController { @RootContext protected Context context; @SystemService protected AlarmManager alarmManager; private static String PREFERENCES_NAME = "com.jops.android.termonitor.controller.ThermonitorController"; public static String PREF_MONITOR_KEY = "monitor"; public void savePref(String name, boolean value) { SharedPreferences.Editor editor = context.getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE).edit(); editor.putBoolean(name, value); SharedPreferencesCompat.apply(editor); } public boolean getBooleanPref(String name) { return context.getSharedPreferences(PREFERENCES_NAME, Activity.MODE_PRIVATE).getBoolean(name, false); } public void setMonitorState(boolean state) { Intent measureIntent = new Intent(context, MeasureRequestReceiver_.class); PendingIntent sender = PendingIntent.getBroadcast(context, C.MEASURE_REQUEST_CODE, measureIntent, PendingIntent.FLAG_CANCEL_CURRENT); if (state) { // We want the alarm to go off 5 seconds from now. long firstTime = SystemClock.elapsedRealtime(); firstTime += 5 * 1000; // Schedule the alarm! alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, C.TEMPERATURE_POLLING_TIME, sender); } else { alarmManager.cancel(sender); } } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-cloudwatchmetrics/src/main/java/com/amazonaws/metrics/internal/cloudwatch/spi/RequestMetricTransformer.java
2588
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.metrics.internal.cloudwatch.spi; import java.util.Date; import java.util.List; import com.amazonaws.Request; import com.amazonaws.Response; import com.amazonaws.metrics.MetricType; import com.amazonaws.services.cloudwatch.model.MetricDatum; import com.amazonaws.util.TimingInfo; /** * Internal SPI used to provide custom request metric transformer that can be * added to or override the default AWS SDK implementation. Implementation of * this interface should ensure the {@link Object#equals(Object)} and * {@link Object#hashCode()} methods are overridden as necessary. */ public interface RequestMetricTransformer { /** * Returns a list of metric datum for the metrics collected for the given * request/response, or null if this transformer does not recognize the * specific input metric type. * <p> * Note returning an empty list means the transformer recognized the metric * type but concluded there is no metrics to be generated for it. * * @param metricType * the predefined metric type */ public List<MetricDatum> toMetricData(MetricType metricType, Request<?> request, Response<?> response); /** A convenient instance of a no-op request metric transformer. */ public static final RequestMetricTransformer NONE = new RequestMetricTransformer() { public List<MetricDatum> toMetricData(MetricType requestMetric, Request<?> request, Response<?> response) { return null; } }; /** Common utilities for implementing this SPI. */ public static enum Utils { ; public static long endTimeMilli(TimingInfo ti) { Long endTimeMilli = ti.getEndEpochTimeMilliIfKnown(); return endTimeMilli == null ? System.currentTimeMillis() : endTimeMilli.longValue(); } public static Date endTimestamp(TimingInfo ti) { return new Date(endTimeMilli(ti)); } } }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p361/Test7227.java
2111
package org.gradle.test.performance.mediummonolithicjavaproject.p361; import org.junit.Test; import static org.junit.Assert.*; public class Test7227 { Production7227 objectUnderTest = new Production7227(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
apache-2.0
vegbye/vsb-fou-pom
vsb-fou-kladd/src/test/java/vsb/fou/kladd/beanlib/VsbBeanLibTest.java
3633
package vsb.fou.kladd.beanlib; import net.sf.beanlib.CollectionPropertyName; import net.sf.beanlib.hibernate.HibernateBeanReplicator; import net.sf.beanlib.hibernate.HibernatePropertyFilter; import net.sf.beanlib.hibernate3.Hibernate3BeanReplicator; import org.apache.log4j.Logger; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class VsbBeanLibTest { private static final Logger log = Logger.getLogger(VsbBeanLibTest.class); @SuppressWarnings("unchecked") @Test public void testBeanLibAntagelser() { Set<CollectionPropertyName<?>> collectionPropertyNameSet = new HashSet<CollectionPropertyName<?>>(); collectionPropertyNameSet.add(new CollectionPropertyName(VsbBeanLibDataA.class, "CList")); collectionPropertyNameSet.add(new CollectionPropertyName(VsbBeanLibDataA.class, "EList")); Set<Class<?>> entityBeanClassSet = createSet(VsbBeanLibDataB.class, VsbBeanLibDataC.class, VsbBeanLibDataD.class, VsbBeanLibDataE.class, VsbBeanLibDataF.class); HibernatePropertyFilter filter = new HibernatePropertyFilter(); filter.withEntityBeanClassSet(entityBeanClassSet); filter.withCollectionPropertyNameSet(collectionPropertyNameSet); HibernateBeanReplicator r = new Hibernate3BeanReplicator(); r.initPropertyFilter(filter); VsbBeanLibDataA fromBean = new VsbBeanLibDataA(); fromBean.setEnumA(VsbBeanLibEnumA.HvitVin); fromBean.setK(56); fromBean.setS("SPK Perform"); fromBean.setC(VsbBeanLibDataC.newInstance("INDIGO", VsbBeanLibDataD.newInstance("RoseVin"))); VsbBeanLibDataC c = VsbBeanLibDataC.newInstance("BL�", VsbBeanLibDataD.newInstance("HvitVin")); fromBean.getCList().add(c); fromBean.getCList().add(c); fromBean.getCList().add(c); fromBean.getEList().add(VsbBeanLibDataE.newInstance("Majorstua")); fromBean.setB(VsbBeanLibDataB.newInstance("Fagerborg")); VsbBeanLibDataA toBean = r.copy(fromBean, VsbBeanLibDataA.class); log.info("fromBean: " + fromBean); log.info("toBean: " + toBean); assertEquals(fromBean.getB(), toBean.getB()); assertEquals(3, fromBean.getCList().size()); assertTrue(fromBean.getCList().get(0) == fromBean.getCList().get(0)); assertTrue(fromBean.getCList().get(0) == fromBean.getCList().get(1)); assertTrue(fromBean.getCList().get(0) == fromBean.getCList().get(2)); assertEquals(3, toBean.getCList().size()); assertTrue(toBean.getCList().get(0) == toBean.getCList().get(0)); assertTrue(toBean.getCList().get(0) == toBean.getCList().get(1)); assertTrue(toBean.getCList().get(0) == toBean.getCList().get(2)); assertEquals(1, fromBean.getEList().size()); assertEquals(1, toBean.getEList().size()); assertEquals(fromBean.getEList().get(0), toBean.getEList().get(0)); assertTrue(fromBean.getEList().get(0) == fromBean.getEList().get(0)); assertTrue(toBean.getEList().get(0) == toBean.getEList().get(0)); assertTrue(fromBean.getEList().get(0) != toBean.getEList().get(0)); assertEquals(fromBean, fromBean); assertEquals(toBean, toBean); assertEquals(fromBean, toBean); } private static Set<Class<?>> createSet(Class<?>... classes) { Set<Class<?>> classSet = new HashSet<Class<?>>(); for (int i = 0; i < classes.length; i++) { classSet.add(classes[i]); } return classSet; } }
apache-2.0
gastaldi/hibernate-validator
hibernate-validator/src/main/java/org/hibernate/validator/metadata/aggregated/BeanMetaDataImpl.java
20536
/* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual 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.hibernate.validator.metadata.aggregated; import java.lang.annotation.ElementType; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.validation.GroupDefinitionException; import javax.validation.groups.Default; import javax.validation.metadata.BeanDescriptor; import javax.validation.metadata.PropertyDescriptor; import org.slf4j.Logger; import org.hibernate.validator.group.DefaultGroupSequenceProvider; import org.hibernate.validator.metadata.aggregated.ConstraintMetaData.ConstraintMetaDataKind; import org.hibernate.validator.metadata.core.ConstraintHelper; import org.hibernate.validator.metadata.core.MetaConstraint; import org.hibernate.validator.metadata.descriptor.BeanDescriptorImpl; import org.hibernate.validator.metadata.descriptor.ConstraintDescriptorImpl; import org.hibernate.validator.metadata.raw.BeanConfiguration; import org.hibernate.validator.metadata.raw.ConfigurationSource; import org.hibernate.validator.metadata.raw.ConstrainedElement; import org.hibernate.validator.metadata.raw.ConstrainedElement.ConstrainedElementKind; import org.hibernate.validator.metadata.raw.ConstrainedField; import org.hibernate.validator.metadata.raw.ConstrainedMethod; import org.hibernate.validator.metadata.raw.ConstrainedType; import org.hibernate.validator.method.metadata.MethodDescriptor; import org.hibernate.validator.method.metadata.TypeDescriptor; import org.hibernate.validator.util.CollectionHelper.Partitioner; import org.hibernate.validator.util.LoggerFactory; import org.hibernate.validator.util.ReflectionHelper; import static org.hibernate.validator.util.CollectionHelper.newArrayList; import static org.hibernate.validator.util.CollectionHelper.newHashMap; import static org.hibernate.validator.util.CollectionHelper.newHashSet; import static org.hibernate.validator.util.CollectionHelper.partition; import static org.hibernate.validator.util.ReflectionHelper.computeAllImplementedInterfaces; import static org.hibernate.validator.util.ReflectionHelper.getMethods; import static org.hibernate.validator.util.ReflectionHelper.newInstance; /** * This class encapsulates all meta data needed for validation. Implementations of {@code Validator} interface can * instantiate an instance of this class and delegate the metadata extraction to it. * * @author Hardy Ferentschik * @author Gunnar Morling * @author Kevin Pollet <kevin.pollet@serli.com> (C) 2011 SERLI */ public final class BeanMetaDataImpl<T> implements BeanMetaData<T> { private static final Logger log = LoggerFactory.make(); /** * The root bean class for this meta data. */ private final Class<T> beanClass; /** * Set of all constraints for this bean type (defined on any implemented interfaces or super types) */ private final Set<MetaConstraint<?>> allMetaConstraints; /** * Set of all constraints which are directly defined on the bean or any of the directly implemented interfaces */ private final Set<MetaConstraint<?>> directMetaConstraints; /** * Contains constrained related meta data for all methods of the type * represented by this bean meta data. Keyed by method, values are an * aggregated view on each method together with all the methods from the * inheritance hierarchy with the same signature. */ private final Map<String, MethodMetaData> methodMetaData; private final Map<String, PropertyMetaData> propertyMetaData; /** * List of cascaded members. */ private final Set<Member> cascadedMembers; /** * The default groups sequence for this bean class. */ private List<Class<?>> defaultGroupSequence = newArrayList(); /** * The default group sequence provider. * * @see org.hibernate.validator.group.GroupSequenceProvider * @see DefaultGroupSequenceProvider */ private DefaultGroupSequenceProvider<T> defaultGroupSequenceProvider; /** * The class hierarchy for this class starting with the class itself going up the inheritance chain. Interfaces * are not included. */ private List<Class<?>> classHierarchyWithoutInterfaces; /** * Creates a new {@link BeanMetaDataImpl} * * @param beanClass The Java type represented by this meta data object. * @param defaultGroupSequence The default group sequence. * @param defaultGroupSequenceProvider The default group sequence provider if set. * @param constraintMetaData All constraint meta data relating to the represented type. */ public BeanMetaDataImpl(Class<T> beanClass, List<Class<?>> defaultGroupSequence, Class<? extends DefaultGroupSequenceProvider<?>> defaultGroupSequenceProvider, Set<ConstraintMetaData> constraintMetaData) { this.beanClass = beanClass; this.propertyMetaData = newHashMap(); Set<PropertyMetaData> propertyMetaDataSet = newHashSet(); Set<MethodMetaData> methodMetaDataSet = newHashSet(); for ( ConstraintMetaData oneElement : constraintMetaData ) { if ( oneElement.getKind() == ConstraintMetaDataKind.PROPERTY ) { propertyMetaDataSet.add( (PropertyMetaData) oneElement ); } else { methodMetaDataSet.add( (MethodMetaData) oneElement ); } } Set<Member> cascadedMembers = newHashSet(); Set<MetaConstraint<?>> allMetaConstraints = newHashSet(); for ( PropertyMetaData oneProperty : propertyMetaDataSet ) { propertyMetaData.put( oneProperty.getName(), oneProperty ); if ( oneProperty.isCascading() ) { cascadedMembers.addAll( oneProperty.getCascadingMembers() ); } allMetaConstraints.addAll( oneProperty.getConstraints() ); } this.cascadedMembers = Collections.unmodifiableSet( cascadedMembers ); this.allMetaConstraints = Collections.unmodifiableSet( allMetaConstraints ); classHierarchyWithoutInterfaces = ReflectionHelper.computeClassHierarchy( beanClass, false ); setDefaultGroupSequenceOrProvider( defaultGroupSequence, defaultGroupSequenceProvider ); directMetaConstraints = buildDirectConstraintSets(); this.methodMetaData = Collections.unmodifiableMap( buildMethodMetaData( methodMetaDataSet ) ); } public Class<T> getBeanClass() { return beanClass; } public BeanDescriptor getBeanDescriptor() { return getBeanDescriptorInternal(); } public TypeDescriptor getTypeDescriptor() { return getBeanDescriptorInternal(); } public Set<Member> getCascadedMembers() { return cascadedMembers; } public Set<MetaConstraint<?>> getMetaConstraints() { return allMetaConstraints; } public Set<MetaConstraint<?>> getDirectMetaConstraints() { return directMetaConstraints; } public MethodMetaData getMetaDataFor(Method method) { return methodMetaData.get( method.getName() + Arrays.toString( method.getParameterTypes() ) ); } public Set<MethodMetaData> getAllMethodMetaData() { return new HashSet<MethodMetaData>( methodMetaData.values() ); } public PropertyMetaData getMetaDataFor(String propertyName) { return propertyMetaData.get( propertyName ); } public boolean isPropertyPresent(String name) { return propertyMetaData.containsKey( name ); } public List<Class<?>> getDefaultGroupSequence(T beanState) { if ( hasDefaultGroupSequenceProvider() ) { List<Class<?>> providerDefaultGroupSequence = defaultGroupSequenceProvider.getValidationGroups( beanState ); return getValidDefaultGroupSequence( providerDefaultGroupSequence ); } return Collections.unmodifiableList( defaultGroupSequence ); } public boolean defaultGroupSequenceIsRedefined() { return defaultGroupSequence.size() > 1 || hasDefaultGroupSequenceProvider(); } public Set<PropertyMetaData> getAllPropertyMetaData() { return Collections.unmodifiableSet( new HashSet<PropertyMetaData>( propertyMetaData.values() ) ); } public List<Class<?>> getClassHierarchy() { return classHierarchyWithoutInterfaces; } /** * Returns a bean descriptor representing this meta data object. A new * descriptor instance is created with each invocation. The descriptor might * be cached internally in the future should that need arise. * * @return A bean descriptor for this meta data object. */ private BeanDescriptorImpl<T> getBeanDescriptorInternal() { return new BeanDescriptorImpl<T>( beanClass, getClassLevelConstraintsAsDescriptors(), getConstrainedPropertiesAsDescriptors(), getMethodsAsDescriptors(), defaultGroupSequenceIsRedefined(), getDefaultGroupSequence( null ) ); } private Set<ConstraintDescriptorImpl<?>> getClassLevelConstraintsAsDescriptors() { Set<MetaConstraint<?>> classLevelConstraints = getClassLevelConstraints( allMetaConstraints ); Set<ConstraintDescriptorImpl<?>> theValue = newHashSet(); for ( MetaConstraint<?> oneConstraint : classLevelConstraints ) { theValue.add( oneConstraint.getDescriptor() ); } return theValue; } private Map<String, PropertyDescriptor> getConstrainedPropertiesAsDescriptors() { Map<String, PropertyDescriptor> theValue = newHashMap(); for ( Entry<String, PropertyMetaData> oneProperty : propertyMetaData.entrySet() ) { if ( oneProperty.getValue().isConstrained() ) { theValue.put( oneProperty.getKey(), oneProperty.getValue() .asDescriptor( defaultGroupSequenceIsRedefined(), getDefaultGroupSequence( null ) ) ); } } return theValue; } private Map<String, MethodDescriptor> getMethodsAsDescriptors() { Map<String, MethodDescriptor> theValue = newHashMap(); for ( Entry<String, MethodMetaData> oneMethod : methodMetaData.entrySet() ) { theValue.put( oneMethod.getKey(), oneMethod.getValue().asDescriptor( defaultGroupSequenceIsRedefined(), getDefaultGroupSequence( null ) ) ); } return theValue; } private void setDefaultGroupSequenceOrProvider(List<Class<?>> defaultGroupSequence, Class<? extends DefaultGroupSequenceProvider<?>> defaultGroupSequenceProvider) { if ( defaultGroupSequence != null && defaultGroupSequenceProvider != null ) { throw new GroupDefinitionException( "Default group sequence and default group sequence provider cannot be defined at the same time." ); } if ( defaultGroupSequenceProvider != null ) { this.defaultGroupSequenceProvider = newGroupSequenceProviderInstance( defaultGroupSequenceProvider ); } else if ( defaultGroupSequence != null && !defaultGroupSequence.isEmpty() ) { setDefaultGroupSequence( defaultGroupSequence ); } else { setDefaultGroupSequence( Arrays.<Class<?>>asList( beanClass ) ); } } private Set<MetaConstraint<?>> getClassLevelConstraints(Set<MetaConstraint<?>> constraints) { Set<MetaConstraint<?>> classLevelConstraints = partition( constraints, byElementType() ).get( ElementType.TYPE ); return classLevelConstraints != null ? classLevelConstraints : Collections.<MetaConstraint<?>>emptySet(); } private Set<MetaConstraint<?>> buildDirectConstraintSets() { Set<MetaConstraint<?>> constraints = newHashSet(); Set<Class<?>> classAndInterfaces = computeAllImplementedInterfaces( beanClass ); classAndInterfaces.add( beanClass ); for ( Class<?> clazz : classAndInterfaces ) { for ( MetaConstraint<?> oneConstraint : allMetaConstraints ) { if ( oneConstraint.getLocation().getBeanClass().equals( clazz ) ) { constraints.add( oneConstraint ); } } } return Collections.unmodifiableSet( constraints ); } /** * Builds up the method meta data for this type */ private Map<String, MethodMetaData> buildMethodMetaData(Set<MethodMetaData> allMethodMetaData) { Map<String, MethodMetaData> theValue = newHashMap(); for ( MethodMetaData oneAggregatedMethodMetaData : allMethodMetaData ) { theValue.put( oneAggregatedMethodMetaData.getName() + Arrays.toString( oneAggregatedMethodMetaData.getParameterTypes() ), oneAggregatedMethodMetaData ); } return theValue; } private void setDefaultGroupSequence(List<Class<?>> groupSequence) { defaultGroupSequence = getValidDefaultGroupSequence( groupSequence ); } private List<Class<?>> getValidDefaultGroupSequence(List<Class<?>> groupSequence) { List<Class<?>> validDefaultGroupSequence = new ArrayList<Class<?>>(); boolean groupSequenceContainsDefault = false; if ( groupSequence != null ) { for ( Class<?> group : groupSequence ) { if ( group.getName().equals( beanClass.getName() ) ) { validDefaultGroupSequence.add( Default.class ); groupSequenceContainsDefault = true; } else if ( group.getName().equals( Default.class.getName() ) ) { throw new GroupDefinitionException( "'Default.class' cannot appear in default group sequence list." ); } else { validDefaultGroupSequence.add( group ); } } } if ( !groupSequenceContainsDefault ) { throw new GroupDefinitionException( beanClass.getName() + " must be part of the redefined default group sequence." ); } if ( log.isTraceEnabled() ) { log.trace( "Members of the default group sequence for bean {} are: {}", beanClass.getName(), validDefaultGroupSequence ); } return validDefaultGroupSequence; } private boolean hasDefaultGroupSequenceProvider() { return defaultGroupSequenceProvider != null; } @SuppressWarnings("unchecked") private <U extends DefaultGroupSequenceProvider<?>> DefaultGroupSequenceProvider<T> newGroupSequenceProviderInstance(Class<U> providerClass) { Method[] providerMethods = getMethods( providerClass ); for ( Method method : providerMethods ) { Class<?>[] paramTypes = method.getParameterTypes(); if ( "getValidationGroups".equals( method.getName() ) && !method.isBridge() && paramTypes.length == 1 && paramTypes[0].isAssignableFrom( beanClass ) ) { return (DefaultGroupSequenceProvider<T>) newInstance( providerClass, "the default group sequence provider" ); } } throw new GroupDefinitionException( "The default group sequence provider defined for " + beanClass.getName() + " has the wrong type" ); } private Partitioner<ElementType, MetaConstraint<?>> byElementType() { return new Partitioner<ElementType, MetaConstraint<?>>() { public ElementType getPartition(MetaConstraint<?> constraint) { return constraint.getElementType(); } }; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append( "BeanMetaDataImpl" ); sb.append( "{beanClass=" ).append( beanClass.getSimpleName() ); sb.append( ", constraintCount=" ).append( getMetaConstraints().size() ); sb.append( ", cascadedMemberCount=" ).append( cascadedMembers.size() ); sb.append( ", defaultGroupSequence=" ).append( getDefaultGroupSequence( null ) ); sb.append( '}' ); return sb.toString(); } public static class BeanMetaDataBuilder<T> { private final ConstraintHelper constraintHelper; private final Class<T> beanClass; private final Set<BuilderDelegate> builders = newHashSet(); private ConfigurationSource sequenceSource; private ConfigurationSource providerSource; private List<Class<?>> defaultGroupSequence; private Class<? extends DefaultGroupSequenceProvider<?>> defaultGroupSequenceProvider; public BeanMetaDataBuilder(ConstraintHelper constraintHelper, Class<T> beanClass) { this.beanClass = beanClass; this.constraintHelper = constraintHelper; } public static <T> BeanMetaDataBuilder<T> getInstance(ConstraintHelper constraintHelper, Class<T> beanClass) { return new BeanMetaDataBuilder<T>( constraintHelper, beanClass ); } public void add(BeanConfiguration<?> configuration) { if ( configuration.getBeanClass().equals( beanClass ) ) { if ( configuration.getDefaultGroupSequence() != null && ( sequenceSource == null || configuration.getSource() .getPriority() >= sequenceSource.getPriority() ) ) { sequenceSource = configuration.getSource(); defaultGroupSequence = configuration.getDefaultGroupSequence(); } if ( configuration.getDefaultGroupSequenceProvider() != null && ( providerSource == null || configuration.getSource() .getPriority() >= providerSource.getPriority() ) ) { providerSource = configuration.getSource(); defaultGroupSequenceProvider = configuration.getDefaultGroupSequenceProvider(); } } for ( ConstrainedElement oneConstrainedElement : configuration.getConstrainedElements() ) { addMetaDataToBuilder( oneConstrainedElement, builders ); } } private void addMetaDataToBuilder(ConstrainedElement constrainableElement, Set<BuilderDelegate> builders) { for ( BuilderDelegate oneBuilder : builders ) { boolean foundBuilder = oneBuilder.add( constrainableElement ); if ( foundBuilder ) { return; } } builders.add( new BuilderDelegate( constrainableElement, constraintHelper ) ); } public BeanMetaDataImpl<T> build() { Set<ConstraintMetaData> aggregatedElements = newHashSet(); for ( BuilderDelegate oneBuilder : builders ) { aggregatedElements.addAll( oneBuilder.build( ( defaultGroupSequence != null && defaultGroupSequence.size() > 1 ) || defaultGroupSequenceProvider != null, defaultGroupSequence ) ); } return new BeanMetaDataImpl<T>( beanClass, defaultGroupSequence, defaultGroupSequenceProvider, aggregatedElements ); } } private static class BuilderDelegate { private final ConstraintHelper constraintHelper; private MetaDataBuilder propertyBuilder; private MethodMetaData.Builder methodBuilder; public BuilderDelegate(ConstrainedElement constrainedElement, ConstraintHelper constraintHelper) { this.constraintHelper = constraintHelper; switch ( constrainedElement.getKind() ) { case FIELD: ConstrainedField constrainedField = (ConstrainedField) constrainedElement; propertyBuilder = new PropertyMetaData.Builder( constrainedField, constraintHelper ); break; case METHOD: ConstrainedMethod constrainedMethod = (ConstrainedMethod) constrainedElement; methodBuilder = new MethodMetaData.Builder( constrainedMethod, constraintHelper ); if ( constrainedMethod.isGetterMethod() ) { propertyBuilder = new PropertyMetaData.Builder( constrainedMethod, constraintHelper ); } break; case TYPE: ConstrainedType constrainedType = (ConstrainedType) constrainedElement; propertyBuilder = new PropertyMetaData.Builder( constrainedType, constraintHelper ); break; } } public boolean add(ConstrainedElement constrainedElement) { boolean added = false; if ( methodBuilder != null && methodBuilder.accepts( constrainedElement ) ) { methodBuilder.add( constrainedElement ); added = true; } if ( propertyBuilder != null && propertyBuilder.accepts( constrainedElement ) ) { propertyBuilder.add( constrainedElement ); if ( added == false && constrainedElement.getKind() == ConstrainedElementKind.METHOD && methodBuilder == null ) { ConstrainedMethod constrainedMethod = (ConstrainedMethod) constrainedElement; methodBuilder = new MethodMetaData.Builder( constrainedMethod, constraintHelper ); } added = true; } return added; } public Set<ConstraintMetaData> build(boolean defaultGroupSequenceRedefined, List<Class<?>> defaultGroupSequence) { Set<ConstraintMetaData> theValue = newHashSet(); if ( propertyBuilder != null ) { theValue.add( propertyBuilder.build() ); } if ( methodBuilder != null ) { theValue.add( methodBuilder.build() ); } return theValue; } } }
apache-2.0
gosu-lang/old-gosu-repo
gosu-core-api/src/main/java/gw/lang/reflect/java/IJavaMethodInfo.java
767
/* * Copyright 2013 Guidewire Software, Inc. */ package gw.lang.reflect.java; import gw.lang.javadoc.IDocRef; import gw.lang.javadoc.IMethodNode; import gw.lang.javadoc.JavaHasParams; import gw.lang.reflect.IAttributedFeatureInfo; import gw.lang.reflect.IGenericMethodInfo; import gw.lang.reflect.IMethodInfo; import gw.lang.reflect.IParameterInfo; import gw.lang.reflect.IType; import java.lang.reflect.Method; public interface IJavaMethodInfo extends IAttributedFeatureInfo, IMethodInfo, IGenericMethodInfo, JavaHasParams { IParameterInfo[] getGenericParameters(); IType getGenericReturnType(); String getShortDescription(); IJavaClassMethod getMethod(); IDocRef<IMethodNode> getMethodDocs(); Method getRawMethod(); int getModifiers(); }
apache-2.0
ebayopensource/turmeric-runtime
codegen/codegen-tools/src/main/java/org/ebayopensource/turmeric/tools/codegen/external/wsdl/parser/schema/SimpleTypeRestriction.java
5310
/** * */ package org.ebayopensource.turmeric.tools.codegen.external.wsdl.parser.schema; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @author rkulandaivel * */ public class SimpleTypeRestriction extends Annotation { private QName base = null; List<Attribute> attributes = new ArrayList<Attribute>(); List<AttributeGroup> attributeGroups = new ArrayList<AttributeGroup>(); List<RestrictionEnumeration> enumerations = new ArrayList<RestrictionEnumeration>(); private int fractionDigits = -1; private int length = -1; private BigDecimal maxExclusive = null; private BigDecimal minExclusive = null; private BigDecimal maxInclusive = null; private BigDecimal minInclusive = null; private int maxLength = -1; private int minLength = -1; private String pattern = null; private String whiteSpace = null; private int totalDigits = -1; public SimpleTypeRestriction(Element el, String tns) { super(el, tns); base = SchemaType.getAttributeQName(el, "base"); NodeList children = el.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { Element subEl = (Element) child; String elType = subEl.getLocalName(); QName value = SchemaType.getAttributeQName(subEl, "value"); if (elType.equals("fractionDigits") && (value != null) ) { fractionDigits = Integer.parseInt(value.getLocalPart()); }else if(elType.equals("length") && (value != null) ) { length = Integer.parseInt(value.getLocalPart()); }else if(elType.equals("maxExclusive") && (value != null) ) { maxExclusive = new BigDecimal(value.getLocalPart()); }else if(elType.equals("maxInclusive") && (value != null) ) { maxInclusive = new BigDecimal(value.getLocalPart()); }else if(elType.equals("maxLength") && (value != null) ) { maxLength = Integer.parseInt(value.getLocalPart()); }else if(elType.equals("minExclusive") && (value != null) ) { minExclusive = new BigDecimal(value.getLocalPart()); }else if(elType.equals("minInclusive") && (value != null) ) { minInclusive = new BigDecimal(value.getLocalPart()); }else if(elType.equals("minLength") && (value != null) ) { minLength = Integer.parseInt(value.getLocalPart()); }else if(elType.equals("pattern") && (value != null) ) { pattern = value.getLocalPart(); }else if(elType.equals("totalDigits") && (value != null) ) { totalDigits = Integer.parseInt(value.getLocalPart()); }else if(elType.equals("whiteSpace") && (value != null) ) { whiteSpace = value.getLocalPart(); } else if(elType.equals("attributeGroup")){ attributeGroups.add(new AttributeGroup(subEl, tns)); } else if(elType.equals("attribute")){ attributes.add(new Attribute(subEl, tns)); }else if(elType.equals("enumeration")){ enumerations.add( new RestrictionEnumeration(subEl, tns) ); } } } } public QName getBase() { return base; } public List<Attribute> getAttributes() { return attributes; } public List<AttributeGroup> getAttributeGroups() { return attributeGroups; } public List<RestrictionEnumeration> getEnumerations() { return enumerations; } public boolean hasFractionDigits() { return fractionDigits != -1; } public int getFractionDigits() { return fractionDigits; } public boolean hasLength() { return length != -1; } public int getLength() { return length; } public boolean hasMaxExclusive() { return maxExclusive != null; } public BigDecimal getMaxExclusive() { return maxExclusive; } public boolean hasMinExclusive() { return minExclusive != null; } public BigDecimal getMinExclusive() { return minExclusive; } public boolean hasMaxInclusive() { return maxInclusive != null; } public BigDecimal getMaxInclusive() { return maxInclusive; } public boolean hasMinInclusive() { return minInclusive != null; } public BigDecimal getMinInclusive() { return minInclusive; } public boolean hasMaxLength() { return maxLength != -1; } public int getMaxLength() { return maxLength; } public boolean hasMinLength() { return minLength != -1; } public int getMinLength() { return minLength; } public boolean hasPattern() { return pattern !=null; } public String getPattern() { return pattern; } public boolean hasWhiteSpace() { return whiteSpace != null; } public String getWhiteSpace() { return whiteSpace; } public boolean hasTotalDigits() { return totalDigits != -1; } public int getTotalDigits() { return totalDigits; } }
apache-2.0
tywe/git-test
basic-struts/src/main/java/org/teng/struts/basic/service/Service.java
71
package org.teng.struts.basic.service; public class Service { }
apache-2.0
ytai/ioio
applications/pc/HelloSequencer/src/main/java/ioio/examples/hello_sequencer/HelloSequencer.java
5405
package ioio.examples.hello_sequencer; import ioio.lib.api.DigitalOutput; import ioio.lib.api.Sequencer; import ioio.lib.api.Sequencer.ChannelConfig; import ioio.lib.api.Sequencer.ChannelConfigBinary; import ioio.lib.api.Sequencer.ChannelConfigPwmSpeed; import ioio.lib.api.Sequencer.ChannelConfigSteps; import ioio.lib.api.Sequencer.ChannelCueBinary; import ioio.lib.api.Sequencer.ChannelCuePwmSpeed; import ioio.lib.api.Sequencer.ChannelCueSteps; import ioio.lib.api.Sequencer.Clock; import ioio.lib.api.exception.ConnectionLostException; import ioio.lib.util.BaseIOIOLooper; import ioio.lib.util.IOIOLooper; import ioio.lib.util.pc.IOIOConsoleApp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class HelloSequencer extends IOIOConsoleApp { // Boilerplate main(). Copy-paste this code into any IOIOapplication. public static void main(String[] args) throws Exception { new HelloSequencer().go(args); } @Override protected void run(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); boolean abort = false; String line; while (!abort && (line = reader.readLine()) != null) { if (line.equals("q")) { abort = true; } else { System.out.println("Unknown input. q=quit."); } } } @Override public IOIOLooper createIOIOLooper(String connectionType, Object extra) { return new BaseIOIOLooper() { private boolean dir_ = false; private int color_ = 0; private Sequencer.ChannelCueBinary led1Cue_ = new ChannelCueBinary(); private Sequencer.ChannelCueBinary led2Cue_ = new ChannelCueBinary(); private Sequencer.ChannelCueBinary led3Cue_ = new ChannelCueBinary(); private Sequencer.ChannelCuePwmSpeed dcMotorACue_ = new ChannelCuePwmSpeed(); private Sequencer.ChannelCuePwmSpeed dcMotorBCue_ = new ChannelCuePwmSpeed(); private Sequencer.ChannelCueBinary stepperDirCue_ = new ChannelCueBinary(); private Sequencer.ChannelCueSteps stepperStepCue_ = new ChannelCueSteps(); private Sequencer.ChannelCue[] cue_ = new Sequencer.ChannelCue[]{led1Cue_, led2Cue_, led3Cue_, dcMotorACue_, dcMotorBCue_, stepperDirCue_, stepperStepCue_}; private Sequencer sequencer_; @Override protected void setup() throws ConnectionLostException, InterruptedException { final ChannelConfigBinary led1Config = new Sequencer.ChannelConfigBinary(true, true, new DigitalOutput.Spec(5, DigitalOutput.Spec.Mode.OPEN_DRAIN)); final ChannelConfigBinary led2Config = new Sequencer.ChannelConfigBinary(true, true, new DigitalOutput.Spec(6, DigitalOutput.Spec.Mode.OPEN_DRAIN)); final ChannelConfigBinary led3Config = new Sequencer.ChannelConfigBinary(true, true, new DigitalOutput.Spec(7, DigitalOutput.Spec.Mode.OPEN_DRAIN)); final ChannelConfigPwmSpeed dcMotorAConfig = new Sequencer.ChannelConfigPwmSpeed( Sequencer.Clock.CLK_2M, 2000, 0, new DigitalOutput.Spec(1)); final ChannelConfigPwmSpeed dcMotorBConfig = new Sequencer.ChannelConfigPwmSpeed( Sequencer.Clock.CLK_2M, 2000, 0, new DigitalOutput.Spec(2)); final ChannelConfigBinary stepperDirConfig = new Sequencer.ChannelConfigBinary( false, false, new DigitalOutput.Spec(3)); final ChannelConfigSteps stepperStepConfig = new ChannelConfigSteps( new DigitalOutput.Spec(4)); final ChannelConfig[] config = new ChannelConfig[]{led1Config, led2Config, led3Config, dcMotorAConfig, dcMotorBConfig, stepperDirConfig, stepperStepConfig}; sequencer_ = ioio_.openSequencer(config); // Pre-fill. sequencer_.waitEventType(Sequencer.Event.Type.STOPPED); while (sequencer_.available() > 0) { push(); } sequencer_.start(); } @Override public void loop() throws ConnectionLostException, InterruptedException { push(); } private void push() throws ConnectionLostException, InterruptedException { stepperStepCue_.clk = Clock.CLK_2M; stepperStepCue_.pulseWidth = 2; stepperStepCue_.period = 400; if (dir_) { dcMotorACue_.pulseWidth = 1000; dcMotorBCue_.pulseWidth = 0; stepperDirCue_.value = false; } else { dcMotorACue_.pulseWidth = 0; dcMotorBCue_.pulseWidth = 1000; stepperDirCue_.value = true; } led1Cue_.value = (color_ & 1) == 0; led2Cue_.value = (color_ & 2) == 0; led3Cue_.value = (color_ & 4) == 0; sequencer_.push(cue_, 62500 / 2); dir_ = !dir_; color_++; } }; } }
apache-2.0
pveyron/dosport
dosport-core/src/main/java/org/springframework/context/config/ContextNamespaceHandler.java
1387
package org.springframework.context.config; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; import org.springframework.context.annotation.AnnotationConfigBeanDefinitionParser; import org.springframework.context.annotation.ComponentScanBeanDefinitionParser; import com.dosport.springframework.remoting.httpinvoker.RemoteBeanDefinitionParser; /** * <context:remote-export />命名空间. * * @author pwl * */ public class ContextNamespaceHandler extends NamespaceHandlerSupport { @Override public void init() { registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser()); registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser()); registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser()); registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser()); registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser()); registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser()); registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser()); registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser()); registerBeanDefinitionParser("remote-export", new RemoteBeanDefinitionParser()); } }
apache-2.0
jsakamoto/selenium
java/client/src/org/openqa/selenium/remote/RemoteMouse.java
2826
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium.remote; import com.google.common.collect.ImmutableMap; import org.openqa.selenium.interactions.Coordinates; import org.openqa.selenium.interactions.Mouse; import java.util.HashMap; import java.util.Map; /** * Executes wire commands for mouse interaction. */ public class RemoteMouse implements Mouse { protected final ExecuteMethod executor; public RemoteMouse(ExecuteMethod executor) { this.executor = executor; } protected Map<String, Object> paramsFromCoordinates(Coordinates where) { Map<String, Object> params = new HashMap<>(); if (where != null) { String id = (String) where.getAuxiliary(); params.put("element", id); } return params; } protected void moveIfNeeded(Coordinates where) { if (where != null) { mouseMove(where); } } public void click(Coordinates where) { moveIfNeeded(where); executor.execute(DriverCommand.CLICK, ImmutableMap.of("button", 0)); } public void contextClick(Coordinates where) { moveIfNeeded(where); executor.execute(DriverCommand.CLICK, ImmutableMap.of("button", 2)); } public void doubleClick(Coordinates where) { moveIfNeeded(where); executor.execute(DriverCommand.DOUBLE_CLICK, ImmutableMap.of()); } public void mouseDown(Coordinates where) { moveIfNeeded(where); executor.execute(DriverCommand.MOUSE_DOWN, ImmutableMap.of()); } public void mouseUp(Coordinates where) { moveIfNeeded(where); executor.execute(DriverCommand.MOUSE_UP, ImmutableMap.of()); } public void mouseMove(Coordinates where) { Map<String, Object> moveParams = paramsFromCoordinates(where); executor.execute(DriverCommand.MOVE_TO, moveParams); } public void mouseMove(Coordinates where, long xOffset, long yOffset) { Map<String, Object> moveParams = paramsFromCoordinates(where); moveParams.put("xoffset", xOffset); moveParams.put("yoffset", yOffset); executor.execute(DriverCommand.MOVE_TO, moveParams); } }
apache-2.0
tesshucom/subsonic-fx-player
subsonic-fx-player-api/src/main/java/com/tesshu/subsonic/client/fx/command/logic/EditPlaylistLogic.java
1158
/** * Copyright © 2017 tesshu.com (webmaster@tesshu.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.tesshu.subsonic.client.fx.command.logic; import com.tesshu.subsonic.client.fx.command.ICancellableLogic; import com.tesshu.subsonic.client.fx.command.UpdateComponentCancellerLogic; import com.tesshu.subsonic.client.fx.command.param.SimpleObjectParam; import com.tesshu.subsonic.client.fx.view.playlists.PlaylistsContainer; import com.tesshu.subsonic.client.model.Playlist; public interface EditPlaylistLogic extends UpdateComponentCancellerLogic<PlaylistsContainer, SimpleObjectParam<Playlist>>, ICancellableLogic { }
apache-2.0
virtuozo/spa-framework
bootstrap/src/main/java/virtuozo/interfaces/RichHeading.java
2092
/** * Copyright (C) 2004-2014 the original author or authors. See the notice.md file distributed with * this work for additional information regarding copyright ownership. * * 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 virtuozo.interfaces; import virtuozo.infra.Elements; import virtuozo.interfaces.Heading.Level; import com.google.gwt.dom.client.Element; public final class RichHeading extends Component<RichHeading> implements HasText<RichHeading> { private Text textHolder = Text.create(); private Tag<Element> secondary = Tag.as(Elements.small()).hide(); public static RichHeading one(){ return new RichHeading(Level.ONE); } public static RichHeading two(){ return new RichHeading(Level.TWO); } public static RichHeading three(){ return new RichHeading(Level.THREE); } public static RichHeading four(){ return new RichHeading(Level.FOUR); } public static RichHeading five(){ return new RichHeading(Level.FIVE); } public static RichHeading six(){ return new RichHeading(Level.SIX); } private RichHeading(Level level) { super(Elements.heading(level.ordinal() + 1)); this.addChild(this.textHolder).addChild(this.secondary); } public RichHeading headline(String text) { this.secondary.text(text).show(); return this; } public String headline() { return this.secondary.text(); } @Override public RichHeading text(String text) { this.textHolder.text(text); return this; } @Override public String text() { return this.textHolder.text(); } }
apache-2.0
legrosbuffle/kythe
kythe/java/com/google/devtools/kythe/analyzers/java/KytheDocTreeScanner.java
3507
/* * Copyright 2015 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.kythe.analyzers.java; import com.google.devtools.kythe.analyzers.base.EntrySet; import com.google.devtools.kythe.common.FormattingLogger; import com.sun.source.doctree.ReferenceTree; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreePathScanner; import com.sun.source.util.DocTrees; import com.sun.source.util.TreePath; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.tree.DCTree.DCDocComment; import com.sun.tools.javac.tree.DCTree.DCReference; import com.sun.tools.javac.util.Context; import java.util.ArrayList; import java.util.List; public class KytheDocTreeScanner extends DocTreePathScanner<Void, DCDocComment> { private static final FormattingLogger logger = FormattingLogger.getLogger(KytheDocTreeScanner.class); private final KytheTreeScanner treeScanner; private final List<MiniAnchor<Symbol>> miniAnchors; private final DocTrees trees; public KytheDocTreeScanner(KytheTreeScanner treeScanner, Context context) { this.treeScanner = treeScanner; this.miniAnchors = new ArrayList<>(); this.trees = JavacTrees.instance(context); } public boolean visitDocComment(TreePath treePath, EntrySet node, EntrySet absNode) { // TODO(https://phabricator-dot-kythe-repo.appspot.com/T185): always use absNode DCDocComment doc = (DCDocComment) trees.getDocCommentTree(treePath); if (doc == null) { return false; } miniAnchors.clear(); scan(new DocTreePath(treePath, doc), doc); int startChar = (int) doc.getSourcePosition(doc); String bracketed = MiniAnchor.bracket( doc.comment.getText(), new MiniAnchor.PositionTransform() { @Override public int transform(int pos) { return doc.comment.getSourcePos(pos); } }, miniAnchors); List<Symbol> anchoredTo = new ArrayList<>(miniAnchors.size()); for (MiniAnchor<Symbol> miniAnchor : miniAnchors) { anchoredTo.add(miniAnchor.getAnchoredTo()); } treeScanner.emitDoc(bracketed, anchoredTo, node, absNode); return treeScanner.emitCommentsOnLine(treeScanner.charToLine(startChar), node); } @Override public Void visitReference(ReferenceTree tree, DCDocComment doc) { DCReference ref = (DCReference) tree; Symbol sym = null; try { sym = (Symbol) trees.getElement(getCurrentPath()); } catch (Symbol.CompletionFailure e) { logger.warningfmt(e, "Failed to resolve documentation reference: %s", tree); } if (sym == null) { return null; } int startPos = (int) ref.getSourcePosition(doc); int endPos = ref.getEndPos(doc); treeScanner.emitDocReference(sym, startPos, endPos); miniAnchors.add(new MiniAnchor<Symbol>(sym, startPos, endPos)); return null; } }
apache-2.0
kohsuke/hadoop
src/contrib/fairscheduler/src/java/org/apache/hadoop/mapred/FairSchedulerServlet.java
12559
/** * 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.mapred; import java.io.IOException; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.hadoop.mapred.FairScheduler.JobInfo; import org.apache.hadoop.util.StringUtils; /** * Servlet for displaying fair scheduler information, installed at * [job tracker URL]/scheduler when the {@link FairScheduler} is in use. * * The main features are viewing each job's task count and fair share, ability * to change job priorities and pools from the UI, and ability to switch the * scheduler to FIFO mode without restarting the JobTracker if this is required * for any reason. * * There is also an "advanced" view for debugging that can be turned on by * going to [job tracker URL]/scheduler?advanced. */ public class FairSchedulerServlet extends HttpServlet { private static final long serialVersionUID = 9104070533067306659L; private static final DateFormat DATE_FORMAT = new SimpleDateFormat("MMM dd, HH:mm"); private FairScheduler scheduler; private JobTracker jobTracker; private static long lastId = 0; // Used to generate unique element IDs @Override public void init() throws ServletException { super.init(); ServletContext servletContext = this.getServletContext(); this.scheduler = (FairScheduler) servletContext.getAttribute("scheduler"); this.jobTracker = (JobTracker) scheduler.taskTrackerManager; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); // Same handler for both GET and POST } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // If the request has a set* param, handle that and redirect to the regular // view page so that the user won't resubmit the data if they hit refresh. boolean advancedView = request.getParameter("advanced") != null; if (request.getParameter("setFifo") != null) { scheduler.setUseFifo(request.getParameter("setFifo").equals("true")); response.sendRedirect("/scheduler" + (advancedView ? "?advanced" : "")); return; } if (request.getParameter("setPool") != null) { PoolManager poolMgr = scheduler.getPoolManager(); synchronized (poolMgr) { String pool = request.getParameter("setPool"); String jobId = request.getParameter("jobid"); Collection<JobInProgress> runningJobs = jobTracker.runningJobs(); for (JobInProgress job: runningJobs) { if (job.getProfile().getJobID().toString().equals(jobId)) { poolMgr.setPool(job, pool); scheduler.update(); break; } } } response.sendRedirect("/scheduler" + (advancedView ? "?advanced" : "")); return; } if (request.getParameter("setPriority") != null) { PoolManager poolMgr = scheduler.getPoolManager(); synchronized (poolMgr) { JobPriority priority = JobPriority.valueOf(request.getParameter( "setPriority")); String jobId = request.getParameter("jobid"); Collection<JobInProgress> runningJobs = jobTracker.runningJobs(); for (JobInProgress job: runningJobs) { if (job.getProfile().getJobID().toString().equals(jobId)) { job.setPriority(priority); scheduler.update(); break; } } } response.sendRedirect("/scheduler" + (advancedView ? "?advanced" : "")); return; } // Print out the normal response response.setContentType("text/html"); PrintWriter out = new PrintWriter(response.getOutputStream()); String hostname = StringUtils.simpleHostname( jobTracker.getJobTrackerMachine()); out.print("<html><head>"); out.printf("<title>%s Job Scheduler Admininstration</title>\n", hostname); out.printf("<META http-equiv=\"refresh\" content=\"15;URL=/scheduler%s\">", advancedView ? "?advanced" : ""); out.print("<link rel=\"stylesheet\" type=\"text/css\" " + "href=\"/static/hadoop.css\">\n"); out.print("</head><body>\n"); out.printf("<h1><a href=\"/jobtracker.jsp\">%s</a> " + "Job Scheduler Administration</h1>\n", hostname); showPools(out, advancedView); showJobs(out, advancedView); showAdminForm(out, advancedView); out.print("</body></html>\n"); out.close(); } /** * Print a view of pools to the given output writer. */ private void showPools(PrintWriter out, boolean advancedView) { PoolManager poolManager = scheduler.getPoolManager(); synchronized(poolManager) { out.print("<h2>Pools</h2>\n"); out.print("<table border=\"2\" cellpadding=\"5\" cellspacing=\"2\">\n"); out.print("<tr><th>Pool</th><th>Running Jobs</th>" + "<th>Min Maps</th><th>Min Reduces</th>" + "<th>Running Maps</th><th>Running Reduces</th></tr>\n"); List<Pool> pools = new ArrayList<Pool>(poolManager.getPools()); Collections.sort(pools, new Comparator<Pool>() { public int compare(Pool p1, Pool p2) { if (p1.isDefaultPool()) return 1; else if (p2.isDefaultPool()) return -1; else return p1.getName().compareTo(p2.getName()); }}); for (Pool pool: pools) { int runningMaps = 0; int runningReduces = 0; for (JobInProgress job: pool.getJobs()) { JobInfo info = scheduler.infos.get(job); if (info != null) { runningMaps += info.runningMaps; runningReduces += info.runningReduces; } } out.print("<tr>\n"); out.printf("<td>%s</td>\n", pool.getName()); out.printf("<td>%s</td>\n", pool.getJobs().size()); out.printf("<td>%s</td>\n", poolManager.getAllocation(pool.getName(), TaskType.MAP)); out.printf("<td>%s</td>\n", poolManager.getAllocation(pool.getName(), TaskType.REDUCE)); out.printf("<td>%s</td>\n", runningMaps); out.printf("<td>%s</td>\n", runningReduces); out.print("</tr>\n"); } out.print("</table>\n"); } } /** * Print a view of running jobs to the given output writer. */ private void showJobs(PrintWriter out, boolean advancedView) { out.print("<h2>Running Jobs</h2>\n"); out.print("<table border=\"2\" cellpadding=\"5\" cellspacing=\"2\">\n"); int colsPerTaskType = advancedView ? 5 : 3; out.printf("<tr><th rowspan=2>Submitted</th>" + "<th rowspan=2>JobID</th>" + "<th rowspan=2>User</th>" + "<th rowspan=2>Name</th>" + "<th rowspan=2>Pool</th>" + "<th rowspan=2>Priority</th>" + "<th colspan=%d>Maps</th>" + "<th colspan=%d>Reduces</th>", colsPerTaskType, colsPerTaskType); out.print("</tr><tr>\n"); out.print("<th>Finished</th><th>Running</th><th>Fair Share</th>" + (advancedView ? "<th>Weight</th><th>Deficit</th>" : "")); out.print("<th>Finished</th><th>Running</th><th>Fair Share</th>" + (advancedView ? "<th>Weight</th><th>Deficit</th>" : "")); out.print("</tr>\n"); Collection<JobInProgress> runningJobs = jobTracker.runningJobs(); for (JobInProgress job: runningJobs) { JobProfile profile = job.getProfile(); JobInfo info = scheduler.infos.get(job); if (info == null) { // Job finished, but let's show 0's for info info = new JobInfo(); } out.print("<tr>\n"); out.printf("<td>%s</td>\n", DATE_FORMAT.format( new Date(job.getStartTime()))); out.printf("<td><a href=\"jobdetails.jsp?jobid=%s\">%s</a></td>", profile.getJobID(), profile.getJobID()); out.printf("<td>%s</td>\n", profile.getUser()); out.printf("<td>%s</td>\n", profile.getJobName()); out.printf("<td>%s</td>\n", generateSelect( scheduler.getPoolManager().getPoolNames(), scheduler.getPoolManager().getPoolName(job), "/scheduler?setPool=<CHOICE>&jobid=" + profile.getJobID() + (advancedView ? "&advanced" : ""))); out.printf("<td>%s</td>\n", generateSelect( Arrays.asList(new String[] {"VERY_LOW", "LOW", "NORMAL", "HIGH", "VERY_HIGH"}), job.getPriority().toString(), "/scheduler?setPriority=<CHOICE>&jobid=" + profile.getJobID() + (advancedView ? "&advanced" : ""))); out.printf("<td>%d / %d</td><td>%d</td><td>%8.1f</td>\n", job.finishedMaps(), job.desiredMaps(), info.runningMaps, info.mapFairShare); if (advancedView) { out.printf("<td>%8.1f</td>\n", info.mapWeight); out.printf("<td>%s</td>\n", info.neededMaps > 0 ? (info.mapDeficit / 1000) + "s" : "--"); } out.printf("<td>%d / %d</td><td>%d</td><td>%8.1f</td>\n", job.finishedReduces(), job.desiredReduces(), info.runningReduces, info.reduceFairShare); if (advancedView) { out.printf("<td>%8.1f</td>\n", info.reduceWeight); out.printf("<td>%s</td>\n", info.neededReduces > 0 ? (info.reduceDeficit / 1000) + "s" : "--"); } out.print("</tr>\n"); } out.print("</table>\n"); } /** * Generate a HTML select control with a given list of choices and a given * option selected. When the selection is changed, take the user to the * <code>submitUrl</code>. The <code>submitUrl</code> can be made to include * the option selected -- the first occurrence of the substring * <code>&lt;CHOICE&gt;</code> will be replaced by the option chosen. */ private String generateSelect(Iterable<String> choices, String selectedChoice, String submitUrl) { StringBuilder html = new StringBuilder(); String id = "select" + lastId++; html.append("<select id=\"" + id + "\" name=\"" + id + "\" " + "onchange=\"window.location = '" + submitUrl + "'.replace('<CHOICE>', document.getElementById('" + id + "').value);\">\n"); for (String choice: choices) { html.append(String.format("<option value=\"%s\"%s>%s</option>\n", choice, (choice.equals(selectedChoice) ? " selected" : ""), choice)); } html.append("</select>\n"); return html.toString(); } /** * Print the administration form at the bottom of the page, which currently * only includes the button for switching between FIFO and Fair Scheduling. */ private void showAdminForm(PrintWriter out, boolean advancedView) { out.print("<h2>Scheduling Mode</h2>\n"); String curMode = scheduler.getUseFifo() ? "FIFO" : "Fair Sharing"; String otherMode = scheduler.getUseFifo() ? "Fair Sharing" : "FIFO"; String advParam = advancedView ? "?advanced" : ""; out.printf("<form method=\"post\" action=\"/scheduler%s\">\n", advParam); out.printf("<p>The scheduler is currently using <b>%s mode</b>. " + "<input type=\"submit\" value=\"Switch to %s mode.\" " + "onclick=\"return confirm('Are you sure you want to change " + "scheduling mode to %s?')\" />\n", curMode, otherMode, otherMode); out.printf("<input type=\"hidden\" name=\"setFifo\" value=\"%s\" />", !scheduler.getUseFifo()); out.print("</form>\n"); } }
apache-2.0
MaximTar/satellite
src/main/resources/libs/JAT/jat/alg/opt/test/GradientSearch_test.java
2214
/* JAT: Java Astrodynamics Toolkit * * Copyright (c) 2002 The JAT Project. All rights reserved. * * This file is part of JAT. JAT is free software; you can * redistribute it and/or modify it under the terms of the * NASA Open Source Agreement, version 1.3 or later. * * 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 * NASA Open Source Agreement for more details. * * You should have received a copy of the NASA Open Source Agreement * along with this program; if not, write to the NASA Goddard * Space Flight Center at opensource@gsfc.nasa.gov. * */ package jat.alg.opt.test; import jat.alg.opt.*; import jat.alg.opt.test.functions.*; public class GradientSearch_test { public static void main(String argv[]) { double[] x; // result double[] x_init = new double[2]; // initial guess double[] x_init3 = new double[3]; // initial guess //System.out.println("Unconstrained Parameter Optimization Test"); // Quadratic Function System.out.println("Quadratic Function"); x_init[0] = 1.; x_init[1] = 1.; GradientSearch g22 = new GradientSearch(new QuadraticFunction(), x_init); g22.err_ods = 1.e-4; g22.err_grad = 1.e-3; g22.eps_FD = 1.e-8; x = g22.find_min_gradient(); System.out.println(); // Rosenbrock function System.out.println("Rosenbrock function"); x_init[0] = -1.2; x_init[1] = 1.; GradientSearch g23 = new GradientSearch(new Rosenbrock(), x_init); g23.err_ods = 1.e-4; g23.err_grad = 1.e-3; g23.eps_FD = 1.e-8; g23.max_it = 20; x = g23.find_min_gradient(); System.out.println(); // n=3 function System.out.println("Function of 3 vars"); x_init3[0] = -1.2; x_init3[1] = 1.; x_init3[2] = 1.; GradientSearch g3 = new GradientSearch(new Function4(), x_init3); g3.err_ods = 1.e-4; g3.err_grad = 1.e-3; g3.eps_FD = 1.e-8; g3.max_it = 20; x = g3.find_min_gradient(); } } //Date start_time = new Date(); //Date stop_time = new Date(); //double etime = (stop_time.getTime() - start_time.getTime()) / 1000.; //System.out.println("Elapsed Time = " + etime + " seconds");
apache-2.0
seava/seava.lib.j4e
seava.j4e.business/src/main/java/seava/j4e/business/service/entity/AbstractEntityService.java
557
/** * DNet eBusiness Suite * Copyright: 2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package seava.j4e.business.service.entity; /** * Top level abstract class for an entity service. Usually it is extended by * custom entity services to inherit all the standard functionality and just * customize the non-standard behavior. * * See the super-classes for more details. * * @author amathe * * @param <E> */ public abstract class AbstractEntityService<E> extends AbstractEntityWriteService<E> { }
apache-2.0
jaikiran/ant-ivy
src/java/org/apache/ivy/plugins/repository/ssh/RemoteScpException.java
1578
/* * 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.ivy.plugins.repository.ssh; /** * This exception will be used for Remote SCP Exceptions (failures on the target system, no * connection probs) */ public class RemoteScpException extends Exception { private static final long serialVersionUID = 3107198655563736600L; public RemoteScpException() { } /** * @param message ditto */ public RemoteScpException(String message) { super(message); } /** * @param cause Throwable */ public RemoteScpException(Throwable cause) { super(cause); } /** * @param message ditto * @param cause Throwable */ public RemoteScpException(String message, Throwable cause) { super(message, cause); } }
apache-2.0
slipstream/SlipStreamServer
jar-persistence/src/main/java/com/sixsq/slipstream/persistence/QuotaParameter.java
1092
package com.sixsq.slipstream.persistence; /* * +=================================================================+ * SlipStream Server (WAR) * ===== * Copyright (C) 2013 SixSq Sarl (sixsq.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. * -=================================================================- */ public class QuotaParameter { public static final String QUOTA_VM_PARAMETER_NAME = "quota.vm"; public static final String QUOTA_VM_DESCRIPTION = "Number of VMs the user can start for this cloud"; public static final String QUOTA_VM_DEFAULT = "20"; }
apache-2.0