code
stringlengths
3
1.04M
repo_name
stringlengths
5
109
path
stringlengths
6
306
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.04M
/** * Copyright (C) 2012 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.sos.cache; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.n52.oxf.valueDomains.time.ITimePeriod; import org.n52.sos.dataTypes.EnvelopeWrapper; import org.n52.sos.dataTypes.ObservationOffering; import org.n52.sos.db.AccessGDB; public class ObservationOfferingCache extends AbstractEntityCache<ObservationOffering> { private static final String TOKEN_SEP = "@@"; private static ObservationOfferingCache instance; public static synchronized ObservationOfferingCache instance(String dbName) throws FileNotFoundException { if (instance == null) { instance = new ObservationOfferingCache(dbName); } return instance; } public static synchronized ObservationOfferingCache instance() throws FileNotFoundException { return instance; } private boolean cancelled; private ObservationOfferingCache(String dbName) throws FileNotFoundException { super(dbName); } @Override protected String getCacheFileName() { return "observationOfferingsList.cache"; } @Override protected String serializeEntity(ObservationOffering entity) throws CacheException { StringBuilder sb = new StringBuilder(); sb.append(entity.getId()); sb.append(TOKEN_SEP); sb.append(entity.getName()); sb.append(TOKEN_SEP); sb.append(entity.getProcedureIdentifier()); sb.append(TOKEN_SEP); try { sb.append(EnvelopeEncoderDecoder.encode(entity.getObservedArea())); } catch (IOException e) { throw new CacheException(e); } sb.append(TOKEN_SEP); sb.append(Arrays.toString(entity.getObservedProperties())); sb.append(TOKEN_SEP); sb.append(TimePeriodEncoder.encode(entity.getTimeExtent())); return sb.toString(); } @Override protected ObservationOffering deserializeEntity(String line) { String[] values = line.split(TOKEN_SEP); if (values == null || values.length != 6) { return null; } String id = values[0].trim(); String name = values[1].trim(); String proc = values[2].trim(); EnvelopeWrapper env = EnvelopeEncoderDecoder.decode(values[3]); String[] props = decodeStringArray(values[4]); ITimePeriod time = TimePeriodEncoder.decode(values[5]); return new ObservationOffering(id, name, props, proc, env, time); } @Override protected boolean mergeWithPreviousEntries() { return true; } protected Collection<ObservationOffering> getCollectionFromDAO(AccessGDB geoDB) throws IOException { this.cancelled = false; clearTempCacheFile(); geoDB.getOfferingAccess().getNetworksAsObservationOfferingsAsync(new OnOfferingRetrieved() { int count = 0; @Override public void retrieveExpectedOfferingsCount(int c) { setMaximumEntries(c); } @Override public void retrieveOffering(ObservationOffering oo, int currentOfferingIndex) throws RetrievingCancelledException { storeTemporaryEntity(oo); setLatestEntryIndex(currentOfferingIndex); LOGGER.info(String.format("Added ObservationOffering #%s to the cache.", count++)); if (cancelled) { throw new RetrievingCancelledException("Cache update cancelled due to shutdown."); } } }); return Collections.emptyList(); } @Override protected AbstractEntityCache<ObservationOffering> getSingleInstance() { return instance; } @Override public void cancelCurrentExecution() { this.cancelled = true; } }
52North/ArcGIS-Server-SOS-Extension
src/main/java/org/n52/sos/cache/ObservationOfferingCache.java
Java
apache-2.0
4,089
/** * Copyright 2010 - 2022 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.io; import jetbrains.exodus.core.dataStructures.Pair; import jetbrains.exodus.env.Environment; import jetbrains.exodus.env.EnvironmentConfig; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ServiceLoader; /** * Service provider interface for creation instances of {@linkplain DataReader} and {@linkplain DataWriter}. * {@linkplain DataReader} and {@linkplain DataWriter} are used by {@code Log} implementation to perform basic * operations with {@linkplain Block blocks} ({@code .xd} files) and basic read/write/delete operations. * * Service provider interface is identified by a fully-qualified name of its implementation. When opening an * {@linkplain Environment}, {@linkplain #DEFAULT_READER_WRITER_PROVIDER} is used as default provide name. To use a * custom I/O provider, specify its fully-qualified name as a parameter of {@linkplain EnvironmentConfig#setLogDataReaderWriterProvider}. * * On {@linkplain Environment} creation new instance of {@code DataReaderWriterProvider} is created. * * @see Block * @see DataReader * @see DataWriter * @see EnvironmentConfig#getLogDataReaderWriterProvider * @see EnvironmentConfig#setLogDataReaderWriterProvider * @since 1.3.0 */ public abstract class DataReaderWriterProvider { /** * Fully-qualified name of default {@code DataReaderWriteProvider}. */ public static final String DEFAULT_READER_WRITER_PROVIDER = "jetbrains.exodus.io.FileDataReaderWriterProvider"; /** * Fully-qualified name of read-only watching {@code DataReaderWriteProvider}. */ public static final String WATCHING_READER_WRITER_PROVIDER = "jetbrains.exodus.io.WatchingFileDataReaderWriterProvider"; /** * Fully-qualified name of in-memory {@code DataReaderWriteProvider}. */ public static final String IN_MEMORY_READER_WRITER_PROVIDER = "jetbrains.exodus.io.MemoryDataReaderWriterProvider"; /** * Creates pair of new instances of {@linkplain DataReader} and {@linkplain DataWriter} by specified location. * What is location depends on the implementation of {@code DataReaderWriterProvider}, e.g. for {@code FileDataReaderWriterProvider} * location is a full path on local file system where the database is located. * * @param location identifies the database in this {@code DataReaderWriterProvider} * @return pair of new instances of {@linkplain DataReader} and {@linkplain DataWriter} */ public abstract Pair<DataReader, DataWriter> newReaderWriter(@NotNull final String location); /** * Returns {@code true} if the {@code DataReaderWriterProvider} creates in-memory {@linkplain DataReader} and {@linkplain DataWriter}. * * @return {@code true} if the {@code DataReaderWriterProvider} creates in-memory {@linkplain DataReader} and {@linkplain DataWriter} */ public boolean isInMemory() { return false; } /** * Returns {@code true} if the {@code DataReaderWriterProvider} creates read-only {@linkplain DataWriter}. * * @return {@code true} if the {@code DataReaderWriterProvider} creates read-only {@linkplain DataWriter} */ public boolean isReadonly() { return false; } /** * Callback method which is called when an environment is been opened/created. Can be used in implementation of * the {@code DataReaderWriterProvider} to access directly an {@linkplain Environment} instance, * its {@linkplain Environment#getEnvironmentConfig() config}, etc. Creation of {@code environment} is not * completed when the method is called. * * @param environment {@linkplain Environment} instance which is been opened/created using this * {@code DataReaderWriterProvider} */ public void onEnvironmentCreated(@NotNull final Environment environment) { } /** * Gets a {@code DataReaderWriterProvider} implementation by specified provider name. * * @param providerName fully-qualified name of {@code DataReaderWriterProvider} implementation * @return {@code DataReaderWriterProvider} implementation or {@code null} if the service could not be loaded */ @Nullable public static DataReaderWriterProvider getProvider(@NotNull final String providerName) { ServiceLoader<DataReaderWriterProvider> serviceLoader = ServiceLoader.load(DataReaderWriterProvider.class); if (!serviceLoader.iterator().hasNext()) { serviceLoader = ServiceLoader.load(DataReaderWriterProvider.class, DataReaderWriterProvider.class.getClassLoader()); } for (DataReaderWriterProvider provider : serviceLoader) { if (provider.getClass().getCanonicalName().equalsIgnoreCase(providerName)) { return provider; } } return null; } }
JetBrains/xodus
openAPI/src/main/java/jetbrains/exodus/io/DataReaderWriterProvider.java
Java
apache-2.0
5,499
package org.commcare.tasks; import android.content.Context; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.Pair; import org.commcare.CommCareApplication; import org.commcare.models.AndroidSessionWrapper; import org.commcare.models.database.AndroidSandbox; import org.commcare.models.database.SqlStorage; import org.commcare.android.database.user.models.FormRecord; import org.commcare.android.database.user.models.SessionStateDescriptor; import org.commcare.suite.model.Text; import org.commcare.tasks.templates.ManagedAsyncTask; import org.commcare.util.FormDataUtil; import org.commcare.utils.AndroidCommCarePlatform; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Queue; import java.util.Set; /** * Loads textual information for a list of FormRecords. * <p/> * This text currently includes the form name, record title, and last modified * date * * @author ctsims */ public class FormRecordLoaderTask extends ManagedAsyncTask<FormRecord, Pair<FormRecord, ArrayList<String>>, Integer> { private Hashtable<String, String> descriptorCache; private final SqlStorage<SessionStateDescriptor> descriptorStorage; private final AndroidCommCarePlatform platform; private Hashtable<Integer, String[]> searchCache; private final Context context; // Functions to call when some or all of the data has been loaded. Data // can be loaded normally, or be given precedence (priority), determining // which callback is dispatched to the listeners. private final ArrayList<FormRecordLoadListener> listeners = new ArrayList<>(); // These are all synchronized together final private Queue<FormRecord> priorityQueue = new LinkedList<>(); // The IDs of FormRecords that have been loaded private final Set<Integer> loaded = new HashSet<>(); // Maps form namespace (unique id for forms) to their form title // (entry-point text). Needed because FormRecords don't have form title // info, but do have the namespace. private Hashtable<String, Text> formNames; // Is the background task done loading all the FormRecord information? private boolean loadingComplete = false; public FormRecordLoaderTask(Context c, SqlStorage<SessionStateDescriptor> descriptorStorage, AndroidCommCarePlatform platform) { this(c, descriptorStorage, null, platform); } private FormRecordLoaderTask(Context c, SqlStorage<SessionStateDescriptor> descriptorStorage, Hashtable<String, String> descriptorCache, AndroidCommCarePlatform platform) { this.context = c; this.descriptorStorage = descriptorStorage; this.descriptorCache = descriptorCache; this.platform = platform; } /** * Create a copy of this loader task. */ public FormRecordLoaderTask spawn() { FormRecordLoaderTask task = new FormRecordLoaderTask(context, descriptorStorage, descriptorCache, platform); task.setListeners(listeners); return task; } /** * Pass in hashtables that will be used to store data that is loaded. * * @param searchCache maps FormRecord ID to an array of query-able form descriptor text * @param formNames map from form namespaces to their titles */ public void init(Hashtable<Integer, String[]> searchCache, Hashtable<String, Text> formNames) { this.searchCache = searchCache; if (descriptorCache == null) { descriptorCache = new Hashtable<>(); } priorityQueue.clear(); loaded.clear(); this.formNames = formNames; } /** * Set the listeners list, whose callbacks will be executed once the data * has been loaded. * * @param listeners a list of objects to call when data is done loading */ private void setListeners(ArrayList<FormRecordLoadListener> listeners) { this.listeners.addAll(listeners); } /** * Add a listener to the list that is called once the data has been loaded. * * @param listener an objects to call when data is done loading */ public void addListener(FormRecordLoadListener listener) { this.listeners.add(listener); } @Override protected Integer doInBackground(FormRecord... params) { // Load text information for every FormRecord passed in, unless task is // cancelled before that. FormRecord current; int loadedFormCount = 0; while (loadedFormCount < params.length && !isCancelled()) { synchronized (priorityQueue) { //If we have one to do immediately, grab it if (!priorityQueue.isEmpty()) { current = priorityQueue.poll(); } else { current = params[loadedFormCount++]; } if (loaded.contains(current.getID())) { // skip if we already loaded this record due to priority queue continue; } } // load text about this record: last modified date, title of the record, and form name ArrayList<String> recordTextDesc = loadRecordText(current); loaded.add(current.getID()); // Copy data into search task and notify anything waiting on this // record. this.publishProgress(new Pair<>(current, recordTextDesc)); } return 1; } private ArrayList<String> loadRecordText(FormRecord current) { ArrayList<String> recordTextDesc = new ArrayList<>(); // Get the date in a searchable format. recordTextDesc.add(DateUtils.formatDateTime(context, current.lastModified().getTime(), DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_NO_YEAR).toLowerCase()); String dataTitle = current.getDescriptor(); if (TextUtils.isEmpty(dataTitle)) { dataTitle = loadDataTitle(current.getID()); } recordTextDesc.add(dataTitle); if (formNames.containsKey(current.getFormNamespace())) { Text name = formNames.get(current.getFormNamespace()); recordTextDesc.add(name.evaluate()); } return recordTextDesc; } private String loadDataTitle(int formRecordId) { // Grab our record hash SessionStateDescriptor ssd = null; try { ssd = descriptorStorage.getRecordForValue(SessionStateDescriptor.META_FORM_RECORD_ID, formRecordId); } catch (NoSuchElementException nsee) { //s'all good } String dataTitle = ""; if (ssd != null) { String descriptor = ssd.getSessionDescriptor(); if (!descriptorCache.containsKey(descriptor)) { AndroidSessionWrapper asw = new AndroidSessionWrapper(platform); asw.loadFromStateDescription(ssd); try { dataTitle = FormDataUtil.getTitleFromSession(new AndroidSandbox(CommCareApplication.instance()), asw.getSession(), asw.getEvaluationContext()); } catch (RuntimeException e) { dataTitle = "[Unavailable]"; } if (dataTitle == null) { dataTitle = ""; } descriptorCache.put(descriptor, dataTitle); } else { return descriptorCache.get(descriptor); } } return dataTitle; } @Override protected void onPreExecute() { super.onPreExecute(); // Tell users of the data being loaded that it isn't ready yet. this.loadingComplete = false; } /** * Has all the FormRecords' textual data been loaded yet? Used to let * users of the data only start accessing it once it is all there. */ public boolean doneLoadingFormRecords() { return this.loadingComplete; } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); this.loadingComplete = true; for (FormRecordLoadListener listener : this.listeners) { if (listener != null) { listener.notifyLoaded(); } } // free up things we don't need to spawn new tasks priorityQueue.clear(); loaded.clear(); formNames = null; } @Override protected void onProgressUpdate(Pair<FormRecord, ArrayList<String>>... values) { super.onProgressUpdate(values); // copy a single form record's data out of method arguments String[] vals = new String[values[0].second.size()]; for (int i = 0; i < vals.length; ++i) { vals[i] = values[0].second.get(i); } // store the loaded data in the search cache this.searchCache.put(values[0].first.getID(), vals); for (FormRecordLoadListener listener : this.listeners) { if (listener != null) { // TODO PLM: pretty sure loaded.contains(values[0].first) is // always true at this point. listener.notifyPriorityLoaded(values[0].first, loaded.contains(values[0].first.getID())); } } } public boolean registerPriority(FormRecord record) { synchronized (priorityQueue) { if (loaded.contains(record.getID())) { return false; } else if (priorityQueue.contains(record)) { // if we already have it in the queue, just move along return true; } else { priorityQueue.add(record); return true; } } } }
dimagi/commcare-android
app/src/org/commcare/tasks/FormRecordLoaderTask.java
Java
apache-2.0
10,155
/* Copyright 2019 Telstra Open Source * * 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.openkilda.wfm.topology.network.controller; import org.openkilda.persistence.PersistenceManager; import org.openkilda.persistence.repositories.FeatureTogglesRepository; import org.openkilda.wfm.share.model.Endpoint; import org.openkilda.wfm.share.utils.AbstractBaseFsm; import org.openkilda.wfm.share.utils.FsmExecutor; import org.openkilda.wfm.topology.network.service.IBfdGlobalToggleCarrier; import lombok.Builder; import lombok.Value; import org.squirrelframework.foundation.fsm.StateMachineBuilder; import org.squirrelframework.foundation.fsm.StateMachineBuilderFactory; public class BfdGlobalToggleFsm extends AbstractBaseFsm<BfdGlobalToggleFsm, BfdGlobalToggleFsm.BfdGlobalToggleFsmState, BfdGlobalToggleFsm.BfdGlobalToggleFsmEvent, BfdGlobalToggleFsm.BfdGlobalToggleFsmContext> { private final IBfdGlobalToggleCarrier carrier; private final Endpoint endpoint; public static BfdGlobalToggleFsmFactory factory(PersistenceManager persistenceManager) { return new BfdGlobalToggleFsmFactory(persistenceManager); } // -- FSM actions -- public void emitBfdKill(BfdGlobalToggleFsmState from, BfdGlobalToggleFsmState to, BfdGlobalToggleFsmEvent event, BfdGlobalToggleFsmContext context) { log.info("BFD event KILL for {}", endpoint); carrier.filteredBfdKillNotification(endpoint); } public void emitBfdUp(BfdGlobalToggleFsmState from, BfdGlobalToggleFsmState to, BfdGlobalToggleFsmEvent event, BfdGlobalToggleFsmContext context) { log.info("BFD event UP for {}", endpoint); carrier.filteredBfdUpNotification(endpoint); } public void emitBfdDown(BfdGlobalToggleFsmState from, BfdGlobalToggleFsmState to, BfdGlobalToggleFsmEvent event, BfdGlobalToggleFsmContext context) { log.info("BFD event DOWN for {}", endpoint); carrier.filteredBfdDownNotification(endpoint); } public void emitBfdFail(BfdGlobalToggleFsmState from, BfdGlobalToggleFsmState to, BfdGlobalToggleFsmEvent event, BfdGlobalToggleFsmContext context) { log.info("BFD event FAIL for {}", endpoint); carrier.filteredBfdFailNotification(endpoint); } // -- private/service methods -- // -- service data types -- public BfdGlobalToggleFsm(IBfdGlobalToggleCarrier carrier, Endpoint endpoint) { this.carrier = carrier; this.endpoint = endpoint; } public static class BfdGlobalToggleFsmFactory { private final FeatureTogglesRepository featureTogglesRepository; private final StateMachineBuilder<BfdGlobalToggleFsm, BfdGlobalToggleFsmState, BfdGlobalToggleFsmEvent, BfdGlobalToggleFsmContext> builder; BfdGlobalToggleFsmFactory(PersistenceManager persistenceManager) { featureTogglesRepository = persistenceManager.getRepositoryFactory().createFeatureTogglesRepository(); final String emitBfdKillMethod = "emitBfdKill"; final String emitBfdFailMethod = "emitBfdFail"; builder = StateMachineBuilderFactory.create( BfdGlobalToggleFsm.class, BfdGlobalToggleFsmState.class, BfdGlobalToggleFsmEvent.class, BfdGlobalToggleFsmContext.class, // extra parameters IBfdGlobalToggleCarrier.class, Endpoint.class); // DOWN_ENABLED builder.transition() .from(BfdGlobalToggleFsmState.DOWN_ENABLED).to(BfdGlobalToggleFsmState.DOWN_DISABLED) .on(BfdGlobalToggleFsmEvent.DISABLE); builder.transition() .from(BfdGlobalToggleFsmState.DOWN_ENABLED).to(BfdGlobalToggleFsmState.UP_ENABLED) .on(BfdGlobalToggleFsmEvent.BFD_UP); builder.internalTransition() .within(BfdGlobalToggleFsmState.DOWN_ENABLED).on(BfdGlobalToggleFsmEvent.BFD_KILL) .callMethod(emitBfdKillMethod); builder.internalTransition() .within(BfdGlobalToggleFsmState.DOWN_ENABLED).on(BfdGlobalToggleFsmEvent.BFD_FAIL) .callMethod(emitBfdFailMethod); // DOWN_DISABLED builder.transition() .from(BfdGlobalToggleFsmState.DOWN_DISABLED).to(BfdGlobalToggleFsmState.DOWN_ENABLED) .on(BfdGlobalToggleFsmEvent.ENABLE); builder.transition() .from(BfdGlobalToggleFsmState.DOWN_DISABLED).to(BfdGlobalToggleFsmState.UP_DISABLED) .on(BfdGlobalToggleFsmEvent.BFD_UP); builder.internalTransition() .within(BfdGlobalToggleFsmState.DOWN_DISABLED).on(BfdGlobalToggleFsmEvent.BFD_FAIL) .callMethod(emitBfdFailMethod); // UP_ENABLED builder.transition() .from(BfdGlobalToggleFsmState.UP_ENABLED).to(BfdGlobalToggleFsmState.UP_DISABLED) .on(BfdGlobalToggleFsmEvent.DISABLE) .callMethod(emitBfdKillMethod); builder.transition() .from(BfdGlobalToggleFsmState.UP_ENABLED).to(BfdGlobalToggleFsmState.DOWN_ENABLED) .on(BfdGlobalToggleFsmEvent.BFD_DOWN) .callMethod("emitBfdDown"); builder.transition() .from(BfdGlobalToggleFsmState.UP_ENABLED).to(BfdGlobalToggleFsmState.DOWN_ENABLED) .on(BfdGlobalToggleFsmEvent.BFD_KILL) .callMethod(emitBfdKillMethod); builder.onEntry(BfdGlobalToggleFsmState.UP_ENABLED) .callMethod("emitBfdUp"); // UP_DISABLED builder.transition() .from(BfdGlobalToggleFsmState.UP_DISABLED).to(BfdGlobalToggleFsmState.UP_ENABLED) .on(BfdGlobalToggleFsmEvent.ENABLE); builder.transition() .from(BfdGlobalToggleFsmState.UP_DISABLED).to(BfdGlobalToggleFsmState.DOWN_DISABLED) .on(BfdGlobalToggleFsmEvent.BFD_DOWN); } public FsmExecutor<BfdGlobalToggleFsm, BfdGlobalToggleFsmState, BfdGlobalToggleFsmEvent, BfdGlobalToggleFsmContext> produceExecutor() { return new FsmExecutor<>(BfdGlobalToggleFsmEvent.NEXT); } /** * Determine initial state and create {@link BfdGlobalToggleFsm} instance. */ public BfdGlobalToggleFsm produce(IBfdGlobalToggleCarrier carrier, Endpoint endpoint) { Boolean toggle = featureTogglesRepository.getOrDefault().getUseBfdForIslIntegrityCheck(); if (toggle == null) { throw new IllegalStateException("Unable to identify initial BFD-global-toggle value (it is null at" + " this moment)"); } BfdGlobalToggleFsmState state; if (toggle) { state = BfdGlobalToggleFsmState.DOWN_ENABLED; } else { state = BfdGlobalToggleFsmState.DOWN_DISABLED; } return builder.newStateMachine(state, carrier, endpoint); } } @Value @Builder public static class BfdGlobalToggleFsmContext { } public enum BfdGlobalToggleFsmState { DOWN_DISABLED, DOWN_ENABLED, UP_DISABLED, UP_ENABLED } public enum BfdGlobalToggleFsmEvent { KILL, NEXT, ENABLE, DISABLE, BFD_UP, BFD_DOWN, BFD_KILL, BFD_FAIL } }
jonvestal/open-kilda
src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/controller/BfdGlobalToggleFsm.java
Java
apache-2.0
8,262
package org.nbone.core.util; /** * * @author thinking * @version 1.0 * @since 2019-07-20 * org.elasticsearch.common.unit.ByteSizeUnit */ public enum ByteSizeUnit { BYTES { @Override public long toBytes(long size) { return size; } @Override public long toKB(long size) { return size / (C1 / C0); } @Override public long toMB(long size) { return size / (C2 / C0); } @Override public long toGB(long size) { return size / (C3 / C0); } @Override public long toTB(long size) { return size / (C4 / C0); } @Override public long toPB(long size) { return size / (C5 / C0); } }, KB { @Override public long toBytes(long size) { return x(size, C1 / C0, MAX / (C1 / C0)); } @Override public long toKB(long size) { return size; } @Override public long toMB(long size) { return size / (C2 / C1); } @Override public long toGB(long size) { return size / (C3 / C1); } @Override public long toTB(long size) { return size / (C4 / C1); } @Override public long toPB(long size) { return size / (C5 / C1); } }, MB { @Override public long toBytes(long size) { return x(size, C2 / C0, MAX / (C2 / C0)); } @Override public long toKB(long size) { return x(size, C2 / C1, MAX / (C2 / C1)); } @Override public long toMB(long size) { return size; } @Override public long toGB(long size) { return size / (C3 / C2); } @Override public long toTB(long size) { return size / (C4 / C2); } @Override public long toPB(long size) { return size / (C5 / C2); } }, GB { @Override public long toBytes(long size) { return x(size, C3 / C0, MAX / (C3 / C0)); } @Override public long toKB(long size) { return x(size, C3 / C1, MAX / (C3 / C1)); } @Override public long toMB(long size) { return x(size, C3 / C2, MAX / (C3 / C2)); } @Override public long toGB(long size) { return size; } @Override public long toTB(long size) { return size / (C4 / C3); } @Override public long toPB(long size) { return size / (C5 / C3); } }, TB { @Override public long toBytes(long size) { return x(size, C4 / C0, MAX / (C4 / C0)); } @Override public long toKB(long size) { return x(size, C4 / C1, MAX / (C4 / C1)); } @Override public long toMB(long size) { return x(size, C4 / C2, MAX / (C4 / C2)); } @Override public long toGB(long size) { return x(size, C4 / C3, MAX / (C4 / C3)); } @Override public long toTB(long size) { return size; } @Override public long toPB(long size) { return size / (C5 / C4); } }, PB { @Override public long toBytes(long size) { return x(size, C5 / C0, MAX / (C5 / C0)); } @Override public long toKB(long size) { return x(size, C5 / C1, MAX / (C5 / C1)); } @Override public long toMB(long size) { return x(size, C5 / C2, MAX / (C5 / C2)); } @Override public long toGB(long size) { return x(size, C5 / C3, MAX / (C5 / C3)); } @Override public long toTB(long size) { return x(size, C5 / C4, MAX / (C5 / C4)); } @Override public long toPB(long size) { return size; } }; static final long C0 = 1L; static final long C1 = C0 * 1024L; static final long C2 = C1 * 1024L; static final long C3 = C2 * 1024L; static final long C4 = C3 * 1024L; static final long C5 = C4 * 1024L; static final long MAX = Long.MAX_VALUE; /** * Scale d by m, checking for overflow. * This has a short name to make above code more readable. */ static long x(long d, long m, long over) { if (d > over) return Long.MAX_VALUE; if (d < -over) return Long.MIN_VALUE; return d * m; } public abstract long toBytes(long size); public abstract long toKB(long size); public abstract long toMB(long size); public abstract long toGB(long size); public abstract long toTB(long size); public abstract long toPB(long size); }
thinking-github/nbone
nbone/nbone-core/src/main/java/org/nbone/core/util/ByteSizeUnit.java
Java
apache-2.0
5,035
package org.zentaur.core.http; /* * Copyright 2012 The Zentaur Server Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.zentaur.http.Response; /** * Factory delegated to {@link Response} instances creation. */ public final class ResponseFactory { /** * Creates a new {@link Response} instance. * * @return a new {@link Response} instance. */ public static Response newResponse() { return new DefaultResponse(); } /** * Hidden constructor, this class cannot be instantiated. */ private ResponseFactory() { // do nothing } }
zentaur/core
src/main/java/org/zentaur/core/http/ResponseFactory.java
Java
apache-2.0
1,161
package pl.wavesoftware.examples.wildflyswarm.service.api; import pl.wavesoftware.examples.wildflyswarm.domain.User; import java.util.Collection; /** * @author Krzysztof Suszynski <krzysztof.suszynski@coi.gov.pl> * @since 04.03.16 */ public interface UserService { /** * Retrieves a collection of active users * @return a collection with only active users */ Collection<User> fetchActiveUsers(); }
cardil/cdi-inheritance-wildfly-swarm
src/main/java/pl/wavesoftware/examples/wildflyswarm/service/api/UserService.java
Java
apache-2.0
427
/* * #%L * ===================================================== * _____ _ ____ _ _ _ _ * |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | | * | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| | * | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ | * |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_| * \____/ * * ===================================================== * * Hochschule Hannover * (University of Applied Sciences and Arts, Hannover) * Faculty IV, Dept. of Computer Science * Ricklinger Stadtweg 118, 30459 Hannover, Germany * * Email: trust@f4-i.fh-hannover.de * Website: http://trust.f4.hs-hannover.de/ * * This file is part of ifmapj, version 2.3.2, implemented by the Trust@HsH * research group at the Hochschule Hannover. * %% * Copyright (C) 2010 - 2016 Trust@HsH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package de.hshannover.f4.trust.ifmapj.messages; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import de.hshannover.f4.trust.ifmapj.exception.IfmapErrorResult; import de.hshannover.f4.trust.ifmapj.messages.SearchResult.Type; /** * Implementation of {@link PollResult} * * @author aw * */ class PollResultImpl implements PollResult { private final List<SearchResult> mResults; private final Collection<IfmapErrorResult> mErrorResults; PollResultImpl(List<SearchResult> results, Collection<IfmapErrorResult> eres) { if (results == null || eres == null) { throw new NullPointerException("result list is null"); } mResults = new ArrayList<SearchResult>(results); mErrorResults = new ArrayList<IfmapErrorResult>(eres); } @Override public List<SearchResult> getResults() { return Collections.unmodifiableList(mResults); } @Override public Collection<SearchResult> getSearchResults() { return resultsOfType(SearchResult.Type.searchResult); } @Override public Collection<SearchResult> getUpdateResults() { return resultsOfType(SearchResult.Type.updateResult); } @Override public Collection<SearchResult> getDeleteResults() { return resultsOfType(SearchResult.Type.deleteResult); } @Override public Collection<SearchResult> getNotifyResults() { return resultsOfType(SearchResult.Type.notifyResult); } @Override public Collection<IfmapErrorResult> getErrorResults() { return Collections.unmodifiableCollection(mErrorResults); } private Collection<SearchResult> resultsOfType(Type type) { List<SearchResult> ret = new ArrayList<SearchResult>(); for (SearchResult sr : mResults) { if (sr.getType() == type) { ret.add(sr); } } return Collections.unmodifiableCollection(ret); } }
trustathsh/ifmapj
src/main/java/de/hshannover/f4/trust/ifmapj/messages/PollResultImpl.java
Java
apache-2.0
3,270
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/resourcemanager/v3/folders.proto package com.google.cloud.resourcemanager.v3; /** * * * <pre> * The request sent to the * [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] * method. * Only the `display_name` field can be changed. All other fields will be * ignored. Use the * [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] method to * change the `parent` field. * </pre> * * Protobuf type {@code google.cloud.resourcemanager.v3.UpdateFolderRequest} */ public final class UpdateFolderRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.resourcemanager.v3.UpdateFolderRequest) UpdateFolderRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateFolderRequest.newBuilder() to construct. private UpdateFolderRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateFolderRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateFolderRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private UpdateFolderRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.resourcemanager.v3.Folder.Builder subBuilder = null; if (folder_ != null) { subBuilder = folder_.toBuilder(); } folder_ = input.readMessage( com.google.cloud.resourcemanager.v3.Folder.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(folder_); folder_ = subBuilder.buildPartial(); } break; } case 18: { com.google.protobuf.FieldMask.Builder subBuilder = null; if (updateMask_ != null) { subBuilder = updateMask_.toBuilder(); } updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(updateMask_); updateMask_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.resourcemanager.v3.FoldersProto .internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.resourcemanager.v3.FoldersProto .internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.resourcemanager.v3.UpdateFolderRequest.class, com.google.cloud.resourcemanager.v3.UpdateFolderRequest.Builder.class); } public static final int FOLDER_FIELD_NUMBER = 1; private com.google.cloud.resourcemanager.v3.Folder folder_; /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the folder field is set. */ @java.lang.Override public boolean hasFolder() { return folder_ != null; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The folder. */ @java.lang.Override public com.google.cloud.resourcemanager.v3.Folder getFolder() { return folder_ == null ? com.google.cloud.resourcemanager.v3.Folder.getDefaultInstance() : folder_; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.resourcemanager.v3.FolderOrBuilder getFolderOrBuilder() { return getFolder(); } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return updateMask_ != null; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return getUpdateMask(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (folder_ != null) { output.writeMessage(1, getFolder()); } if (updateMask_ != null) { output.writeMessage(2, getUpdateMask()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (folder_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getFolder()); } if (updateMask_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.resourcemanager.v3.UpdateFolderRequest)) { return super.equals(obj); } com.google.cloud.resourcemanager.v3.UpdateFolderRequest other = (com.google.cloud.resourcemanager.v3.UpdateFolderRequest) obj; if (hasFolder() != other.hasFolder()) return false; if (hasFolder()) { if (!getFolder().equals(other.getFolder())) return false; } if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasFolder()) { hash = (37 * hash) + FOLDER_FIELD_NUMBER; hash = (53 * hash) + getFolder().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.resourcemanager.v3.UpdateFolderRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The request sent to the * [UpdateFolder][google.cloud.resourcemanager.v3.Folder.UpdateFolder] * method. * Only the `display_name` field can be changed. All other fields will be * ignored. Use the * [MoveFolder][google.cloud.resourcemanager.v3.Folders.MoveFolder] method to * change the `parent` field. * </pre> * * Protobuf type {@code google.cloud.resourcemanager.v3.UpdateFolderRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.resourcemanager.v3.UpdateFolderRequest) com.google.cloud.resourcemanager.v3.UpdateFolderRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.resourcemanager.v3.FoldersProto .internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.resourcemanager.v3.FoldersProto .internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.resourcemanager.v3.UpdateFolderRequest.class, com.google.cloud.resourcemanager.v3.UpdateFolderRequest.Builder.class); } // Construct using com.google.cloud.resourcemanager.v3.UpdateFolderRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); if (folderBuilder_ == null) { folder_ = null; } else { folder_ = null; folderBuilder_ = null; } if (updateMaskBuilder_ == null) { updateMask_ = null; } else { updateMask_ = null; updateMaskBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.resourcemanager.v3.FoldersProto .internal_static_google_cloud_resourcemanager_v3_UpdateFolderRequest_descriptor; } @java.lang.Override public com.google.cloud.resourcemanager.v3.UpdateFolderRequest getDefaultInstanceForType() { return com.google.cloud.resourcemanager.v3.UpdateFolderRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.resourcemanager.v3.UpdateFolderRequest build() { com.google.cloud.resourcemanager.v3.UpdateFolderRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.resourcemanager.v3.UpdateFolderRequest buildPartial() { com.google.cloud.resourcemanager.v3.UpdateFolderRequest result = new com.google.cloud.resourcemanager.v3.UpdateFolderRequest(this); if (folderBuilder_ == null) { result.folder_ = folder_; } else { result.folder_ = folderBuilder_.build(); } if (updateMaskBuilder_ == null) { result.updateMask_ = updateMask_; } else { result.updateMask_ = updateMaskBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.resourcemanager.v3.UpdateFolderRequest) { return mergeFrom((com.google.cloud.resourcemanager.v3.UpdateFolderRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.resourcemanager.v3.UpdateFolderRequest other) { if (other == com.google.cloud.resourcemanager.v3.UpdateFolderRequest.getDefaultInstance()) return this; if (other.hasFolder()) { mergeFolder(other.getFolder()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.resourcemanager.v3.UpdateFolderRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.resourcemanager.v3.UpdateFolderRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private com.google.cloud.resourcemanager.v3.Folder folder_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.resourcemanager.v3.Folder, com.google.cloud.resourcemanager.v3.Folder.Builder, com.google.cloud.resourcemanager.v3.FolderOrBuilder> folderBuilder_; /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the folder field is set. */ public boolean hasFolder() { return folderBuilder_ != null || folder_ != null; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The folder. */ public com.google.cloud.resourcemanager.v3.Folder getFolder() { if (folderBuilder_ == null) { return folder_ == null ? com.google.cloud.resourcemanager.v3.Folder.getDefaultInstance() : folder_; } else { return folderBuilder_.getMessage(); } } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setFolder(com.google.cloud.resourcemanager.v3.Folder value) { if (folderBuilder_ == null) { if (value == null) { throw new NullPointerException(); } folder_ = value; onChanged(); } else { folderBuilder_.setMessage(value); } return this; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setFolder(com.google.cloud.resourcemanager.v3.Folder.Builder builderForValue) { if (folderBuilder_ == null) { folder_ = builderForValue.build(); onChanged(); } else { folderBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeFolder(com.google.cloud.resourcemanager.v3.Folder value) { if (folderBuilder_ == null) { if (folder_ != null) { folder_ = com.google.cloud.resourcemanager.v3.Folder.newBuilder(folder_) .mergeFrom(value) .buildPartial(); } else { folder_ = value; } onChanged(); } else { folderBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearFolder() { if (folderBuilder_ == null) { folder_ = null; onChanged(); } else { folder_ = null; folderBuilder_ = null; } return this; } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.resourcemanager.v3.Folder.Builder getFolderBuilder() { onChanged(); return getFolderFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.resourcemanager.v3.FolderOrBuilder getFolderOrBuilder() { if (folderBuilder_ != null) { return folderBuilder_.getMessageOrBuilder(); } else { return folder_ == null ? com.google.cloud.resourcemanager.v3.Folder.getDefaultInstance() : folder_; } } /** * * * <pre> * Required. The new definition of the Folder. It must include the `name` field, which * cannot be changed. * </pre> * * <code> * .google.cloud.resourcemanager.v3.Folder folder = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.resourcemanager.v3.Folder, com.google.cloud.resourcemanager.v3.Folder.Builder, com.google.cloud.resourcemanager.v3.FolderOrBuilder> getFolderFieldBuilder() { if (folderBuilder_ == null) { folderBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.resourcemanager.v3.Folder, com.google.cloud.resourcemanager.v3.Folder.Builder, com.google.cloud.resourcemanager.v3.FolderOrBuilder>( getFolder(), getParentForChildren(), isClean()); folder_ = null; } return folderBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return updateMaskBuilder_ != null || updateMask_ != null; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; onChanged(); } else { updateMaskBuilder_.setMessage(value); } return this; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); onChanged(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (updateMask_ != null) { updateMask_ = com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial(); } else { updateMask_ = value; } onChanged(); } else { updateMaskBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearUpdateMask() { if (updateMaskBuilder_ == null) { updateMask_ = null; onChanged(); } else { updateMask_ = null; updateMaskBuilder_ = null; } return this; } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Required. Fields to be updated. * Only the `display_name` can be updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.resourcemanager.v3.UpdateFolderRequest) } // @@protoc_insertion_point(class_scope:google.cloud.resourcemanager.v3.UpdateFolderRequest) private static final com.google.cloud.resourcemanager.v3.UpdateFolderRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.resourcemanager.v3.UpdateFolderRequest(); } public static com.google.cloud.resourcemanager.v3.UpdateFolderRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateFolderRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateFolderRequest>() { @java.lang.Override public UpdateFolderRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new UpdateFolderRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<UpdateFolderRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateFolderRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.resourcemanager.v3.UpdateFolderRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/java-resourcemanager
proto-google-cloud-resourcemanager-v3/src/main/java/com/google/cloud/resourcemanager/v3/UpdateFolderRequest.java
Java
apache-2.0
34,397
package com.lyubenblagoev.postfixrest.service; import com.lyubenblagoev.postfixrest.entity.User; import com.lyubenblagoev.postfixrest.security.JwtTokenProvider; import com.lyubenblagoev.postfixrest.security.RefreshTokenProvider; import com.lyubenblagoev.postfixrest.security.UserPrincipal; import com.lyubenblagoev.postfixrest.service.model.AuthResponse; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityNotFoundException; import java.util.Optional; @Service @Transactional(readOnly = true) public class AuthServiceImpl implements AuthService { private final JwtTokenProvider jwtTokenProvider; private final RefreshTokenProvider refreshTokenProvider; private final UserService userService; public AuthServiceImpl(JwtTokenProvider jwtTokenProvider, RefreshTokenProvider refreshTokenProvider, UserService userService) { this.jwtTokenProvider = jwtTokenProvider; this.refreshTokenProvider = refreshTokenProvider; this.userService = userService; } @Override public AuthResponse createTokens(String email) { Optional<User> userOptional = userService.findByEmail(email); if (userOptional.isEmpty()) { throw new EntityNotFoundException("Failed to find user with email " + email); } UserPrincipal userPrincipal = new UserPrincipal(userOptional.get()); String token = jwtTokenProvider.createToken(userPrincipal.getUsername(), userPrincipal.getAuthorities()); RefreshTokenProvider.RefreshToken refreshToken = refreshTokenProvider.createToken(); return new AuthResponse(token, refreshToken.getToken(), refreshToken.getExpirationDate()); } }
lyubenblagoev/postfix-rest-server
src/main/java/com/lyubenblagoev/postfixrest/service/AuthServiceImpl.java
Java
apache-2.0
1,809
package task03.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; public class TicketSelectionPage extends Page { public TicketSelectionPage(PageManager pages) { super(pages); } @FindBy(xpath = ".//*[@id='fareRowContainer_0']/tbody/tr[2]/td[2]") private WebElement firstTicket; @FindBy(xpath = ".//*[@id='fareRowContainer_0']/tbody/tr[2]/td[2]") private WebElement secondTicket; @FindBy(id = "tripSummarySubmitBtn") private WebElement submitButton; public void select2Tickets() { wait.until(ExpectedConditions.elementToBeClickable(firstTicket)); firstTicket.click(); wait.until(ExpectedConditions.elementToBeClickable(secondTicket)); secondTicket.click(); wait.until(ExpectedConditions.elementToBeClickable(submitButton)); submitButton.submit(); } }
RihnKornak/TestTasks
src/test/java/task03/pages/TicketSelectionPage.java
Java
apache-2.0
945
/* Copyright [2011] [Prasad Balan] 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.yarsquidy.x12; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Scanner; import java.util.regex.Pattern; /** * The class represents methods used to translate a X12 transaction represented * as a file or string into an X12 object. * * @author Prasad Balan * @version $Id: $Id */ public class X12Parser implements Parser { private static final int SIZE = 106; /** Constant <code>POS_SEGMENT=105</code> */ public static final int POS_SEGMENT = 105; /** Constant <code>POS_ELEMENT=3</code> */ public static final int POS_ELEMENT = 3; /** Constant <code>POS_COMPOSITE_ELEMENT=104</code> */ public static final int POS_COMPOSITE_ELEMENT = 104; /** Constant <code>START_TAG="ISA"</code> */ public static final String START_TAG = "ISA"; private Cf x12Cf; private Cf cfMarker; private Loop loopMarker; /** * <p>Constructor for X12Parser.</p> * * @param cf a {@link Cf} object. */ public X12Parser(Cf cf) { this.x12Cf = cf; } /** * {@inheritDoc} * * The method takes a X12 file and converts it into a X2 object. The X12 * class has methods to convert it into XML format as well as methods to * modify the contents. */ public EDI parse(File fileName) throws FormatException, IOException { final char[] buffer = new char[SIZE]; FileReader fr = new FileReader(fileName); int count = fr.read(buffer); String start = new String(buffer, 0, 3); fr.close(); if (count != SIZE) { throw new FormatException("The Interchange Control Header is not " + "the correct size expected: "+SIZE+" found: "+count); } if (!start.startsWith(START_TAG)){ throw new FormatException("The Interchange Control Header Segment element: "+START_TAG+" is missing"); } Context context = new Context(); context.setSegmentSeparator(buffer[POS_SEGMENT]); context.setElementSeparator(buffer[POS_ELEMENT]); context.setCompositeElementSeparator(buffer[POS_COMPOSITE_ELEMENT]); Scanner scanner = new Scanner(fileName); X12 x12 = scanSource(scanner, context); scanner.close(); return x12; } /** * private helper method * @param scanner - the scanner to use in scanning. * @param context - context for the scanner. * @return X12 object found by the scanner. */ private X12 scanSource(Scanner scanner, Context context) { Character segmentSeparator = context.getSegmentSeparator(); String quotedSegmentSeparator = Pattern.quote(segmentSeparator.toString()); scanner.useDelimiter(quotedSegmentSeparator + "\r\n|" + quotedSegmentSeparator + "\n|" + quotedSegmentSeparator); cfMarker = x12Cf; X12 x12 = new X12(context); loopMarker = x12; Loop loop = x12; while (scanner.hasNext()) { String line = scanner.next(); String[] tokens = line.split("\\" + context.getElementSeparator()); if (doesChildLoopMatch(cfMarker, tokens)) { loop = loop.addChild(cfMarker.getName()); loop.addSegment(line); } else if (doesParentLoopMatch(cfMarker, tokens, loop)) { loop = loopMarker.addChild(cfMarker.getName()); loop.addSegment(line); } else { loop.addSegment(line); } } return x12; } /** * The method takes a InputStream and converts it into a X2 object. The X12 * class has methods to convert it into XML format as well as methods to * modify the contents. * * @param source * InputStream * @return the X12 object * @throws FormatException if any. * @throws java.io.IOException if any. */ public EDI parse(InputStream source) throws FormatException, IOException { StringBuilder strBuffer = new StringBuilder(); char[] cbuf = new char[1024]; int length; Reader reader = new BufferedReader(new InputStreamReader(source)); while ((length = reader.read(cbuf)) != -1) { strBuffer.append(cbuf, 0, length); } String strSource = strBuffer.toString(); return parse(strSource); } /** * The method takes a X12 string and converts it into a X2 object. The X12 * class has methods to convert it into XML format as well as methods to * modify the contents. * * @param source * String * @return the X12 object * @throws FormatException if any. */ public EDI parse(String source) throws FormatException { if (source.length() < SIZE) { throw new FormatException(); } Context context = new Context(); context.setSegmentSeparator(source.charAt(POS_SEGMENT)); context.setElementSeparator(source.charAt(POS_ELEMENT)); context.setCompositeElementSeparator(source.charAt(POS_COMPOSITE_ELEMENT)); Scanner scanner = new Scanner(source); X12 x12 = scanSource(scanner, context); scanner.close(); return x12; } /** * Checks if the segment (or line read) matches to current loop * * @param cf * Cf * @param tokens * String[] represents the segment broken into elements * @return boolean */ private boolean doesLoopMatch(Cf cf, String[] tokens) { if (cf.getSegment().equals(tokens[0])) { if (null == cf.getSegmentQualPos()) { return true; } else { for (String qual : cf.getSegmentQuals()) { if (qual.equals(tokens[cf.getSegmentQualPos()])) { return true; } } } } return false; } /** * Checks if the segment (or line read) matches to any of the child loops * configuration. * * @param parent * Cf * @param tokens * String[] represents the segment broken into elements * @return boolean */ boolean doesChildLoopMatch(Cf parent, String[] tokens) { for (Cf cf : parent.childList()) { if (doesLoopMatch(cf, tokens)) { cfMarker = cf; return true; } } return false; } /** * Checks if the segment (or line read) matches the parent loop * configuration. * * @param child * Cf * @param tokens * String[] represents the segment broken into elements * @param loop * Loop * @return boolean */ private boolean doesParentLoopMatch(Cf child, String[] tokens, Loop loop) { Cf parent = child.getParent(); if (parent == null) return false; loopMarker = loop.getParent(); for (Cf cf : parent.childList()) { if (doesLoopMatch(cf, tokens)) { cfMarker = cf; return true; } } return doesParentLoopMatch(parent, tokens, loopMarker); } }
ryanco/x12-parser
src/main/java/com/yarsquidy/x12/X12Parser.java
Java
apache-2.0
7,028
package com.chenantao.autolayout.utils; import android.view.ViewGroup; /** * Created by Chenantao_gg on 2016/1/20. */ public class AutoLayoutGenerate { public static <T extends ViewGroup> T generate(Class<T> clazz, Class[] argumentTypes, Object[] arguments) { // Enhancer enhancer = new Enhancer(); // enhancer.setSuperclass(clazz); // CallbackFilter filter = new ConcreteClassCallbackFilter(); // Callback methodInterceptor = new ConcreteClassMethodInterceptor<T>((Context) arguments[0], // (AttributeSet) arguments[1]); // Callback noOp = NoOp.INSTANCE; // Callback[] callbacks = new Callback[]{methodInterceptor, noOp}; // enhancer.setCallbackFilter(filter); // enhancer.setCallbacks(callbacks); // T proxyObj = (T) enhancer.create(argumentTypes, arguments); // //对onMeasure方法以及generateLayoutParams进行拦截,其他方法不进行操作 // return proxyObj; return null; } // static class ConcreteClassMethodInterceptor<T extends ViewGroup> implements MethodInterceptor // { // private AutoLayoutHelper mHelper; // private Context mContext; // private AttributeSet mAttrs; // // public ConcreteClassMethodInterceptor(Context context, AttributeSet attrs) // { // mContext = context; // mAttrs = attrs; // } // // public Object intercept(Object obj, Method method, Object[] arg, MethodProxy proxy) // throws Throwable // { // if (mHelper == null) // { // mHelper = new AutoLayoutHelper((ViewGroup) obj); // } // System.out.println("Before:" + method); // if ("onMeasure".equals(method.getName())) // { // //在onMeasure之前adjustChild // if (!((ViewGroup) obj).isInEditMode()) // { // mHelper.adjustChildren(); // } // // } else if ("generateLayoutParams".equals(method.getName())) // { // ViewGroup parent = (ViewGroup) obj; // final T.LayoutParams layoutParams = (T.LayoutParams) Enhancer.create(T.LayoutParams // .class, new Class[]{ // AutoLayoutHelper.AutoLayoutParams.class}, // new MethodInterceptor() // { // public Object intercept(Object obj, Method method, Object[] args, // MethodProxy proxy) throws Throwable // { // if ("getAutoLayoutInfo".equals(method.getName())) // { // return AutoLayoutHelper.getAutoLayoutInfo(mContext, mAttrs); // } // return proxy.invoke(obj, args); // } // }); // return layoutParams; // } // Object object = proxy.invokeSuper(obj, arg); // System.out.println("After:" + method); // return object; // } // } // // static class ConcreteClassCallbackFilter implements CallbackFilter // { // public int accept(Method method) // { // if ("onMeasure".equals(method.getName())) // { // return 0;//Callback callbacks[0] // } else if ("generateLayoutParams".equals(method.getName())) // { // return 0; // } // return 1; // } // } // static class LayoutParamsGenerate implements FixedValue // { // public LayoutParamsGenerate(Context context, AttributeSet attributeSet) // { // } // // public Object loadObject() throws Exception // { // System.out.println("ConcreteClassFixedValue loadObject ..."); // Object object = 999; // return object; // } // } }
Chenantao/PlayTogether
AutoLayout/src/main/java/com/chenantao/autolayout/utils/AutoLayoutGenerate.java
Java
apache-2.0
3,353
package com.petercipov.mobi.deployer; import com.petercipov.mobi.Instance; import com.petercipov.traces.api.Trace; import java.util.Optional; import rx.Observable; /** * * @author Peter Cipov */ public abstract class RxDeployment { protected Optional<String> name; public RxDeployment() { this.name = Optional.empty(); } public Optional<String> name() { return name; } /** * Sets container name * @since 1.14 * @param name * @return */ public RxDeployment setName(String name) { this.name = Optional.of(name); return this; } /** * Adds volume bindings to container as string in format /host/path:/container/path * @since 1.14 * @param volumeBindings iterable of bindings * @return */ public abstract RxDeployment addVolumes(Iterable<String> volumeBindings); /** * Adds volume binding * @since 1.14 * @param hostPath * @param containerPath * @return */ public abstract RxDeployment addVolume(String hostPath, String containerPath); /** * Adds environment variable to container * @since 1.14 * @param variable variable in a format NAME=VALUE * @return */ public abstract RxDeployment addEnv(String variable); /** * Adds environment variable to container * @since 1.14 * @param name * @param value * @return */ public abstract RxDeployment addEnv(String name, String value); /** * Add port that should be published * @since 1.14 * @param port - container port spect in format [tcp/udp]/port. f.e tcp/8080 * @param customPort - remapping port * @return */ public abstract RxDeployment addPortMapping(String port, int customPort); /** * Publishes all exposed ports if is set to true * @since 1.14 * @param publish * @return */ public abstract RxDeployment setPublishAllPorts(boolean publish); /** * Publishes all exposed ports * @since 1.14 * @return */ public abstract RxDeployment publishAllPorts(); /** * Runs the command when starting the container * @since 1.14 * @param cmd - command in for of single string or multitude of string that * contains parts of command * @return */ public abstract RxDeployment setCmd(String ... cmd); /** * Sets cpu quota * @since 1.19 * @param quota Microseconds of CPU time that the container can get in a CPU period * @return */ public abstract RxDeployment setCpuQuota(long quota); /** * Sets cpu shares * @since 1.14 * @param shares An integer value containing the container’s CPU Shares (ie. the relative weight vs other containers) * @return */ public abstract RxDeployment setCpuShares(long shares); /** * Sets domain name * @since 1.14 * @param name A string value containing the domain name to use for the container. * @return */ public abstract RxDeployment setDomainName(String name); /** * Sets entry point * @since 1.15 * @param entry A command to run inside container. it overrides one specified by container docker file. * @return */ public abstract RxDeployment setEntryPoint(String ... entry); /** * adds container exposed port * @since 1.14 * @param port in format [tcp/udp]/port. f.e tcp/8080 * @return */ public abstract RxDeployment addExposedPort(String port); /** * Sets hostname * @since 1.14 * @param hostName A string value containing the hostname to use for the container. * @return */ public abstract RxDeployment setHostName(String hostName); /** * Adds label * @since 1.18 * @param key * @param value * @return */ public abstract RxDeployment addLabel(String key, String value); /** * Sets MAC address. * @since 1.15 * @param mac * @return */ public abstract RxDeployment setMacAdress(String mac); /** * Sets memory limits * @since 1.14 * @param memory Memory limit in bytes * @return */ public abstract RxDeployment setMemory(long memory); /** * Sets memory limit * @since 1.14 * @param memory Memory limit in bytes * @param swap Memory limit for swap. Set -1 to disable swap. * @return */ public abstract RxDeployment setMemory(long memory, long swap); /** * Disables networking for the container * @since 1.14 * @param disabled * @return */ public abstract RxDeployment setNetworkDisabled(boolean disabled); /** * Opens stdin * @since 1.14 * @param open * @return */ public abstract RxDeployment setOpenStdIn(boolean open); /** * Opens stdin and closes stdin after the 1. attached client disconnects. * @since 1.14 * @param once * @return */ public abstract RxDeployment setStdInOnce(boolean once); /** * Attaches standard streams to a tty, including stdin if it is not closed. * @since 1.14 * @param enabled * @return */ public abstract RxDeployment setTty(boolean enabled); /** * @since 1.14 * @param user A string value specifying the user inside the containe * @return */ public abstract RxDeployment setUser(String user); /** * @since 1.14 * @param workDir A string specifying the working directory for commands to run in. * @return */ public abstract RxDeployment setWorkDir(String workDir); /** * Sets path to cgroup * @since 1.18 * @param parent Path to cgroups under which the cgroup for the container will be created. If the path is not absolute, the path is considered to be relative to the cgroups path of the init process. Cgroups will be created if they do not already exist * @return */ public abstract RxDeployment setCgroupParent(String parent); /** * Adds DNS for fontainer * @since 1.14 * @param dns A list of DNS servers for the container to use * @return */ public abstract RxDeployment addDns(String ... dns); /** * Adds DNS search domains * @since 1.15 * @param dns A list of DNS servers for the container to use. * @return */ public abstract RxDeployment addDnsSearch(String ... dns); /** * Adds extra hosts co container /etc/hosts * @since 1.15 * @param hosts A list of hostnames/IP mappings to add to the container’s /etc/hosts file. Specified in the form ["hostname:IP"] * @return */ public abstract RxDeployment addExtraHosts(String ... hosts); /** * Adds links to other containers * @since 1.14 * @param links A list of links for the container. Each link entry should be in the form of container_name:alias * @return */ public abstract RxDeployment addLinks(String ... links); /** * Sets LXC specific configurations. These configurations only work when using the lxc execution driver. * @since 1.14 * @param key * @param value * @return */ public abstract RxDeployment addLxcParameter(String key, String value); /** * Sets the networking mode for the container * @since 1.15 * @param mode Supported values are: bridge, host, and container:name|id * @return */ public abstract RxDeployment setNetworkMode(String mode); /** * Gives the container full access to the host. * @since 1.14 * @param privileged * @return */ public abstract RxDeployment setPrivileged(boolean privileged); /** * @since 1.15 * @param opts string value to customize labels for MLS systems, such as SELinux. * @return */ public abstract RxDeployment addSecurityOpt(String ... opts); /** * Adds volume from an other container * @since 1.14 * @param volumes volume to inherit from another container. Specified in the form container name:ro|rw * @return */ public abstract RxDeployment addVolumeFrom(String ... volumes); protected abstract Observable<String> createContainer(Trace trace, Instance image); }
petercipov/mobi
deployer/src/main/java/com/petercipov/mobi/deployer/RxDeployment.java
Java
apache-2.0
7,654
/* * Copyright 2015 Torridity. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tor.tribes.ui.models; import de.tor.tribes.types.ext.Village; import de.tor.tribes.ui.wiz.ret.types.RETSourceElement; import java.util.LinkedList; import java.util.List; import javax.swing.table.AbstractTableModel; /** * * @author Torridity */ public class RETSourceTableModel extends AbstractTableModel { private String[] columnNames = new String[]{ "Herkunft" }; private Class[] types = new Class[]{ Village.class }; private final List<RETSourceElement> elements = new LinkedList<RETSourceElement>(); public RETSourceTableModel() { super(); } public void clear() { elements.clear(); fireTableDataChanged(); } public void addRow(RETSourceElement pVillage, boolean pValidate) { elements.add(pVillage); if (pValidate) { fireTableDataChanged(); } } @Override public int getRowCount() { if (elements == null) { return 0; } return elements.size(); } @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public String getColumnName(int column) { return columnNames[column]; } public void removeRow(int row) { elements.remove(row); fireTableDataChanged(); } public RETSourceElement getRow(int row) { return elements.get(row); } @Override public Object getValueAt(int row, int column) { if (elements == null || elements.size() - 1 < row) { return null; } return elements.get(row).getVillage(); } @Override public int getColumnCount() { return columnNames.length; } }
Akeshihiro/dsworkbench
Core/src/main/java/de/tor/tribes/ui/models/RETSourceTableModel.java
Java
apache-2.0
2,442
package com.zk.web.interceptor; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; public class CustomizedHandlerExceptionResolver implements HandlerExceptionResolver, Ordered { private static final Logger LOGGER = LoggerFactory.getLogger(CustomizedHandlerExceptionResolver.class); public int getOrder() { return Integer.MIN_VALUE; } public ModelAndView resolveException(HttpServletRequest aReq, HttpServletResponse aRes, Object aHandler, Exception exception) { if (aHandler instanceof HandlerMethod) { if (exception instanceof BindException) { return null; } } LOGGER.error(StringUtils.EMPTY, exception); ModelAndView mav = new ModelAndView("common/error"); String errorMsg = exception.getMessage(); aRes.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); if ("XMLHttpRequest".equals(aReq.getHeader("X-Requested-With"))) { try { aRes.setContentType("application/text; charset=utf-8"); PrintWriter writer = aRes.getWriter(); aRes.setStatus(HttpServletResponse.SC_FORBIDDEN); writer.print(errorMsg); writer.flush(); writer.close(); return null; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } mav.addObject("errorMsg", errorMsg); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); exception.printStackTrace(pw); mav.addObject("stackTrace", sw.getBuffer().toString()); mav.addObject("exception", exception); return mav; } }
wqintel/zookeeper-web
src/main/java/com/zk/web/interceptor/CustomizedHandlerExceptionResolver.java
Java
apache-2.0
2,187
/** * 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.intelligentsia.dowsers.core.serializers.jackson; import java.io.IOException; import org.intelligentsia.dowsers.core.reflection.ClassInformation; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; /** * * ClassInformationDeserializer. * * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a> */ public class ClassInformationDeserializer extends StdDeserializer<ClassInformation> { /** * serialVersionUID:long */ private static final long serialVersionUID = -6052449554113264932L; public ClassInformationDeserializer() { super(ClassInformation.class); } @Override public ClassInformation deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { String description = null; if (jp.hasCurrentToken()) { if (jp.getCurrentToken().equals(JsonToken.START_OBJECT)) { jp.nextValue(); description = jp.getText(); jp.nextToken(); } } return description != null ? ClassInformation.parse(description) : null; } }
geronimo-iia/dowsers
dowsers-core/src/main/java/org/intelligentsia/dowsers/core/serializers/jackson/ClassInformationDeserializer.java
Java
apache-2.0
2,180
package org.jboss.resteasy.reactive.server.vertx.test; import static org.junit.jupiter.api.Assertions.fail; import io.smallrye.common.annotation.Blocking; import io.smallrye.common.annotation.NonBlocking; import java.util.function.Supplier; import javax.enterprise.inject.spi.DeploymentException; import javax.ws.rs.Path; import org.jboss.resteasy.reactive.server.vertx.test.framework.ResteasyReactiveUnitTest; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class BothBlockingAndNonBlockingOnClassTest { @RegisterExtension static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(Resource.class); } }).setExpectedException(DeploymentException.class); @Test public void test() { fail("Should never have been called"); } @Path("test") @Blocking @NonBlocking public static class Resource { @Path("hello") public String hello() { return "hello"; } } }
quarkusio/quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/BothBlockingAndNonBlockingOnClassTest.java
Java
apache-2.0
1,351
/* * * * * Copyright (C) 2015 Orange * * 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.orange.servicebroker.staticcreds.stories.support_route_services; import com.orange.servicebroker.staticcreds.domain.PlanProperties; import com.orange.servicebroker.staticcreds.domain.ServiceBrokerProperties; import com.orange.servicebroker.staticcreds.domain.ServiceProperties; import com.tngtech.jgiven.junit.SimpleScenarioTest; import org.junit.Test; import org.springframework.cloud.servicebroker.model.ServiceDefinitionRequires; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * @author Sebastien Bortolussi */ @AddRouteService @Issue_32 public class ConfigureServiceBrokerWithRouteServiceTest extends SimpleScenarioTest<ConfigureServiceBrokerStage> { private static ServiceBrokerProperties service_broker_properties_with_route_service_url_at_service_level_and_requires_field_set() { PlanProperties dev = new PlanProperties("dev"); dev.setId("dev-id"); dev.setCredentials(uriCredentials()); ServiceProperties myServiceProperties = new ServiceProperties(); myServiceProperties.setName("myservice"); myServiceProperties.setId("myservice-id"); myServiceProperties.setRequires(Arrays.asList(ServiceDefinitionRequires.SERVICE_REQUIRES_ROUTE_FORWARDING.toString())); myServiceProperties.setRouteServiceUrl("https://myloggingservice.org/path"); final Map<String, PlanProperties> myServicePlans = new HashMap<>(); myServicePlans.put("dev", dev); myServiceProperties.setPlans(myServicePlans); final Map<String, ServiceProperties> services = new HashMap<>(); services.put("myservice", myServiceProperties); return new ServiceBrokerProperties(services); } private static Map<String, Object> uriCredentials() { Map<String, Object> credentials = new HashMap<>(); credentials.put("URI", "http://my-api.org"); return credentials; } private static ServiceBrokerProperties service_broker_properties_with_route_service_url_at_service_plan_level_and_requires_field_set() { PlanProperties dev = new PlanProperties("dev"); dev.setId("dev-id"); dev.setCredentials(uriCredentials()); dev.setRouteServiceUrl("https://myloggingservice.org/path"); ServiceProperties myServiceProperties = new ServiceProperties(); myServiceProperties.setName("myservice"); myServiceProperties.setId("myservice-id"); myServiceProperties.setRequires(Arrays.asList(ServiceDefinitionRequires.SERVICE_REQUIRES_ROUTE_FORWARDING.toString())); final Map<String, PlanProperties> myServicePlans = new HashMap<>(); myServicePlans.put("dev", dev); myServiceProperties.setPlans(myServicePlans); final Map<String, ServiceProperties> services = new HashMap<>(); services.put("myservice", myServiceProperties); return new ServiceBrokerProperties(services); } private static ServiceBrokerProperties catalog_with_route_service_url_at_service_level_but_without_requires_field_set() { PlanProperties dev = new PlanProperties("dev"); dev.setId("dev-id"); dev.setCredentials(uriCredentials()); ServiceProperties myServiceProperties = new ServiceProperties(); myServiceProperties.setName("myservice"); myServiceProperties.setId("myservice-id"); myServiceProperties.setRouteServiceUrl("https://myloggingservice.org/path"); final Map<String, PlanProperties> myServicePlans = new HashMap<>(); myServicePlans.put("dev", dev); myServiceProperties.setPlans(myServicePlans); final Map<String, ServiceProperties> services = new HashMap<>(); services.put("myservice", myServiceProperties); return new ServiceBrokerProperties(services); } private static ServiceBrokerProperties service_broker_properties_with_route_service_url_at_service_plan_level_but_without_requires_field_set() { PlanProperties dev = new PlanProperties("dev"); dev.setId("dev-id"); dev.setCredentials(uriCredentials()); dev.setRouteServiceUrl("https://myloggingservice.org/path"); ServiceProperties myServiceProperties = new ServiceProperties(); myServiceProperties.setName("myservice"); myServiceProperties.setId("myservice-id"); final Map<String, PlanProperties> myServicePlans = new HashMap<>(); myServicePlans.put("dev", dev); myServiceProperties.setPlans(myServicePlans); final Map<String, ServiceProperties> services = new HashMap<>(); services.put("myservice", myServiceProperties); return new ServiceBrokerProperties(services); } @Test public void configure_service_broker_with_same_route_service_url_for_all_service_plans_and_requires_field_set() throws Exception { when().paas_ops_configures_service_broker_with_following_config(service_broker_properties_with_route_service_url_at_service_level_and_requires_field_set()); then().it_should_succeed(); } @Test public void configure_service_broker_with_same_route_service_url_for_all_service_plans_but_omits_requires_field() throws Exception { when().paas_ops_configures_service_broker_with_following_config(catalog_with_route_service_url_at_service_level_but_without_requires_field_set()); then().it_should_fail(); } @Test public void configure_service_broker_with_route_service_url_set_for_a_service_plan_and_requires_field_set() throws Exception { when().paas_ops_configures_service_broker_with_following_config(service_broker_properties_with_route_service_url_at_service_plan_level_and_requires_field_set()); then().it_should_succeed(); } @Test public void configure_service_broker_with_route_service_url_set_for_a_service_plan_but_omits_requires_field() throws Exception { when().paas_ops_configures_service_broker_with_following_config(service_broker_properties_with_route_service_url_at_service_plan_level_but_without_requires_field_set()); then().it_should_fail(); } }
Orange-OpenSource/static-creds-broker
src/test/java/com/orange/servicebroker/staticcreds/stories/support_route_services/ConfigureServiceBrokerWithRouteServiceTest.java
Java
apache-2.0
6,730
/* * Copyright 2018 Sebastien Callier * * 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 sebastien.callier.serialization.codec.extendable.object.field.primitives; import sebastien.callier.serialization.codec.Codec; import sebastien.callier.serialization.codec.extendable.object.field.FieldCodec; import sebastien.callier.serialization.codec.extendable.object.field.LambdaMetaFactoryUtils; import sebastien.callier.serialization.deserializer.InputStreamWrapper; import sebastien.callier.serialization.exceptions.CodecGenerationException; import sebastien.callier.serialization.serializer.OutputStreamWrapper; import java.io.IOException; import java.lang.reflect.Method; /** * @author Sebastien Callier * @since 2018 */ public class ByteFieldCodec implements FieldCodec { private final Getter get; private final Setter set; private final Codec codec; public ByteFieldCodec( Method getter, Method setter, Codec codec) throws CodecGenerationException { super(); get = LambdaMetaFactoryUtils.wrapGetter(Getter.class, getter, byte.class); set = LambdaMetaFactoryUtils.wrapSetter(Setter.class, setter, byte.class); this.codec = codec; } @FunctionalInterface public interface Getter { byte get(Object instance); } @FunctionalInterface public interface Setter { void set(Object instance, byte value); } @Override @SuppressWarnings("unchecked") public void write(OutputStreamWrapper wrapper, Object instance) throws IOException { codec.write(wrapper, get.get(instance)); } @Override @SuppressWarnings("unchecked") public void read(InputStreamWrapper wrapper, Object instance) throws IOException { set.set(instance, (Byte) codec.read(wrapper)); } }
S-Callier/serialization
src/main/java/sebastien/callier/serialization/codec/extendable/object/field/primitives/ByteFieldCodec.java
Java
apache-2.0
2,341
package com.noeasy.money.exception; public class UserErrorMetadata extends BaseErrorMetadata { public static final UserErrorMetadata USER_EXIST = new UserErrorMetadata(101, "User exit"); public static final UserErrorMetadata NULL_USER_BEAN = new UserErrorMetadata(102, "Userbean is null"); protected UserErrorMetadata(int pErrorCode, String pErrorMesage) { super(pErrorCode, pErrorMesage); } }
DormitoryTeam/Dormitory
src/main/java/com/noeasy/money/exception/UserErrorMetadata.java
Java
apache-2.0
428
/******************************************************************************* * Copyright (c) 2015-2019 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.nn.weights.embeddings; import lombok.EqualsAndHashCode; import lombok.NonNull; import org.deeplearning4j.nn.weights.IWeightInit; import org.nd4j.common.base.Preconditions; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.shade.jackson.annotation.JsonIgnoreProperties; import org.nd4j.shade.jackson.annotation.JsonProperty; /** * Weight initialization for initializing the parameters of an EmbeddingLayer from a {@link EmbeddingInitializer} * * Note: WeightInitEmbedding supports both JSON serializable and non JSON serializable initializations. * In the case of non-JSON serializable embeddings, they are a one-time only use: once they have been used * to initialize the parameters, they will be removed from the WeightInitEmbedding instance. * This is to prevent unnecessary references to potentially large objects in memory (i.e., to avoid memory leaks) * * @author Alex Black */ @JsonIgnoreProperties("nonSerializableInit") @EqualsAndHashCode public class WeightInitEmbedding implements IWeightInit { private EmbeddingInitializer serializableInit; private EmbeddingInitializer nonSerializableInit; public WeightInitEmbedding(@NonNull EmbeddingInitializer embeddingInitializer){ this((embeddingInitializer.jsonSerializable() ? embeddingInitializer : null), (embeddingInitializer.jsonSerializable() ? null : embeddingInitializer)); } protected WeightInitEmbedding(@JsonProperty("serializableInit") EmbeddingInitializer serializableInit, @JsonProperty("nonSerializableInit") EmbeddingInitializer nonSerializableInit){ this.serializableInit = serializableInit; this.nonSerializableInit = nonSerializableInit; } @Override public INDArray init(double fanIn, double fanOut, long[] shape, char order, INDArray paramView) { EmbeddingInitializer init = serializableInit != null ? serializableInit : nonSerializableInit; if(init == null){ throw new IllegalStateException("Cannot initialize embedding layer weights: no EmbeddingInitializer is available." + " This can occur if you save network configuration, load it, and the try to "); } Preconditions.checkState(shape[0] == init.vocabSize(), "Parameters shape[0]=%s does not match embedding initializer vocab size of %s", shape[0], init.vocabSize()); Preconditions.checkState(shape[1] == init.vectorSize(), "Parameters shape[1]=%s does not match embedding initializer vector size of %s", shape[1], init.vectorSize()); INDArray reshaped = paramView.reshape('c', shape); init.loadWeightsInto(reshaped); //Now that we've loaded weights - let's clear the reference if it's non-serializable so it can be GC'd this.nonSerializableInit = null; return reshaped; } public long[] shape(){ if(serializableInit != null){ return new long[]{serializableInit.vocabSize(), serializableInit.vectorSize()}; } else if(nonSerializableInit != null){ return new long[]{nonSerializableInit.vocabSize(), nonSerializableInit.vectorSize()}; } return null; } }
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/weights/embeddings/WeightInitEmbedding.java
Java
apache-2.0
3,970
/* * Copyright 2020 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.dmn.openapi.impl; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.microprofile.openapi.OASFactory; import org.eclipse.microprofile.openapi.models.media.Schema; import org.eclipse.microprofile.openapi.models.media.Schema.SchemaType; import org.kie.dmn.api.core.DMNType; import org.kie.dmn.core.impl.BaseDMNTypeImpl; import org.kie.dmn.core.impl.CompositeTypeImpl; import org.kie.dmn.core.impl.SimpleTypeImpl; import org.kie.dmn.openapi.NamingPolicy; import org.kie.dmn.openapi.model.DMNModelIOSets; import org.kie.dmn.openapi.model.DMNModelIOSets.DSIOSets; import org.kie.dmn.typesafe.DMNTypeUtils; public class DMNTypeSchemas { private final List<DMNModelIOSets> ioSets; private final Set<DMNType> typesIndex; private final NamingPolicy namingPolicy; public DMNTypeSchemas(List<DMNModelIOSets> ioSets, Set<DMNType> typesIndex, NamingPolicy namingPolicy) { this.ioSets = Collections.unmodifiableList(ioSets); this.typesIndex = Collections.unmodifiableSet(typesIndex); this.namingPolicy = namingPolicy; } public Map<DMNType, Schema> generateSchemas() { Map<DMNType, Schema> schemas = new HashMap<>(); for (DMNType t : typesIndex) { Schema schema = schemaFromType(t); schemas.put(t, schema); } return schemas; } private Schema refOrBuiltinSchema(DMNType t) { if (DMNTypeUtils.isFEELBuiltInType(t)) { return FEELBuiltinTypeSchemas.from(t); } if (typesIndex.contains(t)) { Schema schema = OASFactory.createObject(Schema.class).ref(namingPolicy.getRef(t)); return schema; } throw new UnsupportedOperationException(); } private boolean isIOSet(DMNType t) { for (DMNModelIOSets ios : ioSets) { if (ios.getInputSet().equals(t)) { return true; } for (DSIOSets ds : ios.getDSIOSets()) { if (ds.getDSInputSet().equals(t)) { return true; } } } return false; } private Schema schemaFromType(DMNType t) { if (t instanceof CompositeTypeImpl) { return schemaFromCompositeType((CompositeTypeImpl) t); } if (t instanceof SimpleTypeImpl) { return schemaFromSimpleType((SimpleTypeImpl) t); } throw new UnsupportedOperationException(); } private Schema schemaFromSimpleType(SimpleTypeImpl t) { DMNType baseType = t.getBaseType(); if (baseType == null) { throw new IllegalStateException(); } Schema schema = refOrBuiltinSchema(baseType); if (t.getAllowedValues() != null && !t.getAllowedValues().isEmpty()) { FEELSchemaEnum.parseAllowedValuesIntoSchema(schema, t.getAllowedValues()); } schema = nestAsItemIfCollection(schema, t); schema.addExtension(DMNOASConstants.X_DMN_TYPE, getDMNTypeSchemaXDMNTYPEdescr(t)); return schema; } private Schema schemaFromCompositeType(CompositeTypeImpl ct) { Schema schema = OASFactory.createObject(Schema.class).type(SchemaType.OBJECT); if (ct.getBaseType() == null) { // main case for (Entry<String, DMNType> fkv : ct.getFields().entrySet()) { schema.addProperty(fkv.getKey(), refOrBuiltinSchema(fkv.getValue())); } if (isIOSet(ct) && ct.getFields().size() > 0) { schema.required(new ArrayList<>(ct.getFields().keySet())); } } else if (ct.isCollection()) { schema = refOrBuiltinSchema(ct.getBaseType()); } else { throw new IllegalStateException(); } schema = nestAsItemIfCollection(schema, ct); schema.addExtension(DMNOASConstants.X_DMN_TYPE, getDMNTypeSchemaXDMNTYPEdescr(ct)); return schema; } private Schema nestAsItemIfCollection(Schema original, DMNType t) { if (t.isCollection()) { return OASFactory.createObject(Schema.class).type(SchemaType.ARRAY).items(original); } else { return original; } } private String getDMNTypeSchemaXDMNTYPEdescr(DMNType t) { if (((BaseDMNTypeImpl) t).getBelongingType() == null) { // internals for anonymous inner types. return t.toString(); } else { return null; } } }
droolsjbpm/drools
kie-dmn/kie-dmn-openapi/src/main/java/org/kie/dmn/openapi/impl/DMNTypeSchemas.java
Java
apache-2.0
5,225
/* * Copyright 2018 OPS4J 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.ops4j.kaiserkai.rest; import com.spotify.docker.client.auth.RegistryAuthSupplier; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.RegistryAuth; import com.spotify.docker.client.messages.RegistryConfigs; /** * @author Harald Wellmann * */ public class LocalAuthSupplier implements RegistryAuthSupplier { @Override public RegistryAuth authFor(String imageName) throws DockerException { if (imageName.startsWith("127.0.0.1")) { RegistryAuth auth = RegistryAuth.builder().username("admin").password("admin").build(); return auth; } return null; } @Override public RegistryAuth authForSwarm() throws DockerException { return null; } @Override public RegistryConfigs authForBuild() throws DockerException { return null; } }
hwellmann/org.ops4j.kaiserkai
kaiserkai-itest/src/test/java/org/ops4j/kaiserkai/rest/LocalAuthSupplier.java
Java
apache-2.0
1,497
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/cx/v3beta1/advanced_settings.proto package com.google.cloud.dialogflow.cx.v3beta1; public final class AdvancedSettingsProto { private AdvancedSettingsProto() {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n:google/cloud/dialogflow/cx/v3beta1/adv" + "anced_settings.proto\022\"google.cloud.dialo" + "gflow.cx.v3beta1\032\037google/api/field_behav" + "ior.proto\"\315\001\n\020AdvancedSettings\022^\n\020loggin" + "g_settings\030\006 \001(\0132D.google.cloud.dialogfl" + "ow.cx.v3beta1.AdvancedSettings.LoggingSe" + "ttings\032Y\n\017LoggingSettings\022\"\n\032enable_stac" + "kdriver_logging\030\002 \001(\010\022\"\n\032enable_interact" + "ion_logging\030\003 \001(\010B\335\001\n&com.google.cloud.d" + "ialogflow.cx.v3beta1B\025AdvancedSettingsPr" + "otoP\001ZDgoogle.golang.org/genproto/google" + "apis/cloud/dialogflow/cx/v3beta1;cx\370\001\001\242\002" + "\002DF\252\002\"Google.Cloud.Dialogflow.Cx.V3Beta1" + "\352\002&Google::Cloud::Dialogflow::CX::V3beta" + "1b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.FieldBehaviorProto.getDescriptor(), }); internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor, new java.lang.String[] { "LoggingSettings", }); internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_descriptor = internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_dialogflow_cx_v3beta1_AdvancedSettings_LoggingSettings_descriptor, new java.lang.String[] { "EnableStackdriverLogging", "EnableInteractionLogging", }); com.google.api.FieldBehaviorProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
googleapis/java-dialogflow-cx
proto-google-cloud-dialogflow-cx-v3beta1/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/AdvancedSettingsProto.java
Java
apache-2.0
4,476
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.rocketmq.client.impl.consumer; import com.alibaba.rocketmq.client.log.ClientLogger; import com.alibaba.rocketmq.common.message.MessageConst; import com.alibaba.rocketmq.common.message.MessageExt; import com.alibaba.rocketmq.common.protocol.body.ProcessQueueInfo; import org.slf4j.Logger; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Queue consumption snapshot * * @author shijia.wxr<vintage.wang@gmail.com> * @since 2013-7-24 */ public class ProcessQueue { public final static long RebalanceLockMaxLiveTime = Long.parseLong(System.getProperty( "rocketmq.client.rebalance.lockMaxLiveTime", "30000")); public final static long RebalanceLockInterval = Long.parseLong(System.getProperty( "rocketmq.client.rebalance.lockInterval", "20000")); private final static long PullMaxIdleTime = Long.parseLong(System.getProperty( "rocketmq.client.pull.pullMaxIdleTime", "120000")); private final Logger log = ClientLogger.getLog(); private final ReadWriteLock lockTreeMap = new ReentrantReadWriteLock(); private final TreeMap<Long, MessageExt> msgTreeMap = new TreeMap<Long, MessageExt>(); private final AtomicLong msgCount = new AtomicLong(); private final Lock lockConsume = new ReentrantLock(); private final TreeMap<Long, MessageExt> msgTreeMapTemp = new TreeMap<Long, MessageExt>(); private final AtomicLong tryUnlockTimes = new AtomicLong(0); private volatile long queueOffsetMax = 0L; private volatile boolean dropped = false; private volatile long lastPullTimestamp = System.currentTimeMillis(); private volatile long lastConsumeTimestamp = System.currentTimeMillis(); private volatile boolean locked = false; private volatile long lastLockTimestamp = System.currentTimeMillis(); private volatile boolean consuming = false; private volatile long msgAccCnt = 0; public boolean isLockExpired() { boolean result = (System.currentTimeMillis() - this.lastLockTimestamp) > RebalanceLockMaxLiveTime; return result; } public boolean isPullExpired() { boolean result = (System.currentTimeMillis() - this.lastPullTimestamp) > PullMaxIdleTime; return result; } public boolean putMessage(final List<MessageExt> msgs) { boolean dispatchToConsume = false; try { this.lockTreeMap.writeLock().lockInterruptibly(); try { int validMsgCnt = 0; for (MessageExt msg : msgs) { MessageExt old = msgTreeMap.put(msg.getQueueOffset(), msg); if (null == old) { validMsgCnt++; this.queueOffsetMax = msg.getQueueOffset(); } } msgCount.addAndGet(validMsgCnt); if (!msgTreeMap.isEmpty() && !this.consuming) { dispatchToConsume = true; this.consuming = true; } if (!msgs.isEmpty()) { MessageExt messageExt = msgs.get(msgs.size() - 1); String property = messageExt.getProperty(MessageConst.PROPERTY_MAX_OFFSET); if (property != null) { long accTotal = Long.parseLong(property) - messageExt.getQueueOffset(); if (accTotal > 0) { this.msgAccCnt = accTotal; } } } } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("putMessage exception", e); } return dispatchToConsume; } public long getMaxSpan() { try { this.lockTreeMap.readLock().lockInterruptibly(); try { if (!this.msgTreeMap.isEmpty()) { return this.msgTreeMap.lastKey() - this.msgTreeMap.firstKey(); } } finally { this.lockTreeMap.readLock().unlock(); } } catch (InterruptedException e) { log.error("getMaxSpan exception", e); } return 0; } public long removeMessage(final List<MessageExt> msgs) { long result = -1; final long now = System.currentTimeMillis(); try { this.lockTreeMap.writeLock().lockInterruptibly(); this.lastConsumeTimestamp = now; try { if (!msgTreeMap.isEmpty()) { result = this.queueOffsetMax + 1; int removedCnt = 0; for (MessageExt msg : msgs) { MessageExt prev = msgTreeMap.remove(msg.getQueueOffset()); if (prev != null) { removedCnt--; } } msgCount.addAndGet(removedCnt); if (!msgTreeMap.isEmpty()) { result = msgTreeMap.firstKey(); } } } finally { this.lockTreeMap.writeLock().unlock(); } } catch (Throwable t) { log.error("removeMessage exception", t); } return result; } public TreeMap<Long, MessageExt> getMsgTreeMap() { return msgTreeMap; } public AtomicLong getMsgCount() { return msgCount; } public boolean isDropped() { return dropped; } public void setDropped(boolean dropped) { this.dropped = dropped; } public boolean isLocked() { return locked; } public void setLocked(boolean locked) { this.locked = locked; } public void rollback() { try { this.lockTreeMap.writeLock().lockInterruptibly(); try { this.msgTreeMap.putAll(this.msgTreeMapTemp); this.msgTreeMapTemp.clear(); } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("rollback exception", e); } } public long commit() { try { this.lockTreeMap.writeLock().lockInterruptibly(); try { Long offset = this.msgTreeMapTemp.lastKey(); msgCount.addAndGet(this.msgTreeMapTemp.size() * (-1)); this.msgTreeMapTemp.clear(); if (offset != null) { return offset + 1; } } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("commit exception", e); } return -1; } public void makeMessageToCosumeAgain(List<MessageExt> msgs) { try { this.lockTreeMap.writeLock().lockInterruptibly(); try { for (MessageExt msg : msgs) { this.msgTreeMapTemp.remove(msg.getQueueOffset()); this.msgTreeMap.put(msg.getQueueOffset(), msg); } } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("makeMessageToCosumeAgain exception", e); } } public List<MessageExt> takeMessags(final int batchSize) { List<MessageExt> result = new ArrayList<MessageExt>(batchSize); final long now = System.currentTimeMillis(); try { this.lockTreeMap.writeLock().lockInterruptibly(); this.lastConsumeTimestamp = now; try { if (!this.msgTreeMap.isEmpty()) { for (int i = 0; i < batchSize; i++) { Map.Entry<Long, MessageExt> entry = this.msgTreeMap.pollFirstEntry(); if (entry != null) { result.add(entry.getValue()); msgTreeMapTemp.put(entry.getKey(), entry.getValue()); } else { break; } } } if (result.isEmpty()) { consuming = false; } } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("take Messages exception", e); } return result; } public void clear() { try { this.lockTreeMap.writeLock().lockInterruptibly(); try { this.msgTreeMap.clear(); this.msgTreeMapTemp.clear(); this.msgCount.set(0); this.queueOffsetMax = 0L; } finally { this.lockTreeMap.writeLock().unlock(); } } catch (InterruptedException e) { log.error("rollback exception", e); } } public long getLastLockTimestamp() { return lastLockTimestamp; } public void setLastLockTimestamp(long lastLockTimestamp) { this.lastLockTimestamp = lastLockTimestamp; } public Lock getLockConsume() { return lockConsume; } public long getLastPullTimestamp() { return lastPullTimestamp; } public void setLastPullTimestamp(long lastPullTimestamp) { this.lastPullTimestamp = lastPullTimestamp; } public long getMsgAccCnt() { return msgAccCnt; } public void setMsgAccCnt(long msgAccCnt) { this.msgAccCnt = msgAccCnt; } public long getTryUnlockTimes() { return this.tryUnlockTimes.get(); } public void incTryUnlockTimes() { this.tryUnlockTimes.incrementAndGet(); } public void fillProcessQueueInfo(final ProcessQueueInfo info) { try { this.lockTreeMap.readLock().lockInterruptibly(); if (!this.msgTreeMap.isEmpty()) { info.setCachedMsgMinOffset(this.msgTreeMap.firstKey()); info.setCachedMsgMaxOffset(this.msgTreeMap.lastKey()); info.setCachedMsgCount(this.msgTreeMap.size()); } if (!this.msgTreeMapTemp.isEmpty()) { info.setTransactionMsgMinOffset(this.msgTreeMapTemp.firstKey()); info.setTransactionMsgMaxOffset(this.msgTreeMapTemp.lastKey()); info.setTransactionMsgCount(this.msgTreeMapTemp.size()); } info.setLocked(this.locked); info.setTryUnlockTimes(this.tryUnlockTimes.get()); info.setLastLockTimestamp(this.lastLockTimestamp); info.setDroped(this.dropped); info.setLastPullTimestamp(this.lastPullTimestamp); info.setLastConsumeTimestamp(this.lastConsumeTimestamp); } catch (Exception e) { } finally { this.lockTreeMap.readLock().unlock(); } } public long getLastConsumeTimestamp() { return lastConsumeTimestamp; } public void setLastConsumeTimestamp(long lastConsumeTimestamp) { this.lastConsumeTimestamp = lastConsumeTimestamp; } }
tgou/RocketMQ
rocketmq-client/src/main/java/com/alibaba/rocketmq/client/impl/consumer/ProcessQueue.java
Java
apache-2.0
12,629
/* * 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. */ /** * @author Alexander Y. Kleymenov * @version $Revision$ */ package javax.crypto.spec; import java.io.Serializable; import java.security.spec.KeySpec; import java.util.Arrays; import javax.crypto.SecretKey; /** * A key specification for a <code>SecretKey</code> and also a secret key * implementation that is provider-independent. It can be used for raw secret * keys that can be specified as <code>byte[]</code>. */ public class SecretKeySpec implements SecretKey, KeySpec, Serializable { // The 5.0 spec. doesn't declare this serialVersionUID field // In order to be compatible it is explicitly declared here // for details see HARMONY-233 private static final long serialVersionUID = 6577238317307289933L; private final byte[] key; private final String algorithm; private final String format = "RAW"; /** * Creates a new <code>SecretKeySpec</code> for the specified key data and * algorithm name. * * @param key * the key data. * @param algorithm * the algorithm name. * @throws IllegalArgumentException * if the key data or the algorithm name is null or if the key * data is empty. */ public SecretKeySpec(byte[] key, String algorithm) { if (key == null) { throw new IllegalArgumentException("key == null"); } if (key.length == 0) { throw new IllegalArgumentException("key.length == 0"); } if (algorithm == null) { throw new IllegalArgumentException("algorithm == null"); } this.algorithm = algorithm; this.key = new byte[key.length]; System.arraycopy(key, 0, this.key, 0, key.length); } /** * Creates a new <code>SecretKeySpec</code> for the key data from the * specified buffer <code>key</code> starting at <code>offset</code> with * length <code>len</code> and the specified <code>algorithm</code> name. * * @param key * the key data. * @param offset * the offset. * @param len * the size of the key data. * @param algorithm * the algorithm name. * @throws IllegalArgumentException * if the key data or the algorithm name is null, the key data * is empty or <code>offset</code> and <code>len</code> do not * specify a valid chunk in the buffer <code>key</code>. * @throws ArrayIndexOutOfBoundsException * if <code>offset</code> or <code>len</code> is negative. */ public SecretKeySpec(byte[] key, int offset, int len, String algorithm) { if (key == null) { throw new IllegalArgumentException("key == null"); } if (key.length == 0) { throw new IllegalArgumentException("key.length == 0"); } // BEGIN android-changed if (len < 0 || offset < 0) { throw new ArrayIndexOutOfBoundsException("len < 0 || offset < 0"); } // END android-changed if (key.length - offset < len) { throw new IllegalArgumentException("key too short"); } if (algorithm == null) { throw new IllegalArgumentException("algorithm == null"); } this.algorithm = algorithm; this.key = new byte[len]; System.arraycopy(key, offset, this.key, 0, len); } /** * Returns the algorithm name. * * @return the algorithm name. */ public String getAlgorithm() { return algorithm; } /** * Returns the name of the format used to encode the key. * * @return the format name "RAW". */ public String getFormat() { return format; } /** * Returns the encoded form of this secret key. * * @return the encoded form of this secret key. */ public byte[] getEncoded() { byte[] result = new byte[key.length]; System.arraycopy(key, 0, result, 0, key.length); return result; } /** * Returns the hash code of this <code>SecretKeySpec</code> object. * * @return the hash code. */ @Override public int hashCode() { int result = algorithm.length(); for (byte element : key) { result += element; } return result; } /** * Compares the specified object with this <code>SecretKeySpec</code> * instance. * * @param obj * the object to compare. * @return true if the algorithm name and key of both object are equal, * otherwise false. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof SecretKeySpec)) { return false; } SecretKeySpec ks = (SecretKeySpec) obj; return (algorithm.equalsIgnoreCase(ks.algorithm)) && (Arrays.equals(key, ks.key)); } }
webos21/xi
java/jcl/src/java/javax/crypto/spec/SecretKeySpec.java
Java
apache-2.0
5,286
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import java.io.File; import java.io.IOException; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.fs.permission.PermissionStatus; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.server.common.GenerationStamp; import org.apache.hadoop.hdfs.server.common.Storage; import org.apache.hadoop.hdfs.server.namenode.BlocksMap.BlockInfo; /** * * CreateEditsLog Synopsis: CreateEditsLog -f numFiles StartingBlockId * numBlocksPerFile [-r replicafactor] [-d editsLogDirectory] Default * replication factor is 1 Default edits log directory is /tmp/EditsLogOut * * Create a name node's edits log in /tmp/EditsLogOut. The file * /tmp/EditsLogOut/current/edits can be copied to a name node's * dfs.name.dir/current direcotry and the name node can be started as usual. * * The files are created in /createdViaInjectingInEditsLog The file names * contain the starting and ending blockIds; hence once can create multiple * edits logs using this command using non overlapping block ids and feed the * files to a single name node. * * See Also @link #DataNodeCluster for injecting a set of matching blocks * created with this command into a set of simulated data nodes. * */ public class CreateEditsLog { static final String BASE_PATH = "/createdViaInjectingInEditsLog"; static final String EDITS_DIR = "/tmp/EditsLogOut"; static String edits_dir = EDITS_DIR; static final public long BLOCK_GENERATION_STAMP = GenerationStamp.FIRST_VALID_STAMP; static void addFiles(FSEditLog editLog, int numFiles, short replication, int blocksPerFile, long startingBlockId, FileNameGenerator nameGenerator) { PermissionStatus p = new PermissionStatus("joeDoe", "people", new FsPermission((short) 0777)); INodeDirectory dirInode = new INodeDirectory(p, 0L); editLog.logMkDir(BASE_PATH, dirInode); long blockSize = 10; BlockInfo[] blocks = new BlockInfo[blocksPerFile]; for (int iB = 0; iB < blocksPerFile; ++iB) { blocks[iB] = new BlockInfo(new Block(0, blockSize, BLOCK_GENERATION_STAMP), replication); } long currentBlockId = startingBlockId; long bidAtSync = startingBlockId; for (int iF = 0; iF < numFiles; iF++) { for (int iB = 0; iB < blocksPerFile; ++iB) { blocks[iB].setBlockId(currentBlockId++); } try { INodeFileUnderConstruction inode = new INodeFileUnderConstruction( null, replication, 0, blockSize, blocks, p, "", "", null); // Append path to filename with information about blockIDs String path = "_" + iF + "_B" + blocks[0].getBlockId() + "_to_B" + blocks[blocksPerFile - 1].getBlockId() + "_"; String filePath = nameGenerator.getNextFileName(""); filePath = filePath + path; // Log the new sub directory in edits if ((iF % nameGenerator.getFilesPerDirectory()) == 0) { String currentDir = nameGenerator.getCurrentDir(); dirInode = new INodeDirectory(p, 0L); editLog.logMkDir(currentDir, dirInode); } editLog.logOpenFile(filePath, inode); editLog.logCloseFile(filePath, inode); if (currentBlockId - bidAtSync >= 2000) { // sync every 2K // blocks editLog.logSync(); bidAtSync = currentBlockId; } } catch (IOException e) { System.out.println("Creating trascation for file " + iF + " encountered exception " + e); } } System.out.println("Created edits log in directory " + edits_dir); System.out.println(" containing " + numFiles + " File-Creates, each file with " + blocksPerFile + " blocks"); System.out.println(" blocks range: " + startingBlockId + " to " + (currentBlockId - 1)); } static String usage = "Usage: createditlogs " + " -f numFiles startingBlockIds NumBlocksPerFile [-r replicafactor] " + "[-d editsLogDirectory]\n" + " Default replication factor is 1\n" + " Default edits log direcory is " + EDITS_DIR + "\n"; static void printUsageExit() { System.out.println(usage); System.exit(-1); } static void printUsageExit(String err) { System.out.println(err); printUsageExit(); } /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { long startingBlockId = 1; int numFiles = 0; short replication = 1; int numBlocksPerFile = 0; if (args.length == 0) { printUsageExit(); } for (int i = 0; i < args.length; i++) { // parse command line if (args[i].equals("-h")) printUsageExit(); if (args[i].equals("-f")) { if (i + 3 >= args.length || args[i + 1].startsWith("-") || args[i + 2].startsWith("-") || args[i + 3].startsWith("-")) { printUsageExit("Missing num files, starting block and/or number of blocks"); } numFiles = Integer.parseInt(args[++i]); startingBlockId = Integer.parseInt(args[++i]); numBlocksPerFile = Integer.parseInt(args[++i]); if (numFiles <= 0 || numBlocksPerFile <= 0) { printUsageExit("numFiles and numBlocksPerFile most be greater than 0"); } } else if (args[i].equals("-r") || args[i + 1].startsWith("-")) { if (i + 1 >= args.length) { printUsageExit("Missing num files, starting block and/or number of blocks"); } replication = Short.parseShort(args[++i]); } else if (args[i].equals("-d")) { if (i + 1 >= args.length || args[i + 1].startsWith("-")) { printUsageExit("Missing edits logs directory"); } edits_dir = args[++i]; } else { printUsageExit(); } } File editsLogDir = new File(edits_dir); File subStructureDir = new File(edits_dir + "/" + Storage.STORAGE_DIR_CURRENT); if (!editsLogDir.exists()) { if (!editsLogDir.mkdir()) { System.out.println("cannot create " + edits_dir); System.exit(-1); } } if (!subStructureDir.exists()) { if (!subStructureDir.mkdir()) { System.out.println("cannot create subdirs of " + edits_dir); System.exit(-1); } } FSImage fsImage = new FSImage(new File(edits_dir)); FileNameGenerator nameGenerator = new FileNameGenerator(BASE_PATH, 100); FSEditLog editLog = fsImage.getEditLog(); editLog.createEditLogFile(fsImage.getFsEditName()); editLog.open(); addFiles(editLog, numFiles, replication, numBlocksPerFile, startingBlockId, nameGenerator); editLog.logSync(); editLog.close(); } }
shot/hadoop-source-reading
src/test/org/apache/hadoop/hdfs/server/namenode/CreateEditsLog.java
Java
apache-2.0
7,159
/* * 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.datapipeline.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.datapipeline.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import static com.fasterxml.jackson.core.JsonToken.*; /** * DeactivatePipelineResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeactivatePipelineResultJsonUnmarshaller implements Unmarshaller<DeactivatePipelineResult, JsonUnmarshallerContext> { public DeactivatePipelineResult unmarshall(JsonUnmarshallerContext context) throws Exception { DeactivatePipelineResult deactivatePipelineResult = new DeactivatePipelineResult(); return deactivatePipelineResult; } private static DeactivatePipelineResultJsonUnmarshaller instance; public static DeactivatePipelineResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DeactivatePipelineResultJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-datapipeline/src/main/java/com/amazonaws/services/datapipeline/model/transform/DeactivatePipelineResultJsonUnmarshaller.java
Java
apache-2.0
1,666
/** * Copyright 2015 Netflix, 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.spectator.placeholders; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Tag; import java.util.Map; /** * An extension of the {@link Id} interface that allows the list of tag names attached * to the Id to be declared in advance of the use of the metric. This can be used to * provide a default value for a tag or to use a TagFactory implementation that uses * context available in the execution environment to compute the value of the tag. */ public interface PlaceholderId { /** Description of the measurement that is being collected. */ String name(); /** New id with an additional tag value. */ PlaceholderId withTag(String k, String v); /** New id with an additional tag value. */ PlaceholderId withTag(Tag t); /** New id with additional tag values. */ PlaceholderId withTags(Iterable<Tag> tags); /** New id with additional tag values. */ PlaceholderId withTags(Map<String, String> tags); /** * New id with an additional tag factory. * @param factory * the factory to use to generate the values for the tag */ PlaceholderId withTagFactory(TagFactory factory); /** * New id with additional tag factories. * @param factories * a collection of factories for producing values for the tags */ PlaceholderId withTagFactories(Iterable<TagFactory> factories); /** * Invokes each of the associated tag factories to produce a Id based on the * runtime context available when this method is invoked. If an associated * TagFactory produces a non-null Tag, then the returned Id will have that * Tag associated with it. * * @return an Id that has the same name as this id and the resolved tag values attached */ Id resolveToId(); }
pstout/spectator
spectator-ext-placeholders/src/main/java/com/netflix/spectator/placeholders/PlaceholderId.java
Java
apache-2.0
2,369
/* * Copyright 2014 - 2016 Real Logic 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 io.aeron.driver; import io.aeron.driver.media.ReceiveChannelEndpoint; import io.aeron.driver.media.UdpChannel; import org.agrona.concurrent.status.ReadablePosition; import java.util.IdentityHashMap; import java.util.Map; /** * Subscription registration from a client used for liveness tracking */ public class SubscriptionLink implements DriverManagedResource { private final long registrationId; private final long clientLivenessTimeoutNs; private final int streamId; private final boolean isReliable; private final String channelUri; private final ReceiveChannelEndpoint channelEndpoint; private final AeronClient aeronClient; private final Map<PublicationImage, ReadablePosition> positionByImageMap = new IdentityHashMap<>(); private final IpcPublication ipcPublication; private final ReadablePosition ipcPublicationSubscriberPosition; private final UdpChannel spiedChannel; private NetworkPublication spiedPublication = null; private ReadablePosition spiedPosition = null; private boolean reachedEndOfLife = false; public SubscriptionLink( final long registrationId, final ReceiveChannelEndpoint channelEndpoint, final int streamId, final String channelUri, final AeronClient aeronClient, final long clientLivenessTimeoutNs, final boolean isReliable) { this.registrationId = registrationId; this.channelEndpoint = channelEndpoint; this.streamId = streamId; this.channelUri = channelUri; this.aeronClient = aeronClient; this.ipcPublication = null; this.ipcPublicationSubscriberPosition = null; this.spiedChannel = null; this.clientLivenessTimeoutNs = clientLivenessTimeoutNs; this.isReliable = isReliable; } public SubscriptionLink( final long registrationId, final int streamId, final String channelUri, final IpcPublication ipcPublication, final ReadablePosition subscriberPosition, final AeronClient aeronClient, final long clientLivenessTimeoutNs) { this.registrationId = registrationId; this.channelEndpoint = null; // will prevent matches between PublicationImages and IpcPublications this.streamId = streamId; this.channelUri = channelUri; this.aeronClient = aeronClient; this.ipcPublication = ipcPublication; ipcPublication.incRef(); this.ipcPublicationSubscriberPosition = subscriberPosition; this.spiedChannel = null; this.clientLivenessTimeoutNs = clientLivenessTimeoutNs; this.isReliable = true; } public SubscriptionLink( final long registrationId, final UdpChannel spiedChannel, final int streamId, final String channelUri, final AeronClient aeronClient, final long clientLivenessTimeoutNs) { this.registrationId = registrationId; this.channelEndpoint = null; this.streamId = streamId; this.channelUri = channelUri; this.aeronClient = aeronClient; this.ipcPublication = null; this.ipcPublicationSubscriberPosition = null; this.spiedChannel = spiedChannel; this.clientLivenessTimeoutNs = clientLivenessTimeoutNs; this.isReliable = true; } public long registrationId() { return registrationId; } public ReceiveChannelEndpoint channelEndpoint() { return channelEndpoint; } public int streamId() { return streamId; } public String channelUri() { return channelUri; } public boolean isReliable() { return isReliable; } public boolean matches(final ReceiveChannelEndpoint channelEndpoint, final int streamId) { return channelEndpoint == this.channelEndpoint && streamId == this.streamId; } public boolean matches(final NetworkPublication publication) { boolean result = false; if (null != spiedChannel) { result = streamId == publication.streamId() && publication.sendChannelEndpoint().udpChannel().canonicalForm().equals(spiedChannel.canonicalForm()); } return result; } public void addImage(final PublicationImage image, final ReadablePosition position) { positionByImageMap.put(image, position); } public void removeImage(final PublicationImage image) { positionByImageMap.remove(image); } public void addSpiedPublication(final NetworkPublication publication, final ReadablePosition position) { spiedPublication = publication; spiedPosition = position; } public void removeSpiedPublication() { spiedPublication = null; spiedPosition = null; } public void close() { positionByImageMap.forEach(PublicationImage::removeSubscriber); if (null != ipcPublication) { ipcPublication.removeSubscription(ipcPublicationSubscriberPosition); ipcPublication.decRef(); } else if (null != spiedPublication) { spiedPublication.removeSpyPosition(spiedPosition); } } public void onTimeEvent(final long time, final DriverConductor conductor) { if (time > (aeronClient.timeOfLastKeepalive() + clientLivenessTimeoutNs)) { reachedEndOfLife = true; conductor.cleanupSubscriptionLink(SubscriptionLink.this); } } public boolean hasReachedEndOfLife() { return reachedEndOfLife; } public void timeOfLastStateChange(final long time) { // not set this way } public long timeOfLastStateChange() { return aeronClient.timeOfLastKeepalive(); } public void delete() { close(); } }
tbrooks8/Aeron
aeron-driver/src/main/java/io/aeron/driver/SubscriptionLink.java
Java
apache-2.0
6,539
/* */ package com.webbuilder.interact; /* */ /* */ import com.webbuilder.controls.Query; /* */ import com.webbuilder.utils.CompressUtil; /* */ import com.webbuilder.utils.DateUtil; /* */ import com.webbuilder.utils.DbUtil; /* */ import com.webbuilder.utils.FileUtil; /* */ import com.webbuilder.utils.StringUtil; /* */ import com.webbuilder.utils.SysUtil; /* */ import com.webbuilder.utils.WebUtil; /* */ import com.webbuilder.utils.XMLParser; /* */ import java.awt.Color; /* */ import java.awt.Graphics; /* */ import java.awt.image.BufferedImage; /* */ import java.io.File; /* */ import java.io.FileInputStream; /* */ import java.io.InputStream; /* */ import java.io.PrintWriter; /* */ import java.sql.Connection; /* */ import java.sql.PreparedStatement; /* */ import java.sql.Timestamp; /* */ import java.util.Calendar; /* */ import java.util.Date; /* */ import java.util.HashMap; /* */ import java.util.HashSet; /* */ import java.util.Iterator; /* */ import javax.imageio.ImageIO; /* */ import javax.servlet.http.HttpServletRequest; /* */ import javax.servlet.http.HttpServletResponse; /* */ import javax.servlet.http.HttpSession; /* */ import javax.swing.Icon; /* */ import javax.swing.filechooser.FileSystemView; /* */ import org.dom4j.Attribute; /* */ import org.dom4j.Document; /* */ import org.dom4j.Element; /* */ import org.json.JSONArray; /* */ import org.json.JSONObject; /* */ /* */ public class Explorer /* */ { /* */ public void getRcvFilter(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 42 */ String find = StringUtil.fetchString(request, "findCombo"); /* */ /* 44 */ if (!StringUtil.isEmpty(find)) { /* 45 */ request.setAttribute("findValue", "%" + find + "%"); /* 46 */ String sql = " and WB_NAME like {?findValue?}"; /* 47 */ request.setAttribute("whereSql", sql); /* */ } else { /* 49 */ DbUtil.getDefaultWhere(request, response, "WB_DATE,WB_CODE=b", /* 50 */ false); /* */ } /* */ } /* */ /* */ public void sendFile(HttpServletRequest request, HttpServletResponse response) throws Exception { /* 55 */ Connection conn = DbUtil.fetchConnection(request, request.getAttribute( /* 56 */ "sys.jndi").toString()); /* 57 */ String depts = request.getAttribute("WB_RDEPT").toString(); /* 58 */ String roles = request.getAttribute("WB_RROLE").toString(); /* 59 */ String users = request.getAttribute("WB_RUSER").toString(); /* 60 */ String scope = request.getAttribute("sys.scope").toString(); /* 61 */ String dbType = request.getAttribute("sys.dbType").toString(); /* 62 */ HashSet userList = new HashSet(); /* */ /* 64 */ userList = DbUtil.getUserList(conn, dbType, scope, depts, roles, users); /* 65 */ conn.setAutoCommit(false); /* */ try { /* 67 */ PreparedStatement stm = null; /* 68 */ int k = 0; int l = userList.size(); /* 69 */ boolean commitAll = false; boolean added = false; /* 70 */ stm = conn /* 71 */ .prepareStatement("insert into WB_FILERECEIVE values(?,?,?,?,null)"); /* */ try { /* 73 */ stm.setString(1, scope); /* 74 */ stm.setTimestamp(2, /* 75 */ new Timestamp(DateUtil.stringToStdDate( /* 75 */ request.getAttribute("sys.now").toString()).getTime())); /* 76 */ stm.setString(3, request.getAttribute("sys.code").toString()); /* 77 */ while ( userList.iterator().hasNext()) { String s=userList.iterator().next().toString(); /* 78 */ k++; /* 79 */ stm.setString(4, s); /* 80 */ stm.addBatch(); /* 81 */ if (!added) /* 82 */ added = true; /* 83 */ if (k % 1000 == 0) { /* 84 */ if (k == l) /* 85 */ commitAll = true; /* 86 */ stm.executeBatch(); /* */ } /* */ } /* 89 */ if ((added) && (!commitAll)) /* 90 */ stm.executeBatch(); /* */ } finally { /* 92 */ DbUtil.closeStatement(stm); /* */ } /* 94 */ conn.commit(); /* */ } catch (Exception e) { /* 96 */ conn.rollback(); /* 97 */ throw new Exception(e); /* */ } finally { /* 99 */ conn.setAutoCommit(true); /* */ } /* */ } /* */ /* */ private String createUserDir(String root) throws Exception { /* 104 */ Date dt = new Date(); /* 105 */ String y = "y" + Integer.toString(DateUtil.yearOf(dt)); /* 106 */ String d = "d" + Integer.toString(DateUtil.dayOfYear(dt)); /* 107 */ String h = "h" + Integer.toString(DateUtil.hourOfDay(dt)); /* 108 */ Calendar cal = Calendar.getInstance(); /* 109 */ cal.setTime(dt); /* 110 */ int m = cal.get(12); /* 111 */ h = h + "m" + Integer.toString(m / 10); /* 112 */ String rel = y + "/" + d + "/" + h + "/"; /* 113 */ File file = FileUtil.getUniqueFile(new File(root + "/" + rel + "s" + /* 114 */ DateUtil.formatDate(dt, "ssSSS"))); /* 115 */ rel = rel + file.getName(); /* 116 */ File dir = new File(root + "/" + rel); /* 117 */ if (!dir.mkdirs()) /* 118 */ throw new Exception("不能创建目录。"); /* 119 */ return rel; /* */ } /* */ /* */ public void createPubDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 124 */ String root = request.getAttribute("sys.path").toString() + /* 125 */ "WEB-INF/myfile"; /* 126 */ String scope = request.getAttribute("sys.scope").toString(); /* */ /* 128 */ String sysPubDir = FileUtil.fetchPubDir(root, scope); /* 129 */ request.setAttribute("sysPubDir", sysPubDir); /* */ } /* */ /* */ public void createUserDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 134 */ String userPath = request.getAttribute("sys.rootpath").toString(); /* */ /* 136 */ if (StringUtil.isEmpty(userPath)) { /* 137 */ String root = request.getAttribute("sys.path").toString() + /* 138 */ "WEB-INF/myfile"; /* 139 */ String path = createUserDir(root); /* 140 */ Query query = new Query(); /* 141 */ query.setRequest(request); /* 142 */ query.type = "update"; /* 143 */ request.setAttribute("rootPath", path); /* 144 */ query.sql = "update WB_USER set ROOT_PATH={?rootPath?} where USERNAME={?sys.user?}"; /* 145 */ query.jndi = StringUtil.fetchString(request, "sys.jndi"); /* 146 */ query.setName("query.updateUser"); /* 147 */ query.create(); /* 148 */ request.getSession(false).setAttribute("sys.rootpath", /* 149 */ root + "/" + path); /* 150 */ request.setAttribute("sys.rootpath", root + "/" + path); /* */ } else { /* 152 */ File dir = new File(userPath); /* 153 */ if ((!dir.exists()) && (!dir.mkdirs())) /* 154 */ throw new Exception("不能创建用户目录。"); /* */ } /* */ } /* */ /* */ public void setOrder(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 160 */ JSONArray files = new JSONArray(request.getParameter("orderTree")); /* 161 */ int j = files.length(); /* 162 */ if (j == 0) /* 163 */ return; /* 164 */ File dir = new File(request.getParameter("orderDir")); /* */ /* 168 */ HashMap hashMap = new HashMap(); /* */ /* 170 */ XMLParser mapXml = new XMLParser(FileUtil.getUserIndex(dir, request.getAttribute( /* 171 */ "sys.scope").toString(), false)); /* 172 */ Element root = mapXml.document.getRootElement(); /* 173 */ Iterator iterator = root.elementIterator(); /* 174 */ while (iterator.hasNext()) { /* 175 */ Element el = (Element)iterator.next(); /* 176 */ hashMap.put(el.attribute("name").getText(), el); /* */ } /* 178 */ for (int i = 0; i < j; i++) { /* 179 */ String name = new JSONObject(files.getString(i)).getString("filename"); /* 180 */ Element el = (Element)hashMap.get(name); /* 181 */ if (el != null) { /* 182 */ root.add(el.createCopy()); /* 183 */ root.remove(el); /* */ } /* */ } /* 186 */ mapXml.save(); /* */ } /* */ /* */ public void getOrder(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 195 */ StringBuilder buf = new StringBuilder(); /* 196 */ boolean added = false; /* */ /* 198 */ buf.append("["); /* 199 */ File file = new File(request.getParameter("dir")); /* 200 */ File mapFile = FileUtil.getUserIndex(file, request.getAttribute("sys.scope") /* 201 */ .toString(), false); /* 202 */ if (mapFile.exists()) { /* 203 */ XMLParser mapXml = new XMLParser(mapFile); /* 204 */ Element el = mapXml.document.getRootElement(); /* 205 */ if (el != null) { /* 206 */ Iterator iterator = el.elementIterator(); /* 207 */ while (iterator.hasNext()) { /* 208 */ el = (Element)iterator.next(); /* 209 */ if (added) /* 210 */ buf.append(","); /* */ else /* 212 */ added = true; /* 213 */ buf.append("{text:\""); /* 214 */ String text = StringUtil.replaceParameters(request, el.attribute( /* 215 */ "caption").getValue()); /* 216 */ String name = el.attribute("name").getValue(); /* 217 */ if (StringUtil.isEmpty(text)) /* 218 */ text = name; /* 219 */ buf.append(StringUtil.toExpress(text)); /* 220 */ text = el.attribute("icon").getValue(); /* 221 */ if (!StringUtil.isEmpty(text)) { /* 222 */ buf.append("\",iconCls:\""); /* 223 */ buf.append(text); /* */ } /* 225 */ buf.append("\",filename:\""); /* 226 */ buf.append(name); /* 227 */ buf.append("\",leaf:true}"); /* */ } /* */ } /* */ } /* 231 */ buf.append("]"); /* 232 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getProperty(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 243 */ File file = new File(request.getParameter("fileName")); /* 244 */ File mapFile = FileUtil.getUserIndex(file.getParentFile(), request /* 245 */ .getAttribute("sys.scope").toString(), false); /* 246 */ if (mapFile.exists()) { /* 247 */ String fileName = file.getName(); /* 248 */ XMLParser mapXml = new XMLParser(mapFile); /* 249 */ Element el = mapXml.document.getRootElement(); /* 250 */ if (el != null) { /* 251 */ Iterator iterator = el.elementIterator(); /* 252 */ while (iterator.hasNext()) { /* 253 */ el = (Element)iterator.next(); /* 254 */ if (!StringUtil.isSame(el.attribute("name").getText(), /* 255 */ fileName)) continue; /* 256 */ StringBuilder buf = new StringBuilder(); /* 257 */ buf.append("{fileCaption:\""); /* 258 */ Attribute attr = el.attribute("caption"); /* 259 */ if (attr != null) /* 260 */ buf.append(StringUtil.toExpress(attr.getText())); /* 261 */ buf.append("\",fileRole:\""); /* 262 */ attr = el.attribute("role"); /* 263 */ if (attr != null) /* 264 */ buf.append(StringUtil.toExpress(attr.getText())); /* 265 */ buf.append("\",fileIcon:\""); /* 266 */ attr = el.attribute("icon"); /* 267 */ if (attr != null) /* 268 */ buf.append(attr.getText()); /* 269 */ buf.append("\",fileHint:\""); /* 270 */ attr = el.attribute("hint"); /* 271 */ if (attr != null) /* 272 */ buf.append(attr.getText()); /* 273 */ buf.append("\",fileHidden:\""); /* 274 */ attr = el.attribute("hidden"); /* 275 */ if (attr != null) /* 276 */ buf.append(StringUtil.toExpress(attr.getText())); /* */ else /* 278 */ buf.append("0"); /* 279 */ buf.append("\"}"); /* 280 */ response.getWriter().print(buf); /* 281 */ return; /* */ } /* */ } /* */ } /* */ } /* */ /* */ public void setPropertyCopy(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 290 */ innerSetProperty(request, response, true); /* */ } /* */ /* */ public void setProperty(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 295 */ innerSetProperty(request, response, false); /* */ } /* */ /* */ private void innerSetProperty(HttpServletRequest request, HttpServletResponse response, boolean createCopy) /* */ throws Exception /* */ { /* 304 */ String caption = request.getParameter("fileCaption"); /* 305 */ String role = request.getParameter("fileRole"); /* 306 */ String icon = request.getParameter("fileIcon"); /* 307 */ String hint = request.getParameter("fileHint"); /* 308 */ String hidden = request.getParameter("fileHidden"); /* 309 */ JSONArray files = new JSONArray(request.getParameter("setFile")); /* 310 */ HashMap map = new HashMap(); /* */ /* 313 */ File file = new File(files.getString(0)); /* 314 */ File dir = file.getParentFile(); /* 315 */ XMLParser mapXml = new XMLParser(FileUtil.getUserIndex(dir, request.getAttribute( /* 316 */ "sys.scope").toString(), createCopy)); /* 317 */ Element root = mapXml.document.getRootElement(); /* 318 */ if (root != null) { /* 319 */ Iterator iterator = root.elementIterator(); /* 320 */ while (iterator.hasNext()) { /* 321 */ Element el = (Element)iterator.next(); /* 322 */ String name = el.attribute("name").getText(); /* 323 */ file = new File(dir, name); /* 324 */ if ((!file.exists()) || (map.containsKey(name))) /* 325 */ root.remove(el); /* */ else /* 327 */ map.put(name, el); /* */ } /* */ } else { /* 330 */ root = mapXml.document.addElement("map"); /* 331 */ }int j = files.length(); /* 332 */ for (int i = 0; i < j; i++) { /* 333 */ String name = FileUtil.extractFileName(files.getString(i)); /* 334 */ Element el = (Element)map.get(name); /* 335 */ if (el == null) { /* 336 */ el = root.addElement("file"); /* 337 */ el.addAttribute("name", name); /* 338 */ el.addAttribute("caption", caption); /* 339 */ el.addAttribute("role", role); /* 340 */ el.addAttribute("icon", icon); /* 341 */ el.addAttribute("hint", hint); /* 342 */ el.addAttribute("hidden", hidden); /* */ } else { /* 344 */ el.attribute("name").setText(name); /* 345 */ el.attribute("caption").setText(caption); /* 346 */ el.attribute("role").setText(role); /* 347 */ el.attribute("icon").setText(icon); /* 348 */ el.attribute("hint").setText(hint); /* 349 */ el.attribute("hidden").setText(hidden); /* */ } /* */ } /* 352 */ mapXml.save(); /* */ } /* */ /* */ public void importFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 357 */ String importDir = request.getAttribute("importDir").toString(); /* 358 */ FileUtil.checkRight(request, new File(importDir)); /* 359 */ InputStream stream = (InputStream)request.getAttribute("importFile"); /* 360 */ String fn = request.getAttribute("importFile__file").toString(); /* */ /* 362 */ if (StringUtil.isEqual(request.getAttribute("importType").toString(), /* 363 */ "1")) { /* 364 */ if (StringUtil.isSame(FileUtil.extractFileExt(fn), "zip")) /* 365 */ CompressUtil.unzip(stream, new File(importDir), /* 366 */ (String)request.getAttribute("sys.fileCharset")); /* */ else /* 368 */ throw new Exception("请选择一个zip格式的压缩文件。"); /* */ } /* 370 */ else FileUtil.saveInputStreamToFile(stream, new File(importDir, fn)); /* */ } /* */ /* */ public void exportFile(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 375 */ String[] list = StringUtil.split(request.getParameter("exportFiles"), /* 376 */ "|"); /* 378 */ int i = 0; int j = list.length; /* */ /* 380 */ File[] files = new File[j]; /* */ /* 382 */ for (i = 0; i < j; i++) { /* 383 */ WebUtil.recordLog(request, "explorer导出:" + list[i], 1); /* 384 */ files[i] = new File(list[i]); /* 385 */ FileUtil.checkRight(request, files[i]); /* */ } /* */ String fileName; /* 387 */ if (j == 1) { /* 388 */ fileName = FileUtil.extractFileNameNoExt(files[0].getName()); /* */ } else { /* 390 */ File parentFile = files[0].getParentFile(); /* 391 */ fileName = ""; /* 392 */ if (parentFile != null) /* 393 */ fileName = FileUtil.extractFileNameNoExt(parentFile.getName()); /* 394 */ if (StringUtil.isEmpty(fileName)) /* 395 */ fileName = "data"; /* */ } /* 397 */ boolean useZip = (StringUtil.isEqual(request.getParameter("exportType"), "1")) || /* 398 */ (j > 1) || (files[0].isDirectory()); /* 399 */ response.reset(); /* 400 */ if (!useZip) { /* 401 */ response.setHeader("content-length", Long.toString(files[0] /* 402 */ .length())); /* 403 */ fileName = files[0].getName(); /* */ } else { /* 405 */ fileName = fileName + ".zip"; /* 406 */ }response.setHeader("content-type", "application/force-download"); /* 407 */ String charset = (String)request.getAttribute("sys.fileCharset"); /* 408 */ response.setHeader("content-disposition", "attachment;filename=" + /* 409 */ WebUtil.getFileName(fileName, charset)); /* 410 */ if (useZip) { /* 411 */ CompressUtil.zip(files, response.getOutputStream(), /* 412 */ (String)request.getAttribute("sys.fileCharset")); /* */ } else { /* 414 */ FileInputStream inputStream = new FileInputStream(files[0]); /* 415 */ SysUtil.inputStreamToOutputStream(inputStream, response /* 416 */ .getOutputStream()); /* 417 */ inputStream.close(); /* */ } /* */ } /* */ /* */ public void exportFile2(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* */ String root = request.getAttribute("sys.path").toString() + "WEB-INF/myfile.doc"; /* 378 */ int i = 0; int j = 1; /* */ /* 380 */ File[] files = new File[j]; /* */ /* 382 */ /* 383 */ WebUtil.recordLog(request, "explorer导出:" + root, 1); /* 384 */ files[i] = new File(root); /* 385 */ FileUtil.checkRight(request, files[i]); /* */ /* */ String fileName; /* 387 */ if (j == 1) { /* 388 */ fileName = FileUtil.extractFileNameNoExt(files[0].getName()); /* */ } else { /* 390 */ File parentFile = files[0].getParentFile(); /* 391 */ fileName = ""; /* 392 */ if (parentFile != null) /* 393 */ fileName = FileUtil.extractFileNameNoExt(parentFile.getName()); /* 394 */ if (StringUtil.isEmpty(fileName)) /* 395 */ fileName = "data"; /* */ } /* 397 */ boolean useZip = (StringUtil.isEqual(request.getParameter("exportType"), "1")) || /* 398 */ (j > 1) || (files[0].isDirectory()); /* 399 */ response.reset(); /* 400 */ if (!useZip) { /* 401 */ response.setHeader("content-length", Long.toString(files[0] /* 402 */ .length())); /* 403 */ fileName = files[0].getName(); /* */ } else { /* 405 */ fileName = fileName + ".zip"; /* 406 */ }response.setHeader("content-type", "application/force-download"); /* 407 */ String charset = (String)request.getAttribute("sys.fileCharset"); /* 408 */ response.setHeader("content-disposition", "attachment;filename=" + /* 409 */ WebUtil.getFileName(fileName, charset)); /* 410 */ if (useZip) { /* 411 */ CompressUtil.zip(files, response.getOutputStream(), /* 412 */ (String)request.getAttribute("sys.fileCharset")); /* */ } else { /* 414 */ FileInputStream inputStream = new FileInputStream(files[0]); /* 415 */ SysUtil.inputStreamToOutputStream(inputStream, response /* 416 */ .getOutputStream()); /* 417 */ inputStream.close(); /* */ } /* */ } /* */ /* */ public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 423 */ String fileName = request.getParameter("file"); /* */ try { /* 425 */ Runtime.getRuntime().exec(fileName); /* */ } catch (Exception e) { /* 427 */ throw new Exception("执行 \"" + FileUtil.extractFileName(fileName) + /* 428 */ "\"错误。"); /* */ } /* */ } /* */ /* */ public void openFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 434 */ FileUtil.checkRight(request, new File(request.getParameter("file"))); /* 435 */ String charset = request.getParameter("charset"); /* */ /* 437 */ if (StringUtil.isEmpty(charset)) /* 438 */ charset = (String)request.getAttribute("sys.charset"); /* 439 */ response.getWriter().print( /* 440 */ FileUtil.readText(request.getParameter("file"), charset)); /* */ } /* */ /* */ public void saveFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 445 */ FileUtil.checkRight(request, new File(request.getParameter("file"))); /* 446 */ String charset = request.getParameter("charset"); /* 447 */ if (StringUtil.isEmpty(charset)) /* 448 */ charset = (String)request.getAttribute("sys.charset"); /* 449 */ FileUtil.writeText(request.getParameter("file"), request /* 450 */ .getParameter("text"), charset); /* */ } /* */ /* */ public void deleteFiles(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 457 */ JSONArray files = new JSONArray(request.getParameter("files")); /* 458 */ int j = files.length(); /* */ /* 460 */ for (int i = 0; i < j; i++) { /* 461 */ String fileName = files.getString(i); /* 462 */ File file = new File(fileName); /* 463 */ FileUtil.checkRight(request, file); /* 464 */ WebUtil.recordLog(request, "explorer删除:" + fileName, 1); /* 465 */ if (file.isDirectory()) /* 466 */ FileUtil.deleteFolder(file); /* 467 */ else if (!file.delete()) /* 468 */ throw new Exception("不能删除文件 \"" + file.getName() + "\"。"); /* */ } /* */ } /* */ /* */ public void pasteFiles(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 474 */ String filesParam = request.getParameter("files"); /* 475 */ String dir = request.getParameter("dir") + "/"; /* 476 */ File destFile = new File(dir); /* 477 */ JSONArray files = new JSONArray(filesParam); /* 478 */ boolean isCut = StringUtil.getStringBool(request.getParameter("isCut")); /* 479 */ int j = files.length(); /* */ /* 481 */ for (int i = 0; i < j; i++) { /* 482 */ File file = new File(files.getString(i)); /* 483 */ File dest = new File(dir + file.getName()); /* 484 */ FileUtil.checkRight(request, file); /* 485 */ FileUtil.checkRight(request, dest); /* 486 */ WebUtil.recordLog(request, "explorer贴粘:" + (isCut ? "剪切" : "复制") + /* 487 */ "," + files.getString(i) + "至" + dir, 1); /* 488 */ if (file.isDirectory()) { /* 489 */ if (FileUtil.isSubFolder(file, destFile)) /* 490 */ throw new Exception("不能复制相同的文件夹。"); /* 491 */ FileUtil.copyFolder(file, dest, true, isCut); /* */ } else { /* 493 */ FileUtil.copyFile(file, dest, true, isCut); /* */ } /* */ } /* */ } /* */ /* */ public void rename(HttpServletRequest request, HttpServletResponse response) throws Exception { /* 499 */ String fileName = request.getParameter("fileName"); /* 500 */ String rename = request.getParameter("fileValue"); /* 501 */ File file = new File(fileName); /* 502 */ FileUtil.checkRight(request, file); /* 503 */ if ((rename.indexOf("/") > -1) || /* 504 */ (rename.indexOf("\\") > -1) || /* 505 */ (!file.renameTo( /* 506 */ new File(FileUtil.extractFilePath(fileName) + /* 506 */ rename)))) /* 507 */ throw new Exception("重命名失败。"); /* */ } /* */ /* */ public void newFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 512 */ String name = request.getParameter("fileValue"); /* 513 */ String fileName = request.getParameter("dir") + "/" + name; /* 514 */ String type = request.getParameter("type"); /* */ /* 517 */ File file = new File(fileName); /* 518 */ FileUtil.checkRight(request, file); /* */ boolean flag; /* */ /* 519 */ if (type.equals("dir")) /* 520 */ flag = file.mkdir(); /* */ else /* 522 */ flag = file.createNewFile(); /* 523 */ if (!flag) /* 524 */ throw new Exception("不能创建\"" + name + "\""); /* */ } /* */ /* */ public void getPubDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 529 */ String dir = request.getParameter("dir"); /* 530 */ StringBuilder buf = new StringBuilder(); /* 531 */ String root = request.getAttribute("sys.path").toString() + /* 532 */ "WEB-INF/myfile"; /* 533 */ String scope = request.getAttribute("sys.scope").toString(); /* */ /* 535 */ if (StringUtil.isEmpty(dir)) { /* 536 */ loadPubDir(FileUtil.fetchPubDir(root, scope), buf); /* */ } else { /* 538 */ File fl = new File(dir); /* 539 */ FileUtil.checkRight(request, fl); /* 540 */ File[] files = fl.listFiles(); /* 541 */ FileUtil.sortFiles(files); /* 542 */ loadFilesBuf(files, buf); /* */ } /* 544 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getUserDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 549 */ String dir = request.getParameter("dir"); /* 550 */ StringBuilder buf = new StringBuilder(); /* */ /* 552 */ if (StringUtil.isEmpty(dir)) { /* 553 */ loadUserDir((String)request.getAttribute("sys.rootpath"), buf); /* */ } else { /* 555 */ File fl = new File(dir); /* 556 */ FileUtil.checkRight(request, fl); /* 557 */ File[] files = fl.listFiles(); /* 558 */ FileUtil.sortFiles(files); /* 559 */ loadFilesBuf(files, buf); /* */ } /* 561 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getDir(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 566 */ String dir = request.getParameter("dir"); /* 567 */ boolean appRoot = StringUtil.getStringBool(request /* 568 */ .getParameter("setAppRoot")); /* 569 */ StringBuilder buf = new StringBuilder(); /* */ /* 571 */ if (StringUtil.isEmpty(dir)) { /* 572 */ if ((appRoot) || (!loadFilesBuf(File.listRoots(), buf))) { /* 573 */ buf = new StringBuilder(); /* 574 */ loadAppDir((String)request.getAttribute("sys.path"), buf); /* */ } /* */ } else { /* 577 */ File[] files = new File(dir).listFiles(); /* 578 */ FileUtil.sortFiles(files); /* 579 */ loadFilesBuf(files, buf); /* */ } /* 581 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getFile(HttpServletRequest request, HttpServletResponse response) throws Exception /* */ { /* 586 */ String dir = request.getParameter("dir"); /* 587 */ File dirFile = new File(dir); /* 588 */ FileUtil.checkRight(request, dirFile); /* 589 */ File[] files = dirFile.listFiles(); /* 590 */ if (files == null) { /* 591 */ response.getWriter().print("{total:0,row:[]}"); /* 592 */ return; /* */ } /* 594 */ FileUtil.sortFiles(files); /* 595 */ StringBuilder buf = new StringBuilder(); /* 596 */ FileSystemView fileView = FileSystemView.getFileSystemView(); /* 597 */ boolean isFirst = true; /* 598 */ String start = request.getParameter("start"); /* 599 */ String limit = request.getParameter("limit"); /* 600 */ int count = 0; /* */ int startValue; /* */ /* 602 */ if (start == null) /* 603 */ startValue = 1; /* */ else /* 605 */ startValue = Integer.parseInt(start) + 1; /* */ int limitValue; /* */ /* 606 */ if (limit == null) /* 607 */ limitValue = 2147483647 - startValue; /* */ else /* 609 */ limitValue = Integer.parseInt(limit); /* 610 */ int end = startValue + limitValue - 1; /* 611 */ buf.append("{total:"); /* 612 */ buf.append(files.length); /* 613 */ buf.append(",row:["); /* 614 */ for (File file : files) { /* 615 */ count++; /* 616 */ if (count < startValue) /* */ continue; /* 618 */ if (count > end) /* */ break; /* 620 */ if (isFirst) /* 621 */ isFirst = false; /* */ else /* 623 */ buf.append(","); /* 624 */ boolean isDir = file.isDirectory(); /* 625 */ buf.append("{filename:\""); /* 626 */ if (isDir) /* 627 */ buf.append("0"); /* */ else /* 629 */ buf.append("1"); /* 630 */ String fileName = file.getName(); /* 631 */ buf.append(fileName); /* 632 */ buf.append("\",size:"); /* 633 */ if (isDir) /* 634 */ buf.append(-1); /* */ else /* 636 */ buf.append(file.length()); /* 637 */ buf.append(",file:\""); /* 638 */ buf.append(StringUtil.replace(file.getAbsolutePath(), "\\", "/")); /* 639 */ buf.append("\",type:\""); /* 640 */ if (isDir) { /* 641 */ buf.append("0文件夹"); } else { /* */ String type; /* */ try { type = fileView.getSystemTypeDescription(file); /* */ } /* */ catch (Exception e) /* */ { /* */ /* 646 */ type = null; /* */ } /* 648 */ if (type != null) { /* 649 */ buf.append("1" + StringUtil.toExpress(type)); /* */ } else { /* 651 */ String ext = FileUtil.extractFileExt(fileName); /* 652 */ if (StringUtil.isEmpty(ext)) { /* 653 */ buf.append("1文件"); /* */ } else { /* 655 */ buf.append("1" + ext); /* 656 */ buf.append(" 文件"); /* */ } /* */ } /* */ } /* 660 */ buf.append("\",modifyTime:\""); /* 661 */ buf.append(DateUtil.dateToString(new Date(file.lastModified()))); /* 662 */ buf.append("\"}"); /* */ } /* 664 */ buf.append("]}"); /* 665 */ response.getWriter().print(buf); /* */ } /* */ /* */ public void getIcon(HttpServletRequest request, HttpServletResponse response) /* */ throws Exception /* */ { /* 671 */ File file = new File(new String(request.getParameter("file") /* 671 */ .getBytes("ISO-8859-1"), "utf-8")); FileSystemView fileView = FileSystemView.getFileSystemView(); Icon icon = fileView.getSystemIcon(file); response.reset(); if (icon == null) { response.setContentType("image/gif"); InputStream is = new FileInputStream(request.getAttribute("sys.path") + "webbuilder/images/file.gif"); SysUtil.inputStreamToOutputStream(is, response.getOutputStream()); is.close(); } else { response.setContentType("image/jpeg"); int width = icon.getIconWidth(); int height = icon.getIconHeight(); BufferedImage image = new BufferedImage(width, height, 1); Graphics graphics = image.getGraphics(); graphics.setColor(Color.white); graphics.fillRect(0, 0, width, height); icon.paintIcon(null, graphics, 0, 0); ImageIO.write(image, "jpeg", response.getOutputStream()); graphics.dispose(); /* */ } /* */ } /* */ /* */ private void loadPubDir(String pubDir, StringBuilder buf) /* */ { /* 697 */ buf.append("["); /* 698 */ buf.append("{text:\"公共文件\",dir:\""); /* 699 */ buf.append(StringUtil.toExpress(pubDir)); /* 700 */ buf.append("\"}"); /* 701 */ buf.append("]"); /* */ } /* */ /* */ private void loadUserDir(String userDir, StringBuilder buf) { /* 705 */ buf.append("["); /* 706 */ buf.append("{text:\"我的文件\",dir:\""); /* 707 */ buf.append(StringUtil.toExpress(userDir)); /* 708 */ buf.append("\"}"); /* 709 */ buf.append("]"); /* */ } /* */ /* */ private void loadAppDir(String appDir, StringBuilder buf) { /* 713 */ String s = FileUtil.extractFileDir(appDir); /* 714 */ buf.append("["); /* 715 */ buf.append("{text:\""); /* 716 */ buf.append(StringUtil.toExpress(s)); /* 717 */ buf.append("\",dir:\""); /* 718 */ buf.append(StringUtil.toExpress(s)); /* 719 */ buf.append("\"}"); /* 720 */ buf.append("]"); /* */ } /* */ /* */ private boolean loadFilesBuf(File[] files, StringBuilder buf) { /* 724 */ boolean isOk = false; boolean isFirst = true; /* */ /* 727 */ buf.append("["); /* 728 */ for (File file : files) { /* 729 */ if (file.isDirectory()) { /* 730 */ isOk = true; /* 731 */ if (isFirst) /* 732 */ isFirst = false; /* */ else /* 734 */ buf.append(","); /* 735 */ buf.append("{text:\""); /* 736 */ String name = file.getName(); /* 737 */ String dir = StringUtil.replace(file.getAbsolutePath(), "\\", "/"); /* 738 */ if (StringUtil.isEmpty(name)) /* 739 */ name = FileUtil.extractFileDir(dir); /* 740 */ buf.append(StringUtil.toExpress(name)); /* 741 */ buf.append("\",dir:\""); /* 742 */ buf.append(StringUtil.replace(dir, "\\", "/")); /* 743 */ if (FileUtil.hasSubFile(file, true)) /* 744 */ buf.append("\"}"); /* */ else /* 746 */ buf.append("\",leaf:true,iconCls:\"icon_folder\"}"); /* */ } /* */ } /* 749 */ buf.append("]"); /* 750 */ return isOk; /* */ } /* */ } /* Location: Z:\EXT\WebBuilderServer (1)\WEB-INF\lib\webbuilder2.jar * Qualified Name: com.webbuilder.interact.Explorer * JD-Core Version: 0.6.0 */
fuhongliang/partmanager
src/com/webbuilder/interact/Explorer.java
Java
apache-2.0
36,158
package org.fax4j.spi.email; import java.io.IOException; import javax.mail.Message; import javax.mail.Transport; import org.fax4j.FaxException; import org.fax4j.FaxJob; import org.fax4j.common.Logger; import org.fax4j.spi.AbstractFax4JClientSpi; import org.fax4j.util.Connection; import org.fax4j.util.ReflectionHelper; /** * This class implements the fax client service provider interface.<br> * This parial implementation will invoke the requests by sending emails to a mail server that supports * conversion between email messages and fax messages.<br> * The mail SPI supports persistent connection to enable to reuse the same connection for all fax * operation invocations or to create a new connection for each fax operation invocation.<br> * By default the SPI will create a new connection for each operation invocation however the * <b>org.fax4j.spi.mail.persistent.connection</b> set to true will enable to reuse the connection.<br> * To set the user/password values of the mail connection the following 2 properties must be defined: * <b>org.fax4j.spi.mail.user.name</b> and <b>org.fax4j.spi.mail.password</b><br> * All properties defined in the fax4j configuration will be passed to the mail connection therefore it is * possible to define mail specific properties (see java mail for more info) in the fax4j properties.<br> * Implementing SPI class will have to implement the createXXXFaxJobMessage methods.<br> * These methods will return the message to be sent for that fax job operation. In case the method * returns null, this class will throw an UnsupportedOperationException exception. * <br> * The configuration of the fax4j framework is made up of 3 layers.<br> * The configuration is based on simple properties.<br> * Each layer overrides the lower layers by adding/changing the property values.<br> * The first layer is the internal fax4j.properties file located in the fax4j jar.<br> * This layer contains the preconfigured values for the fax4j framework and can be changed * by updating these properties in the higher layers.<br> * The second layer is the external fax4j.properties file that is located on the classpath.<br> * This file is optional and provides the ability to override the internal configuration for the * entire fax4j framework.<br> * The top most layer is the optional java.util.Properties object provided by the external classes * when creating a new fax client.<br> * These properties enable to override the configuration of the lower 2 layers.<br> * <br> * <b>SPI Status (Draft, Beta, Stable): </b>Stable<br> * <br> * Below table describes the configuration values relevant for this class.<br> * <b>Configuration:</b> * <table summary="" border="1"> * <tr> * <td>Name</td> * <td>Description</td> * <td>Preconfigured Value</td> * <td>Default Value</td> * <td>Mandatory</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.persistent.connection</td> * <td>True to reuse the same mail connection for all fax activites, false to create a * new mail connection for each fax activity.</td> * <td>false</td> * <td>false</td> * <td>false</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.connection.factory.class.name</td> * <td>The connection factory class name</td> * <td>org.fax4j.spi.email.MailConnectionFactoryImpl</td> * <td>org.fax4j.spi.email.MailConnectionFactoryImpl</td> * <td>false</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.user.name</td> * <td>The mail account user name.</td> * <td>none</td> * <td>none</td> * <td>false</td> * </tr> * <tr> * <td>org.fax4j.spi.mail.password</td> * <td>The mail account password.</td> * <td>none</td> * <td>none</td> * <td>false</td> * </tr> * <tr> * <td>javax mail properties</td> * <td>Any of the javax mail properties can be defined in the fax4j properties.<br> * These properties will be passed to the java mail framework.</td> * <td>mail.transport.protocol=smtp<br> * mail.smtp.port=25</td> * <td>none</td> * <td>false</td> * </tr> * </table> * <br> * <b>Limitations:</b><br> * <ul> * <li>This SPI is based on the java mail infrastructure, therefore this SPI cannot * connect to mail servers through a proxy server. * <li>This SPI provides only partial implementation (this is an abstract class). * </ul> * <br> * <b>Dependencies:</b><br> * <ul> * <li>Required jar files: mail-1.4.jar, activation-1.1.jar * </ul> * <br> * * @author Sagie Gur-Ari * @version 1.12 * @since 0.1 */ public abstract class AbstractMailFaxClientSpi extends AbstractFax4JClientSpi { /** * The use persistent connection flag which defines if the SPI will use a new * connection for each request or will reuse the same connection */ private boolean usePersistentConnection; /**The mail connection factory*/ private MailConnectionFactory connectionFactory; /**The mail connection*/ private Connection<MailResourcesHolder> connection; /** * This class holds the SPI configuration constants. * * @author Sagie Gur-Ari * @version 1.03 * @since 0.1 */ public enum FaxClientSpiConfigurationConstants { /** * The use persistent connection property key which defines if the SPI will use a new * connection for each request or will reuse the same connection */ USE_PERSISTENT_CONNECTION_PROPERTY_KEY("org.fax4j.spi.mail.persistent.connection"), /**The connection factory class name*/ CONNECTION_FACTORY_CLASS_NAME_PROPERTY_KEY("org.fax4j.spi.mail.connection.factory.class.name"), /**The user name used to connect to the mail server*/ USER_NAME_PROPERTY_KEY("org.fax4j.spi.mail.user.name"), /**The password used to connect to the mail server*/ PASSWORD_PROPERTY_KEY("org.fax4j.spi.mail.password"); /**The string value*/ private String value; /** * This is the class constructor. * * @param value * The string value */ private FaxClientSpiConfigurationConstants(String value) { this.value=value; } /** * This function returns the string value. * * @return The string value */ @Override public final String toString() { return this.value; } } /** * This is the default constructor. */ public AbstractMailFaxClientSpi() { super(); } /** * This function initializes the fax client SPI. */ @Override protected void initializeImpl() { //get logger Logger logger=this.getLogger(); //get use persistent connection value this.usePersistentConnection=Boolean.parseBoolean(this.getConfigurationValue(FaxClientSpiConfigurationConstants.USE_PERSISTENT_CONNECTION_PROPERTY_KEY)); logger.logDebug(new Object[]{"Using persistent connection: ",String.valueOf(this.usePersistentConnection)},null); //setup connection factory String className=this.getConfigurationValue(FaxClientSpiConfigurationConstants.CONNECTION_FACTORY_CLASS_NAME_PROPERTY_KEY); this.connectionFactory=this.createMailConnectionFactoryImpl(className); if(this.connectionFactory==null) { throw new FaxException("Mail connection factory is not available."); } } /** * Creates and returns the mail connection factory. * * @param className * The connection factory class name * @return The mail connection factory */ protected final MailConnectionFactory createMailConnectionFactoryImpl(String className) { String factoryClassName=className; if(factoryClassName==null) { factoryClassName=MailConnectionFactoryImpl.class.getName(); } //create new instance MailConnectionFactory factory=(MailConnectionFactory)ReflectionHelper.createInstance(factoryClassName); //initialize factory.initialize(this); return factory; } /** * Releases the connection if open. * * @throws Throwable * Any throwable */ @Override protected void finalize() throws Throwable { //get reference Connection<MailResourcesHolder> mailConnection=this.connection; //release connection this.closeMailConnection(mailConnection); super.finalize(); } /** * Creates and returns the mail connection to be used to send the fax * via mail. * * @return The mail connection */ protected Connection<MailResourcesHolder> createMailConnection() { //create new connection Connection<MailResourcesHolder> mailConnection=this.connectionFactory.createConnection(); //log debug Logger logger=this.getLogger(); logger.logInfo(new Object[]{"Created mail connection."},null); return mailConnection; } /** * This function closes the provided mail connection. * * @param mailConnection * The mail connection to close * @throws IOException * Never thrown */ protected void closeMailConnection(Connection<MailResourcesHolder> mailConnection) throws IOException { if(mailConnection!=null) { //get logger Logger logger=this.getLogger(); //release connection logger.logInfo(new Object[]{"Closing mail connection."},null); mailConnection.close(); } } /** * Returns the mail connection to be used to send the fax * via mail. * * @return The mail connection */ protected Connection<MailResourcesHolder> getMailConnection() { Connection<MailResourcesHolder> mailConnection=null; if(this.usePersistentConnection) { synchronized(this) { if(this.connection==null) { //create new connection this.connection=this.createMailConnection(); } } //get connection mailConnection=this.connection; } else { //create new connection mailConnection=this.createMailConnection(); } return mailConnection; } /** * This function will send the mail message. * * @param faxJob * The fax job object containing the needed information * @param mailConnection * The mail connection (will be released if not persistent) * @param message * The message to send */ protected void sendMail(FaxJob faxJob,Connection<MailResourcesHolder> mailConnection,Message message) { if(message==null) { this.throwUnsupportedException(); } else { //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //get transport Transport transport=mailResourcesHolder.getTransport(); try { //send message message.saveChanges(); if(transport==null) { Transport.send(message,message.getAllRecipients()); } else { transport.sendMessage(message,message.getAllRecipients()); } } catch(Throwable throwable) { throw new FaxException("Unable to send message.",throwable); } finally { if(!this.usePersistentConnection) { try { //close connection this.closeMailConnection(mailConnection); } catch(Exception exception) { //log error Logger logger=this.getLogger(); logger.logInfo(new Object[]{"Error while releasing mail connection."},exception); } } } } } /** * This function will submit a new fax job.<br> * The fax job ID may be populated by this method in the provided * fax job object. * * @param faxJob * The fax job object containing the needed information */ @Override protected void submitFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createSubmitFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will suspend an existing fax job. * * @param faxJob * The fax job object containing the needed information */ @Override protected void suspendFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createSuspendFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will resume an existing fax job. * * @param faxJob * The fax job object containing the needed information */ @Override protected void resumeFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createResumeFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will cancel an existing fax job. * * @param faxJob * The fax job object containing the needed information */ @Override protected void cancelFaxJobImpl(FaxJob faxJob) { //get connection Connection<MailResourcesHolder> mailConnection=this.getMailConnection(); //get holder MailResourcesHolder mailResourcesHolder=mailConnection.getResource(); //create message Message message=this.createCancelFaxJobMessage(faxJob,mailResourcesHolder); //send message this.sendMail(faxJob,mailConnection,message); } /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createSubmitFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createSuspendFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createResumeFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); /** * This function will create the message used to invoke the fax * job action.<br> * If this method returns null, the SPI will throw an UnsupportedOperationException. * * @param faxJob * The fax job object containing the needed information * @param mailResourcesHolder * The mail resources holder * @return The message to send (if null, the SPI will throw an UnsupportedOperationException) */ protected abstract Message createCancelFaxJobMessage(FaxJob faxJob,MailResourcesHolder mailResourcesHolder); }
ZhernakovMikhail/fax4j
src/main/java/org/fax4j/spi/email/AbstractMailFaxClientSpi.java
Java
apache-2.0
15,447
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_1435 { }
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_1435.java
Java
apache-2.0
151
/* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.test.internal.engine.messageinterpolation; import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertThat; import static org.hibernate.validator.testutil.ConstraintViolationAssert.violationOf; import static org.testng.Assert.fail; import java.util.Enumeration; import java.util.Locale; import java.util.ResourceBundle; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.MessageInterpolator; import javax.validation.Validator; import javax.validation.ValidatorFactory; import javax.validation.constraints.Max; import org.hibernate.validator.HibernateValidatorConfiguration; import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator; import org.hibernate.validator.spi.resourceloading.ResourceBundleLocator; import org.hibernate.validator.testutil.TestForIssue; import org.hibernate.validator.testutils.ValidatorUtil; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * @author Hardy Ferentschik */ @TestForIssue(jiraKey = "HV-798") public class EscapedInterpolationVariableTest { private Validator validator; @BeforeTest public void setUp() { MessageInterpolator interpolator = new ResourceBundleMessageInterpolator( new ResourceBundleLocator() { @Override public ResourceBundle getResourceBundle(Locale locale) { return new ResourceBundle() { @Override protected Object handleGetObject(String key) { if ( "key-1".equals( key ) ) { return "\\{escapedParameterKey\\}"; } else if ( "key-2".equals( key ) ) { // since {} are unbalanced the original key (key-2) should be returned from the interpolation return "{escapedParameterKey\\}"; } else if ( "key-3".equals( key ) ) { // since {} are unbalanced the original key (key-3) should be returned from the interpolation return "\\{escapedParameterKey}"; } else if ( "key-4".equals( key ) ) { return "foo"; } else { fail( "Unexpected key: " + key ); } return null; } @Override public Enumeration<String> getKeys() { throw new UnsupportedOperationException(); } }; } }, false ); HibernateValidatorConfiguration config = ValidatorUtil.getConfiguration(); ValidatorFactory factory = config.messageInterpolator( interpolator ).buildValidatorFactory(); validator = factory.getValidator(); } @Test public void testEscapedOpeningAndClosingBrace() throws Exception { Set<ConstraintViolation<A>> constraintViolations = validator.validate( new A() ); assertThat( constraintViolations ).containsOnlyViolations( violationOf( Max.class ).withMessage( "{escapedParameterKey}" ) ); } @Test public void testEscapedClosingBrace() throws Exception { Set<ConstraintViolation<B>> constraintViolations = validator.validate( new B() ); assertThat( constraintViolations ).containsOnlyViolations( violationOf( Max.class ).withMessage( "{key-2}" ) ); } @Test public void testEscapedOpenBrace() throws Exception { Set<ConstraintViolation<C>> constraintViolations = validator.validate( new C() ); assertThat( constraintViolations ).containsOnlyViolations( violationOf( Max.class ).withMessage( "{key-3}" ) ); } @Test public void testMessageStaysUnchangedDueToSingleCurlyBrace() throws Exception { Set<ConstraintViolation<D>> constraintViolations = validator.validate( new D() ); assertThat( constraintViolations ).containsOnlyViolations( violationOf( Max.class ).withMessage( "{key-4} {" ) ); } private class A { @Max(value = 1, message = "{key-1}") private int a = 2; } private class B { @Max(value = 1, message = "{key-2}") private int a = 2; } private class C { @Max(value = 1, message = "{key-3}") private int a = 2; } private class D { @Max(value = 1, message = "{key-4} {") private int a = 2; } }
shahramgdz/hibernate-validator
engine/src/test/java/org/hibernate/validator/test/internal/engine/messageinterpolation/EscapedInterpolationVariableTest.java
Java
apache-2.0
4,239
/* * 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.giraph.benchmark; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.giraph.GiraphConfiguration; import org.apache.giraph.examples.MinimumDoubleCombiner; import org.apache.giraph.graph.EdgeListVertex; import org.apache.giraph.graph.GiraphJob; import org.apache.giraph.io.PseudoRandomVertexInputFormat; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.log4j.Logger; import java.io.IOException; /** * Single-source shortest paths benchmark. */ public class ShortestPathsBenchmark implements Tool { /** Class logger */ private static final Logger LOG = Logger.getLogger(ShortestPathsBenchmark.class); /** Configuration */ private Configuration conf; /** * Vertex implementation */ public static class ShortestPathsBenchmarkVertex extends EdgeListVertex<LongWritable, DoubleWritable, DoubleWritable, DoubleWritable> { @Override public void compute(Iterable<DoubleWritable> messages) throws IOException { ShortestPathsComputation.computeShortestPaths(this, messages); } } @Override public Configuration getConf() { return conf; } @Override public void setConf(Configuration conf) { this.conf = conf; } @Override public final int run(final String[] args) throws Exception { Options options = new Options(); options.addOption("h", "help", false, "Help"); options.addOption("v", "verbose", false, "Verbose"); options.addOption("w", "workers", true, "Number of workers"); options.addOption("V", "aggregateVertices", true, "Aggregate vertices"); options.addOption("e", "edgesPerVertex", true, "Edges per vertex"); options.addOption("c", "vertexClass", true, "Vertex class (0 for HashMapVertex, 1 for EdgeListVertex)"); options.addOption("nc", "noCombiner", false, "Don't use a combiner"); HelpFormatter formatter = new HelpFormatter(); if (args.length == 0) { formatter.printHelp(getClass().getName(), options, true); return 0; } CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { formatter.printHelp(getClass().getName(), options, true); return 0; } if (!cmd.hasOption('w')) { LOG.info("Need to choose the number of workers (-w)"); return -1; } if (!cmd.hasOption('V')) { LOG.info("Need to set the aggregate vertices (-V)"); return -1; } if (!cmd.hasOption('e')) { LOG.info("Need to set the number of edges " + "per vertex (-e)"); return -1; } int workers = Integer.parseInt(cmd.getOptionValue('w')); GiraphJob job = new GiraphJob(getConf(), getClass().getName()); if (!cmd.hasOption('c') || (Integer.parseInt(cmd.getOptionValue('c')) == 1)) { job.getConfiguration().setVertexClass(ShortestPathsBenchmarkVertex.class); } else { job.getConfiguration().setVertexClass( HashMapVertexShortestPathsBenchmark.class); } LOG.info("Using class " + job.getConfiguration().get(GiraphConfiguration.VERTEX_CLASS)); job.getConfiguration().setVertexInputFormatClass( PseudoRandomVertexInputFormat.class); if (!cmd.hasOption("nc")) { job.getConfiguration().setVertexCombinerClass( MinimumDoubleCombiner.class); } job.getConfiguration().setWorkerConfiguration(workers, workers, 100.0f); job.getConfiguration().setLong( PseudoRandomVertexInputFormat.AGGREGATE_VERTICES, Long.parseLong(cmd.getOptionValue('V'))); job.getConfiguration().setLong( PseudoRandomVertexInputFormat.EDGES_PER_VERTEX, Long.parseLong(cmd.getOptionValue('e'))); boolean isVerbose = false; if (cmd.hasOption('v')) { isVerbose = true; } if (job.run(isVerbose)) { return 0; } else { return -1; } } /** * Execute the benchmark. * * @param args Typically the command line arguments. * @throws Exception Any exception from the computation. */ public static void main(final String[] args) throws Exception { System.exit(ToolRunner.run(new ShortestPathsBenchmark(), args)); } }
aljoscha/giraph
src/main/java/org/apache/giraph/benchmark/ShortestPathsBenchmark.java
Java
apache-2.0
5,455
// // ======================================================================== // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.spdy.parser; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jetty.spdy.SessionException; import org.eclipse.jetty.spdy.api.SessionStatus; import org.eclipse.jetty.spdy.frames.ControlFrameType; import org.eclipse.jetty.spdy.frames.CredentialFrame; public class CredentialBodyParser extends ControlFrameBodyParser { private final List<Certificate> certificates = new ArrayList<>(); private final ControlFrameParser controlFrameParser; private State state = State.SLOT; private int totalLength; private int cursor; private short slot; private int proofLength; private byte[] proof; private int certificateLength; private byte[] certificate; public CredentialBodyParser(ControlFrameParser controlFrameParser) { this.controlFrameParser = controlFrameParser; } @Override public boolean parse(ByteBuffer buffer) { while (buffer.hasRemaining()) { switch (state) { case SLOT: { if (buffer.remaining() >= 2) { slot = buffer.getShort(); checkSlotValid(); state = State.PROOF_LENGTH; } else { state = State.SLOT_BYTES; cursor = 2; } break; } case SLOT_BYTES: { byte currByte = buffer.get(); --cursor; slot += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { checkSlotValid(); state = State.PROOF_LENGTH; } break; } case PROOF_LENGTH: { if (buffer.remaining() >= 4) { proofLength = buffer.getInt() & 0x7F_FF_FF_FF; state = State.PROOF; } else { state = State.PROOF_LENGTH_BYTES; cursor = 4; } break; } case PROOF_LENGTH_BYTES: { byte currByte = buffer.get(); --cursor; proofLength += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { proofLength &= 0x7F_FF_FF_FF; state = State.PROOF; } break; } case PROOF: { totalLength = controlFrameParser.getLength() - 2 - 4 - proofLength; proof = new byte[proofLength]; if (buffer.remaining() >= proofLength) { buffer.get(proof); state = State.CERTIFICATE_LENGTH; if (totalLength == 0) { onCredential(); return true; } } else { state = State.PROOF_BYTES; cursor = proofLength; } break; } case PROOF_BYTES: { proof[proofLength - cursor] = buffer.get(); --cursor; if (cursor == 0) { state = State.CERTIFICATE_LENGTH; if (totalLength == 0) { onCredential(); return true; } } break; } case CERTIFICATE_LENGTH: { if (buffer.remaining() >= 4) { certificateLength = buffer.getInt() & 0x7F_FF_FF_FF; state = State.CERTIFICATE; } else { state = State.CERTIFICATE_LENGTH_BYTES; cursor = 4; } break; } case CERTIFICATE_LENGTH_BYTES: { byte currByte = buffer.get(); --cursor; certificateLength += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { certificateLength &= 0x7F_FF_FF_FF; state = State.CERTIFICATE; } break; } case CERTIFICATE: { totalLength -= 4 + certificateLength; certificate = new byte[certificateLength]; if (buffer.remaining() >= certificateLength) { buffer.get(certificate); if (onCertificate()) return true; } else { state = State.CERTIFICATE_BYTES; cursor = certificateLength; } break; } case CERTIFICATE_BYTES: { certificate[certificateLength - cursor] = buffer.get(); --cursor; if (cursor == 0) { if (onCertificate()) return true; } break; } default: { throw new IllegalStateException(); } } } return false; } private void checkSlotValid() { if (slot <= 0) throw new SessionException(SessionStatus.PROTOCOL_ERROR, "Invalid slot " + slot + " for " + ControlFrameType.CREDENTIAL + " frame"); } private boolean onCertificate() { certificates.add(deserializeCertificate(certificate)); if (totalLength == 0) { onCredential(); return true; } else { certificateLength = 0; state = State.CERTIFICATE_LENGTH; } return false; } private Certificate deserializeCertificate(byte[] bytes) { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return certificateFactory.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException x) { throw new SessionException(SessionStatus.PROTOCOL_ERROR, x); } } private void onCredential() { CredentialFrame frame = new CredentialFrame(controlFrameParser.getVersion(), slot, Arrays.copyOf(proof, proof.length), certificates.toArray(new Certificate[certificates.size()])); controlFrameParser.onControlFrame(frame); reset(); } private void reset() { state = State.SLOT; totalLength = 0; cursor = 0; slot = 0; proofLength = 0; proof = null; certificateLength = 0; certificate = null; certificates.clear(); } public enum State { SLOT, SLOT_BYTES, PROOF_LENGTH, PROOF_LENGTH_BYTES, PROOF, PROOF_BYTES, CERTIFICATE_LENGTH, CERTIFICATE_LENGTH_BYTES, CERTIFICATE, CERTIFICATE_BYTES } }
xmpace/jetty-read
jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/parser/CredentialBodyParser.java
Java
apache-2.0
9,058
package com.ctrip.xpipe.redis.core.protocal; /** * @author wenchao.meng * * 2016年3月24日 下午6:27:48 */ public interface RedisProtocol { int REDIS_PORT_DEFAULT = 6379; int KEEPER_PORT_DEFAULT = 6380; int RUN_ID_LENGTH = 40; String CRLF = "\r\n"; String OK = "OK"; String KEEPER_ROLE_PREFIX = "keeperrole"; static String booleanToString(boolean yes){ if(yes){ return "yes"; } return "no"; } }
ctripcorp/x-pipe
redis/redis-core/src/main/java/com/ctrip/xpipe/redis/core/protocal/RedisProtocol.java
Java
apache-2.0
432
package com.pi.xerosync.dbconnect; /** * User: thomas Date: 18/02/14 */ public interface XeroCredentials { String getXeroConsumerKey(); String getXeroConsumerSecret(); String getPrivateKeyPath(); }
tom-haines/patricia-xero-sync
patricia-xero-webapp/src/main/java/com/pi/xerosync/dbconnect/XeroCredentials.java
Java
apache-2.0
207
package main.java; public class SelectionSort9 { public static <T extends Comparable<T>> void sort(final T[] a) { for (int i = 0; i < a.length - 1; i++) { int min = i; for (int j = i + 1; j < a.length; j++) { if (a[j].compareTo(a[min]) < 0) { min = j; } } if (i != min) { final T tmp = a[min]; a[min] = a[i]; a[i] = tmp; } } } }
peteriliev/kata
SelectionSort/src/main/java/SelectionSort9.java
Java
apache-2.0
381
package com.sequenceiq.environment.api.v1.environment.model.response; import java.io.Serializable; import com.sequenceiq.environment.api.doc.environment.EnvironmentModelDescription; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel("EnvironmentAuthenticationV1Response") public class EnvironmentAuthenticationResponse implements Serializable { @ApiModelProperty(EnvironmentModelDescription.PUBLIC_KEY) private String publicKey; @ApiModelProperty(EnvironmentModelDescription.PUBLIC_KEY_ID) private String publicKeyId; @ApiModelProperty(EnvironmentModelDescription.LOGIN_USER_NAME) private String loginUserName; public String getPublicKey() { return publicKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getPublicKeyId() { return publicKeyId; } public void setPublicKeyId(String publicKeyId) { this.publicKeyId = publicKeyId; } public String getLoginUserName() { return loginUserName; } public void setLoginUserName(String loginUserName) { this.loginUserName = loginUserName; } public static Builder builder() { return new Builder(); } @Override public String toString() { return "EnvironmentAuthenticationResponse{" + "publicKey='" + publicKey + '\'' + ", publicKeyId='" + publicKeyId + '\'' + ", loginUserName='" + loginUserName + '\'' + '}'; } public static class Builder { private String publicKey; private String publicKeyId; private String loginUserName; private Builder() { } public Builder withPublicKey(String publicKey) { this.publicKey = publicKey; return this; } public Builder withPublicKeyId(String publicKeyId) { this.publicKeyId = publicKeyId; return this; } public Builder withLoginUserName(String loginUserName) { this.loginUserName = loginUserName; return this; } public EnvironmentAuthenticationResponse build() { EnvironmentAuthenticationResponse response = new EnvironmentAuthenticationResponse(); response.setLoginUserName(loginUserName); response.setPublicKey(publicKey); response.setPublicKeyId(publicKeyId); return response; } } }
hortonworks/cloudbreak
environment-api/src/main/java/com/sequenceiq/environment/api/v1/environment/model/response/EnvironmentAuthenticationResponse.java
Java
apache-2.0
2,539
/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2022 Lunisolar (http://lunisolar.eu/). * * 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 eu.lunisolar.magma.func.predicate; import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import javax.annotation.concurrent.NotThreadSafe; // NOSONAR import java.util.Comparator; // NOSONAR import java.util.Objects; // NOSONAR import eu.lunisolar.magma.basics.*; //NOSONAR import eu.lunisolar.magma.basics.builder.*; // NOSONAR import eu.lunisolar.magma.basics.exceptions.*; // NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.aType.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import eu.lunisolar.magma.func.IA; import eu.lunisolar.magma.func.SA; import eu.lunisolar.magma.func.*; // NOSONAR import eu.lunisolar.magma.func.tuple.*; // NOSONAR import java.util.concurrent.*; // NOSONAR import java.util.function.*; // NOSONAR import java.util.*; // NOSONAR import java.lang.reflect.*; // NOSONAR import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR /** * Non-throwing functional interface (lambda) LBiObjLongPredicate for Java 8. * * Type: predicate * * Domain (lvl: 3): T1 a1,T2 a2,long a3 * * Co-domain: boolean * */ @FunctionalInterface @SuppressWarnings("UnusedDeclaration") public interface LBiObjLongPredicate<T1, T2> extends MetaPredicate, MetaInterface.NonThrowing, Codomain<aBool>, Domain3<a<T1>, a<T2>, aLong> { // NOSONAR String DESCRIPTION = "LBiObjLongPredicate: boolean test(T1 a1,T2 a2,long a3)"; // boolean test(T1 a1,T2 a2,long a3) ; default boolean test(T1 a1, T2 a2, long a3) { // return nestingTest(a1,a2,a3); try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call test(T1 a1,T2 a2,long a3) */ boolean testX(T1 a1, T2 a2, long a3) throws Throwable; default boolean tupleTest(LBiObjLongTriple<T1, T2> args) { return test(args.first(), args.second(), args.third()); } /** Function call that handles exceptions according to the instructions. */ default boolean handlingTest(T1 a1, T2 a2, long a3, HandlingInstructions<Throwable, RuntimeException> handling) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handler.handleOrNest(e, handling); } } default LBiObjLongPredicate<T1, T2> handling(HandlingInstructions<Throwable, RuntimeException> handling) { return (a1, a2, a3) -> handlingTest(a1, a2, a3, handling); } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1, param2); } } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory, newMessage, param1, param2, param3); } } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1, param1); } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { return (a1, a2, a3) -> test(a1, a2, a3, factory, newMessage, param1, param2, param3); } default boolean test(T1 a1, T2 a2, long a3, @Nonnull ExWF<RuntimeException> factory) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.wrap(e, factory); } } default LBiObjLongPredicate<T1, T2> trying(@Nonnull ExWF<RuntimeException> factory) { return (a1, a2, a3) -> test(a1, a2, a3, factory); } default boolean testThen(T1 a1, T2 a2, long a3, @Nonnull LPredicate<Throwable> handler) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR Handling.handleErrors(e); return handler.test(e); } } default LBiObjLongPredicate<T1, T2> tryingThen(@Nonnull LPredicate<Throwable> handler) { return (a1, a2, a3) -> testThen(a1, a2, a3, handler); } /** Function call that handles exceptions by always nesting checked exceptions and propagating the others as is. */ default boolean nestingTest(T1 a1, T2 a2, long a3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** Function call that handles exceptions by always propagating them as is, even when they are undeclared checked ones. */ default boolean shovingTest(T1 a1, T2 a2, long a3) { try { return this.testX(a1, a2, a3); } catch (Throwable e) { // NOSONAR throw Handling.shoveIt(e); } } static <T1, T2> boolean shovingTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.shovingTest(a1, a2, a3); } static <T1, T2> boolean handlingTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, HandlingInstructions<Throwable, RuntimeException> handling) { // <- Null.nonNullArg(func, "func"); return func.handlingTest(a1, a2, a3, handling); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.nestingTest(a1, a2, a3); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1, param2); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWMF<RuntimeException> factory, @Nonnull String newMessage, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory, newMessage, param1, param2, param3); } static <T1, T2> boolean tryTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull ExWF<RuntimeException> factory) { Null.nonNullArg(func, "func"); return func.test(a1, a2, a3, factory); } static <T1, T2> boolean tryTestThen(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull LPredicate<Throwable> handler) { Null.nonNullArg(func, "func"); return func.testThen(a1, a2, a3, handler); } default boolean failSafeTest(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { try { return test(a1, a2, a3); } catch (Throwable e) { // NOSONAR Handling.handleErrors(e); return failSafe.test(a1, a2, a3); } } static <T1, T2> boolean failSafeTest(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> func, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { Null.nonNullArg(failSafe, "failSafe"); if (func == null) { return failSafe.test(a1, a2, a3); } else { return func.failSafeTest(a1, a2, a3, failSafe); } } static <T1, T2> LBiObjLongPredicate<T1, T2> failSafe(LBiObjLongPredicate<T1, T2> func, @Nonnull LBiObjLongPredicate<T1, T2> failSafe) { Null.nonNullArg(failSafe, "failSafe"); return (a1, a2, a3) -> failSafeTest(a1, a2, a3, func, failSafe); } default boolean doIf(T1 a1, T2 a2, long a3, LAction action) { Null.nonNullArg(action, "action"); if (test(a1, a2, a3)) { action.execute(); return true; } else { return false; } } static <T1, T2> boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> predicate, @Nonnull LAction action) { Null.nonNullArg(predicate, "predicate"); return predicate.doIf(a1, a2, a3, action); } static <T1, T2> boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<T1, T2> predicate, @Nonnull LBiObjLongConsumer<? super T1, ? super T2> consumer) { Null.nonNullArg(predicate, "predicate"); return predicate.doIf(a1, a2, a3, consumer); } default boolean doIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongConsumer<? super T1, ? super T2> consumer) { Null.nonNullArg(consumer, "consumer"); if (test(a1, a2, a3)) { consumer.accept(a1, a2, a3); return true; } else { return false; } } /** Just to mirror the method: Ensures the result is not null */ default boolean nonNullTest(T1 a1, T2 a2, long a3) { return test(a1, a2, a3); } /** For convenience, where "test()" makes things more confusing than "applyAsBoolean()". */ default boolean doApplyAsBoolean(T1 a1, T2 a2, long a3) { return test(a1, a2, a3); } /** Returns description of the functional interface. */ @Nonnull default String functionalInterfaceDescription() { return LBiObjLongPredicate.DESCRIPTION; } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void fromTo(long min_a3, long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); if (min_a3 <= max_a3) { for (long a3 = min_a3; a3 <= max_a3; a3++) { func.test(a1, a2, a3); } } else { for (long a3 = min_a3; a3 >= max_a3; a3--) { func.test(a1, a2, a3); } } } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void fromTill(long min_a3, long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); if (min_a3 <= max_a3) { for (long a3 = min_a3; a3 < max_a3; a3++) { func.test(a1, a2, a3); } } else { for (long a3 = min_a3; a3 > max_a3; a3--) { func.test(a1, a2, a3); } } } /** From-To. Intended to be used with non-capturing lambda. */ public static <T1, T2> void times(long max_a3, T1 a1, T2 a2, @Nonnull LBiObjLongPredicate<T1, T2> func) { if (max_a3 < 0) return; fromTill(0, max_a3, a1, a2, func); } /** Extract and apply function. */ public static <M, K, V, T2> boolean from(@Nonnull M container, LBiFunction<M, K, V> extractor, K key, T2 a2, long a3, @Nonnull LBiObjLongPredicate<V, T2> function) { Null.nonNullArg(container, "container"); Null.nonNullArg(function, "function"); V value = extractor.apply(container, key); if (value != null) { return function.test(value, a2, a3); } return false; } default LObjLongPredicate<T2> lShrink(@Nonnull LObjLongFunction<T2, T1> left) { Null.nonNullArg(left, "left"); return (a2, a3) -> test(left.apply(a2, a3), a2, a3); } default LObjLongPredicate<T2> lShrink_(T1 a1) { return (a2, a3) -> test(a1, a2, a3); } public static <T2, T1> LObjLongPredicate<T2> lShrunken(@Nonnull LObjLongFunction<T2, T1> left, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(left, "left"); Null.nonNullArg(func, "func"); return func.lShrink(left); } public static <T2, T1> LObjLongPredicate<T2> lShrunken_(T1 a1, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.lShrink_(a1); } default LBiPredicate<T1, T2> rShrink(@Nonnull LToLongBiFunction<T1, T2> right) { Null.nonNullArg(right, "right"); return (a1, a2) -> test(a1, a2, right.applyAsLong(a1, a2)); } default LBiPredicate<T1, T2> rShrink_(long a3) { return (a1, a2) -> test(a1, a2, a3); } public static <T1, T2> LBiPredicate<T1, T2> rShrunken(@Nonnull LToLongBiFunction<T1, T2> right, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(right, "right"); Null.nonNullArg(func, "func"); return func.rShrink(right); } public static <T1, T2> LBiPredicate<T1, T2> rShrunken_(long a3, @Nonnull LBiObjLongPredicate<T1, T2> func) { Null.nonNullArg(func, "func"); return func.rShrink_(a3); } /** */ public static <T1, T2> LBiObjLongPredicate<T1, T2> uncurry(@Nonnull LFunction<T1, LFunction<T2, LLongPredicate>> func) { Null.nonNullArg(func, "func"); return (T1 a1, T2 a2, long a3) -> func.apply(a1).apply(a2).test(a3); } /** Cast that removes generics. */ default LBiObjLongPredicate untyped() { return this; } /** Cast that replace generics. */ default <V2, V3> LBiObjLongPredicate<V2, V3> cast() { return untyped(); } /** Cast that replace generics. */ public static <V2, V3> LBiObjLongPredicate<V2, V3> cast(LBiObjLongPredicate<?, ?> function) { return (LBiObjLongPredicate) function; } /** Change function to consumer that ignores output. */ default LBiObjLongConsumer<T1, T2> toConsumer() { return this::test; } /** Calls domain consumer before main function. */ default LBiObjLongPredicate<T1, T2> beforeDo(@Nonnull LBiObjLongConsumer<T1, T2> before) { Null.nonNullArg(before, "before"); return (T1 a1, T2 a2, long a3) -> { before.accept(a1, a2, a3); return test(a1, a2, a3); }; } /** Calls codomain consumer after main function. */ default LBiObjLongPredicate<T1, T2> afterDo(@Nonnull LBoolConsumer after) { Null.nonNullArg(after, "after"); return (T1 a1, T2 a2, long a3) -> { final boolean retval = test(a1, a2, a3); after.accept(retval); return retval; }; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (!pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> msgFunc) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msgFunc, "msgFunc"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, msgFunc.apply(a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(msg, a1, a2, a3)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2)); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); if (!pred.test(a1, a2, a3)) { throw Handling.create(factory, String.format(message, param1, param2, param3)); } return a1; } /** Throws new exception if condition is met. */ public static <T1, T2, X extends Throwable> T1 throwIf(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is NOT met. */ public static <T1, T2, X extends Throwable> T1 throwIfNot(T1 a1, @Nonnull LBiObjLongPredicate<? super T1, ? super T2> pred, T2 a2, long a3, @Nonnull ExF<X> noArgFactory) throws X { Null.nonNullArg(pred, "pred"); Null.nonNullArg(noArgFactory, "noArgFactory"); if (!pred.test(a1, a2, a3)) { throw Handling.create(noArgFactory); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(msg, a1, a2, a3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, T2 a2, long a3, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2, param3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String msg) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(msg, "msg"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(msg, a1, a2, a3) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2) + ' ' + m); } return a1; } /** Throws new exception if condition is not met (non null message is returned by 'predicate') */ public static <T1, T2, X extends Throwable> T1 throwIfNot$(T1 a1, @Nonnull LBiObjLongFunction<? super T1, ? super T2, ? extends String> specialPredicate, T2 a2, long a3, @Nonnull ExMF<X> factory, @Nonnull String message, @Nullable Object param1, @Nullable Object param2, @Nullable Object param3) throws X { Null.nonNullArg(specialPredicate, "specialPredicate"); Null.nonNullArg(factory, "factory"); Null.nonNullArg(message, "message"); var m = specialPredicate.apply(a1, a2, a3); if (m != null) { throw Handling.create(factory, String.format(message, param1, param2, param3) + ' ' + m); } return a1; } /** Captures arguments but delays the evaluation. */ default LBoolSupplier capture(T1 a1, T2 a2, long a3) { return () -> this.test(a1, a2, a3); } /** Creates function that always returns the same value. */ static <T1, T2> LBiObjLongPredicate<T1, T2> constant(boolean r) { return (a1, a2, a3) -> r; } /** Captures single parameter function into this interface where only 1st parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test1st(@Nonnull LPredicate<T1> func) { return (a1, a2, a3) -> func.test(a1); } /** Captures single parameter function into this interface where only 2nd parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test2nd(@Nonnull LPredicate<T2> func) { return (a1, a2, a3) -> func.test(a2); } /** Captures single parameter function into this interface where only 3rd parameter will be used. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> test3rd(@Nonnull LLongPredicate func) { return (a1, a2, a3) -> func.test(a3); } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPred(final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** A completely inconvenient method in case lambda expression and generic arguments are ambiguous for the compiler. */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPred(@Nullable Class<T1> c1, @Nullable Class<T2> c2, final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } final class S<T1, T2> implements LBiObjLongPredicate<T1, T2> { private LBiObjLongPredicate<T1, T2> target = null; @Override public boolean testX(T1 a1, T2 a2, long a3) throws Throwable { return target.testX(a1, a2, a3); } } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> recursive(final @Nonnull LFunction<LBiObjLongPredicate<T1, T2>, LBiObjLongPredicate<T1, T2>> selfLambda) { final S<T1, T2> single = new S(); LBiObjLongPredicate<T1, T2> func = selfLambda.apply(single); single.target = func; return func; } public static <T1, T2> M<T1, T2> mementoOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function) { var initialValue = function.test(a1, a2, a3); return initializedMementoOf(initialValue, function); } public static <T1, T2> M<T1, T2> initializedMementoOf(boolean initialValue, LBiObjLongPredicate<T1, T2> function) { return memento(initialValue, initialValue, function, (m, x1, x2) -> x2); } public static <T1, T2> M<T1, T2> deltaOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function, LLogicalBinaryOperator deltaFunction) { var initialValue = function.test(a1, a2, a3); return initializedDeltaOf(initialValue, function, deltaFunction); } public static <T1, T2> M<T1, T2> deltaOf(T1 a1, T2 a2, long a3, LBiObjLongPredicate<T1, T2> function) { var initialValue = function.test(a1, a2, a3); return initializedDeltaOf(initialValue, function, (x1, x2) -> x1 != x2); } public static <T1, T2> M<T1, T2> initializedDeltaOf(boolean initialValue, LBiObjLongPredicate<T1, T2> function, LLogicalBinaryOperator deltaFunction) { return memento(initialValue, deltaFunction.apply(initialValue, initialValue), function, (m, x1, x2) -> deltaFunction.apply(x1, x2)); } public static <T1, T2> M<T1, T2> memento(boolean initialBaseValue, boolean initialValue, LBiObjLongPredicate<T1, T2> baseFunction, LLogicalTernaryOperator mementoFunction) { return new M(initialBaseValue, initialValue, baseFunction, mementoFunction); } /** * Implementation that allows to create derivative functions (do not confuse it with math concepts). Very short name is intended to be used with parent (LBiObjLongPredicate.M) */ @NotThreadSafe final class M<T1, T2> implements LBiObjLongPredicate<T1, T2> { private final LBiObjLongPredicate<T1, T2> baseFunction; private boolean lastBaseValue; private boolean lastValue; private final LLogicalTernaryOperator mementoFunction; private M(boolean lastBaseValue, boolean lastValue, LBiObjLongPredicate<T1, T2> baseFunction, LLogicalTernaryOperator mementoFunction) { this.baseFunction = baseFunction; this.lastBaseValue = lastBaseValue; this.lastValue = lastValue; this.mementoFunction = mementoFunction; } @Override public boolean testX(T1 a1, T2 a2, long a3) throws Throwable { boolean x1 = lastBaseValue; boolean x2 = lastBaseValue = baseFunction.testX(a1, a2, a3); return lastValue = mementoFunction.apply(lastValue, x1, x2); } public boolean lastValue() { return lastValue; }; public boolean lastBaseValue() { return lastBaseValue; }; } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPredThrowing(final @Nonnull ExF<Throwable> exF) { Null.nonNullArg(exF, "exF"); return (a1, a2, a3) -> { throw exF.produce(); }; } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> biObjLongPredThrowing(final String message, final @Nonnull ExMF<Throwable> exF) { Null.nonNullArg(exF, "exF"); return (a1, a2, a3) -> { throw exF.produce(message); }; } // <editor-fold desc="wrap variants"> /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate.LObj0Long2Obj1Pred<T1, T2> obj0Long2Obj1Pred(final @Nonnull LBiObjLongPredicate.LObj0Long2Obj1Pred<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LObj1Obj0Long2Pred<T2, T1> obj1Obj0Long2Pred(final @Nonnull LBiObjLongPredicate.LObj1Obj0Long2Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LObj1Long2Obj0Pred<T2, T1> obj1Long2Obj0Pred(final @Nonnull LBiObjLongPredicate.LObj1Long2Obj0Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T1, T2> LBiObjLongPredicate.LLong2Obj0Obj1Pred<T1, T2> long2Obj0Obj1Pred(final @Nonnull LBiObjLongPredicate.LLong2Obj0Obj1Pred<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } /** Convenient method in case lambda expression is ambiguous for the compiler (that might happen for overloaded methods accepting different interfaces). */ @Nonnull static <T2, T1> LBiObjLongPredicate.LLong2Obj1Obj0Pred<T2, T1> long2Obj1Obj0Pred(final @Nonnull LBiObjLongPredicate.LLong2Obj1Obj0Pred<T2, T1> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda; } // </editor-fold> static <T1, T2> boolean call(T1 a1, T2 a2, long a3, final @Nonnull LBiObjLongPredicate<T1, T2> lambda) { Null.nonNullArg(lambda, "lambda"); return lambda.test(a1, a2, a3); } // <editor-fold desc="wrap"> // </editor-fold> // <editor-fold desc="predicate"> /** * Returns a predicate that represents the logical negation of this predicate. * * @see {@link java.util.function.Predicate#negate} */ @Nonnull default LBiObjLongPredicate<T1, T2> negate() { return (a1, a2, a3) -> !test(a1, a2, a3); } @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> not(@Nonnull LBiObjLongPredicate<T1, T2> pred) { Null.nonNullArg(pred, "pred"); return pred.negate(); } /** * Returns a predicate that represents the logical AND of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#and()} */ @Nonnull default LBiObjLongPredicate<T1, T2> and(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) && other.test(a1, a2, a3); } @Nonnull public static <T1, T2> LBiObjLongPredicate<T1, T2> and(@Nonnull LBiObjLongPredicate<? super T1, ? super T2>... predicates) { Null.nonNullArg(predicates, "predicates"); return (a1, a2, a3) -> { for (LBiObjLongPredicate<? super T1, ? super T2> p : predicates) { if (!p.test(a1, a2, a3)) { return false; } } return true; }; } /** * Returns a predicate that represents the logical OR of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#or} */ @Nonnull default LBiObjLongPredicate<T1, T2> or(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) || other.test(a1, a2, a3); } @Nonnull public static <T1, T2> LBiObjLongPredicate<T1, T2> or(@Nonnull LBiObjLongPredicate<? super T1, ? super T2>... predicates) { Null.nonNullArg(predicates, "predicates"); return (a1, a2, a3) -> { for (LBiObjLongPredicate<? super T1, ? super T2> p : predicates) { if (p.test(a1, a2, a3)) { return true; } } return false; }; } /** * Returns a predicate that represents the logical XOR of evaluation of this predicate and the argument one. * @see {@link java.util.function.Predicate#or} */ @Nonnull default LBiObjLongPredicate<T1, T2> xor(@Nonnull LBiObjLongPredicate<? super T1, ? super T2> other) { Null.nonNullArg(other, "other"); return (a1, a2, a3) -> test(a1, a2, a3) ^ other.test(a1, a2, a3); } /** * Creates predicate that evaluates if an object is equal with the argument one. * @see {@link java.util.function.Predicate#isEqual() */ @Nonnull static <T1, T2> LBiObjLongPredicate<T1, T2> isEqual(T1 v1, T2 v2, long v3) { return (a1, a2, a3) -> (a1 == null ? v1 == null : a1.equals(v1)) && (a2 == null ? v2 == null : a2.equals(v2)) && (a3 == v3); } // </editor-fold> // <editor-fold desc="compose (functional)"> /** Allows to manipulate the domain of the function. */ @Nonnull default <V1, V2> LBiObjLongPredicate<V1, V2> compose(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LLongUnaryOperator before3) { Null.nonNullArg(before1, "before1"); Null.nonNullArg(before2, "before2"); Null.nonNullArg(before3, "before3"); return (v1, v2, v3) -> this.test(before1.apply(v1), before2.apply(v2), before3.applyAsLong(v3)); } public static <V1, V2, T1, T2> LBiObjLongPredicate<V1, V2> composed(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LLongUnaryOperator before3, LBiObjLongPredicate<T1, T2> after) { return after.compose(before1, before2, before3); } /** Allows to manipulate the domain of the function. */ @Nonnull default <V1, V2, V3> LTriPredicate<V1, V2, V3> biObjLongPredCompose(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LToLongFunction<? super V3> before3) { Null.nonNullArg(before1, "before1"); Null.nonNullArg(before2, "before2"); Null.nonNullArg(before3, "before3"); return (v1, v2, v3) -> this.test(before1.apply(v1), before2.apply(v2), before3.applyAsLong(v3)); } public static <V1, V2, V3, T1, T2> LTriPredicate<V1, V2, V3> composed(@Nonnull final LFunction<? super V1, ? extends T1> before1, @Nonnull final LFunction<? super V2, ? extends T2> before2, @Nonnull final LToLongFunction<? super V3> before3, LBiObjLongPredicate<T1, T2> after) { return after.biObjLongPredCompose(before1, before2, before3); } // </editor-fold> // <editor-fold desc="then (functional)"> /** Combines two functions together in a order. */ @Nonnull default <V> LBiObjLongFunction<T1, T2, V> boolToBiObjLongFunc(@Nonnull LBoolFunction<? extends V> after) { Null.nonNullArg(after, "after"); return (a1, a2, a3) -> after.apply(this.test(a1, a2, a3)); } /** Combines two functions together in a order. */ @Nonnull default LBiObjLongPredicate<T1, T2> boolToBiObjLongPred(@Nonnull LLogicalOperator after) { Null.nonNullArg(after, "after"); return (a1, a2, a3) -> after.apply(this.test(a1, a2, a3)); } // </editor-fold> // <editor-fold desc="variant conversions"> // </editor-fold> // <editor-fold desc="interface variants"> /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj0Long2Obj1Pred<T1, T2> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call test(T1 a1,T2 a2,long a3) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj0Long2Obj1(a1, a3, a2); } // boolean testObj0Long2Obj1(T1 a1,long a3,T2 a2) ; default boolean testObj0Long2Obj1(T1 a1, long a3, T2 a2) { // return nestingTestObj0Long2Obj1(a1,a3,a2); try { return this.testObj0Long2Obj1X(a1, a3, a2); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj0Long2Obj1(T1 a1,long a3,T2 a2) */ boolean testObj0Long2Obj1X(T1 a1, long a3, T2 a2) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj1Obj0Long2Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj0Long2Obj1(T1 a1,long a3,T2 a2) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj1Obj0Long2(a2, a1, a3); } // boolean testObj1Obj0Long2(T2 a2,T1 a1,long a3) ; default boolean testObj1Obj0Long2(T2 a2, T1 a1, long a3) { // return nestingTestObj1Obj0Long2(a2,a1,a3); try { return this.testObj1Obj0Long2X(a2, a1, a3); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj1Obj0Long2(T2 a2,T1 a1,long a3) */ boolean testObj1Obj0Long2X(T2 a2, T1 a1, long a3) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LObj1Long2Obj0Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj1Obj0Long2(T2 a2,T1 a1,long a3) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testObj1Long2Obj0(a2, a3, a1); } // boolean testObj1Long2Obj0(T2 a2,long a3,T1 a1) ; default boolean testObj1Long2Obj0(T2 a2, long a3, T1 a1) { // return nestingTestObj1Long2Obj0(a2,a3,a1); try { return this.testObj1Long2Obj0X(a2, a3, a1); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testObj1Long2Obj0(T2 a2,long a3,T1 a1) */ boolean testObj1Long2Obj0X(T2 a2, long a3, T1 a1) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LLong2Obj0Obj1Pred<T1, T2> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testObj1Long2Obj0(T2 a2,long a3,T1 a1) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testLong2Obj0Obj1(a3, a1, a2); } // boolean testLong2Obj0Obj1(long a3,T1 a1,T2 a2) ; default boolean testLong2Obj0Obj1(long a3, T1 a1, T2 a2) { // return nestingTestLong2Obj0Obj1(a3,a1,a2); try { return this.testLong2Obj0Obj1X(a3, a1, a2); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testLong2Obj0Obj1(long a3,T1 a1,T2 a2) */ boolean testLong2Obj0Obj1X(long a3, T1 a1, T2 a2) throws Throwable; } /** Permutation of LBiObjLongPredicate for method references. */ @FunctionalInterface interface LLong2Obj1Obj0Pred<T2, T1> extends LBiObjLongPredicate<T1, T2> { /** * Implement this, but call testLong2Obj0Obj1(long a3,T1 a1,T2 a2) */ default boolean testX(T1 a1, T2 a2, long a3) { return this.testLong2Obj1Obj0(a3, a2, a1); } // boolean testLong2Obj1Obj0(long a3,T2 a2,T1 a1) ; default boolean testLong2Obj1Obj0(long a3, T2 a2, T1 a1) { // return nestingTestLong2Obj1Obj0(a3,a2,a1); try { return this.testLong2Obj1Obj0X(a3, a2, a1); } catch (Throwable e) { // NOSONAR throw Handling.nestCheckedAndThrow(e); } } /** * Implement this, but call testLong2Obj1Obj0(long a3,T2 a2,T1 a1) */ boolean testLong2Obj1Obj0X(long a3, T2 a2, T1 a1) throws Throwable; } // </editor-fold> // >>> LBiObjLongPredicate<T1,T2> /** Returns TRUE. */ public static <T1, T2> boolean alwaysTrue(T1 a1, T2 a2, long a3) { return true; } /** Returns FALSE. */ public static <T1, T2> boolean alwaysFalse(T1 a1, T2 a2, long a3) { return false; } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, C3> void filterForEach(IndexedRead<C1, a<T1>> ia1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); size = Integer.min(size, ia2.size(source2)); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; for (; i < size; i++) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = oiFunc2.apply(source2, i); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, C3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); int size = ia2.size(source2); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (testFunc1.test(iterator1) && i < size) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = oiFunc2.apply(source2, i); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, I2, C3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); size = Integer.min(size, ia3.size(source3)); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (i < size && testFunc2.test(iterator2)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = nextFunc2.apply(iterator2); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, I2, C3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, IndexedRead<C3, aLong> ia3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); int size = ia3.size(source3); LOiToLongFunction<Object> oiFunc3 = (LOiToLongFunction) ia3.getter(); int i = 0; while (testFunc1.test(iterator1) && testFunc2.test(iterator2) && i < size) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = nextFunc2.apply(iterator2); long a3 = oiFunc3.applyAsLong(source3, i); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, C3, I3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); size = Integer.min(size, ia2.size(source2)); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (i < size && testFunc3.test(iterator3)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = oiFunc2.apply(source2, i); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, I1, C2, C3, I3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, IndexedRead<C2, a<T2>> ia2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); int size = ia2.size(source2); LOiFunction<Object, T2> oiFunc2 = (LOiFunction) ia2.getter(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (testFunc1.test(iterator1) && i < size && testFunc3.test(iterator3)) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = oiFunc2.apply(source2, i); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method is not expected. */ default <C1, C2, I2, C3, I3> void filterIterate(IndexedRead<C1, a<T1>> ia1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { int size = ia1.size(source1); LOiFunction<Object, T1> oiFunc1 = (LOiFunction) ia1.getter(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); int i = 0; while (i < size && testFunc2.test(iterator2) && testFunc3.test(iterator3)) { T1 a1 = oiFunc1.apply(source1, i); T2 a2 = nextFunc2.apply(iterator2); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); i++; } } /** * For each element (or tuple) from arguments, calls the consumer if predicate test passes. * Thread safety, fail-fast, fail-safety of this method depends highly on the arguments. */ default <C1, I1, C2, I2, C3, I3> void filterIterate(SequentialRead<C1, I1, a<T1>> sa1, C1 source1, SequentialRead<C2, I2, a<T2>> sa2, C2 source2, SequentialRead<C3, I3, aLong> sa3, C3 source3, LBiObjLongConsumer<? super T1, ? super T2> consumer) { Object iterator1 = ((LFunction) sa1.adapter()).apply(source1); LPredicate<Object> testFunc1 = (LPredicate) sa1.tester(); LFunction<Object, T1> nextFunc1 = (LFunction) sa1.supplier(); Object iterator2 = ((LFunction) sa2.adapter()).apply(source2); LPredicate<Object> testFunc2 = (LPredicate) sa2.tester(); LFunction<Object, T2> nextFunc2 = (LFunction) sa2.supplier(); Object iterator3 = ((LFunction) sa3.adapter()).apply(source3); LPredicate<Object> testFunc3 = (LPredicate) sa3.tester(); LToLongFunction<Object> nextFunc3 = (LToLongFunction) sa3.supplier(); while (testFunc1.test(iterator1) && testFunc2.test(iterator2) && testFunc3.test(iterator3)) { T1 a1 = nextFunc1.apply(iterator1); T2 a2 = nextFunc2.apply(iterator2); long a3 = nextFunc3.applyAsLong(iterator3); doIf(a1, a2, a3, consumer); } } }
lunisolar/magma
magma-func/src/main/java/eu/lunisolar/magma/func/predicate/LBiObjLongPredicate.java
Java
apache-2.0
60,660
/* * Copyright 2012-2018 Christophe Friederich * * 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.devacfr.maven.skins.reflow.context; import static java.util.Objects.requireNonNull; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.Nonnull; import org.apache.commons.lang.builder.ToStringBuilder; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.devacfr.maven.skins.reflow.HtmlTool; import org.devacfr.maven.skins.reflow.ISkinConfig; import org.devacfr.maven.skins.reflow.model.Component; import org.devacfr.maven.skins.reflow.model.Footer; import org.devacfr.maven.skins.reflow.model.NavSideMenu; import org.devacfr.maven.skins.reflow.model.Navbar; import org.devacfr.maven.skins.reflow.model.ScrollTop; import org.devacfr.maven.skins.reflow.model.SideNavMenuItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; /** * The base class of all contexts depending type of page. * * @author Christophe Friederich * @since 2.0 * @param <T> * type of inherrit context object. */ public abstract class Context<T extends Context<?>> extends Component { /** map containing the equivalence of font awesome characters with image found in report pages. */ private static final Map<String, String> ICON_REPLACEMENTS = ImmutableMap.<String, String> builder() .put("img[src$=images/add.gif]", "<i class=\"fas fa-plus\"></i>") .put("img[src$=images/remove.gif]", "<i class=\"fas fa-minus\"></i>") .put("img[src$=images/fix.gif]", "<i class=\"fas fa-wrench\"></i>") .put("img[src$=images/update.gif]", "<i class=\"fas fa-redo\"></i>") .put("img[src$=images/icon_help_sml.gif]", "<i class=\"fas fa-question\"></i>") .put("img[src$=images/icon_success_sml.gif]", "<i class=\"fas fa-check-circle\"></i>") .put("img[src$=images/icon_warning_sml.gif]", "<i class=\"fas fa-exclamation-triangle\"></i>") .put("img[src$=images/icon_error_sml.gif]", "<i class=\"fas fa-exclamation-circle\"></i>") .put("img[src$=images/icon_info_sml.gif]", "<i class=\"fas fa-info\"></i>") .build(); /** */ private static final Logger LOGGER = LoggerFactory.getLogger(Context.class); /** */ private ContextType type; /** */ private final Navbar navbar; /** */ private final Footer footer; /** */ private final ScrollTop scrollTop; /** * Build a context depending of current type of page. * * @param config * a config (can not be {@code null}). * @return Returns a new instance of {@link Context} depending of current page. */ @Nonnull public static Context<?> buildContext(@Nonnull final ISkinConfig config) { requireNonNull(config); ContextType type = ContextType.page; final List<SideNavMenuItem> allSideNaveMenuItems = NavSideMenu.findAllSideNavMenuItems(config); if (LOGGER.isTraceEnabled()) { LOGGER.trace("findAllSideNavMenuItems: " + allSideNaveMenuItems); } final Xpp3Dom pageProperties = config.getPageProperties(); final String fileId = config.getFileId(); if (pageProperties != null) { if (pageProperties.getAttribute("type") != null) { type = ContextType.valueOf(pageProperties.getAttribute("type")); } // frame type whether page associates to document page if (allSideNaveMenuItems.stream().filter(item -> fileId.equals(item.getSlugName())).count() > 0) { type = ContextType.frame; } } // if (type== null) { // type = ContextType.page; // } Context<?> context = null; switch (type) { case doc: context = new DocumentContext(config); break; case frame: // search the parent document page final Optional<SideNavMenuItem> menuItem = allSideNaveMenuItems.stream() .filter(item -> fileId.equals(item.getSlugName())) .findFirst(); final SideNavMenuItem item = menuItem.get(); final String documentParent = item.getParent(); context = new FrameContext(config, documentParent); break; case body: context = new BodyContext(config); break; case page: default: context = new PageContext(config); break; } return context; } /** * Default constructor. * * @param config * a config (can not be {@code null}). * @param type * the type of context (can not be {@code null}). */ public Context(@Nonnull final ISkinConfig config, @Nonnull final ContextType type) { requireNonNull(config); this.withType(requireNonNull(type)); this.navbar = new Navbar(config); this.scrollTop = new ScrollTop(config); this.footer = new Footer(config); this.initialize(config); // the ordering is important for execute preRender method this.addChildren(this.navbar, this.scrollTop, this.footer); } /** * Allows to initialize the context. * @param config * a config (can not be {@code null}). */ protected void initialize(@Nonnull final ISkinConfig config) { // enable AnchorJS if(!config.not("anchorJS")) { this.addCssOptions("anchorjs-enabled"); } } /** * Allows to execute action before rendering of component. * * @param skinConfig * a config (can <b>not</b> be {@code null}). * @return Returns the {@link String} representing the transformed body content. * @since 2.1 */ public String preRender(@Nonnull final ISkinConfig skinConfig) { return onPreRender(skinConfig, getBodyContent(skinConfig)); } @Override protected String onPreRender(final ISkinConfig skinConfig, final String bodyContent) { final HtmlTool htmlTool = getHtmlTool(skinConfig); String content = bodyContent; if (!skinConfig.not("imgLightbox")) { // lightbox is enabled by default, so check for false and negate content = htmlTool.setAttr(content, "a[href$=jpg], a[href$=JPG], a[href$=jpeg], a[href$=JPEG], " + "a[href$=png], a[href$=gif],a[href$=bmp]:has(img)", "data-lightbox", "page"); } if (!skinConfig.not("imgLightbox")) { // lightbox is enabled by default, so check for false and negate content = htmlTool.setAttr(content, "a[href$=jpg], a[href$=JPG], a[href$=jpeg], a[href$=JPEG], " + "a[href$=png], a[href$=gif], a[href$=bmp]:has(img)", "data-lightbox", "page"); } if (!skinConfig.not("html5Anchor")) { // HTML5-style anchors are enabled by default, so check for false and negate content = htmlTool.headingAnchorToId(content); } if (!skinConfig.not("bootstrapCss")) { // Bootstrap CSS class conversion is enabled by default, so check for false and negate content = htmlTool .addClass(content, "table.bodyTable", Lists.newArrayList("table", "table-striped", "table-hover")); // image is responsive by default content = htmlTool.addClass(content, "img", Lists.newArrayList("img-fluid")); content = htmlTool.fixTableHeads(content); } if (!skinConfig.not("bootstrapIcons")) { // Bootstrap Icons are enabled by default, so check for false and negate content = htmlTool.replaceAll(content, ICON_REPLACEMENTS); // The <tt> tag is not supported in HTML5 (see https://www.w3schools.com/tags/tag_tt.asp). content = htmlTool.replaceWith(content, "tt", "<code class=\"literal\">"); } return super.onPreRender(skinConfig, content); } /** * @return Returns the {@link Navbar}. */ public Navbar getNavbar() { return navbar; } /** * @return Returns the {@link ScrollTop}. */ public ScrollTop getScrollTop() { return scrollTop; } /** * @return Returns the {@link Footer}. */ public Footer getFooter() { return footer; } /** * Sets the type of context. * * @param type * the of context. * @return Returns the fluent instance context. */ protected T withType(final ContextType type) { this.type = type; return self(); } /** * @return Returns the type of context of page. */ public String getType() { return type.name(); } /** * @return Returns the fluent instance. */ @SuppressWarnings("unchecked") protected T self() { return (T) this; } /** * {@inheritDoc} */ @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
devacfr/reflow-maven-skin
reflow-velocity-tools/src/main/java/org/devacfr/maven/skins/reflow/context/Context.java
Java
apache-2.0
9,918
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.ssl; import org.apache.activemq.artemis.api.core.ActiveMQSecurityException; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.security.Role; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.settings.HierarchicalRepository; import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.spi.core.security.ActiveMQSecurityManager; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.RetryRule; import org.apache.hadoop.minikdc.MiniKdc; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.File; import java.lang.management.ManagementFactory; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class CoreClientOverOneWaySSLKerb5Test extends ActiveMQTestBase { @Rule public RetryRule retryRule = new RetryRule(2); public static final SimpleString QUEUE = new SimpleString("QueueOverKrb5SSL"); public static final String CLIENT_PRINCIPAL = "client"; public static final String SNI_HOST = "sni.host"; public static final String SERVICE_PRINCIPAL = "host/" + SNI_HOST; static { String path = System.getProperty("java.security.auth.login.config"); if (path == null) { URL resource = CoreClientOverOneWaySSLKerb5Test.class.getClassLoader().getResource("login.config"); if (resource != null) { path = resource.getFile(); System.setProperty("java.security.auth.login.config", path); } } } private MiniKdc kdc; private ActiveMQServer server; private TransportConfiguration tc; private TransportConfiguration inVMTc; private String userPrincipal; @Test public void testOneWaySSLWithGoodClientCipherSuite() throws Exception { // hard coded match, default_keytab_name in minikdc-krb5.conf template File userKeyTab = new File("target/test.krb5.keytab"); kdc.createPrincipal(userKeyTab, CLIENT_PRINCIPAL, SERVICE_PRINCIPAL); createCustomSslServer(); tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true); tc.getParams().put(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, getSuitableCipherSuite()); tc.getParams().put(TransportConstants.SNIHOST_PROP_NAME, SNI_HOST); // static service name rather than dynamic machine name tc.getParams().put(TransportConstants.SSL_KRB5_CONFIG_PROP_NAME, "core-tls-krb5-client"); final ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(tc)); ClientSessionFactory sf = null; try { sf = createSessionFactory(locator); ClientSession session = sf.createSession(false, true, true); session.createQueue(new QueueConfiguration(CoreClientOverOneWaySSLKerb5Test.QUEUE).setRoutingType(RoutingType.ANYCAST)); ClientProducer producer = session.createProducer(CoreClientOverOneWaySSLKerb5Test.QUEUE); final String text = RandomUtil.randomString(); ClientMessage message = createTextMessage(session, text); producer.send(message); ClientConsumer consumer = session.createConsumer(CoreClientOverOneWaySSLKerb5Test.QUEUE); session.start(); ClientMessage m = consumer.receive(1000); Assert.assertNotNull(m); Assert.assertEquals(text, m.getReadOnlyBodyBuffer().readString()); System.err.println("m:" + m + ", user:" + m.getValidatedUserID()); Assert.assertNotNull("got validated user", m.getValidatedUserID()); Assert.assertTrue("krb id in validated user", m.getValidatedUserID().contains(CLIENT_PRINCIPAL)); } finally { if (sf != null) { sf.close(); } locator.close(); } // validate only ssl creds work, try and fake the principal w/o ssl final ServerLocator inVmLocator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(inVMTc)); ClientSessionFactory inVmSf = null; try { inVmSf = createSessionFactory(inVmLocator); inVmSf.createSession(userPrincipal, "", false, false, false, false, 10); fail("supposed to throw exception"); } catch (ActiveMQSecurityException e) { // expected } finally { if (inVmSf != null) { inVmSf.close(); } inVmLocator.close(); } } public String getSuitableCipherSuite() throws Exception { return "TLS_KRB5_WITH_3DES_EDE_CBC_SHA"; } // Package protected --------------------------------------------- @Override @Before public void setUp() throws Exception { super.setUp(); kdc = new MiniKdc(MiniKdc.createConf(), temporaryFolder.newFolder("kdc")); kdc.start(); } @Override @After public void tearDown() throws Exception { try { kdc.stop(); } finally { super.tearDown(); } } private void createCustomSslServer() throws Exception { Map<String, Object> params = new HashMap<>(); params.put(TransportConstants.SSL_ENABLED_PROP_NAME, true); params.put(TransportConstants.ENABLED_CIPHER_SUITES_PROP_NAME, getSuitableCipherSuite()); params.put(TransportConstants.SSL_KRB5_CONFIG_PROP_NAME, "core-tls-krb5-server"); ConfigurationImpl config = createBasicConfig().addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params, "nettySSL")); config.setPopulateValidatedUser(true); // so we can verify the kerb5 id is present config.setSecurityEnabled(true); config.addAcceptorConfiguration(new TransportConfiguration(INVM_ACCEPTOR_FACTORY)); ActiveMQSecurityManager securityManager = new ActiveMQJAASSecurityManager("Krb5Plus"); server = addServer(ActiveMQServers.newActiveMQServer(config, ManagementFactory.getPlatformMBeanServer(), securityManager, false)); HierarchicalRepository<Set<Role>> securityRepository = server.getSecurityRepository(); final String roleName = "ALLOW_ALL"; Role role = new Role(roleName, true, true, true, true, true, true, true, true, true, true); Set<Role> roles = new HashSet<>(); roles.add(role); securityRepository.addMatch(QUEUE.toString(), roles); server.start(); waitForServerToStart(server); // note kerberos user does not exist on the broker save as a role member in dual-authentication-roles.properties userPrincipal = CLIENT_PRINCIPAL + "@" + kdc.getRealm(); tc = new TransportConfiguration(NETTY_CONNECTOR_FACTORY); inVMTc = new TransportConfiguration(INVM_CONNECTOR_FACTORY); } }
andytaylor/activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/ssl/CoreClientOverOneWaySSLKerb5Test.java
Java
apache-2.0
8,618
package org.easyaccess.nist; import java.io.File; import java.util.HashMap; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; public class HomeScreenActivity extends Activity implements OnInitListener { private static final String TAG = "HomeScreenActivity"; boolean isButtonPressed = false; int gFocusPosition = 1; int gMaxFocusableItem = 2; Context gContext = null; String gTTsOnStart = null; SpeakManager gTTS = null; Button gBtnScan = null, gBtnSkipScan = null; View rootView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_ballotstart); gContext = this; rootView = findViewById(R.id.alrt_root_view); gBtnScan = (Button) findViewById(R.id.btn_scan); gBtnSkipScan = (Button) findViewById(R.id.btn_skip_scan); gBtnScan.setBackgroundColor(getResources().getColor(R.color.bg_button)); gBtnScan.setTextColor(getResources().getColor(android.R.color.white)); gBtnSkipScan.setBackgroundColor(getResources().getColor(R.color.bg_button)); gBtnSkipScan.setTextColor(getResources().getColor(android.R.color.white)); gBtnScan.isInTouchMode(); File directory = new File(Constants.NIST_VOTING_PROTOTYPE_DIRECTORY); if (!directory.exists()) { directory.mkdir(); } File sampleFile = new File(directory, Constants.NIST_VOTING_PROTOTYPE_FILE_SP); if (!sampleFile.exists()) { StringBuilder builder = Utils.readFile(gContext, this.getResources().openRawResource(R.raw.election_info_sp)); Utils.writeToFile(builder.toString(), directory + File.separator + Constants.NIST_VOTING_PROTOTYPE_FILE_SP, false); } sampleFile = new File(directory, Constants.NIST_VOTING_PROTOTYPE_FILE_EN); if (!sampleFile.exists()) { StringBuilder builder = Utils.readFile(gContext, this.getResources().openRawResource(R.raw.election_info_en)); Utils.writeToFile(builder.toString(), directory + File.separator + Constants.NIST_VOTING_PROTOTYPE_FILE_EN, false); } } private OnClickListener sOnClickListener = new OnClickListener() { Intent intent = null; @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_scan: launchScan(); break; case R.id.btn_skip_scan: skipScan(); break; case R.id.alrt_root_view: speakWord("", null, false); break; } } private void skipScan() { resetPreferences(); intent = new Intent(gContext, ContestActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } private void launchScan() { resetPreferences(); intent = new Intent(gContext, ScannerActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }; private void resetPreferences() { Constants.SETTING_LANGUAGE = Constants.DEFAULT_LANG_SETTING; Constants.SETTING_TOUCH_PRESENT = Constants.DEFAULT_TOUCH_PRESENT_SETTING; Constants.SETTING_FONT_SIZE = Constants.FONT_SIZE_STD; Constants.SETTING_REVERSE_SCREEN = Constants.DEFAULT_REVERSE_SCREEN_SETTING; Constants.SETTING_TTS_VOICE = Constants.DEFAULT_TTS_VOICE; Constants.SETTING_TTS_SPEED = Constants.TTS_SPEED_STD; Constants.SETTING_SCAN_MODE = Constants.DEFAULT_SCAN_MODE_SETTING; Constants.SETTING_SCAN_MODE_SPEED = Constants.DEFAULT_SCAN_SPEED_SETTING; SharedPreferences preferences = getSharedPreferences( Constants.PREFERENCE_NAME, Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.clear(); editor.commit(); } private OnTouchListener gOnTouchListener = new OnTouchListener() { /** * on touch down announce the info if it represent text. on touch up * perform the action */ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition = 0; switch (v.getId()) { case R.id.btn_scan: v.setBackground(getResources().getDrawable( R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnScan.getText().toString(), null, true); } break; case R.id.btn_skip_scan: v.setBackground(getResources().getDrawable( R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnSkipScan.getText().toString(), null, true); } break; } } else if (event.getAction() == MotionEvent.ACTION_UP) { switch (v.getId()) { case R.id.btn_scan: v.setBackground(null); // v.performClick(); break; case R.id.btn_skip_scan: v.setBackground(null); // v.performClick(); break; } } return false; } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (!isButtonPressed) { int keyPressed = -1; if (keyCode == KeyEvent.KEYCODE_UNKNOWN) { keyPressed = event.getScanCode(); } else { keyPressed = keyCode; } switch (keyPressed) { case KeyEvent.KEYCODE_TAB: if(event.isShiftPressed()){ navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition--; if (gFocusPosition <= 0) { gFocusPosition = gMaxFocusableItem; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); }else{ navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition++; if (gFocusPosition > gMaxFocusableItem) { gFocusPosition = 1; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); } break; case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_BUTTON_1: navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition--; if (gFocusPosition <= 0) { gFocusPosition = gMaxFocusableItem; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); break; case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_BUTTON_2: navigateToOtherItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); gFocusPosition++; if (gFocusPosition > gMaxFocusableItem) { gFocusPosition = 1; } navigateToOtherItem(gFocusPosition, Constants.REACH_NEW_ITEM); break; case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_BUTTON_3: selectCurrentFocusItem(gFocusPosition, Constants.JUMP_FROM_CURRENT_ITEM); break; } } isButtonPressed = true; return true; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { isButtonPressed = false; int keyPressed = -1; if (keyCode == KeyEvent.KEYCODE_UNKNOWN) { keyPressed = event.getScanCode(); } else { keyPressed = keyCode; } switch (keyPressed) { case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_BUTTON_3: // selectCurrentFocusItem(gFocusPosition, // Constants.JUMP_FROM_CURRENT_ITEM); break; } return true; } public void selectCurrentFocusItem(int focusPosition, int pressed_released) { switch (pressed_released) { case Constants.REACH_NEW_ITEM: break; case Constants.JUMP_FROM_CURRENT_ITEM: if (gFocusPosition == 1) { gBtnScan.performClick(); } else if (gFocusPosition == 2) { gBtnSkipScan.performClick(); } break; } } public void navigateToOtherItem(int focusPosition, int reach_jump) { View view = getCurrentFocus(); Log.d(TAG, " from navigation method focus position = " + focusPosition + ", current focus = " + view ); // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); switch (reach_jump) { case Constants.JUMP_FROM_CURRENT_ITEM: if (focusPosition == 1) { // gBtnScan.setBackground(null); } else if (focusPosition == 2) { // gBtnSkipScan.setBackground(null); } break; case Constants.REACH_NEW_ITEM: if (focusPosition == 1) { gBtnScan.setFocusableInTouchMode(true);// for handling the ez-keypad focus gBtnSkipScan.setFocusableInTouchMode(false);// for handling the ez-keypad focus gBtnScan.requestFocus();// for handling the focus when come out of touch mode // gBtnScan.setBackground(getResources().getDrawable( // R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnScan.getText().toString() + Constants.COMMA_SPACE + getString(R.string.button), null, true); } } else if (focusPosition == 2) { gBtnScan.setFocusableInTouchMode(false);// for handling the ez-keypad focus gBtnSkipScan.setFocusableInTouchMode(true);// for handling the ez-keypad focus gBtnSkipScan.requestFocus();// for handling the focus when come out of touch mode // gBtnSkipScan.setBackground(getResources().getDrawable( // R.drawable.focused)); if (HeadsetListener.isHeadsetConnected) { speakWord(gBtnSkipScan.getText().toString() + Constants.COMMA_SPACE + getString(R.string.button), null, true); } } break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d(TAG,"resultCode = " + resultCode); if (requestCode == Constants.TTS_DATA_CHECK_CODE) { if (resultCode == SpeakManager.Engine.CHECK_VOICE_DATA_PASS) { Log.d(TAG,"Setting speak manager"); if (Constants.SETTING_TTS_VOICE == Constants.DEFAULT_TTS_VOICE) { gTTS = new SpeakManager(gContext, this, "com.svox.classic"); } else { gTTS = new SpeakManager(gContext, this, "com.ivona.tts"); } } else { Log.d(TAG,"launching intent for installing tts"); Intent ttsInstallIntent = new Intent(); ttsInstallIntent .setAction(SpeakManager.Engine.ACTION_INSTALL_TTS_DATA); startActivity(ttsInstallIntent); } } } @Override public void onInit(int status) { if (status == SpeakManager.SUCCESS) { if (Constants.SETTING_LANGUAGE == Constants.DEFAULT_LANG_SETTING) { gTTS.setLanguage(Locale.US); } else { gTTS.setLanguage(new Locale("spa", "ESP")); } gTTS.setSpeechRate(Constants.SETTING_TTS_SPEED); speakWord(gTTsOnStart, null, true); } else if (status == SpeakManager.ERROR) { Toast.makeText(gContext, getString(R.string.failed), Toast.LENGTH_SHORT).show(); } } public void speakWord(String word, HashMap<String, String> utteranceId, boolean shouldRepeat) { if (gTTS != null) { gTTS.speak(word, SpeakManager.QUEUE_FLUSH, utteranceId, shouldRepeat); } } @Override protected void onStop() { super.onStop(); if (gTTS != null) { gTTS.stop(); gTTS.shutdown(); } } @Override protected void onStart() { super.onStart(); Intent checkTTSIntent = new Intent(); checkTTSIntent.setAction(SpeakManager.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkTTSIntent, Constants.TTS_DATA_CHECK_CODE); gBtnScan.setText(R.string.scan_barcode); gBtnSkipScan.setText(R.string.skip_barcode); gBtnScan.setTextSize(Constants.SETTING_FONT_SIZE); gBtnSkipScan.setTextSize(Constants.SETTING_FONT_SIZE); gBtnScan.setOnClickListener(sOnClickListener); // gBtnScan.setOnTouchListener(gOnTouchListener); gBtnSkipScan.setOnClickListener(sOnClickListener); // gBtnSkipScan.setOnTouchListener(gOnTouchListener); rootView.setOnClickListener(sOnClickListener); gBtnSkipScan.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ // gBtnSkipScan.setFocusableInTouchMode(true); }else{ // gBtnSkipScan.setFocusableInTouchMode(false); } } }); gBtnScan.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ // gBtnScan.setFocusableInTouchMode(true); }else{ // gBtnScan.setFocusableInTouchMode(false); } } }); gTTsOnStart = getString(R.string.scan_barcode) + Constants.COMMA_SPACE + getString(R.string.button); // View view = getCurrentFocus(); // Log.d(TAG, "current focus = " + view // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); // gBtnScan.setBackgroundResource(R.drawable.focused); gBtnScan.setFocusableInTouchMode(true);// for showing focus initially gBtnScan.requestFocus(); // view = getCurrentFocus(); // Log.d(TAG, "current focus = " + view // + ", next focus down id = " // + view.getNextFocusDownId() // + ", next focus forward id = " + view.getNextFocusForwardId() // + ", next focus left id = " + view.getNextFocusLeftId() // + ", next focus right id = " + view.getNextFocusRightId() // + ", next focus up id = " + view.getNextFocusUpId()); } }
saurabh2590/NIST-Voting-Tablet
src/org/easyaccess/nist/HomeScreenActivity.java
Java
apache-2.0
13,985
// // ÀÌ ÆÄÀÏÀº JAXB(JavaTM Architecture for XML Binding) ÂüÁ¶ ±¸Çö 2.2.8-b130911.1802 ¹öÀüÀ» ÅëÇØ »ý¼ºµÇ¾ú½À´Ï´Ù. // <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>¸¦ ÂüÁ¶ÇϽʽÿÀ. // ÀÌ ÆÄÀÏÀ» ¼öÁ¤ÇÏ¸é ¼Ò½º ½ºÅ°¸¶¸¦ ÀçÄÄÆÄÀÏÇÒ ¶§ ¼öÁ¤ »çÇ×ÀÌ ¼Õ½ÇµË´Ï´Ù. // »ý¼º ³¯Â¥: 2015.07.30 ½Ã°£ 02:38:18 PM KST // package org.gs1.source.tsd; 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.XmlType; /** * <p>TSD_AttributeValuePairListType complex type¿¡ ´ëÇÑ Java Ŭ·¡½ºÀÔ´Ï´Ù. * * <p>´ÙÀ½ ½ºÅ°¸¶ ´ÜÆíÀÌ ÀÌ Å¬·¡½º¿¡ Æ÷ÇԵǴ ÇÊ¿äÇÑ ÄÜÅÙÃ÷¸¦ ÁöÁ¤ÇÕ´Ï´Ù. * * <pre> * &lt;complexType name="TSD_AttributeValuePairListType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="stringAVP" type="{urn:gs1:tsd:tsd_common:xsd:1}TSD_StringAttributeValuePairType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TSD_AttributeValuePairListType", namespace = "urn:gs1:tsd:tsd_common:xsd:1", propOrder = { "stringAVP" }) public class TSDAttributeValuePairListType { @XmlElement(required = true) protected List<TSDStringAttributeValuePairType> stringAVP; /** * Gets the value of the stringAVP 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 stringAVP property. * * <p> * For example, to add a new item, do as follows: * <pre> * getStringAVP().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TSDStringAttributeValuePairType } * * */ public List<TSDStringAttributeValuePairType> getStringAVP() { if (stringAVP == null) { stringAVP = new ArrayList<TSDStringAttributeValuePairType>(); } return this.stringAVP; } }
gs1oliot/gs1source
DataAggregator/src/main/java/org/gs1/source/tsd/TSDAttributeValuePairListType.java
Java
apache-2.0
2,392
/** * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.yahoo.dataplatform.mds.hadoop.hive.io.vector; import java.io.IOException; import org.apache.hadoop.hive.ql.exec.vector.DoubleColumnVector; import jp.co.yahoo.dataplatform.schema.objects.PrimitiveObject; public interface IDecimalPrimitiveSetter{ void set( final PrimitiveObject[] primitiveObjectArray , final DoubleColumnVector columnVector , final int index ) throws IOException; }
yahoojapan/multiple-dimension-spread
src/hive/src/main/java/jp/co/yahoo/dataplatform/mds/hadoop/hive/io/vector/IDecimalPrimitiveSetter.java
Java
apache-2.0
1,217
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileTypes.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher; import com.intellij.openapi.fileTypes.FileNameMatcher; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.util.InvalidDataException; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; final class RemovedMappingTracker { private static final Logger LOG = Logger.getInstance(RemovedMappingTracker.class); static final class RemovedMapping { private final FileNameMatcher myFileNameMatcher; private final String myFileTypeName; private final boolean myApproved; private RemovedMapping(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName, boolean approved) { myFileNameMatcher = matcher; myFileTypeName = fileTypeName; myApproved = approved; } @NotNull FileNameMatcher getFileNameMatcher() { return myFileNameMatcher; } @NotNull String getFileTypeName() { return myFileTypeName; } boolean isApproved() { return myApproved; } @Override public String toString() { return "Removed mapping '" + myFileNameMatcher + "' -> " + myFileTypeName; } // must not look at myApproved @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemovedMapping mapping = (RemovedMapping)o; if (!myFileNameMatcher.equals(mapping.myFileNameMatcher)) return false; return myFileTypeName.equals(mapping.myFileTypeName); } @Override public int hashCode() { int result = myFileNameMatcher.hashCode(); result = 31 * result + myFileTypeName.hashCode(); return result; } } private final MultiMap<FileNameMatcher, RemovedMapping> myRemovedMappings = new MultiMap<>(); @NonNls private static final String ELEMENT_REMOVED_MAPPING = "removed_mapping"; /** Applied for removed mappings approved by user */ @NonNls private static final String ATTRIBUTE_APPROVED = "approved"; @NonNls private static final String ATTRIBUTE_TYPE = "type"; void clear() { myRemovedMappings.clear(); } @NotNull RemovedMapping add(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName, boolean approved) { RemovedMapping mapping = new RemovedMapping(matcher, fileTypeName, approved); List<RemovedMapping> mappings = (List<RemovedMapping>)myRemovedMappings.getModifiable(matcher); boolean found = false; for (int i = 0; i < mappings.size(); i++) { RemovedMapping removedMapping = mappings.get(i); if (removedMapping.getFileTypeName().equals(fileTypeName)) { mappings.set(i, mapping); found = true; break; } } if (!found) { mappings.add(mapping); } return mapping; } void load(@NotNull Element e) { myRemovedMappings.clear(); List<RemovedMapping> removedMappings = readRemovedMappings(e); Set<RemovedMapping> uniques = new LinkedHashSet<>(removedMappings.size()); for (RemovedMapping mapping : removedMappings) { if (!uniques.add(mapping)) { LOG.warn(new InvalidDataException("Duplicate <removed_mapping> tag for " + mapping)); } } for (RemovedMapping mapping : uniques) { myRemovedMappings.putValue(mapping.myFileNameMatcher, mapping); } } @NotNull static List<RemovedMapping> readRemovedMappings(@NotNull Element e) { List<Element> children = e.getChildren(ELEMENT_REMOVED_MAPPING); if (children.isEmpty()) { return Collections.emptyList(); } List<RemovedMapping> result = new ArrayList<>(); for (Element mapping : children) { String ext = mapping.getAttributeValue(AbstractFileType.ATTRIBUTE_EXT); FileNameMatcher matcher = ext == null ? FileTypeManager.parseFromString(mapping.getAttributeValue(AbstractFileType.ATTRIBUTE_PATTERN)) : new ExtensionFileNameMatcher(ext); boolean approved = Boolean.parseBoolean(mapping.getAttributeValue(ATTRIBUTE_APPROVED)); String fileTypeName = mapping.getAttributeValue(ATTRIBUTE_TYPE); if (fileTypeName == null) continue; RemovedMapping removedMapping = new RemovedMapping(matcher, fileTypeName, approved); result.add(removedMapping); } return result; } void save(@NotNull Element element) { List<RemovedMapping> removedMappings = new ArrayList<>(myRemovedMappings.values()); removedMappings.sort(Comparator.comparing((RemovedMapping mapping) -> mapping.getFileNameMatcher().getPresentableString()).thenComparing(RemovedMapping::getFileTypeName)); for (RemovedMapping mapping : removedMappings) { Element content = writeRemovedMapping(mapping.myFileTypeName, mapping.myFileNameMatcher, true, mapping.myApproved); if (content != null) { element.addContent(content); } } } void saveRemovedMappingsForFileType(@NotNull Element map, @NotNull String fileTypeName, @NotNull Collection<? extends FileNameMatcher> associations, boolean specifyTypeName) { for (FileNameMatcher matcher : associations) { Element content = writeRemovedMapping(fileTypeName, matcher, specifyTypeName, isApproved(matcher, fileTypeName)); if (content != null) { map.addContent(content); } } } boolean hasRemovedMapping(@NotNull FileNameMatcher matcher) { return myRemovedMappings.containsKey(matcher); } private boolean isApproved(@NotNull FileNameMatcher matcher, @NotNull String fileTypeName) { RemovedMapping mapping = ContainerUtil.find(myRemovedMappings.get(matcher), m -> m.getFileTypeName().equals(fileTypeName)); return mapping != null && mapping.isApproved(); } @NotNull List<RemovedMapping> getRemovedMappings() { return new ArrayList<>(myRemovedMappings.values()); } @NotNull List<FileNameMatcher> getMappingsForFileType(@NotNull String fileTypeName) { return myRemovedMappings.values().stream() .filter(mapping -> mapping.myFileTypeName.equals(fileTypeName)) .map(mapping -> mapping.myFileNameMatcher) .collect(Collectors.toList()); } @NotNull List<RemovedMapping> removeIf(@NotNull Predicate<? super RemovedMapping> predicate) { List<RemovedMapping> result = new ArrayList<>(); for (Iterator<Map.Entry<FileNameMatcher, Collection<RemovedMapping>>> iterator = myRemovedMappings.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<FileNameMatcher, Collection<RemovedMapping>> entry = iterator.next(); Collection<RemovedMapping> mappings = entry.getValue(); mappings.removeIf(mapping -> { boolean toRemove = predicate.test(mapping); if (toRemove) { result.add(mapping); } return toRemove; }); if (mappings.isEmpty()) { iterator.remove(); } } return result; } void approveUnapprovedMappings() { for (RemovedMapping mapping : new ArrayList<>(myRemovedMappings.values())) { if (!mapping.isApproved()) { myRemovedMappings.remove(mapping.getFileNameMatcher(), mapping); myRemovedMappings.putValue(mapping.getFileNameMatcher(), new RemovedMapping(mapping.getFileNameMatcher(), mapping.getFileTypeName(), true)); } } } private static Element writeRemovedMapping(@NotNull String fileTypeName, @NotNull FileNameMatcher matcher, boolean specifyTypeName, boolean approved) { Element mapping = new Element(ELEMENT_REMOVED_MAPPING); if (!AbstractFileType.writePattern(matcher, mapping)) { return null; } if (approved) { mapping.setAttribute(ATTRIBUTE_APPROVED, "true"); } if (specifyTypeName) { mapping.setAttribute(ATTRIBUTE_TYPE, fileTypeName); } return mapping; } }
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/RemovedMappingTracker.java
Java
apache-2.0
8,518
/******************************************************************************* * Copyright [2016] [Quirino Brizi (quirino.brizi@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 org.actio.modeler.domain.repository; import java.util.List; import org.actio.commons.message.model.ModelMessage; /** * @author quirino.brizi * */ public interface ModelRepository { ModelMessage add(ModelMessage model); List<ModelMessage> getAllModels(); ModelMessage getModel(String modelKey); }
quirinobrizi/actio
webservices/modeler/src/main/java/org/actio/modeler/domain/repository/ModelRepository.java
Java
apache-2.0
1,108
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler.declarative.allocator; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.jobmaster.SlotInfo; import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation; import org.apache.flink.runtime.taskmanager.TaskManagerLocation; /** Test {@link SlotInfo} implementation. */ class TestSlotInfo implements SlotInfo { private final AllocationID allocationId = new AllocationID(); @Override public AllocationID getAllocationId() { return allocationId; } @Override public TaskManagerLocation getTaskManagerLocation() { return new LocalTaskManagerLocation(); } @Override public int getPhysicalSlotNumber() { return 0; } @Override public ResourceProfile getResourceProfile() { return ResourceProfile.ANY; } @Override public boolean willBeOccupiedIndefinitely() { return false; } }
kl0u/flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/declarative/allocator/TestSlotInfo.java
Java
apache-2.0
1,853
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package beans; import java.io.Serializable; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * * @author Chema */ @Component public class Persona implements Serializable { @Value("#{p.nombre}") private String nombre; @Value("#{p.apellido}") private String apellido; public Persona() { } public Persona(String nombre, String apellido) { this.nombre = nombre; this.apellido = apellido; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
xroca/planFormacionJava
spring/Web/AnotacionesWebMaven/src/main/java/beans/Persona.java
Java
apache-2.0
909
/* * 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 delsh.livy; /** * The enumeration types for session kind. */ public enum SessionKind { // Possible values are the following. SPARK("spark"), PYSPARK("pyspark"), SPARKR("sparkr"); private String kind; private SessionKind(String skind) { kind = skind; } public String toString() { return kind; } /** * This class finds enum value that is equivalent to a given string. * @param kind Session kind. * @return Enum value */ public static SessionKind getEnum(String str) { SessionKind[] array = SessionKind.values(); for(SessionKind enumStr : array) { if(str.equals(enumStr.kind.toString())) { return enumStr; } } return null; } }
kojish/hdinsight-spark-livy-client
src/main/java/delsh/livy/SessionKind.java
Java
apache-2.0
1,484
package com.openthinks.libs.utilities.lookup; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import com.openthinks.libs.utilities.Checker; import com.openthinks.libs.utilities.InstanceUtilities; import com.openthinks.libs.utilities.InstanceUtilities.InstanceWrapper; import com.openthinks.libs.utilities.exception.CheckerNoPassException; import com.openthinks.libs.utilities.pools.object.ObjectPool; /** * ClassName: LookupPool <br> * Function: It is used for store shared object instances and find other SPI<br> * Reason: follow the design pattern of fly weight to reduce instantiate new object. <br> * Notice: avoid store or find those object which include its own state and will be changed;<br> * Usage:<br> * * <pre> * <code> * //get gloabl instance of LookupPool * LookupPool lookupPool = LookupPools.gloabl(); * * //get a named instance of LookupPool * lookupPool = LookupPools.get("pool-1"); * * // instance by class directly * LookupInterfaceImpl instanceImpl1 = lookupPool.lookup(LookupInterfaceImpl.class); * * // instance by customized implementation class * LookupInterface instanceImpl2 = lookupPool.lookup(LookupInterface.class,InstanceWrapper.build(LookupInterfaceImpl.class)); * * // lookup shared object already existed * LookupInterface instanceImpl3 = lookupPool.lookup(LookupInterface.class); * assert instanceImpl2==instanceImpl3 ; * * // register a shared object by name * lookupPool.register("beanName1",instanceImpl1); * // lookup shared object by name * LookupInterface instanceImpl4 = lookupPool.lookup("beanName1"); * * assert instanceImpl1==instanceImpl4 ; * * // clear all shared objects and mappings * lookupPool.cleanUp(); * * </code> * </pre> * * date: Sep 8, 2017 3:15:29 PM <br> * * @author dailey.yet@outlook.com * @version 1.0 * @since JDK 1.8 */ public abstract class LookupPool { protected final ObjectPool objectPool; protected final ReadWriteLock lock; public abstract String name(); protected LookupPool() { objectPool = new ObjectPool(); lock = new ReentrantReadWriteLock(); } /** * lookup a object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param type Class lookup key type * @param args Object[] instance constructor parameters * @return T lookup object or null */ public <T> T lookup(Class<T> type, Object... args) { return lookup(type, null, args); } /** * lookup a object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param <E> lookup object type * @param searchType Class lookup key type * @param instancewrapper Class instance type when not lookup the key * @param args Object[] instance constructor parameters * @return T lookup object or null */ public <T, E extends T> T lookup(final Class<T> searchType, InstanceWrapper<E> instancewrapper, Object... args) { T object = null; lock.readLock().lock(); try { object = objectPool.get(searchType); } finally { lock.readLock().unlock(); } if (object == null) { lock.writeLock().lock(); try { object = InstanceUtilities.create(searchType, instancewrapper, args); register(searchType, object); } finally { lock.writeLock().unlock(); } } return object; } /** * look up object by its bean name * * @param <T> lookup object type * @param beanName String lookup object mapping name * @return T lookup object or null */ public <T> T lookup(String beanName) { lock.readLock().lock(); try { return objectPool.get(beanName); } finally { lock.readLock().unlock(); } } /** * lookup a optional object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param type Class lookup key type * @param args Object[] instance constructor parameters * @return Optional of lookup object */ public <T> Optional<T> lookupIf(Class<T> type, Object... args) { return Optional.ofNullable(lookup(type, args)); } /** * lookup a optional object by its type, if not find firstly, try to instance by instanceType and * constructor parameters args * * @param <T> lookup object type * @param <E> lookup object type * @param searchType Class lookup key type * @param instancewrapper Class instance type when not lookup the key * @param args Object[] instance constructor parameters * @return Optional of lookup object */ public <T, E extends T> Optional<T> lookupIf(final Class<T> searchType, InstanceWrapper<E> instancewrapper, Object... args) { return Optional.ofNullable(lookup(searchType, instancewrapper, args)); } /** * look up optional object by its bean name * * @param <T> lookup object type * @param beanName String lookup object mapping name * @return Optional of lookup object */ public <T> Optional<T> lookupIf(String beanName) { return Optional.ofNullable(lookup(beanName)); } /** * * lookupSPI:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will first to try to load instance from cached {@link ObjectPool}, if not found, then try to * load SPI class and instantiate it.<br> * Notice: only load and instantiate first SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param args constructor arguments * @return implementation of parameter spiInterface */ public <T> T lookupSPI(Class<T> spiInterface, Object... args) { return lookupFocusSPI(spiInterface, null, args); } /** * * lookupFocusSPI:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will first to try to load instance from cached {@link ObjectPool}, if not found, then try to * load SPI class and instantiate it.<br> * Notice: only load and instantiate focused SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param focusClassName focused SPI implementation class aname * @param args constructor arguments * @return implementation of parameter spiInterface * */ public <T> T lookupFocusSPI(Class<T> spiInterface, String focusClassName, Object... args) { T object = null; lock.readLock().lock(); try { object = objectPool.get(spiInterface); } finally { lock.readLock().unlock(); } if (object == null) { lock.writeLock().lock(); try { ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface, focusClassName, args); object = serviceLoader.iterator().next(); Checker.require(object).notNull("Cannot found SPI implementation for " + spiInterface); register(spiInterface, object); } finally { lock.writeLock().unlock(); } } return object; } /** * * lookupSPISkipCache:this will used {@link ServiceLoader} to load SPI which defined in folder * <B>META-INF/services</B>. <br> * It will do load SPI skip cache each time, not try to lookup from cache firstly.<br> * Notice: only load and instantiate first SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param args constructor arguments * @return implementation of parameter spiInterface * @throws CheckerNoPassException when not found implementation SPI */ public <T> T lookupSPISkipCache(Class<T> spiInterface, Object... args) { return lookupFocusSPISkipCache(spiInterface, null, args); } /** * * lookupFocusSPISkipCache:this will used {@link ServiceLoader} to load SPI which defined in * folder <B>META-INF/services</B>. <br> * It will do load SPI skip cache each time, not try to lookup from cache firstly.<br> * Notice: only load and instantiate focused SPI class in defined file<br> * * @param <T> lookup SPI interface class * @param spiInterface SPI interface or abstract class type * @param focusClassName focused SPI implementation class name * @param args constructor arguments * @return implementation of parameter spiInterface * * @throws CheckerNoPassException when not found implementation SPI */ public <T> T lookupFocusSPISkipCache(Class<T> spiInterface, String focusClassName, Object... args) { T object = null; ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface, focusClassName, args); object = serviceLoader.iterator().next(); Checker.require(object).notNull("Cannot found SPI implementation for " + spiInterface); return object; } /** * * lookupAllSPI:fina all instance of SPI implementation. <br> * Notice:<BR> * <ul> * <li>all implementation need default constructor.</li> * <li>do not search from cache</li> * </ul> * * @param <T> SPI type * @param spiInterface SPI interface or abstract class type * @return list of all SPI implementation instance */ public <T> List<T> lookupAllSPI(Class<T> spiInterface) { List<T> list = new ArrayList<>(); ServiceLoader<T> serviceLoader = ServiceLoader.load(spiInterface); Iterator<T> iterator = serviceLoader.iterator(); while (iterator.hasNext()) { try { list.add(iterator.next()); } catch (Exception e) { // ignore } } return list; } /** * * register an instance, which key is object.getClass(). <br> * * @param <T> registered object class type * @param object instance which need registered */ public <T> void register(T object) { if (object != null) { lock.writeLock().tryLock(); try { objectPool.put(object.getClass(), object); } finally { lock.writeLock().unlock(); } } } /** * register an instance, which key is given parameter classType * * @param <T> registered object class type * @param classType Class as the key for registered instance * @param object instance which need registered */ public <T> void register(Class<T> classType, T object) { if (object != null) { lock.writeLock().tryLock(); try { objectPool.put(classType, object); } finally { lock.writeLock().unlock(); } } } /** * register object and mapping it to given bean name * * @param <T> register object type * @param beanName String bean name * @param object register object */ public <T> void register(String beanName, T object) { if (object != null) { lock.writeLock().lock(); try { objectPool.put(beanName, object); } finally { lock.writeLock().unlock(); } } } protected void cleanUp() { lock.writeLock().lock(); try { objectPool.cleanUp(); } finally { lock.writeLock().unlock(); } } }
daileyet/openlibs.utilities
src/main/java/com/openthinks/libs/utilities/lookup/LookupPool.java
Java
apache-2.0
11,805
package com.arges.sepan.argmusicplayer.Callbacks; import com.arges.sepan.argmusicplayer.Models.ArgAudio; //Interfaces public interface OnPreparedListener { void onPrepared(ArgAudio audio, int duration); }
mergehez/ArgPlayer
argmusicplayer/src/main/java/com/arges/sepan/argmusicplayer/Callbacks/OnPreparedListener.java
Java
apache-2.0
211
package io.monocycle.agent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @Configuration @EnableAutoConfiguration @ComponentScan @EnableAsync @EnableScheduling public class AgentApplication { private static final Logger LOGGER = LoggerFactory.getLogger(AgentApplication.class); public static void main(String[] args) { LOGGER.debug("Starting Monocycle Agent..."); SpringApplication.run(AgentApplication.class, args); } }
monocycle/monocycle-agent
src/main/java/io/monocycle/agent/AgentApplication.java
Java
apache-2.0
847
/* * Copyright 2014 Waratek 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 com.waratek.spiracle.sql.servlet.oracle; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.waratek.spiracle.sql.servlet.util.ParameterNullFix; import com.waratek.spiracle.sql.util.SelectUtil; /** * Servlet implementation class Get_string_no_quote */ @WebServlet({"/Get_string_no_quote", "/MsSql_Get_string_no_quote", "/MySql_Get_string_no_quote"}) public class Get_string_no_quote extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Get_string_no_quote() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { executeRequest(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { executeRequest(request, response); } private void executeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { ServletContext application = this.getServletConfig().getServletContext(); List<String> queryStringList = new ArrayList<String>(); queryStringList.add("name"); Map<String, String> nullSanitizedMap = ParameterNullFix.sanitizeNull(queryStringList, request); String name = nullSanitizedMap.get("name"); String sql = "SELECT * FROM users WHERE name = " + name; Boolean showErrors = true; Boolean allResults = true; Boolean showOutput = true; SelectUtil.executeQuery(sql, application, request, response, showErrors, allResults, showOutput); } }
waratek/spiracle
src/main/java/com/waratek/spiracle/sql/servlet/oracle/Get_string_no_quote.java
Java
apache-2.0
2,885
package fr.xebia.unittestwithdagger; import android.widget.TextView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import fr.xebia.unittestwithdagger.internal.CustomRobolectricTestRunner; import static junit.framework.Assert.assertEquals; import static org.mockito.BDDMockito.given; /** * Created by florentchampigny on 12/11/2015. */ @RunWith(CustomRobolectricTestRunner.class) @Config(application = MyTestApplication.class, constants = BuildConfig.class, sdk=21) public class UserActivityTest { UserActivity activity; UserStorage userStorage; @Before public void setUp() throws Exception { activity = Robolectric.buildActivity(UserActivity.class).create().get(); userStorage = MyApplication.get().component().userStorage(); } @Test public void displayLoggedUserShoulDisplayFlorent(){ given(userStorage.loadUser()).willReturn(new User("florent")); TextView textView = (TextView)activity.findViewById(R.id.text); activity.displayLoggedUser(); assertEquals("florent", textView.getText().toString()); } }
florent37/UnitTestWithDagger
app/src/test/java/fr/xebia/unittestwithdagger/UserActivityTest.java
Java
apache-2.0
1,254
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package org.politaktiv.map.model.impl; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.model.CacheModel; import org.politaktiv.map.model.Layer; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Date; /** * The cache model class for representing Layer in entity cache. * * @author Paul Butenko * @see Layer * @generated */ public class LayerCacheModel implements CacheModel<Layer>, Externalizable { @Override public String toString() { StringBundler sb = new StringBundler(11); sb.append("{layerId="); sb.append(layerId); sb.append(", createDate="); sb.append(createDate); sb.append(", label="); sb.append(label); sb.append(", userId="); sb.append(userId); sb.append(", portletInstance="); sb.append(portletInstance); sb.append("}"); return sb.toString(); } @Override public Layer toEntityModel() { LayerImpl layerImpl = new LayerImpl(); layerImpl.setLayerId(layerId); if (createDate == Long.MIN_VALUE) { layerImpl.setCreateDate(null); } else { layerImpl.setCreateDate(new Date(createDate)); } if (label == null) { layerImpl.setLabel(StringPool.BLANK); } else { layerImpl.setLabel(label); } layerImpl.setUserId(userId); if (portletInstance == null) { layerImpl.setPortletInstance(StringPool.BLANK); } else { layerImpl.setPortletInstance(portletInstance); } layerImpl.resetOriginalValues(); return layerImpl; } @Override public void readExternal(ObjectInput objectInput) throws IOException { layerId = objectInput.readLong(); createDate = objectInput.readLong(); label = objectInput.readUTF(); userId = objectInput.readLong(); portletInstance = objectInput.readUTF(); } @Override public void writeExternal(ObjectOutput objectOutput) throws IOException { objectOutput.writeLong(layerId); objectOutput.writeLong(createDate); if (label == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(label); } objectOutput.writeLong(userId); if (portletInstance == null) { objectOutput.writeUTF(StringPool.BLANK); } else { objectOutput.writeUTF(portletInstance); } } public long layerId; public long createDate; public String label; public long userId; public String portletInstance; }
PolitAktiv/politaktiv-map2-portlet
docroot/WEB-INF/src/org/politaktiv/map/model/impl/LayerCacheModel.java
Java
apache-2.0
3,021
package org.poormanscastle.studies.compilers.grammar.grammar3_1.astparser.ast; import org.poormanscastle.studies.compilers.utils.grammartools.ast.CodePosition; /** * Created by georg on 15.01.16. */ public class OperatorExpression extends AbstractAstItem implements Expression { private final Expression leftOperand, rightOperand; private final Operator operator; public OperatorExpression(CodePosition codePosition, Expression leftOperand, Operator operator, Expression rightOperand) { super(codePosition); this.leftOperand = leftOperand; this.rightOperand = rightOperand; this.operator = operator; } public Expression getLeftOperand() { return leftOperand; } public Expression getRightOperand() { return rightOperand; } public Operator getOperator() { return operator; } @Override public boolean handleProceedWith(AstItemVisitor visitor) { return visitor.proceedWithOperatorExpression(this); } @Override public void accept(AstItemVisitor visitor) { visitor.visitOperatorExpression(this); if (leftOperand.handleProceedWith(visitor)) { leftOperand.accept(visitor); } if (rightOperand.handleProceedWith(visitor)) { rightOperand.accept(visitor); } visitor.leaveOperatorExpression(this); } }
georgfedermann/compilers
straightline/src/main/java/org/poormanscastle/studies/compilers/grammar/grammar3_1/astparser/ast/OperatorExpression.java
Java
apache-2.0
1,401
package uk.ac.ebi.ddi.extservices.entrez.ncbiresult; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author Yasset Perez-Riverol (ypriverol@gmail.com) * @date 18/05/2015 */ @JsonIgnoreProperties(ignoreUnknown = true) public class NCBITaxResult { @JsonProperty("header") NCBIHeader header; @JsonProperty("esearchresult") NCBIEResult result; public NCBIHeader getHeader() { return header; } public void setHeader(NCBIHeader header) { this.header = header; } public NCBIEResult getResult() { return result; } public void setResult(NCBIEResult result) { this.result = result; } public String[] getNCBITaxonomy() { if (getResult() != null && getResult().getIdList() != null && getResult().getIdList().length == 1) { return getResult().getIdList(); } return null; } }
BD2K-DDI/ddi-annotation
src/main/java/uk/ac/ebi/ddi/extservices/entrez/ncbiresult/NCBITaxResult.java
Java
apache-2.0
974
package peng.zhang.mobilesafe01.servicer; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; public class GPSService extends Service { private LocationManager lm; private MyLocationListener listener; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); lm=(LocationManager) getSystemService(LOCATION_SERVICE); /** * List<String> providers=lm.getAllProviders(); for(String pv :providers){ Log.d(TAG, pv); } */ //ΪÄÚÈÝÌṩÕßÉèÖÃÌõ¼þ Criteria criteria=new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); //ÉèÖòÎÊýϸ»¯£º //criteria.setAccuracy(Criteria.ACCURACY_FINE);//ÉèÖÃΪ×î´ó¾«¶È //criteria.setAltitudeRequired(false);//²»ÒªÇ󺣰ÎÐÅÏ¢ //criteria.setBearingRequired(false);//²»ÒªÇó·½Î»ÐÅÏ¢ //criteria.setCostAllowed(true);//ÊÇ·ñÔÊÐí¸¶·Ñ //criteria.setPowerRequirement(Criteria.POWER_LOW);//¶ÔµçÁ¿µÄÒªÇó //ÉèÖÃλÖøüмàÌýÆ÷£¬ÐèÒª´«Èë²ÎÊýΪ¶¨Î»·½Ê½¡¢¸üÐÂʱ¼ä£¨Ò»°ãÒ»·ÖÖÓ£©£¬¸üоàÀ루һ°ã50Ã×£©£¬¼àÌýÆ÷ //ÉèÖûñÈ¡×îºÃµÄλÖÃÌṩÆ÷ listener =new MyLocationListener(); String provider=lm.getBestProvider(criteria, true); lm.requestLocationUpdates(provider,0, 0, listener); Log.d("Location", "Location0"+"Æô¶¯·þÎñ"); } //·þÎñÏú»Ù£¬È¡Ïû×¢²á @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); lm.removeUpdates(listener); listener=null; } class MyLocationListener implements LocationListener{ /** * µ±Î»ÖøıäµÄʱºò»Øµ÷ */ @Override public void onLocationChanged(Location location) { Log.d("Location", "Location1"+"MyLocationListenerÖ´ÐÐÁË"); String longitude = "jj:" + location.getLongitude() + "\n"; String latitude = "w:" + location.getLatitude() + "\n"; String accuracy = "a" + location.getAccuracy() + "\n"; Log.d("Location", "Location1"+longitude); //½«±ê×¼×ø±êת»»Îª»ðÐÇ×ø±ê //ʵÀý»¯ModifyOffsetÐèÒªÊäÈëÒ»¸öÊäÈëÁ÷£¬Õâ¸öÊäÈëÁ÷¼ÈÊǶÁÈ¡Êý¾Ý¿âÁ÷ // InputStream in = null; // try { // in=getResources().getAssets().open("axisoffset.dat"); // ModifyOffset offset=ModifyOffset.getInstance(in); // //½«±ê×¼×ø±êת»»Îª»ðÐÇ×ø±ê // PointDouble double1=offset.s2c(new PointDouble(location.getLongitude(), location.getLatitude())); // //ת»»Íê³É£¬È¡³ö×ø±ê // longitude ="j:" + offset.X+ "\n"; // latitude = "w:" +offset.Y+ "\n"; // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } //¶ÔµÃµ½µÄ¾­Î³¶È½øÐб£´æ SharedPreferences sp=getSharedPreferences("config", MODE_PRIVATE); Editor editor=sp.edit(); editor.putString("lastlocation", longitude + latitude + accuracy); editor.commit(); } /** * µ±×´Ì¬·¢Éú¸Ä±äµÄʱºò»Øµ÷ ¿ªÆô--¹Ø±Õ £»¹Ø±Õ--¿ªÆô */ @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } /** * ijһ¸öλÖÃÌṩÕß¿ÉÒÔʹÓÃÁË */ @Override public void onProviderEnabled(String provider) { } /** * ijһ¸öλÖÃÌṩÕß²»¿ÉÒÔʹÓÃÁË */ @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } } }
yongyu0102/MobileSafe
src/peng/zhang/mobilesafe01/servicer/GPSService.java
Java
apache-2.0
3,609
package com.ty.activity; import com.ty.app.R; import com.ty.service.AutoUpdateService; import com.ty.util.HttpCallbackListener; import com.ty.util.HttpUtil; import com.ty.util.Utility; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class WeatherActivity extends Activity implements OnClickListener{ private LinearLayout weatherInfoLayout; /** * 用于显示城市名 */ private TextView cityNameText; /** * 用于显示发布时间 */ private TextView publishText; /** * 用于显示天气描述信息 */ private TextView weatherDespText; /** * 用于显示气温1 */ private TextView temp1Text; /** * 用于显示气温2 */ private TextView temp2Text; /** * 用于显示当前日期 */ private TextView currentDateText; /** * 切换城市按钮 */ private Button switchCity; /** * 更新天气按钮 */ private Button refreshWeather; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.weather_layout); // 初始化各控件 weatherInfoLayout = (LinearLayout) findViewById(R.id.tyweather_info_layout); cityNameText = (TextView) findViewById(R.id.tycity_name); publishText = (TextView) findViewById(R.id.typublish_text); weatherDespText = (TextView) findViewById(R.id.tyweather_desp); temp1Text = (TextView) findViewById(R.id.tytemp1); temp2Text = (TextView) findViewById(R.id.tytemp2); currentDateText = (TextView) findViewById(R.id.tycurrent_date); switchCity = (Button) findViewById(R.id.tyswitch_city); refreshWeather = (Button) findViewById(R.id.tyrefresh_weather); String countyCode = getIntent().getStringExtra("county_code"); if (!TextUtils.isEmpty(countyCode)) { // 有县级代号时就去查询天气 publishText.setText("同步中..."); weatherInfoLayout.setVisibility(View.INVISIBLE); cityNameText.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); } else { // 没有县级代号时就直接显示本地天气 showWeather(); } switchCity.setOnClickListener(this); refreshWeather.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tycity_name: Intent intent = new Intent(this, ChooseAreaActivity.class); intent.putExtra("from_weather_activity", true); startActivity(intent); finish(); break; case R.id.tyrefresh_weather: publishText.setText("同步中..."); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherCode = prefs.getString("weather_code", ""); if (!TextUtils.isEmpty(weatherCode)) { queryWeatherInfo(weatherCode); } break; default: break; } } /** * 查询县级代号所对应的天气代号。 */ private void queryWeatherCode(String countyCode) { String address = "http://www.weather.com.cn/data/list3/city" + countyCode + ".xml"; queryFromServer(address, "countyCode"); } /** * 查询天气代号所对应的天气。 */ private void queryWeatherInfo(String weatherCode) { String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html"; queryFromServer(address, "weatherCode"); } /** * 根据传入的地址和类型去向服务器查询天气代号或者天气信息。 */ private void queryFromServer(final String address, final String type) { HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(final String response) { if ("countyCode".equals(type)) { if (!TextUtils.isEmpty(response)) { // 从服务器返回的数据中解析出天气代号 String[] array = response.split("\\|"); if (array != null && array.length == 2) { String weatherCode = array[1]; queryWeatherInfo(weatherCode); } } } else if ("weatherCode".equals(type)) { // 处理服务器返回的天气信息 Utility.handleWeatherResponse(WeatherActivity.this, response); runOnUiThread(new Runnable() { @Override public void run() { showWeather(); } }); } } @Override public void onError(Exception e) { runOnUiThread(new Runnable() { @Override public void run() { publishText.setText("同步失败"); } }); } }); } /** * 从SharedPreferences文件中读取存储的天气信息,并显示到界面上。 */ private void showWeather() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); cityNameText.setText( prefs.getString("city_name", "")); temp1Text.setText(prefs.getString("temp1", "")); temp2Text.setText(prefs.getString("temp2", "")); weatherDespText.setText(prefs.getString("weather_desp", "")); publishText.setText("今天" + prefs.getString("publish_time", "") + "发布"); currentDateText.setText(prefs.getString("current_date", "")); weatherInfoLayout.setVisibility(View.VISIBLE); cityNameText.setVisibility(View.VISIBLE); Intent intent = new Intent(this, AutoUpdateService.class); startService(intent); } }
tanqii/weather
src/com/ty/activity/WeatherActivity.java
Java
apache-2.0
5,476
/** Copyright 2017 Andrea "Stock" Stocchero 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. */ /** * Contains the {@link org.pepstock.charba.client.annotation.AnnotationPlugin#ID} plugin elements interfaces to use in the callbacks and events. * * @author Andrea "Stock" Stocchero * */ package org.pepstock.charba.client.annotation.elements;
pepstock-org/Charba
src/org/pepstock/charba/client/annotation/elements/package-info.java
Java
apache-2.0
881
/* Copyright 2016, 2020 Nationale-Nederlanden, 2020-2021 WeAreFrank! 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 nl.nn.adapterframework.pipes; import java.io.ByteArrayOutputStream; import java.io.IOException; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.Adapter; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.PipeRunException; import nl.nn.adapterframework.core.PipeRunResult; import nl.nn.adapterframework.doc.IbisDoc; import nl.nn.adapterframework.http.RestListenerUtils; import nl.nn.adapterframework.soap.WsdlGenerator; import nl.nn.adapterframework.stream.Message; import nl.nn.adapterframework.util.StreamUtil; /** * Generate WSDL of parent or specified adapter. * * @author Jaco de Groot */ public class WsdlGeneratorPipe extends FixedForwardPipe { private String from = "parent"; @Override public void configure() throws ConfigurationException { super.configure(); if (!"parent".equals(getFrom()) && !"input".equals(getFrom())) { throw new ConfigurationException("from should either be parent or input"); } } @Override public PipeRunResult doPipe(Message message, PipeLineSession session) throws PipeRunException { String result = null; Adapter adapter; try { if ("input".equals(getFrom())) { String adapterName = message.asString(); adapter = getAdapter().getConfiguration().getIbisManager().getRegisteredAdapter(adapterName); if (adapter == null) { throw new PipeRunException(this, "Could not find adapter: " + adapterName); } } else { adapter = getPipeLine().getAdapter(); } } catch (IOException e) { throw new PipeRunException(this, "Could not determine adapter name", e); } try { String generationInfo = "at " + RestListenerUtils.retrieveRequestURL(session); WsdlGenerator wsdl = new WsdlGenerator(adapter.getPipeLine(), generationInfo); wsdl.init(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); wsdl.wsdl(outputStream, null); result = outputStream.toString(StreamUtil.DEFAULT_INPUT_STREAM_ENCODING); } catch (Exception e) { throw new PipeRunException(this, "Could not generate WSDL for adapter [" + adapter.getName() + "]", e); } return new PipeRunResult(getSuccessForward(), result); } public String getFrom() { return from; } @IbisDoc({"either parent (adapter of pipeline which contains this pipe) or input (name of adapter specified by input of pipe)", "parent"}) public void setFrom(String from) { this.from = from; } }
ibissource/iaf
core/src/main/java/nl/nn/adapterframework/pipes/WsdlGeneratorPipe.java
Java
apache-2.0
3,096
/* * #%L * Diana UI Core * %% * Copyright (C) 2014 Diana UI * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.dianaui.universal.core.client.ui.html; import com.dianaui.universal.core.client.ui.base.AbstractTextWidget; import com.dianaui.universal.core.client.ui.constants.ElementTags; import com.google.gwt.dom.client.Document; /** * Simple {@code <strong>} tag to emphasize words * * @author Joshua Godi */ public class Strong extends AbstractTextWidget { public Strong() { super(Document.get().createElement(ElementTags.STRONG)); } public Strong(final String text) { this(); setHTML(text); } }
dianaui/dianaui-universal
core/src/main/java/com/dianaui/universal/core/client/ui/html/Strong.java
Java
apache-2.0
1,186
/* * #%L * Diana UI Core * %% * Copyright (C) 2014 Diana UI * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.dianaui.universal.core.client.ui.constants; import com.dianaui.universal.core.client.ui.base.helper.EnumHelper; import com.google.gwt.dom.client.Style; /** * Only relevant to horizontal forms * * @author Xiaodong Sun */ public enum FormGroupSize implements Size, Style.HasCssName { LARGE("form-group-lg"), DEFAULT(""), SMALL("form-group-sm"),; private final String cssClass; private FormGroupSize(final String cssClass) { this.cssClass = cssClass; } @Override public String getCssName() { return cssClass; } public static FormGroupSize fromStyleName(final String styleName) { return EnumHelper.fromStyleName(styleName, FormGroupSize.class, DEFAULT); } }
dianaui/dianaui-universal
core/src/main/java/com/dianaui/universal/core/client/ui/constants/FormGroupSize.java
Java
apache-2.0
1,385
/* * 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 fixture.simple; import java.util.List; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.Named; import org.apache.isis.applib.annotation.Prototype; import org.apache.isis.applib.fixturescripts.FixtureResult; import org.apache.isis.applib.fixturescripts.FixtureScript; import org.apache.isis.applib.fixturescripts.FixtureScripts; import org.apache.isis.applib.fixturescripts.SimpleFixtureScript; /** * Enables fixtures to be installed from the application. */ @Named("Prototyping") @DomainService(menuOrder = "20") public class SimpleObjectsFixturesService extends FixtureScripts { public SimpleObjectsFixturesService() { super("fixture.simple"); } //@Override // compatibility with core 1.5.0 public FixtureScript default0RunFixtureScript() { return findFixtureScriptFor(SimpleFixtureScript.class); } /** * Raising visibility to <tt>public</tt> so that choices are available for first param * of {@link #runFixtureScript(FixtureScript, String)}. */ @Override public List<FixtureScript> choices0RunFixtureScript() { return super.choices0RunFixtureScript(); } // ////////////////////////////////////// @Prototype @MemberOrder(sequence="20") public Object installFixturesAndReturnFirst() { final List<FixtureResult> run = findFixtureScriptFor(SimpleObjectsFixture.class).run(null); return run.get(0).getObject(); } @Prototype @MemberOrder(sequence="20") public Object instalarFixturesAlumnos() { final List<FixtureResult> run = findFixtureScriptFor(AlumnosFixture.class).run(null); return run.get(0).getObject(); } @Prototype @MemberOrder(sequence="20") public Object instalarFixturesCursos() { final List<FixtureResult> run = findFixtureScriptFor(CursosFixture.class).run(null); return run.get(0).getObject(); } }
leanddrot/isis-asistencia
fixture/src/main/java/fixture/simple/SimpleObjectsFixturesService.java
Java
apache-2.0
2,843
package org.qcri.rheem.basic.operators; import org.apache.commons.lang3.Validate; import org.qcri.rheem.core.api.Configuration; import org.qcri.rheem.core.function.DistinctPredicateDescriptor; import org.qcri.rheem.core.function.PredicateDescriptor; import org.qcri.rheem.core.optimizer.OptimizationContext; import org.qcri.rheem.core.optimizer.ProbabilisticDoubleInterval; import org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimate; import org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator; import org.qcri.rheem.core.optimizer.cardinality.DefaultCardinalityEstimator; import org.qcri.rheem.core.plan.rheemplan.UnaryToUnaryOperator; import org.qcri.rheem.core.types.DataSetType; import java.util.Optional; /** * This operator returns the distinct elements in this dataset. */ public class DistinctOperator<Type> extends UnaryToUnaryOperator<Type, Type> { protected final DistinctPredicateDescriptor<Type> predicateDescriptor; /** * Creates a new instance. * * @param type type of the dataunit elements */ public DistinctOperator(DataSetType<Type> type) { super(type, type, false); this.predicateDescriptor = null; } public DistinctOperator(DataSetType<Type> type, DistinctPredicateDescriptor<Type> predicateDescriptor) { super(type, type, false); this.predicateDescriptor = predicateDescriptor; } /** * Creates a new instance. * * @param typeClass type of the dataunit elements */ public DistinctOperator(Class<Type> typeClass) { this(DataSetType.createDefault(typeClass)); } /** * Copies an instance (exclusive of broadcasts). * * @param that that should be copied */ public DistinctOperator(DistinctOperator<Type> that) { super(that); this.predicateDescriptor = that.getPredicateDescriptor(); } public DistinctPredicateDescriptor<Type> getPredicateDescriptor() { return this.predicateDescriptor; } public String getSelectKeyString(){ if (this.getPredicateDescriptor() != null && this.getPredicateDescriptor().getUdfSelectivity() != null){ return this.getPredicateDescriptor().getUdfSelectivityKeyString(); } else { return ""; } } // // Assume with a confidence of 0.7 that 70% of the data quanta are pairwise distinct. // return Optional.of(new DefaultCardinalityEstimator(0.7d, 1, this.isSupportingBroadcastInputs(), // inputCards -> (long) (inputCards[0] * 0.7d))); // TODO JRK: Do not make baseline worse @Override public Optional<org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator> createCardinalityEstimator( final int outputIndex, final Configuration configuration) { Validate.inclusiveBetween(0, this.getNumOutputs() - 1, outputIndex); return Optional.of(new DistinctOperator.CardinalityEstimator(configuration)); } private class CardinalityEstimator implements org.qcri.rheem.core.optimizer.cardinality.CardinalityEstimator { /** * The expected selectivity to be applied in this instance. */ private final ProbabilisticDoubleInterval selectivity; Configuration configuration; public CardinalityEstimator(Configuration configuration) { this.selectivity = configuration.getUdfSelectivityProvider().provideFor(DistinctOperator.this.predicateDescriptor); this.configuration = configuration; } @Override public CardinalityEstimate estimate(OptimizationContext optimizationContext, CardinalityEstimate... inputEstimates) { Validate.isTrue(inputEstimates.length == DistinctOperator.this.getNumInputs()); final CardinalityEstimate inputEstimate = inputEstimates[0]; String mode = this.configuration.getStringProperty("rheem.optimizer.sr.mode", "best"); if (mode.equals("best")){ mode = this.selectivity.getBest(); } if (mode.equals("lin")) { return new CardinalityEstimate( (long) Math.max(0, ((inputEstimate.getLowerEstimate() * this.selectivity.getCoeff() + this.selectivity.getIntercept()) * inputEstimate.getLowerEstimate())), (long) Math.max(0, ((inputEstimate.getUpperEstimate() * this.selectivity.getCoeff() + this.selectivity.getIntercept()) * inputEstimate.getUpperEstimate())), inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability() ); } else if (mode.equals("log")) { return new CardinalityEstimate( (long) Math.max(0, ((Math.log(inputEstimate.getLowerEstimate()) * this.selectivity.getLog_coeff() + this.selectivity.getLog_intercept()) * inputEstimate.getLowerEstimate())), (long) Math.max(0, ((Math.log(inputEstimate.getUpperEstimate()) * this.selectivity.getLog_coeff() + this.selectivity.getLog_intercept()) * inputEstimate.getUpperEstimate())), inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability() ); } else { return new CardinalityEstimate( (long) Math.max(0, (inputEstimate.getLowerEstimate() * this.selectivity.getLowerEstimate())), (long) Math.max(0, (inputEstimate.getUpperEstimate() * this.selectivity.getUpperEstimate())), inputEstimate.getCorrectnessProbability() * this.selectivity.getCorrectnessProbability() ); } } } }
jonasrk/rheem
rheem-basic/src/main/java/org/qcri/rheem/basic/operators/DistinctOperator.java
Java
apache-2.0
5,747
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.phonemetra.turbo.launcher; import com.phonemetra.turbo.launcher.R; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Region; import android.graphics.Region.Op; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.MotionEvent; import android.widget.TextView; public class BubbleTextView extends TextView { static final float SHADOW_LARGE_RADIUS = 4.0f; static final float SHADOW_SMALL_RADIUS = 1.75f; static final float SHADOW_Y_OFFSET = 2.0f; static final int SHADOW_LARGE_COLOUR = 0xDD000000; static final int SHADOW_SMALL_COLOUR = 0xCC000000; static final float PADDING_H = 8.0f; static final float PADDING_V = 3.0f; private int mPrevAlpha = -1; private HolographicOutlineHelper mOutlineHelper; private final Canvas mTempCanvas = new Canvas(); private final Rect mTempRect = new Rect(); private boolean mDidInvalidateForPressedState; private Bitmap mPressedOrFocusedBackground; private int mFocusedOutlineColor; private int mFocusedGlowColor; private int mPressedOutlineColor; private int mPressedGlowColor; private int mTextColor; private boolean mShadowsEnabled = true; private boolean mIsTextVisible; private boolean mBackgroundSizeChanged; private Drawable mBackground; private boolean mStayPressed; private CheckLongPressHelper mLongPressHelper; public BubbleTextView(Context context) { super(context); init(); } public BubbleTextView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public BubbleTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void onFinishInflate() { super.onFinishInflate(); LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); setTextSize(TypedValue.COMPLEX_UNIT_PX, grid.iconTextSizePx); setTextColor(getResources().getColor(R.color.workspace_icon_text_color)); } private void init() { mLongPressHelper = new CheckLongPressHelper(this); mBackground = getBackground(); mOutlineHelper = HolographicOutlineHelper.obtain(getContext()); final Resources res = getContext().getResources(); mFocusedOutlineColor = mFocusedGlowColor = mPressedOutlineColor = mPressedGlowColor = res.getColor(R.color.outline_color); setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR); } public void applyFromShortcutInfo(ShortcutInfo info, IconCache iconCache) { LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); Bitmap b = info.getIcon(iconCache); setCompoundDrawables(null, Utilities.createIconDrawable(b), null, null); setCompoundDrawablePadding(grid.iconDrawablePaddingPx); setText(info.title); setTag(info); } @Override protected boolean setFrame(int left, int top, int right, int bottom) { if (getLeft() != left || getRight() != right || getTop() != top || getBottom() != bottom) { mBackgroundSizeChanged = true; } return super.setFrame(left, top, right, bottom); } @Override protected boolean verifyDrawable(Drawable who) { return who == mBackground || super.verifyDrawable(who); } @Override public void setTag(Object tag) { if (tag != null) { LauncherModel.checkItemInfo((ItemInfo) tag); } super.setTag(tag); } @Override protected void drawableStateChanged() { if (isPressed()) { // In this case, we have already created the pressed outline on ACTION_DOWN, // so we just need to do an invalidate to trigger draw if (!mDidInvalidateForPressedState) { setCellLayoutPressedOrFocusedIcon(); } } else { // Otherwise, either clear the pressed/focused background, or create a background // for the focused state final boolean backgroundEmptyBefore = mPressedOrFocusedBackground == null; if (!mStayPressed) { mPressedOrFocusedBackground = null; } if (isFocused()) { if (getLayout() == null) { // In some cases, we get focus before we have been layed out. Set the // background to null so that it will get created when the view is drawn. mPressedOrFocusedBackground = null; } else { mPressedOrFocusedBackground = createGlowingOutline( mTempCanvas, mFocusedGlowColor, mFocusedOutlineColor); } mStayPressed = false; setCellLayoutPressedOrFocusedIcon(); } final boolean backgroundEmptyNow = mPressedOrFocusedBackground == null; if (!backgroundEmptyBefore && backgroundEmptyNow) { setCellLayoutPressedOrFocusedIcon(); } } Drawable d = mBackground; if (d != null && d.isStateful()) { d.setState(getDrawableState()); } super.drawableStateChanged(); } /** * Draw this BubbleTextView into the given Canvas. * * @param destCanvas the canvas to draw on * @param padding the horizontal and vertical padding to use when drawing */ private void drawWithPadding(Canvas destCanvas, int padding) { final Rect clipRect = mTempRect; getDrawingRect(clipRect); // adjust the clip rect so that we don't include the text label clipRect.bottom = getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + getLayout().getLineTop(0); // Draw the View into the bitmap. // The translate of scrollX and scrollY is necessary when drawing TextViews, because // they set scrollX and scrollY to large values to achieve centered text destCanvas.save(); destCanvas.scale(getScaleX(), getScaleY(), (getWidth() + padding) / 2, (getHeight() + padding) / 2); destCanvas.translate(-getScrollX() + padding / 2, -getScrollY() + padding / 2); destCanvas.clipRect(clipRect, Op.REPLACE); draw(destCanvas); destCanvas.restore(); } public void setGlowColor(int color) { mFocusedOutlineColor = mFocusedGlowColor = mPressedOutlineColor = mPressedGlowColor = color; } /** * Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location. * Responsibility for the bitmap is transferred to the caller. */ private Bitmap createGlowingOutline(Canvas canvas, int outlineColor, int glowColor) { final int padding = mOutlineHelper.mMaxOuterBlurRadius; final Bitmap b = Bitmap.createBitmap( getWidth() + padding, getHeight() + padding, Bitmap.Config.ARGB_8888); canvas.setBitmap(b); drawWithPadding(canvas, padding); mOutlineHelper.applyExtraThickExpensiveOutlineWithBlur(b, canvas, glowColor, outlineColor); canvas.setBitmap(null); return b; } @Override public boolean onTouchEvent(MotionEvent event) { // Call the superclass onTouchEvent first, because sometimes it changes the state to // isPressed() on an ACTION_UP boolean result = super.onTouchEvent(event); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // So that the pressed outline is visible immediately when isPressed() is true, // we pre-create it on ACTION_DOWN (it takes a small but perceptible amount of time // to create it) if (mPressedOrFocusedBackground == null) { mPressedOrFocusedBackground = createGlowingOutline( mTempCanvas, mPressedGlowColor, mPressedOutlineColor); } // Invalidate so the pressed state is visible, or set a flag so we know that we // have to call invalidate as soon as the state is "pressed" if (isPressed()) { mDidInvalidateForPressedState = true; setCellLayoutPressedOrFocusedIcon(); } else { mDidInvalidateForPressedState = false; } mLongPressHelper.postCheckForLongPress(); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: // If we've touched down and up on an item, and it's still not "pressed", then // destroy the pressed outline if (!isPressed()) { mPressedOrFocusedBackground = null; } mLongPressHelper.cancelLongPress(); break; } return result; } void setStayPressed(boolean stayPressed) { mStayPressed = stayPressed; if (!stayPressed) { mPressedOrFocusedBackground = null; } setCellLayoutPressedOrFocusedIcon(); } void setCellLayoutPressedOrFocusedIcon() { if (getParent() instanceof ShortcutAndWidgetContainer) { ShortcutAndWidgetContainer parent = (ShortcutAndWidgetContainer) getParent(); if (parent != null) { CellLayout layout = (CellLayout) parent.getParent(); layout.setPressedOrFocusedIcon((mPressedOrFocusedBackground != null) ? this : null); } } } void clearPressedOrFocusedBackground() { mPressedOrFocusedBackground = null; setCellLayoutPressedOrFocusedIcon(); } Bitmap getPressedOrFocusedBackground() { return mPressedOrFocusedBackground; } int getPressedOrFocusedBackgroundPadding() { return mOutlineHelper.mMaxOuterBlurRadius / 2; } @Override public void draw(Canvas canvas) { if (!mShadowsEnabled) { super.draw(canvas); return; } final Drawable background = mBackground; if (background != null) { final int scrollX = getScrollX(); final int scrollY = getScrollY(); if (mBackgroundSizeChanged) { background.setBounds(0, 0, getRight() - getLeft(), getBottom() - getTop()); mBackgroundSizeChanged = false; } if ((scrollX | scrollY) == 0) { background.draw(canvas); } else { canvas.translate(scrollX, scrollY); background.draw(canvas); canvas.translate(-scrollX, -scrollY); } } // If text is transparent, don't draw any shadow if (getCurrentTextColor() == getResources().getColor(android.R.color.transparent)) { getPaint().clearShadowLayer(); super.draw(canvas); return; } // We enhance the shadow by drawing the shadow twice getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR); super.draw(canvas); canvas.save(Canvas.CLIP_SAVE_FLAG); canvas.clipRect(getScrollX(), getScrollY() + getExtendedPaddingTop(), getScrollX() + getWidth(), getScrollY() + getHeight(), Region.Op.INTERSECT); getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR); super.draw(canvas); canvas.restore(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mBackground != null) mBackground.setCallback(this); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mBackground != null) mBackground.setCallback(null); } @Override public void setTextColor(int color) { mTextColor = color; super.setTextColor(color); } public void setShadowsEnabled(boolean enabled) { mShadowsEnabled = enabled; getPaint().clearShadowLayer(); invalidate(); } public void setTextVisibility(boolean visible) { Resources res = getResources(); if (visible) { super.setTextColor(mTextColor); } else { super.setTextColor(res.getColor(android.R.color.transparent)); } mIsTextVisible = visible; } public boolean isTextVisible() { return mIsTextVisible; } @Override protected boolean onSetAlpha(int alpha) { if (mPrevAlpha != alpha) { mPrevAlpha = alpha; super.onSetAlpha(alpha); } return true; } @Override public void cancelLongPress() { super.cancelLongPress(); mLongPressHelper.cancelLongPress(); } }
Phonemetra/TurboLauncher
app/src/main/java/com/phonemetra/turbo/launcher/BubbleTextView.java
Java
apache-2.0
13,912
/* * Licensed to Crate.IO GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.operation.merge; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.SettableFuture; import io.crate.core.collections.ArrayBucket; import io.crate.core.collections.Bucket; import io.crate.core.collections.BucketPage; import io.crate.core.collections.Row; import io.crate.core.collections.Row1; import io.crate.core.collections.SingleRowBucket; import io.crate.operation.PageConsumeListener; import io.crate.operation.projectors.RowReceiver; import io.crate.test.integration.CrateUnitTest; import io.crate.testing.CollectingRowReceiver; import io.crate.testing.TestingHelpers; import org.elasticsearch.common.breaker.CircuitBreakingException; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.Mockito; import javax.annotation.Nonnull; import java.util.concurrent.Executor; import static org.hamcrest.core.Is.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class IteratorPageDownstreamTest extends CrateUnitTest { public static final PageConsumeListener PAGE_CONSUME_LISTENER = new PageConsumeListener() { @Override public void needMore() { } @Override public void finish() { } }; @Mock PagingIterator<Row> mockedPagingIterator; @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testMergeOnPagingIteratorIsCalledAfterALLBucketsAreReady() throws Exception { IteratorPageDownstream downstream = new IteratorPageDownstream( new CollectingRowReceiver(), mockedPagingIterator, Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); SettableFuture<Bucket> b2 = SettableFuture.create(); downstream.nextPage(new BucketPage(ImmutableList.of(b1, b2)), PAGE_CONSUME_LISTENER); verify(mockedPagingIterator, times(0)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any()); b1.set(Bucket.EMPTY); verify(mockedPagingIterator, times(0)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any()); b2.set(Bucket.EMPTY); verify(mockedPagingIterator, times(1)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any()); } @Test public void testFailingNextRowIsHandled() throws Exception { expectedException.expect(CircuitBreakingException.class); class FailingRowReceiver extends CollectingRowReceiver { @Override public boolean setNextRow(Row row) { throw new CircuitBreakingException("foo"); } } CollectingRowReceiver rowReceiver = new FailingRowReceiver(); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>oneShot(), Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); b1.set(new SingleRowBucket(new Row1(42))); rowReceiver.result(); } @Test public void testBucketFailureIsPassedToDownstream() throws Exception { IllegalStateException dummy = new IllegalStateException("dummy"); expectedException.expect(IllegalStateException.class); CollectingRowReceiver rowReceiver = new CollectingRowReceiver(); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, mockedPagingIterator, Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); b1.setException(dummy); rowReceiver.result(); } @Test public void testMultipleFinishPropagatesOnlyOnceToDownstream() throws Exception { RowReceiver rowReceiver = mock(RowReceiver.class); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, mockedPagingIterator, Optional.<Executor>absent()); downstream.finish(); downstream.finish(); verify(rowReceiver, times(1)).finish(); } @Test public void testFinishDoesNotEmitRemainingRow() throws Exception { CollectingRowReceiver rowReceiver = CollectingRowReceiver.withLimit(1); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>oneShot(), Optional.<Executor>absent() ); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(new ArrayBucket( new Object[][]{ new Object[]{"a"}, new Object[]{"b"}, new Object[]{"c"} } )); downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); downstream.finish(); assertThat(rowReceiver.result().size(), is(1)); } @Test public void testRejectedExecutionDoesNotCauseBucketMergerToGetStuck() throws Exception { expectedException.expect(EsRejectedExecutionException.class); final CollectingRowReceiver rowReceiver = new CollectingRowReceiver(); IteratorPageDownstream pageDownstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>oneShot(), Optional.<Executor>of(new Executor() { @Override public void execute(@Nonnull Runnable command) { throw new EsRejectedExecutionException("HAHA !"); } })); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(Bucket.EMPTY); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), new PageConsumeListener() { @Override public void needMore() { rowReceiver.finish(); } @Override public void finish() { rowReceiver.finish(); } }); rowReceiver.result(); } @Test public void testRepeat() throws Exception { CollectingRowReceiver rowReceiver = new CollectingRowReceiver(); IteratorPageDownstream pageDownstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>repeatable(), Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(new ArrayBucket( new Object[][] { new Object[] {"a"}, new Object[] {"b"}, new Object[] {"c"} } )); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); pageDownstream.finish(); rowReceiver.repeatUpstream(); pageDownstream.finish(); assertThat(TestingHelpers.printedTable(rowReceiver.result()), is( "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n")); } @Test public void testPauseAndResume() throws Exception { CollectingRowReceiver rowReceiver = CollectingRowReceiver.withPauseAfter(2); IteratorPageDownstream pageDownstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>repeatable(), Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(new ArrayBucket( new Object[][] { new Object[] {"a"}, new Object[] {"b"}, new Object[] {"c"} } )); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); assertThat(rowReceiver.rows.size(), is(2)); rowReceiver.resumeUpstream(false); assertThat(rowReceiver.rows.size(), is(3)); pageDownstream.finish(); rowReceiver.repeatUpstream(); assertThat(TestingHelpers.printedTable(rowReceiver.result()), is( "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n")); } }
aslanbekirov/crate
sql/src/test/java/io/crate/operation/merge/IteratorPageDownstreamTest.java
Java
apache-2.0
9,970
/* * 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.frauddetector.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.frauddetector.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteEventsByEventTypeRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteEventsByEventTypeRequestProtocolMarshaller implements Marshaller<Request<DeleteEventsByEventTypeRequest>, DeleteEventsByEventTypeRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("AWSHawksNestServiceFacade.DeleteEventsByEventType").serviceName("AmazonFraudDetector").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public DeleteEventsByEventTypeRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<DeleteEventsByEventTypeRequest> marshall(DeleteEventsByEventTypeRequest deleteEventsByEventTypeRequest) { if (deleteEventsByEventTypeRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<DeleteEventsByEventTypeRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, deleteEventsByEventTypeRequest); protocolMarshaller.startMarshalling(); DeleteEventsByEventTypeRequestMarshaller.getInstance().marshall(deleteEventsByEventTypeRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-frauddetector/src/main/java/com/amazonaws/services/frauddetector/model/transform/DeleteEventsByEventTypeRequestProtocolMarshaller.java
Java
apache-2.0
2,836
/* * 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.sling; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import javax.jcr.Repository; import org.apache.jackrabbit.oak.api.ContentRepository; import org.apache.jackrabbit.oak.spi.security.SecurityProvider; import org.apache.sling.jcr.api.SlingRepository; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; public class Activator implements BundleActivator, ServiceTrackerCustomizer { private BundleContext context; private ScheduledExecutorService executor; private SecurityProvider securityProvider; private ServiceTracker tracker; private final Map<ServiceReference, ServiceRegistration> jcrRepositories = new HashMap<ServiceReference, ServiceRegistration>(); private final Map<ServiceReference, ServiceRegistration> slingRepositories = new HashMap<ServiceReference, ServiceRegistration>(); //-----------------------------------------------------< BundleActivator >-- @Override public void start(BundleContext bundleContext) throws Exception { context = bundleContext; executor = Executors.newScheduledThreadPool(1); securityProvider = null; // TODO tracker = new ServiceTracker( context, ContentRepository.class.getName(), this); tracker.open(); } @Override public void stop(BundleContext bundleContext) throws Exception { tracker.close(); executor.shutdown(); } //--------------------------------------------< ServiceTrackerCustomizer >-- @Override public Object addingService(ServiceReference reference) { Object service = context.getService(reference); if (service instanceof ContentRepository) { SlingRepository repository = new SlingRepositoryImpl( (ContentRepository) service, executor, securityProvider); jcrRepositories.put(reference, context.registerService( Repository.class.getName(), repository, new Properties())); slingRepositories.put(reference, context.registerService( SlingRepository.class.getName(), repository, new Properties())); return service; } else { context.ungetService(reference); return null; } } @Override public void modifiedService(ServiceReference reference, Object service) { } @Override public void removedService(ServiceReference reference, Object service) { slingRepositories.get(reference).unregister(); jcrRepositories.get(reference).unregister(); context.ungetService(reference); } }
tteofili/jackrabbit-oak
oak-sling/src/main/java/org/apache/jackrabbit/oak/sling/Activator.java
Java
apache-2.0
3,841
/* * Copyright 1999-2101 Alibaba 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 com.alibaba.fastjson.parser; /** * @author wenshao[szujobs@hotmail.com] */ public class JSONToken { // public final static int ERROR = 1; // public final static int LITERAL_INT = 2; // public final static int LITERAL_FLOAT = 3; // public final static int LITERAL_STRING = 4; // public final static int LITERAL_ISO8601_DATE = 5; public final static int TRUE = 6; // public final static int FALSE = 7; // public final static int NULL = 8; // public final static int NEW = 9; // public final static int LPAREN = 10; // ("("), // public final static int RPAREN = 11; // (")"), // public final static int LBRACE = 12; // ("{"), // public final static int RBRACE = 13; // ("}"), // public final static int LBRACKET = 14; // ("["), // public final static int RBRACKET = 15; // ("]"), // public final static int COMMA = 16; // (","), // public final static int COLON = 17; // (":"), // public final static int IDENTIFIER = 18; // public final static int FIELD_NAME = 19; public final static int EOF = 20; public final static int SET = 21; public final static int TREE_SET = 22; public final static int UNDEFINED = 23; // undefined public static String name(int value) { switch (value) { case ERROR: return "error"; case LITERAL_INT: return "int"; case LITERAL_FLOAT: return "float"; case LITERAL_STRING: return "string"; case LITERAL_ISO8601_DATE: return "iso8601"; case TRUE: return "true"; case FALSE: return "false"; case NULL: return "null"; case NEW: return "new"; case LPAREN: return "("; case RPAREN: return ")"; case LBRACE: return "{"; case RBRACE: return "}"; case LBRACKET: return "["; case RBRACKET: return "]"; case COMMA: return ","; case COLON: return ":"; case IDENTIFIER: return "ident"; case FIELD_NAME: return "fieldName"; case EOF: return "EOF"; case SET: return "Set"; case TREE_SET: return "TreeSet"; case UNDEFINED: return "undefined"; default: return "Unkown"; } } }
xiepengchong/FactoryZxing
src/com/alibaba/fastjson/parser/JSONToken.java
Java
apache-2.0
3,656
package com.github.obourgain.elasticsearch.http.response.parser; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.elasticsearch.common.xcontent.XContentParser; import com.github.obourgain.elasticsearch.http.response.entity.Indices; import com.github.obourgain.elasticsearch.http.response.entity.ShardFailure; import com.github.obourgain.elasticsearch.http.response.entity.Shards; import lombok.Getter; @Getter public class IndicesParser { private static List<ShardFailure> failures; public static Indices parse(XContentParser parser) { Map<String, Shards> result = new HashMap<>(); try { XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { failures = ShardFailure.parse(parser); } else if (token == XContentParser.Token.START_OBJECT) { Shards shards = new Shards().parse(parser); result.put(currentFieldName, shards); } } return Indices.fromMap(result); } catch (IOException e) { throw new RuntimeException("Unable to parse source", e); } } }
obourgain/elasticsearch-http
src/main/java/com/github/obourgain/elasticsearch/http/response/parser/IndicesParser.java
Java
apache-2.0
1,496
/* * Copyright 2012 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 com.github.carlomicieli.nerdmovies.controllers; import com.github.carlomicieli.nerdmovies.services.MovieService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * @author Carlo Micieli */ @Controller @RequestMapping("/") public class HomeController { private MovieService movieService; @Autowired public HomeController(MovieService movieService) { this.movieService = movieService; } @RequestMapping(value = {"/", "/home"}, method = RequestMethod.GET) public String index(Model model) { model.addAttribute("movies", movieService.getRecentMovies(10)); return "home/index"; } @RequestMapping(value = "/about", method = RequestMethod.GET) public String about() { return "home/about"; } @RequestMapping(value = "/default", method = RequestMethod.GET) public String defaultPage() { return "home/index"; } }
CarloMicieli/spring-mvc-movies
src/main/java/com/github/carlomicieli/nerdmovies/controllers/HomeController.java
Java
apache-2.0
1,759
package com.camillepradel.movierecommender.utils; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; public class CsvToMySql { static final String pathToCsvFiles = "D:\\MovieRecommender\\src\\main\\java\\com\\camillepradel\\movierecommender\\utils\\"; static final String usersCsvFile = pathToCsvFiles + "users.csv"; static final String moviesCsvFile = pathToCsvFiles + "movies.csv"; static final String genresCsvFile = pathToCsvFiles + "genres.csv"; static final String movGenreCsvFile = pathToCsvFiles + "mov_genre.csv"; static final String ratingsCsvFile = pathToCsvFiles + "ratings.csv"; static final String friendsCsvFile = pathToCsvFiles + "friends.csv"; static final String cvsSplitBy = ","; private static void commitUsers(Connection connection) throws SQLException { System.out.println(usersCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS users (\n" + " id int(11) NOT NULL AUTO_INCREMENT,\n" + " age int(11) NOT NULL,\n" + " sex varchar(1) NOT NULL,\n" + " occupation varchar(60) NOT NULL,\n" + " zip varchar(6) NOT NULL,\n" + " PRIMARY KEY (`id`)\n" + ");"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(usersCsvFile))) { String insertQuery = "INSERT INTO users (id, age, sex, occupation, zip) VALUES (?, ?, ?, ?, ?)"; PreparedStatement insertUsers = null; try { connection.setAutoCommit(false); insertUsers = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); insertUsers.setInt(1, Integer.parseInt(values[0])); insertUsers.setInt(2, Integer.parseInt(values[1])); insertUsers.setString(3, values[2]); insertUsers.setString(4, values[3]); insertUsers.setString(5, values[4]); insertUsers.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertUsers != null) { insertUsers.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitMovies(Connection connection) throws SQLException { // movies.csv System.out.println(moviesCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS movies (\n" + " id int(11) NOT NULL AUTO_INCREMENT,\n" + " title varchar(200) NOT NULL,\n" + " date date NOT NULL,\n" + " PRIMARY KEY (`id`)\n" + ");"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(moviesCsvFile))) { String insertQuery = "INSERT INTO movies (id, title, date) VALUES (?, ?, ?)"; PreparedStatement insertMovies = null; try { connection.setAutoCommit(false); insertMovies = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int movieId = Integer.parseInt(values[0]); String title = String.join(",", Arrays.copyOfRange(values, 1, values.length - 1)); Date date = new Date(Long.parseLong(values[values.length - 1]) * 1000); insertMovies.setInt(1, movieId); insertMovies.setString(2, title); insertMovies.setDate(3, date); insertMovies.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertMovies != null) { insertMovies.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitGenres(Connection connection) throws SQLException { // genres.csv System.out.println(genresCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS genres (\n" + " name varchar(60) NOT NULL,\n" + " id int(11) NOT NULL AUTO_INCREMENT,\n" + " PRIMARY KEY (`id`)\n" + ");"); // necessary to make mySQL accept 0 as a valid id value for genre unknown statement.execute("SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(genresCsvFile))) { String insertQuery = "INSERT INTO genres (name, id) VALUES (?, ?)"; PreparedStatement insertGenres = null; try { connection.setAutoCommit(false); insertGenres = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); String name = values[0]; int genreId = Integer.parseInt(values[1]); insertGenres.setString(1, name); insertGenres.setInt(2, genreId); insertGenres.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertGenres != null) { insertGenres.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitMovieGenre(Connection connection) throws SQLException { // mov_genre.csv System.out.println(movGenreCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS movie_genre (\n" + " movie_id int(11) NOT NULL,\n" + " genre_id int(11) NOT NULL,\n" + " KEY movie_id (movie_id),\n" + " KEY genre_id (genre_id)\n" + ");"); statement.executeUpdate("ALTER TABLE movie_genre\n" + " ADD CONSTRAINT movie_genre_to_movie FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE movie_genre\n" + " ADD CONSTRAINT movie_genre_to_genre FOREIGN KEY (genre_id) REFERENCES genres(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(movGenreCsvFile))) { String insertQuery = "INSERT INTO movie_genre (movie_id, genre_id) VALUES (?, ?)"; PreparedStatement insertMovieGenre = null; try { connection.setAutoCommit(false); insertMovieGenre = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int movieId = Integer.parseInt(values[0]); int genreId = Integer.parseInt(values[1]); insertMovieGenre.setInt(1, movieId); insertMovieGenre.setInt(2, genreId); insertMovieGenre.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertMovieGenre != null) { insertMovieGenre.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitRatings(Connection connection) throws SQLException { // ratings.csv System.out.println(ratingsCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS ratings (\n" + " user_id int(11) NOT NULL,\n" + " movie_id int(11) NOT NULL,\n" + " rating int(11) NOT NULL,\n" + " date date NOT NULL,\n" + " KEY user_id (user_id),\n" + " KEY movie_id (movie_id)\n" + ");"); statement.executeUpdate("ALTER TABLE ratings\n" + " ADD CONSTRAINT ratings_to_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE ratings\n" + " ADD CONSTRAINT ratings_to_movie FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE ratings\n" + " ADD UNIQUE unique_index(user_id, movie_id);\n"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(ratingsCsvFile))) { String insertQuery = "INSERT INTO ratings (user_id, movie_id, rating, date) VALUES (?, ?, ?, ?)"; PreparedStatement insertRatings = null; try { connection.setAutoCommit(false); insertRatings = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int userId = Integer.parseInt(values[0]); int movieId = Integer.parseInt(values[1]); int ratingValue = Integer.parseInt(values[2]); Date date = new Date(Long.parseLong(values[3]) * 1000); insertRatings.setInt(1, userId); insertRatings.setInt(2, movieId); insertRatings.setInt(3, ratingValue); insertRatings.setDate(4, date); insertRatings.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertRatings != null) { insertRatings.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } private static void commitFriends(Connection connection) throws SQLException { // friends.csv System.out.println(friendsCsvFile); // create table Statement statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS friends (\n" + " user1_id int(11) NOT NULL,\n" + " user2_id int(11) NOT NULL,\n" + " KEY user1_id (user1_id),\n" + " KEY user2_id (user2_id)\n" + ");"); statement.executeUpdate("ALTER TABLE friends\n" + " ADD CONSTRAINT friends_to_user1 FOREIGN KEY (user1_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); statement.executeUpdate("ALTER TABLE friends\n" + " ADD CONSTRAINT friends_to_user2 FOREIGN KEY (user2_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE;\n"); // populate table try (BufferedReader br = new BufferedReader(new FileReader(friendsCsvFile))) { String insertQuery = "INSERT INTO friends (user1_id, user2_id) VALUES (?, ?)"; PreparedStatement insertFriends = null; try { connection.setAutoCommit(false); insertFriends = connection.prepareStatement(insertQuery); String line; br.readLine(); // skip first line while ((line = br.readLine()) != null) { String[] values = line.split(cvsSplitBy); int user1Id = Integer.parseInt(values[0]); int user2Id = Integer.parseInt(values[1]); insertFriends.setInt(1, user1Id); insertFriends.setInt(2, user2Id); insertFriends.executeUpdate(); } connection.commit(); } catch (SQLException e) { e.printStackTrace(); if (connection != null) { try { System.err.print("Transaction is being rolled back"); connection.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } } } finally { if (insertFriends != null) { insertFriends.close(); } connection.setAutoCommit(true); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { // load JDBC driver try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } // db connection info String url = "jdbc:mysql://localhost:3306" + "?zeroDateTimeBehavior=convertToNull&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; String login = "admin"; String password = "Q86PhnJRiEa7"; Connection connection = null; try { connection = DriverManager.getConnection(url, login, password); Statement statement = connection.createStatement(); // create database statement.executeUpdate("DROP DATABASE IF EXISTS movie_recommender;"); statement.executeUpdate("CREATE DATABASE movie_recommender;"); statement.executeUpdate("USE movie_recommender;"); commitUsers(connection); commitMovies(connection); commitGenres(connection); commitMovieGenre(connection); commitRatings(connection); commitFriends(connection); } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException ignore) { // exception occured while closing connexion -> nothing else can be done } } } System.out.println("done"); } }
Camille31/MovieRecommender
src/main/java/com/camillepradel/movierecommender/utils/CsvToMySql.java
Java
apache-2.0
17,630
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.cache.query.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.geode.annotations.internal.MakeNotStatic; import org.apache.geode.cache.EntryDestroyedException; import org.apache.geode.cache.Region; import org.apache.geode.cache.query.AmbiguousNameException; import org.apache.geode.cache.query.FunctionDomainException; import org.apache.geode.cache.query.NameResolutionException; import org.apache.geode.cache.query.QueryInvocationTargetException; import org.apache.geode.cache.query.QueryService; import org.apache.geode.cache.query.TypeMismatchException; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.pdx.PdxInstance; import org.apache.geode.pdx.PdxSerializationException; import org.apache.geode.pdx.internal.InternalPdxInstance; import org.apache.geode.pdx.internal.PdxString; /** * Class Description * * @version $Revision: 1.1 $ */ public class CompiledOperation extends AbstractCompiledValue { private final CompiledValue receiver; // may be null if implicit to scope private final String methodName; private final List args; @MakeNotStatic private static final ConcurrentMap cache = new ConcurrentHashMap(); // receiver is an ID or PATH that contains the operation name public CompiledOperation(CompiledValue receiver, String methodName, List args) { this.receiver = receiver; this.methodName = methodName; this.args = args; } @Override public List getChildren() { List list = new ArrayList(); if (this.receiver != null) { list.add(this.receiver); } list.addAll(this.args); return list; } public String getMethodName() { return this.methodName; } public List getArguments() { return this.args; } @Override public int getType() { return METHOD_INV; } public CompiledValue getReceiver(ExecutionContext cxt) { // receiver may be cached in execution context if (this.receiver == null && cxt != null) { return (CompiledValue) cxt.cacheGet(this); } return this.receiver; } @Override public boolean hasIdentifierAtLeafNode() { if (this.receiver.getType() == Identifier) { return true; } else { return this.receiver.hasIdentifierAtLeafNode(); } } @Override public CompiledValue getReceiver() { return this.getReceiver(null); } @Override public Object evaluate(ExecutionContext context) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException { CompiledValue rcvr = getReceiver(context); Object result; Object evalRcvr; if (rcvr == null) { // must be intended as implicit iterator operation // see if it's an implicit operation name RuntimeIterator rcvrItr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); evalRcvr = rcvrItr.evaluate(context); /* * // evaluate on current iteration of collection if (rcvrItr != null) { result = * eval0(rcvrItr.evaluate(context), rcvrItr.getElementType().resolveClass(), context); } * * // function call: no functions implemented except keywords in the grammar throw new * TypeMismatchException("Could not resolve method named 'xyz'") */ } else { // if not null, then explicit receiver evalRcvr = rcvr.evaluate(context); } // short circuit null immediately if (evalRcvr == null) { return QueryService.UNDEFINED; } if (context.isCqQueryContext() && evalRcvr instanceof Region.Entry) { Region.Entry re = (Region.Entry) evalRcvr; if (re.isDestroyed()) { return QueryService.UNDEFINED; } try { evalRcvr = re.getValue(); } catch (EntryDestroyedException ede) { // Even though isDestory() check is made, the entry could // throw EntryDestroyedException if the value becomes null. return QueryService.UNDEFINED; } } // check if the receiver is the iterator, in which // case we resolve the method on the constraint rather // than the runtime type of the receiver Class resolveClass = null; // commented out because we currently always resolve the method // on the runtime types // CompiledValue rcvrVal = rcvrPath.getReceiver(); // if (rcvrVal.getType() == ID) // { // CompiledValue resolvedID = context.resolve(((CompiledID)rcvrVal).getId()); // if (resolvedID.getType() == ITERATOR) // { // resolveClass = ((RuntimeIterator)resolvedID).getBaseCollection().getConstraint(); // } // } // if (resolveClass == null) if (evalRcvr instanceof PdxInstance) { String className = ((PdxInstance) evalRcvr).getClassName(); try { resolveClass = InternalDataSerializer.getCachedClass(className); } catch (ClassNotFoundException cnfe) { throw new QueryInvocationTargetException(cnfe); } } else if (evalRcvr instanceof PdxString) { resolveClass = String.class; } else { resolveClass = evalRcvr.getClass(); } result = eval0(evalRcvr, resolveClass, context); // } // check for PR substitution // check for BucketRegion substitution PartitionedRegion pr = context.getPartitionedRegion(); if (pr != null && (result instanceof Region)) { if (pr.getFullPath().equals(((Region) result).getFullPath())) { result = context.getBucketRegion(); } } return result; } @Override public Set computeDependencies(ExecutionContext context) throws TypeMismatchException, AmbiguousNameException, NameResolutionException { List args = this.args; Iterator i = args.iterator(); while (i.hasNext()) { context.addDependencies(this, ((CompiledValue) i.next()).computeDependencies(context)); } CompiledValue rcvr = getReceiver(context); if (rcvr == null) // implicit iterator operation { // see if it's an implicit operation name RuntimeIterator rcvrItr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); if (rcvrItr == null) { // no receiver resolved // function call: no functions implemented except keywords in the grammar throw new TypeMismatchException( String.format("Could not resolve method named ' %s '", this.methodName)); } // cache the receiver so we don't have to resolve it again context.cachePut(this, rcvrItr); return context.addDependency(this, rcvrItr); } // receiver is explicit return context.addDependencies(this, rcvr.computeDependencies(context)); } @edu.umd.cs.findbugs.annotations.SuppressWarnings( value = "RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED", justification = "Does not matter if the methodDispatch that isn't stored in the map is used") private Object eval0(Object receiver, Class resolutionType, ExecutionContext context) throws TypeMismatchException, FunctionDomainException, NameResolutionException, QueryInvocationTargetException { if (receiver == null || receiver == QueryService.UNDEFINED) return QueryService.UNDEFINED; List args = new ArrayList(); List argTypes = new ArrayList(); Iterator i = this.args.iterator(); while (i.hasNext()) { CompiledValue arg = (CompiledValue) i.next(); Object o = arg.evaluate(context); // undefined arg produces undefines method result if (o == QueryService.UNDEFINED) return QueryService.UNDEFINED; args.add(o); // pass in null for the type if the runtime value is null if (o == null) argTypes.add(null); // commented out because we currently always use the runtime type for args // else if (arg.getType() == Identifier) // { // CompiledValue resolved = context.resolve(((CompiledID)arg).getId()); // if (resolved != null && resolved.getType() == ITERATOR) // argTypes.add(((RuntimeIterator)resolved).getBaseCollection().getConstraint()); // else // argTypes.add(o.getClass()); // } else argTypes.add(o.getClass()); // otherwise use the runtime type } // see if in cache MethodDispatch methodDispatch; List key = Arrays.asList(new Object[] {resolutionType, this.methodName, argTypes}); methodDispatch = (MethodDispatch) CompiledOperation.cache.get(key); if (methodDispatch == null) { try { methodDispatch = new MethodDispatch(context.getCache().getQueryService().getMethodInvocationAuthorizer(), resolutionType, this.methodName, argTypes); } catch (NameResolutionException nre) { if (!org.apache.geode.cache.query.Struct.class.isAssignableFrom(resolutionType) && (DefaultQueryService.QUERY_HETEROGENEOUS_OBJECTS || DefaultQueryService.TEST_QUERY_HETEROGENEOUS_OBJECTS)) { return QueryService.UNDEFINED; } else { throw nre; } } // cache CompiledOperation.cache.putIfAbsent(key, methodDispatch); } if (receiver instanceof InternalPdxInstance) { try { receiver = ((InternalPdxInstance) receiver).getCachedObject(); } catch (PdxSerializationException ex) { throw new QueryInvocationTargetException(ex); } } else if (receiver instanceof PdxString) { receiver = ((PdxString) receiver).toString(); } return methodDispatch.invoke(receiver, args); } // Asif :Function for generating from clause @Override public void generateCanonicalizedExpression(StringBuilder clauseBuffer, ExecutionContext context) throws AmbiguousNameException, TypeMismatchException, NameResolutionException { // Asif: if the method name starts with getABC & argument list is empty // then canonicalize it to aBC int len; if (this.methodName.startsWith("get") && (len = this.methodName.length()) > 3 && (this.args == null || this.args.isEmpty())) { clauseBuffer.insert(0, len > 4 ? this.methodName.substring(4) : ""); clauseBuffer.insert(0, Character.toLowerCase(this.methodName.charAt(3))); } else if (this.args == null || this.args.isEmpty()) { clauseBuffer.insert(0, "()").insert(0, this.methodName); } else { // The method contains arguments which need to be canonicalized clauseBuffer.insert(0, ')'); CompiledValue cv = null; for (int j = this.args.size(); j > 0;) { cv = (CompiledValue) this.args.get(--j); cv.generateCanonicalizedExpression(clauseBuffer, context); clauseBuffer.insert(0, ','); } clauseBuffer.deleteCharAt(0).insert(0, '(').insert(0, this.methodName); } clauseBuffer.insert(0, '.'); CompiledValue rcvr = this.receiver; if (rcvr == null) { // must be intended as implicit iterator operation // see if it's an implicit operation name. The receiver will now be RuntimeIterator rcvr = context.resolveImplicitOperationName(this.methodName, this.args.size(), true); } rcvr.generateCanonicalizedExpression(clauseBuffer, context); } }
PurelyApplied/geode
geode-core/src/main/java/org/apache/geode/cache/query/internal/CompiledOperation.java
Java
apache-2.0
12,213
package com.turlir.abakgists.allgists.view.listing; import androidx.recyclerview.widget.RecyclerView; import android.view.View; abstract class ModelViewHolder<T> extends RecyclerView.ViewHolder { ModelViewHolder(View itemView) { super(itemView); } abstract void bind(T model); }
iljaosintsev/Apress-Gists
app/src/main/java/com/turlir/abakgists/allgists/view/listing/ModelViewHolder.java
Java
apache-2.0
305
package com.zuoqing.demo.entity; /** * http 请求返回的最外层对象 */ public class Result<T> { private Integer code; private String msg; private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
zuoqing135du/SpringBoot
src/main/java/com/zuoqing/demo/entity/Result.java
Java
apache-2.0
569
/* * 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 libthrift091; public interface TEnum { public int getValue(); }
XiaoMi/galaxy-sdk-java
galaxy-thrift-api/src/main/java/libthrift091/TEnum.java
Java
apache-2.0
880
/* * Copyright to 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.rioproject.tools.cli; import java.io.BufferedReader; import java.io.PrintStream; /** * Define plugin interface for CLI option handlers. An OptionHandler is * responsible for providing a option, or activity, that will be used through * the CLI. * * @author Dennis Reedy */ public interface OptionHandler { /** * Process the option. * * @param input Parameters for the option, may be null * @param br An optional BufferdReader, used if the option requires input. * if this is null, the option handler may create a BufferedReader to * handle the input * @param out The PrintStream to use if the option prints results or * choices for the user. Must not be null * * @return The result of the action. */ String process(String input, BufferedReader br, PrintStream out); /** * Get the usage of the command * * @return Command usage */ String getUsage(); }
dreedyman/Rio
rio-tools/rio-cli/src/main/java/org/rioproject/tools/cli/OptionHandler.java
Java
apache-2.0
1,583
package com.eric.drools_demo; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
54070356/sample
drools-demo/src/test/java/com/eric/drools_demo/AppTest.java
Java
apache-2.0
648
package com.cognitionis.nlp_files; import java.io.*; import java.util.regex.*; /** * * @author Héctor Llorens * @since 2011 */ public class TreebankFile extends NLPFile { public TreebankFile(String filename) { super(filename); } @Override public Boolean isWellFormatted() { int par_level = 0; try { if (super.getFile()==null) { throw new Exception("No file loaded in NLPFile object"); } BufferedReader reader = new BufferedReader(new FileReader(this.f)); try { String line = null; int linen = 0; Pattern p = Pattern.compile("[\\(\\)]"); while ((line = reader.readLine()) != null) { linen++; //System.getProperty("line.separator") if (line.matches("\\s*[^\\(\\s].*")) { throw new Exception("Treebank format error: line " + linen + " not begining with \\s*("); } Matcher m = p.matcher(line); while (m.find()) { if (m.group().equals("(")) { par_level++; } else { par_level--; if (par_level < 0) { throw new Exception("Treebank format error: par_level lower than 0"); } } } //System.out.println(linen+": "+line+" - parlevel="+ par_level); } } finally { reader.close(); } if (par_level != 0) { throw new Exception("Treebank format error: positive unbalancement, par_level=" + par_level); } } catch (Exception e) { System.err.println("Errors found ("+this.getClass().getSimpleName()+"):\n\t" + e.toString() + "\n"); if(System.getProperty("DEBUG")!=null && System.getProperty("DEBUG").equalsIgnoreCase("true")){e.printStackTrace(System.err);} return false; } return true; } public String toPlain(String filename){ // one token, one space, one token, one space... (end of sentence -> \n) return this.getFile().toString(); } }
hllorens/cognitionis-nlp-libraries
nlp-files/src/main/java/com/cognitionis/nlp_files/TreebankFile.java
Java
apache-2.0
2,385
package com.kashukov.convert; /** * Convert short to any primitive data type */ public class Short { /** * Convert short to boolean * * @param input short * @return boolean */ public static boolean shortToBoolean(short input) { return input != 0; } /** * Convert short to byte * * @param input short * @return byte */ public static byte shortToByte(short input) { return (byte) input; } /** * Convert short to byte[] * * @param input short * @return byte[] */ public static byte[] shortToByteArray(short input) { return new byte[]{ (byte) (input >>> 8), (byte) input}; } /** * Convert short to char * * @param input short * @return char */ public static char shortToChar(short input) { return (char) input; } /** * Convert short to double * * @param input short * @return double */ public static double shortToDouble(short input) { return (double) input; } /** * Convert short to float * * @param input short * @return float */ public static float shortToFloat(short input) { return (float) input; } /** * Convert short to int * * @param input short * @return int */ public static int shortToInt(short input) { return (int) input; } /** * Convert short to long * * @param input short * @return long */ public static long shortToLong(short input) { return (long) input; } /** * Convert short to String * * @param input short * @return String */ public static java.lang.String shortToString(short input) { return java.lang.Short.toString(input); } }
kashukov/convert
src/main/java/com/kashukov/convert/Short.java
Java
apache-2.0
1,895
package be.dnsbelgium.rdap.sample.parser; import be.dnsbelgium.rdap.sample.dto.Contact; import be.dnsbelgium.rdap.sample.dto.DnsSecKey; import be.dnsbelgium.rdap.sample.dto.SimpleContact; public enum WhoisKeyBlock { MAIN(), DOMAIN(), REGISTRAR(), REGISTRANT(), ADMIN(Contact.class), TECH(Contact.class), DNSSEC(), DNSSECKEY(DnsSecKey.class, true), HOST(), SIMPLE_ADMIN(SimpleContact.class), SIMPLE_TECH(SimpleContact.class); private Class repeatClass = null; private boolean hasIndexSuffix = false; WhoisKeyBlock() { } WhoisKeyBlock(Class repeatClass) { this.repeatClass = repeatClass; } WhoisKeyBlock(Class repeatClass, boolean hasIndexSuffix) { this.repeatClass = repeatClass; this.hasIndexSuffix = hasIndexSuffix; } public Class getRepeatClass() { return repeatClass; } public boolean hasIndexSuffix() { return hasIndexSuffix; } public boolean isRepeatable() { return repeatClass != null; } }
DNSBelgium/rdap-server-sample-gtld
src/main/java/be/dnsbelgium/rdap/sample/parser/WhoisKeyBlock.java
Java
apache-2.0
981
package com.github.hadoop.maven.plugin; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; /** * Writes jars. * * */ public class JarWriter { /** * Given a root directory, this writes the contents of the same as a jar file. * The path to files inside the jar are relative paths, relative to the root * directory specified. * * @param jarRootDir * Root Directory that serves as an input to writing the jars. * @param os * OutputStream to which the jar is to be packed * @throws FileNotFoundException * @throws IOException */ public void packToJar(File jarRootDir, OutputStream os) throws FileNotFoundException, IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); JarOutputStream target = new JarOutputStream(os, manifest); for (File nestedFile : jarRootDir.listFiles()) add(jarRootDir.getPath().replace("\\", "/"), nestedFile, target); target.close(); } private void add(String prefix, File source, JarOutputStream target) throws IOException { BufferedInputStream in = null; try { if (source.isDirectory()) { String name = source.getPath().replace("\\", "/"); if (!name.isEmpty()) { if (!name.endsWith("/")) name += "/"; JarEntry entry = new JarEntry(name.substring(prefix.length() + 1)); entry.setTime(source.lastModified()); target.putNextEntry(entry); target.closeEntry(); } for (File nestedFile : source.listFiles()) add(prefix, nestedFile, target); return; } String jarentryName = source.getPath().replace("\\", "/").substring( prefix.length() + 1); JarEntry entry = new JarEntry(jarentryName); entry.setTime(source.lastModified()); target.putNextEntry(entry); in = new BufferedInputStream(new FileInputStream(source)); byte[] buffer = new byte[1024]; while (true) { int count = in.read(buffer); if (count == -1) break; target.write(buffer, 0, count); } target.closeEntry(); } finally { if (in != null) in.close(); } } }
akkumar/maven-hadoop
src/main/java/com/github/hadoop/maven/plugin/JarWriter.java
Java
apache-2.0
2,529
/* * 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.transfer.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum HomeDirectoryType { PATH("PATH"), LOGICAL("LOGICAL"); private String value; private HomeDirectoryType(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return HomeDirectoryType corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static HomeDirectoryType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (HomeDirectoryType enumEntry : HomeDirectoryType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
aws/aws-sdk-java
aws-java-sdk-transfer/src/main/java/com/amazonaws/services/transfer/model/HomeDirectoryType.java
Java
apache-2.0
1,790
package com.ilad.teamwork; import org.openqa.selenium.WebElement; import io.appium.java_client.android.AndroidDriver; public class TabsMenu extends AbstractTeamWork { public TabsMenu(AndroidDriver<WebElement> driver) { super(driver); } public AllProjectsPage goToProjects() { driver.findElementByXPath("//android.widget.TextView[@text='Projects']").click(); return new AllProjectsPage(driver); } }
Solomon1732/infinity-labs-repository
TeamWorkAndroid/src/main/java/com/ilad/teamwork/TabsMenu.java
Java
apache-2.0
414
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202111; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Gets an {@link ActivityGroupPage} of {@link ActivityGroup} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link ActivityGroup#id}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link ActivityGroup#name}</td> * </tr> * <tr> * <td>{@code impressionsLookback}</td> * <td>{@link ActivityGroup#impressionsLookback}</td> * </tr> * <tr> * <td>{@code clicksLookback}</td> * <td>{@link ActivityGroup#clicksLookback}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link ActivityGroup#status}</td> * </tr> * </table> * * @param filterStatement a statement used to filter a set of activity groups * @return the activity groups that match the given filter * * * <p>Java class for getActivityGroupsByStatement element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="getActivityGroupsByStatement"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="filterStatement" type="{https://www.google.com/apis/ads/publisher/v202111}Statement" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "filterStatement" }) @XmlRootElement(name = "getActivityGroupsByStatement") public class ActivityGroupServiceInterfacegetActivityGroupsByStatement { protected Statement filterStatement; /** * Gets the value of the filterStatement property. * * @return * possible object is * {@link Statement } * */ public Statement getFilterStatement() { return filterStatement; } /** * Sets the value of the filterStatement property. * * @param value * allowed object is * {@link Statement } * */ public void setFilterStatement(Statement value) { this.filterStatement = value; } }
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202111/ActivityGroupServiceInterfacegetActivityGroupsByStatement.java
Java
apache-2.0
3,560
package org.ovirt.engine.ui.uicommonweb.models.vms; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.DiskImageBase; import org.ovirt.engine.core.common.businessentities.StorageType; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VolumeFormat; import org.ovirt.engine.core.common.businessentities.VolumeType; import org.ovirt.engine.core.common.businessentities.storage_domain_static; import org.ovirt.engine.core.common.businessentities.storage_domains; import org.ovirt.engine.core.common.businessentities.storage_pool; import org.ovirt.engine.core.compat.Event; import org.ovirt.engine.core.compat.EventArgs; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.IEventListener; import org.ovirt.engine.core.compat.NGuid; import org.ovirt.engine.core.compat.ObservableCollection; import org.ovirt.engine.core.compat.PropertyChangedEventArgs; import org.ovirt.engine.core.compat.StringFormat; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.ui.frontend.AsyncQuery; import org.ovirt.engine.ui.frontend.INewAsyncCallback; import org.ovirt.engine.ui.uicommonweb.Linq; import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.ListModel; import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel; import org.ovirt.engine.ui.uicommonweb.validation.IValidation; import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation; @SuppressWarnings("unused") public class ImportVmModel extends ListWithDetailsModel { boolean sameSelectedDestinationStorage = false; ArrayList<storage_domains> uniqueDestStorages; ArrayList<storage_domains> allDestStorages; storage_domains selectedDestinationStorage; HashMap<Guid, ArrayList<Guid>> templateGuidUniqueStorageDomainDic; HashMap<Guid, ArrayList<Guid>> templateGuidAllStorageDomainDic; HashMap<Guid, ArrayList<DiskImage>> templateGuidDiskImagesDic; VmImportDiskListModel importDiskListModel; ArrayList<storage_domains> allStorageDomains; int uniqueDomains; Guid templateGuid; private storage_domain_static privateSourceStorage; public storage_domain_static getSourceStorage() { return privateSourceStorage; } public void setSourceStorage(storage_domain_static value) { privateSourceStorage = value; } private storage_pool privateStoragePool; public storage_pool getStoragePool() { return privateStoragePool; } public void setStoragePool(storage_pool value) { privateStoragePool = value; } private ListModel privateDestinationStorage; public ListModel getDestinationStorage() { return privateDestinationStorage; } private void setDestinationStorage(ListModel value) { privateDestinationStorage = value; } private ListModel privateAllDestinationStorage; public ListModel getAllDestinationStorage() { return privateAllDestinationStorage; } private void setAllDestinationStorage(ListModel value) { privateAllDestinationStorage = value; } private ListModel privateCluster; public ListModel getCluster() { return privateCluster; } private void setCluster(ListModel value) { privateCluster = value; } private ListModel privateSystemDiskFormat; public ListModel getSystemDiskFormat() { return privateSystemDiskFormat; } private void setSystemDiskFormat(ListModel value) { privateSystemDiskFormat = value; } private ListModel privateDataDiskFormat; public ListModel getDataDiskFormat() { return privateDataDiskFormat; } private void setDataDiskFormat(ListModel value) { privateDataDiskFormat = value; } private EntityModel collapseSnapshots; public EntityModel getCollapseSnapshots() { return collapseSnapshots; } public void setCollapseSnapshots(EntityModel value) { this.collapseSnapshots = value; } private boolean isMissingStorages; public boolean getIsMissingStorages() { return isMissingStorages; } public void setIsMissingStorages(boolean value) { if (isMissingStorages != value) { isMissingStorages = value; OnPropertyChanged(new PropertyChangedEventArgs("IsMissingStorages")); } } private String nameAndDescription; private AsyncQuery onCollapseSnapshotsChangedFinish; public String getNameAndDescription() { return nameAndDescription; } public void setNameAndDescription(String value) { if (!StringHelper.stringsEqual(nameAndDescription, value)) { nameAndDescription = value; OnPropertyChanged(new PropertyChangedEventArgs("NameAndDescription")); } } private java.util.List<VM> problematicItems; public java.util.List<VM> getProblematicItems() { return problematicItems; } public void setProblematicItems(java.util.List<VM> value) { if (problematicItems != value) { problematicItems = value; OnPropertyChanged(new PropertyChangedEventArgs("ProblematicItems")); } } private EntityModel privateIsSingleDestStorage; public EntityModel getIsSingleDestStorage() { return privateIsSingleDestStorage; } public void setIsSingleDestStorage(EntityModel value) { privateIsSingleDestStorage = value; } private ListModel privateStorageDoamins; public ListModel getStorageDoamins() { return privateStorageDoamins; } private void setStorageDoamins(ListModel value) { privateStorageDoamins = value; } private HashMap<Guid, HashMap<Guid, Guid>> privateDiskStorageMap; public HashMap<Guid, HashMap<Guid, Guid>> getDiskStorageMap() { return privateDiskStorageMap; } public void setDiskStorageMap(HashMap<Guid, HashMap<Guid, Guid>> value) { privateDiskStorageMap = value; } @Override public void setSelectedItem(Object value) { super.setSelectedItem(value); OnEntityChanged(); } public ImportVmModel() { setProblematicItems(new ArrayList<VM>()); setCollapseSnapshots(new EntityModel()); getCollapseSnapshots().setEntity(false); getCollapseSnapshots().getPropertyChangedEvent().addListener( new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { OnCollapseSnapshotsChanged(); } }); setDestinationStorage(new ListModel()); getDestinationStorage().getSelectedItemChangedEvent().addListener( new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { DestinationStorage_SelectedItemChanged(); } }); setCluster(new ListModel()); setSystemDiskFormat(new ListModel()); setDataDiskFormat(new ListModel()); setDiskStorageMap(new HashMap<Guid, HashMap<Guid, Guid>>()); setIsSingleDestStorage(new EntityModel()); getIsSingleDestStorage().setEntity(true); setAllDestinationStorage(new ListModel()); } public void OnCollapseSnapshotsChanged(AsyncQuery _asyncQuery) { this.onCollapseSnapshotsChangedFinish = _asyncQuery; OnCollapseSnapshotsChanged(); } public void initStorageDomains() { templateGuidUniqueStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>(); templateGuidAllStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>(); templateGuidDiskImagesDic = new java.util.HashMap<Guid, ArrayList<DiskImage>>(); uniqueDomains = 0; for (Object item : getItems()) { VM vm = (VM) item; templateGuid = vm.getvmt_guid(); if (templateGuid.equals(NGuid.Empty)) { uniqueDomains++; templateGuidUniqueStorageDomainDic.put(templateGuid, null); templateGuidAllStorageDomainDic.put(templateGuid, null); } else { AsyncDataProvider.GetTemplateDiskList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { ImportVmModel importVmModel = (ImportVmModel) target; ArrayList<DiskImage> disks = (ArrayList<DiskImage>) returnValue; ArrayList<ArrayList<Guid>> allSourceStorages = new ArrayList<ArrayList<Guid>>(); for (DiskImage disk : disks) { allSourceStorages.add(disk.getstorage_ids()); } ArrayList<Guid> intersectStorageDomains = Linq.Intersection(allSourceStorages); ArrayList<Guid> unionStorageDomains = Linq.Union(allSourceStorages); uniqueDomains++; templateGuidUniqueStorageDomainDic.put(importVmModel.templateGuid, intersectStorageDomains); templateGuidAllStorageDomainDic.put(importVmModel.templateGuid, unionStorageDomains); templateGuidDiskImagesDic.put(importVmModel.templateGuid, disks); importVmModel.postInitStorageDomains(); } }), templateGuid); } } postInitStorageDomains(); } protected void postInitStorageDomains() { if (templateGuidUniqueStorageDomainDic.size() != uniqueDomains) { return; } AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.Model = this; _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object returnValue) { allStorageDomains = (ArrayList<storage_domains>) returnValue; OnCollapseSnapshotsChanged(); initDiskStorageMap(); } }; AsyncDataProvider.GetDataDomainsListByDomain(_asyncQuery, this.getSourceStorage().getId()); } private void initDiskStorageMap() { for (Object item : getItems()) { VM vm = (VM) item; for (DiskImage disk : vm.getDiskMap().values()) { if (NGuid.Empty.equals(vm.getvmt_guid())) { Guid storageId = !allDestStorages.isEmpty() ? allDestStorages.get(0).getId() : new Guid(); addToDiskStorageMap(vm.getId(), disk, storageId); } else { ArrayList<Guid> storageIds = templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid()); Guid storageId = storageIds != null ? templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid()).get(0) : new Guid(); addToDiskStorageMap(vm.getId(), disk, storageId); } } } } public void OnCollapseSnapshotsChanged() { if (this.getItems() == null || allStorageDomains == null) { return; } selectedDestinationStorage = null; sameSelectedDestinationStorage = false; uniqueDestStorages = new ArrayList<storage_domains>(); allDestStorages = new ArrayList<storage_domains>(); setIsMissingStorages(false); if (getDestinationStorage().getSelectedItem() != null) { selectedDestinationStorage = (storage_domains) getDestinationStorage().getSelectedItem(); } for (storage_domains domain : allStorageDomains) { boolean addStorage = false; if (Linq.IsDataActiveStorageDomain(domain)) { allDestStorages.add(domain); if (((Boolean) getCollapseSnapshots().getEntity()).equals(true)) { addStorage = true; } else { for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidUniqueStorageDomainDic.entrySet()) { if (NGuid.Empty.equals(keyValuePair.getKey())) { addStorage = true; } else { addStorage = false; for (Guid storageDomainId : keyValuePair.getValue()) { if (storageDomainId.equals(domain.getId())) { addStorage = true; break; } } } if (addStorage == false) { break; } } } } else { for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidAllStorageDomainDic.entrySet()) { if (!NGuid.Empty.equals(keyValuePair.getKey())) { for (Guid storageDomainId : keyValuePair.getValue()) { if (storageDomainId.equals(domain.getId())) { setIsMissingStorages(true); break; } } } } } if (addStorage) { uniqueDestStorages.add(domain); if (sameSelectedDestinationStorage == false && domain.equals(selectedDestinationStorage)) { sameSelectedDestinationStorage = true; selectedDestinationStorage = domain; } } } getAllDestinationStorage().setItems(allDestStorages); getDestinationStorage().setItems(uniqueDestStorages); if (sameSelectedDestinationStorage) { getDestinationStorage().setSelectedItem(selectedDestinationStorage); } else { getDestinationStorage().setSelectedItem(Linq.FirstOrDefault(uniqueDestStorages)); } if (getDetailModels() != null && getActiveDetailModel() instanceof VmImportDiskListModel) { VmImportDiskListModel detailModel = (VmImportDiskListModel) getActiveDetailModel(); detailModel .setCollapseSnapshots((Boolean) getCollapseSnapshots() .getEntity()); } if (onCollapseSnapshotsChangedFinish != null) { onCollapseSnapshotsChangedFinish.asyncCallback.OnSuccess( onCollapseSnapshotsChangedFinish.getModel(), null); onCollapseSnapshotsChangedFinish = null; } } @Override protected void ActiveDetailModelChanged() { super.ActiveDetailModelChanged(); OnCollapseSnapshotsChanged(); } @Override protected void InitDetailModels() { super.InitDetailModels(); importDiskListModel = new VmImportDiskListModel(); ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>(); list.add(new VmGeneralModel()); list.add(new VmImportInterfaceListModel()); list.add(importDiskListModel); list.add(new VmAppListModel()); setDetailModels(list); } public boolean Validate() { getDestinationStorage().ValidateSelectedItem( new IValidation[] { new NotEmptyValidation() }); getCluster().ValidateSelectedItem( new IValidation[] { new NotEmptyValidation() }); return getDestinationStorage().getIsValid() && getCluster().getIsValid(); } @Override protected void OnSelectedItemChanged() { super.OnSelectedItemChanged(); if (getSelectedItem() != null) { VM vm = (VM) getSelectedItem(); setNameAndDescription(StringFormat.format("%1$s%2$s", vm.getvm_name(), !StringHelper.isNullOrEmpty(vm.getvm_description()) ? " [" + vm.getvm_description() + "]" : "")); } else { setNameAndDescription(""); } } public void setItems(Iterable value) { super.setItems(value); for (Object vm : getItems()) { getDiskStorageMap().put(((VM) vm).getId(), new HashMap<Guid, Guid>()); } initStorageDomains(); } @Override protected String getListName() { return "ImportVmModel"; } public void setSelectedVMsCount(int size) { importDiskListModel.setSelectedVMsCount(((List) getItems()).size()); } storage_domains currStorageDomain = null; private void DestinationStorage_SelectedItemChanged() { storage_domains selectedStorageDomain = (storage_domains) getDestinationStorage().getSelectedItem(); List destinationStorageDomains = ((List) getDestinationStorage().getItems()); if (selectedStorageDomain == null && !destinationStorageDomains.isEmpty()) { selectedStorageDomain = (storage_domains) destinationStorageDomains.get(0); } if (currStorageDomain == null || selectedStorageDomain == null || !currStorageDomain.getQueryableId().equals(selectedStorageDomain.getQueryableId())) { currStorageDomain = selectedStorageDomain; UpdateImportWarnings(); } } public void DestinationStorage_SelectedItemChanged(DiskImage disk, String storageDomainName) { VM item = (VM) getSelectedItem(); addToDiskStorageMap(item.getId(), disk, getStorageDomainByName(storageDomainName).getId()); } public void addToDiskStorageMap(Guid vmId, DiskImage disk, Guid storageId) { HashMap<Guid, Guid> vmDiskStorageMap = getDiskStorageMap().get(vmId); vmDiskStorageMap.put(disk.getId(), storageId); } private storage_domains getStorageDomainByName(String storageDomainName) { storage_domains storage = null; for (Object storageDomain : getDestinationStorage().getItems()) { storage = (storage_domains) storageDomain; if (storageDomainName.equals(storage.getstorage_name())) { break; } } return storage; } @Override protected void ItemsChanged() { super.ItemsChanged(); UpdateImportWarnings(); } public VmImportDiskListModel getImportDiskListModel() { return importDiskListModel; } private void UpdateImportWarnings() { // Clear problematic state. getProblematicItems().clear(); if (getItems() == null) { return; } storage_domains destinationStorage = (storage_domains) getDestinationStorage() .getSelectedItem(); for (Object item : getItems()) { VM vm = (VM) item; if (vm.getDiskMap() != null) { for (java.util.Map.Entry<String, DiskImage> pair : vm .getDiskMap().entrySet()) { DiskImage disk = pair.getValue(); if (disk.getvolume_type() == VolumeType.Sparse && disk.getvolume_format() == VolumeFormat.RAW && destinationStorage != null && (destinationStorage.getstorage_type() == StorageType.ISCSI || destinationStorage .getstorage_type() == StorageType.FCP)) { getProblematicItems().add(vm); } } } } // Decide what to do with the CollapseSnapshots option. if (problematicItems.size() > 0) { if (problematicItems.size() == Linq.Count(getItems())) { // All items are problematic. getCollapseSnapshots().setIsChangable(false); getCollapseSnapshots().setEntity(true); getCollapseSnapshots() .setMessage( "Note that all snapshots will be collapsed due to different storage types"); } else { // Some items are problematic. getCollapseSnapshots() .setMessage( "Use a separate import operation for the marked VMs or\nApply \"Collapse Snapshots\" for all VMs"); } } else { // No problematic items. getCollapseSnapshots().setIsChangable(true); getCollapseSnapshots().setMessage(null); } } public void VolumeType_SelectedItemChanged(DiskImage disk, VolumeType tempVolumeType) { for (Object item : getItems()) { VM vm = (VM) item; java.util.HashMap<String, DiskImageBase> diskDictionary = new java.util.HashMap<String, DiskImageBase>(); for (java.util.Map.Entry<String, DiskImage> a : vm.getDiskMap() .entrySet()) { if (a.getValue().getQueryableId().equals(disk.getQueryableId())) { a.getValue().setvolume_type(tempVolumeType); break; } } } } public ArrayList<String> getAvailableStorageDomainsByDiskId(Guid diskId) { ArrayList<String> storageDomains = null; ArrayList<Guid> storageDomainsIds = getImportDiskListModel().getAvailableStorageDomainsByDiskId(diskId); if (storageDomainsIds != null) { storageDomains = new ArrayList<String>(); for (Guid storageId : storageDomainsIds) { if (Linq.IsActiveStorageDomain(getStorageById(storageId))) { storageDomains.add(getStorageNameById(storageId)); } } } if (storageDomains != null) { Collections.sort(storageDomains); } return storageDomains; } public String getStorageNameById(NGuid storageId) { String storageName = ""; for (Object storageDomain : getAllDestinationStorage().getItems()) { storage_domains storage = (storage_domains) storageDomain; if (storage.getId().equals(storageId)) { storageName = storage.getstorage_name(); } } return storageName; } public storage_domains getStorageById(Guid storageId) { for (storage_domains storage : allDestStorages) { if (storage.getId().equals(storageId)) { return storage; } } return null; } }
Dhandapani/gluster-ovirt
frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/ImportVmModel.java
Java
apache-2.0
23,592
package com.pengrad.telegrambot.request; import com.pengrad.telegrambot.response.BaseResponse; /** * Mirco Ianese * 07 December 2021 */ public class UnbanChatSenderChat extends BaseRequest<UnbanChatSenderChat, BaseResponse> { public UnbanChatSenderChat(Object chatId, long sender_chat_id) { super(BaseResponse.class); add("chat_id", chatId).add("sender_chat_id", sender_chat_id); } }
pengrad/java-telegram-bot-api
library/src/main/java/com/pengrad/telegrambot/request/UnbanChatSenderChat.java
Java
apache-2.0
415
/* * Copyright (c) 2017-2018. 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 li.allan.easycache.config; import li.allan.easycache.CacheKeyGenerator; import li.allan.easycache.LocalCacheConfig; /** * @author lialun */ public class ConfigProperties { private LocalCacheConfig localCacheConfig; private CacheKeyGenerator cacheKeyGenerator; public LocalCacheConfig getLocalCacheConfig() { return localCacheConfig; } public void setLocalCacheConfig(LocalCacheConfig localCacheConfig) { this.localCacheConfig = localCacheConfig; } public CacheKeyGenerator getCacheKeyGenerator() { return cacheKeyGenerator; } public void setCacheKeyGenerator(CacheKeyGenerator cacheKeyGenerator) { this.cacheKeyGenerator = cacheKeyGenerator; } }
lialun/EasyCache
easycache/src/main/java/li/allan/easycache/config/ConfigProperties.java
Java
apache-2.0
1,360
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.appsync.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/appsync-2017-07-25/GetFunction" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetFunctionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The <code>Function</code> object. * </p> */ private FunctionConfiguration functionConfiguration; /** * <p> * The <code>Function</code> object. * </p> * * @param functionConfiguration * The <code>Function</code> object. */ public void setFunctionConfiguration(FunctionConfiguration functionConfiguration) { this.functionConfiguration = functionConfiguration; } /** * <p> * The <code>Function</code> object. * </p> * * @return The <code>Function</code> object. */ public FunctionConfiguration getFunctionConfiguration() { return this.functionConfiguration; } /** * <p> * The <code>Function</code> object. * </p> * * @param functionConfiguration * The <code>Function</code> object. * @return Returns a reference to this object so that method calls can be chained together. */ public GetFunctionResult withFunctionConfiguration(FunctionConfiguration functionConfiguration) { setFunctionConfiguration(functionConfiguration); 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 (getFunctionConfiguration() != null) sb.append("FunctionConfiguration: ").append(getFunctionConfiguration()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetFunctionResult == false) return false; GetFunctionResult other = (GetFunctionResult) obj; if (other.getFunctionConfiguration() == null ^ this.getFunctionConfiguration() == null) return false; if (other.getFunctionConfiguration() != null && other.getFunctionConfiguration().equals(this.getFunctionConfiguration()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFunctionConfiguration() == null) ? 0 : getFunctionConfiguration().hashCode()); return hashCode; } @Override public GetFunctionResult clone() { try { return (GetFunctionResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-appsync/src/main/java/com/amazonaws/services/appsync/model/GetFunctionResult.java
Java
apache-2.0
4,022
/* * Copyright 2008-2010 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 groovy.lang; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Field annotation to simplify lazy initialization. * <p> * Example usage without any special modifiers just defers initialization until the first call but is not thread-safe: * <pre> * {@code @Lazy} T x * </pre> * becomes * <pre> * private T $x * * T getX() { * if ($x != null) * return $x * else { * $x = new T() * return $x * } * } * </pre> * * If the field is declared volatile then initialization will be synchronized using * the <a href="http://en.wikipedia.org/wiki/Double-checked_locking">double-checked locking</a> pattern as shown here: * * <pre> * {@code @Lazy} volatile T x * </pre> * becomes * <pre> * private volatile T $x * * T getX() { * T $x_local = $x * if ($x_local != null) * return $x_local * else { * synchronized(this) { * if ($x == null) { * $x = new T() * } * return $x * } * } * } * </pre> * * By default a field will be initialized by calling its default constructor. * * If the field has an initial value expression then this expression will be used instead of calling the default constructor. * In particular, it is possible to use closure <code>{ ... } ()</code> syntax as follows: * * <pre> * {@code @Lazy} T x = { [1, 2, 3] } () * </pre> * becomes * <pre> * private T $x * * T getX() { * T $x_local = $x * if ($x_local != null) * return $x_local * else { * synchronized(this) { * if ($x == null) { * $x = { [1, 2, 3] } () * } * return $x * } * } * } * </pre> * <p> * <code>@Lazy(soft=true)</code> will use a soft reference instead of the field and use the above rules each time re-initialization is required. * <p> * If the <code>soft</code> flag for the annotation is not set but the field is static, then * the <a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom">initialization on demand holder idiom</a> is * used as follows: * <pre> * {@code @Lazy} static FieldType field * {@code @Lazy} static Date date1 * {@code @Lazy} static Date date2 = { new Date().updated(year: 2000) }() * {@code @Lazy} static Date date3 = new GregorianCalendar(2009, Calendar.JANUARY, 1).time * </pre> * becomes these methods and inners classes within the class containing the above definitions: * <pre> * private static class FieldTypeHolder_field { * private static final FieldType INSTANCE = new FieldType() * } * * private static class DateHolder_date1 { * private static final Date INSTANCE = new Date() * } * * private static class DateHolder_date2 { * private static final Date INSTANCE = { new Date().updated(year: 2000) }() * } * * private static class DateHolder_date3 { * private static final Date INSTANCE = new GregorianCalendar(2009, Calendar.JANUARY, 1).time * } * * static FieldType getField() { * return FieldTypeHolder_field.INSTANCE * } * * static Date getDate1() { * return DateHolder_date1.INSTANCE * } * * static Date getDate2() { * return DateHolder_date2.INSTANCE * } * * static Date getDate3() { * return DateHolder_date3.INSTANCE * } * </pre> * * @author Alex Tkachman * @author Paul King */ @java.lang.annotation.Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.FIELD}) @GroovyASTTransformationClass("org.codehaus.groovy.transform.LazyASTTransformation") public @interface Lazy { /** * @return if field should be soft referenced instead of hard referenced */ boolean soft () default false; }
Selventa/model-builder
tools/groovy/src/src/main/groovy/lang/Lazy.java
Java
apache-2.0
4,644
/* * Copyright 2013-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.event.listener; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import com.facebook.buck.artifact_cache.ArtifactCacheConnectEvent; import com.facebook.buck.artifact_cache.CacheResult; import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent; import com.facebook.buck.event.CommandEvent; import com.facebook.buck.artifact_cache.HttpArtifactCacheEventFetchData; import com.facebook.buck.event.ArtifactCompressionEvent; import com.facebook.buck.event.BuckEventBus; import com.facebook.buck.event.BuckEventBusFactory; import com.facebook.buck.event.ChromeTraceEvent; import com.facebook.buck.event.CompilerPluginDurationEvent; import com.facebook.buck.event.PerfEventId; import com.facebook.buck.event.SimplePerfEvent; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.jvm.java.AnnotationProcessingEvent; import com.facebook.buck.jvm.java.tracing.JavacPhaseEvent; import com.facebook.buck.log.InvocationInfo; import com.facebook.buck.model.BuildId; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.rules.BuildEvent; import com.facebook.buck.rules.BuildRuleEvent; import com.facebook.buck.rules.BuildRuleKeys; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.BuildRuleStatus; import com.facebook.buck.rules.BuildRuleSuccessType; import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer; import com.facebook.buck.rules.FakeBuildRule; import com.facebook.buck.rules.RuleKey; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.step.StepEvent; import com.facebook.buck.timing.Clock; import com.facebook.buck.timing.FakeClock; import com.facebook.buck.timing.IncrementingFakeClock; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.ObjectMappers; import com.facebook.buck.util.perf.PerfStatsTracking; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.gson.Gson; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; public class ChromeTraceBuildListenerTest { private static final long TIMESTAMP_NANOS = 1409702151000000000L; private static final String EXPECTED_DIR = "buck-out/log/2014-09-02_23h55m51s_no_sub_command_BUILD_ID/"; @Rule public TemporaryFolder tmpDir = new TemporaryFolder(); private InvocationInfo invocationInfo; @Before public void setUp() throws IOException { invocationInfo = InvocationInfo.builder() .setTimestampMillis(TimeUnit.NANOSECONDS.toMillis(TIMESTAMP_NANOS)) .setBuckLogDir(tmpDir.getRoot().toPath().resolve("buck-out/log")) .setBuildId(new BuildId("BUILD_ID")) .setSubCommand("no_sub_command") .setIsDaemon(false) .setSuperConsoleEnabled(false) .build(); } @Test public void testDeleteFiles() throws IOException { ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath()); String tracePath = invocationInfo.getLogDirectoryPath().resolve("build.trace").toString(); File traceFile = new File(tracePath); projectFilesystem.createParentDirs(tracePath); traceFile.createNewFile(); traceFile.setLastModified(0); for (int i = 0; i < 10; ++i) { File oldResult = new File( String.format("%s/build.100%d.trace", invocationInfo.getLogDirectoryPath(), i)); oldResult.createNewFile(); oldResult.setLastModified(TimeUnit.SECONDS.toMillis(i)); } ChromeTraceBuildListener listener = new ChromeTraceBuildListener( projectFilesystem, invocationInfo, new FakeClock(TIMESTAMP_NANOS), ObjectMappers.newDefaultInstance(), Locale.US, TimeZone.getTimeZone("America/Los_Angeles"), /* tracesToKeep */ 3, false); listener.outputTrace(invocationInfo.getBuildId()); ImmutableList<String> files = FluentIterable. from(Arrays.asList(projectFilesystem.listFiles(invocationInfo.getLogDirectoryPath()))). filter(input -> input.toString().endsWith(".trace")). transform(File::getName). toList(); assertEquals(4, files.size()); assertEquals( ImmutableSortedSet.of( "build.trace", "build.1009.trace", "build.1008.trace", "build.2014-09-02.16-55-51.BUILD_ID.trace"), ImmutableSortedSet.copyOf(files)); } @Test public void testBuildJson() throws IOException { ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath()); ObjectMapper mapper = ObjectMappers.newDefaultInstance(); BuildId buildId = new BuildId("ChromeTraceBuildListenerTestBuildId"); ChromeTraceBuildListener listener = new ChromeTraceBuildListener( projectFilesystem, invocationInfo, new FakeClock(TIMESTAMP_NANOS), mapper, Locale.US, TimeZone.getTimeZone("America/Los_Angeles"), /* tracesToKeep */ 42, false); BuildTarget target = BuildTargetFactory.newInstance("//fake:rule"); FakeBuildRule rule = new FakeBuildRule( target, new SourcePathResolver( new BuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()) ), ImmutableSortedSet.of()); RuleKey ruleKey = new RuleKey("abc123"); String stepShortName = "fakeStep"; String stepDescription = "I'm a Fake Step!"; UUID stepUuid = UUID.randomUUID(); ImmutableSet<BuildTarget> buildTargets = ImmutableSet.of(target); Iterable<String> buildArgs = Iterables.transform(buildTargets, Object::toString); Clock fakeClock = new IncrementingFakeClock(TimeUnit.MILLISECONDS.toNanos(1)); BuckEventBus eventBus = BuckEventBusFactory.newInstance(fakeClock, buildId); eventBus.register(listener); CommandEvent.Started commandEventStarted = CommandEvent.started( "party", ImmutableList.of("arg1", "arg2"), /* isDaemon */ true); eventBus.post(commandEventStarted); eventBus.post(new PerfStatsTracking.MemoryPerfStatsEvent( /* freeMemoryBytes */ 1024 * 1024L, /* totalMemoryBytes */ 3 * 1024 * 1024L, /* timeSpentInGcMs */ -1, /* currentMemoryBytesUsageByPool */ ImmutableMap.of("flower", 42L * 1024 * 1024))); ArtifactCacheConnectEvent.Started artifactCacheConnectEventStarted = ArtifactCacheConnectEvent.started(); eventBus.post(artifactCacheConnectEventStarted); eventBus.post(ArtifactCacheConnectEvent.finished(artifactCacheConnectEventStarted)); BuildEvent.Started buildEventStarted = BuildEvent.started(buildArgs); eventBus.post(buildEventStarted); HttpArtifactCacheEvent.Started artifactCacheEventStarted = HttpArtifactCacheEvent.newFetchStartedEvent(ruleKey); eventBus.post(artifactCacheEventStarted); eventBus.post( HttpArtifactCacheEvent.newFinishedEventBuilder(artifactCacheEventStarted) .setFetchDataBuilder( HttpArtifactCacheEventFetchData.builder() .setFetchResult(CacheResult.hit("http"))) .build()); ArtifactCompressionEvent.Started artifactCompressionStartedEvent = ArtifactCompressionEvent.started( ArtifactCompressionEvent.Operation.COMPRESS, ImmutableSet.of(ruleKey)); eventBus.post(artifactCompressionStartedEvent); eventBus.post(ArtifactCompressionEvent.finished(artifactCompressionStartedEvent)); eventBus.post(BuildRuleEvent.started(rule)); eventBus.post(StepEvent.started(stepShortName, stepDescription, stepUuid)); JavacPhaseEvent.Started runProcessorsStartedEvent = JavacPhaseEvent.started( target, JavacPhaseEvent.Phase.RUN_ANNOTATION_PROCESSORS, ImmutableMap.of()); eventBus.post(runProcessorsStartedEvent); String annotationProcessorName = "com.facebook.FakeProcessor"; AnnotationProcessingEvent.Operation operation = AnnotationProcessingEvent.Operation.PROCESS; int annotationRound = 1; boolean isLastRound = false; AnnotationProcessingEvent.Started annotationProcessingEventStarted = AnnotationProcessingEvent.started( target, annotationProcessorName, operation, annotationRound, isLastRound); eventBus.post(annotationProcessingEventStarted); HttpArtifactCacheEvent.Scheduled httpScheduled = HttpArtifactCacheEvent.newStoreScheduledEvent( Optional.of("TARGET_ONE"), ImmutableSet.of(ruleKey)); HttpArtifactCacheEvent.Started httpStarted = HttpArtifactCacheEvent.newStoreStartedEvent(httpScheduled); eventBus.post(httpStarted); HttpArtifactCacheEvent.Finished httpFinished = HttpArtifactCacheEvent.newFinishedEventBuilder(httpStarted).build(); eventBus.post(httpFinished); final CompilerPluginDurationEvent.Started processingPartOneStarted = CompilerPluginDurationEvent.started( target, annotationProcessorName, "processingPartOne", ImmutableMap.of()); eventBus.post(processingPartOneStarted); eventBus.post( CompilerPluginDurationEvent.finished( processingPartOneStarted, ImmutableMap.of())); eventBus.post(AnnotationProcessingEvent.finished(annotationProcessingEventStarted)); eventBus.post( JavacPhaseEvent.finished(runProcessorsStartedEvent, ImmutableMap.of())); eventBus.post(StepEvent.finished( StepEvent.started(stepShortName, stepDescription, stepUuid), 0)); eventBus.post( BuildRuleEvent.finished( rule, BuildRuleKeys.of(ruleKey), BuildRuleStatus.SUCCESS, CacheResult.miss(), Optional.of(BuildRuleSuccessType.BUILT_LOCALLY), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty())); try (final SimplePerfEvent.Scope scope1 = SimplePerfEvent.scope( eventBus, PerfEventId.of("planning"), ImmutableMap.<String, Object>of("nefarious", "true"))) { try (final SimplePerfEvent.Scope scope2 = SimplePerfEvent.scope( eventBus, PerfEventId.of("scheming"))) { scope2.appendFinishedInfo("success", "false"); } } eventBus.post(BuildEvent.finished(buildEventStarted, 0)); eventBus.post(CommandEvent.finished(commandEventStarted, /* exitCode */ 0)); listener.outputTrace(new BuildId("BUILD_ID")); File resultFile = new File(tmpDir.getRoot(), "buck-out/log/build.trace"); List<ChromeTraceEvent> originalResultList = mapper.readValue( resultFile, new TypeReference<List<ChromeTraceEvent>>() {}); List<ChromeTraceEvent> resultListCopy = new ArrayList<>(); resultListCopy.addAll(originalResultList); ImmutableMap<String, String> emptyArgs = ImmutableMap.of(); assertNextResult( resultListCopy, "process_name", ChromeTraceEvent.Phase.METADATA, ImmutableMap.of("name", "buck")); assertNextResult( resultListCopy, "party", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of("command_args", "arg1 arg2")); assertNextResult( resultListCopy, "memory", ChromeTraceEvent.Phase.COUNTER, ImmutableMap.of( "used_memory_mb", "2", "free_memory_mb", "1", "total_memory_mb", "3", "time_spent_in_gc_sec", "0", "pool_flower_mb", "42")); assertNextResult( resultListCopy, "artifact_connect", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "artifact_connect", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "build", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "http_artifact_fetch", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of("rule_key", "abc123")); assertNextResult( resultListCopy, "http_artifact_fetch", ChromeTraceEvent.Phase.END, ImmutableMap.of( "rule_key", "abc123", "success", "true", "cache_result", "HTTP_HIT")); assertNextResult( resultListCopy, "artifact_compress", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of("rule_key", "abc123")); assertNextResult( resultListCopy, "artifact_compress", ChromeTraceEvent.Phase.END, ImmutableMap.of("rule_key", "abc123")); // BuildRuleEvent.Started assertNextResult( resultListCopy, "//fake:rule", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of()); assertNextResult( resultListCopy, "fakeStep", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "run annotation processors", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "com.facebook.FakeProcessor.process", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "http_artifact_store", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of( "rule_key", "abc123")); assertNextResult( resultListCopy, "http_artifact_store", ChromeTraceEvent.Phase.END, ImmutableMap.of( "success", "true", "rule_key", "abc123")); assertNextResult( resultListCopy, "processingPartOne", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "processingPartOne", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "com.facebook.FakeProcessor.process", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "run annotation processors", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "fakeStep", ChromeTraceEvent.Phase.END, ImmutableMap.of( "description", "I'm a Fake Step!", "exit_code", "0")); assertNextResult( resultListCopy, "//fake:rule", ChromeTraceEvent.Phase.END, ImmutableMap.of( "cache_result", "miss", "success_type", "BUILT_LOCALLY")); assertNextResult( resultListCopy, "planning", ChromeTraceEvent.Phase.BEGIN, ImmutableMap.of("nefarious", "true")); assertNextResult( resultListCopy, "scheming", ChromeTraceEvent.Phase.BEGIN, emptyArgs); assertNextResult( resultListCopy, "scheming", ChromeTraceEvent.Phase.END, ImmutableMap.of("success", "false")); assertNextResult( resultListCopy, "planning", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "build", ChromeTraceEvent.Phase.END, emptyArgs); assertNextResult( resultListCopy, "party", ChromeTraceEvent.Phase.END, ImmutableMap.of( "command_args", "arg1 arg2", "daemon", "true")); assertEquals(0, resultListCopy.size()); } private static void assertNextResult( List<ChromeTraceEvent> resultList, String expectedName, ChromeTraceEvent.Phase expectedPhase, ImmutableMap<String, String> expectedArgs) { assertTrue(resultList.size() > 0); assertEquals(expectedName, resultList.get(0).getName()); assertEquals(expectedPhase, resultList.get(0).getPhase()); assertEquals(expectedArgs, resultList.get(0).getArgs()); resultList.remove(0); } @Test public void testOutputFailed() throws IOException { ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath()); assumeTrue("Can make the root directory read-only", tmpDir.getRoot().setReadOnly()); try { ChromeTraceBuildListener listener = new ChromeTraceBuildListener( projectFilesystem, invocationInfo, new FakeClock(TIMESTAMP_NANOS), ObjectMappers.newDefaultInstance(), Locale.US, TimeZone.getTimeZone("America/Los_Angeles"), /* tracesToKeep */ 3, false); listener.outputTrace(invocationInfo.getBuildId()); fail("Expected an exception."); } catch (HumanReadableException e) { assertEquals( "Unable to write trace file: java.nio.file.AccessDeniedException: " + projectFilesystem.resolve(projectFilesystem.getBuckPaths().getBuckOut()), e.getMessage()); } finally { tmpDir.getRoot().setWritable(true); } } @Test public void outputFileUsesCurrentTime() throws IOException { ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath()); ChromeTraceBuildListener listener = new ChromeTraceBuildListener( projectFilesystem, invocationInfo, new FakeClock(TIMESTAMP_NANOS), ObjectMappers.newDefaultInstance(), Locale.US, TimeZone.getTimeZone("America/Los_Angeles"), /* tracesToKeep */ 1, false); listener.outputTrace(invocationInfo.getBuildId()); assertTrue( projectFilesystem.exists( Paths.get(EXPECTED_DIR + "build.2014-09-02.16-55-51.BUILD_ID.trace"))); } @Test public void canCompressTraces() throws IOException { ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath()); ChromeTraceBuildListener listener = new ChromeTraceBuildListener( projectFilesystem, invocationInfo, new FakeClock(TIMESTAMP_NANOS), ObjectMappers.newDefaultInstance(), Locale.US, TimeZone.getTimeZone("America/Los_Angeles"), /* tracesToKeep */ 1, true); listener.outputTrace(invocationInfo.getBuildId()); Path tracePath = Paths.get(EXPECTED_DIR + "build.2014-09-02.16-55-51.BUILD_ID.trace.gz"); assertTrue(projectFilesystem.exists(tracePath)); BufferedReader reader = new BufferedReader( new InputStreamReader( new GZIPInputStream(projectFilesystem.newFileInputStream(tracePath)))); List<?> elements = new Gson().fromJson(reader, List.class); assertThat(elements, notNullValue()); } }
justinmuller/buck
test/com/facebook/buck/event/listener/ChromeTraceBuildListenerTest.java
Java
apache-2.0
20,351
/* * Copyright (C) 2016 CaMnter yuanyu.camnter@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 com.camnter.savevolley.network.adapter.core; import com.camnter.savevolley.network.core.http.SaveHttpEntity; /** * Description:SaveHttpEntityAdapter * Created by:CaMnter * Time:2016-05-27 14:10 */ public interface SaveHttpEntityAdapter<T> { SaveHttpEntity adaptiveEntity(T t); }
CaMnter/SaveVolley
savevolley-network-adapter/src/main/java/com/camnter/savevolley/network/adapter/core/SaveHttpEntityAdapter.java
Java
apache-2.0
925
/******************************************************************************* * Copyright 2007-2013 See AUTHORS file. * * 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 xworker.dataObject.http; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.xmeta.ActionContext; import org.xmeta.Thing; import xworker.dataObject.DataObject; public class DataObjectHttpUtils { /** * 通过给定的DataObject从httpRequest中分析参数。 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Object parseHttpRequestData(ActionContext actionContext){ DataObject theData = (DataObject) actionContext.get("theData"); Thing self = (Thing) actionContext.get("self"); if(theData == null){ theData = new DataObject(self); } HttpServletRequest request = (HttpServletRequest) actionContext.get("request"); Map paramMap = request.getParameterMap(); for(Thing attribute : self.getChilds("attribute")){ String name = attribute.getString("name"); if(paramMap.containsKey(name)){ theData.put(name, request.getParameter(name)); }else if("truefalse".equals(attribute.getString("inputtype"))){ //checkbox特殊处理 theData.put(name, "false"); } } return theData; } }
x-meta/xworker
xworker_dataobject/src/main/java/xworker/dataObject/http/DataObjectHttpUtils.java
Java
apache-2.0
2,037
/* * 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. */ /* * Created by IntelliJ IDEA. * User: yole * Date: 17.11.2006 * Time: 17:36:42 */ package com.intellij.openapi.vcs.changes.patch; import com.intellij.icons.AllIcons; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class PatchFileType implements FileType { public static final PatchFileType INSTANCE = new PatchFileType(); public static final String NAME = "PATCH"; @NotNull @NonNls public String getName() { return NAME; } @NotNull public String getDescription() { return VcsBundle.message("patch.file.type.description"); } @NotNull @NonNls public String getDefaultExtension() { return "patch"; } @Nullable public Icon getIcon() { return AllIcons.Nodes.Pointcut; } public boolean isBinary() { return false; } public boolean isReadOnly() { return false; } @Nullable @NonNls public String getCharset(@NotNull VirtualFile file, final byte[] content) { return null; } }
ernestp/consulo
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileType.java
Java
apache-2.0
1,803
package io.ray.streaming.runtime.core.processor; import io.ray.streaming.message.Record; import io.ray.streaming.operator.SourceOperator; /** * The processor for the stream sources, containing a SourceOperator. * * @param <T> The type of source data. */ public class SourceProcessor<T> extends StreamProcessor<Record, SourceOperator<T>> { public SourceProcessor(SourceOperator<T> operator) { super(operator); } @Override public void process(Record record) { throw new UnsupportedOperationException("SourceProcessor should not process record"); } public void fetch() { operator.fetch(); } @Override public void close() {} }
pcmoritz/ray-1
streaming/java/streaming-runtime/src/main/java/io/ray/streaming/runtime/core/processor/SourceProcessor.java
Java
apache-2.0
663
/** * Copyright 2012-2015 Niall Gallagher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.cqengine.index.support; import com.googlecode.cqengine.query.QueryFactory; import com.googlecode.cqengine.testutil.Car; import org.junit.Test; import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions; import static org.mockito.Mockito.*; /** * Tests for {@link PartialSortedKeyStatisticsAttributeIndex}. * * @author niall.gallagher */ public class PartialSortedKeyStatisticsAttributeIndexTest { @Test public void testGetDistinctKeys1() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getDistinctKeys(noQueryOptions()); verify(backingIndex, times(1)).getDistinctKeys(noQueryOptions()); } @Test public void testGetDistinctKeys2() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getDistinctKeys(1, true, 2, true, noQueryOptions()); verify(backingIndex, times(1)).getDistinctKeys(1, true, 2, true, noQueryOptions()); } @Test public void testGetDistinctKeysDescending1() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getDistinctKeysDescending(noQueryOptions()); verify(backingIndex, times(1)).getDistinctKeysDescending(noQueryOptions()); } @Test public void testGetDistinctKeysDescending2() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getDistinctKeysDescending(1, true, 2, true, noQueryOptions()); verify(backingIndex, times(1)).getDistinctKeysDescending(1, true, 2, true, noQueryOptions()); } @Test public void testGetStatisticsForDistinctKeysDescending() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getStatisticsForDistinctKeysDescending(noQueryOptions()); verify(backingIndex, times(1)).getStatisticsForDistinctKeysDescending(noQueryOptions()); } @Test public void testGetKeysAndValues1() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getKeysAndValues(noQueryOptions()); verify(backingIndex, times(1)).getKeysAndValues(noQueryOptions()); } @Test public void testGetKeysAndValues2() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getKeysAndValues(1, true, 2, true, noQueryOptions()); verify(backingIndex, times(1)).getKeysAndValues(1, true, 2, true, noQueryOptions()); } @Test public void testGetKeysAndValuesDescending() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getKeysAndValuesDescending(noQueryOptions()); verify(backingIndex, times(1)).getKeysAndValuesDescending(noQueryOptions()); } @Test public void testGetKeysAndValuesDescending1() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getKeysAndValuesDescending(1, true, 2, true, noQueryOptions()); verify(backingIndex, times(1)).getKeysAndValuesDescending(1, true, 2, true, noQueryOptions()); } @Test public void testGetCountForKey() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getCountForKey(1, noQueryOptions()); verify(backingIndex, times(1)).getCountForKey(1, noQueryOptions()); } @Test public void testGetCountOfDistinctKeys() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getCountOfDistinctKeys(noQueryOptions()); verify(backingIndex, times(1)).getCountOfDistinctKeys(noQueryOptions()); } @Test public void testGetStatisticsForDistinctKeys() { SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex(); PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex); index.getStatisticsForDistinctKeys(noQueryOptions()); verify(backingIndex, times(1)).getStatisticsForDistinctKeys(noQueryOptions()); } static PartialSortedKeyStatisticsAttributeIndex<Integer, Car> wrapWithPartialIndex(final SortedKeyStatisticsAttributeIndex<Integer, Car> mockedBackingIndex) { return new PartialSortedKeyStatisticsAttributeIndex<Integer, Car>(Car.CAR_ID, QueryFactory.between(Car.CAR_ID, 2, 5)) { @Override protected SortedKeyStatisticsAttributeIndex<Integer, Car> createBackingIndex() { return mockedBackingIndex; } }; } @SuppressWarnings("unchecked") static SortedKeyStatisticsAttributeIndex<Integer, Car> mockBackingIndex() { return mock(SortedKeyStatisticsAttributeIndex.class); } }
npgall/cqengine
code/src/test/java/com/googlecode/cqengine/index/support/PartialSortedKeyStatisticsAttributeIndexTest.java
Java
apache-2.0
6,673