repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
liuyuanyuan/dbeaver
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/actions/datasource/DataSourceAutoCommitHandler.java
5163
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.actions.datasource; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.osgi.util.NLS; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.commands.IElementUpdater; import org.eclipse.ui.menus.UIElement; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.model.DBPTransactionIsolation; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.IDataSourceContainerProvider; import org.jkiss.dbeaver.model.exec.DBCException; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.exec.DBCTransactionManager; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.dbeaver.ui.DBeaverIcons; import org.jkiss.dbeaver.ui.UIIcon; import org.jkiss.dbeaver.ui.actions.AbstractDataSourceHandler; import java.util.Map; public class DataSourceAutoCommitHandler extends AbstractDataSourceHandler implements IElementUpdater { @Override public Object execute(ExecutionEvent event) throws ExecutionException { DBCExecutionContext context = getExecutionContext(event, true); if (context != null) { DBCTransactionManager txnManager = DBUtils.getTransactionManager(context); if (txnManager != null) { try { final DBPDataSourceContainer container = context.getDataSource().getContainer(); boolean newAutocommit = !container.isDefaultAutoCommit(); if (context.isConnected()) { // Get flag from connection newAutocommit = !txnManager.isAutoCommit(); } container.setDefaultAutoCommit(newAutocommit, context, true, new Runnable() { @Override public void run() { // Save config container.persistConfiguration(); } }); } catch (DBException e) { DBWorkbench.getPlatformUI().showError("Auto-Commit", "Error while toggle auto-commit", e); } } } return null; } @Override public void updateElement(UIElement element, Map parameters) { IWorkbenchWindow workbenchWindow = element.getServiceLocator().getService(IWorkbenchWindow.class); if (workbenchWindow == null || workbenchWindow.getActivePage() == null) { return; } IEditorPart activeEditor = workbenchWindow.getActivePage().getActiveEditor(); if (activeEditor == null) { return; } boolean autoCommit = true; DBPTransactionIsolation isolation = null; DBCExecutionContext context = getExecutionContext(activeEditor); if (context != null && context.isConnected()) { DBCTransactionManager txnManager = DBUtils.getTransactionManager(context); if (txnManager != null) { try { // Change auto-commit mode autoCommit = txnManager.isAutoCommit(); isolation = txnManager.getTransactionIsolation(); } catch (DBCException e) { log.warn(e); } } } else if (activeEditor instanceof IDataSourceContainerProvider) { DBPDataSourceContainer container = ((IDataSourceContainerProvider) activeEditor).getDataSourceContainer(); if (container != null) { autoCommit = container.isDefaultAutoCommit(); isolation = container.getActiveTransactionsIsolation(); } } element.setChecked(autoCommit); // Update command image element.setIcon(DBeaverIcons.getImageDescriptor(autoCommit ? UIIcon.TXN_COMMIT_AUTO : UIIcon.TXN_COMMIT_MANUAL)); String isolationName = isolation == null ? "?" : isolation.getTitle(); String text = autoCommit ? NLS.bind(CoreMessages.action_menu_transaction_manualcommit_name, isolationName) : CoreMessages.action_menu_transaction_autocommit_name; element.setText(text); element.setTooltip(text); } }
apache-2.0
bozimmerman/CoffeeMud
com/planet_ink/coffee_mud/core/interfaces/Combatant.java
6962
package com.planet_ink.coffee_mud.core.interfaces; import com.planet_ink.coffee_mud.Behaviors.interfaces.Behavior; import com.planet_ink.coffee_mud.Items.interfaces.Item; import com.planet_ink.coffee_mud.MOBS.interfaces.MOB; /* Copyright 2016-2022 Bo Zimmerman 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. */ /** * A physical object in the world that is capable of engaging in combat * with others. * * @author Bo Zimmerman * */ public interface Combatant extends PhysicalAgent { /** * Returns whether this combatant is in an active combat state * @see MOB#getVictim() * @see MOB#setVictim(MOB) * @see Combatant#setCombatant(PhysicalAgent) * @see Combatant#getCombatant() * @see Combatant#makePeace(boolean) * @see Combatant#setRangeToTarget(int) * @see Combatant#mayIFight(PhysicalAgent) * @return true if this combatant is in combat, false otherwise */ public boolean isInCombat(); /** * Sets the distance between this combatant and the current combat * victim. This method only matters if the combatant is in combat * and getCombatant() returns a non-null value. * This method does not reciprocate by setting the range to * target of the combat target. * @see MOB#getVictim() * @see Combatant#setCombatant(PhysicalAgent) * @see Combatant#getCombatant() * @see Combatant#rangeToTarget() * @see Combatant#mayIFight(PhysicalAgent) * @param newRange the range from this combatant to their target */ public void setRangeToTarget(int newRange); /** * Gets the distance between this combatant and the current combat * victim. This method only matters if the combatant is in combat * and getCombatant() returns a non-null value. * @see MOB#getVictim() * @see Combatant#setCombatant(PhysicalAgent) * @see Combatant#getCombatant() * @see Combatant#setRangeToTarget(int) * @see Combatant#mayIFight(PhysicalAgent) * @return newRange the range from this combatant to their target */ public int rangeToTarget(); /** * Gets the compass direction between this combatant and the current combat * victim. This method only matters if the combatant is in combat * and getCombatant() returns a non-null value. * @see MOB#getVictim() * @see Combatant#setCombatant(PhysicalAgent) * @see Combatant#getCombatant() * @see Combatant#setRangeToTarget(int) * @see Combatant#mayIFight(PhysicalAgent) * @return cardinal direction from this combatant to their target */ public int getDirectionToTarget(); /** * Returns whether this combatant is permitted to attack the * given combatant, both this combatant and the potential target are alive, * both the combatant and the target are confirmed to be the same * place. * @see MOB#getVictim() * @see Combatant#setCombatant(PhysicalAgent) * @see Combatant#getCombatant() * @see Combatant#setRangeToTarget(int) * @see Combatant#mayPhysicallyAttack(PhysicalAgent) * @param victim the potential combat target * @return true if this combatant can attack the given combatant, false otherwise */ public boolean mayPhysicallyAttack(PhysicalAgent victim); /** * Returns whether this combatant is both permitted to attack the * given combatant, and that both this combatant and the potential target * are alive. Being in the same place is not necessary. * @see MOB#getVictim() * @see Combatant#setCombatant(PhysicalAgent) * @see Combatant#getCombatant() * @see Combatant#setRangeToTarget(int) * @see Combatant#mayPhysicallyAttack(PhysicalAgent) * @param victim the potential combat target * @return true if this combatant can fight the given combatant, false otherwise */ public boolean mayIFight(PhysicalAgent victim); /** * Clears the combat state between this combatant and their * target, clears the targets combat state, as well as * that of any followers of this combatant. It is at best * an approximation of a universal combat ender. * @see Combatant#isInCombat() * @see MOB#getVictim() * @see MOB#setVictim(MOB) * @see Combatant#setCombatant(PhysicalAgent) * @see Combatant#getCombatant() * @see Combatant#setRangeToTarget(int) * @see Combatant#mayIFight(PhysicalAgent) * @param includePlayerFollowers false to apply only to npc followers, true for npc and player */ public void makePeace(boolean includePlayerFollowers); /** * If this mob is in combat, this returns the mob that this mob is * targeting. If this method returns null, the mob is not in combat. * @see Combatant#isInCombat() * @see Combatant#setCombatant(PhysicalAgent) * @see Combatant#makePeace(boolean) * @see Combatant#setRangeToTarget(int) * @see Combatant#mayIFight(PhysicalAgent) * @return the combat target, or null for a peace state */ public PhysicalAgent getCombatant(); /** * Sets the mob that this mob is targeting for combat, which * either puts them into, or clears their combat state. * If a null value, the mob is no longer fighting. * @see Combatant#isInCombat() * @see Combatant#getCombatant() * @see Combatant#makePeace(boolean) * @see Combatant#setRangeToTarget(int) * @see Combatant#mayIFight(PhysicalAgent) * @param other the combat target, or null for a peace state */ public void setCombatant(PhysicalAgent other); /** * Returns the friendly viewable description of this mobs health status, * from the given viewer mobs point of view. * @param viewer the mob viewing this mob * @return the friendly viewable health status string */ public String healthText(MOB viewer); /* Combat and death */ /** * Returns whether this combatant is dead and presumably waiting for rejuv. * @see Combatant#killMeDead(boolean) * @see MOB#bringToLife(Room, boolean) * @see MOB#removeFromGame(boolean, boolean) * @return true if this combatant is dead, false otherwise */ public boolean amDead(); /** * Puts this combatant in a dead state, removes all temporary effects, * creates a corpse, ends combat, and sends mob players to their graveyard. * @see Combatant#amDead() * @see MOB#bringToLife(Room, boolean) * @see MOB#removeFromGame(boolean, boolean) * @param createBody true to create a corpse, false otherwise * @return the corpse, if one was created */ public Item killMeDead(boolean createBody); }
apache-2.0
projectomakase/omakase
omakase-worker/src/main/java/org/projectomakase/omakase/worker/tool/ToolInfo.java
1978
/* * #%L * omakase-worker * %% * Copyright (C) 2015 Project Omakase 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. * #L% */ package org.projectomakase.omakase.worker.tool; /** * Tool Information * * @author Richard Lucas */ public class ToolInfo { private final String name; private final int maxCapacity; private final int availableCapacity; public ToolInfo(String name, int maxCapacity, int availableCapacity) { this.name = name; this.maxCapacity = maxCapacity; this.availableCapacity = availableCapacity; } /** * Returns the tools name. * * @return the tools name. */ public String getName() { return name; } /** * Returns the tools maximum capacity i.e. the maximum number of tasks it can process concurrently. * * @return the tools maximum capacity i.e. the maximum number of tasks it can process concurrently. */ public int getMaxCapacity() { return maxCapacity; } /** * Returns the tools available capacity. * * @return the tools maximum capacity. */ public int getAvailableCapacity() { return availableCapacity; } @Override public String toString() { return "ToolInfo{" + "name='" + name + '\'' + ", maxCapacity=" + maxCapacity + ", availableCapacity=" + availableCapacity + '}'; } }
apache-2.0
neoautus/lucidj
modules/plotly/src/org/lucidj/plotly/Error_Z.java
1199
/* * Copyright 2016 NEOautus Ltd. (http://neoautus.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.lucidj.plotly; public class Error_Z { // instance variables - replace the example below with your own private int x; /** * Constructor for objects of class Error_Z */ public Error_Z() { // initialise instance variables x = 0; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ public int sampleMethod(int y) { // put your code here return x + y; } } // EOF
apache-2.0
nagachika/DataflowJavaSDK
sdk/src/main/java/com/google/cloud/dataflow/sdk/util/BigQueryTableRowIterator.java
8634
/* * Copyright (C) 2015 Google 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.google.cloud.dataflow.sdk.util; import com.google.api.client.util.BackOff; import com.google.api.client.util.BackOffUtils; import com.google.api.client.util.Data; import com.google.api.client.util.Preconditions; import com.google.api.client.util.Sleeper; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.model.Table; import com.google.api.services.bigquery.model.TableDataList; import com.google.api.services.bigquery.model.TableFieldSchema; import com.google.api.services.bigquery.model.TableReference; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; /** * Iterates over all rows in a table. */ public class BigQueryTableRowIterator implements Iterator<TableRow>, Closeable { private static final Logger LOG = LoggerFactory.getLogger(BigQueryTableRowIterator.class); private final Bigquery client; private final TableReference ref; private TableSchema schema; private String pageToken; private Iterator<TableRow> rowIterator; // Set true when the final page is seen from the service. private boolean lastPage = false; // The maximum number of times a BigQuery request will be retried private static final int MAX_RETRIES = 3; // Initial wait time for the backoff implementation private static final int INITIAL_BACKOFF_MILLIS = 1000; public BigQueryTableRowIterator(Bigquery client, TableReference ref) { this.client = client; this.ref = ref; } @Override public boolean hasNext() { try { if (!isOpen()) { open(); } if (!rowIterator.hasNext() && !lastPage) { readNext(); } } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } return rowIterator.hasNext(); } /** * Adjusts a field returned from the API to * match the type that will be seen when run on the * backend service. The end result is: * * <p><ul> * <li> Nulls are {@code null}. * <li> Repeated fields are lists. * <li> Record columns are {@link TableRow}s. * <li> {@code BOOLEAN} columns are JSON booleans, hence Java {@link Boolean}s. * <li> {@code FLOAT} columns are JSON floats, hence Java {@link Double}s. * <li> {@code TIMESTAMP} columns are {@link String}s that are of the format * {yyyy-MM-dd HH:mm:ss.SSS UTC}. * <li> Every other atomic type is a {@link String}. * </ul></p> * * <p> Note that currently integers are encoded as strings to match * the behavior of the backend service. */ private Object getTypedCellValue(TableFieldSchema fieldSchema, Object v) { // In the input from the BQ API, atomic types all come in as // strings, while on the Dataflow service they have more precise // types. if (Data.isNull(v)) { return null; } if (Objects.equals(fieldSchema.getMode(), "REPEATED")) { TableFieldSchema elementSchema = fieldSchema.clone().setMode("REQUIRED"); @SuppressWarnings("unchecked") List<Map<String, Object>> rawValues = (List<Map<String, Object>>) v; List<Object> values = new ArrayList<Object>(rawValues.size()); for (Map<String, Object> element : rawValues) { values.add(getTypedCellValue(elementSchema, element.get("v"))); } return values; } if (fieldSchema.getType().equals("RECORD")) { @SuppressWarnings("unchecked") Map<String, Object> typedV = (Map<String, Object>) v; return getTypedTableRow(fieldSchema.getFields(), typedV); } if (fieldSchema.getType().equals("FLOAT")) { return Double.parseDouble((String) v); } if (fieldSchema.getType().equals("BOOLEAN")) { return Boolean.parseBoolean((String) v); } if (fieldSchema.getType().equals("TIMESTAMP")) { // Seconds to milliseconds long milliSecs = (new Double(Double.parseDouble((String) v) * 1000)).longValue(); DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC(); return formatter.print(milliSecs) + " UTC"; } return v; } private TableRow getTypedTableRow(List<TableFieldSchema> fields, Map<String, Object> rawRow) { @SuppressWarnings("unchecked") List<Map<String, Object>> cells = (List<Map<String, Object>>) rawRow.get("f"); Preconditions.checkState(cells.size() == fields.size()); Iterator<Map<String, Object>> cellIt = cells.iterator(); Iterator<TableFieldSchema> fieldIt = fields.iterator(); TableRow row = new TableRow(); while (cellIt.hasNext()) { Map<String, Object> cell = cellIt.next(); TableFieldSchema fieldSchema = fieldIt.next(); row.set(fieldSchema.getName(), getTypedCellValue(fieldSchema, cell.get("v"))); } return row; } @Override public TableRow next() { if (!hasNext()) { throw new NoSuchElementException(); } // Embed schema information into the raw row, so that values have an // associated key. This matches how rows are read when using the // DataflowPipelineRunner. return getTypedTableRow(schema.getFields(), rowIterator.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } private void readNext() throws IOException, InterruptedException { Bigquery.Tabledata.List list = client.tabledata() .list(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); if (pageToken != null) { list.setPageToken(pageToken); } Sleeper sleeper = Sleeper.DEFAULT; BackOff backOff = new AttemptBoundedExponentialBackOff(MAX_RETRIES, INITIAL_BACKOFF_MILLIS); TableDataList result = null; while (true) { try { result = list.execute(); break; } catch (IOException e) { LOG.error("Error reading from BigQuery table {} of dataset {} : {}", ref.getTableId(), ref.getDatasetId(), e.getMessage()); if (!BackOffUtils.next(sleeper, backOff)) { LOG.error("Aborting after {} retries.", MAX_RETRIES); throw e; } } } pageToken = result.getPageToken(); rowIterator = result.getRows() != null ? result.getRows().iterator() : Collections.<TableRow>emptyIterator(); // The server may return a page token indefinitely on a zero-length table. if (pageToken == null || result.getTotalRows() != null && result.getTotalRows() == 0) { lastPage = true; } } @Override public void close() throws IOException { // Prevent any further requests. lastPage = true; } private boolean isOpen() { return schema != null; } /** * Opens the table for read. * @throws IOException on failure */ private void open() throws IOException, InterruptedException { // Get table schema. Bigquery.Tables.Get get = client.tables() .get(ref.getProjectId(), ref.getDatasetId(), ref.getTableId()); Sleeper sleeper = Sleeper.DEFAULT; BackOff backOff = new AttemptBoundedExponentialBackOff(MAX_RETRIES, INITIAL_BACKOFF_MILLIS); Table table = null; while (true) { try { table = get.execute(); break; } catch (IOException e) { LOG.error("Error opening BigQuery table {} of dataset {} : {}", ref.getTableId(), ref.getDatasetId(), e.getMessage()); if (!BackOffUtils.next(sleeper, backOff)) { LOG.error("Aborting after {} retries.", MAX_RETRIES); throw e; } } } schema = table.getSchema(); // Read the first page of results. readNext(); } }
apache-2.0
ngageoint/mrgeo
mrgeo-core/src/main/java/org/mrgeo/data/image/MrsImageReader.java
4463
/* * Copyright 2009-2017. DigitalGlobe, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package org.mrgeo.data.image; import org.mrgeo.data.KVIterator; import org.mrgeo.data.raster.MrGeoRaster; import org.mrgeo.data.tile.TileIdWritable; import org.mrgeo.utils.LongRectangle; import org.mrgeo.utils.tms.Bounds; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; public abstract class MrsImageReader { /** * This will pull in a list of classes under the package name given. * * @param packageName where to look in the java space * @return an array of classes found */ protected static Class<?>[] getClasses(String packageName) throws IOException, ClassNotFoundException { // list all the classes in org.mrgeo.core.mrsimage.reader // ClassLoader cl = ClassLoader.getSystemClassLoader(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); String pkgP = packageName.replace('.', '/'); // get the list of items in the package space Enumeration<URL> resources = cl.getResources(pkgP); // go through the resources and add to the list of classes List<File> dirs = new ArrayList<>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class<?>> classes = new ArrayList<>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } return classes.toArray(new Class[classes.size()]); } // end getReader /** * Recursively find Classes from a given directory * * @param directory directory to look at * @param packageName package to look into * @return list of classes in the package */ private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException { List<Class<?>> classes = new ArrayList<>(); if (!directory.exists()) { return classes; } File[] files = directory.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file, packageName + "." + file.getName())); } else if (file.getName().endsWith(".class")) { classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); } } } return classes; } // end findClasses /** * Retrieve an tile from the data * * @param key item to retrieve * @return the result of the query */ public abstract MrGeoRaster get(TileIdWritable key); /** * Need to know the zoom level of the data being used * * @return the zoom level */ public abstract int getZoomlevel(); // gets the proper zoom level for this image... public abstract int getTileSize(); /** * All readers need to close off connections out to data */ public abstract void close(); public abstract long calculateTileCount(); /** * Varify if an item exists in the data. * * @param key item to find * @return result of search */ public abstract boolean exists(TileIdWritable key); public abstract KVIterator<TileIdWritable, MrGeoRaster> get(); public abstract KVIterator<TileIdWritable, MrGeoRaster> get(LongRectangle tileBounds); public abstract KVIterator<Bounds, MrGeoRaster> get(Bounds bounds); /** * Need to be able to pull a series of items from the data store * * @param startKey where to start * @param endKey where to end (inclusive) * @return an Iterator through the data */ public abstract KVIterator<TileIdWritable, MrGeoRaster> get(TileIdWritable startKey, TileIdWritable endKey); /** * Return true if this reader can be cached by the caller. Implementors should * return false if this reader requires a resource that is limited, like * a connection to a backend data source. */ public abstract boolean canBeCached(); }
apache-2.0
nyuuyn/ProSit
src/main/java/iaas/uni/stuttgart/de/prosit/tasks/PackageProcessWorker.java
4482
package iaas.uni.stuttgart.de.prosit.tasks; import iaas.uni.stuttgart.de.prosit.fragment.FragmentUtils; import iaas.uni.stuttgart.de.prosit.util.FragmentoClient; import iaas.uni.stuttgart.de.prosit.util.Util; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactoryConfigurationError; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.model.ZipParameters; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.IOFileFilter; /** * Takes an artefactId, which should point to a process, fragment process or * fragmented process. With the id this worker packages the process and all * referenced artefacts into a single package * * @author Kalman Kepes - kepeskn@studi.informatik.uni-stuttgart.de * */ public class PackageProcessWorker extends Worker implements Runnable { public PackageProcessWorker(String artefactId) { this.artefactId = artefactId; } /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ @Override public void run() { this.state = State.FETCH; File artefactTempDir = null; File packageTempDir = null; try { // create temp folder for artefacts artefactTempDir = Files.createTempDirectory("ProSit").toFile(); // create temp folder for package packageTempDir = Files.createTempDirectory("ProSit").toFile(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if(!FragmentUtils.notNull(artefactTempDir,packageTempDir)){ this.state = State.ERROR; return; } /* store all artefacts into temp folder */ String ddId = FragmentoClient .getDeploymentDesckriptorId(this.artefactId); List<String> wsdlIds = FragmentoClient.getWSDLIds(this.artefactId); List<String> xsdIds = FragmentoClient.getXSDIds(this.artefactId); File artefactFile = new File(artefactTempDir, FragmentoClient.getFileName(this.artefactId)); File ddFile = new File(artefactTempDir, FragmentoClient.getFileName(ddId)); // download artefacts into temp folder try { FileUtils.writeStringToFile(artefactFile, Util .domToString(FragmentoClient .getDocumentElement(this.artefactId))); FileUtils.writeStringToFile(ddFile, Util.domToString(FragmentoClient.getDocumentElement(ddId))); for (String wsdlId : wsdlIds) { FileUtils.writeStringToFile(new File(artefactTempDir, FragmentoClient.getFileName(wsdlId)), Util.domToString(FragmentoClient .getDocumentElement(wsdlId))); } for (String xsdId : xsdIds) { FileUtils .writeStringToFile(new File(artefactTempDir, FragmentoClient.getFileName(xsdId)), Util .domToString(FragmentoClient .getDocumentElement(xsdId))); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } // package stored artefacts into temp folder this.state = State.TRANSFORM; File packagedProcessFile = null; try { ZipFile packageZipFile = new ZipFile(new File(packageTempDir, Util.fetchProcessName(FragmentoClient .getDocumentElement(this.artefactId)) + ".zip")); Collection<File> artefactFiles = FileUtils.listFiles( artefactTempDir, this.createOnlyFilesFilter(), this.createOnlyFilesFilter()); packageZipFile.addFiles(new ArrayList<File>(artefactFiles), new ZipParameters()); packagedProcessFile = packageZipFile.getFile(); } catch (ZipException e) { // TODO Auto-generated catch block e.printStackTrace(); } // save state String pkgId = FragmentoClient.savePackage(this.artefactId, packagedProcessFile); this.state = State.FINISHED; this.runRegisteredWorkers(); } private IOFileFilter createOnlyFilesFilter() { return new IOFileFilter() { @Override public boolean accept(File dir, String name) { // TODO Auto-generated method stub return false; } @Override public boolean accept(File file) { // TODO Auto-generated method stub if (file.isFile()) { return true; } return false; } }; } }
apache-2.0
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/runtime/LoggingProgressMonitor.java
2260
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * * 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.jkiss.dbeaver.model.runtime; import org.eclipse.core.runtime.IProgressMonitor; import org.jkiss.dbeaver.Log; import java.io.PrintStream; /** * Progress monitor null implementation */ public class LoggingProgressMonitor extends DefaultProgressMonitor { public LoggingProgressMonitor(Log log) { super(new LoggingMonitorProxy(log)); } public LoggingProgressMonitor() { super(new LoggingMonitorProxy(null)); } private static class LoggingMonitorProxy implements IProgressMonitor { private final Log log; private PrintStream out = System.out; public LoggingMonitorProxy(Log log) { this.log = log; } @Override public void beginTask(String name, int totalWork) { if (log != null) { log.debug(name); } else { out.println(name); } } @Override public void done() { } @Override public void internalWorked(double work) { } @Override public boolean isCanceled() { return false; } @Override public void setCanceled(boolean value) { } @Override public void setTaskName(String name) { } @Override public void subTask(String name) { if (log != null) { log.debug("\t" + name); } else { out.println("\t" + name); } } @Override public void worked(int work) { } } }
apache-2.0
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.data.gis.view/src/org/jkiss/dbeaver/ui/gis/internal/GISViewerActivator.java
2078
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * * 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.jkiss.dbeaver.ui.gis.internal; import org.eclipse.core.runtime.Plugin; import org.jkiss.dbeaver.model.impl.preferences.BundlePreferenceStore; import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore; import org.osgi.framework.BundleContext; import java.io.InputStream; /** * The activator class controls the plug-in life cycle */ public class GISViewerActivator extends Plugin { public static final String PLUGIN_ID = "org.jkiss.dbeaver.data.gis.view"; // The shared instance private static GISViewerActivator plugin; private DBPPreferenceStore preferences; /** * The constructor */ public GISViewerActivator() { } @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; preferences = new BundlePreferenceStore(getBundle()); } @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static GISViewerActivator getDefault() { return plugin; } public DBPPreferenceStore getPreferences() { return preferences; } public InputStream getResourceStream(String path) { return GISViewerActivator.class.getClassLoader().getResourceAsStream(path); } }
apache-2.0
jahlborn/rmiio
src/main/java/com/healthmarketscience/rmiio/RmiioUtil.java
2775
/* Copyright (c) 2007 Health Market Science, 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.healthmarketscience.rmiio; import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Utility methods for working with rmiio classes. * * @author James Ahlborn */ public class RmiioUtil { private static final Log LOG = LogFactory.getLog(RmiioUtil.class); private RmiioUtil() { } /** * Adapts an {@link Iterator} to the {@link CloseableIOIterator} interface. * If the given iterator implements {@link Closeable}, it will be closed by * a close call on the wrapper. The wrapper implementation is a subclass of * {@link AbstractCloseableIOIterator}, so the iterator will automagically * be closed if used with a SerialRemoteIteratorServer. */ public static <T> CloseableIOIterator<T> adapt(Iterator<? extends T> iter) { if(iter == null) { return null; } return new IOIteratorAdapter<T>(iter); } /** * Closes the given Closeable if non-{@code null}, swallowing any * IOExceptions generated. */ public static void closeQuietly(Closeable closeable) { // yes, this has been written many times before and elsewhere, but i did // not want to add a dependency just for one method if(closeable != null) { try { closeable.close(); } catch(IOException e) { // optionally log the exception, but otherwise ignore if(LOG.isDebugEnabled()) { LOG.debug("Failed closing closeable", e); } } } } /** * Adapts an Iterator to the CloseableIOIterator interface. */ private static class IOIteratorAdapter<DataType> extends AbstractCloseableIOIterator<DataType> { private final Iterator<? extends DataType> _iter; public IOIteratorAdapter(Iterator<? extends DataType> iter) { _iter = iter; } @Override public boolean hasNext() { return _iter.hasNext(); } @Override protected DataType nextImpl() { return _iter.next(); } @Override protected void closeImpl() { if(_iter instanceof Closeable) { closeQuietly((Closeable)_iter); } } } }
apache-2.0
otsecbsol/linkbinder
linkbinder-core/src/main/java/jp/co/opentone/bsol/linkbinder/dto/code/AddressType.java
1683
/* * Copyright 2016 OPEN TONE 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 jp.co.opentone.bsol.linkbinder.dto.code; import jp.co.opentone.bsol.framework.core.dto.Code; /** * 宛先種別. * * @author opentone * */ public enum AddressType implements Code { /** * To. */ TO(1, "To"), /** * Cc. */ CC(2, "Cc"); /** * このコードの値. */ private Integer value; /** * このコードの名前を表すラベル. */ private String label; /** * 値とラベルを指定してインスタンス化する. * @param value * 値 * @param label * ラベル */ private AddressType(Integer value, String label) { this.value = value; this.label = label; } /* * (non-Javadoc) * @see jp.co.opentone.bsol.framework.extension.ibatis.EnumValue#getValue() */ public Integer getValue() { return value; } /* * (non-Javadoc) * @see jp.co.opentone.bsol.linkbinder.dto.code.Code#getLabel() */ public String getLabel() { return label; } }
apache-2.0
alvinkwekel/camel
components/camel-box/camel-box-api/src/main/java/org/apache/camel/component/box/api/BoxTasksManager.java
11044
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.box.api; import java.util.Date; import java.util.List; import com.box.sdk.BoxAPIConnection; import com.box.sdk.BoxAPIException; import com.box.sdk.BoxFile; import com.box.sdk.BoxTask; import com.box.sdk.BoxTaskAssignment; import com.box.sdk.BoxUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides operations to manage Box tasks. */ public class BoxTasksManager { private static final Logger LOG = LoggerFactory.getLogger(BoxTasksManager.class); /** * Box connection to authenticated user account. */ private BoxAPIConnection boxConnection; /** * Create tasks manager to manage the tasks of Box connection's authenticated user. * * @param boxConnection - Box connection to authenticated user account. */ public BoxTasksManager(BoxAPIConnection boxConnection) { this.boxConnection = boxConnection; } /** * Get a list of any tasks on file. * * @param fileId - the id of file. * @return The list of tasks on file. */ public List<BoxTask.Info> getFileTasks(String fileId) { try { LOG.debug("Getting tasks of file(id={})", fileId); if (fileId == null) { throw new IllegalArgumentException("Parameter 'fileId' can not be null"); } BoxFile file = new BoxFile(boxConnection, fileId); return file.getTasks(); } catch (BoxAPIException e) { throw new RuntimeException( String.format("Box API returned the error code %d%n%n%s", e.getResponseCode(), e.getResponse()), e); } } /** * Add task to file. * * @param fileId - the id of file to add task to. * @param action - the action the task assignee will be prompted to do. * @param dueAt - - the day at which this task is due. * @param message - an optional message to include with the task. * @return The new task. */ public BoxTask addFileTask(String fileId, BoxTask.Action action, Date dueAt, String message) { try { LOG.debug("Adding task to file(id=" + fileId + ") to '" + message + "'"); if (fileId == null) { throw new IllegalArgumentException("Parameter 'fileId' can not be null"); } if (action == null) { throw new IllegalArgumentException("Parameter 'action' can not be null"); } if (dueAt == null) { throw new IllegalArgumentException("Parameter 'dueAt' can not be null"); } BoxFile fileToAddTaskOn = new BoxFile(boxConnection, fileId); return fileToAddTaskOn.addTask(action, message, dueAt).getResource(); } catch (BoxAPIException e) { throw new RuntimeException( String.format("Box API returned the error code %d%n%n%s", e.getResponseCode(), e.getResponse()), e); } } /** * Delete task. * * @param taskId - the id of task to delete. */ public void deleteTask(String taskId) { try { LOG.debug("Deleting task(id={})", taskId); if (taskId == null) { throw new IllegalArgumentException("Parameter 'taskId' can not be null"); } BoxTask task = new BoxTask(boxConnection, taskId); task.delete(); } catch (BoxAPIException e) { throw new RuntimeException( String.format("Box API returned the error code %d%n%n%s", e.getResponseCode(), e.getResponse()), e); } } /** * Get task information. * * @param taskId - the id of task. * @return The task information. */ public BoxTask.Info getTaskInfo(String taskId) { try { LOG.debug("Getting info for task(id={})", taskId); if (taskId == null) { throw new IllegalArgumentException("Parameter 'taskId' can not be null"); } BoxTask task = new BoxTask(boxConnection, taskId); return task.getInfo(); } catch (BoxAPIException e) { throw new RuntimeException( String.format("Box API returned the error code %d%n%n%s", e.getResponseCode(), e.getResponse()), e); } } /** * Update task information. * * @param taskId - the id of task. * @param info - the updated information * @return The updated task. */ public BoxTask updateTaskInfo(String taskId, BoxTask.Info info) { try { LOG.debug("Updating info for task(id={})", taskId); if (taskId == null) { throw new IllegalArgumentException("Parameter 'taskId' can not be null"); } if (info == null) { throw new IllegalArgumentException("Parameter 'info' can not be null"); } BoxTask task = new BoxTask(boxConnection, taskId); task.updateInfo(info); return task; } catch (BoxAPIException e) { throw new RuntimeException( String.format("Box API returned the error code %d%n%n%s", e.getResponseCode(), e.getResponse()), e); } } /** * Get a list of any assignments for task. * * @param taskId - the id of task. * @return The list of assignments for task. */ public List<BoxTaskAssignment.Info> getTaskAssignments(String taskId) { try { LOG.debug("Getting assignments for task(id={})", taskId); if (taskId == null) { throw new IllegalArgumentException("Parameter 'taskId' can not be null"); } BoxTask file = new BoxTask(boxConnection, taskId); return file.getAssignments(); } catch (BoxAPIException e) { throw new RuntimeException( String.format("Box API returned the error code %d%n%n%s", e.getResponseCode(), e.getResponse()), e); } } /** * Add assignment for task. * * @param taskId - the id of task to add assignment for. * @param assignTo - the user to assign to task. * @return The assigned task. */ @SuppressWarnings("unused") // compiler for some reason thinks 'if (assignTo // == null)' clause is dead code. public BoxTask addAssignmentToTask(String taskId, BoxUser assignTo) { try { if (taskId == null) { throw new IllegalArgumentException("Parameter 'commentId' can not be null"); } if (assignTo == null) { throw new IllegalArgumentException("Parameter 'assignTo' can not be null"); } LOG.debug("Assigning task(id=" + taskId + ") to user(id=" + assignTo.getID() + ")"); BoxTask task = new BoxTask(boxConnection, taskId); task.addAssignment(assignTo); return task; } catch (BoxAPIException e) { throw new RuntimeException( String.format("Box API returned the error code %d%n%n%s", e.getResponseCode(), e.getResponse()), e); } } /** * Get task assignment information. * * @param taskAssignmentId - the id of task assignment. * @return The task assignment information. */ public BoxTaskAssignment.Info getTaskAssignmentInfo(String taskAssignmentId) { try { LOG.debug("Getting info for task(id={})", taskAssignmentId); if (taskAssignmentId == null) { throw new IllegalArgumentException("Parameter 'taskAssignmentId' can not be null"); } BoxTaskAssignment taskAssignment = new BoxTaskAssignment(boxConnection, taskAssignmentId); return taskAssignment.getInfo(); } catch (BoxAPIException e) { throw new RuntimeException( String.format("Box API returned the error code %d%n%n%s", e.getResponseCode(), e.getResponse()), e); } } // TODO Add this method when BoxTaskAssignment API fixed: // BoxTaskAssignment.update method currently // takes BoxTask.Info instead of BoxTaskAssignment.Info // /** // * Update task assignment information. // * // * @param taskAssignmentId // * - the id of task assignment. // * @param info // * - the updated information // * @return The updated task assignment. // */ // public BoxTaskAssignment updateTaskAssignmentInfo(String // taskAssignmentId, BoxTaskAssignment.Info info) { // try { // LOG.debug("Updating info for task(id={})", taskAssignmentId); // if (taskAssignmentId == null) { // throw new IllegalArgumentException("Parameter 'taskAssignmentId' can not // be null"); // } // if (info == null) { // throw new IllegalArgumentException("Parameter 'info' can not be null"); // } // // BoxTaskAssignment taskAssignment = new BoxTaskAssignment(boxConnection, // taskAssignmentId); // taskAssignment.updateInfo(info); // // return taskAssignment; // } catch (BoxAPIException e) { // throw new RuntimeException( // String.format("Box API returned the error code %d\n\n%s", // e.getResponseCode(), e.getResponse()), e); // } // } /** * Delete task assignment. * * @param taskAssignmentId - the id of task assignment to delete. */ public void deleteTaskAssignment(String taskAssignmentId) { try { LOG.debug("Deleting task(id={})", taskAssignmentId); if (taskAssignmentId == null) { throw new IllegalArgumentException("Parameter 'taskAssignmentId' can not be null"); } BoxTaskAssignment taskAssignment = new BoxTaskAssignment(boxConnection, taskAssignmentId); taskAssignment.delete(); } catch (BoxAPIException e) { throw new RuntimeException( String.format("Box API returned the error code %d%n%n%s", e.getResponseCode(), e.getResponse()), e); } } }
apache-2.0
MarukoZ/FaceRecognition
app/src/main/java/com/jason/facerecognition/data/Global.java
643
package com.jason.facerecognition.data; import android.app.Application; import com.jason.facerecognition.recognier.TensorflowLoader; import java.util.ArrayList; /** * Created by Administrator on 2017/8/9. */ public class Global extends Application { public static boolean user; public static TensorflowLoader loader; private ArrayList<String> globalFaces = new ArrayList<>(); public ArrayList<String> getGlobalVariable() { return globalFaces; } public void setGlobalVariable(String face) { this.globalFaces.add(face); } public void clear(){ this.globalFaces.clear(); } }
apache-2.0
InfoSec812/vertx-web
vertx-web/src/main/java/io/vertx/ext/web/impl/RoutingContextInternal.java
1535
/* * Copyright 2014 Red Hat, Inc. * * 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 io.vertx.ext.web.impl; import io.vertx.ext.web.RoutingContext; /** * Internal methods that are not expected or prime to be in the public API * * @author Paulo Lopes */ public interface RoutingContextInternal extends RoutingContext { int BODY_HANDLER = 1 << 1; int CORS_HANDLER = 1 << 2; /** * flags the current routing context as having visited the handler with {@code id}. * @param id one of the constants of this interface * @return self */ RoutingContextInternal visitHandler(int id); /** * returns true if the current context has been visited by the handler with {@code id}. * * @param id one of the constants of this interface * @return true if the {@link #visitHandler(int)} has been called with the same id. */ boolean seenHandler(int id); /** * propagates a matching failure across routers. * * @param matchFailure the desired match failure * @return fluent self */ RoutingContextInternal setMatchFailure(int matchFailure); }
apache-2.0
hiteshsahu/React-Native-Music-Player
android/app/src/main/java/com/react_audio_player/utils/PreferenceHelper.java
2532
/** * */ package com.react_audio_player.utils; import android.content.Context; import android.preference.PreferenceManager; /** * @author Hitesh */ public class PreferenceHelper { public static final String FIRST_TIME = "FirstTime"; public static final String SUBMIT_LOGS = "CrashLogs"; private PreferenceHelper() { } private static PreferenceHelper preferenceHelperInstance = new PreferenceHelper(); public void init(Context context) { if (!getPrefernceHelperInstace().getBoolean(context, FIRST_TIME, false)) { setBoolean(context, FIRST_TIME, true); setBoolean(context, SUBMIT_LOGS, true); } } public static PreferenceHelper getPrefernceHelperInstace() { return preferenceHelperInstance; } public void setBoolean(Context appContext, String key, Boolean value) { PreferenceManager.getDefaultSharedPreferences(appContext).edit() .putBoolean(key, value).apply(); } public void setInteger(Context appContext, String key, int value) { PreferenceManager.getDefaultSharedPreferences(appContext).edit() .putInt(key, value).apply(); } public void setFloat(Context appContext, String key, float value) { PreferenceManager.getDefaultSharedPreferences(appContext).edit() .putFloat(key, value).apply(); } public void setString(Context appContext, String key, String value) { PreferenceManager.getDefaultSharedPreferences(appContext).edit() .putString(key, value).apply(); } // To retrieve values from shared preferences: public boolean getBoolean(Context appContext, String key, Boolean defaultValue) { return PreferenceManager.getDefaultSharedPreferences(appContext) .getBoolean(key, defaultValue); } public int getInteger(Context appContext, String key, int defaultValue) { return PreferenceManager.getDefaultSharedPreferences(appContext) .getInt(key, defaultValue); } public float getString(Context appContext, String key, float defaultValue) { return PreferenceManager.getDefaultSharedPreferences(appContext) .getFloat(key, defaultValue); } public String getString(Context appContext, String key, String defaultValue) { return PreferenceManager.getDefaultSharedPreferences(appContext) .getString(key, defaultValue); } }
apache-2.0
symphoniacloud/lambda-monitoring
lambda-metrics-maven-plugin/src/main/java/io/symphonia/lambda/metrics/GenerateMetricFiltersMojo.java
2850
package io.symphonia.lambda.metrics; import io.symphonia.lambda.annotations.CloudwatchLogGroup; import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import java.io.File; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @Execute(phase = LifecyclePhase.COMPILE) @Mojo(name = "generate") public class GenerateMetricFiltersMojo extends AbstractMetricFiltersMojo { @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; @Parameter(property = "dryRun", defaultValue = "false", required = true) private boolean dryRun; @Override public void execute() throws MojoExecutionException, MojoFailureException { checkConfiguration(); MetricFilterPublisher publisher = dryRun ? new DryRunMetricFilterPublisher(getLog()) : new GenerateMetricFilterPublisher(getLog(), new File(project.getBuild().getDirectory())); // Gets a map of fully-namespaced metric names -> annotated fields in classes that extend LambdaMetricSet Map<String, Field> metricFields = new HashMap<>(); try { metricFields.putAll(new MetricsFinder(project).find()); } catch (DependencyResolutionRequiredException | MalformedURLException e) { throw new MojoExecutionException("Could not scan classpath for metric fields", e); } if (!metricFields.isEmpty()) { getLog().info(String.format("Found [%d] metric fields in classpath.", metricFields.size())); List<MetricFilter> metricFilters = getMetricFilters(metricFields); getLog().info(String.format("Published [%d] metric filters.", publisher.publishMetricFilters(metricFilters))); } else { getLog().warn("Did not find any metric fields in classpath."); } } private void checkConfiguration() throws MojoFailureException { if (!filterPatternMap.keySet().containsAll(metricValueMap.keySet()) || !metricValueMap.keySet().containsAll(filterPatternMap.keySet())) { throw new MojoFailureException("filterPatternMap and metricValueMap are inconsistent."); } } }
apache-2.0
MosumTree/lightning
app/src/main/java/com/example/mosum/lightning/MainActivity.java
30488
package com.example.mosum.lightning; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.media.Image; import android.net.Uri; import android.net.wifi.WpsInfo; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pDeviceList; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager; import android.os.AsyncTask; import android.os.Environment; import android.provider.ContactsContract; import android.provider.MediaStore; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.miguelcatalan.materialsearchview.MaterialSearchView; import com.mingle.entity.MenuEntity; import com.mingle.sweetpick.BlurEffect; import com.mingle.sweetpick.RecyclerViewDelegate; import com.mingle.sweetpick.SweetSheet; import java.io.File; import java.io.IOException; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import connect.FileServerAsyncTask; import connect.FileTransferService; import connect.SimpleServer; import connect.WifiP2PReceiver; import ui.ContentAdapter; import ui.ContentModel; import ui.RippleImageView; import ui.WaterWaveView; import static android.R.attr.data; import static android.R.id.list; import static com.mingle.sweetsheet.R.id.rl; import static com.mingle.sweetsheet.R.id.useLogo; public class MainActivity extends FragmentActivity implements WifiP2pManager.PeerListListener,WifiP2pManager.ConnectionInfoListener { private DrawerLayout drawerLayout; private ImageView leftMenu; private ListView leftlistView; private FragmentManager fm; private List<ContentModel> list; private List<ContentModel> historylist; private ContentAdapter adapter; private ContentAdapter historyAdapter; //主界面下部效果测试按钮 private Button searchbt; private Button netlistbt; //private Button filelistbt; private Button transferbt; private Button MediaBtn; private ImageButton filelistBtn;//查看已连接设备的文件本地文件 private ImageButton transferBtn;//进行文件传输 private ImageButton netlistBtn;//查看发现设备列表 private ImageButton disconnectBtn;//断开与当前设备的连接 //主界面历史记录 private ListView historyListView; //主界面闪电按钮 private RippleImageView rippleImageView; private Button ligntningBt; private boolean isSearchFlag=true; //底部列表 private SweetSheet mSweetSheet; private RelativeLayout rl; //广播 wifiP2P private IntentFilter intentFilter = new IntentFilter(); private WifiP2pManager.Channel mChannel; private WifiP2pManager mManager; private WifiP2PReceiver wifiP2PReceiver; private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>(); // 用来存放发现的节点 //private static WifiP2pDevice device;//设备 private boolean isConnected=false; private String[] peersname; private WifiP2pInfo info; private TextView connectDevice; private TextView connectDeviceTitle; //文件传输 private FileServerAsyncTask mServerTask; private String FilePath = Environment.getExternalStorageDirectory() + "/com.ligntningTransfer/"; //自建服务器 private SimpleServer server; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); leftMenu = (ImageView) findViewById(R.id.leftmenu); drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout); leftlistView = (ListView) findViewById(R.id.left_listview); historyListView = (ListView) findViewById(R.id.history_listview_main); rippleImageView=(RippleImageView)findViewById(R.id.rippleImageView); ligntningBt= (Button) findViewById(R.id.ligntning_btn); connectDevice = (TextView)findViewById(R.id.connect_user) ; connectDevice.setVisibility(View.GONE); fm = getSupportFragmentManager(); initLeftmenu(); /** * 如果不存在该文件夹,在应用启动时就创建该文件夹,如果存在当然不会创建 * 然后获取该文件下的所有文件 * */ makeRootDirectory(FilePath); adapter = new ContentAdapter(this, list); leftlistView.setAdapter(adapter); //historyListView.setAdapter(adapter); leftMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawerLayout.openDrawer(Gravity.LEFT); } }); historylist=readHistory(); historyAdapter = new ContentAdapter(this,historylist); historyListView.setAdapter(historyAdapter); //打开指定目录下的文件 historyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*");//设置类型,我这里是任意类型,任意后缀的可以这样写。 intent.addCategory(Intent.CATEGORY_OPENABLE); startActivity(intent); } }); //开启服务器 server = new SimpleServer(); try { // 因为程序模拟的是html放置在asset目录下, // 所以在这里存储一下AssetManager的指针。 server.asset_mgr = this.getAssets(); // 启动web服务 server.start(); Log.i("Httpd", "The server started."+getHostIP()); } catch(IOException ioe) { Log.w("Httpd", "The server could not start."+ioe); } ligntningBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isSearchFlag){ rippleImageView.startWaveAnimation(); isSearchFlag=false; mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.d(MainActivity.this.getClass().getName(), "检测P2P进程成功"); } @Override public void onFailure(int reason) { Log.d(MainActivity.this.getClass().getName(), "检测P2P进程失败"); } }); } else { isSearchFlag=true; rippleImageView.stopWaveAnimation(); } } }); /*//打开搜索界面 searchbt = (Button) findViewById(R.id.search_bt); searchbt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, SearchActivity.class); startActivity(intent); } });*/ //打开连接设备的文件列表 rl = (RelativeLayout) findViewById(R.id.fragment_layout); //打开文件列表 filelistBtn=(ImageButton) findViewById(R.id.filelist_ibtn); filelistBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, Media.class); startActivity(intent); } }); //打开搜索到的wifiP2P用户列表 netlistBtn = (ImageButton) findViewById(R.id.netlist_ibtn); netlistBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setupRecyclerView(); mSweetSheet.toggle(); } }); //打开本地文件 transferBtn = (ImageButton) findViewById(R.id.transfer_ibtn); transferBtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*");//设置类型,我这里是任意类型,任意后缀的可以这样写。 intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(intent,20); } }); transferBtn.setVisibility(View.VISIBLE); /*停止主界面按钮波纹效果测试按钮 stopbt = (Button) findViewById(R.id.stop_bt); stopbt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rippleImageView.stopWaveAnimation(); } });*/ /*打开文件互传界面 filelistBtn = (ImageButton) findViewById(R.id.transfer_bt); filelistBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, TransferActivity.class); intent.putExtra("isSend",false); startActivity(intent); } });*/ /*播放器测试 MediaBtn =(Button)findViewById(R.id.media); MediaBtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,Media.class); startActivity(intent); } });*/ //断开连接 disconnectBtn=(ImageButton)findViewById(R.id.disconnect_ibtn); disconnectBtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { disconnect(); } }); //侧边栏监听事件 leftlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch ((int) id) { case 1: setupRecyclerView(); mSweetSheet.toggle(); break; case 2: Intent intent2=new Intent(MainActivity.this,DeviceMessage.class); startActivity(intent2); break; case 3: Intent intent3=new Intent(MainActivity.this,History.class); startActivity(intent3); break; case 4: System.exit(0); break; case 5: Intent intent5=new Intent(MainActivity.this,About.class); startActivity(intent5); break; default: break; } drawerLayout.closeDrawer(Gravity.LEFT); } }); /* * 创建wifiP2P广播监听 * * */ // 状态发生变化 intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); // peers列表发生变化 intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); // p2p连接发生变化 intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); // 设备信息发生变化. intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); //获得 WifiP2pManager 的实例,并调用它的 initialize() 方法。该方法将返回 WifiP2pManager.Channel 对象。 我们的应用将在后面使用该对象连接 Wi-Fi P2P 框架 mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); mChannel = mManager.initialize(this, getMainLooper(), null); } //获取本机IP地址 public static String getHostIP() { String hostIp = null; try { Enumeration nis = NetworkInterface.getNetworkInterfaces(); InetAddress ia = null; while (nis.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) nis.nextElement(); Enumeration<InetAddress> ias = ni.getInetAddresses(); while (ias.hasMoreElements()) { ia = ias.nextElement(); if (ia instanceof Inet6Address) { continue;// skip ipv6 } String ip = ia.getHostAddress(); if (!"127.0.0.1".equals(ip)) { hostIp = ia.getHostAddress(); break; } } } } catch (SocketException e) { Log.i("yao", "SocketException"); e.printStackTrace(); } return hostIp; } /*public String getLocalIpAddress() { try { // 遍历网络接口 Enumeration<NetworkInterface> infos = NetworkInterface.getNetworkInterfaces(); while (infos.hasMoreElements()) { // 获取网络接口 NetworkInterface niFace = infos.nextElement(); Enumeration<InetAddress> enumIpAddr = niFace.getInetAddresses(); while (enumIpAddr.hasMoreElements()) { InetAddress mInetAddress = enumIpAddr.nextElement(); // 所获取的网络地址不是127.0.0.1时返回得得到的IP if (!mInetAddress.isLoopbackAddress()&& InetAddressUtils.isIPv4Address(mInetAddress .getHostAddress())) { return mInetAddress.getHostAddress().toString(); } } } } catch (SocketException e) { e.printStackTrace(); } return null; }*/ //初始化侧边栏菜单 private void initLeftmenu() { list = new ArrayList<ContentModel>(); list.add(new ContentModel(R.drawable.left_nearby, "nearby", 1)); list.add(new ContentModel(R.drawable.left_dev, "device", 2)); list.add(new ContentModel(R.drawable.left_history, "history", 3)); list.add(new ContentModel(R.drawable.left_exit, "exit", 4)); list.add(new ContentModel(R.drawable.left_about, "about", 5)); } //底部列表视图设置 private void setupRecyclerView() { final ArrayList<MenuEntity> list = new ArrayList<>(); //添加假数据 MenuEntity menuEntity = new MenuEntity(); menuEntity.iconId = R.drawable.left_account; menuEntity.titleColor = 0xff000000; menuEntity.title = "Users"; list.add(menuEntity); for (int i=0;i<peers.size();i++){ MenuEntity menuEntity1 = new MenuEntity(); menuEntity1.iconId = R.drawable.ic_account_child; menuEntity1.titleColor = 0xff000000; menuEntity1.title = peersname[i]; list.add(menuEntity1); } // SweetSheet 控件,根据 rl 确认位置 mSweetSheet = new SweetSheet(rl); //设置数据源 (数据源支持设置 list 数组,也支持从菜单中获取) mSweetSheet.setMenuList(list); //根据设置不同的 Delegate 来显示不同的风格. RecyclerViewDelegate mRecycclerViewDelegate=new RecyclerViewDelegate(true); mSweetSheet.setDelegate(mRecycclerViewDelegate); //根据设置不同Effect 来显示背景效果BlurEffect:模糊效果.DimEffect 变暗效果 mSweetSheet.setBackgroundEffect(new BlurEffect(8)); //设置点击事件 mSweetSheet.setOnMenuItemClickListener(new SweetSheet.OnMenuItemClickListener() { @Override public boolean onItemClick(int position, MenuEntity menuEntity1) { //即时改变当前项的颜色 list.get(position).titleColor = 0xff5823ff; ((RecyclerViewDelegate) mSweetSheet.getDelegate()).notifyDataSetChanged(); connectToPeer(position); //根据返回值, true 会关闭 SweetSheet ,false 则不会. //Toast.makeText(MainActivity.this, menuEntity1.title + " " + position, Toast.LENGTH_SHORT).show(); return false; } }); } //重写后退键(按后退键会报错,先注释标记一下) /* @Override public void onBackPressed() { if (mSweetSheet.isShow()) { if (mSweetSheet.isShow()) { mSweetSheet.dismiss(); } } else { super.onBackPressed(); } }*/ @Override protected void onResume() { super.onResume(); wifiP2PReceiver = new WifiP2PReceiver(mManager, mChannel,this); registerReceiver(wifiP2PReceiver, intentFilter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(wifiP2PReceiver); } @Override public void onDestroy() { super.onDestroy(); if (server != null){ // 在程序退出时关闭web服务器 server.stop(); } Log.w("Httpd", "The server stopped."); } /** * 连接或者断开连接的处理方法 */ private void connectToPeer(int num) { if (num<1) return; final WifiP2pDevice device = peers.get(num-1); WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; Log.d("FIND_DEVICE", "设备名称是:"+device.deviceName+"---"+"设备地址是:"+device.deviceAddress); config.wps.setup = WpsInfo.PBC; config.groupOwnerIntent = 1; mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.d(MainActivity.this.getClass().getName(), "成功连接到" + device.deviceName); isConnected=true; connectDevice.setText(device.deviceName); connectDevice.setVisibility(View.VISIBLE); Toast.makeText(MainActivity.this, "成功连接到" + device.deviceName, Toast.LENGTH_SHORT).show(); } @Override public void onFailure(int reason) { Log.d(MainActivity.this.getClass().getName(), "连接失败"); Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT) .show(); isConnected=false; } }); } //断开连接 private void disconnect() { mManager.removeGroup(mChannel, new WifiP2pManager.ActionListener() { @Override public void onFailure(int reasonCode) { } @Override public void onSuccess() { // 将对等信息情况 peers.clear(); isConnected=false; } }); } //连接设备后会触发 /** * 要实现设备连接后把指定文件夹里的所有文件都传输给设备另一端,就需要去除transferbt的选择过程, * 所以采用以下逻辑,两设备连接,接收方仍然选择accept是进入传输界面, * 发送方省去选择传输文件的逻辑,直接定死传输路径,即连接后就传输。 * */ @Override public void onConnectionInfoAvailable(WifiP2pInfo minfo) { Log.i("xyz", "InfoAvailable is on"); info = minfo; //TextView view = (TextView) findViewById(R.id.tv_main); if (info.groupFormed && info.isGroupOwner) { Log.i("xyz","owner start"); /*mServerTask = new FileServerAsyncTask(MainActivity.this); mServerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); filelistbt.setVisibility(View.GONE);*/ AlertDialog.Builder dialog =new AlertDialog.Builder(MainActivity.this); dialog.setTitle("File transfer ask"); dialog.setPositiveButton("Accept", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent=new Intent(MainActivity.this,TransferActivity.class); intent.putExtra("isSend",false); MainActivity.this.startActivity(intent); } }); dialog.setNegativeButton("refuse", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); dialog.show(); } else if (info.groupFormed) { //SetButtonVisible(); Log.i("xyz","client start"); AlertDialog.Builder dialog =new AlertDialog.Builder(MainActivity.this); transferBtn.setVisibility(View.VISIBLE); dialog.setTitle("File send ask"); dialog.setPositiveButton("Accept", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { File f = new File(FilePath); File[] files = f.listFiles();// 列出所有文件 for (int i=0;i<files.length;i++){ Log.i("filename"+i+":",files[i].getName()); Intent serviceIntent = new Intent(MainActivity.this, FileTransferService.class); serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE); serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, FilePath+files[i].getName());//将位置传入Service serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS, info.groupOwnerAddress.getHostAddress());//传入组长IP,用于创建socket端口 serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8981);//传入端口port serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_TYPE, getType(files[i].getName()));//传入文件类型 MainActivity.this.startService(serviceIntent); } } }); dialog.setNegativeButton("refuse", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); dialog.show(); } } //实现确定谁是GO private void BeGroupOwener() { mManager.createGroup(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { } @Override public void onFailure(int reason) { } }); } //获取搜索到的设备列表 @Override public void onPeersAvailable(WifiP2pDeviceList peersLists) { peers.clear(); peers.addAll(peersLists.getDeviceList()); if (peers.size() == 0) { Log.d(this.getClass().getName(), "No devices found"); peersname = new String[1]; if (peersname.length>0){ peersname[0]="No Devices"; }else { peersname = new String[1]; peersname[0]="No Devices"; } return; } else { peersname = new String[peers.size()]; int i=0; for(WifiP2pDevice device: peers){ peersname[i++]=device.deviceName; } //设置网络列表 setupRecyclerView(); } } //将选择好的文件数据返回时的回调函数 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 20) { super.onActivityResult(requestCode, resultCode, data); if (data==null) return; Uri uri = data.getData();//获取文件所在位置 String uriname=uri.toString(); if(uriname==null) uriname="unknown"; Log.i("path",uriname); int type=1; String mimeType = getContentResolver().getType(uri); //image/jpeg Intent transferIntent = new Intent(MainActivity.this, TransferActivity.class); transferIntent.putExtra("isSend",true); transferIntent.putExtra("uri",uri.toString()); Log.i("xyz", "mimeType is"+mimeType); if (mimeType==null)type=1; else{ switch (mimeType){ case "video/mp4": type=2; break; case "image/jpeg": type=1; break; }} transferIntent.putExtra("type",type); transferIntent.putExtra("IP",info.groupOwnerAddress.getHostAddress()); MainActivity.this.startActivity(transferIntent); } } //获取路径中的文件名 public String getFileName(String pathandname){ int start=pathandname.lastIndexOf("/"); int end=pathandname.lastIndexOf("."); if(start!=-1 && end!=-1){ if(pathandname.substring(start+1,end)==null) end=pathandname.lastIndexOf(":"); return pathandname.substring(start+1,end); }else{ return null; } } //获取文件后缀名转成类型 public int getType(String fileName){ String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); if (suffix=="jpg") return 1; else if (suffix=="mp4") return 2; return 1; } //根据uri获取路径名 public static String getRealFilePath( final Context context, final Uri uri ) { if ( null == uri ) return null; final String scheme = uri.getScheme(); String data = null; //file:///storage/emulated/0/com.ligntning/lalala.mp4 if ( scheme == null ) data = uri.getPath(); else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) { data = uri.getPath(); } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) { Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null ); if ( null != cursor ) { if ( cursor.moveToFirst() ) { int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA ); if ( index > -1 ) { data = cursor.getString( index ); } } cursor.close(); } } if (data==null){return "unknown";} return data; } //读历史记录 List<ContentModel> readHistory(){ List<ContentModel> list= new ArrayList<ContentModel>(); SharedPreferences SAVE = getSharedPreferences("save", MODE_PRIVATE); int point=SAVE.getInt("point", 0); if (point==0){ list.add(new ContentModel(R.drawable.left_history,"无历史记录",1)); return list; } String type; String filename; final int N=16; for(int i=0,n=point;i<=N;i++){ type=SAVE.getString("type"+n, null); filename= SAVE.getString("filename"+n,null); if(type!=null){ switch (type){ case "jpg": Log.i("history", "jpg"); list.add(new ContentModel(R.drawable.type_jpg,filename+n,i+1)); break; case "mp4": Log.i("history", "mp4"); list.add(new ContentModel(R.drawable.type_mp4,filename+n,i+1)); break; case "mp3": list.add(new ContentModel(R.drawable.type_mp3,filename+n,i+1)); break; case "txt": list.add(new ContentModel(R.drawable.type_txt,filename+n,i+1)); break; } } n=n>0?(--n):(--n+N)%16; } return list; } // 生成文件夹 public static void makeRootDirectory(String filePath) { File file = null; try { file = new File(filePath); if (!file.exists()) { file.mkdir(); } } catch (Exception e) { Log.i("error:", e+""); } } }
apache-2.0
firejack-open/Firejack-Platform
platform/src/main/java/net/firejack/platform/core/config/meta/element/authority/EntityRole.java
1534
/* * 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 net.firejack.platform.core.config.meta.element.authority; public class EntityRole { private String path; public EntityRole() { } public EntityRole(String path) { this.path = path; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof EntityRole)) return false; EntityRole that = (EntityRole) o; return !(path != null ? !path.equals(that.path) : that.path != null); } @Override public int hashCode() { return path != null ? path.hashCode() : 0; } }
apache-2.0
intropro/prairie
junit-runner/src/test/java/com/intropro/prairie/junit/Prairie.java
1258
package com.intropro.prairie.junit; import com.intropro.prairie.unit.common.annotation.PrairieUnit; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Created by presidentio on 11/10/15. */ @RunWith(PrairieRunner.class) public class Prairie { @PrairieUnit private static SimpleUnit simpleStaticUnit; @PrairieUnit private SimpleUnit simpleUnit; private boolean simpleInitedBefore = false; private static boolean simpleInitedBeforeClass = false; @Before public void init(){ simpleInitedBefore = simpleUnit != null && simpleUnit.isInited(); } @BeforeClass public static void initClass(){ simpleInitedBeforeClass = simpleStaticUnit != null && simpleStaticUnit.isInited(); } @Test public void testInit() throws Exception { Assert.assertNotNull(simpleUnit); Assert.assertTrue(simpleUnit.isInited()); Assert.assertTrue(simpleInitedBefore); } @Test public void testStatic() throws Exception { Assert.assertNotNull(simpleStaticUnit); Assert.assertTrue(simpleStaticUnit.isInited()); Assert.assertTrue(simpleInitedBeforeClass); } }
apache-2.0
TatsianaKasiankova/pentaho-kettle
engine/src/test/java/org/pentaho/di/trans/steps/csvinput/CsvInputUnicodeTest.java
7490
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.csvinput; import java.nio.charset.StandardCharsets; import org.junit.Assert; import org.mockito.Matchers; import org.mockito.Mockito; import org.junit.BeforeClass; import org.junit.Test; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.logging.LoggingObjectInterface; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.RowAdapter; import org.pentaho.di.trans.steps.mock.StepMockHelper; import org.pentaho.di.trans.steps.textfileinput.TextFileInputField; /** * Tests for unicode support in CsvInput step * * @author Pavel Sakun * @see CsvInput */ public class CsvInputUnicodeTest extends CsvInputUnitTestBase { private static final String UTF8 = "UTF-8"; private static final String UTF16LE = "UTF-16LE"; private static final String UTF16LEBOM = "x-UTF-16LE-BOM"; private static final String UTF16BE = "UTF-16BE"; private static final String ONE_CHAR_DELIM = "\t"; private static final String MULTI_CHAR_DELIM = "|||"; private static final String TEXT = "Header1%1$sHeader2\nValue%1$sValue\nValue%1$sValue\n"; private static final String TEXT_WITH_ENCLOSURES = "Header1%1$sHeader2\n\"Value\"%1$s\"Value\"\n\"Value\"%1$s\"Value\"\n"; private static final String TEST_DATA = String.format( TEXT, ONE_CHAR_DELIM ); private static final String TEST_DATA1 = String.format( TEXT, MULTI_CHAR_DELIM ); private static final String TEST_DATA2 = String.format( TEXT_WITH_ENCLOSURES, ONE_CHAR_DELIM ); private static final String TEST_DATA3 = String.format( TEXT_WITH_ENCLOSURES, MULTI_CHAR_DELIM ); private static final byte[] UTF8_BOM = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }; private static final String TEST_DATA_UTF8_BOM = String.format( new String( UTF8_BOM, StandardCharsets.UTF_8 ) + TEXT, ONE_CHAR_DELIM ); private static final byte[] UTF16LE_BOM = { (byte) 0xFF, (byte) 0xFE }; private static final String TEST_DATA_UTF16LE_BOM = String.format( new String( UTF16LE_BOM, StandardCharsets.UTF_16LE ) + TEST_DATA2, ONE_CHAR_DELIM ); private static final byte[] UTF16BE_BOM = { (byte) 0xFE, (byte) 0xFF }; private static final String TEST_DATA_UTF16BE_BOM = String.format( new String( UTF16BE_BOM, StandardCharsets.UTF_16BE ) + TEST_DATA2, ONE_CHAR_DELIM ); private static StepMockHelper<?, ?> stepMockHelper; @BeforeClass public static void setUp() throws KettleException { stepMockHelper = new StepMockHelper<CsvInputMeta, CsvInputData>( "CsvInputTest", CsvInputMeta.class, CsvInputData.class ); Mockito.when( stepMockHelper.logChannelInterfaceFactory.create( Matchers.any(), Matchers.any( LoggingObjectInterface.class ) ) ) .thenReturn( stepMockHelper.logChannelInterface ); Mockito.when( stepMockHelper.trans.isRunning() ).thenReturn( true ); } @Test public void testUTF16LE() throws Exception { doTest( UTF16LE, UTF16LE, TEST_DATA, ONE_CHAR_DELIM ); } @Test public void testUTF16BE() throws Exception { doTest( UTF16BE, UTF16BE, TEST_DATA, ONE_CHAR_DELIM ); } @Test public void testUTF16BE_multiDelim() throws Exception { doTest( UTF16BE, UTF16BE, TEST_DATA1, MULTI_CHAR_DELIM ); } @Test public void testUTF16LEBOM() throws Exception { doTest( UTF16LEBOM, UTF16LE, TEST_DATA, ONE_CHAR_DELIM ); } @Test public void testUTF8() throws Exception { doTest( UTF8, UTF8, TEST_DATA, ONE_CHAR_DELIM ); } @Test public void testUTF8_multiDelim() throws Exception { doTest( UTF8, UTF8, TEST_DATA1, MULTI_CHAR_DELIM ); } @Test public void testUTF8_headerWithBOM() throws Exception { doTest( UTF8, UTF8, TEST_DATA_UTF8_BOM, ONE_CHAR_DELIM ); } @Test public void testUTF16LEDataWithEnclosures() throws Exception { doTest( UTF16LE, UTF16LE, TEST_DATA2, ONE_CHAR_DELIM ); } @Test public void testUTF16LE_headerWithBOM() throws Exception { doTest( UTF16LE, UTF16LE, TEST_DATA_UTF16LE_BOM, ONE_CHAR_DELIM ); } @Test public void testUTF16BEDataWithEnclosures() throws Exception { doTest( UTF16BE, UTF16BE, TEST_DATA2, ONE_CHAR_DELIM ); } @Test public void testUTF16BE_headerWithBOM() throws Exception { doTest( UTF16BE, UTF16BE, TEST_DATA_UTF16BE_BOM, ONE_CHAR_DELIM ); } @Test public void testUTF16LEBOMDataWithEnclosures() throws Exception { doTest( UTF16LEBOM, UTF16LE, TEST_DATA2, ONE_CHAR_DELIM ); } @Test public void testUTF16BE_multiDelim_DataWithEnclosures() throws Exception { doTest( UTF16BE, UTF16BE, TEST_DATA3, MULTI_CHAR_DELIM ); } @Test public void testUTF16LE_multiDelim_DataWithEnclosures() throws Exception { doTest( UTF16LE, UTF16LE, TEST_DATA3, MULTI_CHAR_DELIM ); } @Test public void testUTF8_multiDelim_DataWithEnclosures() throws Exception { doTest( UTF8, UTF8, TEST_DATA3, MULTI_CHAR_DELIM ); } private void doTest( final String fileEncoding, final String stepEncoding, final String testData, final String delimiter ) throws Exception { String testFilePath = createTestFile( fileEncoding, testData ).getAbsolutePath(); CsvInputMeta meta = createStepMeta( testFilePath, stepEncoding, delimiter ); CsvInputData data = new CsvInputData(); CsvInput csvInput = new CsvInput( stepMockHelper.stepMeta, stepMockHelper.stepDataInterface, 0, stepMockHelper.transMeta, stepMockHelper.trans ); csvInput.init( meta, data ); csvInput.addRowListener( new RowAdapter() { @Override public void rowWrittenEvent( RowMetaInterface rowMeta, Object[] row ) throws KettleStepException { for ( int i = 0; i < rowMeta.size(); i++ ) { Assert.assertEquals( "Value", row[ i ] ); } } } ); boolean haveRowsToRead; do { haveRowsToRead = !csvInput.processRow( meta, data ); } while ( !haveRowsToRead ); csvInput.dispose( meta, data ); Assert.assertEquals( 2, csvInput.getLinesWritten() ); } private CsvInputMeta createStepMeta( final String testFilePath, final String encoding, final String delimiter ) { final CsvInputMeta meta = new CsvInputMeta(); meta.setFilename( testFilePath ); meta.setDelimiter( delimiter ); meta.setEncoding( encoding ); meta.setEnclosure( "\"" ); meta.setBufferSize( "50000" ); meta.setInputFields( getInputFileFields() ); meta.setHeaderPresent( true ); return meta; } private TextFileInputField[] getInputFileFields() { return createInputFileFields( "Header1", "Header2" ); } }
apache-2.0
stevek-ngdata/kite
kite-data/kite-data-core/src/test/java/org/kitesdk/data/TestMetadataProviders.java
10335
/** * Copyright 2013 Cloudera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data; import static org.kitesdk.data.filesystem.DatasetTestUtilities.*; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.Sets; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collection; import org.apache.avro.Schema; import org.apache.hadoop.conf.Configuration; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public abstract class TestMetadataProviders extends MiniDFSTest { protected static final String NAME = "provider_test1"; @Parameterized.Parameters public static Collection<Object[]> data() { Object[][] data = new Object[][] { { false }, // default to local FS { true } }; // default to distributed FS return Arrays.asList(data); } // whether this should use the DFS provided by MiniDFSTest protected boolean distributed; protected Configuration conf; protected DatasetDescriptor testDescriptor; protected DatasetDescriptor anotherDescriptor; protected MetadataProvider provider; abstract public MetadataProvider newProvider(Configuration conf); public TestMetadataProviders(boolean distributed) { this.distributed = distributed; } @Before public void setUp() throws IOException, URISyntaxException { this.conf = (distributed ? MiniDFSTest.getConfiguration() : new Configuration()); this.testDescriptor = new DatasetDescriptor.Builder() .format(Formats.AVRO) .schemaUri(USER_SCHEMA_URL) .partitionStrategy(new PartitionStrategy.Builder() .year("timestamp") .month("timestamp") .day("timestamp") .build()) .build(); // something completely different this.anotherDescriptor = new DatasetDescriptor.Builder() .format(Formats.PARQUET) .schema(Schema.createArray(Schema.create(Schema.Type.FLOAT))) .partitionStrategy(new PartitionStrategy.Builder() .hash("some_field", 20000) .build()) .build(); this.provider = newProvider(conf); } @Test public void testCreate() { Assert.assertFalse("Sanity check", provider.exists(NAME)); DatasetDescriptor created = provider.create(NAME, testDescriptor); Assert.assertNotNull("Descriptor should be returned", created); Assert.assertTrue("Descriptor should exist", provider.exists(NAME)); Assert.assertEquals("Schema should match", testDescriptor.getSchema(), created.getSchema()); Assert.assertEquals("PartitionStrategy should match", testDescriptor.getPartitionStrategy(), created.getPartitionStrategy()); Assert.assertEquals("Format should match", testDescriptor.getFormat(), created.getFormat()); Assert.assertNotNull("Location URI should be set", created.getLocation()); Assert.assertNotNull("Location URI should have a scheme", created.getLocation().getScheme()); } public void testCreateWithLocation() throws URISyntaxException { Assert.assertFalse("Sanity check", provider.exists(NAME)); URI requestedLocation = new URI("hdfs:/tmp/data/my_data_set"); DatasetDescriptor requested = new DatasetDescriptor.Builder(testDescriptor) .location(requestedLocation) .build(); final DatasetDescriptor created; try { created = provider.create(NAME, requested); } catch (MetadataProviderException ex) { // this is expected if the provider doesn't support requested locations return; } // if supported, the location should be unchanged. Assert.assertNotNull("Descriptor should be returned", created); Assert.assertTrue("Descriptor should exist", provider.exists(NAME)); Assert.assertEquals("Requested locations should match", requestedLocation, created.getLocation()); } public void ensureCreated() { // use testCreate to create NAME testCreate(); Assert.assertTrue("Sanity check", provider.exists(NAME)); } @Test(expected=DatasetExistsException.class) public void testCreateAlreadyExists() { ensureCreated(); provider.create(NAME, anotherDescriptor); } @Test(expected=IllegalArgumentException.class) public void testCreateFailsNullName() { provider.create(null, testDescriptor); } @Test(expected=IllegalArgumentException.class) public void testCreateFailsNullDescriptor() { provider.create(NAME, null); } @Test public void testLoad() { ensureCreated(); DatasetDescriptor loaded = provider.load(NAME); Assert.assertNotNull("DatasetDescriptor should be returned", loaded); Assert.assertEquals("Schema should match", testDescriptor.getSchema(), loaded.getSchema()); Assert.assertEquals("PartitionStrategy should match", testDescriptor.getPartitionStrategy(), loaded.getPartitionStrategy()); Assert.assertEquals("Format should match", testDescriptor.getFormat(), loaded.getFormat()); } @Test(expected=DatasetNotFoundException.class) public void testLoadNoDataset() { Assert.assertFalse("Sanity check", provider.exists(NAME)); provider.load(NAME); } @Test(expected=IllegalArgumentException.class) public void testLoadFailsNullName() { provider.load(null); } public void testUpdate() { ensureCreated(); /* * To be clear: we are testing that even crazy, incompatible changes are * happily saved by the MetadataProvider. Rule enforcement is done upstream * by libraries that are in a better position to make decisions about what * changes are incompatible. */ final DatasetDescriptor saved = provider.update(NAME, anotherDescriptor); Assert.assertNotNull("Updated Descriptor should be returned", saved); Assert.assertEquals("Schema should match update", anotherDescriptor.getSchema(), saved.getSchema()); Assert.assertEquals("PartitionStrategy should match update", anotherDescriptor.getPartitionStrategy(), saved.getPartitionStrategy()); Assert.assertEquals("Format should match update", anotherDescriptor.getFormat(), saved.getFormat()); } @Test(expected=DatasetNotFoundException.class) public void testUpdateFailsNoDataset() { provider.update(NAME, testDescriptor); } @Test(expected=IllegalArgumentException.class) public void testUpdateFailsNullName() { provider.update(null, testDescriptor); } @Test(expected=IllegalArgumentException.class) public void testUpdateFailsNullDescriptor() { provider.update(NAME, null); } public void testDelete() { ensureCreated(); boolean result = provider.delete(NAME); Assert.assertTrue("Delete descriptor should return true", result); result = provider.delete(NAME); Assert.assertFalse("Delete non-existent descriptor should return false", result); } @Test(expected=IllegalArgumentException.class) public void testDeleteFailsNullName() { provider.delete(null); } @Test public void testExists() { Assert.assertFalse(provider.exists(NAME)); provider.create(NAME, testDescriptor); Assert.assertTrue(provider.exists(NAME)); provider.delete(NAME); Assert.assertFalse(provider.exists(NAME)); } @Test(expected=IllegalArgumentException.class) public void testExistsNullName() { provider.exists(null); } @Test public void testList() { Assert.assertEquals(ImmutableMultiset.of(), ImmutableMultiset.copyOf(provider.list())); provider.create("test1", testDescriptor); Assert.assertEquals(ImmutableMultiset.of("test1"), ImmutableMultiset.copyOf(provider.list())); provider.create("test2", testDescriptor); Assert.assertEquals(ImmutableMultiset.of("test1", "test2"), ImmutableMultiset.copyOf(provider.list())); provider.create("test3", testDescriptor); Assert.assertEquals(ImmutableMultiset.of("test1", "test2", "test3"), ImmutableMultiset.copyOf(provider.list())); provider.delete("test2"); Assert.assertEquals(ImmutableMultiset.of("test1", "test3"), ImmutableMultiset.copyOf(provider.list())); provider.delete("test3"); Assert.assertEquals(ImmutableMultiset.of("test1"), ImmutableMultiset.copyOf(provider.list())); provider.delete("test1"); Assert.assertEquals(ImmutableMultiset.of(), ImmutableMultiset.copyOf(provider.list())); } @Test public void testCustomProperties() { final String propName = "my.custom.property"; final String propValue = "string"; DatasetDescriptor descriptorWithProp = new DatasetDescriptor.Builder(testDescriptor) .property(propName, propValue) .build(); DatasetDescriptor created = provider.create(NAME, descriptorWithProp); junit.framework.Assert.assertTrue("Should have custom property", created.hasProperty(propName)); junit.framework.Assert.assertEquals( "Should have correct custom property value", propValue, created.getProperty(propName)); junit.framework.Assert.assertEquals("Should correctly list property names", Sets.newHashSet(propName), created.listProperties()); DatasetDescriptor loaded = provider.load(NAME); junit.framework.Assert.assertTrue("Should have custom property", loaded.hasProperty(propName)); junit.framework.Assert.assertEquals( "Should have correct custom property value", propValue, loaded.getProperty(propName)); junit.framework.Assert.assertEquals("Should correctly list property names", Sets.newHashSet(propName), loaded.listProperties()); } }
apache-2.0
jjeb/kettle-trunk
engine/src/org/pentaho/di/trans/steps/tableoutput/TableOutputData.java
3106
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.trans.steps.tableoutput; import java.sql.PreparedStatement; import java.sql.Savepoint; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.BaseStepData; import org.pentaho.di.trans.step.StepDataInterface; /** * Storage class for table output step. * * @author Matt * @since 24-jan-2005 */ public class TableOutputData extends BaseStepData implements StepDataInterface { public Database db; public int warnings; public String tableName; public int valuenrs[]; // Stream valuename nrs to prevent searches. /** * Mapping between the SQL and the actual prepared statement. * Normally this is only one, but in case we have more then one, it's convenient to have this. */ public Map<String, PreparedStatement> preparedStatements; public int indexOfPartitioningField; /** Cache of the data formatter object */ public SimpleDateFormat dateFormater; /** Use batch mode or not? */ public boolean batchMode; public int indexOfTableNameField; public List<Object[]> batchBuffer; public boolean sendToErrorRow; public RowMetaInterface outputRowMeta; public RowMetaInterface insertRowMeta; public boolean useSafePoints; public Savepoint savepoint; public boolean releaseSavepoint; public DatabaseMeta databaseMeta; public Map<String, Integer> commitCounterMap; public int commitSize; public TableOutputData() { super(); db=null; warnings=0; tableName=null; preparedStatements = new Hashtable<String, PreparedStatement>(); indexOfPartitioningField = -1; indexOfTableNameField = -1; batchBuffer = new ArrayList<Object[]>(); commitCounterMap = new HashMap<String, Integer>(); releaseSavepoint = true; } }
apache-2.0
McLeodMoores/starling
projects/engine/src/main/java/com/opengamma/engine/cache/AbstractIdentifierMap.java
2685
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.engine.cache; import java.util.Collection; import java.util.HashSet; import java.util.Set; import com.opengamma.engine.value.ValueSpecification; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.LongCollection; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; /** * Partial implementation of {@link IdentifierMap}. A real implementation should * handle the multiple value lookup more efficiently. */ public abstract class AbstractIdentifierMap implements IdentifierMap { @Override public Object2LongMap<ValueSpecification> getIdentifiers(final Collection<ValueSpecification> specifications) { return getIdentifiers(this, specifications); } public static Object2LongMap<ValueSpecification> getIdentifiers(final IdentifierMap map, final Collection<ValueSpecification> specifications) { final Object2LongMap<ValueSpecification> identifiers = new Object2LongOpenHashMap<>(); for (final ValueSpecification specification : specifications) { identifiers.put(specification, map.getIdentifier(specification)); } return identifiers; } @Override public Long2ObjectMap<ValueSpecification> getValueSpecifications(final LongCollection identifiers) { return getValueSpecifications(this, identifiers); } public static Long2ObjectMap<ValueSpecification> getValueSpecifications(final IdentifierMap map, final LongCollection identifiers) { final Long2ObjectMap<ValueSpecification> specifications = new Long2ObjectOpenHashMap<>(); for (final Long identifier : identifiers) { specifications.put(identifier, map.getValueSpecification(identifier)); } return specifications; } public static void convertIdentifiers(final IdentifierMap map, final IdentifierEncodedValueSpecifications object) { final Set<ValueSpecification> valueSpecifications = new HashSet<>(); object.collectValueSpecifications(valueSpecifications); object.convertValueSpecifications(map.getIdentifiers(valueSpecifications)); } public static void resolveIdentifiers(final IdentifierMap map, final IdentifierEncodedValueSpecifications object) { final LongSet identifiers = new LongOpenHashSet(); object.collectIdentifiers(identifiers); object.convertIdentifiers(map.getValueSpecifications(identifiers)); } }
apache-2.0
looker-open-source/java-spanner
google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/FailedQuery.java
3393
/* * Copyright 2019 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.cloud.spanner.connection; import com.google.cloud.spanner.AbortedException; import com.google.cloud.spanner.Options.QueryOption; import com.google.cloud.spanner.ResultSet; import com.google.cloud.spanner.SpannerException; import com.google.cloud.spanner.SpannerExceptionFactory; import com.google.cloud.spanner.connection.ReadWriteTransaction.RetriableStatement; import com.google.cloud.spanner.connection.StatementParser.ParsedStatement; import com.google.common.base.Preconditions; import java.util.Objects; /** * A query that failed with a {@link SpannerException} on a {@link ReadWriteTransaction}. The query * can be retried if the transaction is aborted, and should throw the same exception during retry as * during the original transaction. */ final class FailedQuery implements RetriableStatement { private final ReadWriteTransaction transaction; private final SpannerException exception; private final ParsedStatement statement; private final AnalyzeMode analyzeMode; private final QueryOption[] options; FailedQuery( ReadWriteTransaction transaction, SpannerException exception, ParsedStatement statement, AnalyzeMode analyzeMode, QueryOption... options) { Preconditions.checkNotNull(transaction); Preconditions.checkNotNull(exception); Preconditions.checkNotNull(statement); this.transaction = transaction; this.exception = exception; this.statement = statement; this.analyzeMode = analyzeMode; this.options = options; } @Override public void retry(AbortedException aborted) throws AbortedException { transaction .getStatementExecutor() .invokeInterceptors(statement, StatementExecutionStep.RETRY_STATEMENT, transaction); try { transaction .getStatementExecutor() .invokeInterceptors(statement, StatementExecutionStep.RETRY_STATEMENT, transaction); try (ResultSet rs = DirectExecuteResultSet.ofResultSet( transaction.internalExecuteQuery(statement, analyzeMode, options))) { // Do nothing with the results, we are only interested in whether the statement throws the // same exception as in the original transaction. } } catch (AbortedException e) { // Propagate abort to force a new retry. throw e; } catch (SpannerException e) { // Check that we got the same exception as in the original transaction if (e.getErrorCode() == exception.getErrorCode() && Objects.equals(e.getMessage(), exception.getMessage())) { return; } throw SpannerExceptionFactory.newAbortedDueToConcurrentModificationException(aborted, e); } throw SpannerExceptionFactory.newAbortedDueToConcurrentModificationException(aborted); } }
apache-2.0
FOC-framework/framework
foc/src/com/foc/business/config/BusinessConfig.java
6277
/******************************************************************************* * Copyright 2016 Antoine Nicolas SAMAHA * * 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.foc.business.config; import com.foc.Globals; import com.foc.admin.FocGroup; import com.foc.admin.FocGroupDesc; import com.foc.admin.UserSession; import com.foc.business.company.Company; import com.foc.business.notifier.FocNotificationEmailTemplate; import com.foc.business.workflow.WFTitle; import com.foc.desc.FocConstructor; import com.foc.desc.FocObject; import com.foc.list.FocList; @SuppressWarnings("serial") public class BusinessConfig extends FocObject { public BusinessConfig(FocConstructor constr) { super(constr); newFocProperties(); } @Override public String getSelectionFilterExpressionFor_ObjectProperty(int fieldID) { String filter = super.getSelectionFilterExpressionFor_ObjectProperty(fieldID); if(fieldID == BusinessConfigDesc.FLD_GuestUserGroup) { filter = FocGroupDesc.FNAME_GUEST_APPLICABLE; } return filter; } public String getPartyPrefix(){ String codePrefix = getPropertyString(BusinessConfigDesc.FLD_ADR_BOOK_PARTY_PREFIX); if(codePrefix != null){ codePrefix = adjustCodePrefix(codePrefix); } return codePrefix; } public String getPartyCodePrefix(){ return getPropertyString(BusinessConfigDesc.FLD_ADR_BOOK_PARTY_PREFIX); } public void setPartyCodePrefix(String prefix){ setPropertyString(BusinessConfigDesc.FLD_ADR_BOOK_PARTY_PREFIX, prefix); } public FocNotificationEmailTemplate getGeneralEmailTemplate(){ return (FocNotificationEmailTemplate) getPropertyObject(BusinessConfigDesc.FLD_GENERAL_EMAIL_TEMPLATE); } public void setGeneralEmailTemplate(FocNotificationEmailTemplate emailTemplate){ setPropertyObject(BusinessConfigDesc.FLD_GENERAL_EMAIL_TEMPLATE, emailTemplate); } public FocNotificationEmailTemplate getEmailTemplateUserCreation(){ return (FocNotificationEmailTemplate) getPropertyObject(BusinessConfigDesc.FLD_EmailTmplUserCreation); } public void setEmailTemplateUserCreation(FocNotificationEmailTemplate emailTemplate){ setPropertyObject(BusinessConfigDesc.FLD_EmailTmplUserCreation, emailTemplate); } public FocNotificationEmailTemplate getEmailTemplatePasswordChange(){ return (FocNotificationEmailTemplate) getPropertyObject(BusinessConfigDesc.FLD_EmailTmplPwdChange); } public void setEmailTemplatePasswordChange(FocNotificationEmailTemplate emailTemplate){ setPropertyObject(BusinessConfigDesc.FLD_EmailTmplPwdChange, emailTemplate); } public FocGroup getGuestGroup(){ return (FocGroup) getPropertyObject(BusinessConfigDesc.FLD_GuestUserGroup); } public WFTitle getGuestTitle(){ return (WFTitle) getPropertyObject(BusinessConfigDesc.FLD_GuestUserTitle); } public String getPartySeparator(){ return getPropertyString(BusinessConfigDesc.FLD_ADR_BOOK_PARTY_SEPERATOR); } public int getPartyNbrDigits(){ return getPropertyInteger(BusinessConfigDesc.FLD_ADR_BOOK_PARTY_NBR_DIGITS); } public void setPartyNbrDigits(int nbrDigits){ setPropertyInteger(BusinessConfigDesc.FLD_ADR_BOOK_PARTY_NBR_DIGITS, nbrDigits); } public boolean getPartyResetCode(){ return getPropertyBoolean(BusinessConfigDesc.FLD_ADR_BOOK_PARTY_RESET_NUMBERING_WHEN_PREFIX_CHANGE); } public boolean isAddressBookParty121(){ return getPropertyBoolean(BusinessConfigDesc.FLD_ADR_BOOK_TO_PARTY_ONE_2_ONE); } public void setAddressBookParty121(boolean isAddressBookParty121){ setPropertyBoolean(BusinessConfigDesc.FLD_ADR_BOOK_TO_PARTY_ONE_2_ONE, isAddressBookParty121); } public boolean isContactInPartyMandatory(){ return getPropertyBoolean(BusinessConfigDesc.FLD_CONTACT_IN_PARTY_MANDATORY); } public void setContactInPartyMandatory(boolean isContactInPartyMandatory){ setPropertyBoolean(BusinessConfigDesc.FLD_CONTACT_IN_PARTY_MANDATORY, isContactInPartyMandatory); } public boolean isAllowModif_UndDesc_EvenIfFilledInUnderlying(){ return getPropertyBoolean(BusinessConfigDesc.FLD_ALLOW_MODIF_OF_UND_DESC_EVEN_IF_FILLED_IN_UND); } public String getProjectIdPrefix(){ return getPropertyString(BusinessConfigDesc.FLD_PROJECT_ID_PREFIX); } public int getProjectIdNbrDigits(){ return getPropertyInteger(BusinessConfigDesc.FLD_PROJECT_ID_NBR_DIGITS); } public static BusinessConfig getOrCreateForCompany(Company company){ BusinessConfig foundConfig = null; FocList basicsConfigList = BusinessConfigDesc.getList(FocList.LOAD_IF_NEEDED); for(int i=0; i<basicsConfigList.size() && foundConfig == null; i++){ BusinessConfig cfg = (BusinessConfig) basicsConfigList.getFocObject(i); if(cfg != null && cfg.isForCompany(company)){ foundConfig = cfg; } } if(foundConfig == null){ foundConfig = (BusinessConfig) basicsConfigList.newEmptyItem(); foundConfig.setCompany(company); basicsConfigList.add(foundConfig); } return foundConfig; } // private static BusinessConfig generalConfig = null; public synchronized static BusinessConfig getInstance(){ BusinessConfig generalConfig = (BusinessConfig) UserSession.getParameter("BUSINESS_CONFIG"); if(generalConfig == null || !generalConfig.isForCurrentCompany()){ generalConfig = getOrCreateForCompany(Globals.getApp().getCurrentCompany()); if(generalConfig != null){ UserSession.putParameter("BUSINESS_CONFIG", generalConfig); } } return generalConfig; } }
apache-2.0
Craftware/Kornell
kornell-gwt/src/main/java/kornell/scorm/client/scorm12/SCORM12Binder.java
2266
package kornell.scorm.client.scorm12; import static kornell.scorm.client.scorm12.Scorm12.logger; public class SCORM12Binder { public static void bindToWindow(SCORM12Adapter api) { nativeBind(api); logger.info("SCORM 1.2 API Adapter bound to window."); } public static native void nativeBind(SCORM12Adapter api) /*-{ var API = $wnd.API || {}; //[instance-expr.]@class-name::method-name(param-signature)(arguments) API.LMSInitialize = function(param) { return api.@kornell.scorm.client.scorm12.SCORM12Adapter::LMSInitialize(Ljava/lang/String;)(param); } API.LMSFinish = function(param) { return api.@kornell.scorm.client.scorm12.SCORM12Adapter::LMSFinish(Ljava/lang/String;)(param); } API.LMSGetLastError = function() { return api.@kornell.scorm.client.scorm12.SCORM12Adapter::LMSGetLastError()(); } API.LMSGetValue = function(param,moduleUUID) { return api.@kornell.scorm.client.scorm12.SCORM12Adapter::LMSGetValue(Ljava/lang/String;Ljava/lang/String;)(param,moduleUUID); } API.LMSCommit = function(param) { return api.@kornell.scorm.client.scorm12.SCORM12Adapter::LMSCommit(Ljava/lang/String;)(param); } API.LMSSetValue = function(param, value, moduleUUID) { switch (typeof value) { case "number": var dbl = @java.lang.Double::valueOf(D)(value); return api.@kornell.scorm.client.scorm12.SCORM12Adapter::LMSSetDouble(Ljava/lang/String;Ljava/lang/Double;Ljava/lang/String;)(param,dbl,moduleUUID); case "string": return api.@kornell.scorm.client.scorm12.SCORM12Adapter::LMSSetString(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)(param,value,moduleUUID); default: throw "SCORM 1.2 Unsupported value type" } } // Modules Extension API.launch = function(param) { return api.@kornell.scorm.client.scorm12.SCORM12Adapter::launch(Ljava/lang/String;)(param); } // End Of Modules Extension $wnd.API = API; }-*/; }
apache-2.0
millmanorama/autopsy
ImageGallery/src/org/sleuthkit/autopsy/imagegallery/gui/DataSourceCell.java
2043
/* * Autopsy Forensic Browser * * Copyright 2018 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.imagegallery.gui; import java.util.Map; import java.util.Optional; import javafx.scene.control.ListCell; import org.sleuthkit.datamodel.DataSource; /** * Cell used to represent a DataSource in the dataSourceComboBoxes */ public class DataSourceCell extends ListCell<Optional<DataSource>> { private final Map<DataSource, Boolean> dataSourcesTooManyFiles; public DataSourceCell(Map<DataSource, Boolean> dataSourcesViewable) { this.dataSourcesTooManyFiles = dataSourcesViewable; } @Override protected void updateItem(Optional<DataSource> item, boolean empty) { super.updateItem(item, empty); if (empty || item == null) { setText(""); } else { DataSource dataSource = item.orElse(null); String text = (dataSource == null) ? "All" : dataSource.getName() + " (Id: " + dataSource.getId() + ")"; Boolean tooManyFilesInDataSource = dataSourcesTooManyFiles.getOrDefault(dataSource, false); if (tooManyFilesInDataSource) { text += " - Too many files"; setStyle("-fx-opacity : .5"); } else { setGraphic(null); setStyle("-fx-opacity : 1"); } setDisable(tooManyFilesInDataSource); setText(text); } } }
apache-2.0
niyueming/NApply
sample/src/main/java/net/nym/napply/FrescoSampleActivity.java
6885
/* * Copyright (c) 2016 Ni YueMing<niyueming@163.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 net.nym.napply; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.ColorMatrixColorFilter; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.drawable.Animatable; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.facebook.common.logging.FLog; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.BaseControllerListener; import com.facebook.drawee.generic.GenericDraweeHierarchy; import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.image.ImageInfo; import com.facebook.imagepipeline.image.QualityInfo; import net.nym.napply.library.common.FrescoImageLoader; import net.nym.napply.library.utils.Log; /** * @author niyueming * @date 2016-08-05 * @time 16:19 */ public class FrescoSampleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fresco_sample_activity); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); SimpleDraweeView simpleDraweeView = (SimpleDraweeView) findViewById(R.id.my_image_view); FrescoImageLoader.getInstance().setImageURI(simpleDraweeView,"http://image.39.net/104/5/663072_1.jpg"); // simpleDraweeView.setImageURI("http://image.39.net/104/5/663072_1.jpg"); // DraweeController controller = Fresco.newDraweeControllerBuilder() // .setUri("http://image.39.net/104/5/663072_1.jpg") // .setOldController(simpleDraweeView.getController()) // .setControllerListener(new BaseControllerListener<ImageInfo>(){ // @Override // public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) { // if (imageInfo == null) { // return; // } // QualityInfo qualityInfo = imageInfo.getQualityInfo(); // Log.i("Final image received! " + // "Size %d x %d" + // "Quality level %d, good enough: %s, full quality: %s", // imageInfo.getWidth(), // imageInfo.getHeight(), // qualityInfo.getQuality(), // qualityInfo.isOfGoodEnoughQuality(), // qualityInfo.isOfFullQuality()); // } // // @Override // public void onFailure(String id, Throwable throwable) { // super.onFailure(id, throwable); // } // }) // .build(); // simpleDraweeView.setController(controller); SimpleDraweeView gifDraweeView = (SimpleDraweeView) findViewById(R.id.gifImage); // simpleDraweeView.setImageURI("http://image.39.net/104/5/663072_1.jpg"); // DraweeController gifController = Fresco.newDraweeControllerBuilder() // .setUri("res:///" + R.mipmap.gif) // .setOldController(gifDraweeView.getController()) // .setAutoPlayAnimations(true) // .setControllerListener(new BaseControllerListener<ImageInfo>(){ // @Override // public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) { // if (imageInfo == null) { // return; // } // QualityInfo qualityInfo = imageInfo.getQualityInfo(); // Log.i("Final image received! " + // "Size %d x %d" + // "Quality level %d, good enough: %s, full quality: %s", // imageInfo.getWidth(), // imageInfo.getHeight(), // qualityInfo.getQuality(), // qualityInfo.isOfGoodEnoughQuality(), // qualityInfo.isOfFullQuality()); // } // // @Override // public void onFailure(String id, Throwable throwable) { // super.onFailure(id, throwable); // } // }) // .build(); // gifDraweeView.setController(gifController); FrescoImageLoader.getInstance().setController(gifDraweeView,"res:///" + R.mipmap.gif,new BaseControllerListener<ImageInfo>(){ @Override public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) { if (imageInfo == null) { return; } QualityInfo qualityInfo = imageInfo.getQualityInfo(); Log.i("Final image received! " + "Size %d x %d" + "Quality level %d, good enough: %s, full quality: %s", imageInfo.getWidth(), imageInfo.getHeight(), qualityInfo.getQuality(), qualityInfo.isOfGoodEnoughQuality(), qualityInfo.isOfFullQuality()); } @Override public void onFailure(String id, Throwable throwable) { super.onFailure(id, throwable); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }
apache-2.0
Bouquet2/AssoGenda
app/src/main/java/fr/paris10/projet/assogenda/assogenda/ui/fragment/CreateAssociationFragment.java
5744
package fr.paris10.projet.assogenda.assogenda.ui.fragment; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import fr.paris10.projet.assogenda.assogenda.R; /** * A simple {@link Fragment} subclass. * Create an instance of this fragment. */ public class CreateAssociationFragment extends Fragment implements View.OnClickListener { private OnFragmentInteractionListener mListener; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment AssociationMainFragment. */ public static CreateAssociationFragment newInstance() { return new CreateAssociationFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.fragment_create_association, container, false); Button buttonAddImage = (Button) v.findViewById(R.id.fragment_create_association_button_logo); buttonAddImage.setOnClickListener(this); Button buttonValidate = (Button) v.findViewById(R.id.fragment_create_association_button_validate); buttonValidate.setOnClickListener(this); listenerAssociationNameInput(v); return v; } //For API Level 23 @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (CreateAssociationFragment.OnFragmentInteractionListener) context; } else { throw new FragmentRuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } //For API Level 22 (deprecated) @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (CreateAssociationFragment.OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new FragmentClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * Manage buttons actions. * @param view */ @Override public void onClick(View view) { switch (view.getId()) { case R.id.fragment_create_association_button_validate: mListener.onCreateAssociationFragmentInteraction(); break; case R.id.fragment_create_association_button_logo: mListener.onAddImageAssociationFragmentInteraction(); break; default: break; } } /** * Notify user if association name is already taken */ private void listenerAssociationNameInput(View v) { final EditText input = (EditText) v.findViewById(R.id.fragment_create_association_name); input.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { Log.d("afterTextChanged", "before text changed : " + charSequence.toString()); } @Override public void onTextChanged(final CharSequence charSequence, int i, int i1, int i2) { FirebaseDatabase.getInstance().getReference("association") .orderByChild("clear_name") .equalTo(charSequence.toString().toLowerCase().trim().replaceAll(" ", "")) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { input.setError(String.format("%s is already taken", charSequence.toString())); } } @Override public void onCancelled(DatabaseError databaseError) { Log.d("onCancelled", "validateAssocationName : " + databaseError.getMessage()); } }); } @Override public void afterTextChanged(Editable editable) { Log.d("afterTextChanged", "After text changed : " + editable.toString()); } }); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. */ public interface OnFragmentInteractionListener { void onCreateAssociationFragmentInteraction(); void onAddImageAssociationFragmentInteraction(); } }
apache-2.0
bhecquet/seleniumRobot
core/src/test/java/com/seleniumtests/GenericTest.java
6096
/** * Orignal work: Copyright 2015 www.seleniumtests.com * Modified work: Copyright 2016 www.infotel.com * Copyright 2017-2019 B.Hecquet * * 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.seleniumtests; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.internal.TestNGMethod; import org.testng.internal.TestResult; import org.testng.internal.annotations.DefaultAnnotationTransformer; import org.testng.internal.annotations.JDK15AnnotationFinder; import org.testng.xml.XmlSuite; import org.testng.xml.XmlTest; import com.seleniumtests.core.SeleniumTestsContext; import com.seleniumtests.core.SeleniumTestsContextManager; import com.seleniumtests.core.runner.SeleniumRobotTestPlan; import com.seleniumtests.driver.WebUIDriver; import com.seleniumtests.util.logging.ScenarioLogger; import com.seleniumtests.util.logging.SeleniumRobotLogger; import com.seleniumtests.util.video.VideoCaptureMode; public class GenericTest { protected static final ScenarioLogger logger = ScenarioLogger.getScenarioLogger(SeleniumRobotTestPlan.class); /** * Reinitializes context between tests so that it's clean before test starts * Beware that this reset does not affect the set context * @param testNGCtx */ @BeforeMethod(groups={"ut", "it", "ut context2"}) public void initTest(final ITestContext testNGCtx, final ITestResult testResult) { SeleniumTestsContextManager.initGlobalContext(testNGCtx); SeleniumTestsContextManager.initThreadContext(testNGCtx, testResult); SeleniumTestsContextManager.getThreadContext().setSoftAssertEnabled(false); SeleniumTestsContextManager.getGlobalContext().setSoftAssertEnabled(false); SeleniumTestsContextManager.getThreadContext().setVideoCapture(VideoCaptureMode.FALSE.toString()); SeleniumTestsContextManager.getGlobalContext().setVideoCapture(VideoCaptureMode.FALSE.toString()); SeleniumTestsContext.resetOutputFolderNames(); } public void initThreadContext(final ITestContext testNGCtx) { SeleniumTestsContextManager.initGlobalContext(testNGCtx); try { SeleniumTestsContextManager.initThreadContext(testNGCtx, generateResult(testNGCtx, getClass())); } catch (NoSuchMethodException | SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { } SeleniumTestsContextManager.getThreadContext().setSoftAssertEnabled(false); SeleniumTestsContextManager.getGlobalContext().setSoftAssertEnabled(false); SeleniumTestsContextManager.getThreadContext().setVideoCapture(VideoCaptureMode.FALSE.toString()); SeleniumTestsContextManager.getGlobalContext().setVideoCapture(VideoCaptureMode.FALSE.toString()); SeleniumTestsContext.resetOutputFolderNames(); } @AfterMethod(groups={"ut", "it", "ut context2"}, alwaysRun=true) public void reset() { resetTestNGREsultAndLogger(); } @AfterClass(groups={"ut", "it", "ut context2"}, alwaysRun=true) public void closeBrowser() { WebUIDriver.cleanUp(); } public static File createFileFromResource(String resource) throws IOException { File tempFile = File.createTempFile("img", null); tempFile.deleteOnExit(); FileUtils.copyInputStreamToFile(Thread.currentThread().getContextClassLoader().getResourceAsStream(resource), tempFile); return tempFile; } public static String readResourceToString(String resourceName) throws IOException { return IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName), StandardCharsets.UTF_8); } public static void resetCurrentTestResult() { //Reporter.setCurrentTestResult(null); // do not reset, TestNG do this for us } public static void resetTestNGREsultAndLogger() { resetCurrentTestResult(); try { SeleniumRobotLogger.reset(); } catch (IOException e) { logger.error("Cannot delete log file", e); } } /** * Generate a ITestResult from scratch * @param testNGCtx * @return * @throws NoSuchMethodException * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static ITestResult generateResult(final ITestContext testNGCtx, final Class<?> clazz) throws NoSuchMethodException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { ITestResult testResult = TestResult.newEmptyTestResult(); testResult.setParameters(new String[] {"foo", "bar"}); XmlSuite suite = new XmlSuite(); suite.setName("TmpSuite"); XmlTest test = new XmlTest(suite); test.setName("myTestNg"); ITestNGMethod testMethod = new TestNGMethod(clazz.getMethod("myTest"), new JDK15AnnotationFinder(new DefaultAnnotationTransformer()), test, null); Field methodField = TestResult.class.getDeclaredField("m_method"); methodField.setAccessible(true); methodField.set(testResult, testMethod); Field contextField = TestResult.class.getDeclaredField("m_context"); contextField.setAccessible(true); contextField.set(testResult, testNGCtx); return testResult; } public void myTest() { } }
apache-2.0
dbolser-ebi/ensj-healthcheck
test/src/org/ensembl/healthcheck/test/DBUtilsTest.java
1001
/* * Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute * * 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.ensembl.healthcheck.test; import org.ensembl.healthcheck.util.DBUtils; import org.testng.Assert; import org.testng.annotations.Test; public class DBUtilsTest { @Test public void testGenerateTempDatabaseName() { String dbName = DBUtils.generateTempDatabaseName(); Assert.assertNotNull(dbName); } }
apache-2.0
sdliang1013/account-import
src/main/java/com/caul/modules/user/User.java
834
package com.caul.modules.user; import cn.easybuild.pojo.StringPojo; public class User extends StringPojo { private String userName; private String password; private String realName; private int userType; public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getUserType() { return userType; } public void setUserType(int userType) { this.userType = userType; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
apache-2.0
leafcoin/leafcoinj
core/src/main/java/com/google/leafcoin/core/FullPrunedBlockChain.java
25328
/* * Copyright 2012 Matt Corallo. * * 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.leafcoin.core; import com.google.leafcoin.script.Script; import com.google.leafcoin.store.BlockStoreException; import com.google.leafcoin.store.FullPrunedBlockStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.concurrent.*; import static com.google.common.base.Preconditions.checkState; /** * <p>A FullPrunedBlockChain works in conjunction with a {@link FullPrunedBlockStore} to verify all the rules of the * Bitcoin system, with the downside being a larg cost in system resources. Fully verifying means all unspent transaction * outputs are stored. Once a transaction output is spent and that spend is buried deep enough, the data related to it * is deleted to ensure disk space usage doesn't grow forever. For this reason a pruning node cannot serve the full * block chain to other clients, but it nevertheless provides the same security guarantees as a regular Satoshi * client does.</p> */ public class FullPrunedBlockChain extends AbstractBlockChain { private static final Logger log = LoggerFactory.getLogger(FullPrunedBlockChain.class); /** Keeps a map of block hashes to StoredBlocks. */ protected final FullPrunedBlockStore blockStore; // Whether or not to execute scriptPubKeys before accepting a transaction (i.e. check signatures). private boolean runScripts = true; /** * Constructs a BlockChain connected to the given wallet and store. To obtain a {@link Wallet} you can construct * one from scratch, or you can deserialize a saved wallet from disk using {@link Wallet#loadFromFile(java.io.File)} */ public FullPrunedBlockChain(NetworkParameters params, Wallet wallet, FullPrunedBlockStore blockStore) throws BlockStoreException { this(params, new ArrayList<BlockChainListener>(), blockStore); if (wallet != null) addWallet(wallet); } /** * Constructs a BlockChain that has no wallet at all. This is helpful when you don't actually care about sending * and receiving coins but rather, just want to explore the network data structures. */ public FullPrunedBlockChain(NetworkParameters params, FullPrunedBlockStore blockStore) throws BlockStoreException { this(params, new ArrayList<BlockChainListener>(), blockStore); } /** * Constructs a BlockChain connected to the given list of wallets and a store. */ public FullPrunedBlockChain(NetworkParameters params, List<BlockChainListener> listeners, FullPrunedBlockStore blockStore) throws BlockStoreException { super(params, listeners, blockStore); this.blockStore = blockStore; // Ignore upgrading for now this.chainHead = blockStore.getVerifiedChainHead(); } @Override protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block header, TransactionOutputChanges txOutChanges) throws BlockStoreException, VerificationException { StoredBlock newBlock = storedPrev.build(header); blockStore.put(newBlock, new StoredUndoableBlock(newBlock.getHeader().getHash(), txOutChanges)); return newBlock; } @Override protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block block) throws BlockStoreException, VerificationException { StoredBlock newBlock = storedPrev.build(block); blockStore.put(newBlock, new StoredUndoableBlock(newBlock.getHeader().getHash(), block.transactions)); return newBlock; } @Override protected boolean shouldVerifyTransactions() { return true; } /** * Whether or not to run scripts whilst accepting blocks (i.e. checking signatures, for most transactions). * If you're accepting data from an untrusted node, such as one found via the P2P network, this should be set * to true (which is the default). If you're downloading a chain from a node you control, script execution * is redundant because you know the connected node won't relay bad data to you. In that case it's safe to set * this to false and obtain a significant speedup. */ public void setRunScripts(boolean value) { this.runScripts = value; } //TODO: Remove lots of duplicated code in the two connectTransactions // TODO: execute in order of largest transaction (by input count) first ExecutorService scriptVerificationExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); /** A job submitted to the executor which verifies signatures. */ private static class Verifier implements Callable<VerificationException> { final Transaction tx; final List<Script> prevOutScripts; final boolean enforcePayToScriptHash; public Verifier(final Transaction tx, final List<Script> prevOutScripts, final boolean enforcePayToScriptHash) { this.tx = tx; this.prevOutScripts = prevOutScripts; this.enforcePayToScriptHash = enforcePayToScriptHash; } @Nullable @Override public VerificationException call() throws Exception { try{ ListIterator<Script> prevOutIt = prevOutScripts.listIterator(); for (int index = 0; index < tx.getInputs().size(); index++) { tx.getInputs().get(index).getScriptSig().correctlySpends(tx, index, prevOutIt.next(), enforcePayToScriptHash); } } catch (VerificationException e) { return e; } return null; } } @Override protected TransactionOutputChanges connectTransactions(int height, Block block) throws VerificationException, BlockStoreException { checkState(lock.isHeldByCurrentThread()); if (block.transactions == null) throw new RuntimeException("connectTransactions called with Block that didn't have transactions!"); if (!params.passesCheckpoint(height, block.getHash())) throw new VerificationException("Block failed checkpoint lockin at " + height); blockStore.beginDatabaseBatchWrite(); LinkedList<StoredTransactionOutput> txOutsSpent = new LinkedList<StoredTransactionOutput>(); LinkedList<StoredTransactionOutput> txOutsCreated = new LinkedList<StoredTransactionOutput>(); long sigOps = 0; final boolean enforcePayToScriptHash = block.getTimeSeconds() >= NetworkParameters.BIP16_ENFORCE_TIME; if (scriptVerificationExecutor.isShutdown()) scriptVerificationExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); List<Future<VerificationException>> listScriptVerificationResults = new ArrayList<Future<VerificationException>>(block.transactions.size()); try { if (!params.isCheckpoint(height)) { // BIP30 violator blocks are ones that contain a duplicated transaction. They are all in the // checkpoints list and we therefore only check non-checkpoints for duplicated transactions here. See the // BIP30 document for more details on this: https://en.bitcoin.it/wiki/BIP_0030 for (Transaction tx : block.transactions) { Sha256Hash hash = tx.getHash(); // If we already have unspent outputs for this hash, we saw the tx already. Either the block is // being added twice (bug) or the block is a BIP30 violator. if (blockStore.hasUnspentOutputs(hash, tx.getOutputs().size())) throw new VerificationException("Block failed BIP30 test!"); if (enforcePayToScriptHash) // We already check non-BIP16 sigops in Block.verifyTransactions(true) sigOps += tx.getSigOpCount(); } } BigInteger totalFees = BigInteger.ZERO; BigInteger coinbaseValue = null; for (final Transaction tx : block.transactions) { boolean isCoinBase = tx.isCoinBase(); BigInteger valueIn = BigInteger.ZERO; BigInteger valueOut = BigInteger.ZERO; final List<Script> prevOutScripts = new LinkedList<Script>(); if (!isCoinBase) { // For each input of the transaction remove the corresponding output from the set of unspent // outputs. for (int index = 0; index < tx.getInputs().size(); index++) { TransactionInput in = tx.getInputs().get(index); StoredTransactionOutput prevOut = blockStore.getTransactionOutput(in.getOutpoint().getHash(), in.getOutpoint().getIndex()); if (prevOut == null) throw new VerificationException("Attempted to spend a non-existent or already spent output!"); // Coinbases can't be spent until they mature, to avoid re-orgs destroying entire transaction // chains. The assumption is there will ~never be re-orgs deeper than the spendable coinbase // chain depth. if (height - prevOut.getHeight() < params.getSpendableCoinbaseDepth()) throw new VerificationException("Tried to spend coinbase at depth " + (height - prevOut.getHeight())); // TODO: Check we're not spending the genesis transaction here. Satoshis code won't allow it. valueIn = valueIn.add(prevOut.getValue()); if (enforcePayToScriptHash) { if (new Script(prevOut.getScriptBytes()).isPayToScriptHash()) sigOps += Script.getP2SHSigOpCount(in.getScriptBytes()); if (sigOps > Block.MAX_BLOCK_SIGOPS) throw new VerificationException("Too many P2SH SigOps in block"); } prevOutScripts.add(new Script(prevOut.getScriptBytes())); //in.getScriptSig().correctlySpends(tx, index, new Script(params, prevOut.getScriptBytes(), 0, prevOut.getScriptBytes().length)); blockStore.removeUnspentTransactionOutput(prevOut); txOutsSpent.add(prevOut); } } Sha256Hash hash = tx.getHash(); for (TransactionOutput out : tx.getOutputs()) { valueOut = valueOut.add(out.getValue()); // For each output, add it to the set of unspent outputs so it can be consumed in future. StoredTransactionOutput newOut = new StoredTransactionOutput(hash, out.getIndex(), out.getValue(), height, isCoinBase, out.getScriptBytes()); blockStore.addUnspentTransactionOutput(newOut); txOutsCreated.add(newOut); } // All values were already checked for being non-negative (as it is verified in Transaction.verify()) // but we check again here just for defence in depth. Transactions with zero output value are OK. if (valueOut.signum() < 0 || valueOut.compareTo(params.MAX_MONEY) > 0) throw new VerificationException("Transaction output value out of rage"); if (isCoinBase) { coinbaseValue = valueOut; } else { if (valueIn.compareTo(valueOut) < 0 || valueIn.compareTo(params.MAX_MONEY) > 0) throw new VerificationException("Transaction input value out of range"); totalFees = totalFees.add(valueIn.subtract(valueOut)); } if (!isCoinBase && runScripts) { // Because correctlySpends modifies transactions, this must come after we are done with tx FutureTask<VerificationException> future = new FutureTask<VerificationException>(new Verifier(tx, prevOutScripts, enforcePayToScriptHash)); scriptVerificationExecutor.execute(future); listScriptVerificationResults.add(future); } } if (totalFees.compareTo(params.MAX_MONEY) > 0 || block.getBlockInflation(height).add(totalFees).compareTo(coinbaseValue) < 0) throw new VerificationException("Transaction fees out of range"); for (Future<VerificationException> future : listScriptVerificationResults) { VerificationException e; try { e = future.get(); } catch (InterruptedException thrownE) { throw new RuntimeException(thrownE); // Shouldn't happen } catch (ExecutionException thrownE) { log.error("Script.correctlySpends threw a non-normal exception: " + thrownE.getCause()); throw new VerificationException("Bug in Script.correctlySpends, likely script malformed in some new and interesting way.", thrownE); } if (e != null) throw e; } } catch (VerificationException e) { scriptVerificationExecutor.shutdownNow(); blockStore.abortDatabaseBatchWrite(); throw e; } catch (BlockStoreException e) { scriptVerificationExecutor.shutdownNow(); blockStore.abortDatabaseBatchWrite(); throw e; } return new TransactionOutputChanges(txOutsCreated, txOutsSpent); } @Override /** * Used during reorgs to connect a block previously on a fork */ protected synchronized TransactionOutputChanges connectTransactions(StoredBlock newBlock) throws VerificationException, BlockStoreException, PrunedException { checkState(lock.isHeldByCurrentThread()); if (!params.passesCheckpoint(newBlock.getHeight(), newBlock.getHeader().getHash())) throw new VerificationException("Block failed checkpoint lockin at " + newBlock.getHeight()); blockStore.beginDatabaseBatchWrite(); StoredUndoableBlock block = blockStore.getUndoBlock(newBlock.getHeader().getHash()); if (block == null) { // We're trying to re-org too deep and the data needed has been deleted. blockStore.abortDatabaseBatchWrite(); throw new PrunedException(newBlock.getHeader().getHash()); } TransactionOutputChanges txOutChanges; try { List<Transaction> transactions = block.getTransactions(); if (transactions != null) { LinkedList<StoredTransactionOutput> txOutsSpent = new LinkedList<StoredTransactionOutput>(); LinkedList<StoredTransactionOutput> txOutsCreated = new LinkedList<StoredTransactionOutput>(); long sigOps = 0; final boolean enforcePayToScriptHash = newBlock.getHeader().getTimeSeconds() >= NetworkParameters.BIP16_ENFORCE_TIME; if (!params.isCheckpoint(newBlock.getHeight())) { for(Transaction tx : transactions) { Sha256Hash hash = tx.getHash(); if (blockStore.hasUnspentOutputs(hash, tx.getOutputs().size())) throw new VerificationException("Block failed BIP30 test!"); } } BigInteger totalFees = BigInteger.ZERO; BigInteger coinbaseValue = null; if (scriptVerificationExecutor.isShutdown()) scriptVerificationExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); List<Future<VerificationException>> listScriptVerificationResults = new ArrayList<Future<VerificationException>>(transactions.size()); for(final Transaction tx : transactions) { boolean isCoinBase = tx.isCoinBase(); BigInteger valueIn = BigInteger.ZERO; BigInteger valueOut = BigInteger.ZERO; final List<Script> prevOutScripts = new LinkedList<Script>(); if (!isCoinBase) { for (int index = 0; index < tx.getInputs().size(); index++) { final TransactionInput in = tx.getInputs().get(index); final StoredTransactionOutput prevOut = blockStore.getTransactionOutput(in.getOutpoint().getHash(), in.getOutpoint().getIndex()); if (prevOut == null) throw new VerificationException("Attempted spend of a non-existent or already spent output!"); if (newBlock.getHeight() - prevOut.getHeight() < params.getSpendableCoinbaseDepth()) throw new VerificationException("Tried to spend coinbase at depth " + (newBlock.getHeight() - prevOut.getHeight())); valueIn = valueIn.add(prevOut.getValue()); if (enforcePayToScriptHash) { Script script = new Script(prevOut.getScriptBytes()); if (script.isPayToScriptHash()) sigOps += Script.getP2SHSigOpCount(in.getScriptBytes()); if (sigOps > Block.MAX_BLOCK_SIGOPS) throw new VerificationException("Too many P2SH SigOps in block"); } prevOutScripts.add(new Script(prevOut.getScriptBytes())); blockStore.removeUnspentTransactionOutput(prevOut); txOutsSpent.add(prevOut); } } Sha256Hash hash = tx.getHash(); for (TransactionOutput out : tx.getOutputs()) { valueOut = valueOut.add(out.getValue()); StoredTransactionOutput newOut = new StoredTransactionOutput(hash, out.getIndex(), out.getValue(), newBlock.getHeight(), isCoinBase, out.getScriptBytes()); blockStore.addUnspentTransactionOutput(newOut); txOutsCreated.add(newOut); } // All values were already checked for being non-negative (as it is verified in Transaction.verify()) // but we check again here just for defence in depth. Transactions with zero output value are OK. if (valueOut.signum() < 0 || valueOut.compareTo(params.MAX_MONEY) > 0) throw new VerificationException("Transaction output value out of rage"); if (isCoinBase) { coinbaseValue = valueOut; } else { if (valueIn.compareTo(valueOut) < 0 || valueIn.compareTo(params.MAX_MONEY) > 0) throw new VerificationException("Transaction input value out of range"); totalFees = totalFees.add(valueIn.subtract(valueOut)); } if (!isCoinBase) { // Because correctlySpends modifies transactions, this must come after we are done with tx FutureTask<VerificationException> future = new FutureTask<VerificationException>(new Verifier(tx, prevOutScripts, enforcePayToScriptHash)); scriptVerificationExecutor.execute(future); listScriptVerificationResults.add(future); } } if (totalFees.compareTo(params.MAX_MONEY) > 0 || newBlock.getHeader().getBlockInflation(newBlock.getHeight()).add(totalFees).compareTo(coinbaseValue) < 0) throw new VerificationException("Transaction fees out of range"); txOutChanges = new TransactionOutputChanges(txOutsCreated, txOutsSpent); for (Future<VerificationException> future : listScriptVerificationResults) { VerificationException e; try { e = future.get(); } catch (InterruptedException thrownE) { throw new RuntimeException(thrownE); // Shouldn't happen } catch (ExecutionException thrownE) { log.error("Script.correctlySpends threw a non-normal exception: " + thrownE.getCause()); throw new VerificationException("Bug in Script.correctlySpends, likely script malformed in some new and interesting way.", thrownE); } if (e != null) throw e; } } else { txOutChanges = block.getTxOutChanges(); if (!params.isCheckpoint(newBlock.getHeight())) for(StoredTransactionOutput out : txOutChanges.txOutsCreated) { Sha256Hash hash = out.getHash(); if (blockStore.getTransactionOutput(hash, out.getIndex()) != null) throw new VerificationException("Block failed BIP30 test!"); } for (StoredTransactionOutput out : txOutChanges.txOutsCreated) blockStore.addUnspentTransactionOutput(out); for (StoredTransactionOutput out : txOutChanges.txOutsSpent) blockStore.removeUnspentTransactionOutput(out); } } catch (VerificationException e) { scriptVerificationExecutor.shutdownNow(); blockStore.abortDatabaseBatchWrite(); throw e; } catch (BlockStoreException e) { scriptVerificationExecutor.shutdownNow(); blockStore.abortDatabaseBatchWrite(); throw e; } return txOutChanges; } /** * This is broken for blocks that do not pass BIP30, so all BIP30-failing blocks which are allowed to fail BIP30 * must be checkpointed. */ @Override protected void disconnectTransactions(StoredBlock oldBlock) throws PrunedException, BlockStoreException { checkState(lock.isHeldByCurrentThread()); blockStore.beginDatabaseBatchWrite(); try { StoredUndoableBlock undoBlock = blockStore.getUndoBlock(oldBlock.getHeader().getHash()); if (undoBlock == null) throw new PrunedException(oldBlock.getHeader().getHash()); TransactionOutputChanges txOutChanges = undoBlock.getTxOutChanges(); for(StoredTransactionOutput out : txOutChanges.txOutsSpent) blockStore.addUnspentTransactionOutput(out); for(StoredTransactionOutput out : txOutChanges.txOutsCreated) blockStore.removeUnspentTransactionOutput(out); } catch (PrunedException e) { blockStore.abortDatabaseBatchWrite(); throw e; } catch (BlockStoreException e) { blockStore.abortDatabaseBatchWrite(); throw e; } } @Override protected void doSetChainHead(StoredBlock chainHead) throws BlockStoreException { checkState(lock.isHeldByCurrentThread()); blockStore.setVerifiedChainHead(chainHead); blockStore.commitDatabaseBatchWrite(); } @Override protected void notSettingChainHead() throws BlockStoreException { blockStore.abortDatabaseBatchWrite(); } @Override protected StoredBlock getStoredBlockInCurrentScope(Sha256Hash hash) throws BlockStoreException { checkState(lock.isHeldByCurrentThread()); return blockStore.getOnceUndoableStoredBlock(hash); } }
apache-2.0
atamurius/bus
src/main/java/ua/atamurius/bus/web/JsonCars.java
435
package ua.atamurius.bus.web; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import ua.atamurius.bus.data.TrackerFacade; public class JsonCars extends JsonController { private static final long serialVersionUID = 1L; @Override protected Object process(TrackerFacade api, HttpServletRequest req) throws IOException { return api.getCars(req.getParameter("id")); } }
apache-2.0
nagyist/marketcetera
trunk/util/src/test/java/org/marketcetera/util/unicode/DecoderTestBase.java
3423
package org.marketcetera.util.unicode; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.junit.Ignore; import static org.junit.Assert.*; import static org.marketcetera.util.test.UnicodeData.*; /** * @author tlerios@marketcetera.com * @since 0.6.0 * @version $Id: DecoderTestBase.java 16154 2012-07-14 16:34:05Z colin $ */ /* $License$ */ @Ignore public abstract class DecoderTestBase extends IOTestBase { protected abstract String decode (byte[] bytes) throws Exception; private void testDecode (byte[] bytes, String string) throws Exception { assertEquals(string,decode(bytes)); } protected abstract String decode (SignatureCharset sc, byte[] bytes) throws Exception; private void testDecode (SignatureCharset sc, byte[] bytes, String string) throws Exception { assertEquals(string,decode(sc,bytes)); } protected abstract String decode (DecodingStrategy strategy, SignatureCharset sc, byte[] bytes) throws Exception; private void testDecode (DecodingStrategy strategy, SignatureCharset sc, byte[] bytes, String string) throws Exception { assertEquals(string,decode(strategy,sc,bytes)); } @Override protected void testNative() throws Exception { testDecode(HELLO_EN_NAT,HELLO_EN); testDecode(null,HELLO_EN_NAT,HELLO_EN); testDecode(null,null,HELLO_EN_NAT,HELLO_EN); testDecode(ArrayUtils.EMPTY_BYTE_ARRAY,StringUtils.EMPTY); testDecode(null,ArrayUtils.EMPTY_BYTE_ARRAY,StringUtils.EMPTY); testDecode(null,null,ArrayUtils.EMPTY_BYTE_ARRAY,StringUtils.EMPTY); } @Override protected void testSignatureCharset (SignatureCharset sc, byte[] bytes) throws Exception { testDecode(sc,bytes,COMBO); testDecode(sc,ArrayUtils.EMPTY_BYTE_ARRAY,StringUtils.EMPTY); } @Override protected void testStrategy (DecodingStrategy strategy, SignatureCharset sc, String string, byte[] bytes) throws Exception { testDecode (strategy,sc,bytes,string); testDecode (strategy,sc,ArrayUtils.EMPTY_BYTE_ARRAY,StringUtils.EMPTY); testDecode (strategy,SignatureCharset.UTF8_UTF8, ArrayUtils.addAll(Signature.UTF8.getMark(),COMBO_UTF8), COMBO); testDecode (strategy,SignatureCharset.UTF16BE_UTF16BE, ArrayUtils.addAll(Signature.UTF16BE.getMark(),COMBO_UTF16BE), COMBO); testDecode (strategy,SignatureCharset.UTF16LE_UTF16LE, ArrayUtils.addAll(Signature.UTF16LE.getMark(),COMBO_UTF16LE), COMBO); testDecode (strategy,SignatureCharset.UTF32BE_UTF32BE, ArrayUtils.addAll(Signature.UTF32BE.getMark(),COMBO_UTF32BE), COMBO); testDecode (strategy,SignatureCharset.UTF32LE_UTF32LE, ArrayUtils.addAll(Signature.UTF32LE.getMark(),COMBO_UTF32LE), COMBO); } }
apache-2.0
hmunfru/fiware-paas
core/src/main/java/com/telefonica/euro_iaas/paasmanager/util/RegionCache.java
2769
/** * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br> * This file is part of FI-WARE project. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. * </p> * <p> * You may obtain a copy of the License at:<br> * <br> * http://www.apache.org/licenses/LICENSE-2.0 * </p> * <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. * </p> * <p> * See the License for the specific language governing permissions and limitations under the License. * </p> * <p> * For those usages not covered by the Apache version 2.0 License please contact with opensource@tid.es * </p> */ package com.telefonica.euro_iaas.paasmanager.util; import java.io.InputStream; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import net.sf.ehcache.config.CacheConfiguration; public class RegionCache { public static final String CACHE_NAME = "regions"; private Cache cache; public RegionCache() { CacheManager singletonManager; try { InputStream inputStream = this.getClass().getResourceAsStream("/ehcache.xml"); singletonManager = CacheManager.newInstance(inputStream); } catch (Exception e) { singletonManager = CacheManager.create(); singletonManager.addCache(CACHE_NAME); cache.getCacheConfiguration(); cache = singletonManager.getCache(CACHE_NAME); CacheConfiguration cacheConfiguration = cache.getCacheConfiguration(); cacheConfiguration.setTimeToIdleSeconds(300); cacheConfiguration.setTimeToLiveSeconds(300); e.printStackTrace(); } cache = singletonManager.getCache(CACHE_NAME); } public void putUrl(String region, String service, String url) { String key = getKey(region, service); cache.put(new Element(key, url)); } public String getUrl(String region, String service) { String key = getKey(region, service); if (cache.isKeyInCache(key) && (cache.get(key) != null)) { return (String) cache.get(key).getObjectValue(); } else { return null; } } private String getKey(String region, String service) { return region + "_" + service; } public void clear() { cache.removeAll(); } public CacheConfiguration getConfiguration() { CacheConfiguration cacheConfiguration = cache.getCacheConfiguration(); return cacheConfiguration; } }
apache-2.0
macKyp/smart-bedside
core/src/main/java/com/n3rditorium/core/injection/SystemModule.java
715
package com.n3rditorium.core.injection; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; import android.view.WindowManager; import com.n3rditorium.core.system.DisplayInfoService; import com.n3rditorium.core.system.NetworkInfoService; import dagger.Module; import dagger.Provides; @Module public class SystemModule { @Provides DisplayInfoService provideDisplayInfoService(WindowManager windowManager) { return new DisplayInfoService(windowManager); } @Provides NetworkInfoService provideNetworkInfoService(ConnectivityManager connectivityManager, WifiManager wifiManager) { return new NetworkInfoService(connectivityManager, wifiManager); } }
apache-2.0
softindex/datakernel
launchers/dataflow/src/test/java/io/datakernel/launchers/dataflow/DataflowServerLauncherTest.java
248
package io.datakernel.launchers.dataflow; import org.junit.Test; public class DataflowServerLauncherTest { @Test public void testsInjector() { DataflowServerLauncher launcher = new DataflowServerLauncher() {}; launcher.testInjector(); } }
apache-2.0
b2ihealthcare/snow-owl
snomed/com.b2international.snowowl.snomed.reasoner/src/com/b2international/snowowl/snomed/reasoner/request/ClassificationCreateRequest.java
4174
/* * Copyright 2017-2021 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.snomed.reasoner.request; import java.util.List; import java.util.concurrent.TimeUnit; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; import com.b2international.snowowl.core.authorization.AccessControl; import com.b2international.snowowl.core.branch.Branch; import com.b2international.snowowl.core.domain.BranchContext; import com.b2international.snowowl.core.events.AsyncRequest; import com.b2international.snowowl.core.events.Request; import com.b2international.snowowl.core.identity.Permission; import com.b2international.snowowl.core.identity.User; import com.b2international.snowowl.core.jobs.JobRequests; import com.b2international.snowowl.snomed.core.domain.SnomedConcept; import com.b2international.snowowl.snomed.datastore.config.SnomedCoreConfiguration; import com.b2international.snowowl.snomed.reasoner.classification.ClassificationSchedulingRule; import com.b2international.snowowl.snomed.reasoner.classification.ClassificationTracker; import com.google.common.base.Strings; /** * Signals the classification tracker that a classification run is about to * start, then schedules a remote job for the actual work. * * @since 7.0 */ final class ClassificationCreateRequest implements Request<BranchContext, String>, AccessControl { private static final long serialVersionUID = 1L; private static final long SCHEDULE_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(1L); @NotEmpty private String classificationId; @NotEmpty private String reasonerId; private String userId; @NotNull private List<SnomedConcept> additionalConcepts; @NotNull private String parentLockContext; ClassificationCreateRequest() {} void setClassificationId(final String classificationId) { this.classificationId = classificationId; } void setReasonerId(final String reasonerId) { this.reasonerId = reasonerId; } void setUserId(final String userId) { this.userId = userId; } void setAdditionalConcepts(final List<SnomedConcept> additionalConcepts) { this.additionalConcepts = additionalConcepts; } void setParentLockContext(final String parentLockContext) { this.parentLockContext = parentLockContext; } @Override public String execute(final BranchContext context) { final String repositoryId = context.info().id(); final Branch branch = context.branch(); final ClassificationTracker tracker = context.service(ClassificationTracker.class); final SnomedCoreConfiguration config = context.service(SnomedCoreConfiguration.class); final String user = !Strings.isNullOrEmpty(userId) ? userId : context.service(User.class).getUsername(); tracker.classificationScheduled(classificationId, reasonerId, user, branch.path()); final AsyncRequest<Boolean> jobRequest = new ClassificationJobRequestBuilder() .setReasonerId(reasonerId) .setParentLockContext(parentLockContext) .addAllConcepts(additionalConcepts) .build(branch.path()); final ClassificationSchedulingRule rule = ClassificationSchedulingRule.create( config.getMaxReasonerCount(), repositoryId, branch.path()); JobRequests.prepareSchedule() .setKey(classificationId) .setUser(user) .setRequest(jobRequest) .setDescription(String.format("Classifying the ontology on %s", branch.path())) .setSchedulingRule(rule) .buildAsync() .get(context, SCHEDULE_TIMEOUT_MILLIS); return classificationId; } @Override public String getOperation() { return Permission.OPERATION_CLASSIFY; } }
apache-2.0
jjojala/trackxsport
src/main/java/org/gemini/trackxsport/Track.java
3777
/* * Copyright (c) 2016 Jari Ojala (jari.ojala@iki.fi) * * 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.gemini.trackxsport; import java.util.Iterator; import java.util.NoSuchElementException; import jssc.SerialPort; import jssc.SerialPortException; /* * * <h1>GD-003 Protocol</h1> * * <p>The content of each request: * <pre><tt> * | offset | type | description * |--------|--------|------------------------ * | 0x00 | byte | fixed 'H' (0x48) * | 0x01 | byte | fixed 'Y' (0x59) * | 0x02 | byte | fixed 0x03 ("request family") * | 0x03 | byte | fixed 0x02 ("get track") * | 0x04 | uint16 | fixed 0x01 (message length, always the same) * | 0x06 | byte | track id to be fetched, but this is ignored by the * | device. Instead, regardless of this, the most recent * | track is always returned. This is likely a bug in * | GD-003. * | 0x07 | byte | fixed 0x07 (first checksum byte, algorithm unknown, * | but this works for this message). * | 0x08 | byte | fixed 0x1b (second checksum byte, works for this) * </tt></pre> * * <p>The reply is one, or typically several track segment packages, * described further in {@link TrackSegment}. Note, that even though * the request supports giving the desired track identifier as a parameter, * the device seems to reply with the most latest track it has recorded, i.e. * the given parameter is not honored. This seems to an obvious bug in the * device firmware (and may be fixed in some forthcoming versions). */ public final class Track { private static final byte[] REQUEST_MESSAGE = { 0x48, 0x59, 0x03, 0x02, 0x01, 0x00, 0x01, 0x07, 0x1b }; private byte[] data; public static Track getTrack(final SerialPort port, final long waitTime) throws SerialPortException, InterruptedException { if (!port.writeBytes(REQUEST_MESSAGE)) throw new SerialPortException(port.getPortName(), "Track.requestTrack", "Writing request failed"); return new Track(DataUtil.readBytes(port, waitTime)); } private Track(final byte[] data) { this.data = data; } public int getTrackId() { return data[TrackSegment.TRACK_ID]; } public Iterator<TrackSegment> segments() { return new Iterator<TrackSegment>() { private int offset = 0; @Override public boolean hasNext() { return (offset < data.length) && (data[offset+2] == 0x03) && (data[offset+3] == 0x02); } @Override public TrackSegment next() { if (!hasNext()) throw new NoSuchElementException(); final int length = DataUtil.readUInt16(data, offset + DataUtil.MESSAGE_SIZE_OFFS) + DataUtil.MESSAGE_SIZE_PADDING; final TrackSegment block = new TrackSegment(data, offset, length); offset += length; return block; } }; } }
apache-2.0
YoungOG/CarbyneCore
src/com/medievallords/carbyne/customevents/CarbyneRepairedEvent.java
1104
package com.medievallords.carbyne.customevents; import com.medievallords.carbyne.gear.types.CarbyneGear; import lombok.Getter; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; /** * Created by Williams on 2017-08-09 * for the Carbyne project. */ public class CarbyneRepairedEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); @Getter private Player player; private CarbyneGear gear; private boolean isCancelled; public CarbyneRepairedEvent(Player player, CarbyneGear gear) { this.player = player; this.gear = gear; this.isCancelled = false; } @Override public boolean isCancelled() { return this.isCancelled; } @Override public void setCancelled(boolean arg0) { this.isCancelled = arg0; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
apache-2.0
joansmith/pdfbox
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/PDAnnotationLink.java
7115
/* * 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.pdfbox.pdmodel.interactive.annotation; import java.io.IOException; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.interactive.action.PDActionFactory; import org.apache.pdfbox.pdmodel.interactive.action.PDAction; import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDDestination; /** * This is the class that represents a link annotation. * * @author Ben Litchfield * @author Paul King */ public class PDAnnotationLink extends PDAnnotation { /** * Constant values of the Text as defined in the PDF 1.6 reference Table 8.19. */ public static final String HIGHLIGHT_MODE_NONE = "N"; /** * Constant values of the Text as defined in the PDF 1.6 reference Table 8.19. */ public static final String HIGHLIGHT_MODE_INVERT = "I"; /** * Constant values of the Text as defined in the PDF 1.6 reference Table 8.19. */ public static final String HIGHLIGHT_MODE_OUTLINE = "O"; /** * Constant values of the Text as defined in the PDF 1.6 reference Table 8.19. */ public static final String HIGHLIGHT_MODE_PUSH = "P"; /** * The type of annotation. */ public static final String SUB_TYPE = "Link"; /** * Constructor. */ public PDAnnotationLink() { super(); getCOSObject().setItem(COSName.SUBTYPE, COSName.getPDFName(SUB_TYPE)); } /** * Creates a Link annotation from a COSDictionary, expected to be a correct object definition. * * @param field the PDF objet to represent as a field. */ public PDAnnotationLink(COSDictionary field) { super(field); } /** * Get the action to be performed when this annotation is to be activated. Either this or the * destination entry should be set, but not both. * * @return The action to be performed when this annotation is activated. */ public PDAction getAction() { COSDictionary action = (COSDictionary) this.getCOSObject().getDictionaryObject(COSName.A); return PDActionFactory.createAction(action); } /** * Set the annotation action. Either this or the destination entry should be set, but not both. * * @param action The annotation action. * */ public void setAction(PDAction action) { this.getCOSObject().setItem(COSName.A, action); } /** * This will set the border style dictionary, specifying the width and dash pattern used in drawing the line. * * @param bs the border style dictionary to set. * */ public void setBorderStyle(PDBorderStyleDictionary bs) { this.getCOSObject().setItem(COSName.BS, bs); } /** * This will retrieve the border style dictionary, specifying the width and dash pattern used in * drawing the line. * * @return the border style dictionary. */ public PDBorderStyleDictionary getBorderStyle() { COSBase bs = this.getCOSObject().getDictionaryObject(COSName.BS); if (bs instanceof COSDictionary) { return new PDBorderStyleDictionary((COSDictionary) bs); } return null; } /** * Get the destination to be displayed when the annotation is activated. Either this or the * action entry should be set, but not both. * * @return The destination for this annotation. * * @throws IOException If there is an error creating the destination. */ public PDDestination getDestination() throws IOException { COSBase base = getCOSObject().getDictionaryObject(COSName.DEST); return PDDestination.create(base); } /** * The new destination value. Either this or the action entry should be set, but not both. * * @param dest The updated destination. */ public void setDestination(PDDestination dest) { getCOSObject().setItem(COSName.DEST, dest); } /** * Set the highlight mode for when the mouse is depressed. See the HIGHLIGHT_MODE_XXX constants. * * @return The string representation of the highlight mode. */ public String getHighlightMode() { return getCOSObject().getNameAsString(COSName.H, HIGHLIGHT_MODE_INVERT); } /** * Set the highlight mode. See the HIGHLIGHT_MODE_XXX constants. * * @param mode The new highlight mode. */ public void setHighlightMode(String mode) { getCOSObject().setName(COSName.H, mode); } /** * This will set the previous URI action, in case it needs to be retrieved at later date. * * @param pa The previous URI. */ public void setPreviousURI(PDActionURI pa) { getCOSObject().setItem("PA", pa); } /** * This will set the previous URI action, in case it's needed. * * @return The previous URI. */ public PDActionURI getPreviousURI() { COSDictionary pa = (COSDictionary) getCOSObject().getDictionaryObject("PA"); if (pa != null) { return new PDActionURI(pa); } return null; } /** * This will set the set of quadpoints which encompass the areas of this annotation which will activate. * * @param quadPoints an array representing the set of area covered. */ public void setQuadPoints(float[] quadPoints) { COSArray newQuadPoints = new COSArray(); newQuadPoints.setFloatArray(quadPoints); getCOSObject().setItem("QuadPoints", newQuadPoints); } /** * This will retrieve the set of quadpoints which encompass the areas of this annotation which will activate. * * @return An array of floats representing the quad points. */ public float[] getQuadPoints() { COSArray quadPoints = (COSArray) getCOSObject().getDictionaryObject("QuadPoints"); if (quadPoints != null) { return quadPoints.toFloatArray(); } // Should never happen as this is a required item return null; } }
apache-2.0
chrimm/cordovastudio
src/org/cordovastudio/editors/designer/rendering/engines/cssBox/css/NormalOutput.java
5880
/* * NormalOutput.java * Copyright (c) 2005-2007 Radek Burget * * CSSBox 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 3 of the License, or * (at your option) any later version. * * CSSBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 30. leden 2005, 19:02 */ package org.cordovastudio.editors.designer.rendering.engines.cssBox.css; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; /** * An output generator that outputs the DOM tree in a standard (xml) way * * @author radek */ public class NormalOutput extends Output { private boolean filterStyles = true; public NormalOutput(Node root) { super(root); } public NormalOutput(Node root, boolean filterStyles) { super(root); this.filterStyles = filterStyles; } /** * Formats the complete tag tree to an output stream. * @param out The output stream to be used for the output. */ public void dumpTo(OutputStream out) { PrintWriter writer; try { writer = new PrintWriter(new OutputStreamWriter(out, "utf-8")); } catch (UnsupportedEncodingException e) { writer = new PrintWriter(out); } recursiveDump(root, 0, writer); writer.close(); } /** * Formats the complete tag tree and prints using a writer. * @param writer The writer to be used for printing the ouput. */ public void dumpTo(PrintWriter writer) { recursiveDump(root, 0, writer); } //======================================================================== private void recursiveDump(Node n, int level, PrintWriter p) { //Opening tag if (n.getNodeType() == Node.ELEMENT_NODE) { String tag = ""; Element el = (Element) n; //do not dump original style definitions if (filterStyles) { if (el.getTagName().equals("style")) return; if (el.getTagName().equals("link") && (el.getAttribute("rel").equalsIgnoreCase("stylesheet") || el.getAttribute("type").equalsIgnoreCase("text/css"))) return; } //Replace meta generator if (el.getTagName().equals("meta") && el.getAttribute("name").equals("generator")) el.setAttribute("content", "CSS Transformer by Radek Burget, burgetr@fit.vutbr.cz"); //Change encoding to utf-8 if (el.getTagName().equals("meta") && el.getAttribute("http-equiv").equalsIgnoreCase("content-type")) el.setAttribute("content", "text/html; charset=utf-8"); //Dump the tag tag = tag + "<" + el.getTagName(); NamedNodeMap attrs = el.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); tag = tag + " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\""; } tag = tag + ">"; p.print(tag); } else if (n.getNodeType() == Node.TEXT_NODE) { p.print(n.getNodeValue()); } NodeList child = n.getChildNodes(); for (int i = 0; i < child.getLength(); i++) recursiveDump(child.item(i), level+1, p); //Closing tag if (n.getNodeType() == Node.ELEMENT_NODE) { //if (n.getNodeName().equals("head")) // p.print("<script type=\"text/javascript\" src=\"visual.js\"></script>"); p.print("</" + n.getNodeName() + ">"); } } @SuppressWarnings("unused") private void recursiveDumpNice(Node n, int level, PrintWriter p) { //Opening tag if (n.getNodeType() == Node.ELEMENT_NODE) { String tag = ""; Element el = (Element) n; if (el.getTagName().equals("style")) return; tag = tag + "<" + el.getTagName(); NamedNodeMap attrs = el.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); tag = tag + " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\""; } tag = tag + ">"; indent(level, p); p.println(tag); } else if (n.getNodeType() == Node.TEXT_NODE) { indent(level, p); p.println(n.getNodeValue()); } NodeList child = n.getChildNodes(); for (int i = 0; i < child.getLength(); i++) recursiveDumpNice(child.item(i), level+1, p); //Closing tag if (n.getNodeType() == Node.ELEMENT_NODE) { indent(level, p); p.println("</" + n.getNodeName() + ">"); } } private void indent(int level, PrintWriter p) { String ind = ""; for (int i = 0; i < level*4; i++) ind = ind + ' '; p.print(ind); } }
apache-2.0
rahulpalamuttam/nd4j
nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/transforms/VectorIFFT.java
4902
/* * * * Copyright 2015 Skymind,Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package org.nd4j.linalg.api.ops.impl.transforms; import org.nd4j.linalg.api.complex.IComplexNDArray; import org.nd4j.linalg.api.complex.IComplexNumber; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.BaseTransformOp; import org.nd4j.linalg.api.ops.Op; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.util.ComplexNDArrayUtil; /** * Single ifft operation * * @author Adam Gibson */ public class VectorIFFT extends BaseTransformOp { protected int fftLength; private int originalN = -1; protected boolean executed = false; public VectorIFFT() { } public VectorIFFT(INDArray x, INDArray z,int fftLength) { super(x, z); this.fftLength = fftLength; exec(); } public VectorIFFT(INDArray x, INDArray z, int n,int fftLength) { super(x, z, n); this.fftLength = fftLength; exec(); } public VectorIFFT(INDArray x, INDArray y, INDArray z, int n,int fftLength) { super(x, y, z, n); this.fftLength = fftLength; exec(); } public VectorIFFT(INDArray x,int fftLength) { super(x); this.fftLength = fftLength; exec(); } public VectorIFFT(INDArray x) { this(x,x.length()); } @Override public String name() { return "ifft"; } @Override public IComplexNumber op(IComplexNumber origin, double other) { return origin; } @Override public IComplexNumber op(IComplexNumber origin, float other) { return origin; } @Override public IComplexNumber op(IComplexNumber origin, IComplexNumber other) { return origin; } @Override public float op(float origin, float other) { return origin; } @Override public double op(double origin, double other) { return origin; } @Override public double op(double origin) { return origin; } @Override public float op(float origin) { return origin; } @Override public IComplexNumber op(IComplexNumber origin) { return origin; } @Override public Op opForDimension(int index, int dimension) { INDArray xAlongDimension = x.vectorAlongDimension(index, dimension); if (y() != null) return new VectorFFT(xAlongDimension, y.vectorAlongDimension(index, dimension), z.vectorAlongDimension(index, dimension), xAlongDimension.length(),fftLength); else return new VectorFFT(xAlongDimension, z.vectorAlongDimension(index, dimension), xAlongDimension.length(),fftLength); } @Override public Op opForDimension(int index, int... dimension) { INDArray xAlongDimension = x.tensorAlongDimension(index, dimension); if (y() != null) return new VectorFFT(xAlongDimension, y.tensorAlongDimension(index, dimension), z.tensorAlongDimension(index, dimension), xAlongDimension.length(),fftLength); else return new VectorFFT(xAlongDimension, z.tensorAlongDimension(index, dimension), xAlongDimension.length(),fftLength); } @Override public boolean isPassThrough() { return true; } @Override public void setX(INDArray x) { this.x = x; executed = false; this.fftLength = z.length(); this.n = fftLength; } @Override public void setZ(INDArray z) { this.z = z; executed = false; this.fftLength = z.length(); this.n = fftLength; } @Override public void exec() { if(!x.isVector()) return; if(executed) return; executed = true; //ifft(x) = conj(fft(conj(x)) / length(x) IComplexNDArray ndArray = x instanceof IComplexNDArray ? (IComplexNDArray) x : Nd4j.createComplex(x); IComplexNDArray fft = (IComplexNDArray) Nd4j.getExecutioner().execAndReturn(new VectorFFT(ndArray.conj(),y,z,x.length(),fftLength)); IComplexNDArray ret = fft.conj().divi(Nd4j.complexScalar(fftLength)); //completely pass through this.z = originalN > 0 ? ComplexNDArrayUtil.truncate(ret, originalN, 0) : ret; this.x = this.z; } }
apache-2.0
milg0/onvif-java-lib
src/org/onvif/ver10/schema/EFlipOptionsExtension.java
2157
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // �nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2014.02.04 um 12:22:03 PM CET // package org.onvif.ver10.schema; 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.XmlAnyElement; import javax.xml.bind.annotation.XmlType; import org.w3c.dom.Element; /** * <p> * Java-Klasse f�r EFlipOptionsExtension complex type. * * <p> * Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * <complexType name="EFlipOptionsExtension"> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * <any processContents='lax' maxOccurs="unbounded" minOccurs="0"/> * </sequence> * </restriction> * </complexContent> * </complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EFlipOptionsExtension", propOrder = { "any" }) public class EFlipOptionsExtension { @XmlAnyElement(lax = true) protected List<java.lang.Object> any; /** * Gets the value of the any 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 any property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Element } {@link java.lang.Object } * * */ public List<java.lang.Object> getAny() { if (any == null) { any = new ArrayList<java.lang.Object>(); } return this.any; } }
apache-2.0
seeyoui/kensite_cms
src/main/java/com/seeyoui/kensite/common/util/CacheUtils.java
1898
package com.seeyoui.kensite.common.util; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; /** * Cache工具类 * @author * @version */ public class CacheUtils { private static CacheManager cacheManager = ((CacheManager)SpringContextHolder.getBean("cacheManager")); private static final String SYS_CACHE = "sysCache"; /** * 获取SYS_CACHE缓存 * @param key * @return */ public static Object get(String key) { return get(SYS_CACHE, key); } /** * 写入SYS_CACHE缓存 * @param key * @return */ public static void put(String key, Object value) { put(SYS_CACHE, key, value); } /** * 从SYS_CACHE缓存中移除 * @param key * @return */ public static void remove(String key) { remove(SYS_CACHE, key); } /** * 获取缓存 * @param cacheName * @param key * @return */ public static Object get(String cacheName, String key) { Element element = getCache(cacheName).get(key); return element==null?null:element.getObjectValue(); } /** * 写入缓存 * @param cacheName * @param key * @param value */ public static void put(String cacheName, String key, Object value) { Element element = new Element(key, value); getCache(cacheName).put(element); } /** * 从缓存中移除 * @param cacheName * @param key */ public static void remove(String cacheName, String key) { getCache(cacheName).remove(key); } /** * 获得一个Cache,没有则创建一个。 * @param cacheName * @return */ private static Cache getCache(String cacheName){ Cache cache = cacheManager.getCache(cacheName); if (cache == null){ cacheManager.addCache(cacheName); cache = cacheManager.getCache(cacheName); cache.getCacheConfiguration().setEternal(true); } return cache; } public static CacheManager getCacheManager() { return cacheManager; } }
apache-2.0
johncol/spring-tests
spring-boot-sample/src/main/java/com/colpatria/controllers/HelloWorldController.java
1239
package com.colpatria.controllers; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.io.Serializable; import java.util.Collections; import java.util.Map; @RestController @RequestMapping("/hello/") public class HelloWorldController { @RequestMapping("/map") public Map<Object, Object> map() { return Collections.singletonMap("message", "Hello..?"); } @RequestMapping("/world") public String hello() { return "Hello World!"; } @RequestMapping("/you") public String world() { return "Hello you!"; } } class MyCustomResponse implements Serializable { private int status; private String message; private Object data; public MyCustomResponse(int status, String message, Object data) { this.status = status; this.message = message; this.data = data; } @Override public String toString() { return "MyCustomResponse{" + "status=" + status + ", message='" + message + '\'' + ", data=" + data + '}'; } }
apache-2.0
3D-e-Chem/knime-klifs
nl.vu_compmedchem.klifs.client/src/main/java/io/swagger/client/ApiCallback.java
2358
/* * KLIFS API * Dynamically interact with the rich content of KLIFS: the structural kinase database * * OpenAPI spec version: 0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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.swagger.client; import java.util.Map; import java.util.List; /** * Callback for asynchronous API call. * * @param <T> The return type */ public interface ApiCallback<T> { /** * This is called when the API call fails. * * @param e The exception causing the failure * @param statusCode Status code of the response if available, otherwise it would be 0 * @param responseHeaders Headers of the response if available, otherwise it would be null */ void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders); /** * This is called when the API call succeeded. * * @param result The result deserialized from response * @param statusCode Status code of the response * @param responseHeaders Headers of the response */ void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders); /** * This is called when the API upload processing. * * @param bytesWritten bytes Written * @param contentLength content length of request body * @param done write end */ void onUploadProgress(long bytesWritten, long contentLength, boolean done); /** * This is called when the API downlond processing. * * @param bytesRead bytes Read * @param contentLength content lenngth of the response * @param done Read end */ void onDownloadProgress(long bytesRead, long contentLength, boolean done); }
apache-2.0
joewalnes/idea-community
platform/lang-impl/src/com/intellij/psi/util/proximity/ProximityWeigher.java
1033
/* * 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. */ package com.intellij.psi.util.proximity; import com.intellij.psi.PsiElement; import com.intellij.psi.Weigher; import com.intellij.psi.util.ProximityLocation; import org.jetbrains.annotations.NotNull; /** * @author peter */ public abstract class ProximityWeigher extends Weigher<PsiElement, ProximityLocation> { public abstract Comparable weigh(@NotNull final PsiElement element, @NotNull final ProximityLocation location); }
apache-2.0
crate/crate
server/src/test/java/io/crate/expression/symbol/FunctionTest.java
4244
/* * 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.expression.symbol; import io.crate.metadata.Scalar; import io.crate.metadata.functions.Signature; import org.elasticsearch.test.ESTestCase; import io.crate.testing.TestingHelpers; import io.crate.types.DataType; import io.crate.types.DataTypes; import org.elasticsearch.Version; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.StreamInput; import org.junit.Test; import java.util.EnumSet; import java.util.List; import java.util.Set; import static com.carrotsearch.randomizedtesting.RandomizedTest.randomAsciiLettersOfLength; import static io.crate.testing.TestingHelpers.createReference; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; public class FunctionTest extends ESTestCase { private DataType<?> returnType = TestingHelpers.randomPrimitiveType(); private Signature signature = Signature.scalar( randomAsciiLettersOfLength(10), DataTypes.BOOLEAN.getTypeSignature(), returnType.getTypeSignature() ).withFeatures(randomFeatures()); @Test public void test_serialization_without_filter() throws Exception { Function fn = new Function( signature, List.of(createReference(randomAsciiLettersOfLength(2), DataTypes.BOOLEAN)), returnType ); BytesStreamOutput output = new BytesStreamOutput(); Symbols.toStream(fn, output); StreamInput input = output.bytes().streamInput(); Function fn2 = (Function) Symbols.fromStream(input); assertThat(fn, is(fn2)); } @Test public void test_serialization_with_filter() throws Exception { Function fn = new Function( signature, List.of(createReference(randomAsciiLettersOfLength(2), DataTypes.BOOLEAN)), returnType, Literal.of(true) ); BytesStreamOutput output = new BytesStreamOutput(); Symbols.toStream(fn, output); StreamInput input = output.bytes().streamInput(); Function fn2 = (Function) Symbols.fromStream(input); assertThat(fn2.filter(), not(nullValue())); assertThat(fn, is(fn2)); } @Test public void test_serialization_before_version_4_1_0() throws Exception { Function fn = new Function( signature, List.of(createReference(randomAsciiLettersOfLength(2), DataTypes.BOOLEAN)), returnType ); var output = new BytesStreamOutput(); output.setVersion(Version.V_4_0_0); Symbols.toStream(fn, output); var input = output.bytes().streamInput(); input.setVersion(Version.V_4_0_0); Function fn2 = (Function) Symbols.fromStream(input); assertThat(fn2.filter(), is(nullValue())); assertThat(fn, is(fn2)); } private static Set<Scalar.Feature> randomFeatures() { Set<Scalar.Feature> features = EnumSet.noneOf(Scalar.Feature.class); for (Scalar.Feature feature : Scalar.Feature.values()) { if (randomBoolean()) { features.add(feature); } } return features; } }
apache-2.0
Grasea/Grandroid2
app/src/main/java/com/grasea/grandroid/util/ByteArrayUtils.java
11476
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.grasea.grandroid.util; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.logging.Level; import java.util.logging.Logger; /** * ArrayUtil,一些基于byte数组的操作方法集 */ public class ByteArrayUtils { /** * 查找并替换指定byte数组 * * @param org of type byte[] 原数组 * @param search of type byte[] 要查找的数组 * @param replace of type byte[] 要替换的数组 * @param startIndex of type int 开始搜索索引 * @return byte[] 返回新的数组 * @throws UnsupportedEncodingException when */ public static byte[] arrayReplace(byte[] org, byte[] search, byte[] replace, int startIndex) throws UnsupportedEncodingException { int index = indexOf(org, search, startIndex); if (index != -1) { int newLength = org.length + replace.length - search.length; byte[] newByte = new byte[newLength]; System.arraycopy(org, 0, newByte, 0, index); System.arraycopy(replace, 0, newByte, index, replace.length); System.arraycopy(org, index + search.length, newByte, index + replace.length, org.length - index - search.length); int newStart = index + replace.length; if ((newByte.length - newStart) > replace.length) { return arrayReplace(newByte, search, replace, newStart); } return newByte; } else { return org; } } /** * 从指定数组的copy一个子数组并返回 * * @param org of type byte[] 原数组 * @param to 合并一个byte[] * @return 合并的数据 */ public static byte[] append(byte[] org, byte[] to) { byte[] newByte = new byte[org.length + to.length]; System.arraycopy(org, 0, newByte, 0, org.length); System.arraycopy(to, 0, newByte, org.length, to.length); return newByte; } /** * 从指定数组的copy一个子数组并返回 * * @param org of type byte[] 原数组 * @param to 合并一个byte * @return 合并的数据 */ public static byte[] append(byte[] org, byte to) { byte[] newByte = new byte[org.length + 1]; System.arraycopy(org, 0, newByte, 0, org.length); newByte[org.length] = to; return newByte; } /** * 从指定数组的copy一个子数组并返回 * * @param org of type byte[] 原数组 * @param from 起始点 * @param append 要合并的数据 */ public static void append(byte[] org, int from, byte[] append) { System.arraycopy(append, 0, org, from, append.length); } /** * 从指定数组的copy一个子数组并返回 * * @param original of type byte[] 原数组 * @param from 起始点 * @param to 结束点 * @return 返回copy的数组 */ public static byte[] copyOfRange(byte[] original, int from, int to) { int newLength = to - from; if (newLength < 0) { throw new IllegalArgumentException(from + " > " + to); } byte[] copy = new byte[newLength]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; } public static byte[] char2byte(String encode, char... chars) { Charset cs = Charset.forName(encode); CharBuffer cb = CharBuffer.allocate(chars.length); cb.put(chars); cb.flip(); ByteBuffer bb = cs.encode(cb); return bb.array(); } /** * 查找指定数组的起始索引 * * @param org of type byte[] 原数组 * @param search of type byte[] 要查找的数组 * @return int 返回索引 */ public static int indexOf(byte[] org, byte[] search) { return indexOf(org, search, 0); } /** * 查找指定数组的起始索引 * * @param org of type byte[] 原数组 * @param search of type byte[] 要查找的数组 * @param startIndex 起始索引 * @return int 返回索引 */ public static int indexOf(byte[] org, byte[] search, int startIndex) { KMPMatcher kmpMatcher = new ByteArrayUtils.KMPMatcher(); kmpMatcher.computeFailure4Byte(search); return kmpMatcher.indexOf(org, startIndex); //return com.alibaba.common.lang.ArrayUtil.indexOf(org, search); } /** * 查找指定数组的最后一次出现起始索引 * * @param org of type byte[] 原数组 * @param search of type byte[] 要查找的数组 * @return int 返回索引 */ public static int lastIndexOf(byte[] org, byte[] search) { return lastIndexOf(org, search, 0); } /** * 查找指定数组的最后一次出现起始索引 * * @param org of type byte[] 原数组 * @param search of type byte[] 要查找的数组 * @param fromIndex 起始索引 * @return int 返回索引 */ public static int lastIndexOf(byte[] org, byte[] search, int fromIndex) { KMPMatcher kmpMatcher = new ByteArrayUtils.KMPMatcher(); kmpMatcher.computeFailure4Byte(search); return kmpMatcher.lastIndexOf(org, fromIndex); } public static String toString(byte[] form) { return new String(form); } public static String toString(byte[] form, String encoding) { try { return new String(form, encoding); } catch (UnsupportedEncodingException ex) { Logger.getLogger(ByteArrayUtils.class.getName()).log(Level.SEVERE, null, ex); return ""; } } public static int toInt(byte[] bRefArr) { int iOutcome = 0; byte bLoop; for (int i = 0; i < bRefArr.length; i++) { bLoop = bRefArr[i]; iOutcome += (bLoop & 0xFF) << (8 * i); } return iOutcome; } public static float tofloat(byte[] form) { return Float.intBitsToFloat(toInt(form)); } /** * 通过byte数组取到short * * @param b * @param index 第几位开始取 * @return */ public static short toShort(byte[] b, int index) { return (short) (((b[index + 1] << 8) | b[index + 0] & 0xff)); } public static byte[] toByteArray(float f, int arraylen) { int intBits = Float.floatToIntBits(f); return toByteArray(intBits, arraylen); } public static byte[] toByteArray(short s) { return new byte[]{(byte) (s & 0x00FF), (byte) ((s & 0xFF00) >> 8)}; } public static byte[] toByteArray(int i, int arrayLen) { byte[] bLocalArr = new byte[arrayLen]; for (int j = 0; (j < 4) && (j < arrayLen); j++) { bLocalArr[j] = (byte) (i >> 8 * j & 0xFF); } return bLocalArr; } /** * KMP算法类 */ static class KMPMatcher { private int[] failure; private int matchPoint; private byte[] bytePattern; /** * Method indexOf … * * @param text of type byte[] * @param startIndex of type int * @return int */ public int indexOf(byte[] text, int startIndex) { int j = 0; if (text.length == 0 || startIndex > text.length) { return -1; } for (int i = startIndex; i < text.length; i++) { while (j > 0 && bytePattern[j] != text[i]) { j = failure[j - 1]; } if (bytePattern[j] == text[i]) { j++; } if (j == bytePattern.length) { matchPoint = i - bytePattern.length + 1; return matchPoint; } } return -1; } /** * 找到末尾后重头开始找 * * @param text of type byte[] * @param startIndex of type int * @return int */ public int lastIndexOf(byte[] text, int startIndex) { matchPoint = -1; int j = 0; if (text.length == 0 || startIndex > text.length) { return -1; } int end = text.length; for (int i = startIndex; i < end; i++) { while (j > 0 && bytePattern[j] != text[i]) { j = failure[j - 1]; } if (bytePattern[j] == text[i]) { j++; } if (j == bytePattern.length) { matchPoint = i - bytePattern.length + 1; if ((text.length - i) > bytePattern.length) { j = 0; continue; } return matchPoint; } //如果从中间某个位置找,找到末尾没找到后,再重头开始找 if (startIndex != 0 && i + 1 == end) { end = startIndex; i = -1; startIndex = 0; } } return matchPoint; } /** * 找到末尾后不会重头开始找 * * @param text of type byte[] * @param startIndex of type int * @return int */ public int lastIndexOfWithNoLoop(byte[] text, int startIndex) { matchPoint = -1; int j = 0; if (text.length == 0 || startIndex > text.length) { return -1; } for (int i = startIndex; i < text.length; i++) { while (j > 0 && bytePattern[j] != text[i]) { j = failure[j - 1]; } if (bytePattern[j] == text[i]) { j++; } if (j == bytePattern.length) { matchPoint = i - bytePattern.length + 1; if ((text.length - i) > bytePattern.length) { j = 0; continue; } return matchPoint; } } return matchPoint; } /** * Method computeFailure4Byte … * * @param patternStr of type byte[] */ public void computeFailure4Byte(byte[] patternStr) { bytePattern = patternStr; int j = 0; int len = bytePattern.length; failure = new int[len]; for (int i = 1; i < len; i++) { while (j > 0 && bytePattern[j] != bytePattern[i]) { j = failure[j - 1]; } if (bytePattern[j] == bytePattern[i]) { j++; } failure[i] = j; } } } public static void print(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { sb.append((int) bytes[i]); sb.append(" "); } System.out.println("bytes: " + sb.toString()); } }
apache-2.0
jaschenk/jeffaschenk-commons
src/main/java/jeffaschenk/commons/system/internal/file/services/UtilityServiceImpl.java
9117
package jeffaschenk.commons.system.internal.file.services; import jeffaschenk.commons.system.internal.file.services.extract.ExtractLifecyclePostProcessing; import jeffaschenk.commons.system.internal.file.services.extract.ExtractLifecyclePreProcessing; import jeffaschenk.commons.system.internal.file.services.extract.ExtractLifecycleUpdateDetermination; import jeffaschenk.commons.touchpoint.model.wrappers.ExtractMappings; import jeffaschenk.commons.touchpoint.model.wrappers.PostProcessingMappings; import jeffaschenk.commons.touchpoint.model.wrappers.PreProcessingMappings; import jeffaschenk.commons.touchpoint.model.RootElement; import jeffaschenk.commons.touchpoint.model.wrappers.UpdateProcessingMappings; import jeffaschenk.commons.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.File; /** * Utilit Service Implementation * * @author jeffaschenk@gmail.com */ @Service("utilityService") public class UtilityServiceImpl implements UtilityService, ApplicationContextAware { /** * Logging */ private final static Logger logger = LoggerFactory.getLogger(UtilityServiceImpl.class); /** * Initialization Indicator. */ private boolean initialized = false; /** * Extract Mappings */ @Autowired private ExtractMappings extractMappings; public ExtractMappings getExtractMappings() { return extractMappings; } public void setExtractMappings(ExtractMappings extractMappings) { this.extractMappings = extractMappings; } /** * Pre Processing Mappings */ @Autowired private PreProcessingMappings preProcessingMappings; public PreProcessingMappings getPreProcessingMappings() { return preProcessingMappings; } public void setUpdateProcessingMappings(PreProcessingMappings preProcessingMappings) { this.preProcessingMappings = preProcessingMappings; } /** * Update Mappings */ @Autowired private UpdateProcessingMappings updateProcessingMappings; public UpdateProcessingMappings getUpdateProcessingMappings() { return updateProcessingMappings; } public void setUpdateProcessingMappings(UpdateProcessingMappings updateProcessingMappings) { this.updateProcessingMappings = updateProcessingMappings; } /** * Post Processing Mappings */ @Autowired private PostProcessingMappings postProcessingMappings; public PostProcessingMappings getPostProcessingMappings() { return postProcessingMappings; } public void setPostProcessingMappings(PostProcessingMappings postProcessingMappings) { this.postProcessingMappings = postProcessingMappings; } /** * Spring Application Context, * used to obtain access to Resources on * Classpath. */ private ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Initialize the Service Provider Interface */ @PostConstruct public synchronized void initialize() { logger.info("Starting Utility Service Provider Facility."); // ************************************* // Show Filter Mapping if ((this.extractMappings == null) || (this.extractMappings.getFilterMappings() == null) || (this.extractMappings.getFilterMappings().size() <= 0)) { logger.error("Unable to initialize the Extract FileName to Object Class Mappings, Utility Service not Initialized!"); return; } // ************************************** // Log Runtime Mappings logger.info("Extract Filter Mappings: " + this.extractMappings.toString()); // Service Ready and loaded for action. this.initialized = true; } /** * Destroy Service * Invoked during Termination of the Spring Container. */ @PreDestroy public synchronized void destroy() { if (this.initialized) { logger.info("Ending Utility Service Provider Facility."); } } /** * Utility Service to lookup and provide associate Object Model Class * per specified Extract FileName. * <p/> * Yes, there is order in the world! * * @param extractFileName * @return Class<? extends RootElement> */ @Override public Class<? extends RootElement> getClassBasedOnExtractFilename(final String extractFileName) { if (StringUtils.isEmpty(extractFileName)) { throw new IllegalArgumentException("Extract File Name must be specified."); } String className = this.extractMappings.getMappedClassName(extractFileName); if (className == null) { return null; } try { return RootElement.class.forName(className).asSubclass(RootElement.class); } catch (ClassNotFoundException cnfe) { logger.error("Class Name:[" + className + "], is not defined in the current Object model, Returning Null."); } return null; } /** * Utility Service to obtain default class. * * @return Class<? extends RootElement> */ @Override public Class<? extends RootElement> getDefaultClassInstance() { try { return RootElement.class.forName(RootElement.class.getName()).asSubclass(RootElement.class); } catch (ClassNotFoundException cnfe) { logger.error("Class Name:[" + RootElement.class.getName() + "], is not defined in the current Object model, Returning Null."); } return null; } /** * Helper method to determine if Directory is valid. * * @param zoneDirectory * @return boolean inidicator - true if Zone directory is Valid. */ @Override public boolean isZoneDirectoryValid(File zoneDirectory) { return ((zoneDirectory.exists()) && (zoneDirectory.canRead()) && (zoneDirectory.canWrite()) && (zoneDirectory.isDirectory())); } /** * Utility Service to lookup and provide associated Update Component Bean * per specified Extract Entity Name. * <p/> * Yes, there is order in the world! * * @param extractEntityClassName * @return ExtractLifecycleUpdateDetermination Bean */ @Override public ExtractLifecycleUpdateDetermination getBeanBasedOnExtractEntityClassNameForUpdateDetermination(final String extractEntityClassName) { if (StringUtils.isEmpty(extractEntityClassName)) { throw new IllegalArgumentException("Extract Entity ClassName Name must be specified."); } String beanName = this.updateProcessingMappings.getMappedClassName(extractEntityClassName); if (beanName == null) { return null; } return (ExtractLifecycleUpdateDetermination) this.applicationContext.getBean(beanName); } /** * Utility Service to lookup and provide associated Update Module Class * per specified Extract Entity Name. * <p/> * Yes, there is order in the world! * * @param extractEntityClassName * @return ExtractLifecycleUpdateDetermination */ @Override public ExtractLifecyclePreProcessing getBeanBasedOnExtractEntityClassNameForPreProcessing(String extractEntityClassName) { if (StringUtils.isEmpty(extractEntityClassName)) { throw new IllegalArgumentException("Extract Entity ClassName Name must be specified."); } String beanName = this.preProcessingMappings.getMappedClassName(extractEntityClassName); if (beanName == null) { return null; } return (ExtractLifecyclePreProcessing) this.applicationContext.getBean(beanName); } /** * Utility Service to lookup and provide associated Update Module Class * per specified Extract Entity Name. * <p/> * Yes, there is order in the world! * * @param extractEntityClassName * @return ExtractLifecycleUpdateDetermination */ @Override public ExtractLifecyclePostProcessing getBeanBasedOnExtractEntityClassNameForPostProcessing(String extractEntityClassName) { if (StringUtils.isEmpty(extractEntityClassName)) { throw new IllegalArgumentException("Extract Entity ClassName Name must be specified."); } String beanName = this.postProcessingMappings.getMappedClassName(extractEntityClassName); if (beanName == null) { return null; } return (ExtractLifecyclePostProcessing) this.applicationContext.getBean(beanName); } }
apache-2.0
apereo/cas
support/cas-server-support-oidc-core-api/src/main/java/org/apereo/cas/oidc/ticket/OidcDefaultPushedAuthorizationRequestFactory.java
2687
package org.apereo.cas.oidc.ticket; import org.apereo.cas.support.oauth.services.OAuthRegisteredService; import org.apereo.cas.support.oauth.web.response.accesstoken.ext.AccessTokenRequestContext; import org.apereo.cas.ticket.ExpirationPolicy; import org.apereo.cas.ticket.ExpirationPolicyBuilder; import org.apereo.cas.ticket.Ticket; import org.apereo.cas.ticket.UniqueTicketIdGenerator; import org.apereo.cas.ticket.accesstoken.OAuth20AccessToken; import org.apereo.cas.util.EncodingUtils; import org.apereo.cas.util.crypto.CipherExecutor; import org.apereo.cas.util.serialization.SerializationUtils; import lombok.RequiredArgsConstructor; import lombok.val; /** * This is {@link OidcDefaultPushedAuthorizationRequestFactory}. * * @author Misagh Moayyed * @since 6.5.0 */ @RequiredArgsConstructor public class OidcDefaultPushedAuthorizationRequestFactory implements OidcPushedAuthorizationRequestFactory { /** * Default instance for the ticket id generator. */ protected final UniqueTicketIdGenerator idGenerator; /** * ExpirationPolicy for refresh tokens. */ protected final ExpirationPolicyBuilder<OAuth20AccessToken> expirationPolicyBuilder; @Override public Class<? extends Ticket> getTicketType() { return OidcPushedAuthorizationRequest.class; } @Override public OidcPushedAuthorizationRequest create(final AccessTokenRequestContext holder) throws Exception { val request = SerializationUtils.serialize(holder); val id = idGenerator.getNewTicketId(OidcPushedAuthorizationRequest.PREFIX); val expirationPolicy = determineExpirationPolicyForService(holder.getRegisteredService()); return new OidcDefaultPushedAuthorizationRequest(id, expirationPolicy, holder.getAuthentication(), holder.getService(), holder.getRegisteredService(), EncodingUtils.encodeBase64(request)); } @Override public AccessTokenRequestContext toAccessTokenRequest(final OidcPushedAuthorizationRequest authzRequest) throws Exception { val decodedRequest = EncodingUtils.decodeBase64(authzRequest.getAuthorizationRequest()); return SerializationUtils.decodeAndDeserializeObject(decodedRequest, CipherExecutor.noOp(), AccessTokenRequestContext.class); } /** * Determine the expiration policy for the registered service. * * @param registeredService the registered service * @return the expiration policy */ protected ExpirationPolicy determineExpirationPolicyForService(final OAuthRegisteredService registeredService) { return this.expirationPolicyBuilder.buildTicketExpirationPolicy(); } }
apache-2.0
rahulkavale/springmvc-raml-plugin
springmvc-raml-parser/src/main/java/com/phoenixnap/oss/ramlapisync/generation/rules/RamlLoader.java
1916
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.phoenixnap.oss.ramlapisync.generation.rules; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.phoenixnap.oss.ramlapisync.raml.InvalidRamlResourceException; import com.phoenixnap.oss.ramlapisync.raml.RamlModelFactoryOfFactories; import com.phoenixnap.oss.ramlapisync.raml.RamlRoot; /** * * Class containing method used to load a raml file * * @author kurtpa * @since 0.10.3 */ public class RamlLoader { /** * Class Logger */ protected static final Logger logger = LoggerFactory.getLogger(RamlLoader.class); /** * Loads a RAML document from a file. This method will * * @param ramlFileUrl The path to the file, this can either be a resource on the class path (in which case the classpath: prefix should be omitted) or a file on disk (in which case the file: prefix should be included) * @return Built Raml model * @throws InvalidRamlResourceException If the Raml Provided isnt correct for the required parser */ public static RamlRoot loadRamlFromFile(String ramlFileUrl) throws InvalidRamlResourceException { try { return RamlModelFactoryOfFactories.createRamlModelFactoryFor(ramlFileUrl).buildRamlRoot(ramlFileUrl); } catch (NullPointerException npe) { logger.error("File not found at " + ramlFileUrl); return null; } } }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p390/Test7811.java
2174
package org.gradle.test.performance.mediummonolithicjavaproject.p390; import org.junit.Test; import static org.junit.Assert.*; public class Test7811 { Production7811 objectUnderTest = new Production7811(); @Test public void testProperty0() { Production7808 value = new Production7808(); objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { Production7809 value = new Production7809(); objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { Production7810 value = new Production7810(); objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
apache-2.0
XillioQA/xill-platform-3.4
plugin-xurl/src/main/java/nl/xillio/xill/plugins/xurl/constructs/PostConstruct.java
1057
/** * Copyright (C) 2014 Xillio (support@xillio.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 nl.xillio.xill.plugins.xurl.constructs; import org.apache.http.client.fluent.Request; import java.net.URI; /** * This construct will perform post requests using the abstract request framework. * * @author Thomas Biesaart */ public class PostConstruct extends AbstractRequestConstruct { @Override protected Request buildRequest(URI uri) { return Request.Post(uri); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-securityhub/src/main/java/com/amazonaws/services/securityhub/model/AwsEc2InstanceDetails.java
18483
/* * 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.securityhub.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The details of an Amazon EC2 instance. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/AwsEc2InstanceDetails" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AwsEc2InstanceDetails implements Serializable, Cloneable, StructuredPojo { /** * <p> * The instance type of the instance. * </p> */ private String type; /** * <p> * The Amazon Machine Image (AMI) ID of the instance. * </p> */ private String imageId; /** * <p> * The IPv4 addresses associated with the instance. * </p> */ private java.util.List<String> ipV4Addresses; /** * <p> * The IPv6 addresses associated with the instance. * </p> */ private java.util.List<String> ipV6Addresses; /** * <p> * The key name associated with the instance. * </p> */ private String keyName; /** * <p> * The IAM profile ARN of the instance. * </p> */ private String iamInstanceProfileArn; /** * <p> * The identifier of the VPC that the instance was launched in. * </p> */ private String vpcId; /** * <p> * The identifier of the subnet that the instance was launched in. * </p> */ private String subnetId; /** * <p> * The date/time the instance was launched. * </p> */ private String launchedAt; /** * <p> * The instance type of the instance. * </p> * * @param type * The instance type of the instance. */ public void setType(String type) { this.type = type; } /** * <p> * The instance type of the instance. * </p> * * @return The instance type of the instance. */ public String getType() { return this.type; } /** * <p> * The instance type of the instance. * </p> * * @param type * The instance type of the instance. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withType(String type) { setType(type); return this; } /** * <p> * The Amazon Machine Image (AMI) ID of the instance. * </p> * * @param imageId * The Amazon Machine Image (AMI) ID of the instance. */ public void setImageId(String imageId) { this.imageId = imageId; } /** * <p> * The Amazon Machine Image (AMI) ID of the instance. * </p> * * @return The Amazon Machine Image (AMI) ID of the instance. */ public String getImageId() { return this.imageId; } /** * <p> * The Amazon Machine Image (AMI) ID of the instance. * </p> * * @param imageId * The Amazon Machine Image (AMI) ID of the instance. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withImageId(String imageId) { setImageId(imageId); return this; } /** * <p> * The IPv4 addresses associated with the instance. * </p> * * @return The IPv4 addresses associated with the instance. */ public java.util.List<String> getIpV4Addresses() { return ipV4Addresses; } /** * <p> * The IPv4 addresses associated with the instance. * </p> * * @param ipV4Addresses * The IPv4 addresses associated with the instance. */ public void setIpV4Addresses(java.util.Collection<String> ipV4Addresses) { if (ipV4Addresses == null) { this.ipV4Addresses = null; return; } this.ipV4Addresses = new java.util.ArrayList<String>(ipV4Addresses); } /** * <p> * The IPv4 addresses associated with the instance. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setIpV4Addresses(java.util.Collection)} or {@link #withIpV4Addresses(java.util.Collection)} if you want * to override the existing values. * </p> * * @param ipV4Addresses * The IPv4 addresses associated with the instance. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withIpV4Addresses(String... ipV4Addresses) { if (this.ipV4Addresses == null) { setIpV4Addresses(new java.util.ArrayList<String>(ipV4Addresses.length)); } for (String ele : ipV4Addresses) { this.ipV4Addresses.add(ele); } return this; } /** * <p> * The IPv4 addresses associated with the instance. * </p> * * @param ipV4Addresses * The IPv4 addresses associated with the instance. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withIpV4Addresses(java.util.Collection<String> ipV4Addresses) { setIpV4Addresses(ipV4Addresses); return this; } /** * <p> * The IPv6 addresses associated with the instance. * </p> * * @return The IPv6 addresses associated with the instance. */ public java.util.List<String> getIpV6Addresses() { return ipV6Addresses; } /** * <p> * The IPv6 addresses associated with the instance. * </p> * * @param ipV6Addresses * The IPv6 addresses associated with the instance. */ public void setIpV6Addresses(java.util.Collection<String> ipV6Addresses) { if (ipV6Addresses == null) { this.ipV6Addresses = null; return; } this.ipV6Addresses = new java.util.ArrayList<String>(ipV6Addresses); } /** * <p> * The IPv6 addresses associated with the instance. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setIpV6Addresses(java.util.Collection)} or {@link #withIpV6Addresses(java.util.Collection)} if you want * to override the existing values. * </p> * * @param ipV6Addresses * The IPv6 addresses associated with the instance. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withIpV6Addresses(String... ipV6Addresses) { if (this.ipV6Addresses == null) { setIpV6Addresses(new java.util.ArrayList<String>(ipV6Addresses.length)); } for (String ele : ipV6Addresses) { this.ipV6Addresses.add(ele); } return this; } /** * <p> * The IPv6 addresses associated with the instance. * </p> * * @param ipV6Addresses * The IPv6 addresses associated with the instance. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withIpV6Addresses(java.util.Collection<String> ipV6Addresses) { setIpV6Addresses(ipV6Addresses); return this; } /** * <p> * The key name associated with the instance. * </p> * * @param keyName * The key name associated with the instance. */ public void setKeyName(String keyName) { this.keyName = keyName; } /** * <p> * The key name associated with the instance. * </p> * * @return The key name associated with the instance. */ public String getKeyName() { return this.keyName; } /** * <p> * The key name associated with the instance. * </p> * * @param keyName * The key name associated with the instance. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withKeyName(String keyName) { setKeyName(keyName); return this; } /** * <p> * The IAM profile ARN of the instance. * </p> * * @param iamInstanceProfileArn * The IAM profile ARN of the instance. */ public void setIamInstanceProfileArn(String iamInstanceProfileArn) { this.iamInstanceProfileArn = iamInstanceProfileArn; } /** * <p> * The IAM profile ARN of the instance. * </p> * * @return The IAM profile ARN of the instance. */ public String getIamInstanceProfileArn() { return this.iamInstanceProfileArn; } /** * <p> * The IAM profile ARN of the instance. * </p> * * @param iamInstanceProfileArn * The IAM profile ARN of the instance. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withIamInstanceProfileArn(String iamInstanceProfileArn) { setIamInstanceProfileArn(iamInstanceProfileArn); return this; } /** * <p> * The identifier of the VPC that the instance was launched in. * </p> * * @param vpcId * The identifier of the VPC that the instance was launched in. */ public void setVpcId(String vpcId) { this.vpcId = vpcId; } /** * <p> * The identifier of the VPC that the instance was launched in. * </p> * * @return The identifier of the VPC that the instance was launched in. */ public String getVpcId() { return this.vpcId; } /** * <p> * The identifier of the VPC that the instance was launched in. * </p> * * @param vpcId * The identifier of the VPC that the instance was launched in. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withVpcId(String vpcId) { setVpcId(vpcId); return this; } /** * <p> * The identifier of the subnet that the instance was launched in. * </p> * * @param subnetId * The identifier of the subnet that the instance was launched in. */ public void setSubnetId(String subnetId) { this.subnetId = subnetId; } /** * <p> * The identifier of the subnet that the instance was launched in. * </p> * * @return The identifier of the subnet that the instance was launched in. */ public String getSubnetId() { return this.subnetId; } /** * <p> * The identifier of the subnet that the instance was launched in. * </p> * * @param subnetId * The identifier of the subnet that the instance was launched in. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withSubnetId(String subnetId) { setSubnetId(subnetId); return this; } /** * <p> * The date/time the instance was launched. * </p> * * @param launchedAt * The date/time the instance was launched. */ public void setLaunchedAt(String launchedAt) { this.launchedAt = launchedAt; } /** * <p> * The date/time the instance was launched. * </p> * * @return The date/time the instance was launched. */ public String getLaunchedAt() { return this.launchedAt; } /** * <p> * The date/time the instance was launched. * </p> * * @param launchedAt * The date/time the instance was launched. * @return Returns a reference to this object so that method calls can be chained together. */ public AwsEc2InstanceDetails withLaunchedAt(String launchedAt) { setLaunchedAt(launchedAt); 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 (getType() != null) sb.append("Type: ").append(getType()).append(","); if (getImageId() != null) sb.append("ImageId: ").append(getImageId()).append(","); if (getIpV4Addresses() != null) sb.append("IpV4Addresses: ").append(getIpV4Addresses()).append(","); if (getIpV6Addresses() != null) sb.append("IpV6Addresses: ").append(getIpV6Addresses()).append(","); if (getKeyName() != null) sb.append("KeyName: ").append(getKeyName()).append(","); if (getIamInstanceProfileArn() != null) sb.append("IamInstanceProfileArn: ").append(getIamInstanceProfileArn()).append(","); if (getVpcId() != null) sb.append("VpcId: ").append(getVpcId()).append(","); if (getSubnetId() != null) sb.append("SubnetId: ").append(getSubnetId()).append(","); if (getLaunchedAt() != null) sb.append("LaunchedAt: ").append(getLaunchedAt()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AwsEc2InstanceDetails == false) return false; AwsEc2InstanceDetails other = (AwsEc2InstanceDetails) obj; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; if (other.getImageId() == null ^ this.getImageId() == null) return false; if (other.getImageId() != null && other.getImageId().equals(this.getImageId()) == false) return false; if (other.getIpV4Addresses() == null ^ this.getIpV4Addresses() == null) return false; if (other.getIpV4Addresses() != null && other.getIpV4Addresses().equals(this.getIpV4Addresses()) == false) return false; if (other.getIpV6Addresses() == null ^ this.getIpV6Addresses() == null) return false; if (other.getIpV6Addresses() != null && other.getIpV6Addresses().equals(this.getIpV6Addresses()) == false) return false; if (other.getKeyName() == null ^ this.getKeyName() == null) return false; if (other.getKeyName() != null && other.getKeyName().equals(this.getKeyName()) == false) return false; if (other.getIamInstanceProfileArn() == null ^ this.getIamInstanceProfileArn() == null) return false; if (other.getIamInstanceProfileArn() != null && other.getIamInstanceProfileArn().equals(this.getIamInstanceProfileArn()) == false) return false; if (other.getVpcId() == null ^ this.getVpcId() == null) return false; if (other.getVpcId() != null && other.getVpcId().equals(this.getVpcId()) == false) return false; if (other.getSubnetId() == null ^ this.getSubnetId() == null) return false; if (other.getSubnetId() != null && other.getSubnetId().equals(this.getSubnetId()) == false) return false; if (other.getLaunchedAt() == null ^ this.getLaunchedAt() == null) return false; if (other.getLaunchedAt() != null && other.getLaunchedAt().equals(this.getLaunchedAt()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); hashCode = prime * hashCode + ((getImageId() == null) ? 0 : getImageId().hashCode()); hashCode = prime * hashCode + ((getIpV4Addresses() == null) ? 0 : getIpV4Addresses().hashCode()); hashCode = prime * hashCode + ((getIpV6Addresses() == null) ? 0 : getIpV6Addresses().hashCode()); hashCode = prime * hashCode + ((getKeyName() == null) ? 0 : getKeyName().hashCode()); hashCode = prime * hashCode + ((getIamInstanceProfileArn() == null) ? 0 : getIamInstanceProfileArn().hashCode()); hashCode = prime * hashCode + ((getVpcId() == null) ? 0 : getVpcId().hashCode()); hashCode = prime * hashCode + ((getSubnetId() == null) ? 0 : getSubnetId().hashCode()); hashCode = prime * hashCode + ((getLaunchedAt() == null) ? 0 : getLaunchedAt().hashCode()); return hashCode; } @Override public AwsEc2InstanceDetails clone() { try { return (AwsEc2InstanceDetails) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.securityhub.model.transform.AwsEc2InstanceDetailsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
ops4j/org.ops4j.pax.exam2
core/pax-exam/src/main/java/org/ops4j/pax/exam/RerunTestException.java
1025
/* * * * 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.pax.exam; public class RerunTestException extends RuntimeException { private static final long serialVersionUID = 8756603601548606567L; public RerunTestException(final String message) { super(message); } public RerunTestException(final String message, final Throwable cause) { super(message, cause); } public RerunTestException(final Throwable cause) { super(cause); } }
apache-2.0
barneykim/pinpoint
plugins-loader/src/main/java/com/navercorp/pinpoint/loader/plugins/trace/yaml/ParsedServiceType.java
3218
/* * Copyright 2019 NAVER Corp. * * 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.navercorp.pinpoint.loader.plugins.trace.yaml; import com.navercorp.pinpoint.common.trace.AnnotationKeyMatcher; import com.navercorp.pinpoint.common.trace.DefaultServiceTypeInfo; import com.navercorp.pinpoint.common.trace.ServiceType; import com.navercorp.pinpoint.common.trace.ServiceTypeBuilder; import com.navercorp.pinpoint.common.trace.ServiceTypeInfo; import com.navercorp.pinpoint.common.util.StringUtils; /** * @author HyunGil Jeong */ public class ParsedServiceType { private Short code; private String name; private String desc; private ParsedServiceTypeProperty property; private ParsedAnnotationKeyMatcher matcher; public Short getCode() { return code; } public void setCode(Short code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public ParsedServiceTypeProperty getProperty() { return property; } public void setProperty(ParsedServiceTypeProperty property) { this.property = property; } public ParsedAnnotationKeyMatcher getMatcher() { return matcher; } public void setMatcher(ParsedAnnotationKeyMatcher matcher) { this.matcher = matcher; } ServiceTypeInfo toServiceTypeInfo() { if (code == null) { throw new IllegalArgumentException("service type code must not be null"); } if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("service type name must not be empty"); } ServiceTypeBuilder builder; if (StringUtils.isEmpty(desc)) { builder = new ServiceTypeBuilder(code, name); } else { builder = new ServiceTypeBuilder(code, name, desc); } if (property != null) { builder.terminal(property.isTerminal()); builder.queue(property.isQueue()); builder.recordStatistics(property.isRecordStatistics()); builder.includeDestinationId(property.isIncludeDestinationId()); builder.alias(property.isAlias()); } ServiceType serviceType = builder.build(); if (matcher == null) { return new DefaultServiceTypeInfo(serviceType); } AnnotationKeyMatcher annotationKeyMatcher = matcher.toAnnotationKeyMatcher(); return new DefaultServiceTypeInfo(serviceType, annotationKeyMatcher); } }
apache-2.0
webos21/xi
java/jcl/src/java/java/util/Map.java
8684
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util; /** * A {@code Map} is a data structure consisting of a set of keys and values in * which each key is mapped to a single value. The class of the objects used as * keys is declared when the {@code Map} is declared, as is the class of the * corresponding values. * <p> * A {@code Map} provides helper methods to iterate through all of the keys * contained in it, as well as various methods to access and update the * key/value pairs. */ public interface Map<K, V> { /** * {@code Map.Entry} is a key/value mapping contained in a {@code Map}. */ public static interface Entry<K, V> { /** * Compares the specified object to this {@code Map.Entry} and returns * if they are equal. To be equal, the object must be an instance of * {@code Map.Entry} and have the same key and value. * * @param object * the {@code Object} to compare with this {@code Object}. * @return {@code true} if the specified {@code Object} is equal to this * {@code Map.Entry}, {@code false} otherwise. * @see #hashCode() */ public boolean equals(Object object); /** * Returns the key. * * @return the key */ public K getKey(); /** * Returns the value. * * @return the value */ public V getValue(); /** * Returns an integer hash code for the receiver. {@code Object} which * are equal return the same value for this method. * * @return the receiver's hash code. * @see #equals(Object) */ public int hashCode(); /** * Sets the value of this entry to the specified value, replacing any * existing value. * * @param object * the new value to set. * @return object the replaced value of this entry. */ public V setValue(V object); }; /** * Removes all elements from this {@code Map}, leaving it empty. * * @throws UnsupportedOperationException * if removing elements from this {@code Map} is not supported. * @see #isEmpty() * @see #size() */ public void clear(); /** * Returns whether this {@code Map} contains the specified key. * * @param key * the key to search for. * @return {@code true} if this map contains the specified key, * {@code false} otherwise. */ public boolean containsKey(Object key); /** * Returns whether this {@code Map} contains the specified value. * * @param value * the value to search for. * @return {@code true} if this map contains the specified value, * {@code false} otherwise. */ public boolean containsValue(Object value); /** * Returns a {@code Set} containing all of the mappings in this {@code Map}. * Each mapping is an instance of {@link Map.Entry}. As the {@code Set} is * backed by this {@code Map}, changes in one will be reflected in the * other. * * @return a set of the mappings */ public Set<Map.Entry<K, V>> entrySet(); /** * Compares the argument to the receiver, and returns {@code true} if the * specified object is a {@code Map} and both {@code Map}s contain the same * mappings. * * @param object * the {@code Object} to compare with this {@code Object}. * @return boolean {@code true} if the {@code Object} is the same as this * {@code Object} {@code false} if it is different from this * {@code Object}. * @see #hashCode() * @see #entrySet() */ public boolean equals(Object object); /** * Returns the value of the mapping with the specified key. * * @param key * the key. * @return the value of the mapping with the specified key, or {@code null} * if no mapping for the specified key is found. */ public V get(Object key); /** * Returns an integer hash code for the receiver. {@code Object}s which are * equal return the same value for this method. * * @return the receiver's hash. * @see #equals(Object) */ public int hashCode(); /** * Returns whether this map is empty. * * @return {@code true} if this map has no elements, {@code false} * otherwise. * @see #size() */ public boolean isEmpty(); /** * Returns a set of the keys contained in this {@code Map}. The {@code Set} * is backed by this {@code Map} so changes to one are reflected by the * other. The {@code Set} does not support adding. * * @return a set of the keys. */ public Set<K> keySet(); /** * Maps the specified key to the specified value. * * @param key * the key. * @param value * the value. * @return the value of any previous mapping with the specified key or * {@code null} if there was no mapping. * @throws UnsupportedOperationException * if adding to this {@code Map} is not supported. * @throws ClassCastException * if the class of the key or value is inappropriate for this * {@code Map}. * @throws IllegalArgumentException * if the key or value cannot be added to this {@code Map}. * @throws NullPointerException * if the key or value is {@code null} and this {@code Map} does * not support {@code null} keys or values. */ public V put(K key, V value); /** * Copies every mapping in the specified {@code Map} to this {@code Map}. * * @param map * the {@code Map} to copy mappings from. * @throws UnsupportedOperationException * if adding to this {@code Map} is not supported. * @throws ClassCastException * if the class of a key or a value of the specified {@code Map} * is inappropriate for this {@code Map}. * @throws IllegalArgumentException * if a key or value cannot be added to this {@code Map}. * @throws NullPointerException * if a key or value is {@code null} and this {@code Map} does * not support {@code null} keys or values. */ public void putAll(Map<? extends K, ? extends V> map); /** * Removes a mapping with the specified key from this {@code Map}. * * @param key * the key of the mapping to remove. * @return the value of the removed mapping or {@code null} if no mapping * for the specified key was found. * @throws UnsupportedOperationException * if removing from this {@code Map} is not supported. */ public V remove(Object key); /** * Returns the number of mappings in this {@code Map}. * * @return the number of mappings in this {@code Map}. */ public int size(); /** * Returns a {@code Collection} of the values contained in this {@code Map}. * The {@code Collection} is backed by this {@code Map} so changes to one * are reflected by the other. The {@code Collection} supports * {@link Collection#remove}, {@link Collection#removeAll}, * {@link Collection#retainAll}, and {@link Collection#clear} operations, * and it does not support {@link Collection#add} or * {@link Collection#addAll} operations. * <p> * This method returns a {@code Collection} which is the subclass of * {@link AbstractCollection}. The {@link AbstractCollection#iterator} * method of this subclass returns a "wrapper object" over the iterator of * this {@code Map}'s {@link #entrySet()}. The * {@link AbstractCollection#size} method wraps this {@code Map}'s * {@link #size} method and the {@link AbstractCollection#contains} method * wraps this {@code Map}'s {@link #containsValue} method. * <p> * The collection is created when this method is called at first time and * returned in response to all subsequent calls. This method may return * different Collection when multiple calls to this method, since it has no * synchronization performed. * * @return a collection of the values contained in this map. */ public Collection<V> values(); }
apache-2.0
nomoa/elasticsearch
core/src/main/java/org/elasticsearch/index/query/SpanOrQueryBuilder.java
6506
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.query; import org.apache.lucene.search.Query; import org.apache.lucene.search.spans.SpanOrQuery; import org.apache.lucene.search.spans.SpanQuery; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Span query that matches the union of its clauses. Maps to {@link SpanOrQuery}. */ public class SpanOrQueryBuilder extends AbstractQueryBuilder<SpanOrQueryBuilder> implements SpanQueryBuilder { public static final String NAME = "span_or"; public static final ParseField QUERY_NAME_FIELD = new ParseField(NAME); private static final ParseField CLAUSES_FIELD = new ParseField("clauses"); private final List<SpanQueryBuilder> clauses = new ArrayList<>(); public SpanOrQueryBuilder(SpanQueryBuilder initialClause) { if (initialClause == null) { throw new IllegalArgumentException("query must include at least one clause"); } clauses.add(initialClause); } /** * Read from a stream. */ public SpanOrQueryBuilder(StreamInput in) throws IOException { super(in); for (QueryBuilder clause: readQueries(in)) { clauses.add((SpanQueryBuilder) clause); } } @Override protected void doWriteTo(StreamOutput out) throws IOException { writeQueries(out, clauses); } public SpanOrQueryBuilder clause(SpanQueryBuilder clause) { if (clause == null) { throw new IllegalArgumentException("inner bool query clause cannot be null"); } clauses.add(clause); return this; } /** * @return the {@link SpanQueryBuilder} clauses that were set for this query */ public List<SpanQueryBuilder> clauses() { return this.clauses; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(NAME); builder.startArray(CLAUSES_FIELD.getPreferredName()); for (SpanQueryBuilder clause : clauses) { clause.toXContent(builder, params); } builder.endArray(); printBoostAndQueryName(builder); builder.endObject(); } public static SpanOrQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException { XContentParser parser = parseContext.parser(); float boost = AbstractQueryBuilder.DEFAULT_BOOST; String queryName = null; List<SpanQueryBuilder> clauses = new ArrayList<>(); String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { if (parseContext.getParseFieldMatcher().match(currentFieldName, CLAUSES_FIELD)) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { QueryBuilder query = parseContext.parseInnerQueryBuilder(); if (!(query instanceof SpanQueryBuilder)) { throw new ParsingException(parser.getTokenLocation(), "spanOr [clauses] must be of type span query"); } clauses.add((SpanQueryBuilder) query); } } else { throw new ParsingException(parser.getTokenLocation(), "[span_or] query does not support [" + currentFieldName + "]"); } } else { if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) { boost = parser.floatValue(); } else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) { queryName = parser.text(); } else { throw new ParsingException(parser.getTokenLocation(), "[span_or] query does not support [" + currentFieldName + "]"); } } } if (clauses.isEmpty()) { throw new ParsingException(parser.getTokenLocation(), "spanOr must include [clauses]"); } SpanOrQueryBuilder queryBuilder = new SpanOrQueryBuilder(clauses.get(0)); for (int i = 1; i < clauses.size(); i++) { queryBuilder.clause(clauses.get(i)); } queryBuilder.boost(boost); queryBuilder.queryName(queryName); return queryBuilder; } @Override protected Query doToQuery(QueryShardContext context) throws IOException { SpanQuery[] spanQueries = new SpanQuery[clauses.size()]; for (int i = 0; i < clauses.size(); i++) { Query query = clauses.get(i).toQuery(context); assert query instanceof SpanQuery; spanQueries[i] = (SpanQuery) query; } return new SpanOrQuery(spanQueries); } @Override protected int doHashCode() { return Objects.hash(clauses); } @Override protected boolean doEquals(SpanOrQueryBuilder other) { return Objects.equals(clauses, other.clauses); } @Override public String getWriteableName() { return NAME; } }
apache-2.0
khanimteyaz/CacheService
api/src/integration-test/java/com/flipkart/gradle/test/SampleIntegrationTest.java
362
package com.flipkart.gradle.test; import org.junit.Assert; import org.junit.Test; /** * Created by imteyaz.khan on 23/09/17. */ public class SampleIntegrationTest { @Test public void integrationTest1() { Assert.assertTrue(true); } @Test public void integrationTest2() { Assert.assertNotNull(Integer.valueOf(1)); } }
apache-2.0
zhaoshiling1017/SSM-Platform
src/main/java/com/ducetech/framework/web/listener/AuthLogonHistRefreshListener.java
1135
package com.ducetech.framework.web.listener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * 通过监听器更新相关登录记录的登录时间 */ public class AuthLogonHistRefreshListener implements HttpSessionListener, ServletContextListener { private final static Logger logger = LoggerFactory.getLogger(AuthLogonHistRefreshListener.class); @Override public void sessionCreated(HttpSessionEvent se) { //Do nothing } @Override public void sessionDestroyed(HttpSessionEvent se) { } @Override public void contextInitialized(ServletContextEvent sce) { //Do nothing } @Override public void contextDestroyed(ServletContextEvent sce) { //在容器销毁时把未正常结束遗留的登录记录信息强制设置登出时间 logger.info("ServletContext destroy force setup session user logout time..."); } }
apache-2.0
Hujunjob/E-Pet
src/com/e_pet/app/util/BaseActivity.java
538
package com.e_pet.app.util; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class BaseActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); Log.i("BaseActivity", getClass().getSimpleName()); ActivityManager.addActivity(this); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); ActivityManager.removeActivity(this); } }
apache-2.0
avantica-peru/dapp-mobile
dapp/presentation/src/main/java/net/avantica/xinef/dapp/view/fragment/ProjectsMapFragment.java
8060
package net.avantica.xinef.dapp.view.fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import net.avantica.xinef.dapp.R; import net.avantica.xinef.dapp.di.components.PublicInvestmentProjectComponent; import net.avantica.xinef.dapp.model.PublicInvestmentProjectModel; import net.avantica.xinef.dapp.presenter.PublicInvestmentProjectListPresenter; import net.avantica.xinef.dapp.view.PublicInvestmentProjectListView; import java.util.Collection; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.Unbinder; public class ProjectsMapFragment extends BaseFragment implements PublicInvestmentProjectListView, OnMapReadyCallback, GoogleMap.OnMarkerClickListener { private static final String LATITUDE_KEY = "latitude_key"; private static final String LONGITUDE_KEY = "longitude_key"; private static final int CAMERA_ZOOM = 8; private double latitude; private double longitude; @Inject PublicInvestmentProjectListPresenter publicInvestmentProjectListPresenter; MapView mapView; GoogleMap googleMap; private PublicInvestmentProjectListListener publicInvestmentProjectListListener; private Unbinder unbinder; public ProjectsMapFragment() { // Required empty public constructor setRetainInstance(true); } public static ProjectsMapFragment newInstance(double latitude, double longitude) { ProjectsMapFragment fragment = new ProjectsMapFragment(); Bundle args = new Bundle(); args.putDouble(LATITUDE_KEY, latitude); args.putDouble(LONGITUDE_KEY, longitude); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getComponent(PublicInvestmentProjectComponent.class).inject(this); latitude = getArguments().getDouble(LATITUDE_KEY); longitude = getArguments().getDouble(LONGITUDE_KEY); } @Override public void onAttach(Context context) { super.onAttach(context); this.publicInvestmentProjectListListener = (PublicInvestmentProjectListListener) context; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_project_map, container, false); unbinder = ButterKnife.bind(this, view); setHasOptionsMenu(true); // Gets the MapView from the XML layout and creates it this.mapView = (MapView) view.findViewById(R.id.mapview); this.mapView.onCreate(savedInstanceState); // Gets to GoogleMap from the MapView and does initialization stuff mapView.getMapAsync(this); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); this.publicInvestmentProjectListPresenter.setView(this); // if (savedInstanceState == null) { // this.loadPublicInvestmentProjectList(); // } } @Override public void onMapReady(GoogleMap googleMap) { this.publicInvestmentProjectListPresenter.setView(this); this.loadPublicInvestmentProjectList(); this.googleMap = googleMap; this.googleMap.setOnMarkerClickListener(this); this.googleMap.getUiSettings().setMyLocationButtonEnabled(false); this.googleMap.getUiSettings().setAllGesturesEnabled(true); this.googleMap.getUiSettings().setZoomControlsEnabled(true); // googleMap.setMyLocationEnabled(true); // Needs to call MapsInitializer before doing any CameraUpdateFactory calls // try { MapsInitializer.initialize(this.getActivity()); // } catch (GooglePlayServicesNotAvailableException e) { // e.printStackTrace(); // } // Updates the location and zoom of the MapView final LatLng latLng = new LatLng(latitude, longitude); final CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, CAMERA_ZOOM); this.googleMap.animateCamera(cameraUpdate); // map.moveCamera(CameraUpdateFactory.newLatLng(latLng)); } private MarkerOptions getMarkerFromProject(PublicInvestmentProjectModel publicInvestmentProjectModel) { final double latitude = Double.valueOf(publicInvestmentProjectModel.getLatitude()); final double longitude = Double.valueOf(publicInvestmentProjectModel.getLongitude()); final LatLng latLng = new LatLng(latitude, longitude); return new MarkerOptions().position(latLng).title(publicInvestmentProjectModel.getSnipCode()); } @Override public boolean onMarkerClick(Marker marker) { if (this.publicInvestmentProjectListPresenter != null) { this.publicInvestmentProjectListPresenter.onPublicInvestmentProjectClicked(marker.getTitle()); } return false; } @Override public void onResume() { super.onResume(); this.mapView.onResume(); this.publicInvestmentProjectListPresenter.resume(); } @Override public void onPause() { super.onPause(); this.mapView.onPause(); this.publicInvestmentProjectListPresenter.pause(); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @Override public void onDestroy() { super.onDestroy(); this.mapView.onDestroy(); // this.publicInvestmentProjectListPresenter.destroy();//TODO edward.carrion si hago el detruir presentador, en la otra vista de listado se pierde el presenter } @Override public void onDetach() { super.onDetach(); this.publicInvestmentProjectListListener = null; } @Override public void onLowMemory() { super.onLowMemory(); this.mapView.onLowMemory(); } private void loadPublicInvestmentProjectList() { this.publicInvestmentProjectListPresenter.initialize(PAGE); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_list, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public void renderPublicInvestmentProjectList(Collection<PublicInvestmentProjectModel> publicInvestmentProjectModelCollection) { if (publicInvestmentProjectModelCollection != null) { for (PublicInvestmentProjectModel publicInvestmentProjectModel : publicInvestmentProjectModelCollection) { MarkerOptions markerOptions = getMarkerFromProject(publicInvestmentProjectModel); this.googleMap.addMarker(markerOptions); } } } @Override public void viewPublicInvestmentProject(String snipCode) { this.publicInvestmentProjectListListener.onPublicInvestmentProjectClicked(snipCode); } @Override public void showLoading() { } @Override public void hideLoading() { } @Override public void showRetry() { } @Override public void hideRetry() { } @Override public void showError(String message) { } @Override public Context context() { return this.getActivity().getApplicationContext(); } }
apache-2.0
googleapis/java-debugger-client
proto-google-cloud-debugger-client-v2/src/main/java/com/google/devtools/clouddebugger/v2/RegisterDebuggeeRequestOrBuilder.java
2245
/* * 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/devtools/clouddebugger/v2/controller.proto package com.google.devtools.clouddebugger.v2; public interface RegisterDebuggeeRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.devtools.clouddebugger.v2.RegisterDebuggeeRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. Debuggee information to register. * The fields `project`, `uniquifier`, `description` and `agent_version` * of the debuggee must be set. * </pre> * * <code> * .google.devtools.clouddebugger.v2.Debuggee debuggee = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the debuggee field is set. */ boolean hasDebuggee(); /** * * * <pre> * Required. Debuggee information to register. * The fields `project`, `uniquifier`, `description` and `agent_version` * of the debuggee must be set. * </pre> * * <code> * .google.devtools.clouddebugger.v2.Debuggee debuggee = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The debuggee. */ com.google.devtools.clouddebugger.v2.Debuggee getDebuggee(); /** * * * <pre> * Required. Debuggee information to register. * The fields `project`, `uniquifier`, `description` and `agent_version` * of the debuggee must be set. * </pre> * * <code> * .google.devtools.clouddebugger.v2.Debuggee debuggee = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ com.google.devtools.clouddebugger.v2.DebuggeeOrBuilder getDebuggeeOrBuilder(); }
apache-2.0
ezsimple/java
study/EGOVTEST/src/main/java/ion/net/common/db/DynamicDao.java
1405
package ion.net.common.db; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.List; import org.springframework.stereotype.Repository; import org.springframework.util.ReflectionUtils; import lombok.extern.slf4j.Slf4j; @Slf4j @Repository public abstract class DynamicDao extends DbDao { public abstract String getPackageName(); protected void initDao() { String packageName = getPackageName(); if(packageName == null || packageName.isEmpty()) { log.error("packageName is null or Empty"); return; } } protected void bindDao() { String packageName = this.getPackageName(); if(packageName == null || packageName.isEmpty()) return; List<FunctionSpec> functions = PackageService.getPackageFunctions(packageName); if(functions.size()==0) throw new NotExistPackage(packageName); for(FunctionSpec s : functions) log.debug(s.getName()); Class<?> c = this.getClass(); ReflectionUtils.doWithFields(c, new ReflectionUtils.FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { log.debug(field.toString()); } }, new ReflectionUtils.FieldFilter(){ public boolean matches(Field field) { if(SqlObject.class.isAssignableFrom(field.getType()) && field.getGenericType() instanceof ParameterizedType) return true ; return false; } }); } }
apache-2.0
stink123456/SimpleAPI
src/main/java/com/exorath/simpleapi/api/game/minigame/Minigame.java
3184
/* * Copyright 2016 Exorath * * 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.exorath.simpleapi.api.game.minigame; import com.exorath.simpleapi.api.SimpleAPI; import com.exorath.simpleapi.api.events.EventManager; import com.exorath.simpleapi.api.game.Game; import com.exorath.simpleapi.api.player.GamePlayer; import com.exorath.simpleapi.impl.game.minigame.gamestate.GameStateManagerImpl; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.WorldCreator; import java.util.Collection; /** * Created by Toon Sevrin on 5/15/2016. */ public abstract class Minigame extends Game { private World lobbyWorld; private boolean repeating = false; public Minigame(String gameName) { this("world", gameName); } public Minigame(String worldName, String gameName) { super(gameName); loadWorld(worldName); SimpleAPI.getInstance().addManager(new GameStateManagerImpl(this)); } private void loadWorld(String worldName) { lobbyWorld = Bukkit.createWorld(WorldCreator.name(worldName)); SimpleAPI.getInstance().getManager(EventManager.class).protectWorld(lobbyWorld); } public World getLobbyWorld() { return lobbyWorld; } /** * Sets the world players should wait inside while the game is waiting for players. Players will spawn at {@link World#getSpawnLocation()} * * @param lobbyWorld the world of the lobby */ public void setLobbyWorld(World lobbyWorld) { this.lobbyWorld = lobbyWorld; } /** * Sets whether or not the players should remain on the server when the game is finished. * * @param repeating true will teleport players to the lobbyWorld on finish, false will connect players to the game's hub server on finish */ public void setRepeating(boolean repeating) { this.repeating = repeating; } /** * Gets whether or not the players should remain on the server when the game is finished. * * @return whether or not the players should remain on the server when the game is finished */ public boolean isRepeating() { return repeating; } /** * This method is called when the game is about to start (GameState changed to PLAYING). */ public abstract void start(); @Override public Collection<GamePlayer> getPlayers() { return null; } /** * Connects the given GamePlayer to an available game hub server * @param player player to connect to an available game hub server */ public static void connectToGameHub(GamePlayer player){ } }
apache-2.0
sonu283304/onos
apps/cordvtn/src/main/java/org/onosproject/cordvtn/RemoteIpCommandUtil.java
8339
/* * Copyright 2016 Open Networking Laboratory * * 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.onosproject.cordvtn; import com.google.common.collect.Sets; import com.google.common.io.CharStreams; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import org.onlab.packet.IpAddress; import org.slf4j.Logger; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import static org.slf4j.LoggerFactory.getLogger; /** * {@code RemoteIpCommandUtil} provides methods to help execute Linux IP commands to a remote server. * It opens individual exec channels for each command. User can create a session with {@code connect} * method and then execute a series commands. After done with all commands, the session must be closed * explicitly by calling {@code disconnect}. */ public final class RemoteIpCommandUtil { protected static final Logger log = getLogger(RemoteIpCommandUtil.class); private static final String STRICT_HOST_CHECKING = "StrictHostKeyChecking"; private static final String DEFAULT_STRICT_HOST_CHECKING = "no"; private static final int DEFAULT_SESSION_TIMEOUT = 60000; // milliseconds private static final String IP_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; private static final String IP_ADDR_SHOW = "sudo ip addr show %s"; private static final String IP_ADDR_FLUSH = "sudo ip addr flush %s"; private static final String IP_ADDR_ADD = "sudo ip addr add %s dev %s"; private static final String IP_ADDR_DELETE = "sudo ip addr delete %s dev %s"; private static final String IP_LINK_SHOW = "sudo ip link show %s"; private static final String IP_LINK_UP = "sudo ip link set %s up"; /** * Default constructor. */ private RemoteIpCommandUtil() { } /** * Adds a given IP address to a given device. * * @param session ssh connection * @param ip network address * @param device device name to assign the ip address * @return true if the command succeeds, or false */ public static boolean addIp(Session session, NetworkAddress ip, String device) { if (session == null || !session.isConnected()) { return false; } executeCommand(session, String.format(IP_ADDR_ADD, ip.cidr(), device)); Set<IpAddress> result = getCurrentIps(session, device); return result.contains(ip.ip()); } /** * Removes the IP address from a given device. * * @param session ssh connection * @param ip ip address * @param device device name * @return true if the command succeeds, or false */ public static boolean deleteIp(Session session, IpAddress ip, String device) { if (session == null || !session.isConnected()) { return false; } executeCommand(session, String.format(IP_ADDR_DELETE, ip, device)); Set<IpAddress> result = getCurrentIps(session, device); return !result.contains(ip); } /** * Removes all IP address on a given device. * * @param session ssh connection * @param device device name * @return true if the command succeeds, or false */ public static boolean flushIp(Session session, String device) { if (session == null || !session.isConnected()) { return false; } executeCommand(session, String.format(IP_ADDR_FLUSH, device)); return getCurrentIps(session, device).isEmpty(); } /** * Returns a set of IP address that a given device has. * * @param session ssh connection * @param device device name * @return set of IP prefix or empty set */ public static Set<IpAddress> getCurrentIps(Session session, String device) { if (session == null || !session.isConnected()) { return Sets.newHashSet(); } String output = executeCommand(session, String.format(IP_ADDR_SHOW, device)); Set<IpAddress> result = Pattern.compile(" |/") .splitAsStream(output) .filter(s -> s.matches(IP_PATTERN)) .map(IpAddress::valueOf) .collect(Collectors.toSet()); return result; } /** * Sets link state up for a given device. * * @param session ssh connection * @param device device name * @return true if the command succeeds, or false */ public static boolean setInterfaceUp(Session session, String device) { if (session == null || !session.isConnected()) { return false; } executeCommand(session, String.format(IP_LINK_UP, device)); return isInterfaceUp(session, device); } /** * Checks if a given interface is up or not. * * @param session ssh connection * @param device device name * @return true if the interface is up, or false */ public static boolean isInterfaceUp(Session session, String device) { if (session == null || !session.isConnected()) { return false; } String output = executeCommand(session, String.format(IP_LINK_SHOW, device)); return output != null && output.contains("UP"); } /** * Creates a new session with a given access information. * * @param sshInfo information to ssh to the remove server * @return ssh session, or null */ public static Session connect(SshAccessInfo sshInfo) { try { JSch jsch = new JSch(); jsch.addIdentity(sshInfo.privateKey()); Session session = jsch.getSession(sshInfo.user(), sshInfo.remoteIp().toString(), sshInfo.port().toInt()); session.setConfig(STRICT_HOST_CHECKING, DEFAULT_STRICT_HOST_CHECKING); session.connect(DEFAULT_SESSION_TIMEOUT); return session; } catch (JSchException e) { log.debug("Failed to connect to {} due to {}", sshInfo.toString(), e.toString()); return null; } } /** * Closes a connection. * * @param session session */ public static void disconnect(Session session) { if (session.isConnected()) { session.disconnect(); } } /** * Executes a given command. It opens exec channel for the command and closes * the channel when it's done. * * @param session ssh connection to a remote server * @param command command to execute * @return command output string if the command succeeds, or null */ private static String executeCommand(Session session, String command) { if (session == null || !session.isConnected()) { return null; } log.trace("Execute command {} to {}", command, session.getHost()); try { Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); InputStream output = channel.getInputStream(); channel.connect(); String result = CharStreams.toString(new InputStreamReader(output)); channel.disconnect(); return result; } catch (JSchException | IOException e) { log.debug("Failed to execute command {} due to {}", command, e.toString()); return null; } } }
apache-2.0
chen-lin-1518/weatherquery
src/com/weatherquery/app/model/Province.java
526
package com.weatherquery.app.model; public class Province { private int id; private String provinceName; private String provinceCode; public int getId(){ return id; } public void setId(int id){ this.id = id; } public String getProvinceName(){ return provinceName; } public void setProvinceName(String provinceName){ this.provinceName = provinceName; } public String getProvinceCode(){ return provinceCode; } public void setProvinceCode(String provinceCode){ this.provinceCode = provinceCode; } }
apache-2.0
osmdroid/osmdroid
osmdroid-third-party/src/main/java/org/osmdroid/api/IPosition.java
729
package org.osmdroid.api; /** * An interface that is used for simultaneously accessing several properties of the map * this is only used by the Google Wrapper/3rd party library */ @Deprecated public interface IPosition { /** * The latitude of the center of the map */ double getLatitude(); /** * The longitude of the center of the map */ double getLongitude(); /** * Whether this position has a bearing */ boolean hasBearing(); /** * The bearing of the map */ float getBearing(); /** * Whether this position has a zoom level */ boolean hasZoomLevel(); /** * The zoom level of the map */ float getZoomLevel(); }
apache-2.0
Acosix/alfresco-utility
core/repository/src/main/java/de/acosix/alfresco/utility/repo/job/GenericJob.java
1911
/* * Copyright 2016 - 2021 Acosix GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.acosix.alfresco.utility.repo.job; import org.quartz.DisallowConcurrentExecution; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.PersistJobDataAfterExecution; /** * Instances of this interface are invoked as relays of {@link Job} instances based on the * {@link de.acosix.alfresco.utility.core.repo.quartz1.InvocationRelayJob} or * {@link de.acosix.alfresco.utility.core.repo.quartz2.InvocationRelayJob} * implementation, depending on which Quartz version is in use in the Alfresco installation on which these instances have been configured. * Usage of this interface requires that job details be generated by {@link GenericJobDetailsFactoryBean a special job detail factory}. * * The primary drawback of using this interface is that job implementations cannot use {@link DisallowConcurrentExecution} or * {@link PersistJobDataAfterExecution} annotations. This is a negligible limitation since those are rarely if ever used in Alfresco * extensions. * * @author Axel Faust */ public interface GenericJob { /** * Executes the logic of this job. * * @param jobExecutionContext * the execution context for this invocation * @see Job#execute(JobExecutionContext) */ void execute(Object jobExecutionContext); }
apache-2.0
firejack-open/Firejack-Platform
platform/src/main/java/net/firejack/platform/service/content/broker/collection/SwapCollectionBroker.java
2162
/* * 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 net.firejack.platform.service.content.broker.collection; import net.firejack.platform.core.broker.ServiceBroker; import net.firejack.platform.core.domain.NamedValues; import net.firejack.platform.core.request.ServiceRequest; import net.firejack.platform.core.response.ServiceResponse; import net.firejack.platform.core.store.registry.resource.ICollectionStore; import net.firejack.platform.web.statistics.annotation.TrackDetails; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component("swapCollectionBroker") @TrackDetails public class SwapCollectionBroker extends ServiceBroker<ServiceRequest<NamedValues<Long>>, ServiceResponse> { @Autowired @Qualifier("collectionStore") private ICollectionStore collectionStore; @Override public ServiceResponse perform(ServiceRequest<NamedValues<Long>> request) throws Exception { NamedValues<Long> data = request.getData(); Long collectionId = data.get("collectionId"); Long oneRefId = data.get("oneRefId"); Long twoRefId = data.get("twoRefId"); collectionStore.swapCollectionMemberships(collectionId, oneRefId, twoRefId); return new ServiceResponse("Swap Success", true); } }
apache-2.0
hhjuliet/zstack
sdk/src/main/java/org/zstack/sdk/CreateRebootVmInstanceSchedulerAction.java
3807
package org.zstack.sdk; import java.util.HashMap; import java.util.Map; public class CreateRebootVmInstanceSchedulerAction extends AbstractAction { private static final HashMap<String, Parameter> parameterMap = new HashMap<>(); public static class Result { public ErrorCode error; public CreateRebootVmInstanceSchedulerResult value; public Result throwExceptionIfError() { if (error != null) { throw new ApiException( String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details) ); } return this; } } @Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String vmUuid; @Param(required = true, maxLength = 255, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String schedulerName; @Param(required = false, maxLength = 2048, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String schedulerDescription; @Param(required = true, validValues = {"simple","cron"}, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String type; @Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.Integer interval; @Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.Integer repeatCount; @Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.Long startTime; @Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String cron; @Param(required = false) public java.lang.String resourceUuid; @Param(required = false) public java.util.List systemTags; @Param(required = false) public java.util.List userTags; @Param(required = true) public String sessionId; public long timeout; public long pollingInterval; public Result call() { ApiResult res = ZSClient.call(this); Result ret = new Result(); if (res.error != null) { ret.error = res.error; return ret; } CreateRebootVmInstanceSchedulerResult value = res.getResult(CreateRebootVmInstanceSchedulerResult.class); ret.value = value == null ? new CreateRebootVmInstanceSchedulerResult() : value; return ret; } public void call(final Completion<Result> completion) { ZSClient.call(this, new InternalCompletion() { @Override public void complete(ApiResult res) { Result ret = new Result(); if (res.error != null) { ret.error = res.error; completion.complete(ret); return; } CreateRebootVmInstanceSchedulerResult value = res.getResult(CreateRebootVmInstanceSchedulerResult.class); ret.value = value == null ? new CreateRebootVmInstanceSchedulerResult() : value; completion.complete(ret); } }); } Map<String, Parameter> getParameterMap() { return parameterMap; } RestInfo getRestInfo() { RestInfo info = new RestInfo(); info.httpMethod = "POST"; info.path = "/vm-instances/{vmUuid}/schedulers/rebooting"; info.needSession = true; info.needPoll = true; info.parameterName = "params"; return info; } }
apache-2.0
Qi4j/qi4j-extensions
indexing-sql/src/main/java/org/qi4j/index/sql/support/postgresql/PostgreSQLAppStartup.java
5264
/* * Copyright (c) 2010, Stanislav Muhametsin. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.qi4j.index.sql.support.postgresql; import org.qi4j.api.injection.scope.Service; import org.qi4j.api.injection.scope.Uses; import org.qi4j.api.service.ServiceDescriptor; import org.qi4j.index.sql.support.skeletons.AbstractSQLStartup; import org.qi4j.library.sql.ds.DataSourceService; import org.sql.generation.api.grammar.common.datatypes.SQLDataType; import org.sql.generation.api.grammar.definition.table.TableScope; import org.sql.generation.api.grammar.definition.table.pgsql.PgSQLTableCommitAction; import org.sql.generation.api.grammar.factories.DataTypeFactory; import org.sql.generation.api.grammar.factories.DefinitionFactory; import org.sql.generation.api.grammar.factories.TableReferenceFactory; import org.sql.generation.api.vendor.PostgreSQLVendor; import org.sql.generation.api.vendor.SQLVendor; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Map; /** * TODO refactoring * * @author Stanislav Muhametsin */ public class PostgreSQLAppStartup extends AbstractSQLStartup { @Uses private ServiceDescriptor descriptor; @Service private DataSourceService _dataSource; private PostgreSQLVendor _vendor; @Override public void activate() throws Exception { super.activate(); this._vendor = this.descriptor.metaInfo( PostgreSQLVendor.class ); } // @Override // protected void dropTablesIfExist( DatabaseMetaData metaData, String schemaName, String tableName, Statement stmt ) // throws SQLException // { // ResultSet rs = metaData.getTables( null, schemaName, tableName, new String[] // { // "TABLE" // } ); // try // { // while( rs.next() ) // { // stmt.execute( this._vendor.toString( this._vendor.getManipulationFactory() // .createDropTableOrViewStatement( // this._vendor.getTableReferenceFactory().tableName( schemaName, tableName ), ObjectType.TABLE, // DropBehaviour.CASCADE, true ) ) ); // } // } // finally // { // rs.close(); // } // } @Override protected void testRequiredCapabilities() throws SQLException { // If collection structure matching will ever be needed, using ltree as path to each leaf item in // collection-generated tree will be very useful // ltree module provides specific datatype for such path, which may be indexed in order to greatly improve // performance Connection connection = this._dataSource.getDataSource().getConnection(); Statement stmt = connection.createStatement(); try { DefinitionFactory d = this._vendor.getDefinitionFactory(); TableReferenceFactory t = this._vendor.getTableReferenceFactory(); DataTypeFactory dt = this._vendor.getDataTypeFactory(); stmt.execute( this._vendor.toString( d .createTableDefinitionBuilder() .setTableScope( TableScope.LOCAL_TEMPORARY ) .setTableName( t.tableName( "ltree_test" ) ) .setCommitAction( PgSQLTableCommitAction.DROP ) .setTableContentsSource( d.createTableElementListBuilder() .addTableElement( d.createColumnDefinition( "test_column", dt.userDefined( "ltree" ) ) ) .createExpression() ).createExpression() ) ); } catch( SQLException sqle ) { throw new InternalError( "It seems that your database doesn't have ltree as type. It is needed to store collections. Please refer to hopefully supplied instructions on how to add ltree type (hint: run <pg_install_dir>/share/contrib/ltree.sql script)." ); } } @Override protected void modifyPrimitiveTypes( Map<Class<?>, SQLDataType> primitiveTypes, Map<Class<?>, Integer> jdbcTypes ) { // Set TEXT as default type for strings, since PgSQL can optimize that better than some VARCHAR with weird max // length primitiveTypes.put( String.class, this._vendor.getDataTypeFactory().text() ); } @Override protected SQLDataType getCollectionPathDataType() { return this._vendor.getDataTypeFactory().userDefined( "ltree" ); } @Override protected void setVendor( SQLVendor vendor ) { this._vendor = (PostgreSQLVendor) vendor; } }
apache-2.0
ketao1989/tools
src/main/java/test/OrderStatus.java
256
/* * Copyright (c) 2014 Qunar.com. All Rights Reserved. */ package test; /** * @author tao.ke Date: 15-3-11 Time: 下午10:12 * @version \$Id$ */ public enum OrderStatus { INIT_ORDER, NEW_ORDER, PAY_ORDER, CONFIRM_ORDER, UNPAY_ORDER, END_ORDER }
apache-2.0
rodrigokuroda/recominer
recominer-extractor/src/test/java/br/edu/utfpr/recominer/metric/network/centrality/BetweennessCalculatorTest.java
1288
package br.edu.utfpr.recominer.metric.network.centrality; import br.edu.utfpr.recominer.metric.network.centrality.BetweennessCalculator; import java.util.Map; import org.junit.Assert; import org.junit.Test; /** * * @author Rodrigo T. Kuroda <rodrigokuroda at alunos.utfpr.edu.br> */ public class BetweennessCalculatorTest { public BetweennessCalculatorTest() { } /** * Network: A-B-C-D-E */ @Test public void testCalculeGraph() { final Map<String, Double> degree = BetweennessCalculator.calcule( new NetworkFactory<String, String>() .createUndirectedSparseGraph() .addEdge("AB", "A", "B") .addEdge("BC", "B", "C") .addEdge("CD", "C", "D") .addEdge("DE", "D", "E") .getInstance()); Assert.assertEquals(0, degree.get("A"), 0.0); Assert.assertEquals(3, degree.get("B"), 0.0); Assert.assertEquals(4, degree.get("C"), 0.0); Assert.assertEquals(3, degree.get("D"), 0.0); Assert.assertEquals(0, degree.get("E"), 0.0); } @Test public void testCalculeGraphWithEdgeWeight() { // TODO search calculation examples to create test } }
apache-2.0
nh632343/Bird_Compiler
src/analyse/EmptyList.java
384
package analyse; import java.util.List; import node.ASTList; import node.ASTree; import node.Environment; public class EmptyList extends ASTList { public EmptyList(List<ASTree> list) { super(list); // TODO Auto-generated constructor stub } @Override public Object eval(Environment env) { // TODO Auto-generated method stub return null; } }
apache-2.0
OpenCode4Workspace/Watson-Work-Services-Java-SDK
wws-api/src/main/java/org/opencode4workspace/bo/FileResponse.java
2681
package org.opencode4workspace.bo; import java.io.Serializable; import java.util.Map; /** * @author Paul Withers * @since 0.7.0 * * Response from posting a file to a space */ public class FileResponse implements Serializable { private static final long serialVersionUID = 1L; private String id; private String name; private int size; private Map<String, String> urls; private long created; private String createdBy; private String contentType; /** * @author Paul Withers * @since 0.7.0 * * Enum for URL types, keys for {@link FileResponse#urls} */ public enum UrlTypes { METADATA("metadata"), NO_REDIRECT_DOWNLOAD("noredirect_download"), REDIRECT_DOWNLOAD("redirect_download"); private String value; private UrlTypes(String value) { this.value = value; } public String getValue() { return value; } } /** * @return String ID of the file */ public String getId() { return id; } /** * @param id * String ID of the file */ public void setId(String id) { this.id = id; } /** * @return file's name */ public String getName() { return name; } /** * @param name * file's name */ public void setName(String name) { this.name = name; } /** * @return size of the file in bytes */ public int getSize() { return size; } /** * @param size * of the file in bytes */ public void setSize(int size) { this.size = size; } /** * @return URLs for the file's metadata, noredirect_download, * redirect_download */ public Map<String, String> getUrls() { return urls; } /** * @param urls * for the file's metadata, noredirect_download, * redirect_download */ public void setUrls(Map<String, String> urls) { this.urls = urls; } /** * @return timestamp of when the file was added to the space */ public long getCreated() { return created; } /** * @param created * timestamp for when the file was added to the space */ public void setCreated(long created) { this.created = created; } /** * @return String id of the user who added the file to the space */ public String getCreatedBy() { return createdBy; } /** * @param createdBy * String id of the user who added the file to the space */ public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } /** * @return content type for the file */ public String getContentType() { return contentType; } /** * @param contentType * for the file */ public void setContentType(String contentType) { this.contentType = contentType; } }
apache-2.0
Draagon/draagon-metaobjects
metadata/src/main/java/com/draagon/meta/io/xml/XMLIOUtil.java
6313
package com.draagon.meta.io.xml; import com.draagon.meta.DataTypes; import com.draagon.meta.MetaData; import com.draagon.meta.attr.MetaAttribute; import com.draagon.meta.field.MetaField; import com.draagon.meta.io.MetaDataIO; import com.draagon.meta.io.MetaDataIOException; import com.draagon.meta.object.MetaObject; import com.draagon.meta.util.DataConverter; import com.draagon.meta.util.MetaDataUtil; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; import java.util.List; import static com.draagon.meta.io.xml.XMLIOConstants.*; public class XMLIOUtil { public static String getXmlName( MetaData md ) { // Return null for the XML Name so it pulls all children and sets the type field if ( md instanceof MetaObject && isXmlTyped( (MetaObject) md )) return null; if ( md.hasMetaAttr( ATTR_XMLNAME )) { return md.getMetaAttr( ATTR_XMLNAME ).getValueAsString(); } return md.getShortName(); } public static boolean isXmlTyped( MetaObject mo ) { if (mo.hasMetaAttr(ATTR_XMLTYPED)) { MetaAttribute a = mo.getMetaAttr(ATTR_XMLTYPED); if (a.getValue() == null) return false; return true; } return false; } public static String getXmlTypedField( MetaObject mo ) { if (mo.hasMetaAttr(ATTR_XMLTYPED)) { MetaAttribute a = mo.getMetaAttr(ATTR_XMLTYPED); if (a.getValue() == null) return null; return a.getValueAsString(); } return null; } public static boolean ifXmlIgnore( MetaField mf ) { return xmlBoolean(mf, ATTR_XMLIGNORE); } public static boolean xmlBoolean(MetaField mf, String attrName) { if (mf.hasMetaAttr(attrName)) { MetaAttribute a = mf.getMetaAttr(attrName); if (a.getValue() == null) return false; return DataConverter.toBoolean(a.getValue()); } return false; } public static boolean isXmlAttr( MetaField mf ) { return xmlBoolean(mf, ATTR_ISXMLATTR); } public static boolean xmlWrap( MetaField mf ) { boolean wrap = true; if ( mf.hasMetaAttr( ATTR_XMLWRAP )) { MetaAttribute isXml = mf.getMetaAttr( ATTR_XMLWRAP ); wrap = DataConverter.toBoolean( isXml.getValue() ); } else if ( mf.getDataType() == DataTypes.OBJECT ) { wrap = false; } else if ( mf.getDataType() == DataTypes.OBJECT_ARRAY ) { /*try { MetaObject objRef = MetaDataUtil.getObjectRef(mf); if ( getXmlName( objRef ).equals( getXmlName( mf ))) { wrap = false; } } catch( MetaObjectNotFoundException ignore ) { wrap = true; }*/ wrap = true; } return wrap; } public static boolean hasObjectRef(MetaDataIO io, MetaField mf ) throws MetaDataIOException { return MetaDataUtil.hasObjectRef(mf); } public static MetaObject getObjectRef(MetaDataIO io, MetaField mf ) throws MetaDataIOException { return MetaDataUtil.getObjectRef(mf); /*ObjectReference oref = mf.getFirstObjectReference(); if ( oref == null ) throw new MetaDataIOException( io, "No ObjectReference existed ["+mf+"]" ); MetaObject refmo = oref.getReferencedObject(); if ( refmo == null ) throw new MetaDataIOException( io, "No MetaObject reference not found ["+refmo+"]" ); return refmo;*/ } /*public static Element getFirstElementByName(MetaDataIO io, Element e, MetaField mf ) throws MetaDataIOException { String xmlName = getXmlName( mf); Node node = e.getElementsByTagName(xmlName).item(0); if (node == null) return null; if ( node instanceof Element ) return (Element) e; throw new MetaDataIOException( io, "Node found by name ["+xmlName+"] was not an Element ["+node+"]"); } public static List<Element> getElementsByName(MetaDataIO io, Element e, MetaData md ) throws MetaDataIOException { List<Element> elements = new ArrayList<>(); String xmlName = getXmlName( md); NodeList nodeList = e.getElementsByTagName(xmlName); for( int i=0; i < nodeList.getLength(); i++ ) { Node node = nodeList.item(i); if ( node instanceof Element ) { elements.add((Element) node); } else { throw new MetaDataIOException( io, "Node found by name ["+xmlName+"] was not an Element ["+node+"]"); } } return elements; }*/ /** * Returns a collection of child elements of the given name * or all elements if name is null */ public static Element getFirstChildElementOfName(Node n, String name) { //if ( name == null ) throw new IllegalArgumentException("Name cannot be null"); List<Element> els = getChildElementsOfName( n, name, true ); if ( els.isEmpty() ) return null; return els.iterator().next(); } /** * Returns a collection of child elements of the given name * or all elements if name is null */ public static List<Element> getChildElementsOfName(Node n, String name) { //if ( name == null ) throw new IllegalArgumentException("Name cannot be null"); return getChildElementsOfName( n, name, false ); } /** * Returns a collection of child elements of the given name * or all elements if name is null */ public static List<Element> getChildElementsOfName(Node n, String name, boolean firstOnly) { if ( n == null ) throw new IllegalArgumentException("Node cannot be null"); ArrayList<Element> elements = new ArrayList<>(); if (n == null) return elements; NodeList list = n.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node instanceof Element && ( name == null || node.getNodeName().equals(name))) { elements.add((Element) node); if ( firstOnly ) break; } } return elements; } }
apache-2.0
deleidos/digitaledge-platform
ingest/src/test/java/com/deleidos/rtws/core/util/ThrottleTest.java
15229
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright {yyyy} {name of copyright owner} * * 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.deleidos.rtws.core.util; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import org.junit.Test; import com.deleidos.rtws.commons.util.time.MockClock; import com.deleidos.rtws.core.util.Throttle; import com.deleidos.rtws.core.util.Throttle.Action; import com.deleidos.rtws.core.util.Throttle.State; import com.deleidos.rtws.core.util.Throttle.StateTransitionListener; public class ThrottleTest { @Test public void testEvaluateProceed() { StateTransitionListener listener = mock(StateTransitionListener.class); MockClock clock = new MockClock(); MockThrottle throttle = new MockThrottle(); throttle.setListener(listener); throttle.clock = clock; when(throttle.mock.checkForThrottle()).thenReturn(Action.proceed()); assertEquals(State.PROCEED, throttle.evaluate()); verify(throttle.mock, times(1)).checkForThrottle(); verify(throttle.mock, times(0)).checkForResume(); assertEquals(0, clock.time()); } @Test public void testEvaluateTerminate() { StateTransitionListener listener = mock(StateTransitionListener.class); MockClock clock = new MockClock(); MockThrottle throttle = new MockThrottle(); throttle.setListener(listener); throttle.clock = clock; when(throttle.mock.checkForThrottle()).thenReturn(Action.terminate()); assertEquals(State.TERMINATE, throttle.evaluate()); verify(throttle.mock, times(1)).checkForThrottle(); verify(throttle.mock, times(0)).checkForResume(); verify(listener, times(1)).onTerminate(); verifyNoMoreInteractions(listener); assertEquals(0, clock.time()); } @Test public void testEvaluatePause() { StateTransitionListener listener = mock(StateTransitionListener.class); MockClock clock = new MockClock(); MockThrottle throttle = new MockThrottle(); throttle.setListener(listener); throttle.clock = clock; when(throttle.mock.checkForThrottle()).thenReturn(Action.pause(1000)); assertEquals(State.PAUSE, throttle.evaluate()); verify(throttle.mock, times(1)).checkForThrottle(); verify(throttle.mock, times(0)).checkForResume(); verify(listener, times(1)).onPause(); verifyNoMoreInteractions(listener); assertEquals(1000, clock.time()); } @Test public void testEvaluateSuspend() throws Exception { StateTransitionListener listener = mock(StateTransitionListener.class); MockClock clock = new MockClock(); MockThrottle throttle = new MockThrottle(); throttle.setListener(listener); throttle.clock = clock; when(throttle.mock.checkForThrottle()).thenReturn(Action.suspend(1000)); when(throttle.mock.checkForResume()).thenReturn(false, true); assertEquals(State.SUSPEND, throttle.evaluate()); verify(throttle.mock, times(1)).checkForThrottle(); verify(listener, times(1)).onSuspend(); verifyNoMoreInteractions(listener); assertEquals(0, clock.time()); } private interface MockThrottleDelegate { public boolean checkForResume(); public Action checkForThrottle(); } private class MockThrottle extends Throttle { public MockThrottleDelegate mock = mock(MockThrottleDelegate.class); protected boolean checkForResume() {return mock.checkForResume();} protected Action checkForThrottle() {return mock.checkForThrottle();} } }
apache-2.0
pfirmstone/JGDMS
qa/src/org/apache/river/test/share/TesterTransactionManager.java
8554
/* * 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.river.test.share; import java.io.IOException; import org.apache.river.qa.harness.QAConfig; import java.io.ObjectStreamException; import java.io.Serializable; import java.rmi.RemoteException; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; import net.jini.config.Configuration; import net.jini.config.ConfigurationException; import net.jini.core.transaction.*; import net.jini.core.transaction.server.*; import net.jini.export.CodebaseAccessor; import net.jini.export.Exporter; import net.jini.jeri.AtomicILFactory; import net.jini.jeri.BasicILFactory; import net.jini.jeri.BasicJeriExporter; import net.jini.jeri.tcp.TcpServerEndpoint; import net.jini.security.TrustVerifier; import net.jini.security.proxytrust.ProxyTrust; import org.apache.river.api.util.Startable; import org.apache.river.proxy.CodebaseProvider; /** * This class provides a simple transaction manager that tests can use * to test a particpant. It is not designed to be robust in any way, * just to allow a test to drive the participant to various parts of * the transaction in a controlled way. This means that some of the * methods are not supported -- anything not needed by a participant * may have a simpler local version, since this is always used locally * by the test. */ public class TesterTransactionManager implements TransactionManager, TransactionConstants, Serializable, ProxyTrust, Startable, CodebaseAccessor { private static Logger logger = Logger.getLogger("org.apache.river.qa.harness"); private static int serviceID = 100; /** Our transaction objects. */ private final Map txns; /** The next ID to allocate. */ private static long nextID = 1; final LoginContext context; final RemoteException exception; final Configuration c; private Object proxy; private Object myRef; public TesterTransactionManager() throws RemoteException { this.txns = Collections.synchronizedMap(new HashMap()); c = QAConfig.getConfig().getConfiguration(); LoginContext context = null; RemoteException exception = null; try { context = (LoginContext) c.getEntry("test", "mahaloLoginContext", LoginContext.class, null); if (context != null) { logger.log(Level.FINEST, "got a TesterTransactionManager login context"); } } catch (Throwable e) { exception = new RemoteException("Configuration error", e); } finally { this.context = context; this.exception = exception; } } public synchronized TrustVerifier getProxyVerifier() { return new TesterTransactionManagerProxyVerifier((TransactionManager) myRef); } private void doExport(Configuration c) throws RemoteException { Exporter exporter = new BasicJeriExporter(TcpServerEndpoint.getInstance(0), // new AtomicILFactory(null, null, TesterTransactionManager.class ) new BasicILFactory() ); if (c instanceof org.apache.river.qa.harness.QAConfiguration) { try { exporter = (Exporter) c.getEntry("test", "testerTransactionManagerExporter", Exporter.class); } catch (ConfigurationException e) { throw new RemoteException("Configuration error", e); } } myRef = exporter.export(this); proxy = TesterTransactionManagerProxy.getInstance( (TransactionManager) myRef, serviceID++); } private void doExportWithLogin(LoginContext context, final Configuration c) throws RemoteException { try { context.login(); } catch (Throwable e) { throw new RemoteException("Login failed", e); } try { Subject.doAsPrivileged(context.getSubject(), new PrivilegedExceptionAction() { public Object run() throws RemoteException { doExport(c); return null; } }, null); } catch (PrivilegedActionException e) { Throwable t = e.getException(); throw new RemoteException("doAs failed", t); } catch (Throwable e) { throw new RemoteException("doAs failed", e); } } public synchronized Object writeReplace() throws ObjectStreamException { return proxy; } /** * Return a new <code>ServerTransaction</code> object. */ public synchronized TesterTransaction create() { TesterTransaction tt = new TesterTransaction(this, nextID()); txns.put(tt.idObj, tt); return tt; } /** * Return the next transaction id. */ private static synchronized long nextID() { return nextID++; } /** * This implementation ignores the time -- it is always synchronous. */ public void commit(long id, long timeout) throws UnknownTransactionException, CannotCommitException, RemoteException { commit(id); } /** * This implementation ignores the time -- it is always synchronous. */ public synchronized void commit(long id) throws UnknownTransactionException, CannotCommitException, RemoteException { tt(id).commit(); } private TesterTransaction tt(long id) throws UnknownTransactionException { try { return (TesterTransaction) txns.get(new Long(id)); } catch (NullPointerException e) { throw new UnknownTransactionException("" + id); } } /** * This implementation ignores the time -- it is always synchronous. */ public void abort(long id, long timeout) throws UnknownTransactionException, CannotAbortException, RemoteException { abort(id); } /** * This implementation ignores the time -- it is always synchronous. */ public synchronized void abort(long id) throws UnknownTransactionException, CannotAbortException, RemoteException { tt(id).sendAbort(); } /** * @throws UnsupportedOperationException * Use <code>create()</code>: no leases or other mess * supported or needed in this local case. * @see #create() */ public TransactionManager.Created create(long leaseTime) { throw new UnsupportedOperationException("don't get fancy: use" + " create()"); } /** * Return the current state of this transasction. */ public synchronized int getState(long id) throws UnknownTransactionException, RemoteException { return tt(id).getState(); } /** * Join the transaction. Only one participant in each transaction, * currently. */ public synchronized void join(long id, TransactionParticipant part, long crashCnt) throws UnknownTransactionException, CannotJoinException, CrashCountException { tt(id).join(part, crashCnt); } @Override public synchronized void start() throws Exception { if (exception != null) throw exception; if (context != null) { doExportWithLogin(context, c); } else { doExport(c); } } @Override public String getClassAnnotation() throws IOException { return CodebaseProvider.getClassAnnotation(TesterTransactionManagerProxy.class); } @Override public String getCertFactoryType() throws IOException { return null; } @Override public String getCertPathEncoding() throws IOException { return null; } @Override public byte[] getEncodedCerts() throws IOException { return null; } }
apache-2.0
opetrovski/development
oscm-portal/javasrc/org/oscm/ui/dialog/classic/exportBillingdata/ExportBillingDataModel.java
4870
/******************************************************************************* * Copyright FUJITSU LIMITED 2017 *******************************************************************************/ package org.oscm.ui.dialog.classic.exportBillingdata; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.model.SelectItem; import org.oscm.internal.types.enumtypes.BillingSharesResultType; @ViewScoped @ManagedBean(name="exportBillingDataModel") public class ExportBillingDataModel { boolean initialized; private Date fromDate; private Date toDate; private String failedDateComponentId = null; // Select options List<Customer> customers; List<SelectItem> billingDataTypeOptions; List<SelectItem> sharesResultTypeOptions; String anyCustomerSelected = "0"; public String getAnyCustomerSelected() { return anyCustomerSelected; } public void setAnyCustomerSelected(String anyCustomerSelected) { this.anyCustomerSelected = anyCustomerSelected; } // current user boolean platformOperator = false; boolean supplierOrReseller = false; public List<SelectItem> getSharesResultTypeOptions() { return sharesResultTypeOptions; } public void setSharesResultTypeOptions( List<SelectItem> sharesResultTypeOptions) { this.sharesResultTypeOptions = sharesResultTypeOptions; } // chosen options private List<BillingSharesResultType> billingSharesResultTypes; BillingSharesResultType selectedSharesResultType; BillingDataType selectedBillingDataType; // xml result byte[] billingData; // getter and setter public byte[] getBillingData() { return billingData; } public void setBillingData(byte[] billingData) { this.billingData = billingData; } public boolean isInitialized() { return initialized; } public void setInitialized(boolean initialized) { this.initialized = initialized; } public Date getFromDate() { /* * BUG #8350: no initialization */ return fromDate; } public void setFromDate(Date fromDate) { this.fromDate = fromDate; } public Date getToDate() { return toDate; } public void setToDate(Date toDate) { this.toDate = toDate; } public BillingDataType getSelectedBillingDataType() { return selectedBillingDataType; } public void setSelectedBillingDataType( BillingDataType selectedBillingDataType) { this.selectedBillingDataType = selectedBillingDataType; } public List<SelectItem> getBillingDataTypeOptions() { return billingDataTypeOptions; } public void setBillingDataTypeOptions( List<SelectItem> billingDataTypeOptions) { this.billingDataTypeOptions = billingDataTypeOptions; } public List<Customer> getCustomers() { return customers; } public void setCustomers(List<Customer> customerOrgs) { this.customers = customerOrgs; } public BillingSharesResultType getSelectedSharesResultType() { return selectedSharesResultType; } public void setSelectedSharesResultType( BillingSharesResultType selectedSharesResultType) { this.selectedSharesResultType = selectedSharesResultType; } public List<String> getSelectedOrganizationIds() { List<String> selectedOrganizationIds = new ArrayList<String>(); for (Customer customer : customers) { if (customer.isSelected()) { selectedOrganizationIds.add(customer.getOrganizationId()); } } return selectedOrganizationIds; } public List<BillingSharesResultType> getBillingSharesResultTypes() { return billingSharesResultTypes; } public void setBillingSharesResultTypes( List<BillingSharesResultType> billingSharesResultTypes) { this.billingSharesResultTypes = billingSharesResultTypes; } public boolean isPlatformOperator() { return platformOperator; } public void setPlatformOperator(boolean platformOperator) { this.platformOperator = platformOperator; } public boolean isSupplierOrReseller() { return supplierOrReseller; } public void setSupplierOrReseller(boolean supplierOrReseller) { this.supplierOrReseller = supplierOrReseller; } public void setFailedDateComponentId(String failedDateComponentId) { this.failedDateComponentId = (failedDateComponentId == null) ? "" : failedDateComponentId; } public String getFailedDateComponentId() { return this.failedDateComponentId; } }
apache-2.0
chenzj-king/RvHelper
demo/src/main/java/com/dreamliner/lib/rvhelper/sample/ui/activity/customloading/CustomLoadingActivity.java
3091
package com.dreamliner.lib.rvhelper.sample.ui.activity.customloading; import androidx.recyclerview.widget.LinearLayoutManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.dreamliner.lib.rvhelper.sample.AppContext; import com.dreamliner.lib.rvhelper.sample.R; import com.dreamliner.lib.rvhelper.sample.ui.adapter.TextAdapter; import com.dreamliner.lib.rvhelper.sample.ui.base.BaseActivity; import com.dreamliner.lib.rvhelper.sample.utils.DividerUtil; import com.dreamliner.ptrlib.PtrFrameLayout; import com.dreamliner.rvhelper.OptimumRecyclerView; import com.dreamliner.rvhelper.interfaces.OnRefreshListener; import java.util.ArrayList; import java.util.Random; import butterknife.BindView; /** * @author chenzj * @Title: CustomLoadingActivity * @Description: 类的描述 - * @date 2016/10/11 9:42 * @email admin@chenzhongjin.cn */ public class CustomLoadingActivity extends BaseActivity implements OnRefreshListener { private static final String TAG = "CustomLoadingActivity"; @BindView(R.id.optimum_rv) OptimumRecyclerView mOptimumRecyclerView; private TextAdapter mAdapter; @Override protected int getLayoutId() { return R.layout.activity_loading; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_loading, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_try_loading) { mOptimumRecyclerView.showLoadingView(); getNewData(); return true; } return super.onOptionsItemSelected(item); } @Override protected void initViews() { mAdapter = new TextAdapter(new ItemClickIml(this)); mOptimumRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mOptimumRecyclerView.addItemDecoration(DividerUtil.getDefalutDivider(AppContext.getInstance())); mOptimumRecyclerView.setAdapter(mAdapter); //设置下拉刷新 mOptimumRecyclerView.setRefreshListener(this); getNewData(); } @Override public void onRefresh(PtrFrameLayout ptrFrameLayout) { getNewData(); } private void getNewData() { mHandler.postDelayed(new Runnable() { @Override public void run() { //get Data by db/server updateData(); } }, 1000); } protected void updateData() { ArrayList<String> strings = new ArrayList<>(); int size = new Random().nextInt(50); size = size < 15 ? 15 : size; int itemCount = 0; for (int i = itemCount; i < size + itemCount; i++) { strings.add("测试数据 " + (i + 1)); } mAdapter.update(strings); mOptimumRecyclerView.loadMoreFinish(false, true); } @Override protected void onItemClick(View view, int position) { showToast("click " + (position + 1) + " item"); } }
apache-2.0
OSGP/Protocol-Adapter-OSLP
osgp-adapter-protocol-oslp-elster/src/main/java/org/opensmartgridplatform/adapter/protocol/oslp/elster/infra/messaging/processors/TariffSwitchingGetStatusRequestMessageProcessor.java
7756
/** * Copyright 2015 Smart Society Services B.V. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ package org.opensmartgridplatform.adapter.protocol.oslp.elster.infra.messaging.processors; import java.io.IOException; import javax.jms.JMSException; import javax.jms.ObjectMessage; import org.opensmartgridplatform.adapter.protocol.oslp.elster.device.DeviceRequest; import org.opensmartgridplatform.adapter.protocol.oslp.elster.device.DeviceResponse; import org.opensmartgridplatform.adapter.protocol.oslp.elster.device.DeviceResponseHandler; import org.opensmartgridplatform.adapter.protocol.oslp.elster.device.requests.GetStatusDeviceRequest; import org.opensmartgridplatform.adapter.protocol.oslp.elster.device.responses.GetStatusDeviceResponse; import org.opensmartgridplatform.adapter.protocol.oslp.elster.infra.messaging.DeviceRequestMessageProcessor; import org.opensmartgridplatform.adapter.protocol.oslp.elster.infra.messaging.OslpEnvelopeProcessor; import org.opensmartgridplatform.dto.valueobjects.DeviceStatusDto; import org.opensmartgridplatform.dto.valueobjects.DomainTypeDto; import org.opensmartgridplatform.oslp.OslpEnvelope; import org.opensmartgridplatform.oslp.SignedOslpEnvelopeDto; import org.opensmartgridplatform.oslp.UnsignedOslpEnvelopeDto; import org.opensmartgridplatform.shared.exceptionhandling.ComponentType; import org.opensmartgridplatform.shared.exceptionhandling.OsgpException; import org.opensmartgridplatform.shared.exceptionhandling.TechnicalException; import org.opensmartgridplatform.shared.infra.jms.DeviceMessageMetadata; import org.opensmartgridplatform.shared.infra.jms.MessageMetadata; import org.opensmartgridplatform.shared.infra.jms.MessageType; import org.opensmartgridplatform.shared.infra.jms.ProtocolResponseMessage; import org.opensmartgridplatform.shared.infra.jms.ResponseMessageResultType; import org.opensmartgridplatform.shared.infra.jms.ResponseMessageSender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * Class for processing tariff switching get status request messages */ @Component("oslpTariffSwitchingGetStatusRequestMessageProcessor") public class TariffSwitchingGetStatusRequestMessageProcessor extends DeviceRequestMessageProcessor implements OslpEnvelopeProcessor { /** * Logger for this class */ private static final Logger LOGGER = LoggerFactory.getLogger(TariffSwitchingGetStatusRequestMessageProcessor.class); public TariffSwitchingGetStatusRequestMessageProcessor() { super(MessageType.GET_TARIFF_STATUS); } @Override public void processMessage(final ObjectMessage message) { LOGGER.info("Processing tariff switching get status request message"); MessageMetadata messageMetadata; try { messageMetadata = MessageMetadata.fromMessage(message); } catch (final JMSException e) { LOGGER.error("UNRECOVERABLE ERROR, unable to read ObjectMessage instance, giving up.", e); return; } this.printDomainInfo(messageMetadata.getMessageType(), messageMetadata.getDomain(), messageMetadata.getDomainVersion()); final GetStatusDeviceRequest deviceRequest = new GetStatusDeviceRequest( DeviceRequest.newBuilder().messageMetaData(messageMetadata), DomainTypeDto.TARIFF_SWITCHING); this.deviceService.getStatus(deviceRequest); } @Override public void processSignedOslpEnvelope(final String deviceIdentification, final SignedOslpEnvelopeDto signedOslpEnvelopeDto) { final UnsignedOslpEnvelopeDto unsignedOslpEnvelopeDto = signedOslpEnvelopeDto.getUnsignedOslpEnvelopeDto(); final OslpEnvelope oslpEnvelope = signedOslpEnvelopeDto.getOslpEnvelope(); final String correlationUid = unsignedOslpEnvelopeDto.getCorrelationUid(); final String organisationIdentification = unsignedOslpEnvelopeDto.getOrganisationIdentification(); final String domain = unsignedOslpEnvelopeDto.getDomain(); final String domainVersion = unsignedOslpEnvelopeDto.getDomainVersion(); final String messageType = unsignedOslpEnvelopeDto.getMessageType(); final int messagePriority = unsignedOslpEnvelopeDto.getMessagePriority(); final String ipAddress = unsignedOslpEnvelopeDto.getIpAddress(); final int retryCount = unsignedOslpEnvelopeDto.getRetryCount(); final boolean isScheduled = unsignedOslpEnvelopeDto.isScheduled(); final DeviceResponseHandler deviceResponseHandler = new DeviceResponseHandler() { @Override public void handleResponse(final DeviceResponse deviceResponse) { TariffSwitchingGetStatusRequestMessageProcessor.this.handleGetStatusDeviceResponse(deviceResponse, TariffSwitchingGetStatusRequestMessageProcessor.this.responseMessageSender, domain, domainVersion, messageType, retryCount); } @Override public void handleException(final Throwable t, final DeviceResponse deviceResponse) { TariffSwitchingGetStatusRequestMessageProcessor.this.handleUnableToConnectDeviceResponse(deviceResponse, t, null, TariffSwitchingGetStatusRequestMessageProcessor.this.responseMessageSender, deviceResponse, domain, domainVersion, messageType, isScheduled, retryCount); } }; final DeviceRequest deviceRequest = new DeviceRequest(organisationIdentification, deviceIdentification, correlationUid, messagePriority); try { this.deviceService.doGetStatus(oslpEnvelope, deviceRequest, deviceResponseHandler, ipAddress); } catch (final IOException e) { this.handleError(e, correlationUid, organisationIdentification, deviceIdentification, domain, domainVersion, messageType, messagePriority, retryCount); } } private void handleGetStatusDeviceResponse(final DeviceResponse deviceResponse, final ResponseMessageSender responseMessageSender, final String domain, final String domainVersion, final String messageType, final int retryCount) { ResponseMessageResultType result = ResponseMessageResultType.OK; OsgpException osgpException = null; DeviceStatusDto status = null; try { final GetStatusDeviceResponse response = (GetStatusDeviceResponse) deviceResponse; status = response.getDeviceStatus(); } catch (final Exception e) { LOGGER.error("Device Response Exception", e); result = ResponseMessageResultType.NOT_OK; osgpException = new TechnicalException(ComponentType.UNKNOWN, "Exception occurred while getting device status", e); } final DeviceMessageMetadata deviceMessageMetadata = new DeviceMessageMetadata( deviceResponse.getDeviceIdentification(), deviceResponse.getOrganisationIdentification(), deviceResponse.getCorrelationUid(), messageType, deviceResponse.getMessagePriority()); final ProtocolResponseMessage responseMessage = ProtocolResponseMessage.newBuilder().domain(domain) .domainVersion(domainVersion).deviceMessageMetadata(deviceMessageMetadata).result(result) .osgpException(osgpException).dataObject(status).retryCount(retryCount).build(); responseMessageSender.send(responseMessage); } }
apache-2.0
l-dobrev/activemq-artemis
artemis-protocols/artemis-proton-plug/src/main/java/org/proton/plug/context/client/ProtonClientConnectionContextFactory.java
1883
/* * 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.proton.plug.context.client; import org.proton.plug.AMQPConnectionContext; import org.proton.plug.AMQPConnectionContextFactory; import org.proton.plug.AMQPConnectionCallback; public class ProtonClientConnectionContextFactory extends AMQPConnectionContextFactory { private static final AMQPConnectionContextFactory theInstance = new ProtonClientConnectionContextFactory(); public static AMQPConnectionContextFactory getFactory() { return theInstance; } @Override public AMQPConnectionContext createConnection(AMQPConnectionCallback connectionCallback) { return new ProtonClientConnectionContext(connectionCallback); } @Override public AMQPConnectionContext createConnection(AMQPConnectionCallback connectionCallback, int idleTimeout, int maxFrameSize, int channelMax) { return new ProtonClientConnectionContext(connectionCallback, idleTimeout, maxFrameSize, channelMax); } }
apache-2.0
stephanlukasczyk/busybox-preprocessor
src/me/lukasczyk/busybox_preprocessor/core/package-info.java
703
/* * Copyright 2016 Stephan Lukasczyk * * 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 central classes for the project. */ package me.lukasczyk.busybox_preprocessor.core;
apache-2.0
mcekovic/tennis-crystal-ball
tennis-stats/src/main/java/org/strangeforest/tcb/stats/model/DominanceEra.java
741
package org.strangeforest.tcb.stats.model; import java.util.*; public class DominanceEra { private final int seasonCount; private double dominanceRatio; private PlayerDominanceTimeline player; public DominanceEra(List<DominanceSeason> seasons) { seasonCount = seasons.size(); dominanceRatio = seasons.stream().mapToDouble(DominanceSeason::getDominanceRatio).average().orElseThrow(); player = seasons.get(0).getEraPlayer(); } public int getSeasonCount() { return seasonCount; } public double getDominanceRatio() { return dominanceRatio; } public int getDominanceRatioRounded() { return DominanceTimeline.roundDominanceRatio(dominanceRatio); } public PlayerDominanceTimeline getPlayer() { return player; } }
apache-2.0
ZhangPeng1990/crm
gdsap-framework/src/main/java/uk/co/quidos/gdsap/framework/charge/persistence/object/GdsapChargeTransactionRecord.java
12121
package uk.co.quidos.gdsap.framework.charge.persistence.object; import java.util.Date; import uk.co.quidos.dal.object.AbstractDO; public class GdsapChargeTransactionRecord extends AbstractDO { private static final long serialVersionUID = -8404061717322266905L; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private Long id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.TRANSACTION_NUM * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private Double transactionNum; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.TRANSACTION_TYPE * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private Integer transactionType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.RECORD_TYPE * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private Integer recordType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.PURPOSE * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private Integer purpose; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.USER_ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private Long userId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.USER_NAME * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private String userName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.ADMIN_ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private Integer adminId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.ADMIN_USER_NAME * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private String adminUserName; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.REPORT_ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private Long reportId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column gdsap_charge_transaction_record.INSERT_TIME * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ private Date insertTime; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.ID * * @return the value of gdsap_charge_transaction_record.ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public Long getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.ID * * @param id the value for gdsap_charge_transaction_record.ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setId(Long id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.TRANSACTION_NUM * * @return the value of gdsap_charge_transaction_record.TRANSACTION_NUM * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public Double getTransactionNum() { return transactionNum; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.TRANSACTION_NUM * * @param transactionNum the value for gdsap_charge_transaction_record.TRANSACTION_NUM * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setTransactionNum(Double transactionNum) { this.transactionNum = transactionNum; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.TRANSACTION_TYPE * * @return the value of gdsap_charge_transaction_record.TRANSACTION_TYPE * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public Integer getTransactionType() { return transactionType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.TRANSACTION_TYPE * * @param transactionType the value for gdsap_charge_transaction_record.TRANSACTION_TYPE * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setTransactionType(Integer transactionType) { this.transactionType = transactionType; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.RECORD_TYPE * * @return the value of gdsap_charge_transaction_record.RECORD_TYPE * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public Integer getRecordType() { return recordType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.RECORD_TYPE * * @param recordType the value for gdsap_charge_transaction_record.RECORD_TYPE * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setRecordType(Integer recordType) { this.recordType = recordType; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.PURPOSE * * @return the value of gdsap_charge_transaction_record.PURPOSE * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public Integer getPurpose() { return purpose; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.PURPOSE * * @param purpose the value for gdsap_charge_transaction_record.PURPOSE * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setPurpose(Integer purpose) { this.purpose = purpose; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.USER_ID * * @return the value of gdsap_charge_transaction_record.USER_ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public Long getUserId() { return userId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.USER_ID * * @param userId the value for gdsap_charge_transaction_record.USER_ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setUserId(Long userId) { this.userId = userId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.USER_NAME * * @return the value of gdsap_charge_transaction_record.USER_NAME * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public String getUserName() { return userName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.USER_NAME * * @param userName the value for gdsap_charge_transaction_record.USER_NAME * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.ADMIN_ID * * @return the value of gdsap_charge_transaction_record.ADMIN_ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public Integer getAdminId() { return adminId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.ADMIN_ID * * @param adminId the value for gdsap_charge_transaction_record.ADMIN_ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setAdminId(Integer adminId) { this.adminId = adminId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.ADMIN_USER_NAME * * @return the value of gdsap_charge_transaction_record.ADMIN_USER_NAME * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public String getAdminUserName() { return adminUserName; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.ADMIN_USER_NAME * * @param adminUserName the value for gdsap_charge_transaction_record.ADMIN_USER_NAME * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setAdminUserName(String adminUserName) { this.adminUserName = adminUserName == null ? null : adminUserName.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.REPORT_ID * * @return the value of gdsap_charge_transaction_record.REPORT_ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public Long getReportId() { return reportId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.REPORT_ID * * @param reportId the value for gdsap_charge_transaction_record.REPORT_ID * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setReportId(Long reportId) { this.reportId = reportId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column gdsap_charge_transaction_record.INSERT_TIME * * @return the value of gdsap_charge_transaction_record.INSERT_TIME * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public Date getInsertTime() { return insertTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column gdsap_charge_transaction_record.INSERT_TIME * * @param insertTime the value for gdsap_charge_transaction_record.INSERT_TIME * * @mbggenerated Fri Oct 31 17:19:10 CST 2014 */ public void setInsertTime(Date insertTime) { this.insertTime = insertTime; } }
apache-2.0
visallo/visallo
web/web-base/src/main/java/org/visallo/web/privilegeFilters/PublishPrivilegeFilter.java
465
package org.visallo.web.privilegeFilters; import com.google.inject.Inject; import com.google.inject.Singleton; import org.visallo.core.model.user.PrivilegeRepository; import org.visallo.web.clientapi.model.Privilege; @Singleton public class PublishPrivilegeFilter extends PrivilegeFilter { @Inject protected PublishPrivilegeFilter(PrivilegeRepository privilegeRepository) { super(Privilege.newSet(Privilege.PUBLISH), privilegeRepository); } }
apache-2.0
lastaflute/lastaflute
src/main/java/org/lastaflute/core/json/adapter/CollectionGsonAdaptable.java
5929
/* * Copyright 2015-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.lastaflute.core.json.adapter; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.lastaflute.core.json.JsonMappingOption; import com.google.gson.Gson; import com.google.gson.InstanceCreator; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.bind.CollectionTypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; /** * @author jflute * @since 0.7.3 (2015/12/29 Tuesday) */ public interface CollectionGsonAdaptable { // to show property path in exception message // =================================================================================== // Type Adapter // ============ class WrappingCollectionTypeAdapterFactory implements TypeAdapterFactory { protected final CollectionTypeAdapterFactory embeddedFactory; protected final JsonMappingOption gsonOption; public WrappingCollectionTypeAdapterFactory(JsonMappingOption gsonOption) { this.embeddedFactory = createEmbeddedFactory(); this.gsonOption = gsonOption; } protected CollectionTypeAdapterFactory createEmbeddedFactory() { final Map<Type, InstanceCreator<?>> instanceCreators = prepareInstanceCreators(); final ConstructorConstructor constructor = createConstructorConstructor(instanceCreators); return newCollectionTypeAdapterFactory(constructor); } protected Map<Type, InstanceCreator<?>> prepareInstanceCreators() { return Collections.emptyMap(); } protected ConstructorConstructor createConstructorConstructor(Map<Type, InstanceCreator<?>> instanceCreators) { return new ConstructorConstructor(instanceCreators); } protected CollectionTypeAdapterFactory newCollectionTypeAdapterFactory(ConstructorConstructor constructor) { return new CollectionTypeAdapterFactory(constructor); } @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { final TypeAdapter<T> embedded = embeddedFactory.create(gson, typeToken); // null allowed when other types return embedded != null ? createWrappingTypeAdapterCollection(embedded) : null; } @SuppressWarnings("unchecked") protected <T> TypeAdapter<T> createWrappingTypeAdapterCollection(TypeAdapter<T> embedded) { return (TypeAdapter<T>) newWrappingTypeAdapterCollection(embedded, gsonOption); } protected <T> WrappingTypeAdapterCollection newWrappingTypeAdapterCollection(TypeAdapter<T> embedded, JsonMappingOption option) { return new WrappingTypeAdapterCollection(embedded, option); } } class WrappingTypeAdapterCollection extends TypeAdapter<Collection<?>> { protected final TypeAdapter<Collection<?>> embedded; protected final JsonMappingOption gsonOption; @SuppressWarnings("unchecked") public WrappingTypeAdapterCollection(TypeAdapter<?> embedded, JsonMappingOption gsonOption) { this.embedded = (TypeAdapter<Collection<?>>) embedded; this.gsonOption = gsonOption; } @Override public Collection<?> read(JsonReader in) throws IOException { if (gsonOption.isListNullToEmptyReading()) { if (in.peek() == JsonToken.NULL) { in.nextNull(); return Collections.emptyList(); } } return embedded.read(in); } @Override public void write(JsonWriter out, Collection<?> collection) throws IOException { if (gsonOption.isListNullToEmptyWriting()) { if (collection == null) { out.beginArray(); out.endArray(); return; // [] } } embedded.write(out, collection); } } // =================================================================================== // Creator // ======= default TypeAdapterFactory createCollectionTypeAdapterFactory() { return newWrappingCollectionTypeAdapterFactory(getGsonOption()); } default WrappingCollectionTypeAdapterFactory newWrappingCollectionTypeAdapterFactory(JsonMappingOption option) { return new WrappingCollectionTypeAdapterFactory(option); } // =================================================================================== // Accessor // ======== JsonMappingOption getGsonOption(); }
apache-2.0
ryandcarter/hybris-connector
src/main/java/org/mule/modules/hybris/model/ExportsDTO.java
2055
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.11.29 at 12:35:53 PM GMT // package org.mule.modules.hybris.model; 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.XmlType; /** * <p>Java class for exportsDTO complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="exportsDTO"> * &lt;complexContent> * &lt;extension base="{}abstractCollectionDTO"> * &lt;sequence> * &lt;element ref="{}export" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "exportsDTO", propOrder = { "export" }) public class ExportsDTO extends AbstractCollectionDTO { protected List<ExportDTO> export; /** * Gets the value of the export 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 export property. * * <p> * For example, to add a new item, do as follows: * <pre> * getExport().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ExportDTO } * * */ public List<ExportDTO> getExport() { if (export == null) { export = new ArrayList<ExportDTO>(); } return this.export; } }
apache-2.0
DmitryTeterkin/java-programming-for-testers
sandbox/src/main/java/Lev05/task0519/Circle.java
1896
package Lev05.task0519; /* Создать класс (Circle) круг, с тремя конструкторами: - centerX, centerY, radius - centerX, centerY, radius, width - centerX, centerY, radius, width, color Требования: 1. У класса Circle должны быть переменные centerX, centerY, radius, width и color с типом int. 2. У класса должен быть конструктор, принимающий в качестве параметров centerX, centerY, radius и инициализирующий соответствующие переменные класса. 3. У класса должен быть конструктор, принимающий в качестве параметров centerX, centerY, radius, width и инициализирующий соответствующие переменные класса. 4. У класса должен быть конструктор, принимающий в качестве параметров centerX, centerY, radius, width, color и инициализирующий соответствующие переменные класса. */ public class Circle { int centerX, centerY, radius, width, color; public Circle(int centerX, int centerY, int radius) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; } public Circle(int centerX, int centerY, int radius, int width) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; this.width = width; } public Circle(int centerX, int centerY, int radius, int width, int color) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; this.width = width; this.color = color; } public static void main(String[] args) { } }
apache-2.0
Altiscale/tez
tez-runtime-library/src/test/java/org/apache/tez/runtime/library/common/shuffle/orderedgrouped/TestFetcher.java
13536
/** * 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.tez.runtime.library.common.shuffle.orderedgrouped; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyList; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.tez.common.counters.TezCounters; import org.apache.tez.common.security.JobTokenSecretManager; import org.apache.tez.dag.api.TezConfiguration; import org.apache.tez.runtime.api.InputContext; import org.apache.tez.runtime.library.api.TezRuntimeConfiguration; import org.apache.tez.runtime.library.common.InputAttemptIdentifier; import org.apache.tez.runtime.library.common.security.SecureShuffleUtils; import org.apache.tez.runtime.library.common.sort.impl.TezIndexRecord; import org.apache.tez.runtime.library.exceptions.FetcherReadTimeoutException; import org.apache.tez.runtime.library.common.shuffle.HttpConnection; import org.apache.tez.runtime.library.common.shuffle.ShuffleUtils; import org.junit.Assert; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class TestFetcher { public static final String SHUFFLE_INPUT_FILE_PREFIX = "shuffle_input_file_"; public static final String HOST = "localhost"; public static final int PORT = 0; static final Log LOG = LogFactory.getLog(TestFetcher.class); @Test(timeout = 5000) public void testSetupLocalDiskFetch() throws Exception { Configuration conf = new TezConfiguration(); ShuffleScheduler scheduler = mock(ShuffleScheduler.class); MergeManager merger = mock(MergeManager.class); ShuffleClientMetrics metrics = mock(ShuffleClientMetrics.class); Shuffle shuffle = mock(Shuffle.class); InputContext inputContext = mock(InputContext.class); when(inputContext.getCounters()).thenReturn(new TezCounters()); when(inputContext.getSourceVertexName()).thenReturn(""); FetcherOrderedGrouped fetcher = new FetcherOrderedGrouped(null, scheduler, merger, metrics, shuffle, null, false, 0, null, inputContext, conf, true, HOST); FetcherOrderedGrouped spyFetcher = spy(fetcher); MapHost host = new MapHost(1, HOST + ":" + PORT, "http://" + HOST + ":" + PORT + "/mapOutput?job=job_123&&reduce=1&map="); List<InputAttemptIdentifier> srcAttempts = Arrays.asList( new InputAttemptIdentifier(0, 1, InputAttemptIdentifier.PATH_PREFIX + "pathComponent_0"), new InputAttemptIdentifier(1, 2, InputAttemptIdentifier.PATH_PREFIX + "pathComponent_1"), new InputAttemptIdentifier(2, 3, InputAttemptIdentifier.PATH_PREFIX + "pathComponent_2"), new InputAttemptIdentifier(3, 4, InputAttemptIdentifier.PATH_PREFIX + "pathComponent_3"), new InputAttemptIdentifier(4, 4, InputAttemptIdentifier.PATH_PREFIX + "pathComponent_4") ); final int FIRST_FAILED_ATTEMPT_IDX = 2; final int SECOND_FAILED_ATTEMPT_IDX = 4; final int[] sucessfulAttemptsIndexes = { 0, 1, 3 }; doReturn(srcAttempts).when(scheduler).getMapsForHost(host); doAnswer(new Answer<MapOutput>() { @Override public MapOutput answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); MapOutput mapOutput = mock(MapOutput.class); doReturn(MapOutput.Type.DISK_DIRECT).when(mapOutput).getType(); doReturn(args[0]).when(mapOutput).getAttemptIdentifier(); return mapOutput; } }).when(spyFetcher) .getMapOutputForDirectDiskFetch(any(InputAttemptIdentifier.class), any(Path.class), any(TezIndexRecord.class)); doAnswer(new Answer<Path>() { @Override public Path answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return new Path(SHUFFLE_INPUT_FILE_PREFIX + args[0]); } }).when(spyFetcher).getShuffleInputFileName(anyString(), anyString()); doAnswer(new Answer<TezIndexRecord>() { @Override public TezIndexRecord answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); String pathComponent = (String) args[0]; int len = pathComponent.length(); long p = Long.valueOf(pathComponent.substring(len - 1, len)); if (p == FIRST_FAILED_ATTEMPT_IDX || p == SECOND_FAILED_ATTEMPT_IDX) { throw new IOException("failing to simulate failure case"); } // match with params for copySucceeded below. return new TezIndexRecord(p * 10, p * 1000, p * 100); } }).when(spyFetcher).getIndexRecord(anyString(), eq(host.getPartitionId())); doNothing().when(scheduler).copySucceeded(any(InputAttemptIdentifier.class), any(MapHost.class), anyLong(), anyLong(), anyLong(), any(MapOutput.class)); doNothing().when(scheduler).putBackKnownMapOutput(host, srcAttempts.get(FIRST_FAILED_ATTEMPT_IDX)); doNothing().when(scheduler).putBackKnownMapOutput(host, srcAttempts.get(SECOND_FAILED_ATTEMPT_IDX)); spyFetcher.setupLocalDiskFetch(host); // should have exactly 3 success and 1 failure. for (int i : sucessfulAttemptsIndexes) { verifyCopySucceeded(scheduler, host, srcAttempts, i); } verify(scheduler).copyFailed(srcAttempts.get(FIRST_FAILED_ATTEMPT_IDX), host, true, false); verify(scheduler).copyFailed(srcAttempts.get(SECOND_FAILED_ATTEMPT_IDX), host, true, false); verify(metrics, times(3)).successFetch(); verify(metrics, times(2)).failedFetch(); verify(spyFetcher).putBackRemainingMapOutputs(host); verify(scheduler).putBackKnownMapOutput(host, srcAttempts.get(FIRST_FAILED_ATTEMPT_IDX)); verify(scheduler).putBackKnownMapOutput(host, srcAttempts.get(SECOND_FAILED_ATTEMPT_IDX)); } private void verifyCopySucceeded(ShuffleScheduler scheduler, MapHost host, List<InputAttemptIdentifier> srcAttempts, long p) throws IOException { // need to verify filename, offsets, sizes wherever they are used. InputAttemptIdentifier srcAttemptToMatch = srcAttempts.get((int) p); String filenameToMatch = SHUFFLE_INPUT_FILE_PREFIX + srcAttemptToMatch.getPathComponent(); ArgumentCaptor<MapOutput> captureMapOutput = ArgumentCaptor.forClass(MapOutput.class); verify(scheduler).copySucceeded(eq(srcAttemptToMatch), eq(host), eq(p * 100), eq(p * 1000), anyLong(), captureMapOutput.capture()); // cannot use the equals of MapOutput as it compares id which is private. so doing it manually MapOutput m = captureMapOutput.getAllValues().get(0); Assert.assertTrue(m.getType().equals(MapOutput.Type.DISK_DIRECT) && m.getAttemptIdentifier().equals(srcAttemptToMatch)); } static class FakeHttpConnection extends HttpConnection { public FakeHttpConnection(URL url, HttpConnectionParams connParams, String logIdentifier, JobTokenSecretManager jobTokenSecretMgr) throws IOException { super(url, connParams, logIdentifier, jobTokenSecretMgr); this.connection = mock(HttpURLConnection.class); when(connection.getResponseCode()).thenReturn(200); when(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_NAME)) .thenReturn(ShuffleHeader.DEFAULT_HTTP_HEADER_NAME); when(connection.getHeaderField(ShuffleHeader.HTTP_HEADER_VERSION)) .thenReturn(ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION); when(connection.getHeaderField(SecureShuffleUtils.HTTP_HEADER_REPLY_URL_HASH)).thenReturn(""); } public DataInputStream getInputStream() throws IOException { byte[] b = new byte[1024]; ByteArrayInputStream bin = new ByteArrayInputStream(b); return new DataInputStream(bin); } public void validate() throws IOException { //empty } public void cleanup(boolean disconnect) throws IOException { LOG.info("HttpConnection cleanup called with disconnect=" + disconnect); //ignore } } @Test(timeout = 5000) public void testWithRetry() throws Exception { Configuration conf = new TezConfiguration(); conf.setInt(TezRuntimeConfiguration.TEZ_RUNTIME_SHUFFLE_READ_TIMEOUT, 3000); conf.setInt(TezRuntimeConfiguration.TEZ_RUNTIME_SHUFFLE_CONNECT_TIMEOUT, 3000); ShuffleScheduler scheduler = mock(ShuffleScheduler.class); MergeManager merger = mock(MergeManager.class); ShuffleClientMetrics metrics = mock(ShuffleClientMetrics.class); Shuffle shuffle = mock(Shuffle.class); InputContext inputContext = mock(InputContext.class); when(inputContext.getCounters()).thenReturn(new TezCounters()); when(inputContext.getSourceVertexName()).thenReturn(""); HttpConnection.HttpConnectionParams httpConnectionParams = ShuffleUtils.constructHttpShuffleConnectionParams(conf); FetcherOrderedGrouped mockFetcher = new FetcherOrderedGrouped(httpConnectionParams, scheduler, merger, metrics, shuffle, null, false, 0, null, inputContext, conf, false, HOST); final FetcherOrderedGrouped fetcher = spy(mockFetcher); final MapHost host = new MapHost(1, HOST + ":" + PORT, "http://" + HOST + ":" + PORT + "/mapOutput?job=job_123&&reduce=1&map="); final List<InputAttemptIdentifier> srcAttempts = Arrays.asList( new InputAttemptIdentifier(0, 1, InputAttemptIdentifier.PATH_PREFIX + "pathComponent_0"), new InputAttemptIdentifier(1, 2, InputAttemptIdentifier.PATH_PREFIX + "pathComponent_1"), new InputAttemptIdentifier(3, 4, InputAttemptIdentifier.PATH_PREFIX + "pathComponent_3") ); doReturn(srcAttempts).when(scheduler).getMapsForHost(host); doReturn(true).when(fetcher).setupConnection(host, srcAttempts); URL url = ShuffleUtils.constructInputURL(host.getBaseUrl(), srcAttempts, false); fetcher.httpConnection = new FakeHttpConnection(url, null, "", null); doAnswer(new Answer<MapOutput>() { @Override public MapOutput answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); MapOutput mapOutput = mock(MapOutput.class); doReturn(MapOutput.Type.MEMORY).when(mapOutput).getType(); doReturn(args[0]).when(mapOutput).getAttemptIdentifier(); return mapOutput; } }).when(merger).reserve(any(InputAttemptIdentifier.class), anyInt(), anyInt(), anyInt()); //Create read timeout when reading data doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { // Emulate host down for 4 seconds. Thread.sleep(4000); doReturn(false).when(fetcher).setupConnection(host, srcAttempts); // Throw IOException when fetcher tries to connect again to the same node throw new FetcherReadTimeoutException("creating fetcher socket read timeout exception"); } }).when(fetcher).copyMapOutput(any(MapHost.class), any(DataInputStream.class)); try { fetcher.copyFromHost(host); } catch(IOException e) { //ignore } //setup connection should be called twice (1 for connect and another for retry) verify(fetcher, times(2)).setupConnection(any(MapHost.class), anyList()); //since copyMapOutput consistently fails, it should call copyFailed once verify(scheduler, times(1)).copyFailed(any(InputAttemptIdentifier.class), any(MapHost.class), anyBoolean(), anyBoolean()); verify(fetcher, times(1)).putBackRemainingMapOutputs(any(MapHost.class)); verify(scheduler, times(3)).putBackKnownMapOutput(any(MapHost.class), any(InputAttemptIdentifier.class)); //Verify by stopping the fetcher abruptly try { fetcher.stopped = false; // flag to indicate fetcher stopped fetcher.copyFromHost(host); verify(fetcher, times(2)).putBackRemainingMapOutputs(any(MapHost.class)); } catch(IOException e) { //ignore } } }
apache-2.0
adamjshook/accumulo
server/tserver/src/test/java/org/apache/accumulo/tserver/AssignmentWatcherTest.java
2419
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.tserver; import java.util.HashMap; import java.util.Map; import org.apache.accumulo.core.conf.AccumuloConfiguration; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.data.impl.KeyExtent; import org.apache.accumulo.server.util.time.SimpleTimer; import org.apache.accumulo.tserver.TabletServerResourceManager.AssignmentWatcher; import org.apache.hadoop.io.Text; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; public class AssignmentWatcherTest { private Map<KeyExtent,RunnableStartedAt> assignments; private SimpleTimer timer; private AccumuloConfiguration conf; private AssignmentWatcher watcher; @Before public void setup() { assignments = new HashMap<>(); timer = EasyMock.createMock(SimpleTimer.class); conf = EasyMock.createMock(AccumuloConfiguration.class); watcher = new AssignmentWatcher(conf, assignments, timer); } @Test public void testAssignmentWarning() { ActiveAssignmentRunnable task = EasyMock.createMock(ActiveAssignmentRunnable.class); RunnableStartedAt run = new RunnableStartedAt(task, System.currentTimeMillis()); EasyMock.expect(conf.getTimeInMillis(Property.TSERV_ASSIGNMENT_DURATION_WARNING)).andReturn(0l); assignments.put(new KeyExtent(new Text("1"), null, null), run); EasyMock.expect(task.getException()).andReturn(new Exception("Assignment warning happened")); EasyMock.expect(timer.schedule(watcher, 5000l)).andReturn(null); EasyMock.replay(timer, conf, task); watcher.run(); EasyMock.verify(timer, conf, task); } }
apache-2.0
ecarm002/incubator-asterixdb
asterixdb/asterix-runtime/src/main/java/org/apache/asterix/runtime/evaluators/functions/temporal/DurationFromMonthsDescriptor.java
4620
/* * 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.asterix.runtime.evaluators.functions.temporal; import java.io.DataOutput; import org.apache.asterix.formats.nontagged.SerializerDeserializerProvider; import org.apache.asterix.om.base.ADuration; import org.apache.asterix.om.base.AMutableDuration; import org.apache.asterix.om.functions.BuiltinFunctions; import org.apache.asterix.om.functions.IFunctionDescriptor; import org.apache.asterix.om.functions.IFunctionDescriptorFactory; import org.apache.asterix.om.types.BuiltinType; import org.apache.asterix.om.types.hierachy.ATypeHierarchy; import org.apache.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor; import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluator; import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory; import org.apache.hyracks.api.context.IHyracksTaskContext; import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.data.std.api.IPointable; import org.apache.hyracks.data.std.primitive.VoidPointable; import org.apache.hyracks.data.std.util.ArrayBackedValueStorage; import org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference; public class DurationFromMonthsDescriptor extends AbstractScalarFunctionDynamicDescriptor { private final static long serialVersionUID = 1L; public final static FunctionIdentifier FID = BuiltinFunctions.DURATION_FROM_MONTHS; public final static IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() { @Override public IFunctionDescriptor createFunctionDescriptor() { return new DurationFromMonthsDescriptor(); } }; @Override public IScalarEvaluatorFactory createEvaluatorFactory(final IScalarEvaluatorFactory[] args) { return new IScalarEvaluatorFactory() { private static final long serialVersionUID = 1L; @Override public IScalarEvaluator createScalarEvaluator(final IHyracksTaskContext ctx) throws HyracksDataException { return new IScalarEvaluator() { private ArrayBackedValueStorage resultStorage = new ArrayBackedValueStorage(); private DataOutput out = resultStorage.getDataOutput(); private IPointable argPtr0 = new VoidPointable(); private IScalarEvaluator eval0 = args[0].createScalarEvaluator(ctx); @SuppressWarnings("unchecked") private ISerializerDeserializer<ADuration> durationSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ADURATION); AMutableDuration aDuration = new AMutableDuration(0, 0); @Override public void evaluate(IFrameTupleReference tuple, IPointable result) throws HyracksDataException { resultStorage.reset(); eval0.evaluate(tuple, argPtr0); byte[] bytes = argPtr0.getByteArray(); int offset = argPtr0.getStartOffset(); aDuration.setValue(ATypeHierarchy.getIntegerValue(getIdentifier().getName(), 0, bytes, offset), 0); durationSerde.serialize(aDuration, out); result.set(resultStorage); } }; } }; } /* (non-Javadoc) * @see org.apache.asterix.om.functions.AbstractFunctionDescriptor#getIdentifier() */ @Override public FunctionIdentifier getIdentifier() { return FID; } }
apache-2.0
jerome-tan-git/led
ledweb/src/ledweb/action/AboutUsAction.java
2476
package ledweb.action; import java.util.List; import ledweb.ModelSessionFactory; import ledweb.Util; import ledweb.model.AboutUs; import ledweb.model.Category; import ledweb.model.mapper.IAboutUsOperation; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import com.opensymphony.xwork2.ActionSupport; public class AboutUsAction extends ActionSupport { private static Logger logger = Logger.getLogger(ContactUsAction.class); private AboutUs aboutUs; private String article; private String isSubmit; private List<Category> allCategories; private String module = "about us"; public String getModule() { return module; } public void setModule(String module) { this.module = module; } public List<Category> getAllCategories() { return allCategories; } public void setAllCategories(List<Category> allCategories) { this.allCategories = allCategories; } public AboutUs getAboutUs() { return aboutUs; } public void setAboutUs(AboutUs aboutUs) { this.aboutUs = aboutUs; } public String getArticle() { return article; } public void setArticle(String article) { this.article = article; } public String getIsSubmit() { return isSubmit; } public void setIsSubmit(String isSubmit) { this.isSubmit = isSubmit; } private void showAboutUsContent() { SqlSession session = null; try { session = ModelSessionFactory.getSession().openSession(); IAboutUsOperation co = session.getMapper(IAboutUsOperation.class); this.setAboutUs(co.selectAboutUs()); logger.warn("Get aboutUs versionID: " + aboutUs.getVersionID()); logger.warn("Get aboutUs article: " + aboutUs.getArticle()); } catch (Exception e) { logger.error(e.getMessage()); } finally { if (session!=null) { session.close(); } } } private void updateAboutUsInfo(){ SqlSession session = null; try { session = ModelSessionFactory.getSession().openSession(); IAboutUsOperation ao = session.getMapper(IAboutUsOperation.class); AboutUs aon = new AboutUs(); aon.setArticle(this.article); ao.updateAboutUs(aon); session.commit(); } catch (Exception e) { logger.error(e.getMessage()); } finally { if (session !=null) { session.close(); } } } @Override public String execute() { this.allCategories = Util.getAllCategories(); if ("submit".equals(this.getIsSubmit())) { this.updateAboutUsInfo(); } this.showAboutUsContent(); return SUCCESS; } }
apache-2.0
albertocsm/presto
presto-tests/src/test/java/com/facebook/presto/tests/TestLocalBinarySpilledQueries.java
2581
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.tests; import com.facebook.presto.Session; import com.facebook.presto.SystemSessionProperties; import com.facebook.presto.connector.ConnectorId; import com.facebook.presto.metadata.SessionPropertyManager; import com.facebook.presto.testing.LocalQueryRunner; import com.facebook.presto.tpch.TpchConnectorFactory; import com.google.common.collect.ImmutableMap; import static com.facebook.presto.testing.TestingSession.TESTING_CATALOG; import static com.facebook.presto.testing.TestingSession.testSessionBuilder; import static com.facebook.presto.tpch.TpchMetadata.TINY_SCHEMA_NAME; public class TestLocalBinarySpilledQueries extends AbstractTestQueries { public TestLocalBinarySpilledQueries() { super(createLocalQueryRunner()); } private static LocalQueryRunner createLocalQueryRunner() { Session defaultSession = testSessionBuilder() .setCatalog("local") .setSchema(TINY_SCHEMA_NAME) .setSystemProperty(SystemSessionProperties.SPILL_ENABLED, "true") .setSystemProperty(SystemSessionProperties.OPERATOR_MEMORY_LIMIT_BEFORE_SPILL, "1B") //spill constantly .build(); LocalQueryRunner localQueryRunner = new LocalQueryRunner(defaultSession); // add the tpch catalog // local queries run directly against the generator localQueryRunner.createCatalog( defaultSession.getCatalog().get(), new TpchConnectorFactory(1), ImmutableMap.<String, String>of()); localQueryRunner.getMetadata().addFunctions(CUSTOM_FUNCTIONS); SessionPropertyManager sessionPropertyManager = localQueryRunner.getMetadata().getSessionPropertyManager(); sessionPropertyManager.addSystemSessionProperties(TEST_SYSTEM_PROPERTIES); sessionPropertyManager.addConnectorSessionProperties(new ConnectorId(TESTING_CATALOG), TEST_CATALOG_PROPERTIES); return localQueryRunner; } }
apache-2.0
gentics/mesh
rest-model/src/main/java/com/gentics/mesh/core/rest/event/AbstractMeshEventModel.java
1312
package com.gentics.mesh.core.rest.event; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.gentics.mesh.core.rest.MeshEvent; /** * Abstract event model implementation which contains information about the {@link #cause} of the event and where the event originates (cluster node name via * {@link #origin}) */ public abstract class AbstractMeshEventModel implements MeshEventModel { @JsonProperty(required = true) @JsonPropertyDescription("Name of the mesh node from which the event originates.") private String origin; @JsonProperty(required = true) @JsonPropertyDescription("Some events will be caused by another action. This object contains information about the cause of the event.") private EventCauseInfo cause; @JsonIgnore private MeshEvent event; @Override public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } @Override public MeshEvent getEvent() { return event; } public void setEvent(MeshEvent event) { this.event = event; } @Override public EventCauseInfo getCause() { return cause; } @Override public void setCause(EventCauseInfo cause) { this.cause = cause; } }
apache-2.0
samini/gort-public
Source/GortGUIv2/Gort/api/src/org/cmuchimps/gort/api/gort/TraversalProviderServiceFactory.java
1028
/* Copyright 2014 Shahriyar Amini 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.cmuchimps.gort.api.gort; import org.netbeans.api.project.Project; import org.openide.util.Lookup; /** * * @author shahriyar */ public abstract class TraversalProviderServiceFactory { public static TraversalProviderServiceFactory getDefault() { return Lookup.getDefault().lookup(TraversalProviderServiceFactory.class); } public abstract TraversalProviderService getInstance(Project project); }
apache-2.0