repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
lang010/acit | uva/10018/Main.java | 1376 | /*
* Copyright (c) 2014 Liang Li <ll@lianglee.org>. All rights reserved.
*
* This program is a free software and released under the BSD license.
* https://github.com/lang010/acit
*
* Solutions for UVa Problem 10018
* UVa link: http://uva.onlinejudge.org/external/100/10018.html
*
* @Authur Liang Li <ll@lianglee.org>
* @Date Nov 18 19:33:14 2014
*/
import java.util.Scanner;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Main {
Scanner sc = new Scanner(System.in, "ISO-8859-1");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out, "ISO-8859-1"));
public Main() throws Exception {
}
public static void main(String[] args) throws Exception {
Main m = new Main();
m.run();
m.release();
}
void release() {
sc.close();
pw.close();
}
long reverse(long p) {
long y = 0;
while (p>0) {
y = y*10 + p%10;
p /= 10;
}
return y;
}
void run() {
int cnt = 0;
int n = sc.nextInt();
long x, y;
for (int k = 0; k < n; k++) {
cnt = 0;
x = sc.nextLong();
y = reverse(x);
while (x != y) {
x += y;
y = reverse(x);
cnt++;
}
pw.printf("%d %d%n", cnt, x);
}
}
}
| bsd-3-clause |
jeanlazarou/store | src/com/ap/io/text/LineIterator.java | 1051 | package com.ap.io.text;
import com.ap.io.FilePosition;
public interface LineIterator {
void beforeFirst();
void afterLast();
String next();
String previous();
/**
* Returns an object that represents the last retrieved element, by using
* {@link next} or {@link previous}.
* <p>
* Returns null if no last position exists.
*
* @return last retrieved element or null if none was retrieved
*/
FilePosition lastPosition();
/**
* Sets the iterator position so that next call to <tt>next</tt> returns the
* line identified by the given position object
*
* @param position the line position to go to
*/
void setNext(FilePosition position);
/**
* Sets the iterator position so that next call to <tt>previous</tt> returns the
* line identified by the given position object
*
* @param position the line position to go to
*/
void setPrevious(FilePosition position);
/**
* Closes the iteratror so that resources can be disposed
*
*/
void close();
}
| bsd-3-clause |
Small-Bodies-Node/ntl_archive_db_demo | import_and_persistence/src/java/main/gov/nasa/pds/processors/impl/Helper.java | 22957 | /*
* Copyright (C) 2012-2013 TopCoder Inc., All Rights Reserved.
*/
package gov.nasa.pds.processors.impl;
import gov.nasa.pds.entities.Column;
import gov.nasa.pds.entities.MetadataObject;
import gov.nasa.pds.entities.Product;
import gov.nasa.pds.entities.Property;
import gov.nasa.pds.entities.Table;
import gov.nasa.pds.services.DataSetProcessingException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.topcoder.commons.utils.LoggingWrapperUtility;
import com.topcoder.util.log.Level;
import com.topcoder.util.log.Log;
/**
* <p>
* The {@code Helper} class provides utility methods for classes from gov.nasa.pds.processors.impl package.
* </p>
*
* <p>
* <strong>Thread Safety:</strong> This class is thread safe since it has no state.
* </p>
*
* <p>
* Version 1.1 changes [PDS - Import and Persistence Update - Assembly Contest]:
* <ol>
* <li>Added {@link #getRowItemsCount(Table)} method.</li>
* <li>Added {@link #readFileLines(InputStream)} method.</li>
* <li>Moved {@link #parseTableRow(String, int)} method from DataSetTemplate class.</li>
* </ol>
* </p>
*
* @author KennyAlive
* @version 1.1
*/
public final class Helper {
/**
* Do not allow to instantiate this class.
*/
private Helper() {
}
/**
* Gets all files from the given directory and all its sub-directories.
*
* @param directory
* the directory to scan for files and sub-directories
* @param result
* the resulted list with the found files
*/
public static void listFiles(File directory, List<File> result) {
File[] directoryFiles = directory.listFiles();
List<File> subDirectories = new ArrayList<File>();
// at first get the files from the current directory
for (File file : directoryFiles) {
if (file.isFile()) {
result.add(file);
} else {
subDirectories.add(file);
}
}
// add files from sub-directories only after the files from the current directory
// were added in order to not intermix files from different directories
for (File subDirectory : subDirectories) {
listFiles(subDirectory, result);
}
}
/**
* Gets the name of the given file or directory without extension.
*
* @param fileName
* represents file path or directory path or just file name or directory name
*
* @return name of the file or directory without extension
*/
public static String getNameWithoutExtension(String fileName) {
String name = (new File(fileName)).getName();
int dotIndex = name.lastIndexOf('.');
if (dotIndex != -1) {
name = name.substring(0, dotIndex);
}
return name;
}
/**
* Reads file in text mode line-by-line.
*
* @param stream
* the input stream
*
* @return the list of lines that is the file content
*
* @throws IOException
* if failed to read file content
*
* @since 1.1
*/
public static List<String> readFileLines(InputStream stream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
List<String> lines = new ArrayList<String>();
try {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
return lines;
}
/**
* Does heuristic check if the given file is a text file.
*
* @param file
* the file to check
*
* @return true if the given file is probably a text file, otherwise false
*/
public static boolean isProbablyTextFile(File file) {
try {
if (!file.exists())
return false;
FileInputStream in = new FileInputStream(file);
int size = in.available();
if (size > 1000)
size = 1000;
byte[] data = new byte[size];
in.read(data);
in.close();
String s = new String(data, "ISO-8859-1");
String s2 = s.replaceAll(
"[a-zA-Z0-9\\.\\*!\"\\$\\%&/()=\\?@~'#:,;\\+><\\|\\[\\]\\{\\}\\^\\\\ \\n\\r\\t_\\-]", "");
// will delete all text signs
double d = (double) (s.length() - s2.length()) / (double) (s.length());
// percentage of text signs in the text
return d > 0.95;
} catch (IOException e) {
return false;
}
}
/**
* Gets timing string for the time period between the two given dates.
*
* @param startDate
* the start date
* @param endDate
* the end date
*
* @return the string with timing info between the two given dates
*/
public static String getTimingString(Date startDate, Date endDate) {
long seconds = (new Date().getTime() - startDate.getTime()) / 1000;
long hours = seconds / 3600;
seconds = seconds % 3600;
long minutes = seconds / 60;
seconds = seconds % 60;
String timeStr;
if (hours > 0) {
timeStr = String.format("%d hours, %d minute(s), %d seconds", hours, minutes, seconds);
} else if (minutes > 0) {
timeStr = String.format("%d minute(s), %d seconds", minutes, seconds);
} else {
timeStr = String.format("%d seconds", seconds);
}
return timeStr;
}
/**
* Gets the data offset in bytes defined by the given pointer property or -1 if the property does not define the
* offset.
*
* @param pointerProperty
* the pointer property
* @param recordSizeInBytes
* the record size in bytes (it's used only when offset value does not have <BYTES> suffix)
* @param logger
* the logger
*
* @return the data offset or -1 if it is not defined
*/
public static int getDataOffset(Property pointerProperty, int recordSizeInBytes, Log logger)
throws DataSetProcessingException {
String signature = "Helper.getDataOffset(Property pointerProperty, int recordSizeInBytes, Log logger)";
String pointerValue = pointerProperty.getValues().get(0).toLowerCase();
int dataOffset = computeOffsetInBytes(pointerValue, recordSizeInBytes);
if (dataOffset == -1) { // if label is detached
if (pointerProperty.getValues().size() > 1) { // check if offset is specified after the filename
String pointerValue2 = pointerProperty.getValues().get(1);
dataOffset = computeOffsetInBytes(pointerValue2, recordSizeInBytes);
if (dataOffset == -1) {
throw LoggingWrapperUtility.logException(logger, signature,
new DataSetProcessingException("Invalid offset format: " + pointerValue2));
}
}
}
return dataOffset;
}
/**
* Checks if the data defined by the given pointer property is attached to the label file.
*
* @param pointerProperty
* the pointer property
* @param recordSizeInBytes
* the record size in bytes (it's used only when offset value does not have <BYTES> suffix)
*
* @return true if the data is attached to the label file, otherwise false
*/
public static boolean isDataAttached(Property pointerProperty, int recordSizeInBytes) {
String pointerValue = pointerProperty.getValues().get(0).toLowerCase();
int offset = Helper.computeOffsetInBytes(pointerValue, recordSizeInBytes);
return offset > -1;
}
/**
* Computes offset in bytes for the given offset value.
*
* @param offsetValue
* the offset value as specified in the label file
* @param recordSizeInBytes
* the record size in bytes (it's used only when offset value does not have <BYTES> suffix)
*
* @return the offset in bytes or -1 if fails to parse offset value
*/
public static int computeOffsetInBytes(String offsetValue, int recordSizeInBytes) {
final String BYTES_SUFFIX = "<BYTES>";
boolean isBytesOffset = false;
if (offsetValue.toUpperCase().endsWith(BYTES_SUFFIX)) {
int endPos = offsetValue.length() - BYTES_SUFFIX.length();
offsetValue = offsetValue.substring(0, endPos).trim();
isBytesOffset = true;
}
int offset = 0;
try {
offset = Integer.valueOf(offsetValue);
if (!isBytesOffset) {
offset = (offset - 1) * recordSizeInBytes;
} else {
offset = offset - 1;
}
} catch (NumberFormatException e) {
offset = -1;
}
return offset;
}
/**
* Checks if the property with a given name is a pointer.
*
* @param propertyName
* the property name
*
* @return true if the property is a pointer, otherwise false
*/
public static boolean isPointer(String propertyName) {
return propertyName.startsWith("^");
}
/**
* Gets a short name of the pointer represented by a property with a given name.
*
* @param propertyName
* the property name
*
* @return the pointer short name or null if the property does not represent a pointer
*/
public static String getPointerShortName(String propertyName) {
if (!isPointer(propertyName)) {
return null;
}
int underscoreIndex = propertyName.lastIndexOf('_');
if (underscoreIndex != -1) {
propertyName = propertyName.substring(underscoreIndex + 1);
} else {
propertyName = propertyName.substring(1); // skip leading ^ symbol
}
return propertyName;
}
/**
* Check if the given property represents a pointer to the data table.
*
* @param propertyName
* the property name
*
* @return true if the property represents a pointer to the data table, otherwise false
*/
public static boolean isTablePointer(String propertyName) {
String shortName = getPointerShortName(propertyName);
return shortName != null && (shortName.equals("TABLE") || shortName.equals("SERIES"));
}
/**
* Retrieves all children of the metadata object with a given name.
*
* @param object
* the metadata object to retrieve children from
* @param childObjectName
* the name of the child objects we are looking for
*
* @return the children objects with a given name, the empty list is returned if none is found
*/
public static List<MetadataObject> getChildrenByName(MetadataObject object, String childObjectName) {
List<MetadataObject> childObjects = new ArrayList<MetadataObject>();
for (MetadataObject child : object.getChildren()) {
if (child.getName().equals(childObjectName)) {
childObjects.add(child);
}
}
return childObjects;
}
/**
* Retrieves the first child metadata object with a given name.
*
* @param object
* the metadata object to retrieve child from
* @param childObjectName
* the name of the child object we are looking for
* @param logger
* the logger instance
*
* @return the first child metadata object with a given name
*
* @throws DataSetProcessingException
* if the child object is not found
*/
public static MetadataObject getRequiredChildObject(MetadataObject object, String childObjectName, Log logger)
throws DataSetProcessingException {
final String signature = "Helper.getRequiredChildObject(String childObjectName, Log logger)";
List<MetadataObject> children = getChildrenByName(object, childObjectName);
if (children.isEmpty()) {
String message = String.format("Failed to find a child object (%s) in parent (%s) object",
childObjectName, object.getName());
throw LoggingWrapperUtility.logException(logger, signature, new DataSetProcessingException(message));
}
return children.get(0);
}
/**
* Gets the object from product by its name. The full object name is used for comparison.
*
* @param product
* the product that holds the object of interest
* @param objectName
* the object name we are looking for
*
* @return found object or null if none found
*/
public static MetadataObject getObjectFromProduct(Product product, String objectName) {
for (MetadataObject object : product.getOtherChildren()) {
if (object.getFullName().equals(objectName)) {
return object;
}
}
return null;
}
/**
* Returns the extension of the given file without leading dot symbol.
*
* @param fileName
* the file name (can also be file path) to extract extension from
*
* @return the extension of the given file or an empty string if the file has no extension
*/
public static String getFileExtension(String fileName) {
fileName = new File(fileName).getName();
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex == -1) {
return "";
}
return fileName.substring(dotIndex + 1);
}
/**
* Gets column name that is defined by the PDS table and converts it to the name that is a valid SQL column name.
*
* @param identifier
* the identifier that should be converted to SQL-compliant identifier
*
* @return the corrected column name
*/
public static String getSqlIdentifier(String identifier) {
identifier = identifier.replace(' ', '_');
identifier = identifier.replace('-', '_');
identifier = identifier.replace('(', '_');
identifier = identifier.replace(')', '_');
identifier = identifier.replace('.', '_');
return identifier;
}
/**
* Get the list of unique names by appending indices to non-unique names.
*
* @param names
* the original list of names
*
* @return the processed list of unique names
*/
public static List<String> getUniqueNames(List<String> names) {
Map<String, Integer> map = new HashMap<String, Integer>();
List<String> result = new ArrayList<String>();
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
Integer index = map.get(name);
if (index != null) {
index++;
while (names.contains(name + index)) {
index++;
}
map.put(name, index);
name = name + index;
} else {
map.put(name, 1);
}
result.add(name);
}
return result;
}
/**
* Computes the number of items per row for the given table.
*
* @param table
* the table instance
*
* @return the number of items per row
*
* @since 1.1
*/
public static int getRowItemsCount(Table table) {
int items = 0;
for (Column column : table.getColumns()) {
items += (column.getItems() == null) ? 1 : column.getItems();
}
return items;
}
/**
* Selects the datasets for processing.
*
* @param dataSetSelector
* the dataset selector instance
* @param startDataSet
* the dataset to start processing from
* @param endDataSet
* the last dataset for processing
* @param logger
* the logger instance for logging (can be null)
*
* @return the list of selected datasets (not null, can be empty)
*/
public static List<DataSetInfo> selectDataSets(DataSetSelector dataSetSelector, String startDataSet,
String endDataSet, Log logger) {
Date startDate = new Date();
// 1. Get configured list of datasets from DataSetSelector instance.
List<DataSetInfo> selectedDataSets = dataSetSelector.selectDataSetsForProcessing();
int start = 0;
int end = selectedDataSets.size() - 1;
// 2. Take into account startDataSet/endDataSet properties.
if (startDataSet != null || endDataSet != null) {
boolean startFound = false;
boolean endFound = false;
// locate start/end datasets
for (int i = 0; i < selectedDataSets.size(); i++) {
String directoryName = selectedDataSets.get(i).getDirectoryName();
if (startDataSet != null && directoryName.equals(startDataSet)) {
start = i;
startFound = true;
}
if (endDataSet != null && directoryName.equals(endDataSet)) {
end = i;
endFound = true;
}
}
// validate start/end datasets
if (startDataSet != null) {
if (!startFound) {
if (logger != null) {
logger.log(Level.ERROR, "startDataSet {0} not found", startDataSet);
}
return null;
}
if (logger != null) {
logger.log(Level.INFO, "startDataSet = {0} ({1})", startDataSet, start + 1);
}
}
if (endDataSet != null) {
if (!endFound) {
if (logger != null) {
logger.log(Level.ERROR, "endDataSet {0} not found", endDataSet);
}
return null;
}
if (logger != null) {
logger.log(Level.INFO, "endDataSet = {0} ({1})", endDataSet, end + 1);
}
}
if (start > end) {
if (logger != null) {
logger.log(Level.ERROR, "Invalid startDataSet or/and endDataSet. "
+ "Check that startDataSet goes before or equals to endDataSet.");
}
return null;
}
}
// 3. Log summary
if (logger != null) {
logger.log(Level.INFO, "Selected {0} dataset(s) for processing (in {1})",
end - start + 1, Helper.getTimingString(startDate, new Date()));
StringBuilder sb = new StringBuilder();
for (int i = start; i <= end; i++) {
sb.append("\n " + (i + 1) + ") ");
sb.append(selectedDataSets.get(i).getDirectoryName());
}
logger.log(Level.INFO, "Selected datasets: {0}", sb.toString());
logger.log(Level.INFO, "----------------------------------------");
}
return selectedDataSets.subList(start, end + 1);
}
/**
* Parses a single row of values. Used to parse index.tab file, Cassini inventory table, etc.
*
* @param row
* the row to parse
* @param rowNumber
* the row number, used for logging
*
* @return the list of parsed column values
*
* @throws DataSetProcessingException
* if failed to parse the given row
*
* @since 1.1
*/
public static List<String> parseTableRow(String row, int rowNumber) throws DataSetProcessingException {
List<String> values = new ArrayList<String>();
int i = 0;
while (true) {
// skip column separators
while (i < row.length() && row.charAt(i) <= 32) {
i++;
}
if (i != 0 && i < row.length() && row.charAt(i) == ',') {
i++;
while (i < row.length() && row.charAt(i) <= 32) {
i++;
}
}
if (i == row.length()) {
break;
}
// check if the next value is a quoted string
boolean quote = false;
boolean doubleQuote = false; // fix for the values like this: ""N/A""
if (row.charAt(i) == '"') {
quote = true;
if (i < row.length() - 1 && row.charAt(i + 1) == '"') {
doubleQuote = true;
i++;
}
} else if (row.charAt(i) == ',') {
throw new DataSetProcessingException("Malformed line: superfluous comma at position " + i + ", row "
+ rowNumber);
}
// mark start position of the next column value
int beginIndex = i;
// search for the end of the column value
i++;
String value = null;
if (quote) {
while (i < row.length() && row.charAt(i) != '"') {
i++;
}
boolean missedDoubleQuote = doubleQuote && i < row.length() - 1 && row.charAt(i + 1) != '"';
if (i == row.length() || missedDoubleQuote) {
throw new DataSetProcessingException(
"Malformed line: missing closed quote for opening quote at position " + beginIndex
+ ", row " + rowNumber);
}
value = row.substring(beginIndex + 1, i).trim();
if (doubleQuote) {
i++;
}
i++;
if (i < row.length() && !(row.charAt(i) <= 32 || row.charAt(i) == ',')) {
throw new DataSetProcessingException(
"Malformed line: unexpected symbol after ending quote at position " + i + ", row "
+ rowNumber);
}
} else {
while (i < row.length() && (row.charAt(i) > 32 && row.charAt(i) != ',')) {
i++;
}
value = row.substring(beginIndex, i);
}
// add the column value to result list
values.add(value);
}
return values;
}
}
| bsd-3-clause |
synergynet/synergynet3 | synergynet3-parent/synergynet3-appsystem-core/src/main/java/synergynet3/additionalitems/interfaces/IRadialMenu.java | 607 | package synergynet3.additionalitems.interfaces;
import java.util.logging.Logger;
import synergynet3.additionalitems.RadialMenuOption;
import com.jme3.math.ColorRGBA;
import multiplicity3.csys.items.item.IItem;
import multiplicity3.csys.stage.IStage;
public interface IRadialMenu extends IItem {
public void setRootItem(IItem studentIcon, IStage stage, Logger log, ColorRGBA studentColour);
public void setRadius(int i);
public void toggleOptionVisibility();
public void setOptionVisibility(boolean b);
public void removeOption(int optionIndex);
public int addOption(RadialMenuOption option);
}
| bsd-3-clause |
FIRSTTeam102/2012-bball-robot | src/edu/wpi/first/wpilibj/templates/commands/SetSetPointWithTrigger.java | 964 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
/**
*
* @author Administrator
*/
public class SetSetPointWithTrigger extends CommandBase {
public SetSetPointWithTrigger() {
requires(cannon);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
cannon.setSetPointWithTrigger(oi.getXBox());
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
} | bsd-3-clause |
NCIP/cab2b | software/dependencies/dynamicextensions/caB2B_2009_JUN_02/src/edu/common/dynamicextensions/domain/ObjectAttributeTypeInformation.java | 1051 | /*L
* Copyright Georgetown University, Washington University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cab2b/LICENSE.txt for details.
*/
package edu.common.dynamicextensions.domain;
import edu.common.dynamicextensions.domaininterface.ObjectTypeInformationInterface;
import edu.common.dynamicextensions.entitymanager.EntityManagerConstantsInterface;
/**
* @hibernate.joined-subclass table="DYEXTN_OBJECT_TYPE_INFO"
* @hibernate.joined-subclass-key column="IDENTIFIER"
* @author Rahul Ner
*
*/
public class ObjectAttributeTypeInformation extends AttributeTypeInformation implements
ObjectTypeInformationInterface {
/**
* Empty Constructor.
*/
public ObjectAttributeTypeInformation() {
}
/**
* @see edu.common.dynamicextensions.domaininterface.AttributeTypeInformationInterface#getDataType()
*/
public String getDataType() {
return EntityManagerConstantsInterface.OBJECT_ATTRIBUTE_TYPE;
}
}
| bsd-3-clause |
FRCTeam1073-TheForceTeam/EncoderTest | src/org/usfirst/frc1073/EncoderTest/OI.java | 3484 | // RobotBuilder Version: 1.5
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc1073.EncoderTest;
import org.usfirst.frc1073.EncoderTest.commands.*;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* This class is the glue that binds the controls on the physical operator
* interface to the commands and command groups that allow control of the robot.
*/
public class OI {
//// CREATING BUTTONS
// One type of button is a joystick button which is any button on a joystick.
// You create one by telling it which joystick it's on and which button
// number it is.
// Joystick stick = new Joystick(port);
// Button button = new JoystickButton(stick, buttonNumber);
// There are a few additional built in buttons you can use. Additionally,
// by subclassing Button you can create custom triggers and bind those to
// commands the same as any other Button.
//// TRIGGERING COMMANDS WITH BUTTONS
// Once you have a button, it's trivial to bind it to a button in one of
// three ways:
// Start the command when the button is pressed and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenPressed(new ExampleCommand());
// Run the command while the button is being held down and interrupt it once
// the button is released.
// button.whileHeld(new ExampleCommand());
// Start the command when the button is released and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenReleased(new ExampleCommand());
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public Joystick driver;
public Joystick rotator;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public OI() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
rotator = new Joystick(1);
driver = new Joystick(0);
// SmartDashboard Buttons
SmartDashboard.putData("Autonomous Command", new AutonomousCommand());
SmartDashboard.putData("PrintEncoderValues", new PrintEncoderValues());
SmartDashboard.putData("Drive", new Drive());
SmartDashboard.putData("Stop", new Stop());
SmartDashboard.putData("IncreaseSpeed", new IncreaseSpeed());
SmartDashboard.putData("DecreaseSpeed", new DecreaseSpeed());
SmartDashboard.putData("ResetSpeedToZero", new ResetSpeedToZero());
SmartDashboard.putData("DriveTo360", new DriveTo360());
SmartDashboard.putData("DriveForward", new DriveForward());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
}
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
public Joystick getdriver() {
return driver;
}
public Joystick getrotator() {
return rotator;
}
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
}
| bsd-3-clause |
valfirst/jbehave-core | jbehave-core/src/test/java/org/jbehave/core/embedder/PerformableTreeConversionBehaviour.java | 7825 | package org.jbehave.core.embedder;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.lang.reflect.Type;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jbehave.core.annotations.Scope;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.Keywords;
import org.jbehave.core.failures.BatchFailures;
import org.jbehave.core.model.ExamplesTable;
import org.jbehave.core.model.GivenStories;
import org.jbehave.core.model.Lifecycle;
import org.jbehave.core.model.Meta;
import org.jbehave.core.model.Narrative;
import org.jbehave.core.model.Scenario;
import org.jbehave.core.model.Story;
import org.jbehave.core.steps.ParameterControls;
import org.jbehave.core.steps.ParameterConverters;
import org.jbehave.core.steps.Step;
import org.jbehave.core.steps.StepCollector;
import org.jbehave.core.steps.StepCollector.Stage;
import org.jbehave.core.steps.StepMonitor;
import org.junit.jupiter.api.Test;
class PerformableTreeConversionBehaviour {
@Test
void shouldConvertParameters() {
SharpParameterConverters sharpParameterConverters = new SharpParameterConverters();
ParameterControls parameterControls = new ParameterControls();
PerformableTree performableTree = new PerformableTree();
Configuration configuration = mock(Configuration.class);
when(configuration.storyControls()).thenReturn(new StoryControls());
AllStepCandidates allStepCandidates = mock(AllStepCandidates.class);
EmbedderMonitor embedderMonitor = mock(EmbedderMonitor.class);
BatchFailures failures = mock(BatchFailures.class);
PerformableTree.RunContext context = spy(performableTree.newRunContext(configuration, allStepCandidates,
embedderMonitor, new MetaFilter(), failures));
StoryControls storyControls = mock(StoryControls.class);
when(configuration.storyControls()).thenReturn(storyControls);
when(storyControls.skipBeforeAndAfterScenarioStepsIfGivenStory()).thenReturn(false);
when(configuration.parameterConverters()).thenReturn(sharpParameterConverters);
when(configuration.parameterControls()).thenReturn(parameterControls);
GivenStories givenStories = new GivenStories("");
Map<String,String> scenarioExample = new HashMap<>();
scenarioExample.put("var1","#E");
scenarioExample.put("var3","<var2>#F");
Map<String,String> scenarioExampleSecond = new HashMap<>();
scenarioExampleSecond.put("var1","#G<var2>");
scenarioExampleSecond.put("var3","#H");
ExamplesTable scenarioExamplesTable = ExamplesTable.empty().withRows(
asList(scenarioExample, scenarioExampleSecond));
String scenarioTitle = "scenario title";
Scenario scenario = new Scenario(scenarioTitle, new Meta(), givenStories, scenarioExamplesTable, emptyList());
Narrative narrative = mock(Narrative.class);
Lifecycle lifecycle = mock(Lifecycle.class);
Story story = new Story(null, null, new Meta(), narrative, givenStories, lifecycle,
singletonList(scenario));
ExamplesTable storyExamplesTable = mock(ExamplesTable.class);
when(lifecycle.getExamplesTable()).thenReturn(storyExamplesTable);
Map<String,String> storyExampleFirstRow = new HashMap<>();
storyExampleFirstRow.put("var1","#A");
storyExampleFirstRow.put("var2","#B");
Map<String,String> storyExampleSecondRow = new HashMap<>();
storyExampleSecondRow.put("var1","#C");
storyExampleSecondRow.put("var2","#D");
when(storyExamplesTable.getRows()).thenReturn(asList(storyExampleFirstRow, storyExampleSecondRow));
Keywords keywords = mock(Keywords.class);
when(configuration.keywords()).thenReturn(keywords);
StepMonitor stepMonitor = mock(StepMonitor.class);
when(configuration.stepMonitor()).thenReturn(stepMonitor);
StepCollector stepCollector = mock(StepCollector.class);
when(configuration.stepCollector()).thenReturn(stepCollector);
Map<Stage, List<Step>> lifecycleSteps = new EnumMap<>(Stage.class);
lifecycleSteps.put(Stage.BEFORE, emptyList());
lifecycleSteps.put(Stage.AFTER, emptyList());
when(stepCollector.collectLifecycleSteps(eq(emptyList()), eq(lifecycle), isEmptyMeta(), eq(Scope.STORY),
any(MatchingStepMonitor.class))).thenReturn(lifecycleSteps);
when(stepCollector.collectLifecycleSteps(eq(emptyList()), eq(lifecycle), isEmptyMeta(), eq(Scope.SCENARIO),
any(MatchingStepMonitor.class))).thenReturn(lifecycleSteps);
performableTree.addStories(context, singletonList(story));
List<PerformableTree.PerformableScenario> performableScenarios = performableTree.getRoot().getStories().get(0)
.getScenarios();
assertThatAreEqual(scenarioExample.size(), performableScenarios.size());
assertThatAreEqual(scenarioTitle + " [1]", performableScenarios.get(0).getScenario().getTitle());
List<PerformableTree.ExamplePerformableScenario> examplePerformableScenarios = performableScenarios.get(0)
.getExamples();
assertThatAreEqual(scenarioExample.size(), examplePerformableScenarios.size());
assertThatAreEqual("eE", examplePerformableScenarios.get(0).getParameters().get("var1"));
assertThatAreEqual("bB", examplePerformableScenarios.get(0).getParameters().get("var2"));
assertThatAreEqual("bBb#fF", examplePerformableScenarios.get(0).getParameters().get("var3"));
assertThatAreEqual("gbbGbB", examplePerformableScenarios.get(1).getParameters().get("var1"));
assertThatAreEqual("bB", examplePerformableScenarios.get(1).getParameters().get("var2"));
assertThatAreEqual("hH", examplePerformableScenarios.get(1).getParameters().get("var3"));
assertThatAreEqual(scenarioTitle + " [2]", performableScenarios.get(1).getScenario().getTitle());
examplePerformableScenarios = performableScenarios.get(1).getExamples();
assertThatAreEqual(scenarioExample.size(), examplePerformableScenarios.size());
assertThatAreEqual("eE", examplePerformableScenarios.get(0).getParameters().get("var1"));
assertThatAreEqual("dD", examplePerformableScenarios.get(0).getParameters().get("var2"));
assertThatAreEqual("dDd#fF", examplePerformableScenarios.get(0).getParameters().get("var3"));
assertThatAreEqual("gddGdD", examplePerformableScenarios.get(1).getParameters().get("var1"));
assertThatAreEqual("dD", examplePerformableScenarios.get(1).getParameters().get("var2"));
assertThatAreEqual("hH", examplePerformableScenarios.get(1).getParameters().get("var3"));
}
private void assertThatAreEqual(Object expected, Object actual) {
assertThat(actual, is(expected));
}
private Meta isEmptyMeta() {
return argThat(meta -> meta.getPropertyNames().isEmpty());
}
private static class SharpParameterConverters extends ParameterConverters {
@Override
public Object convert(String value, Type type) {
if (type == String.class) {
return value.replace("#", value.substring(1).toLowerCase());
}
return null;
}
}
}
| bsd-3-clause |
piciuoka/cafe | Cafe/src/cafe/analysis/Autocorrelation.java | 507 | package cafe.analysis;
public class Autocorrelation {
private static double[] x,r;
public static double[] get_fr() {
return x;
}
public static double[] get_fi() {
return r;
}
public static void acorr(double[] _x, double[] _r, int l, int np) {
double d;
int k,i;
x = java.util.Arrays.copyOf(_x, _x.length);
r = java.util.Arrays.copyOf(_r, _r.length);
for (k=1; k<=np; k++) {
d=0;
for (i=0; i<l-k-1; i++) {
d=d+x[i]*x[i+k];
}
r[k-1]=d;
}
}
}
| bsd-3-clause |
vkravets/Fido4Java | binkp/binkp-common/src/main/java/org/fidonet/binkp/common/commands/CramOPTCommand.java | 3368 | /******************************************************************************
* Copyright (c) 2012-2015, Vladimir Kravets *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are *
* met: Redistributions of source code must retain the above copyright notice,*
* this list of conditions and the following disclaimer. *
* Redistributions in binary form must reproduce the above copyright notice, *
* this list of conditions and the following disclaimer in the documentation *
* and/or other materials provided with the distribution. *
* Neither the name of the Fido4Java nor the names of its contributors *
* may be used to endorse or promote products derived from this software *
* without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"*
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, *
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR *
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR *
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;*
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, *
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR *
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, *
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
******************************************************************************/
package org.fidonet.binkp.common.commands;
import org.fidonet.binkp.common.SessionContext;
import java.security.MessageDigest;
/**
* Created by IntelliJ IDEA.
* Author: Vladimir Kravets
* E-Mail: vova.kravets@gmail.com
* Date: 9/23/12
* Time: 5:04 PM
*/
public class CramOPTCommand extends OPTCommand {
private MessageDigest messageDigest;
public CramOPTCommand(MessageDigest messageDigest) {
this.messageDigest = messageDigest;
messageDigest.reset();
messageDigest.update(String.format("%d%d", System.currentTimeMillis(),
System.nanoTime()).getBytes());
}
@Override
protected String getArguments(SessionContext sessionContext) {
if (!sessionContext.getLinksInfo().getCurLink().isMD()) {
return null;
}
final byte[] bufKey = messageDigest.digest();
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < 16; i++) {
builder.append(String.format("%02x", bufKey[i]));
}
final String key = builder.toString();
sessionContext.setPasswordKey(key);
return String.format("CRAM-%s-%s", messageDigest.getAlgorithm(), key);
}
}
| bsd-3-clause |
wsldl123292/jodd | jodd-db/src/test/java/jodd/db/oom/tst/BadGirlBase.java | 289 | // Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.
package jodd.db.oom.tst;
import jodd.db.oom.meta.DbColumn;
import jodd.db.oom.meta.DbId;
public class BadGirlBase {
@DbColumn("SPECIALITY")
public String foospeciality;
@DbId("ID")
public Integer fooid;
}
| bsd-3-clause |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/trackedentity/TrackedEntityInstanceEventFilter.java | 4204 | /*
* Copyright (c) 2004-2021, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity;
import android.database.Cursor;
import androidx.annotation.Nullable;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.gabrielittner.auto.value.cursor.ColumnAdapter;
import com.google.auto.value.AutoValue;
import org.hisp.dhis.android.core.arch.db.adapters.custom.internal.FilterPeriodColumnAdapter;
import org.hisp.dhis.android.core.arch.db.adapters.enums.internal.AssignedUserModeColumnAdapter;
import org.hisp.dhis.android.core.arch.db.adapters.enums.internal.EventStatusColumnAdapter;
import org.hisp.dhis.android.core.common.AssignedUserMode;
import org.hisp.dhis.android.core.common.CoreObject;
import org.hisp.dhis.android.core.common.FilterPeriod;
import org.hisp.dhis.android.core.event.EventStatus;
@AutoValue
@JsonDeserialize(builder = $$AutoValue_TrackedEntityInstanceEventFilter.Builder.class)
public abstract class TrackedEntityInstanceEventFilter implements CoreObject {
@Nullable
public abstract String trackedEntityInstanceFilter();
@Nullable
@JsonProperty()
public abstract String programStage();
@Nullable
@JsonProperty()
@ColumnAdapter(EventStatusColumnAdapter.class)
public abstract EventStatus eventStatus();
@Nullable
@JsonProperty()
@ColumnAdapter(FilterPeriodColumnAdapter.class)
public abstract FilterPeriod eventCreatedPeriod();
@Nullable
@JsonProperty()
@ColumnAdapter(AssignedUserModeColumnAdapter.class)
public abstract AssignedUserMode assignedUserMode();
public static Builder builder() {
return new $$AutoValue_TrackedEntityInstanceEventFilter.Builder();
}
public static TrackedEntityInstanceEventFilter create(Cursor cursor) {
return $AutoValue_TrackedEntityInstanceEventFilter.createFromCursor(cursor);
}
public abstract Builder toBuilder();
@AutoValue.Builder
@JsonPOJOBuilder(withPrefix = "")
public abstract static class Builder {
public abstract Builder id(Long id);
public abstract Builder trackedEntityInstanceFilter(String trackedEntityInstanceFilter);
public abstract Builder programStage(String programStage);
public abstract Builder eventStatus(EventStatus eventStatus);
public abstract Builder eventCreatedPeriod(FilterPeriod eventCreatedPeriod);
public abstract Builder assignedUserMode(AssignedUserMode assignedUserMode);
public abstract TrackedEntityInstanceEventFilter build();
}
} | bsd-3-clause |
x-clone/brackit.brackitdb | brackitdb-server/src/main/java/org/brackit/server/util/IntList.java | 3717 | /*
* [New BSD License]
* Copyright (c) 2011-2012, Brackit Project Team <info@brackit.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Brackit Project Team nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.brackit.server.util;
import java.util.Arrays;
/**
* This list is optimized for short lists of int type. Emulates full
* functionality of Java.Util.List. See append function for optimization issues.
*
*
* @author Martin Meiringer
* @author Sebastian Baechle
*
*/
public class IntList implements java.io.Serializable {
private int[] list;
private int size = 0;
public IntList() {
this(10);
}
public IntList(int initialSize) {
list = new int[initialSize];
size = 0;
}
public void clear() {
size = 0;
}
public int append(int element) {
return insert(element, this.size);
}
public int insert(int element, int pos) {
ensureCapacity(size + 1);
// shift from insert position to right
System.arraycopy(list, pos, list, pos + 1, pos + 1 - size);
// insert new element
list[pos] = element;
size++;
return pos;
} // insert
public void set(int pos, int element) {
if ((pos < 0) || (pos >= size)) {
throw new IndexOutOfBoundsException();
}
list[pos] = element;
}
public int get(int pos) {
if ((pos < 0) || (pos >= size)) {
throw new IndexOutOfBoundsException();
}
return list[pos];
}
public int size() {
return size;
}
public boolean isEmpty() {
return (size == 0);
}
public int[] toArray() {
return Arrays.copyOf(list, size);
}
@Override
public String toString() {
StringBuffer sBuff = new StringBuffer();
sBuff.append("(");
for (int i = 0; i < size; i++) {
if (i > 0)
sBuff.append(",");
sBuff.append(this.list[i]);
}
sBuff.append(")");
return sBuff.toString();
} // toString
private void ensureCapacity(int minCapacity) {
int oldCapacity = list.length;
if (oldCapacity < minCapacity) {
int newCapacity = (oldCapacity * 3) / 2 + 1;
int[] newList = new int[newCapacity];
System.arraycopy(this.list, 0, newList, 0, this.list.length);
list = newList;
}
}
public boolean contains(int containerNo) {
for (int i = 0; i < size; i++) {
if (list[i] == containerNo) {
return true;
}
}
return false;
}
} | bsd-3-clause |
mpakarlsson/ilearnrw | src/ilearnrw/utils/LanguageCode.java | 724 | package ilearnrw.utils;
/*
* Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details.
*/
public enum LanguageCode {
EN, GR;
public static byte getEnglishCode(){
return 1;
}
public static byte getGreekCode(){
return 0;
}
public static LanguageCode fromString(String languageCode) {
if (languageCode == null)
// default is EN
return EN;
if (languageCode.compareToIgnoreCase("EN") == 0) {
return EN;
}
if (languageCode.compareToIgnoreCase("GR") == 0) {
return GR;
}
// default is EN
return EN;
}
public byte getCode() {
if (this.equals(EN))
return getEnglishCode();
if (this.equals(GR))
return getGreekCode();
return -1;
}
}
| bsd-3-clause |
LiquidEngine/legui | src/main/java/org/liquidengine/legui/component/misc/animation/selectbox/SelectBoxAnimation.java | 2919 | package org.liquidengine.legui.component.misc.animation.selectbox;
import org.joml.Vector2f;
import org.liquidengine.legui.animation.Animation;
import org.liquidengine.legui.component.SelectBox;
import org.liquidengine.legui.component.SelectBox.SelectBoxScrollablePanel;
import java.lang.ref.WeakReference;
/**
* @author ShchAlexander.
*/
public class SelectBoxAnimation extends Animation {
private final WeakReference<SelectBox> selectBox;
private final WeakReference<SelectBoxScrollablePanel> selectionListPanel;
private double deltaSum = 0d;
public SelectBoxAnimation(SelectBox selectBox, SelectBoxScrollablePanel selectionListPanel) {
this.selectBox = new WeakReference<>(selectBox);
this.selectionListPanel = new WeakReference<>(selectionListPanel);
}
/**
* This method used to update animated object. Called by animator every frame. Removed from animator and stops when this method returns true. <p> Returns
* true if animation is finished and could be removed from animator.
*
* @param delta delta time (from previous call).
*
* @return true if animation is finished and could be removed from animator.
*/
@Override
protected boolean animate(double delta) {
SelectBox selectBox = this.selectBox.get();
SelectBoxScrollablePanel selectionListPanel = this.selectionListPanel.get();
if (selectBox == null || selectionListPanel == null) {
return true;
}
if (selectBox.isCollapsed()) {
return false;
}
deltaSum += delta;
if (deltaSum < 0.01d) {
return false;
}
float buttonWidth = selectBox.getButtonWidth();
selectionListPanel.getVerticalScrollBar().getStyle().setMaxWidth(buttonWidth);
selectionListPanel.getVerticalScrollBar().getStyle().setMaxWidth(buttonWidth);
int visibleCount = Math.min(selectBox.getVisibleCount(), selectBox.getElements().size());
float elementHeight = selectBox.getElementHeight();
Vector2f size = selectBox.getSize();
Vector2f wsize = new Vector2f(size.x, visibleCount * elementHeight);
Vector2f wpos = new Vector2f();
Vector2f sbPos = selectBox.getAbsolutePosition();
Vector2f pSize = selectBox.getSelectBoxLayer().getSize();
if (sbPos.y + wsize.y + size.y > pSize.y && sbPos.y - wsize.y > 0) {
wpos.set(sbPos.x, sbPos.y - wsize.y);
} else {
wpos.set(sbPos.x, sbPos.y + size.y);
}
selectionListPanel.setSize(wsize);
selectionListPanel.setPosition(wpos);
selectionListPanel.getContainer().getSize().y = selectionListPanel.getContainer().count() * elementHeight;
selectionListPanel.getContainer().getSize().x = size.x - selectionListPanel.getVerticalScrollBar().getSize().x;
deltaSum = 0;
return false;
}
}
| bsd-3-clause |
luttero/Maud | src/it/unitn/ing/wizard/LCLS2Wizard/Cspad.java | 287 | package it.unitn.ing.wizard.LCLS2Wizard;
import java.util.Vector;
public class Cspad {
public String name;
public boolean enabled = true;
public boolean available = false;
public Vector<SensorImage> detectors;
public Cspad() {
detectors = new Vector<SensorImage>(0, 1);
}
}
| bsd-3-clause |
conormcd/exemplar | src/com/mcdermottroe/exemplar/model/XMLDocumentTypeException.java | 3206 | // vim:filetype=java:ts=4
/*
Copyright (c) 2004-2007
Conor McDermottroe. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the author nor the names of any contributors to
the software may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.mcdermottroe.exemplar.model;
import com.mcdermottroe.exemplar.Exception;
/** An exception that can be thrown in response to an error in operations on an
{@link XMLDocumentType}.
@author Conor McDermottroe
@since 0.1
*/
public class XMLDocumentTypeException extends Exception {
/** XMLDocumentTypeException without a description. */
public XMLDocumentTypeException() {
super();
}
/** XMLDocumentTypeException with a description.
@param message The description of the exception.
*/
public XMLDocumentTypeException(String message) {
super(message);
}
/** XMLDocumentTypeException with a description and a reference to an
exception which caused it.
@param message The description of the exception.
@param cause The cause of the exception.
*/
public XMLDocumentTypeException(String message, Throwable cause) {
super(message, cause);
}
/** XMLDocumentTypeException with a reference to the exception that caused
it.
@param cause The cause of the exception.
*/
public XMLDocumentTypeException(Throwable cause) {
super(cause);
}
/** {@inheritDoc} */
public XMLDocumentTypeException getCopy() {
XMLDocumentTypeException copy;
String message = getMessage();
Throwable cause = getCause();
if (message != null && cause != null) {
copy = new XMLDocumentTypeException(message, cause);
} else if (message != null) {
copy = new XMLDocumentTypeException(message);
} else if (cause != null) {
copy = new XMLDocumentTypeException(cause);
} else {
copy = new XMLDocumentTypeException();
}
copy.setStackTrace(copyStackTrace(getStackTrace()));
return copy;
}
}
| bsd-3-clause |
anandbn/tosho | src/main/java/canvas/SignedRequest.java | 6472 | /**
* Copyright (c) 2011, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package canvas;
import org.apache.commons.codec.binary.Base64;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectReader;
import org.codehaus.jackson.type.TypeReference;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.StringWriter;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
/**
*
* The utility class can be used to un-sign the signed request. The request needs un-signing such that
* it can be verified that it is from Salesforce and that the request has not been tampered with.
* <p>
* This utility class has two method. One un-signs the request as a Java object the other as a JSON String.
*
*/
public class SignedRequest {
public static CanvasRequest unsign(String input, String secret) throws SecurityException {
String[] split = getParts(input);
String encodedSig = split[0];
String encodedEnvelope = split[1];
// Deserialize the json body
String json_envelope = new String(new Base64(true).decode(encodedEnvelope));
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.reader(CanvasRequest.class);
CanvasRequest canvasRequest;
String algorithm;
try {
canvasRequest = reader.readValue(json_envelope);
algorithm = canvasRequest.getAlgorithm() == null ? "HMACSHA256" : canvasRequest.getAlgorithm();
} catch (IOException e) {
throw new SecurityException(String.format("Error [%s] deserializing JSON to Object [%s]", e.getMessage(), CanvasRequest.class.getName()), e);
}
verify(secret, algorithm, encodedEnvelope, encodedSig);
// If we got this far, then the request was not tampered with.
// return the request as a Java object
return canvasRequest;
}
public static String unsignAsJson(String input, String secret) throws SecurityException {
String[] split = getParts(input);
String encodedSig = split[0];
String encodedEnvelope = split[1];
String json_envelope = new String(new Base64(true).decode(encodedEnvelope));
ObjectMapper mapper = new ObjectMapper();
String algorithm;
StringWriter writer;
TypeReference<HashMap<String,Object>> typeRef
= new TypeReference<HashMap<String, Object>>() { };
try {
HashMap<String,Object> o = mapper.readValue(json_envelope, typeRef);
writer = new StringWriter();
mapper.writeValue(writer, o);
algorithm = (String)o.get("algorithm");
} catch (IOException e) {
throw new SecurityException(String.format("Error [%s] deserializing JSON to Object [%s]", e.getMessage(),
typeRef.getClass().getName()), e);
}
verify(secret, algorithm, encodedEnvelope, encodedSig);
// If we got this far, then the request was not tampered with.
// return the request as a JSON string.
return writer.toString();
}
private static String[] getParts(String input) {
if (input == null || input.indexOf(".") <= 0) {
throw new SecurityException(String.format("Input [%s] doesn't look like a signed request", input));
}
String[] split = input.split("[.]", 2);
return split;
}
private static void verify(String secret, String algorithm, String encodedEnvelope, String encodedSig )
throws SecurityException
{
if (secret == null || secret.trim().length() == 0) {
throw new IllegalArgumentException("secret is null, did you set your environment variable CANVAS_CONSUMER_SECRET?");
}
SecretKey hmacKey = null;
try {
byte[] key = secret.getBytes();
hmacKey = new SecretKeySpec(key, algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(hmacKey);
// Check to see if the body was tampered with
byte[] digest = mac.doFinal(encodedEnvelope.getBytes());
byte[] decode_sig = new Base64(true).decode(encodedSig);
if (! Arrays.equals(digest, decode_sig)) {
String label = "Warning: Request was tampered with";
throw new SecurityException(label);
}
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(String.format("Problem with algorithm [%s] Error [%s]", algorithm, e.getMessage()), e);
} catch (InvalidKeyException e) {
throw new SecurityException(String.format("Problem with key [%s] Error [%s]", hmacKey, e.getMessage()), e);
}
// If we got here and didn't throw a SecurityException then all is good.
}
}
| bsd-3-clause |
kavanj/marioai | src/ch/idsia/unittests/LevelGeneratorTest.java | 9162 | /*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.unittests;
import ch.idsia.benchmark.mario.engine.level.Level;
import ch.idsia.benchmark.mario.engine.level.LevelGenerator;
import ch.idsia.benchmark.mario.engine.level.SpriteTemplate;
import ch.idsia.benchmark.mario.engine.sprites.Sprite;
import ch.idsia.benchmark.tasks.BasicTask;
import ch.idsia.tools.MarioAIOptions;
import ch.idsia.tools.RandomCreatureGenerator;
import junit.framework.TestCase;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, sergey.karakovskiy@gmail.com
* Date: Aug 28, 2010
* Time: 10:30:34 PM
* Package: ch.idsia.unittests
*/
public class LevelGeneratorTest extends TestCase
{
@BeforeTest
public void setUp()
{
}
@AfterTest
public void tearDown()
{
}
@Test
public void testRegressionLBBug() throws Exception
{
// This test has to be first because it only happens if blocks have
// never been on before.
final MarioAIOptions marioAIOptions = new MarioAIOptions();
marioAIOptions.setArgs("-lb off");
Level level1 = LevelGenerator.createLevel(marioAIOptions);
marioAIOptions.setArgs("-vis off -ag ch.idsia.agents.controllers.ForwardJumpingAgent -lb on");
final BasicTask basicTask = new BasicTask(marioAIOptions);
basicTask.setOptionsAndReset(marioAIOptions);
basicTask.runSingleEpisode(1);
marioAIOptions.setArgs("-lb off");
Level level2 = LevelGenerator.createLevel(marioAIOptions);
for (int i = 0; i < level1.length; i++)
{
for (int j = 0; j < level1.height; j++)
{
assertEquals(level1.getBlock(i, j), level2.getBlock(i, j));
}
}
}
@Test
public void testCreateLevel() throws Exception
{
final MarioAIOptions marioAIOptions = new MarioAIOptions();
Level level1 = LevelGenerator.createLevel(marioAIOptions);
Level level2 = LevelGenerator.createLevel(marioAIOptions);
for (int i = 0; i < level1.length; i++)
{
for (int j = 0; j < level1.height; j++)
{
assertEquals(level1.getBlock(i, j), level2.getBlock(i, j));
}
}
}
@Test
public void testSpriteTemplates() throws Exception
{
final MarioAIOptions marioAIOptions = new MarioAIOptions();
Level level1 = LevelGenerator.createLevel(marioAIOptions);
Level level2 = LevelGenerator.createLevel(marioAIOptions);
for (int i = 0; i < level1.length; i++)
{
for (int j = 0; j < level1.height; j++)
{
int t1 = 0;
int t2 = 0;
SpriteTemplate st1 = level1.getSpriteTemplate(i, j);
SpriteTemplate st2 = level2.getSpriteTemplate(i, j);
if (st1 != null)
{
t1 = st1.getType();
}
if (st2 != null)
{
t2 = st2.getType();
}
else if (st1 != null)
{
throw new AssertionError("st1 is not null, st2 is null!");
}
assertEquals(t1, t2);
}
}
}
@Test
public void testCreateLevelWithoutCreatures() throws Exception
{
final MarioAIOptions marioAIOptions = new MarioAIOptions("-le off");
Level level = LevelGenerator.createLevel(marioAIOptions);
for (int i = 0; i < level.length; i++)
{
for (int j = 0; j < level.height; j++)
{
SpriteTemplate st = level.getSpriteTemplate(i, j);
if (st != null && st.getType() == Sprite.KIND_PRINCESS)
{
continue;
}
assertNull(st);
}
}
}
// @Test
// public void testCreateLevelWithTubesWithoutFlowers()
// {
// final MarioAIOptions marioAIOptions = new MarioAIOptions("-ltb on -le g,gw,gk,gkw,rk,rkw,s,sw");
// Level level = LevelGenerator.createLevel(marioAIOptions);
//
// assertEquals(true, level.counters.tubesCount > 0);
// assertEquals(true, level.counters.totalTubes == Integer.MAX_VALUE);
// }
// @Test
// public void testCreateLevelWithTubesWithFlowers()
// {
// final MarioAIOptions marioAIOptions = new MarioAIOptions("-ltb on -le f -ld 5 -ls 222");
// Level level = LevelGenerator.createLevel(marioAIOptions);
//
// boolean fl = false;
//
// for (int i = 0; i < level.length; i++)
// for (int j = 0; j < level.height; j++)
// if ((level.getSpriteTemplate (i, j) != null) && (level.getSpriteTemplate (i, j).getType() == Sprite.KIND_ENEMY_FLOWER))
// {
// fl = true;
// break;
// }
//
// assertEquals(true, fl);
// }
@Test
public void testRandomCreatureGenerator_RedKoopaWinged()
{
RandomCreatureGenerator g = new RandomCreatureGenerator(0, "rkw", 0);
assertEquals(Sprite.KIND_RED_KOOPA_WINGED, g.nextCreature());
}
@Test
public void testRandomCreatureGenerator_GreenKoopaWinged()
{
RandomCreatureGenerator g = new RandomCreatureGenerator(0, "gkw", 0);
assertEquals(Sprite.KIND_GREEN_KOOPA_WINGED, g.nextCreature());
}
@Test
public void testRandomCreatureGenerator_Goomba()
{
RandomCreatureGenerator g = new RandomCreatureGenerator(0, "g", 0);
assertEquals(Sprite.KIND_GOOMBA, g.nextCreature());
}
@Test
public void testRandomCreatureGenerator_10Goombas()
{
final MarioAIOptions marioAIOptions = new MarioAIOptions("-le g:10");
Level level = LevelGenerator.createLevel(marioAIOptions);
int counter = 0;
for (int i = 0; i < level.length; i++)
{
for (int j = 0; j < level.height; j++)
{
SpriteTemplate st1 = level.getSpriteTemplate(i, j);
if (st1 != null && st1.getType() != Sprite.KIND_PRINCESS)
{
int type = st1.getType();
assertEquals(Sprite.KIND_GOOMBA, type);
++counter;
}
}
}
System.out.println("level.counters.creatures = " + Level.counters.creatures);
assertEquals(10, counter);
}
@Test
public void testRandomCreatureGenerator_20RedWingedKoopas()
{
final MarioAIOptions marioAIOptions = new MarioAIOptions("-le rkw:20");
Level level = LevelGenerator.createLevel(marioAIOptions);
int counter = 0;
for (int i = 0; i < level.length; i++)
{
for (int j = 0; j < level.height; j++)
{
SpriteTemplate st1 = level.getSpriteTemplate(i, j);
if (st1 != null && st1.getType() != Sprite.KIND_PRINCESS)
{
int type = st1.getType();
assertEquals(Sprite.KIND_RED_KOOPA_WINGED, type);
++counter;
}
}
}
System.out.println("level.counters.creatures = " + Level.counters.creatures);
assertEquals(20, counter);
}
}
| bsd-3-clause |
groupon/Novie | novie-core/src/main/java/com/groupon/novie/internal/engine/QuerySortConstraint.java | 1075 | package com.groupon.novie.internal.engine;
/**
* This class represent an order/sort constraint. Dimension and information name are stored in upperCase
* @author thomas
* @since 10/01/2014.
*/
public class QuerySortConstraint {
private OrderByDirection orderByDirection;
private String dimensionName;
private String informationName;
public QuerySortConstraint(OrderByDirection orderByDirection, String dimensionName, String informationName) throws IllegalArgumentException {
if (dimensionName == null) {
throw new IllegalArgumentException("dimensionName can not be null");
}
this.orderByDirection = orderByDirection;
this.dimensionName = dimensionName;
this.informationName = (informationName == null) ? null : informationName.toUpperCase();
}
public OrderByDirection getOrderByDirection() {
return orderByDirection;
}
public String getDimensionName() {
return dimensionName;
}
public String getInformationName() {
return informationName;
}
}
| bsd-3-clause |
wsldl123292/jodd | jodd-bean/src/main/java/jodd/bean/BeanTemplateParser.java | 1170 | // Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.
package jodd.bean;
import jodd.util.StringTemplateParser;
/**
* Bean template is a string template with JSP-alike
* macros for injecting context values.
* This is a parser for such bean templates.
* <p>
* Once set, <code>BeanTemplateParser</code> instance is reusable
* as it doesn't store any parsing state.
* <p>
* Based on {@link StringTemplateParser}.
*/
public class BeanTemplateParser extends StringTemplateParser {
/**
* Replaces named macros with context values.
* All declared properties are considered during value lookup.
*/
public String parse(String template, Object context) {
return parse(template, createBeanMacroResolver(context));
}
/**
* Creates bean-backed <code>MacroResolver</code>.
*/
public static MacroResolver createBeanMacroResolver(final Object context) {
return new MacroResolver() {
public String resolve(String macroName) {
Object value = BeanUtil.getDeclaredProperty(context, macroName);
if (value == null) {
return null;
}
return value.toString();
}
};
}
}
| bsd-3-clause |
mikem2005/vijava | src/com/vmware/vim25/AlreadyExists.java | 1905 | /*================================================================================
Copyright (c) 2009 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
@author Steve Jin (sjin@vmware.com)
*/
public class AlreadyExists extends VimFault
{
public String name;
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name=name;
}
} | bsd-3-clause |
vivo-project/Vitro | api/src/main/java/edu/cornell/mannlib/vitro/webapp/searchengine/elasticsearch/QueryConverter.java | 6254 | /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.searchengine.elasticsearch;
import static edu.cornell.mannlib.vitro.webapp.searchengine.elasticsearch.JsonTree.EMPTY_JSON_MAP;
import static edu.cornell.mannlib.vitro.webapp.searchengine.elasticsearch.JsonTree.ifPositive;
import static edu.cornell.mannlib.vitro.webapp.searchengine.elasticsearch.JsonTree.tree;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchEngineException;
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchQuery;
import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchQuery.Order;
/**
* Accept a SearchQuery and make it available as a JSON string, suitable for
* Elasticsearch.
*/
public class QueryConverter {
private static final Log log = LogFactory.getLog(QueryConverter.class);
private final SearchQuery query;
private final Map<String, Object> queryAndFilters;
private final Map<String, Object> sortFields;
private final Map<String, Object> facets;
private final Map<String, Object> highlighter;
private final List<String> returnFields;
private final Map<String, Object> fullMap;
public QueryConverter(SearchQuery query) {
this.query = query;
this.queryAndFilters = filteredOrNot();
this.sortFields = figureSortFields();
this.facets = figureFacets();
this.highlighter = figureHighlighter();
this.returnFields = figureReturnFields();
this.fullMap = figureFullMap();
}
private Map<String, Object> filteredOrNot() {
if (query.getFilters().isEmpty()) {
return new QueryStringMap(query.getQuery()).map;
} else {
return buildFilterStructure();
}
}
private Map<String, Object> buildFilterStructure() {
return tree() //
.put("bool", tree() //
.put("must", new QueryStringMap(query.getQuery()).map) //
.put("filter", buildFiltersList())) //
.asMap();
}
private List<Map<String, Object>> buildFiltersList() {
List<Map<String, Object>> list = new ArrayList<>();
for (String filter : query.getFilters()) {
list.add(new QueryStringMap(filter).map);
}
return list;
}
private Map<String, Object> figureSortFields() {
Map<String, Order> fields = query.getSortFields();
Map<String, Object> map = new HashMap<>();
for (String name : fields.keySet()) {
String sortOrder = fields.get(name).toString().toLowerCase();
map.put(name, sortOrder);
}
return map;
}
private Map<String, Object> figureFacets() {
Map<String, Object> map = new HashMap<>();
for (String field : query.getFacetFields()) {
map.put("facet_" + field, figureFacet(field));
}
return map;
}
private Map<String, Object> figureHighlighter() {
return tree() //
.put("fields", tree() //
.put("ALLTEXT", EMPTY_JSON_MAP))
.asMap();
}
private Map<String, Object> figureFacet(String field) {
return tree() //
.put("terms", tree() //
.put("field", field) //
.put("size", ifPositive(query.getFacetLimit())) //
.put("min_doc_count",
ifPositive(query.getFacetMinCount()))) //
.asMap();
}
private List<String> figureReturnFields() {
return new ArrayList<>(query.getFieldsToReturn());
}
private Map<String, Object> figureFullMap() {
return tree() //
.put("query", queryAndFilters) //
.put("from", ifPositive(query.getStart())) //
.put("highlight", highlighter)
.put("size", ifPositive(query.getRows())) //
.put("sort", sortFields) //
.put("_source", returnFields) //
.put("aggregations", facets) //
.asMap();
}
public String asString() throws SearchEngineException {
try {
return new ObjectMapper().writeValueAsString(fullMap);
} catch (JsonProcessingException e) {
throw new SearchEngineException(e);
}
}
private static class QueryStringMap {
public final Map<String, Object> map;
public QueryStringMap(String queryString) {
map = new HashMap<>();
map.put("query_string", makeInnerMap(escape(queryString)));
}
/**
* This is a kluge, but perhaps it will work for now.
*
* Apparently Solr is willing to put up with query strings that contain
* special characters in odd places, but Elasticsearch is not.
*
* So, a query string of "classgroup:http://this/that" must be escaped
* as "classgroup:http\:\/\/this\/that". Notice that the first colon
* delimits the field name, and so must not be escaped.
*
* But what if no field is specified? Then all colons must be escaped.
* How would we distinguish that?
*
* And what if the query is more complex, and more than one field is
* specified? What if other special characters are included?
*
* This could be a real problem.
*/
private String escape(String queryString) {
return queryString.replace(":", "\\:").replace("/", "\\/")
.replaceFirst("\\\\:", ":");
}
private Map<String, String> makeInnerMap(String queryString) {
Map<String, String> inner = new HashMap<>();
inner.put("default_field", "ALLTEXT");
inner.put("query", queryString);
return inner;
}
}
}
| bsd-3-clause |
Sukelluskello/VectorAttackScanner | Android/DependenciesVectorAttackScanner/src/brut/androlib/mod/SmaliMod.java | 2344 | /**
* Copyright 2011 Ryszard Wiśniewski <brut.alll@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package brut.androlib.mod;
import java.io.*;
import org.antlr.runtime.*;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeNodeStream;
import org.jf.dexlib.DexFile;
import org.jf.smali.*;
/**
* @author Ryszard Wiśniewski <brut.alll@gmail.com>
*/
public class SmaliMod {
public static boolean assembleSmaliFile(InputStream smaliStream,
String name, DexFile dexFile, boolean verboseErrors,
boolean oldLexer, boolean printTokens) throws IOException,
RecognitionException {
CommonTokenStream tokens;
boolean lexerErrors = false;
LexerErrorInterface lexer;
InputStreamReader reader = new InputStreamReader(smaliStream, "UTF-8");
lexer = new smaliFlexLexer(reader);
tokens = new CommonTokenStream((TokenSource) lexer);
if (printTokens) {
tokens.getTokens();
for (int i = 0; i < tokens.size(); i++) {
Token token = tokens.get(i);
if (token.getChannel() == BaseRecognizer.HIDDEN) {
continue;
}
System.out.println(smaliParser.tokenNames[token.getType()]
+ ": " + token.getText());
}
}
smaliParser parser = new smaliParser(tokens);
parser.setVerboseErrors(verboseErrors);
smaliParser.smali_file_return result = parser.smali_file();
if (parser.getNumberOfSyntaxErrors() > 0
|| lexer.getNumberOfSyntaxErrors() > 0) {
return false;
}
CommonTree t = (CommonTree) result.getTree();
CommonTreeNodeStream treeStream = new CommonTreeNodeStream(t);
treeStream.setTokenStream(tokens);
smaliTreeWalker dexGen = new smaliTreeWalker(treeStream);
dexGen.dexFile = dexFile;//ojo
dexGen.smali_file();
if (dexGen.getNumberOfSyntaxErrors() > 0) {
return false;
}
return true;
}
}
| bsd-3-clause |
BaseXdb/basex | basex-core/src/main/java/org/basex/server/ServerCmd.java | 1916 | package org.basex.server;
/**
* This class defines the available command-line commands.
*
* @author BaseX Team 2005-22, BSD License
* @author Christian Gruen
*/
public enum ServerCmd {
/** Code for creating a query process: {query}0. */
QUERY(0),
/** Code for iterating results (obsolete). */
NEXT(1),
/** Code for closing the query: {id}0. */
CLOSE(2),
/** Code for binding an external query variable: {id}0{name}0{val}0{type}0. */
BIND(3),
/** Code for executing the query in an iterative manner: {id}0. */
RESULTS(4),
/** Code for executing the query: {id}0. */
EXEC(5),
/** Code for showing the query info: {id}0. */
INFO(6),
/** Code for showing the serializations options: {id}0. */
OPTIONS(7),
/** Code for creating a database: {name}0{input}0. */
CREATE(8),
/** Code for adding a document to a database: {path}0{input}0. */
ADD(9),
/** Code for replacing a document in a database: {path}0{input}0. */
REPLACE(12),
/** Code for storing raw data in a database: {path}0{input}0. */
STORE(13),
/** Code for binding a context value: {id}0{val}0{type}0. */
CONTEXT(14),
/** Code for returning the update flag: {id}0. */
UPDATING(30),
/** Code for executing a query and returning all information relevant for XQJ: {id}0. */
FULL(31),
/** Code for running a database command: {path}0{input}0. */
COMMAND(-1);
/** Control code (soon obsolete). */
public final int code;
/**
* Constructor.
* @param code control code
*/
ServerCmd(final int code) {
this.code = code;
}
/**
* Returns the server command for the specified control byte.
* @param code control code
* @return server command
*/
static ServerCmd get(final int code) {
for(final ServerCmd value : values()) {
if(value.code == code) return value;
}
// current default for unknown codes: database command.
return COMMAND;
}
}
| bsd-3-clause |
compgen-io/sjq | src/java/io/compgen/sjq/server/ThreadedJobQueue.java | 10125 | package io.compgen.sjq.server;
import io.compgen.common.MonitoredThread;
import io.compgen.common.StringUtils;
import io.compgen.common.TallyValues;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Date;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadedJobQueue {
private String queueID = StringUtils.randomString(8);
final private SJQServer server;
final private int maxProcs;
final private long maxMem;
final private File tempDir;
private int usedProcs = 0;
private int usedMem = 0;
private int lastId = 0;
private long emptyCheck = -1;
private long timeout = -1;
public Deque<Job> pending = new ArrayDeque<Job>();
public Map<String, RunningJob> running = new LinkedHashMap<String, RunningJob>();
public Map<String, Job> jobs = new LinkedHashMap<String, Job>();
private boolean closing = false;
private MonitoredThread procThread = null;
private Lock lock = new ReentrantLock();
public ThreadedJobQueue(SJQServer server, int maxProcs, long maxMem, long timeout, String tempDir) {
this.server = server;
this.maxProcs = maxProcs;
this.maxMem = maxMem;
this.timeout = timeout;
if (tempDir != null) {
this.tempDir = new File(tempDir);
} else {
this.tempDir = null;
}
}
public String getNewJobId() {
lock.lock();
String jobid = queueID+"."+(++lastId);
lock.unlock();
return jobid;
}
public void close() {
if (!closing) {
lock.lock();
closing = true;
procThread.interrupt();
List<String> runningJobIds = new ArrayList<String>();
for (RunningJob runningjob:running.values()) {
server.log("Currently running job: "+runningjob.getJob().getJobId());
runningJobIds.add(runningjob.getJob().getJobId());
}
for (String jobId: runningJobIds) {
killJob(jobId);
}
server.log("Shutdown job queue...");
lock.unlock();
}
}
public boolean start() {
lock.lock();
if (procThread != null) {
lock.unlock();
return false;
}
procThread = new MonitoredThread(new Runnable() {
public void run() {
while (!closing) {
if (timeout > 0 && pending.size() == 0 && running.size() == 0) {
if (emptyCheck == -1) {
emptyCheck = System.currentTimeMillis();
} else {
if ((System.currentTimeMillis() - emptyCheck) > timeout) {
server.log("Timeout waiting for a job!");
server.shutdown();
return;
}
}
}
server.log("Status: " + getStatus());
if (running.size()>0) {
printRunningStatus();
}
checkJobHolds();
Job jobToRun = findJobToRun();
if (jobToRun != null) {
runJob(jobToRun);
emptyCheck = -1;
} else {
try {
// sleep for one minute, or half the length of the timeout, which ever is shorter.
Thread.sleep(timeout > 0 ? Math.min(60000, timeout/2) : 60000);
} catch (InterruptedException e) {
}
}
}
}
});
procThread.start();
lock.unlock();
return true;
}
public void printRunningStatus() {
System.err.println("-------------------------");
lock.lock();
for (RunningJob job: running.values()) {
System.err.println("Running: " + job.getJob().getJobId() + " "+ StringUtils.pad(job.getJob().getName(), 12, ' ') + " " + job.getJob().getProcs() + " " + timespanToString(System.currentTimeMillis() - job.getJob().getStartTime()));
}
lock.unlock();
System.err.println("-------------------------");
}
public String getServerStatus() {
String out = "";
lock.lock();
for (Job job: server.getQueue().jobs.values()) {
if (!out.equals("")) {
out += "\n";
}
List<String> outs = new ArrayList<String>();
outs.add(job.getJobId());
outs.add(job.getName());
outs.add(job.getState().getCode());
outs.add(""+ThreadedJobQueue.timestampToString(job.getSubmitTime()));
if (job.getState() == JobState.RUNNING) {
outs.add(""+ThreadedJobQueue.timestampToString(job.getStartTime()));
outs.add(""+ThreadedJobQueue.timespanToString(System.currentTimeMillis() - job.getStartTime()));
} else if (job.getState() == JobState.SUCCESS || job.getState() == JobState.ERROR) {
outs.add(""+ThreadedJobQueue.timestampToString(job.getStartTime()));
outs.add(""+ThreadedJobQueue.timestampToString(job.getEndTime()));
outs.add(""+job.getRetCode());
outs.add(""+ThreadedJobQueue.timespanToString(job.getEndTime() - job.getStartTime()));
} else {
outs.add(""+ThreadedJobQueue.timespanToString(System.currentTimeMillis() - job.getSubmitTime()));
}
out += StringUtils.join("\t", outs);
}
lock.unlock();
return out;
}
public String getStatus() {
TallyValues<String> counter = new TallyValues<String>();
lock.lock();
for (Job job: jobs.values()) {
counter.incr(job.getState().getCode());
}
lock.unlock();
String s = "";
for (String k: counter.keySet()) {
if (!s.equals("")) {
s+=" ";
}
s += k+":"+counter.getCount(k);
}
if (s.equals("")) {
return "Waiting for jobs...";
}
return s;
}
private Job findJobToRun() {
lock.lock();
for (Job job: pending) {
if (job.getState() == JobState.QUEUED) {
if (usedProcs + job.getProcs() <= maxProcs && (maxMem < 0 || usedMem + job.getMem() < maxMem)) {
lock.unlock();
return job;
}
}
}
lock.unlock();
return null;
}
private void checkJobHolds() {
lock.lock();
for (Job job: pending) {
if (job.getState() == JobState.HOLD) {
boolean good = true;
for (String jobId: job.getWaitFor()) {
Job dep = jobs.get(jobId);
if (dep == null || dep.getState() != JobState.SUCCESS) {
good = false;
break;
}
}
if (good) {
job.setState(JobState.QUEUED);
}
}
}
lock.unlock();
}
private void runJob(Job job) {
if (closing) {
return;
}
lock.lock();
server.log("Starting job - "+ job.getJobId());
job.setState(JobState.RUNNING);
job.setStartTime(System.currentTimeMillis());
pending.remove(job);
usedProcs += job.getProcs();
usedMem += job.getMem();
RunningJob run = new RunningJob(this, job);
running.put(job.getJobId(), run);
lock.unlock();
run.start();
}
public String addJob(Job job) {
String jobId = getNewJobId();
job.setJobId(jobId);
job.setState(JobState.HOLD);
job.setSubmitTime(System.currentTimeMillis());
lock.lock();
jobs.put(jobId, job);
pending.add(job);
lock.unlock();
emptyCheck = -1;
server.log("New job: "+ jobId+ " "+job.getName());
procThread.interrupt();
return jobId;
}
public boolean killJob(String jobId) {
Job job = jobs.get(jobId);
if (job == null) {
return false;
}
lock.lock();
if (running.containsKey(jobId)) {
server.log("Killing job: " + jobId);
running.get(jobId).kill();
job.setState(JobState.KILLED);
server.log("Job killed: " + jobId);
lock.unlock();
return true;
}
if (job != null && (job.getState() == JobState.HOLD || job.getState() == JobState.QUEUED)) {
job.setState(JobState.KILLED);
server.log("Job killed: " + jobId);
lock.unlock();
return true;
}
lock.unlock();
return false;
}
public void jobDone(String jobId, int retcode) {
server.log("Job done: " + jobId + " " + retcode);
lock.lock();
running.remove(jobId);
Job job = jobs.get(jobId);
if (job.getState() == JobState.RUNNING) {
if (retcode == 0) {
job.setState(JobState.SUCCESS);
} else {
job.setState(JobState.ERROR);
}
}
job.setEndTime(System.currentTimeMillis());
usedProcs -= job.getProcs();
usedMem -= job.getMem();
lock.unlock();
procThread.interrupt();
}
public File getTempDir() {
return tempDir;
}
public Job getJob(String jobId) {
return jobs.get(jobId);
}
public void join() {
while (this.procThread != null && !this.procThread.isDone()) {
try {
this.procThread.join(1000);
} catch (InterruptedException e) {
}
}
}
public static long memStrToLong(String memVal) {
if (memVal.toUpperCase().endsWith("G")) {
return Long.parseLong(memVal.substring(0, memVal.length()-1)) * 1024 * 1024 * 1024;
} else if (memVal.toUpperCase().endsWith("M")) {
return Long.parseLong(memVal.substring(0, memVal.length()-1)) * 1024 * 1024;
} else if (memVal.toUpperCase().endsWith("K")) {
return Long.parseLong(memVal.substring(0, memVal.length()-1)) * 1024;
}
try {
return Long.parseLong(memVal);
} catch (NumberFormatException e) {
return -1;
}
}
public static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String timestampToString(long ts) {
return dateFormat.format(new Date(ts));
}
public static String timespanToString(long timeSpanMillis) {
String s = "";
long hours = timeSpanMillis / (60 * 60 * 1000);
timeSpanMillis = timeSpanMillis - (hours * 60 * 60 * 1000);
long mins = timeSpanMillis / (60 * 1000);
timeSpanMillis = timeSpanMillis - (mins * 60 * 1000);
long secs = timeSpanMillis / 1000;
if (hours > 0) {
s += hours +":";
}
if (mins > 9) {
s += mins +":";
} else if (mins > 0) {
if (!s.equals("")) {
s += "0";
}
s += mins +":";
} else if (mins == 0 && hours > 0) {
if (!s.equals("")) {
s += "00:";
}
} else {
s += "0:";
}
if (secs > 9) {
s += secs;
} else if (secs > 0) {
if (!s.equals("")) {
s += "0";
}
s += secs;
} else if (secs == 0) {
if (!s.equals("")) {
s += "00";
}
}
return s;
}
public SJQServer getServer() {
return server;
}
public boolean releaseJob(String jobId) {
Job job = jobs.get(jobId);
if (job == null) {
return false;
}
lock.lock();
if (job != null && (job.getState() == JobState.USERHOLD)) {
job.setState(JobState.HOLD);
server.log("Job released from user-hold: " + jobId);
procThread.interrupt();
lock.unlock();
return true;
}
lock.unlock();
return false;
}
}
| bsd-3-clause |
motech/MOTECH-Mobile | motech-mobile-core/src/main/java/org/motechproject/mobile/core/model/GatewayRequestImpl.java | 11499 | /**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.mobile.core.model;
import org.motechproject.mobile.core.util.MotechIDGenerator;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Date :Jul 24, 2009
* @author Joseph Djomeda (joseph@dreamoval.com)
*/
@SuppressWarnings("serial")
public class GatewayRequestImpl implements GatewayRequest, Serializable {
private Long id;
private GatewayRequestDetails gatewayRequestDetails;
private Date dateTo;
private String message;
private String recipientsNumber;
private Date dateFrom;
private Set<GatewayResponse> responseDetails = new HashSet<GatewayResponse>();
private Date dateSent;
private int tryNumber;
private String requestId;
private MStatus messageStatus;
private Date lastModified;
private MessageRequest messageRequest;
public GatewayRequestImpl() {
this.id = MotechIDGenerator.generateID();
}
public GatewayRequestImpl(Date dateTo, String messageText, String recipientsNumber, Date dateFrom, Date dateSent) {
this();
this.dateTo = dateTo;
this.message = messageText;
this.dateFrom = dateFrom;
this.dateSent = dateSent;
this.recipientsNumber = recipientsNumber;
}
private int version = -1;
/*
* @return the version
*/
public int getVersion() {
return version;
}
/*
* @param version the version to set
*/
public void setVersion(int version) {
this.version = version;
}
/*
* @return the messageType
*/
/*
* @return the numberOfPages
*/
public Date getDateTo() {
return dateTo;
}
/*
* @param numberOfPages the numberOfPages to set
*/
public void setDateTo(Date dateTo) {
this.dateTo = dateTo;
}
/*
* @return the messageText
*/
public String getMessage() {
return message;
}
/*
* @param messageText the messageText to set
*/
public void setMessage(String messageText) {
this.message = messageText;
}
/*
* @return the dateFrom
*/
public Date getDateFrom() {
return dateFrom;
}
/*
* @param dateFrom the dateFrom to set
*/
public void setDateFrom(Date dateFrom) {
this.dateFrom = dateFrom;
}
/*
* @return the responseDetails
*/
public Set<GatewayResponse> getResponseDetails() {
return responseDetails;
}
/*
* @param responseDetails the responseDetails to set
*/
public void setResponseDetails(Set<GatewayResponse> responseDetails) {
this.responseDetails = responseDetails;
}
/*
* @return the dateSent
*/
public Date getDateSent() {
return dateSent;
}
/*
* @param dateSent the dateSent to set
*/
public void setDateSent(Date dateSent) {
this.dateSent = dateSent;
}
/*
* @return the recipientsNumbers
*/
public String getRecipientsNumber() {
return recipientsNumber;
}
/*
* @param recipientsNumbers the recipientsNumbers to set
*/
public void setRecipientsNumber(String recipientsNumbers) {
this.recipientsNumber = recipientsNumbers;
}
public MessageRequest getMessageRequest() {
return messageRequest;
}
public void setMessageRequest(MessageRequest messageRequest) {
this.messageRequest = messageRequest;
}
/*
* @see {@link org.motechproject.mobile.core.model.GatewayRequest#addResponse(org.motechproject.mobile.core.model.GatewayResponse) }
*/
public void addResponse(GatewayResponse response) {
response.setGatewayRequest(this);
this.responseDetails.add(response);
}
/*
* @see {@link org.motechproject.mobile.core.model.GatewayRequest#removeResponse(org.motechproject.mobile.core.model.GatewayResponse) }
*/
public void removeResponse(GatewayResponse response) {
if (this.responseDetails.contains(response)) {
this.responseDetails.remove(response);
}
}
/*
* @see {@link org.motechproject.mobile.core.model.GatewayRequest#addResponse(java.util.List) }
*/
public void addResponse(List<GatewayResponse> responses) {
for (GatewayResponse r : responses) {
r.setGatewayRequest(this);
this.responseDetails.add(r);
}
}
/*
* @see {@link org.motechproject.mobile.core.model.GatewayRequest#removeResponse(java.util.List) }
*/
public void removeResponse(List<GatewayResponse> responses) {
for (GatewayResponse r : responses) {
if (this.responseDetails.contains(r)) {
this.responseDetails.remove(r);
}
}
}
/*
* @return the gatewayRequestDetails
*/
public GatewayRequestDetails getGatewayRequestDetails() {
return gatewayRequestDetails;
}
/*
* @param gatewayRequestDetails the gatewayRequestDetails to set
*/
public void setGatewayRequestDetails(GatewayRequestDetails gatewayRequestDetails) {
this.gatewayRequestDetails = gatewayRequestDetails;
}
/*
* @return the requestId
*/
public String getRequestId() {
return requestId;
}
/*
* @param requestId the requestId to set
*/
public void setRequestId(String requestId) {
this.requestId = requestId;
}
/*
* @return the tryNumber
*/
public int getTryNumber() {
return tryNumber;
}
/*
* @param tryNumber the tryNumber to set
*/
public void setTryNumber(int tryNumber) {
this.tryNumber = tryNumber;
}
/*
* @return the messageStatus
*/
public MStatus getMessageStatus() {
return messageStatus;
}
/*
* @param messageStatus the messageStatus to set
*/
public void setMessageStatus(MStatus messageStatus) {
this.messageStatus = messageStatus;
}
/*
* @return the lastModified
*/
public Date getLastModified() {
return lastModified;
}
/*
* @param lastModified the lastModified to set
*/
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
String newLine = System.getProperty("line.separator");
if (this != null) {
sb.append((this.getId() != null) ? "key=Id value=" + this.getId().toString() : "Id is null ");
sb.append(newLine);
sb.append((this.message != null) ? "key=message value=" + this.message : "message is null ");
sb.append(newLine);
sb.append((this.recipientsNumber != null) ? "key=recipientsNumber value=" + this.recipientsNumber : "recipientsNumber is null ");
sb.append(newLine);
sb.append((this.requestId != null) ? "key=requestId value=" + this.requestId : "requestId is null ");
sb.append(newLine);
sb.append((this.gatewayRequestDetails != null) ? "key=gatewayRequestDetails.Id value=" + this.gatewayRequestDetails.getId() : "gatewayRequestDetails.Id is null ");
sb.append(newLine);
sb.append((this.getMessageRequest() != null) ? "key=messageRequest.Id value=" + this.messageRequest.getId() : "messageRequest.Id is null ");
sb.append(newLine);
sb.append((this.tryNumber != -1) ? "key=tryNumber.Id value=" + Integer.toString(this.tryNumber) : "tryNumber is null ");
sb.append(newLine);
sb.append((this.responseDetails.isEmpty()) ? "key=responseDetails length=" + Integer.toString(this.responseDetails.size()) : "responseDetails is empty ");
sb.append(newLine);
for (Iterator it = this.responseDetails.iterator(); it.hasNext();) {
GatewayResponse resp = (GatewayResponse) it.next();
sb.append((resp != null) ? "key=GatewayResponse.Id value=" + resp.getId().toString() : "GatewayResponse.Id is null ");
sb.append(newLine);
}
sb.append((this.dateSent != null) ? "key=dateSent value=" + this.dateSent.toString() : "dateSent is null ");
sb.append(newLine);
sb.append((this.dateTo != null) ? "key=dateTo value=" + this.dateTo.toString() : "dateTo is null ");
sb.append(newLine);
sb.append((this.dateFrom != null) ? "key=dateFrom value=" + this.dateFrom.toString() : "dateFrom is null ");
sb.append(newLine);
sb.append((this.lastModified != null) ? "key=lastModified value=" + this.lastModified.toString() : "lastModified is null ");
sb.append(newLine);
sb.append((this.messageStatus != null) ? "key=messageStatus value=" + this.messageStatus.toString() : "messageStatus is null ");
sb.append(newLine);
return sb.toString();
} else {
return "Object is null";
}
}
/*
* @return the id
*/
public Long getId() {
return id;
}
/*
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
}
| bsd-3-clause |
jayjaybillings/fern | src/edu.utk.phys.fern/edu/utk/phys/fern/MakeMyDialog.java | 7493 | package edu.utk.phys.fern;
// ----------------------------------------------------------------------------------------------------------
// Example class for testing creation of a modally blocking dialog window.
// Test by executing java MakeMyDialog.
// ----------------------------------------------------------------------------------------------------------
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MakeMyDialog extends Frame {
Font warnFont = new java.awt.Font("SanSerif", Font.BOLD, 12);
FontMetrics warnFontMetrics = getFontMetrics(warnFont);
public static void main (String[] args) {
MakeMyDialog md = new MakeMyDialog(50,50,300,100,Color.black,
Color.white,"A Frame", "A frame from which warning is launched",true);
}
// ------------------------------------------------------------
// Constructor
// ------------------------------------------------------------
public MakeMyDialog (int X, int Y, int width, int height, Color fg, Color bg, String title,
String text, boolean oneLine) {
// Create a frame from which we will launch a dialog warning window
final Frame mw = new Frame(title);
mw.setLayout(new BorderLayout());
mw.setSize(width,height);
mw.setLocation(X,Y);
Label hT = new Label(text,Label.CENTER);
hT.setForeground(fg);
hT.setBackground(bg);
hT.setFont(warnFont);
mw.add("Center", hT);
mw.setTitle(title);
// Add show warning button
Panel botPanel = new Panel();
botPanel.setBackground(Color.lightGray);
Label label1 = new Label();
Label label2 = new Label();
Button showButton = new Button("Show Modal Warning Window");
botPanel.add(label1);
botPanel.add(showButton);
botPanel.add(label2);
// Add inner class event handler for show warning button. This must be
// added to the showButton before botPanel is added to mw.
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
MakeMyDialog.this.makeTheWarning(200,200,200,100,Color.black,
Color.lightGray,"Warning","Warning message",
true, MakeMyDialog.this);
}
});
mw.add("South", botPanel);
// Add window closing button (inner class)
mw.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
mw.hide();
mw.dispose();
System.exit(0);
}
});
mw.show();
}
// -----------------------------------------------------------------------------------------------------------------------
// The method makeTheWarning creates a modal warning window when invoked
// from within an object that subclasses Frame. The window is
// modally blocked (the window from which the warning window is
// launched is blocked from further input until the warning window
// is dismissed by the user). Method arguments:
//
// X = x-position of window on screen (relative upper left)
// Y = y-position of window on screen (relative upper left)
// width = width of window
// height = height of window
// fg = foreground (font) color
// bg = background color
// title = title string
// text = warning string text
// oneLine = display as one-line Label (true)
// or multiline TextArea (false)
// frame = A Frame that is the parent window modally
// blocked by the warning window. If the parent
// class from which this method is invoked extends
// Frame, this argument can be just "this" (or
// "ParentClass.this" if invoked from an
// inner class event handler of ParentClass).
// Otherwise, it must be the name of an object derived from
// Frame that represents the window modally blocked.
//
// If oneLine is true, you must make width large enough to display all
// text on one line.
// -------------------------------------------------------------------------------------------------------------------------
public void makeTheWarning (int X, int Y, int width, int height,
Color fg, Color bg, String title,
String text, boolean oneLine, Frame frame) {
Font warnFont = new java.awt.Font("SanSerif", Font.BOLD, 12);
FontMetrics warnFontMetrics = getFontMetrics(warnFont);
// Create Dialog window with modal blocking set to true.
// Make final so inner class below can access it.
final Dialog mww = new Dialog(frame, title, true);
mww.setLayout(new BorderLayout());
mww.setSize(width,height);
mww.setLocation(X,Y);
// Use Label for 1-line warning
if (oneLine) {
Label hT = new Label(text,Label.CENTER);
hT.setForeground(fg);
hT.setBackground(bg);
hT.setFont(warnFont);
mww.add("Center", hT);
// Use TextArea for multiline warning
} else {
TextArea hT = new TextArea("",height,width,
TextArea.SCROLLBARS_NONE);
hT.setEditable(false);
hT.setForeground(fg);
hT.setBackground(bg); // no effect once setEditable (false)?
hT.setFont(warnFont);
mww.add("Center", hT);
hT.appendText(text);
}
mww.setTitle(title);
// Add dismiss button
Panel botPanel = new Panel();
botPanel.setBackground(Color.lightGray);
Label label1 = new Label();
Label label2 = new Label();
Button dismissButton = new Button("Dismiss");
botPanel.add(label1);
botPanel.add(dismissButton);
botPanel.add(label2);
// Add inner class event handler for Dismiss button. This must be
// added to the dismissButton before botPanel is added to mww.
dismissButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
mww.hide();
mww.dispose();
}
});
mww.add("South", botPanel);
// Add window closing button (inner class)
mww.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
mww.hide();
mww.dispose();
}
});
mww.show(); // Note that this show must come after all the above
// additions; otherwise they are not added before the
// window is displayed.
}
} /* End class MakeMyDialog */
| bsd-3-clause |
KommuSoft/jahmm | jahmm/src/jahmm/jadetree/DecisionLeaf.java | 186 | package jahmm.jadetree;
/**
*
* @author kommusoft
* @param <TSource>
*/
public interface DecisionLeaf<TSource> extends DecisionRealNode<TSource> {
public void expandThis();
}
| bsd-3-clause |
OBHITA/Consent2Share | DS4P/access-control-service/pep-sts-war/src/main/java/gov/samhsa/acs/pep/sts/PasswordCallbackHandler.java | 1032 | package gov.samhsa.acs.pep.sts;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.wss4j.common.ext.WSPasswordCallback;
public class PasswordCallbackHandler implements CallbackHandler {
@Override
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof WSPasswordCallback) {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
if (pc.getUsage() == WSPasswordCallback.DECRYPT
|| pc.getUsage() == WSPasswordCallback.SIGNATURE) {
if ("mystskey".equals(pc.getIdentifier())) {
pc.setPassword("stskpass");
}
} else if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN) {
// TODO: remove hard coding
if ("alice".equals(pc.getIdentifier())) {
pc.setPassword("clarinet");
}
}
}
}
}
}
| bsd-3-clause |
jrialland/jrc | src/main/java/net/jr/jrc/utils/IOUtils.java | 1929 |
package net.jr.jrc.utils;
import java.io.*;
import java.nio.channels.FileChannel;
public final class IOUtils {
private static final int DEFAULT_BUF_SIZE = 4096;
public static InputStream readResource(String path) {
return IOUtils.class.getClassLoader().getResourceAsStream(path);
}
public static InputStream readResource(Class<?> klass, String resName) {
final String path = klass.getPackage().getName().replace('.', '/') + '/' + resName;
return IOUtils.class.getClassLoader().getResourceAsStream(path);
}
public static String readFile(String filename) throws IOException {
return readFully(new FileReader(filename));
}
public static String readFully(Reader in) {
char[] buf = new char[DEFAULT_BUF_SIZE];
int c = 0;
StringWriter sw = new StringWriter();
try {
while ((c = in.read(buf)) > -1) {
sw.write(buf, 0, c);
}
in.close();
return sw.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static byte[] readFully(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
IOUtils.copy(new BufferedInputStream(is), baos);
} catch (IOException e) {
throw new RuntimeException(e);
}
return baos.toByteArray();
}
public static long copy(InputStream is, OutputStream os) throws IOException {
if (is instanceof FileInputStream && os instanceof FileOutputStream) {
FileChannel inChannel = ((FileInputStream) is).getChannel();
FileChannel outChannel = ((FileOutputStream) os).getChannel();
return inChannel.transferTo(0, inChannel.size(), outChannel);
} else {
byte[] buff = new byte[DEFAULT_BUF_SIZE];
int c;
long copied = 0;
while ((c = is.read(buff)) > -1) {
os.write(buff, 0, c);
copied += c;
}
is.close();
os.flush();
return copied;
}
}
}
| bsd-3-clause |
arnaudsj/carrot2 | core/carrot2-util-attribute/src-test/org/carrot2/util/attribute/TestProcessing.java | 490 |
/*
* Carrot2 project.
*
* Copyright (C) 2002-2010, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.util.attribute;
import java.lang.annotation.*;
/**
* A test attribute filtering annotation.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TestProcessing
{
}
| bsd-3-clause |
sonyxperiadev/logdog | logdog/src/logdog/logdog.java | 4250 | /**
* Copyright (c) 2013, Sony Mobile Communications Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This file is part of logdog.
*/
package logdog;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import logdog.controller.MainController;
import logdog.utils.ConsoleLogger;
import logdog.utils.FileLogger;
import logdog.utils.Logger;
import logdog.utils.Utils;
import logdog.view.Splash;
import logdog.view.UIUtils;
public class logdog {
private static final String sName = "logdog";
static final String sThisVersion = "0.9.5";
public static boolean DEBUG = false;
private static final String NEWER_VERSION_TITLE = "Newer version";
private static final String NEWER_VERSION_MSG_FORMAT =
"\nThere is a newer version of %1$s available (%s). You are using version %s.\n\n" +
"Please exit the program and run this command in a terminal window to upgrade:\n" +
"$ sudo apt-get update\n$ sudo apt-get install %1$s\n\n";
private static final String DONT_SHOW_AGAIN = "Do not show this message again.";
public static String getFriendlyVersion() {
return String.format("%s %s", sName, sThisVersion);
}
private static void parseArgs(String[] args) {
if (args.length <= 0) {
return;
}
for (int argIdx = 0; argIdx < args.length; ++argIdx) {
final String crntOption = args[argIdx];
if (crntOption.equals("-lf")) {
Logger.addListener(new FileLogger());
} else if (crntOption.equals("-lc")) {
Logger.addListener(new ConsoleLogger());
} else if (crntOption.equals("-d")) {
DEBUG = true;
} else if (crntOption.equals("-h")) {
System.out.printf("usage: %s [-lf] [-lc] [-d] [-h]\n", sName);
System.out.println("-lf log to file");
System.out.println("-lc log to console");
System.out.println("-d debug, you also need either -lf or -lc");
System.out.println("-h this help");
System.exit(0);
} else if (!Utils.emptyString(crntOption)) {
System.out.printf("Unknown option: %s\n", crntOption);
}
}
}
public static void main(String[] args) {
parseArgs(args);
Prefs prefs = new Prefs();
UIUtils.load(prefs);
new Splash("/resources/splash-whitebg.png");
// Model created when loading files.
MainController mainController = new MainController();
mainController.showChartView(prefs);
}
}
| bsd-3-clause |
pongad/api-client-staging | generated/java/proto-google-cloud-vision-v1p2beta1/src/main/java/com/google/cloud/vision/v1p2beta1/Position.java | 18966 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/vision/v1p2beta1/geometry.proto
package com.google.cloud.vision.v1p2beta1;
/**
* <pre>
* A 3D position in the image, used primarily for Face detection landmarks.
* A valid Position must have both x and y coordinates.
* The position coordinates are in the same scale as the original image.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p2beta1.Position}
*/
public final class Position extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.cloud.vision.v1p2beta1.Position)
PositionOrBuilder {
private static final long serialVersionUID = 0L;
// Use Position.newBuilder() to construct.
private Position(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Position() {
x_ = 0F;
y_ = 0F;
z_ = 0F;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Position(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 13: {
x_ = input.readFloat();
break;
}
case 21: {
y_ = input.readFloat();
break;
}
case 29: {
z_ = input.readFloat();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.vision.v1p2beta1.GeometryProto.internal_static_google_cloud_vision_v1p2beta1_Position_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p2beta1.GeometryProto.internal_static_google_cloud_vision_v1p2beta1_Position_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p2beta1.Position.class, com.google.cloud.vision.v1p2beta1.Position.Builder.class);
}
public static final int X_FIELD_NUMBER = 1;
private float x_;
/**
* <pre>
* X coordinate.
* </pre>
*
* <code>float x = 1;</code>
*/
public float getX() {
return x_;
}
public static final int Y_FIELD_NUMBER = 2;
private float y_;
/**
* <pre>
* Y coordinate.
* </pre>
*
* <code>float y = 2;</code>
*/
public float getY() {
return y_;
}
public static final int Z_FIELD_NUMBER = 3;
private float z_;
/**
* <pre>
* Z coordinate (or depth).
* </pre>
*
* <code>float z = 3;</code>
*/
public float getZ() {
return z_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (x_ != 0F) {
output.writeFloat(1, x_);
}
if (y_ != 0F) {
output.writeFloat(2, y_);
}
if (z_ != 0F) {
output.writeFloat(3, z_);
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (x_ != 0F) {
size += com.google.protobuf.CodedOutputStream
.computeFloatSize(1, x_);
}
if (y_ != 0F) {
size += com.google.protobuf.CodedOutputStream
.computeFloatSize(2, y_);
}
if (z_ != 0F) {
size += com.google.protobuf.CodedOutputStream
.computeFloatSize(3, z_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.vision.v1p2beta1.Position)) {
return super.equals(obj);
}
com.google.cloud.vision.v1p2beta1.Position other = (com.google.cloud.vision.v1p2beta1.Position) obj;
boolean result = true;
result = result && (
java.lang.Float.floatToIntBits(getX())
== java.lang.Float.floatToIntBits(
other.getX()));
result = result && (
java.lang.Float.floatToIntBits(getY())
== java.lang.Float.floatToIntBits(
other.getY()));
result = result && (
java.lang.Float.floatToIntBits(getZ())
== java.lang.Float.floatToIntBits(
other.getZ()));
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + X_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(
getX());
hash = (37 * hash) + Y_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(
getY());
hash = (37 * hash) + Z_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(
getZ());
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.vision.v1p2beta1.Position parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p2beta1.Position parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p2beta1.Position parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p2beta1.Position parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p2beta1.Position parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p2beta1.Position parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p2beta1.Position parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p2beta1.Position parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1p2beta1.Position parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p2beta1.Position parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1p2beta1.Position parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p2beta1.Position parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.vision.v1p2beta1.Position prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* A 3D position in the image, used primarily for Face detection landmarks.
* A valid Position must have both x and y coordinates.
* The position coordinates are in the same scale as the original image.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p2beta1.Position}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.cloud.vision.v1p2beta1.Position)
com.google.cloud.vision.v1p2beta1.PositionOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.vision.v1p2beta1.GeometryProto.internal_static_google_cloud_vision_v1p2beta1_Position_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p2beta1.GeometryProto.internal_static_google_cloud_vision_v1p2beta1_Position_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p2beta1.Position.class, com.google.cloud.vision.v1p2beta1.Position.Builder.class);
}
// Construct using com.google.cloud.vision.v1p2beta1.Position.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
x_ = 0F;
y_ = 0F;
z_ = 0F;
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.cloud.vision.v1p2beta1.GeometryProto.internal_static_google_cloud_vision_v1p2beta1_Position_descriptor;
}
public com.google.cloud.vision.v1p2beta1.Position getDefaultInstanceForType() {
return com.google.cloud.vision.v1p2beta1.Position.getDefaultInstance();
}
public com.google.cloud.vision.v1p2beta1.Position build() {
com.google.cloud.vision.v1p2beta1.Position result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.cloud.vision.v1p2beta1.Position buildPartial() {
com.google.cloud.vision.v1p2beta1.Position result = new com.google.cloud.vision.v1p2beta1.Position(this);
result.x_ = x_;
result.y_ = y_;
result.z_ = z_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.vision.v1p2beta1.Position) {
return mergeFrom((com.google.cloud.vision.v1p2beta1.Position)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vision.v1p2beta1.Position other) {
if (other == com.google.cloud.vision.v1p2beta1.Position.getDefaultInstance()) return this;
if (other.getX() != 0F) {
setX(other.getX());
}
if (other.getY() != 0F) {
setY(other.getY());
}
if (other.getZ() != 0F) {
setZ(other.getZ());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.vision.v1p2beta1.Position parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.vision.v1p2beta1.Position) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private float x_ ;
/**
* <pre>
* X coordinate.
* </pre>
*
* <code>float x = 1;</code>
*/
public float getX() {
return x_;
}
/**
* <pre>
* X coordinate.
* </pre>
*
* <code>float x = 1;</code>
*/
public Builder setX(float value) {
x_ = value;
onChanged();
return this;
}
/**
* <pre>
* X coordinate.
* </pre>
*
* <code>float x = 1;</code>
*/
public Builder clearX() {
x_ = 0F;
onChanged();
return this;
}
private float y_ ;
/**
* <pre>
* Y coordinate.
* </pre>
*
* <code>float y = 2;</code>
*/
public float getY() {
return y_;
}
/**
* <pre>
* Y coordinate.
* </pre>
*
* <code>float y = 2;</code>
*/
public Builder setY(float value) {
y_ = value;
onChanged();
return this;
}
/**
* <pre>
* Y coordinate.
* </pre>
*
* <code>float y = 2;</code>
*/
public Builder clearY() {
y_ = 0F;
onChanged();
return this;
}
private float z_ ;
/**
* <pre>
* Z coordinate (or depth).
* </pre>
*
* <code>float z = 3;</code>
*/
public float getZ() {
return z_;
}
/**
* <pre>
* Z coordinate (or depth).
* </pre>
*
* <code>float z = 3;</code>
*/
public Builder setZ(float value) {
z_ = value;
onChanged();
return this;
}
/**
* <pre>
* Z coordinate (or depth).
* </pre>
*
* <code>float z = 3;</code>
*/
public Builder clearZ() {
z_ = 0F;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.vision.v1p2beta1.Position)
}
// @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Position)
private static final com.google.cloud.vision.v1p2beta1.Position DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vision.v1p2beta1.Position();
}
public static com.google.cloud.vision.v1p2beta1.Position getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Position>
PARSER = new com.google.protobuf.AbstractParser<Position>() {
public Position parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Position(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Position> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Position> getParserForType() {
return PARSER;
}
public com.google.cloud.vision.v1p2beta1.Position getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| bsd-3-clause |
darkrsw/safe | src/main/java/kr/ac/kaist/jsaf/nodes/Expr.java | 1092 | package kr.ac.kaist.jsaf.nodes;
import java.lang.Double;
import java.lang.String;
import java.math.BigInteger;
import java.io.Writer;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.LinkedList;
import kr.ac.kaist.jsaf.nodes_util.*;
import kr.ac.kaist.jsaf.useful.*;
import edu.rice.cs.plt.tuple.Option;
/**
* Class Expr, a component of the ASTGen-generated composite hierarchy.
* Note: null is not allowed as a value for any field.
* @version Generated automatically by ASTGen at Mon Nov 21 18:10:55 CET 2016
*/
@SuppressWarnings("unused")
public abstract class Expr extends AbstractNode {
/**
* Constructs a Expr.
* @throws java.lang.IllegalArgumentException If any parameter to the constructor is null.
*/
public Expr(ASTSpanInfo in_info) {
super(in_info);
}
public abstract int generateHashCode();
/**
* Empty constructor, for reflective access. Clients are
* responsible for manually instantiating each field.
*/
protected Expr() {
}
}
| bsd-3-clause |
apptentive/apptentive-android | apptentive/src/main/java/com/apptentive/android/sdk/storage/Saveable.java | 413 | /*
* Copyright (c) 2017, Apptentive, Inc. All Rights Reserved.
* Please refer to the LICENSE file for the terms and conditions
* under which redistribution and use of this file is permitted.
*/
package com.apptentive.android.sdk.storage;
import java.io.Serializable;
public interface Saveable extends Serializable {
void setDataChangedListener(DataChangedListener listener);
void notifyDataChanged();
}
| bsd-3-clause |
NCIP/cagrid | cagrid/Software/core/caGrid/projects/syncgts/src/gov/nih/nci/cagrid/syncgts/service/globus/resource/MetadataConfiguration.java | 615 | package gov.nih.nci.cagrid.syncgts.service.globus.resource;
public class MetadataConfiguration {
private String registrationTemplateFile;
private boolean performRegistration;
public boolean shouldPerformRegistration() {
return performRegistration;
}
public void setPerformRegistration(boolean performRegistration) {
this.performRegistration = performRegistration;
}
public String getRegistrationTemplateFile() {
return registrationTemplateFile;
}
public void setRegistrationTemplateFile(String registrationTemplateFile) {
this.registrationTemplateFile = registrationTemplateFile;
}
}
| bsd-3-clause |
bwaldvogel/mongo-java-server | postgresql-backend/src/test/java/de/bwaldvogel/mongo/backend/postgresql/PostgresqlBackendTest.java | 9876 | package de.bwaldvogel.mongo.backend.postgresql;
import static de.bwaldvogel.mongo.backend.TestUtils.json;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.Arrays;
import java.util.Collections;
import java.util.UUID;
import org.bson.Document;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import com.mongodb.DuplicateKeyException;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.IndexOptions;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import de.bwaldvogel.mongo.MongoBackend;
import de.bwaldvogel.mongo.MongoDatabase;
import de.bwaldvogel.mongo.backend.AbstractBackendTest;
import de.bwaldvogel.mongo.backend.AbstractTest;
import de.bwaldvogel.mongo.oplog.NoopOplog;
public class PostgresqlBackendTest extends AbstractBackendTest {
private static GenericContainer<?> postgresContainer;
private static HikariDataSource dataSource;
@BeforeAll
static void initializeDataSource() {
String password = UUID.randomUUID().toString();
postgresContainer = new GenericContainer<>("postgres:9.6-alpine")
.withTmpFs(Collections.singletonMap("/var/lib/postgresql/data", "rw"))
.withEnv("POSTGRES_USER", "mongo-java-server-test")
.withEnv("POSTGRES_PASSWORD", password)
.withEnv("POSTGRES_DB", "mongo-java-server-test")
.withExposedPorts(5432);
postgresContainer.start();
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:" + postgresContainer.getFirstMappedPort() + "/mongo-java-server-test");
config.setUsername("mongo-java-server-test");
config.setPassword(password);
config.setMaximumPoolSize(5);
dataSource = new HikariDataSource(config);
}
@AfterAll
static void closeDataSource() {
dataSource.close();
postgresContainer.stop();
}
@Override
protected MongoBackend createBackend() throws Exception {
PostgresqlBackend backend = new PostgresqlBackend(dataSource, clock);
for (String db : Arrays.asList(TEST_DATABASE_NAME, OTHER_TEST_DATABASE_NAME)) {
MongoDatabase mongoDatabase = backend.openOrCreateDatabase(db);
mongoDatabase.drop(NoopOplog.get());
}
return backend;
}
@Override
public void testCompoundSparseUniqueIndex() throws Exception {
assumeStrictTests();
super.testCompoundSparseUniqueIndex();
}
@Override
public void testCompoundSparseUniqueIndexOnEmbeddedDocuments() throws Exception {
assumeStrictTests();
super.testCompoundSparseUniqueIndexOnEmbeddedDocuments();
}
@Override
public void testSparseUniqueIndexOnEmbeddedDocument() throws Exception {
assumeStrictTests();
super.testSparseUniqueIndexOnEmbeddedDocument();
}
@Override
public void testSecondarySparseUniqueIndex() throws Exception {
assumeStrictTests();
super.testSecondarySparseUniqueIndex();
}
@Override
public void testUniqueIndexWithDeepDocuments() throws Exception {
assumeStrictTests();
super.testUniqueIndexWithDeepDocuments();
}
@Override
public void testOrderByEmbeddedDocument() throws Exception {
assumeStrictTests();
super.testOrderByEmbeddedDocument();
}
@Override
public void testOrderByMissingAndNull() throws Exception {
assumeStrictTests();
super.testOrderByMissingAndNull();
}
@Override
public void testSortDocuments() throws Exception {
assumeStrictTests();
super.testSortDocuments();
}
@Override
public void testFindAndOrderByWithListValues() throws Exception {
assumeStrictTests();
super.testFindAndOrderByWithListValues();
}
@Override
public void testSort() {
assumeStrictTests();
super.testSort();
}
@Override
public void testInsertQueryAndSortBinaryTypes() throws Exception {
assumeStrictTests();
super.testInsertQueryAndSortBinaryTypes();
}
@Override
public void testUuidAsId() throws Exception {
assumeStrictTests();
super.testUuidAsId();
}
@Override
public void testTypeMatching() throws Exception {
assumeStrictTests();
super.testTypeMatching();
}
@Override
public void testDecimal128() throws Exception {
assumeStrictTests();
super.testDecimal128();
}
@Override
public void testDecimal128_Inc() throws Exception {
assumeStrictTests();
super.testDecimal128_Inc();
}
@Override
public void testArrayNe() throws Exception {
assumeStrictTests();
super.testArrayNe();
}
@Override
@Test
public void testRegExQuery() throws Exception {
assumeStrictTests();
super.testRegExQuery();
}
@Override
public void testInsertAndFindJavaScriptContent() throws Exception {
assumeStrictTests();
super.testInsertAndFindJavaScriptContent();
}
@Override
public void testMultikeyIndex_simpleArrayValues() throws Exception {
assumeStrictTests();
super.testMultikeyIndex_simpleArrayValues();
}
@Override
public void testCompoundMultikeyIndex_simpleArrayValues() throws Exception {
assumeStrictTests();
super.testCompoundMultikeyIndex_simpleArrayValues();
}
@Override
public void testCompoundMultikeyIndex_documents() throws Exception {
assumeStrictTests();
super.testCompoundMultikeyIndex_documents();
}
@Override
public void testCompoundMultikeyIndex_multiple_document_keys() throws Exception {
assumeStrictTests();
super.testCompoundMultikeyIndex_multiple_document_keys();
}
@Override
public void testCompoundMultikeyIndex_deepDocuments() throws Exception {
assumeStrictTests();
super.testCompoundMultikeyIndex_deepDocuments();
}
@Override
public void testCompoundMultikeyIndex_threeKeys() throws Exception {
assumeStrictTests();
super.testCompoundMultikeyIndex_threeKeys();
}
@Override
public void testEmbeddedSort_arrayOfDocuments() {
assumeStrictTests();
super.testEmbeddedSort_arrayOfDocuments();
}
@Override
public void testAddUniqueIndexOnExistingDocuments_violatingUniqueness() throws Exception {
collection.insertOne(json("_id: 1, value: 'a'"));
collection.insertOne(json("_id: 2, value: 'b'"));
collection.insertOne(json("_id: 3, value: 'c'"));
collection.insertOne(json("_id: 4, value: 'b'"));
assertThatExceptionOfType(DuplicateKeyException.class)
.isThrownBy(() -> collection.createIndex(json("value: 1"), new IndexOptions().unique(true)))
.withMessage("Write failed with error code 11000 and error message " +
"'E11000 duplicate key error collection: testdb.testcoll index: value_1 dup key: " +
"ERROR: could not create unique index \"testcoll_value_1\"\n Detail: Key ((data ->> 'value'::text))=(b) is duplicated.'");
assertThat(collection.listIndexes())
.containsExactly(json("name: '_id_', ns: 'testdb.testcoll', key: {_id: 1}, v: 2"));
collection.insertOne(json("_id: 5, value: 'a'"));
}
@Override
public void testGetKeyValues_multiKey_document_nested_objects() throws Exception {
assumeStrictTests();
super.testGetKeyValues_multiKey_document_nested_objects();
}
@Override
public void testOldAndNewUuidTypes() throws Exception {
assumeStrictTests();
}
@Test
public void testNewUuidDuplicate() throws Exception {
Document document1 = new Document("_id", UUID.fromString("5542cbb9-7833-96a2-b456-f13b6ae1bc80"));
try (MongoClient standardUuidClient = getClientWithStandardUuid()) {
MongoCollection<Document> collectionStandardUuid = standardUuidClient.getDatabase(AbstractTest.collection.getNamespace().getDatabaseName()).getCollection(AbstractTest.collection.getNamespace().getCollectionName());
collectionStandardUuid.insertOne(document1);
assertMongoWriteException(() -> collectionStandardUuid.insertOne(document1),
11000, null, "E11000 duplicate key error collection: testdb.testcoll index: ERROR: duplicate key value violates unique constraint \"testcoll__id_\"\n" +
" Detail: Key ((data ->> '_id'::text))=([\"java.util.UUID\",\"5542cbb9-7833-96a2-b456-f13b6ae1bc80\"]) already exists.");
Document document2 = new Document("_id", UUID.fromString("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"));
collectionStandardUuid.insertOne(document2);
assertThat(collectionStandardUuid.find())
.containsExactlyInAnyOrder(
document1,
document2
);
}
}
@Override
public void testUpdatePushSlice() throws Exception {
assumeStrictTests();
super.testUpdatePushSlice();
}
@Override
public void testUpdatePushSortAndSlice() throws Exception {
assumeStrictTests();
super.testUpdatePushSortAndSlice();
}
@Override
public void testMinMaxKeyRangeQuery() throws Exception {
assumeStrictTests();
super.testMinMaxKeyRangeQuery();
}
private void assumeStrictTests() {
Assumptions.assumeTrue(Boolean.getBoolean(PostgresqlBackend.class.getSimpleName() + ".strictTest"));
}
}
| bsd-3-clause |
liry/gooddata-java | src/main/java/com/gooddata/gdc/GdcSardine.java | 1163 | /**
* Copyright (C) 2004-2016, GoodData(R) Corporation. All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
package com.gooddata.gdc;
import static com.gooddata.util.Validate.notNull;
import com.github.sardine.impl.SardineImpl;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
/**
* This class extends SardineImpl, connections were not correctly closed by parent
*/
class GdcSardine extends SardineImpl {
public GdcSardine(HttpClientBuilder builder) {
super(builder);
}
/**
* had to be overriden, because parent method did not close connection after execution
*/
@Override
protected <T> T execute(HttpRequestBase request, ResponseHandler<T> responseHandler) throws IOException {
try {
notNull(request,"request");
return super.execute(request, responseHandler);
} finally {
request.releaseConnection();
}
}
}
| bsd-3-clause |
xizi-xu/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/alert/DefaultAlertService.java | 42930 | /*
* Copyright (c) 2016, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.dva.argus.service.alert;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.persist.Transactional;
import com.salesforce.dva.argus.entity.Alert;
import com.salesforce.dva.argus.entity.History;
import com.salesforce.dva.argus.entity.History.JobStatus;
import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.entity.Notification;
import com.salesforce.dva.argus.entity.PrincipalUser;
import com.salesforce.dva.argus.entity.Trigger;
import com.salesforce.dva.argus.service.AlertService;
import com.salesforce.dva.argus.service.AuditService;
import com.salesforce.dva.argus.service.HistoryService;
import com.salesforce.dva.argus.service.MQService;
import com.salesforce.dva.argus.service.MailService;
import com.salesforce.dva.argus.service.MetricService;
import com.salesforce.dva.argus.service.MonitorService;
import com.salesforce.dva.argus.service.MonitorService.Counter;
import com.salesforce.dva.argus.service.NotifierFactory;
import com.salesforce.dva.argus.service.TSDBService;
import com.salesforce.dva.argus.service.jpa.DefaultJPAService;
import com.salesforce.dva.argus.service.metric.transform.MissingDataException;
import com.salesforce.dva.argus.system.SystemConfiguration;
import com.salesforce.dva.argus.util.Cron;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import static com.salesforce.dva.argus.service.MQService.MQQueue.ALERT;
import static com.salesforce.dva.argus.system.SystemAssert.requireArgument;
import static java.math.BigInteger.ZERO;
/**
* Default implementation of the alert service.
*
* @author Tom Valine (tvaline@salesforce.com), Raj sarkapally (rsarkapally@salesforce.com)
*/
public class DefaultAlertService extends DefaultJPAService implements AlertService {
//~ Static fields/initializers *******************************************************************************************************************
private static final String USERTAG = "user";
private static final ThreadLocal<SimpleDateFormat> DATE_FORMATTER = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf;
}
};
//~ Instance fields ******************************************************************************************************************************
private final Logger _logger = LoggerFactory.getLogger(DefaultAlertService.class);
private final Provider<EntityManager> _emProvider;
private final MQService _mqService;
private final TSDBService _tsdbService;
private final MetricService _metricService;
private final MailService _mailService;
private final SystemConfiguration _configuration;
private final HistoryService _historyService;
private final MonitorService _monitorService;
private final NotifierFactory _notifierFactory;
private final ObjectMapper _mapper = new ObjectMapper();
private static NotificationsCache _notificationsCache = null;
//~ Constructors *********************************************************************************************************************************
/**
* Creates a new DefaultAlertService object.
*
* @param mqService The MQ service instance to use. Cannot be null.
* @param metricService The Metric service instance to use. Cannot be null.
* @param auditService The audit service instance to use. Cannot be null.
* @param mailService The mail service instance to use. Cannot be null.
* @param configuration The system configuration instance to use. Cannot be null.
* @param historyService The job history service instance to use. Cannot be null.
* @param monitorService The monitor service instance to use. Cannot be null.
*/
@Inject
public DefaultAlertService(SystemConfiguration configuration, MQService mqService, MetricService metricService,
AuditService auditService, TSDBService tsdbService, MailService mailService, HistoryService historyService,
MonitorService monitorService, NotifierFactory notifierFactory, Provider<EntityManager> emProvider) {
super(auditService, configuration);
requireArgument(mqService != null, "MQ service cannot be null.");
requireArgument(metricService != null, "Metric service cannot be null.");
requireArgument(tsdbService != null, "TSDB service cannot be null.");
_tsdbService = tsdbService;
_mqService = mqService;
_metricService = metricService;
_mailService = mailService;
_configuration = configuration;
_historyService = historyService;
_monitorService = monitorService;
_notifierFactory = notifierFactory;
_emProvider = emProvider;
_initializeObjectMapper();
}
//~ Methods **************************************************************************************************************************************
private void _initializeObjectMapper() {
SimpleModule module = new SimpleModule();
module.addSerializer(Alert.class, new Alert.Serializer());
module.addSerializer(Trigger.class, new Trigger.Serializer());
module.addSerializer(Notification.class, new Notification.Serializer());
module.addSerializer(PrincipalUser.class, new Alert.PrincipalUserSerializer());
module.addDeserializer(Alert.class, new Alert.Deserializer());
_mapper.registerModule(module);
}
@Override
@Transactional
public Alert updateAlert(Alert alert) {
requireNotDisposed();
requireArgument(alert != null, "Cannot update a null alert");
boolean isCronValid = Cron.isCronEntryValid(alert.getCronEntry());
if(!isCronValid) {
throw new RuntimeException("Input cron entry - " + alert.getCronEntry() + " is invalid");
}
alert.setModifiedDate(new Date());
EntityManager em = _emProvider.get();
Alert result = mergeEntity(em, alert);
em.flush();
_logger.debug("Updated alert to : {}", result);
_auditService.createAudit("Updated alert to : {0}", result, result);
return result;
}
@Override
@Transactional
public void deleteAlert(String name, PrincipalUser owner) {
requireNotDisposed();
requireArgument(name != null && !name.isEmpty(), "Name cannot be null or empty.");
requireArgument(owner != null, "Owner cannot be null.");
Alert alert = findAlertByNameAndOwner(name, owner);
deleteAlert(alert);
}
@Override
@Transactional
public void deleteAlert(Alert alert) {
requireNotDisposed();
requireArgument(alert != null, "Alert cannot be null.");
_logger.debug("Deleting an alert {}.", alert);
EntityManager em = _emProvider.get();
deleteEntity(em, alert);
em.flush();
}
@Override
@Transactional
public void markAlertForDeletion(String name, PrincipalUser owner) {
requireNotDisposed();
requireArgument(name != null && !name.isEmpty(), "Name cannot be null or empty.");
requireArgument(owner != null, "Owner cannot be null.");
Alert alert = findAlertByNameAndOwner(name, owner);
markAlertForDeletion(alert);
}
@Override
@Transactional
public void markAlertForDeletion(Alert alert) {
requireNotDisposed();
requireArgument(alert != null, "Alert cannot be null.");
_logger.debug("Marking alert for deletion {}.", alert);
EntityManager em = _emProvider.get();
alert.setDeleted(true);
alert.setEnabled(false);
alert.setName(alert.getName() + System.currentTimeMillis());
Alert result = mergeEntity(em, alert);
em.flush();
_logger.debug("Set delete marker for alert : {}", result);
_auditService.createAudit("Set delete marker for alert : {0}", result, result);
}
@Override
public List<Alert> findAlertsMarkedForDeletion() {
requireNotDisposed();
return findEntitiesMarkedForDeletion(_emProvider.get(), Alert.class, -1);
}
@Override
public List<Alert> findAlertsMarkedForDeletion(final int limit) {
requireNotDisposed();
requireArgument(limit > 0, "Limit must be greater than 0.");
return findEntitiesMarkedForDeletion(_emProvider.get(), Alert.class, limit);
}
@Override
public List<Alert> findAlertsByOwner(PrincipalUser owner, boolean metadataOnly) {
requireNotDisposed();
requireArgument(owner != null, "Owner cannot be null.");
return metadataOnly ? Alert.findByOwnerMeta(_emProvider.get(), owner) : Alert.findByOwner(_emProvider.get(), owner);
}
@Override
public Alert findAlertByPrimaryKey(BigInteger id) {
requireNotDisposed();
requireArgument(id != null && id.compareTo(ZERO) > 0, "ID must be a positive non-zero value.");
EntityManager em = _emProvider.get();
em.getEntityManagerFactory().getCache().evictAll();
Alert result = Alert.findByPrimaryKey(em, id, Alert.class);
_logger.debug("Query for alert having id {} resulted in : {}", id, result);
return result;
}
@Override
public List<Alert> findAlertsByPrimaryKeys(List<BigInteger> ids) {
requireNotDisposed();
requireArgument(ids != null && !ids.isEmpty(), "IDs list cannot be null or empty.");
EntityManager em = _emProvider.get();
em.getEntityManagerFactory().getCache().evictAll();
List<Alert> result = Alert.findByPrimaryKeys(em, ids, Alert.class);
_logger.debug("Query for alerts having ids {} resulted in : {}", ids, result);
return result;
}
@Override
public void updateNotificationsActiveStatusAndCooldown(List<Notification> notifications) {
List<BigInteger> ids = notifications.stream().map(x -> x.getId()).collect(Collectors.toList());
_logger.debug("Updating notifications: {}", ids);
if(_notificationsCache == null) {
synchronized(DefaultAlertService.class) {
if(_notificationsCache == null) {
_notificationsCache = new NotificationsCache(_emProvider);
}
}
}
// if cache is refreshed, we read the cooldown and trigger info from cache, else we query the db directly
if(_notificationsCache.isNotificationsCacheRefreshed()) {
for(Notification notification : notifications) {
if(_notificationsCache.getNotificationActiveStatusMap().get(notification.getId())!=null) {
notification.setActiveStatusMap(_notificationsCache.getNotificationActiveStatusMap().get(notification.getId()));
}else {
notification.getActiveStatusMap().clear();
}
if(_notificationsCache.getNotificationCooldownExpirationMap().get(notification.getId())!=null) {
notification.setCooldownExpirationMap(_notificationsCache.getNotificationCooldownExpirationMap().get(notification.getId()));
}else {
notification.getCooldownExpirationMap().clear();
}
}
}else {
Notification.updateActiveStatusAndCooldown(_emProvider.get(), notifications);
}
}
@Override
@Transactional
public List<History> executeScheduledAlerts(int alertCount, int timeout) {
requireNotDisposed();
requireArgument(alertCount > 0, "Alert count must be greater than zero.");
requireArgument(timeout > 0, "Timeout in milliseconds must be greater than zero.");
List<History> historyList = new ArrayList<>();
List<AlertWithTimestamp> alertsWithTimestamp = _mqService.dequeue(ALERT.getQueueName(), AlertWithTimestamp.class, timeout,
alertCount);
List<Notification> allNotifications = new ArrayList<>();
Map<BigInteger, Alert> alertsByNotificationId = new HashMap<>();
Map<BigInteger, Long> alertEnqueueTimestampsByAlertId = new HashMap<>();
for(AlertWithTimestamp alertWithTimestamp : alertsWithTimestamp) {
String serializedAlert = alertWithTimestamp.getSerializedAlert();
Alert alert;
try {
alert = _mapper.readValue(serializedAlert, Alert.class);
} catch (IOException e) {
_logger.warn("Failed to deserialize alert.", e);
continue;
}
if(!_shouldEvaluateAlert(alert, alert.getId())) {
continue;
}
alertEnqueueTimestampsByAlertId.put(alert.getId(), alertWithTimestamp.getAlertEnqueueTime());
List<Notification> notifications = new ArrayList<>(alert.getNotifications());
alert.setNotifications(null);
for(Notification n : notifications) {
alertsByNotificationId.put(n.getId(), alert);
}
allNotifications.addAll(notifications);
}
// Update the state of notification objects from the database since the notification contained
// in the serialized alert might be stale. This is because the scheduler only refreshes the alerts
// after a specified REFRESH_INTERVAL. And within this interval, the notification state may have changed.
// For example, the notification may have been updated to be on cooldown by a previous alert evaluation.
// Or it's active/clear status may have changed.
updateNotificationsActiveStatusAndCooldown(allNotifications);
for(Notification n : allNotifications) {
alertsByNotificationId.get(n.getId()).addNotification(n);
}
Set<Alert> alerts = new HashSet<>(alertsByNotificationId.values());
for (Alert alert : alerts) {
long jobStartTime = System.currentTimeMillis();
long jobEndTime = 0;
String logMessage = null;
History history = null;
if(Boolean.valueOf(_configuration.getValue(com.salesforce.dva.argus.system.SystemConfiguration.Property.DATA_LAG_MONITOR_ENABLED))){
if(_monitorService.isDataLagging()) {
history = new History(addDateToMessage(JobStatus.SKIPPED.getDescription()), SystemConfiguration.getHostname(), alert.getId(), JobStatus.SKIPPED);
logMessage = MessageFormat.format("Skipping evaluating the alert with id: {0}. because metric data was lagging", alert.getId());
_logger.info(logMessage);
_appendMessageNUpdateHistory(history, logMessage, null, 0);
history = _historyService.createHistory(alert, history.getMessage(), history.getJobStatus(), history.getExecutionTime());
historyList.add(history);
Map<String, String> tags = new HashMap<>();
tags.put(USERTAG, alert.getOwner().getUserName());
_monitorService.modifyCounter(Counter.ALERTS_SKIPPED, 1, tags);
continue;
}
}
history = new History(addDateToMessage(JobStatus.STARTED.getDescription()), SystemConfiguration.getHostname(), alert.getId(), JobStatus.STARTED);
try {
List<Metric> metrics = _metricService.getMetrics(alert.getExpression(), alertEnqueueTimestampsByAlertId.get(alert.getId()));
if(metrics.isEmpty()) {
if (alert.isMissingDataNotificationEnabled()) {
_sendNotificationForMissingData(alert);
logMessage = MessageFormat.format("Metric data does not exist for alert expression: {0}. Sent notification for missing data.",
alert.getExpression());
_logger.info(logMessage);
_appendMessageNUpdateHistory(history, logMessage, null, 0);
} else {
logMessage = MessageFormat.format("Metric data does not exist for alert expression: {0}. Missing data notification was not enabled.",
alert.getExpression());
_logger.info(logMessage);
_appendMessageNUpdateHistory(history, logMessage, null, 0);
}
} else {
//Only evaluate those triggers which are associated with any notification.
List<Trigger> triggersToEvaluate = new ArrayList<>();
for(Notification notification : alert.getNotifications()) {
triggersToEvaluate.addAll(notification.getTriggers());
}
Map<BigInteger, Map<Metric, Long>> triggerFiredTimesAndMetricsByTrigger = _evaluateTriggers(triggersToEvaluate,
metrics, history);
for(Notification notification : alert.getNotifications()) {
if (notification.getTriggers().isEmpty()) {
logMessage = MessageFormat.format("The notification {0} has no triggers.", notification.getName());
_logger.info(logMessage);
_appendMessageNUpdateHistory(history, logMessage, null, 0);
} else {
_processNotification(alert, history, metrics, triggerFiredTimesAndMetricsByTrigger, notification);
}
}
}
jobEndTime = System.currentTimeMillis();
long evalLatency = jobEndTime - jobStartTime;
_appendMessageNUpdateHistory(history, "Alert was evaluated successfully.", JobStatus.SUCCESS, evalLatency);
// publishing evaluation latency as a metric
Map<Long, Double> datapoints = new HashMap<>();
datapoints.put(1000 * 60 * (System.currentTimeMillis()/(1000 *60)), Double.valueOf(evalLatency));
Metric metric = new Metric("alerts.evaluated", "alert-evaluation-latency-" + alert.getId().toString());
metric.addDatapoints(datapoints);
try {
_tsdbService.putMetrics(Arrays.asList(new Metric[] {metric}));
} catch (Exception ex) {
_logger.error("Exception occurred while pushing alert evaluation latency metric to tsdb - {}", ex.getMessage());
}
Map<String, String> tags = new HashMap<>();
tags.put(USERTAG, alert.getOwner().getUserName());
_monitorService.modifyCounter(Counter.ALERTS_EVALUATION_LATENCY, evalLatency, tags);
} catch (MissingDataException mde) {
jobEndTime = System.currentTimeMillis();
logMessage = MessageFormat.format("Failed to evaluate alert : {0}. Reason: {1}", alert.getId().intValue(), mde.getMessage());
_logger.warn(logMessage);
_appendMessageNUpdateHistory(history, logMessage, JobStatus.FAILURE, jobEndTime - jobStartTime);
if (alert.isMissingDataNotificationEnabled()) {
_sendNotificationForMissingData(alert);
}
Map<String, String> tags = new HashMap<>();
tags.put(USERTAG, alert.getOwner().getUserName());
_monitorService.modifyCounter(Counter.ALERTS_FAILED, 1, tags);
} catch (Exception ex) {
jobEndTime = System.currentTimeMillis();
logMessage = MessageFormat.format("Failed to evaluate alert : {0}. Reason: {1}", alert.getId().intValue(), ex.getMessage());
_logger.warn(logMessage);
_appendMessageNUpdateHistory(history, logMessage, JobStatus.FAILURE, jobEndTime - jobStartTime);
if (Boolean.valueOf(_configuration.getValue(SystemConfiguration.Property.EMAIL_EXCEPTIONS))) {
_sendEmailToAdmin(alert, alert.getId(), ex);
}
Map<String, String> tags = new HashMap<>();
tags.put(USERTAG, alert.getOwner().getUserName());
_monitorService.modifyCounter(Counter.ALERTS_FAILED, 1, tags);
} finally {
Map<String, String> tags = new HashMap<>();
tags.put(USERTAG, alert.getOwner().getUserName());
_monitorService.modifyCounter(Counter.ALERTS_EVALUATED, 1, tags);
history = _historyService.createHistory(alert, history.getMessage(), history.getJobStatus(), history.getExecutionTime());
historyList.add(history);
}
} // end for
return historyList;
}
/**
* Evaluates all triggers associated with the notification and updates the job history.
*/
private void _processNotification(Alert alert, History history, List<Metric> metrics,
Map<BigInteger, Map<Metric, Long>> triggerFiredTimesAndMetricsByTrigger, Notification notification) {
for(Trigger trigger : notification.getTriggers()) {
Map<Metric, Long> triggerFiredTimesForMetrics = triggerFiredTimesAndMetricsByTrigger.get(trigger.getId());
for(Metric m : metrics) {
if(triggerFiredTimesForMetrics.containsKey(m)) {
String logMessage = MessageFormat.format("The trigger {0} was evaluated against metric {1} and it is fired.", trigger.getName(), m.getIdentifier());
_appendMessageNUpdateHistory(history, logMessage, null, 0);
if(!notification.onCooldown(trigger, m)) {
_updateNotificationSetActiveStatus(trigger, m, history, notification);
sendNotification(trigger, m, history, notification, alert, triggerFiredTimesForMetrics.get(m));
} else {
logMessage = MessageFormat.format("The notification {0} is on cooldown until {1}.", notification.getName(), getDateMMDDYYYY(notification.getCooldownExpirationByTriggerAndMetric(trigger, m)));
_appendMessageNUpdateHistory(history, logMessage, null, 0);
}
} else {
String logMessage = MessageFormat.format("The trigger {0} was evaluated against metric {1} and it is not fired.", trigger.getName(), m.getIdentifier());
_appendMessageNUpdateHistory(history, logMessage, null, 0);
if(notification.isActiveForTriggerAndMetric(trigger, m)) {
// This is case when the notification was active for the given trigger, metric combination
// and the metric did not violate triggering condition on current evaluation. Hence we must clear it.
_updateNotificationClearActiveStatus(trigger, m, notification);
sendClearNotification(trigger, m, history, notification, alert);
} else {
// This is case when the notification is not active for the given trigger, metric combination
// and the metric did not violate triggering condition on current evaluation.
;
}
}
}
}
}
/**
* Determines if the alert should be evaluated or not.
*/
private boolean _shouldEvaluateAlert(Alert alert, BigInteger alertId) {
if (alert == null) {
_logger.warn(MessageFormat.format("Could not find alert ID {0}", alertId));
return false;
}
if(!alert.isEnabled()) {
_logger.warn(MessageFormat.format("Alert {0} has been disabled. Will not evaluate.", alert.getId().intValue()));
return false;
}
return true;
}
/**
* Evaluates all triggers for the given set of metrics and returns a map of triggerIds to a map containing the triggered metric
* and the trigger fired time.
*/
private Map<BigInteger, Map<Metric, Long>> _evaluateTriggers(List<Trigger> triggers, List<Metric> metrics, History history) {
Map<BigInteger, Map<Metric, Long>> triggerFiredTimesAndMetricsByTrigger = new HashMap<>();
for(Trigger trigger : triggers) {
Map<Metric, Long> triggerFiredTimesForMetrics = new HashMap<>(metrics.size());
for(Metric metric : metrics) {
Long triggerFiredTime = getTriggerFiredDatapointTime(trigger, metric);
if (triggerFiredTime != null) {
triggerFiredTimesForMetrics.put(metric, triggerFiredTime);
Map<String, String> tags = new HashMap<>();
tags.put(USERTAG, trigger.getAlert().getOwner().getUserName());
_monitorService.modifyCounter(Counter.TRIGGERS_VIOLATED, 1, tags);
}
}
triggerFiredTimesAndMetricsByTrigger.put(trigger.getId(), triggerFiredTimesForMetrics);
}
return triggerFiredTimesAndMetricsByTrigger;
}
public void sendNotification(Trigger trigger, Metric metric, History history, Notification notification, Alert alert,
Long triggerFiredTime) {
double value = metric.getDatapoints().get(triggerFiredTime);
NotificationContext context = new NotificationContext(alert, trigger, notification, triggerFiredTime, value, metric);
Notifier notifier = getNotifier(SupportedNotifier.fromClassName(notification.getNotifierName()));
notifier.sendNotification(context);
Map<String, String> tags = new HashMap<>();
tags.put("status", "active");
tags.put("type", SupportedNotifier.fromClassName(notification.getNotifierName()).name());
_monitorService.modifyCounter(Counter.NOTIFICATIONS_SENT, 1, tags);
String logMessage = MessageFormat.format("Sent alert notification and updated the cooldown: {0}",
getDateMMDDYYYY(notification.getCooldownExpirationByTriggerAndMetric(trigger, metric)));
_logger.info(logMessage);
_appendMessageNUpdateHistory(history, logMessage, null, 0);
}
public void sendClearNotification(Trigger trigger, Metric metric, History history, Notification notification, Alert alert) {
NotificationContext context = new NotificationContext(alert, trigger, notification, System.currentTimeMillis(), 0.0, metric);
Notifier notifier = getNotifier(SupportedNotifier.fromClassName(notification.getNotifierName()));
notifier.clearNotification(context);
Map<String, String> tags = new HashMap<>();
tags.put("status", "clear");
tags.put("type", SupportedNotifier.fromClassName(notification.getNotifierName()).name());
_monitorService.modifyCounter(Counter.NOTIFICATIONS_SENT, 1, tags);
String logMessage = MessageFormat.format("The notification {0} was cleared.", notification.getName());
_logger.info(logMessage);
_appendMessageNUpdateHistory(history, logMessage, null, 0);
}
private void _updateNotificationSetActiveStatus(Trigger trigger, Metric metric, History history, Notification notification) {
notification.setCooldownExpirationByTriggerAndMetric(trigger, metric, System.currentTimeMillis() + notification.getCooldownPeriod());
notification.setActiveForTriggerAndMetric(trigger, metric, true);
notification = mergeEntity(_emProvider.get(), notification);
}
private void _updateNotificationClearActiveStatus(Trigger trigger, Metric metric, Notification notification) {
notification.setCooldownExpirationByTriggerAndMetric(trigger, metric, System.currentTimeMillis());
notification.setActiveForTriggerAndMetric(trigger, metric, false);
notification = mergeEntity(_emProvider.get(), notification);
}
private void _appendMessageNUpdateHistory(History history, String message, JobStatus jobStatus, long executionTime) {
String oldMessage = history.getMessage();
history.setMessage(oldMessage + addDateToMessage(message));
if(jobStatus != null) {
history.setJobStatus(jobStatus);
}
history.setExecutionTime(executionTime);
}
private void _sendEmailToAdmin(Alert alert, BigInteger alertId, Throwable ex) {
Set<String> to = new HashSet<>();
to.add(_configuration.getValue(SystemConfiguration.Property.ADMIN_EMAIL));
String subject = "Alert evaluation failure notification.";
StringBuilder message = new StringBuilder();
message.append("<p>The evaluation for the following alert failed. </p>");
message.append(MessageFormat.format("Alert Id: {0}", alertId));
if (alert != null) {
message.append(MessageFormat.format("<br> Alert name: {0} <br> Exception message: {1} ", alert.getName(), ex.toString()));
} else {
message.append(MessageFormat.format("<br> Exception message: The alert with id {0} does not exist.", alertId));
}
message.append(MessageFormat.format("<br> Time stamp: {0}", DATE_FORMATTER.get().format(new Date(System.currentTimeMillis()))));
_mailService.sendMessage(to, subject, message.toString(), "text/html; charset=utf-8", MailService.Priority.HIGH);
if (alert != null && alert.getOwner() != null && alert.getOwner().getEmail() != null && !alert.getOwner().getEmail().isEmpty()) {
to.clear();
to.add(alert.getOwner().getEmail());
_mailService.sendMessage(to, subject, message.toString(), "text/html; charset=utf-8", MailService.Priority.HIGH);
}
}
private void _sendNotificationForMissingData(Alert alert) {
Set<String> to = new HashSet<>();
to.add(alert.getOwner().getEmail());
String subject = "Alert Missing Data Notification.";
StringBuilder message = new StringBuilder();
message.append("<p>This is a missing data notification. </p>");
message.append(MessageFormat.format("Alert Id: {0}", alert.getId().intValue()));
message.append(MessageFormat.format("<br> Alert name: {0}" , alert.getName()));
message.append(MessageFormat.format("<br> No data found for the following metric expression: ", alert.getExpression()));
message.append(MessageFormat.format("<br> Time stamp: {0}", DATE_FORMATTER.get().format(new Date(System.currentTimeMillis()))));
_mailService.sendMessage(to, subject, message.toString(), "text/html; charset=utf-8", MailService.Priority.HIGH);
Map<String, String> tags = new HashMap<>();
tags.put("status", "missingdata");
tags.put("type", SupportedNotifier.EMAIL.name());
_monitorService.modifyCounter(Counter.NOTIFICATIONS_SENT, 1, tags);
}
@Override
@Transactional
public Alert findAlertByNameAndOwner(String name, PrincipalUser owner) {
requireNotDisposed();
requireArgument(name != null && !name.isEmpty(), "Name cannot be null or empty.");
requireArgument(owner != null, "Owner cannot be null.");
return Alert.findByNameAndOwner(_emProvider.get(), name, owner);
}
@Override
public void enqueueAlerts(List<Alert> alerts) {
requireNotDisposed();
requireArgument(alerts != null, "The list of alerts cannot be null.");
List<AlertWithTimestamp> alertsWithTimestamp = new ArrayList<>(alerts.size());
for (Alert alert : alerts) {
AlertWithTimestamp obj;
try {
String serializedAlert = _mapper.writeValueAsString(alert);
obj = new AlertWithTimestamp(serializedAlert, System.currentTimeMillis());
} catch (JsonProcessingException e) {
_logger.warn("Failed to serialize alert: {}.", alert.getId().intValue());
_logger.warn("", e);
continue;
}
alertsWithTimestamp.add(obj);
}
_mqService.enqueue(ALERT.getQueueName(), alertsWithTimestamp);
List<Metric> metricsAlertScheduled = new ArrayList<Metric>();
// Write alerts scheduled for evaluation as time series to TSDB
for (Alert alert : alerts) {
Map<Long, Double> datapoints = new HashMap<>();
// convert timestamp to nearest minute since cron is Least scale resolution of minute
datapoints.put(1000 * 60 * (System.currentTimeMillis()/(1000 *60)), 1.0);
Metric metric = new Metric("alerts.scheduled", "alert-" + alert.getId().toString());
metric.setTag("host",SystemConfiguration.getHostname());
metric.addDatapoints(datapoints);
metricsAlertScheduled.add(metric);
Map<String, String> tags = new HashMap<>();
tags.put(USERTAG, alert.getOwner().getUserName());
_monitorService.modifyCounter(Counter.ALERTS_SCHEDULED, 1, tags);
}
try {
_tsdbService.putMetrics(metricsAlertScheduled);
} catch (Exception ex) {
_logger.error("Error occurred while pushing alert audit scheduling time series. Reason: {}", ex.getMessage());
}
}
@Override
public List<Alert> findAllAlerts(boolean metadataOnly) {
requireNotDisposed();
return metadataOnly ? Alert.findAllMeta(_emProvider.get()) : Alert.findAll(_emProvider.get());
}
@Override
public List<Alert> findAlertsByStatus(boolean enabled) {
requireNotDisposed();
return Alert.findByStatus(_emProvider.get(), enabled);
}
@Override
public List<BigInteger> findAlertIdsByStatus(boolean enabled) {
requireNotDisposed();
return Alert.findIDsByStatus(_emProvider.get(), enabled);
}
@Override
public List<Alert> findAlertsByRangeAndStatus(BigInteger fromId, BigInteger toId, boolean enabled) {
requireNotDisposed();
return Alert.findByRangeAndStatus(_emProvider.get(), fromId, toId, enabled);
}
@Override
public List<Alert> findAlertsModifiedAfterDate(Date modifiedDate) {
requireNotDisposed();
return Alert.findAlertsModifiedAfterDate(_emProvider.get(), modifiedDate);
}
@Override
public int alertCountByStatus(boolean enabled) {
requireNotDisposed();
return Alert.alertCountByStatus(_emProvider.get(), enabled);
}
@Override
public List<Alert> findAlertsByLimitOffsetStatus(int limit, int offset,
boolean enabled) {
requireNotDisposed();
return Alert.findByLimitOffsetStatus(_emProvider.get(), limit, offset, enabled);
}
@Override
public List<Alert> findAlertsByNameWithPrefix(String prefix) {
requireNotDisposed();
requireArgument(prefix != null && !prefix.isEmpty(), "Name prefix cannot be null or empty.");
return Alert.findByPrefix(_emProvider.get(), prefix);
}
@Override
public List<String> getSupportedNotifiers() {
requireNotDisposed();
List<String> result = new ArrayList<>(SupportedNotifier.values().length);
for (SupportedNotifier notifier : SupportedNotifier.values()) {
result.add(notifier.toString());
}
return result;
}
@Override
public List<Alert> findSharedAlerts(boolean metadataOnly, PrincipalUser owner, Integer limit) {
requireNotDisposed();
return metadataOnly ? Alert.findSharedAlertsMeta(_emProvider.get(), owner, limit) : Alert.findSharedAlerts(_emProvider.get(), owner, limit);
}
/**
* Returns an instance of a supported notifier.
*
* @param notifier The supported notifier to obtain an instance for.
*
* @return The notifier instance.
*/
@Override
public Notifier getNotifier(SupportedNotifier notifier) {
switch (notifier) {
case CALLBACK:
return _notifierFactory.getCallbackNotifier();
case EMAIL:
return _notifierFactory.getEmailNotifier();
case GOC:
return _notifierFactory.getGOCNotifier();
case DATABASE:
return _notifierFactory.getDBNotifier();
case WARDENAPI:
return _notifierFactory.getWardenApiNotifier();
case WARDENPOSTING:
return _notifierFactory.getWardenPostingNotifier();
case GUS:
return _notifierFactory.getGusNotifier();
default:
return _notifierFactory.getDBNotifier();
}
}
@Override
public void dispose() {
super.dispose();
_metricService.dispose();
}
/**
* Evaluates the trigger against metric data.
*
* @param trigger Trigger to be evaluated.
* @param metric Metric data for the alert which the trigger belongs.
*
* @return The time stamp of the last data point in metric at which the trigger was decided to be fired.
*/
public Long getTriggerFiredDatapointTime(Trigger trigger, Metric metric) {
List<Map.Entry<Long, Double>> sortedDatapoints = new ArrayList<>(metric.getDatapoints().entrySet());
if (metric.getDatapoints().isEmpty()) {
return null;
} else if (metric.getDatapoints().size() == 1) {
if (trigger.getInertia().compareTo(0L) <= 0) {
if (Trigger.evaluateTrigger(trigger, sortedDatapoints.get(0).getValue())) {
return sortedDatapoints.get(0).getKey();
} else {
return null;
}
} else {
return null;
}
}
Collections.sort(sortedDatapoints, new Comparator<Map.Entry<Long, Double>>() {
@Override
public int compare(Entry<Long, Double> e1, Entry<Long, Double> e2) {
return e1.getKey().compareTo(e2.getKey());
}
});
int endIndex = sortedDatapoints.size();
for(int startIndex=sortedDatapoints.size()-1; startIndex>=0; startIndex--){
if(Trigger.evaluateTrigger(trigger, sortedDatapoints.get(startIndex).getValue())){
Long interval = sortedDatapoints.get(endIndex-1).getKey() - sortedDatapoints.get(startIndex).getKey();
if(interval >= trigger.getInertia())
return sortedDatapoints.get(endIndex-1).getKey();
}else{
endIndex=startIndex;
}
}
return null;
}
@Override
@Transactional
public void deleteTrigger(Trigger trigger) {
requireNotDisposed();
requireArgument(trigger != null, "Trigger cannot be null.");
_logger.debug("Deleting trigger {}.", trigger);
EntityManager em = _emProvider.get();
deleteEntity(em, trigger);
em.flush();
}
@Override
@Transactional
public void deleteNotification(Notification notification) {
requireNotDisposed();
requireArgument(notification != null, "Notification cannot be null.");
_logger.debug("Deleting notification {}.", notification);
EntityManager em = _emProvider.get();
deleteEntity(em, notification);
em.flush();
}
private String addDateToMessage(String message) {
return MessageFormat.format("\n {0} : {1}", DATE_FORMATTER.get().format(new Date()), message);
}
private String getDateMMDDYYYY(long dateInSeconds) {
String result;
try {
result = DATE_FORMATTER.get().format(new Date(dateInSeconds));
} catch (Exception ex) {
result = String.valueOf(dateInSeconds);
}
return result;
}
//~ Inner Classes ********************************************************************************************************************************
/**
* Used to enqueue alerts to evaluate. The timestamp is used to reconcile lag between enqueue time
* and evaluation time by adjusting relative times in the alert metric expression being evaluated.
*
* @author Bhinav Sura (bhinav.sura@salesforce.com)
*/
public static class AlertWithTimestamp implements Serializable {
/** The serial version UID. */
private static final long serialVersionUID = 1L;
protected String serializedAlert;
protected long alertEnqueueTime;
/** Creates a new AlertIdWithTimestamp object. */
public AlertWithTimestamp() { }
/**
* Creates a new AlertIdWithTimestamp object.
*
* @param id The alert ID. Cannot be null.
* @param timestamp The epoch timestamp the alert was enqueued for evaluation.
*/
public AlertWithTimestamp(String serializedAlert, long timestamp) {
this.serializedAlert = serializedAlert;
this.alertEnqueueTime = timestamp;
}
public String getSerializedAlert() {
return serializedAlert;
}
public void setSerializedAlert(String serializedAlert) {
this.serializedAlert = serializedAlert;
}
public long getAlertEnqueueTime() {
return alertEnqueueTime;
}
public void setAlertEnqueueTime(long alertEnqueueTime) {
this.alertEnqueueTime = alertEnqueueTime;
}
}
/**
* The context for the notification which contains relevant information for the notification occurrence.
*
* @author Tom Valine (tvaline@salesforce.com)
*/
public static class NotificationContext {
private Alert alert;
private Trigger trigger;
private long coolDownExpiration;
private Notification notification;
private long triggerFiredTime;
private double triggerEventValue;
private Metric triggeredMetric;
/**
* Creates a new Notification Context object.
*
* @param alert The id of the alert for which the trigger is fired.
* @param trigger Name of the trigger fired.
* @param notification coolDownExpiration The cool down period of the notification.
* @param triggerFiredTime The time stamp of the last data point in metric at which the trigger was decided to be fired.
* @param triggerEventValue The value of the metric at the event trigger time.
*/
public NotificationContext(Alert alert, Trigger trigger, Notification notification, long triggerFiredTime, double triggerEventValue, Metric triggeredMetric) {
this.alert = alert;
this.trigger = trigger;
this.coolDownExpiration = notification.getCooldownExpirationByTriggerAndMetric(trigger, triggeredMetric);
this.notification = notification;
this.triggerFiredTime = triggerFiredTime;
this.triggerEventValue = triggerEventValue;
this.triggeredMetric = triggeredMetric;
}
/** Creates a new NotificationContext object. */
protected NotificationContext() { }
/**
* returns the alert id.
*
* @return Id of the alert
*/
public Alert getAlert() {
return alert;
}
/**
* Sets the alert id.
*
* @param alert Id of the alert for which the trigger is fired.
*/
public void setAlert(Alert alert) {
this.alert = alert;
}
/**
* returns the trigger.
*
* @return trigger Trigger Object.
*/
public Trigger getTrigger() {
return trigger;
}
/**
* sets the trigger.
*
* @param trigger Trigger Object.
*/
public void setTriggerName(Trigger trigger) {
this.trigger = trigger;
}
/**
* Returns the cool down period.
*
* @return The cool down period of the notification.
*/
public long getCoolDownExpiration() {
return coolDownExpiration;
}
/**
* Sets the cool down period.
*
* @param coolDownExpiration cool down period of the notification.
*/
public void setCoolDownExpiration(long coolDownExpiration) {
this.coolDownExpiration = coolDownExpiration;
}
/**
* returns the notification object.
*
* @return the notification object for which the trigger is fired.
*/
public Notification getNotification() {
return notification;
}
/**
* Sets the notification object.
*
* @param notification the notification object for which the trigger is fired.
*/
public void setNotificationName(Notification notification) {
this.notification = notification;
}
/**
* returns the last time stamp in metric at which the trigger was decided to be fired.
*
* @return The time stamp of the last data point in metric at which the trigger was decided to be fired.
*/
public long getTriggerFiredTime() {
return triggerFiredTime;
}
/**
* Sets the trigger fired time.
*
* @param triggerFiredTime The time stamp of the last data point in metric at which the trigger was decided to be fired.
*/
public void setTriggerFiredTime(long triggerFiredTime) {
this.triggerFiredTime = triggerFiredTime;
}
/**
* Returns the event trigger value.
*
* @return The event trigger value.
*/
public double getTriggerEventValue() {
return triggerEventValue;
}
/**
* Sets the event trigger value.
*
* @param triggerEventValue The event trigger value.
*/
public void setTriggerEventValue(double triggerEventValue) {
this.triggerEventValue = triggerEventValue;
}
public Metric getTriggeredMetric() {
return triggeredMetric;
}
public void setTriggeredMetric(Metric triggeredMetric) {
this.triggeredMetric = triggeredMetric;
}
}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */ | bsd-3-clause |
lang010/acit | leetcode/785.is-graph-bipartite.315117831.ac.java | 2715 | /*
* @lc app=leetcode id=785 lang=java
*
* [785] Is Graph Bipartite?
*
* https://leetcode.com/problems/is-graph-bipartite/description/
*
* algorithms
* Medium (48.05%)
* Total Accepted: 150.2K
* Total Submissions: 312.6K
* Testcase Example: '[[1,3],[0,2],[1,3],[0,2]]'
*
* Given an undirected graph, return true if and only if it is bipartite.
*
* Recall that a graph is bipartite if we can split its set of nodes into two
* independent subsets A and B, such that every edge in the graph has one node
* in A and another node in B.
*
* The graph is given in the following form: graph[i] is a list of indexes j
* for which the edge between nodes i and j exists. Each node is an integer
* between 0 and graph.length - 1. There are no self edges or parallel edges:
* graph[i] does not contain i, and it doesn't contain any element twice.
*
*
* Example 1:
*
*
* Input: graph = [[1,3],[0,2],[1,3],[0,2]]
* Output: true
* Explanation: We can divide the vertices into two groups: {0, 2} and {1,
* 3}.
*
*
*
* Example 2:
*
*
* Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
* Output: false
* Explanation: We cannot find a way to divide the set of nodes into two
* independent subsets.
*
*
*
*
* Constraints:
*
*
* 1 <= graph.length <= 100
* 0 <= graph[i].length < 100
* 0 <= graph[i][j] <= graph.length - 1
* graph[i][j] != i
* All the values of graph[i] are unique.
* The graph is guaranteed to be undirected.
*
*
*/
class Solution {
public boolean isBipartite(int[][] graph) {
int n = graph.length;
int[] visited = new int[n];
Set<Integer> s1 = new HashSet<>();
Set<Integer> s2 = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (visited[i] == 0) {
s1.add(i);
queue.add(i);
while (!queue.isEmpty()) {
int cur = queue.poll();
if (visited[cur] == 1) {
continue;
}
visited[cur] = 1;
Set<Integer> set = s1.contains(cur) ? s1 : s2;
Set<Integer> another = set == s1 ? s2 : s1;
for (int j = 0; j < graph[cur].length; j++) {
if (set.contains(graph[cur][j]))
return false;
if (!another.contains(graph[cur][j])) {
another.add(graph[cur][j]);
queue.add(graph[cur][j]);
}
}
}
}
}
return true;
}
}
| bsd-3-clause |
mbordas/qualify | src/main/java/qualify/doc/DocImage.java | 1767 | /*Copyright (c) 2011, Mathieu Bordas
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3- Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package qualify.doc;
import java.io.File;
public class DocImage {
private File originalFile = null;
public DocImage(File originalFile) {
this.originalFile = originalFile;
}
public void addRectangle(int x, int y, int width, int height, int borderSize) {
}
}
| bsd-3-clause |
genome-vendor/apollo | src/java/apollo/gui/genomemap/FeatureTierManagerI.java | 893 | package apollo.gui.genomemap;
import java.awt.Graphics;
import java.util.Vector;
import apollo.gui.Selection;
import apollo.gui.TierManagerI;
import apollo.gui.Transformer;
public interface FeatureTierManagerI extends TierManagerI {
public void synchDrawablesWithTiers();
public String getTierLabel(int tier_number);
public void clearFeatures();
public void setTextAvoidance(Transformer t, Graphics g);
public void unsetTextAvoidance();
public boolean isAvoidingTextOverlaps();
public boolean areAnyTiersLabeled();
public Vector getHiddenTiers();
public void setVisible(String type, boolean state);
public void collapseTier(String tier_label);
public void expandTier(String tier_label);
/** Searches through the tiers to find all drawables that have
features in the current selection */
public Selection getViewSelection(Selection selection);
}
| bsd-3-clause |
ValentinMinder/pocketcampus | platform/android/src/main/java/org/pocketcampus/platform/android/ui/labeler/IRichLabeler.java | 1608 | package org.pocketcampus.platform.android.ui.labeler;
import java.util.Date;
/**
* Interface to the methods provided by a <code>RichLabeler</code>. A
* <code>RichLabeler</code> should have a title, a description, a value and a
* <code>Date</code>.
*
* Defines where the information about an object that is to be displayed will be
* fetched from.
*
* @author Oriane <oriane.rodriguez@epfl.ch>
*/
public interface IRichLabeler<LabeledObjectType> extends
ILabeler<LabeledObjectType> {
/**
* Returns the title of the labeled object.
*
* @param obj
* The object for which we want the title.
* @return The <code>String</code> object's title defined by the labeler.
*/
public String getTitle(LabeledObjectType obj);
/**
* Returns the description of the labeled object.
*
* @param obj
* The object for which we want the description.
* @return The <code>String</code> object's description defined by the
* labeler.
*/
public String getDescription(LabeledObjectType obj);
/**
* Returns the value (e.g. price) of the labeled object.
*
* @param obj
* The object for which we want the value.
* @return The <code>double</code> object's value defined by the labeler.
*/
public double getValue(LabeledObjectType obj);
/**
* Returns the <code>Date</code> of the labeled object.
*
* @param obj
* The object for which we want the <code>Date</code>.
* @return The <code>Date</code> object's <code>Date</code> defined by the
* labeler.
*/
public Date getDate(LabeledObjectType obj);
}
| bsd-3-clause |
xebialabs/vijava | src/com/vmware/vim25/DistributedVirtualSwitchInfo.java | 2520 | /*================================================================================
Copyright (c) 2012 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class DistributedVirtualSwitchInfo extends DynamicData {
public String switchName;
public String switchUuid;
public ManagedObjectReference distributedVirtualSwitch;
public String getSwitchName() {
return this.switchName;
}
public String getSwitchUuid() {
return this.switchUuid;
}
public ManagedObjectReference getDistributedVirtualSwitch() {
return this.distributedVirtualSwitch;
}
public void setSwitchName(String switchName) {
this.switchName=switchName;
}
public void setSwitchUuid(String switchUuid) {
this.switchUuid=switchUuid;
}
public void setDistributedVirtualSwitch(ManagedObjectReference distributedVirtualSwitch) {
this.distributedVirtualSwitch=distributedVirtualSwitch;
}
} | bsd-3-clause |
kakada/dhis2 | dhis-services/dhis-service-datamart-default/src/main/java/org/hisp/dhis/datamart/DataMartScheduler.java | 2112 | package org.hisp.dhis.datamart;
/*
* Copyright (c) 2004-2015, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @author Lars Helge Overland
*/
public interface DataMartScheduler
{
final String CRON_NIGHTLY = "0 0 2 * * ?";
final String CRON_TEST = "0 * * * * ?";
final String STATUS_RUNNING = "running";
final String STATUS_DONE = "done";
final String STATUS_STOPPED = "stopped";
final String STATUS_NOT_STARTED = "not_started";
void executeDataMartExport();
public void scheduleDataMartExport();
boolean stopDataMartExport();
String getDataMartExportStatus();
}
| bsd-3-clause |
JeffreyFalgout/ThrowingStream | throwing-interfaces/src/main/java/name/falgout/jeffrey/throwing/ThrowingDoubleToIntFunction.java | 1457 | package name.falgout.jeffrey.throwing;
import java.util.function.Consumer;
import java.util.function.DoubleToIntFunction;
import java.util.function.Function;
import javax.annotation.Nullable;
@FunctionalInterface
public interface ThrowingDoubleToIntFunction<X extends Throwable> {
public int applyAsInt(double value) throws X;
default public DoubleToIntFunction fallbackTo(DoubleToIntFunction fallback) {
return fallbackTo(fallback, null);
}
default public DoubleToIntFunction fallbackTo(DoubleToIntFunction fallback,
@Nullable Consumer<? super Throwable> thrown) {
ThrowingDoubleToIntFunction<Nothing> t = fallback::applyAsInt;
return orTry(t, thrown)::applyAsInt;
}
default public <Y extends Throwable> ThrowingDoubleToIntFunction<Y>
orTry(ThrowingDoubleToIntFunction<? extends Y> f) {
return orTry(f, null);
}
default public <Y extends Throwable> ThrowingDoubleToIntFunction<Y> orTry(
ThrowingDoubleToIntFunction<? extends Y> f, @Nullable Consumer<? super Throwable> thrown) {
return t -> {
ThrowingSupplier<Integer, X> s = () -> applyAsInt(t);
return s.orTry(() -> f.applyAsInt(t), thrown).get();
};
}
default public <Y extends Throwable> ThrowingDoubleToIntFunction<Y> rethrow(Class<X> x,
Function<? super X, ? extends Y> mapper) {
return t -> {
ThrowingSupplier<Integer, X> s = () -> applyAsInt(t);
return s.rethrow(x, mapper).get();
};
}
}
| bsd-3-clause |
huntergdavis/Easy_Reptile_Whistle | src/com/hunterdavis/easyreptilewhistle/EasyReptileWhistle.java | 3184 | package com.hunterdavis.easyreptilewhistle;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.hunterdavis.easyreptilewhistle.R;
public class EasyReptileWhistle extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// listener for frequency button
OnClickListener frequencyListner = new OnClickListener() {
public void onClick(View v) {
EditText freqText = (EditText) findViewById(R.id.freqbonus);
String frequency = freqText.getText().toString();
if (frequency.length() > 0) {
float localFreqValue = Float.valueOf(frequency);
playFrequency(v.getContext(), localFreqValue);
}
}
};
// listener for frequency button
OnClickListener dogOneListener = new OnClickListener() {
public void onClick(View v) {
playFrequency(v.getContext(), 1000);
}
};
// listener for frequency button
OnClickListener dogTwoListener = new OnClickListener() {
public void onClick(View v) {
playFrequency(v.getContext(), 750);
}
};
// listener for frequency button
OnClickListener dogThreeListener = new OnClickListener() {
public void onClick(View v) {
playFrequency(v.getContext(), 250);
}
};
// listener for frequency button
OnClickListener dogFourListener = new OnClickListener() {
public void onClick(View v) {
playFrequency(v.getContext(), 100);
}
};
// frequency button
Button freqButton = (Button) findViewById(R.id.freqbutton);
freqButton.setOnClickListener(frequencyListner);
// Whistle Button 1-4
Button dogOneButton = (Button) findViewById(R.id.dogone);
dogOneButton.setOnClickListener(dogOneListener);
Button dogTwoButton = (Button) findViewById(R.id.dogtwo);
dogTwoButton.setOnClickListener(dogTwoListener);
Button dogThreeButton = (Button) findViewById(R.id.dogthree);
dogThreeButton.setOnClickListener(dogThreeListener);
Button dogFourButton = (Button) findViewById(R.id.dogfour);
dogFourButton.setOnClickListener(dogFourListener);
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
}
public void playFrequency(Context context, float frequency) {
// final float frequency2 = 440;
float increment = (float) (2 * Math.PI) * frequency / 44100; // angular
// increment
// for
// each
// sample
float angle = 0;
AndroidAudioDevice device = new AndroidAudioDevice();
float samples[] = new float[1024];
for (int j = 0; j < 60; j++) {
for (int i = 0; i < samples.length; i++) {
samples[i] = (float) Math.sin(angle);
angle += increment;
}
device.writeSamples(samples);
}
}
} | bsd-3-clause |
UrielCh/ovh-java-sdk | ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/price/dedicatedcloud/_2014v1/rbx2a/enterprise/filer/OvhHourlyEnum.java | 1115 | package net.minidev.ovh.api.price.dedicatedcloud._2014v1.rbx2a.enterprise.filer;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Enum of Hourlys
*/
public enum OvhHourlyEnum {
@JsonProperty("iscsi-1200-GB")
iscsi_1200_GB("iscsi-1200-GB"),
@JsonProperty("iscsi-13200g-GB")
iscsi_13200g_GB("iscsi-13200g-GB"),
@JsonProperty("iscsi-3300-GB")
iscsi_3300_GB("iscsi-3300-GB"),
@JsonProperty("iscsi-6600-GB")
iscsi_6600_GB("iscsi-6600-GB"),
@JsonProperty("iscsi-800-GB")
iscsi_800_GB("iscsi-800-GB"),
@JsonProperty("nfs-100-GB")
nfs_100_GB("nfs-100-GB"),
@JsonProperty("nfs-1200-GB")
nfs_1200_GB("nfs-1200-GB"),
@JsonProperty("nfs-13200-GB")
nfs_13200_GB("nfs-13200-GB"),
@JsonProperty("nfs-1600-GB")
nfs_1600_GB("nfs-1600-GB"),
@JsonProperty("nfs-2400-GB")
nfs_2400_GB("nfs-2400-GB"),
@JsonProperty("nfs-3300-GB")
nfs_3300_GB("nfs-3300-GB"),
@JsonProperty("nfs-6600-GB")
nfs_6600_GB("nfs-6600-GB"),
@JsonProperty("nfs-800-GB")
nfs_800_GB("nfs-800-GB");
final String value;
OvhHourlyEnum(String s) {
this.value = s;
}
public String toString() {
return this.value;
}
}
| bsd-3-clause |
iotsap/FiWare-Template-Handler | ExecutionEnvironment/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ReceiveTaskActivityBehavior.java | 1368 | /* 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.
*/
//the original file has been modified by SAP Research, 2014
package org.activiti.engine.impl.bpmn.behavior;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.pvm.delegate.ActivityExecution;
/**
* A receive task is a wait state that waits for the receival of some message.
*
* Currently, the only message that is supported is the external trigger,
* given by calling the {@link RuntimeService#signal(String)} operation.
*
* @author Joram Barrez
*/
public class ReceiveTaskActivityBehavior extends TaskActivityBehavior {
public void execute(ActivityExecution execution) throws Exception {
// Do nothing: waitstate behavior
}
public void signal(ActivityExecution execution, String signalName, Object data) throws Exception {
leave(execution);
}
}
| bsd-3-clause |
shilongdai/bookManager | src/main/java/net/viperfish/bookManager/core/TransactionWithResult.java | 719 | package net.viperfish.bookManager.core;
public abstract class TransactionWithResult<T> implements Transaction {
private boolean isDone;
private T result;
protected void setResult(T result) {
this.result = result;
isDone = true;
}
/**
* check whether this has finished executing
*
* @return is complete
*/
public boolean isDone() {
return isDone;
}
/**
* get the result
*
* This method gets the result of the operation. It blocks until the result
* is available. It will block for no more 1 minute. If exceeds one minute,
* it is interrupted and a {@link RuntimeException} is thrown.
*
* @return the result of the operation
*/
public T getResult() {
return result;
}
}
| bsd-3-clause |
knopflerfish/knopflerfish.org | osgi/bundles/wireadmin/src/org/osgi/service/wireadmin/WireAdmin.java | 6863 | /*
* Copyright (c) OSGi Alliance (2002, 2013). 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.osgi.service.wireadmin;
import java.util.Dictionary;
import org.osgi.framework.InvalidSyntaxException;
/**
* Wire Administration service.
*
* <p>
* This service can be used to create {@code Wire} objects connecting a Producer
* service and a Consumer service. {@code Wire} objects also have wire
* properties that may be specified when a {@code Wire} object is created. The
* Producer and Consumer services may use the {@code Wire} object's properties
* to manage or control their interaction. The use of {@code Wire} object's
* properties by a Producer or Consumer services is optional.
*
* <p>
* Security Considerations. A bundle must have
* {@code ServicePermission[WireAdmin,GET]} to get the Wire Admin service to
* create, modify, find, and delete {@code Wire} objects.
*
* @noimplement
* @author $Id: 783de096cb9644a2c5d0be1343a2f48c504a8a19 $
*/
public interface WireAdmin {
/**
* Create a new {@code Wire} object that connects a Producer service to a
* Consumer service.
*
* The Producer service and Consumer service do not have to be registered
* when the {@code Wire} object is created.
*
* <p>
* The {@code Wire} configuration data must be persistently stored. All
* {@code Wire} connections are reestablished when the {@code WireAdmin}
* service is registered. A {@code Wire} can be permanently removed by using
* the {@link #deleteWire(Wire)} method.
*
* <p>
* The {@code Wire} object's properties must have case insensitive
* {@code String} objects as keys (like the Framework). However, the case of
* the key must be preserved.
*
* <p>
* The {@code WireAdmin} service must automatically add the following
* {@code Wire} properties:
* <ul>
* <li>{@link WireConstants#WIREADMIN_PID} set to the value of the
* {@code Wire} object's persistent identity (PID). This value is generated
* by the Wire Admin service when a {@code Wire} object is created.</li>
* <li>{@link WireConstants#WIREADMIN_PRODUCER_PID} set to the value of
* Producer service's PID.</li>
* <li>{@link WireConstants#WIREADMIN_CONSUMER_PID} set to the value of
* Consumer service's PID.</li>
* </ul>
* If the {@code properties} argument already contains any of these keys,
* then the supplied values are replaced with the values assigned by the
* Wire Admin service.
*
* <p>
* The Wire Admin service must broadcast a {@code WireAdminEvent} of type
* {@link WireAdminEvent#WIRE_CREATED} after the new {@code Wire} object
* becomes available from {@link #getWires(String)}.
*
* @param producerPID The {@code service.pid} of the Producer service to be
* connected to the {@code Wire} object.
* @param consumerPID The {@code service.pid} of the Consumer service to be
* connected to the {@code Wire} object.
* @param properties The {@code Wire} object's properties. This argument may
* be {@code null} if the caller does not wish to define any
* {@code Wire} object's properties.
* @return The {@code Wire} object for this connection.
*
* @throws java.lang.IllegalArgumentException If {@code properties} contains
* invalid wire types or case variants of the same key name.
*/
public Wire createWire(String producerPID, String consumerPID, Dictionary properties);
/**
* Delete a {@code Wire} object.
*
* <p>
* The {@code Wire} object representing a connection between a Producer
* service and a Consumer service must be removed. The persistently stored
* configuration data for the {@code Wire} object must destroyed. The
* {@code Wire} object's method {@link Wire#isValid()} will return
* {@code false} after it is deleted.
*
* <p>
* The Wire Admin service must broadcast a {@code WireAdminEvent} of type
* {@link WireAdminEvent#WIRE_DELETED} after the {@code Wire} object becomes
* invalid.
*
* @param wire The {@code Wire} object which is to be deleted.
*/
public void deleteWire(Wire wire);
/**
* Update the properties of a {@code Wire} object.
*
* The persistently stored configuration data for the {@code Wire} object is
* updated with the new properties and then the Consumer and Producer
* services will be called at the respective
* {@link Consumer#producersConnected(Wire[])} and
* {@link Producer#consumersConnected(Wire[])} methods.
*
* <p>
* The Wire Admin service must broadcast a {@code WireAdminEvent} of type
* {@link WireAdminEvent#WIRE_UPDATED} after the updated properties are
* available from the {@code Wire} object.
*
* @param wire The {@code Wire} object which is to be updated.
* @param properties The new {@code Wire} object's properties or
* {@code null} if no properties are required.
*
* @throws java.lang.IllegalArgumentException If {@code properties} contains
* invalid wire types or case variants of the same key name.
*/
public void updateWire(Wire wire, Dictionary properties);
/**
* Return the {@code Wire} objects that match the given {@code filter}.
*
* <p>
* The list of available {@code Wire} objects is matched against the
* specified {@code filter}.{@code Wire} objects which match the
* {@code filter} must be returned. These {@code Wire} objects are not
* necessarily connected. The Wire Admin service should not return invalid
* {@code Wire} objects, but it is possible that a {@code Wire} object is
* deleted after it was placed in the list.
*
* <p>
* The filter matches against the {@code Wire} object's properties including
* {@link WireConstants#WIREADMIN_PRODUCER_PID},
* {@link WireConstants#WIREADMIN_CONSUMER_PID} and
* {@link WireConstants#WIREADMIN_PID}.
*
* @param filter Filter string to select {@code Wire} objects or
* {@code null} to select all {@code Wire} objects.
* @return An array of {@code Wire} objects which match the {@code filter}
* or {@code null} if no {@code Wire} objects match the
* {@code filter}.
* @throws org.osgi.framework.InvalidSyntaxException If the specified
* {@code filter} has an invalid syntax.
* @see org.osgi.framework.Filter
*/
public Wire[] getWires(String filter) throws InvalidSyntaxException;
}
| bsd-3-clause |
wangscript/ameba | src/test/java/ameba/event/EventTest.java | 4682 | package ameba.event;
import ameba.core.AddOn;
import ameba.core.Application;
import ameba.lib.Akka;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author icode
*/
public class EventTest {
private static final Logger logger = LoggerFactory.getLogger(EventTest.class);
@Test
public void publish() {
AddOn addOn = new Akka.AddOn();
addOn.setup(new TestApp());
EventBus eventBus = EventBus.createMix();
eventBus.subscribe(new AnnotationSub());
eventBus.subscribe(new ChildSub());
eventBus.subscribe(AnnotationSub.class);
for (int i = 0; i < 10; i++) {
final int finalI = i;
eventBus.subscribe(TestEvent.class, new AsyncListener<TestEvent>() {
@Override
public void onReceive(TestEvent event) {
logger.info("async receive message {} : {}", finalI, event.message);
}
});
eventBus.subscribe(TestEvent1.class, new AsyncListener<TestEvent1>() {
@Override
public void onReceive(TestEvent1 event) {
logger.info("TestEvent1 async receive message {} : {}", finalI, event.message);
}
});
}
for (int i = 0; i < 5; i++) {
final int finalI = i;
eventBus.subscribe(TestEvent.class, new Listener<TestEvent>() {
@Override
public void onReceive(TestEvent event) {
logger.info("receive message {} : {}", finalI, event.message);
}
});
eventBus.subscribe(TestEvent1.class, new Listener<TestEvent1>() {
@Override
public void onReceive(TestEvent1 event) {
logger.info("TestEvent1 receive message {} : {}", finalI, event.message);
}
});
}
logger.info("publish message ..");
for (int i = 0; i < 10; i++) {
eventBus.publish(new TestEvent("message: " + i));
eventBus.publish(new TestEvent1("message: " + i));
}
try {
synchronized (this) {
wait(1800);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.info("remove all event and publish message ..");
eventBus.unsubscribe(TestEvent.class);
eventBus.unsubscribe(TestEvent1.class);
for (int i = 0; i < 10; i++) {
eventBus.publish(new TestEvent("message: " + i));
eventBus.publish(new TestEvent1("message: " + i));
}
}
public static class AnnotationSub {
@Subscribe(TestEvent.class)
private void doSomething(TestEvent e) {
logger.info("AnnotationSub receive message : {}", e.message);
}
@Subscribe(value = TestEvent.class, async = true)
private void doAsyncSomething(TestEvent e) {
logger.info("Async AnnotationSub receive message : {}", e.message);
}
@Subscribe
private void doSomething2(TestEvent e) {
logger.info("CoC AnnotationSub receive message : {}", e.message);
}
@Subscribe(async = true)
private void doAsyncSomething2(TestEvent e) {
logger.info("Async CoC AnnotationSub receive message : {}", e.message);
}
@Subscribe
public void doSomething3(TestEvent e, TestEvent1 e1) {
if (e != null)
logger.info("doSomething3 CoC AnnotationSub receive TestEvent message : {}", e.message);
if (e1 != null)
logger.info("doSomething3 CoC AnnotationSub receive TestEvent1 message : {}", e1.message);
}
}
public static class ChildSub extends AnnotationSub {
@Subscribe
public void doSomething3(TestEvent e, TestEvent1 e1) {
if (e != null)
logger.info("doSomething3 CoC AnnotationSub receive TestEvent message : {}", e.message);
if (e1 != null)
logger.info("doSomething3 CoC AnnotationSub receive TestEvent1 message : {}", e1.message);
}
}
public static class TestEvent implements Event {
public String message;
public TestEvent(String message) {
this.message = message;
}
}
public static class TestEvent1 implements Event {
public String message;
public TestEvent1(String message) {
this.message = message;
}
}
private class TestApp extends Application {
public TestApp() {
}
}
}
| mit |
itlenergy/server-api | itlenergy-web/src/main/java/com/itl_energy/webcore/AuthenticationService.java | 4476 | package com.itl_energy.webcore;
import java.util.Date;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import com.itl_energy.model.User;
import com.itl_energy.repo.UserCollection;
/**
* Provides a means of authenticating users.
*
* @author Gordon Mackenzie-Leigh <gordon@stugo.co.uk>
*/
@Stateless
public class AuthenticationService {
public static final String PARAM_NAME = "sgauth";
@EJB
UserCollection users;
/**
* Gets the ticket for the current context.
* @return The ticket if available, or null.
*/
public SecurityTicket getTicket(UriInfo uri) {
MultivaluedMap<String,String> query = uri.getQueryParameters();
String value = query.getFirst(PARAM_NAME);
if (value == null)
return null;
else
return SecurityTicket.parse(value, AuthenticationServiceConfig.key, AuthenticationServiceConfig.secret);
}
/**
* Attempts to authenticate the given credentials and returns a ticket if
* successful.
* @param username
* @param password
* @return The ticket or null.
*/
public TicketModel createTicket(String username, String password) {
User user = users.get(username, password);
if (user == null)
return null;
Date expires = new Date();
expires.setTime(expires.getTime() + SecurityTicket.EXPIRES_MS);
Integer related = user.getRelatedId();
SecurityTicket ticket = new SecurityTicket(expires, username, user.getRole(), related != null ? related : 0, false);
String encrypted = ticket.encrypt(AuthenticationServiceConfig.key, AuthenticationServiceConfig.secret);
return new TicketModel(encrypted, ticket.getExpires());
}
/**
* Renews the current ticket, if any.
* @return The new ticket, or null.
*/
public TicketModel renewTicket(UriInfo uri) {
SecurityTicket ticket = getTicket(uri);
if (ticket == null)
return null;
Date expires = new Date();
expires.setTime(expires.getTime() + SecurityTicket.EXPIRES_MS);
ticket.setExpires(expires);
ticket.setReissue(true);
return new TicketModel(ticket.encrypt(AuthenticationServiceConfig.key, AuthenticationServiceConfig.secret), ticket.getExpires());
}
/**
* Throws an exception if the current user does not have the required role.
* @param role
*/
public void requireRole(UriInfo uri, String role) {
SecurityTicket ticket = getTicket(uri);
if (ticket == null || !ticket.getRole().equals(role))
throw new NotAuthorizedException();
}
/**
* Throws an exception if the current user is not related to the specified
* hub.
* @param role
*/
public void requireHub(UriInfo uri, int hubId) {
SecurityTicket ticket = getTicket(uri);
if (ticket == null || !ticket.getRole().equals(AuthRoles.ADMIN)
&& !(ticket.getRole().equals(AuthRoles.HUB) && ticket.getRelatedId() != hubId))
throw new NotAuthorizedException();
}
/**
* Throws an exception if the current user is not related to the specified
* site.
* @param role
*/
public void requireSite(UriInfo uri, int siteId) {
SecurityTicket ticket = getTicket(uri);
if (ticket == null || !ticket.getRole().equals(AuthRoles.WEATHER_REPORTER)
&& !(ticket.getRole().equals(AuthRoles.WEATHER_REPORTER) && ticket.getRelatedId() != siteId))
throw new NotAuthorizedException();
}
/**
* Throws an exception if the current ticket has been reissued or
* is older than the specified age.
* @param uri
* @param maxSeconds
*/
public void requireRecentAdmin(UriInfo uri, int maxSeconds) {
SecurityTicket ticket = getTicket(uri);
if (ticket == null || !ticket.getRole().equals(AuthRoles.ADMIN) || ticket.getReissue())
throw new NotAuthorizedException();
long issueDate = ticket.getExpires().getTime() - SecurityTicket.EXPIRES_MS;
long now = System.currentTimeMillis();
if (issueDate + maxSeconds * 1000 < now)
throw new NotAuthorizedException();
}
}
| mit |
JeffRisberg/BING01 | proxies/com/microsoft/bingads/v10/campaignmanagement/ArrayOfMediaRepresentation.java | 2153 |
package com.microsoft.bingads.v10.campaignmanagement;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ArrayOfMediaRepresentation complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ArrayOfMediaRepresentation">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="MediaRepresentation" type="{https://bingads.microsoft.com/CampaignManagement/v10}MediaRepresentation" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfMediaRepresentation", propOrder = {
"mediaRepresentations"
})
public class ArrayOfMediaRepresentation {
@XmlElement(name = "MediaRepresentation", nillable = true)
protected List<MediaRepresentation> mediaRepresentations;
/**
* Gets the value of the mediaRepresentations 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 mediaRepresentations property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMediaRepresentations().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link MediaRepresentation }
*
*
*/
public List<MediaRepresentation> getMediaRepresentations() {
if (mediaRepresentations == null) {
mediaRepresentations = new ArrayList<MediaRepresentation>();
}
return this.mediaRepresentations;
}
}
| mit |
AronXue/Android-Plugin-Framework | PluginCore/src/com/plugin/core/PluginCreator.java | 5200 | package com.plugin.core;
import java.io.File;
import java.lang.reflect.Method;
import com.plugin.content.PluginDescriptor;
import com.plugin.util.LogUtil;
import com.plugin.util.RefInvoker;
import android.app.Application;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Build;
import dalvik.system.DexClassLoader;
public class PluginCreator {
private PluginCreator() {
}
/**
* 根据插件apk文件,创建插件dex的classloader
*
* @param absolutePluginApkPath
* 插件apk文件路径
* @return
*/
public static DexClassLoader createPluginClassLoader(String absolutePluginApkPath, boolean isStandalone) {
if (!isStandalone) {
return new DexClassLoader(absolutePluginApkPath, new File(absolutePluginApkPath).getParent(),
new File(absolutePluginApkPath).getParent() + File.separator + "lib",
PluginLoader.class.getClassLoader());
} else {
return new DexClassLoader(absolutePluginApkPath, new File(absolutePluginApkPath).getParent(),
new File(absolutePluginApkPath).getParent() + File.separator + "lib",
PluginLoader.class.getClassLoader().getParent());
}
}
/**
* 根据插件apk文件,创建插件资源文件,同时绑定宿主程序的资源,这样就可以在插件中使用宿主程序的资源。
*
* @param application
* 宿主程序的Application
* @param absolutePluginApkPath
* 插件apk文件路径
* @return
*/
public static Resources createPluginResource(Application application, String absolutePluginApkPath,
boolean isStandalone) {
try {
// 如果是第三方编译的独立插件的话,插件的资源id默认是0x7f开头。
// 但是宿主程序的资源id必须使用默认值0x7f(否则在5.x系统上主题会由问题)
// 插件运行时可能会通过getActivityInfo等
// 会拿到到PluginStubActivity的ActivityInfo以及ApplicationInfo
// 这两个info里面有部分资源id是在宿主程序的Manifest中配置的,比如logo和icon
// 所有如果在独立插件中尝试通过Context获取上述这些资源会导致异常
String[] assetPaths = buildAssetPath(isStandalone, application.getApplicationInfo().sourceDir,
absolutePluginApkPath);
AssetManager assetMgr = AssetManager.class.newInstance();
RefInvoker.invokeMethod(assetMgr, AssetManager.class.getName(), "addAssetPaths",
new Class[] { String[].class }, new Object[] { assetPaths });
// Method addAssetPaths =
// AssetManager.class.getDeclaredMethod("addAssetPaths",
// String[].class);
// addAssetPaths.invoke(assetMgr, new Object[] { assetPaths });
Resources mainRes = application.getResources();
Resources pluginRes = new PluginResourceWrapper(assetMgr, mainRes.getDisplayMetrics(),
mainRes.getConfiguration());
return pluginRes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String[] buildAssetPath(boolean isStandalone, String app, String plugin) {
String[] assetPaths = new String[isStandalone ? 1 : 2];
if (!isStandalone) {
// 不可更改顺序否则不能兼容4.x
assetPaths[0] = app;
assetPaths[1] = plugin;
if ("vivo".equalsIgnoreCase(Build.BRAND) || "oppo".equalsIgnoreCase(Build.BRAND)
|| "Coolpad".equalsIgnoreCase(Build.BRAND)) {
// 但是!!!如是OPPO或者vivo4.x系统的话 ,要吧这个顺序反过来,否则在混合模式下会找不到资源
assetPaths[0] = plugin;
assetPaths[1] = app;
}
LogUtil.d("create Plugin Resource from: ", assetPaths[0], assetPaths[1]);
} else {
assetPaths[0] = plugin;
LogUtil.d("create Plugin Resource from: ", assetPaths[0]);
}
return assetPaths;
}
/* package */static Resources createPluginResourceFor5(Application application, String absolutePluginApkPath) {
try {
AssetManager assetMgr = AssetManager.class.newInstance();
Method addAssetPaths = AssetManager.class.getDeclaredMethod("addAssetPaths", String[].class);
String[] assetPaths = new String[2];
// 不可更改顺序否则不能兼容4.x
assetPaths[0] = absolutePluginApkPath;
assetPaths[1] = application.getApplicationInfo().sourceDir;
addAssetPaths.invoke(assetMgr, new Object[] { assetPaths });
Resources mainRes = application.getResources();
Resources pluginRes = new PluginResourceWrapper(assetMgr, mainRes.getDisplayMetrics(),
mainRes.getConfiguration());
LogUtil.d("create Plugin Resource from: ", assetPaths[0], assetPaths[1]);
return pluginRes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 创建插件apk的Context。
* 如果插件是运行在普通的Activity中,那么插件中需要使用context的地方,都需要使用此方法返回的Context
*
* @param application
* @param pluginRes
* @param pluginClassLoader
* @return
*/
static Context createPluginApplicationContext(PluginDescriptor pluginDescriptor, Application application, Resources pluginRes,
DexClassLoader pluginClassLoader) {
return new PluginContextTheme(pluginDescriptor, application, pluginRes, pluginClassLoader);
}
}
| mit |
chipster/chipster | src/main/java/fi/csc/microarray/messaging/message/ModuleDescriptionMessage.java | 5804 | package fi.csc.microarray.messaging.message;
import java.awt.Color;
import java.util.LinkedList;
import java.util.List;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import fi.csc.microarray.util.XmlUtil;
/**
* Message for sending module information and tool
* descriptions.
*
* @author naktinis
*
*/
public class ModuleDescriptionMessage extends ChipsterMessage {
private final static String KEY_MODULE = "module";
private final static String KEY_MODULE_NAME = "module-name";
public Document moduleXml;
private String moduleName;
private List<Category> categories = new LinkedList<Category>();
/**
* Empty constructor (needed for MessageListenerWrap.onMessage)
*/
public ModuleDescriptionMessage() { }
public ModuleDescriptionMessage(String moduleName) {
try {
// Start constructing the XML
moduleXml = XmlUtil.newDocument();
moduleXml.appendChild(moduleXml.createElement("module"));
// Set module's name
setModuleName(moduleName);
getFirstModule().setAttribute("name", moduleName);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e); // should never happen
}
}
private void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getModuleName() {
return this.moduleName;
}
public void addConfString(String configuration) {
// TODO ADD to XML
}
private Element getFirstModule() {
return (Element)moduleXml.getElementsByTagName("module").item(0);
}
/**
* Store a Category object in the inner XML.
*
* @param category
*/
public void addCategory(Category category) {
Element categoryElement = moduleXml.createElement("category");
categoryElement.setAttribute("name", category.getName());
String colorString = Integer.toHexString(category.getColor().getRGB());
colorString = "#" + colorString.substring(2, colorString.length());
categoryElement.setAttribute("color", colorString);
categoryElement.setAttribute("hidden", category.isHidden().toString());
for (Tool tool : category.getTools()) {
Element toolElement = moduleXml.createElement("tool");
toolElement.setAttribute("helpURL", tool.getHelpURL());
toolElement.setTextContent(tool.getDescription());
categoryElement.appendChild(toolElement);
}
getFirstModule().appendChild(categoryElement);
}
/**
* @return all categories contained in the inner XML.
*/
public List<Category> getCategories() {
NodeList categoryList = getFirstModule().getElementsByTagName("category");
for (int i=0; i<categoryList.getLength(); i++) {
Element categoryElement = (Element) categoryList.item(i);
Category category = new Category(categoryElement.getAttribute("name"),
categoryElement.getAttribute("color"),
Boolean.valueOf(categoryElement.getAttribute("hidden")));
NodeList toolList = categoryElement.getElementsByTagName("tool");
for (int j=0; j<toolList.getLength(); j++) {
Element toolElement = (Element) toolList.item(j);
category.addTool(toolElement.getTextContent(),
toolElement.getAttribute("helpURL"));
}
categories.add(category);
}
return categories;
}
@Override
public void unmarshal(MapMessage from) throws JMSException {
super.unmarshal(from);
this.setModuleName(from.getStringProperty(KEY_MODULE_NAME));
this.moduleXml = XmlUtil.stringToXML(from.getString(KEY_MODULE));
}
@Override
public void marshal(MapMessage to) throws JMSException {
super.marshal(to);
to.setStringProperty(KEY_MODULE_NAME, this.getModuleName());
to.setString(KEY_MODULE, XmlUtil.xmlToString(moduleXml));
}
/**
* Tool category. Contains several related tools.
*/
public static class Category {
private String name;
private List<Tool> tools = new LinkedList<Tool>();
private Color color;
private Boolean hidden;
/**
* @param name - name for this category.
* @param color - String representing hexidecimal RGB value (e.g. "FF1122")
*/
public Category(String name, String color, Boolean hidden) {
this.name = name;
this.color = Color.decode(color);
this.hidden = hidden;
}
public String getName() {
return name;
}
public Color getColor() {
return color;
}
public Boolean isHidden() {
return hidden;
}
public void addTool(String description, String helpURL) {
tools.add(new Tool(description, helpURL));
}
public List<Tool> getTools() {
return tools;
}
}
/**
* Single analysis tool.
*/
public static class Tool {
private String description;
private String helpURL;
public Tool(String description, String helpURL) {
this.description = description;
this.helpURL = helpURL;
}
public String getHelpURL() {
return helpURL;
}
public String getDescription() {
return description;
}
}
}
| mit |
ria-ee/X-Road | src/common-verifier/src/test/java/ee/ria/xroad/common/conf/globalconfextension/OcspFetchIntervalSchemaValidatorTest.java | 2959 | /**
* The MIT License
* Copyright (c) 2015 Estonian Information System Authority (RIA), Population Register Centre (VRK)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package ee.ria.xroad.common.conf.globalconfextension;
import ee.ria.xroad.common.util.ResourceUtils;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.File;
import java.net.URL;
/**
* Tests for {@link OcspFetchIntervalSchemaValidator}
*/
public class OcspFetchIntervalSchemaValidatorTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
private static final String VALID_FILE = "valid-fetchinterval-params.xml";
private static final String EMPTY_FILE = "empty-fetchinterval-params.xml";
private static final String INVALID_FILE = "invalid-fetchinterval-params.xml";
private String getClasspathFilename(String fileName) {
URL schemaLocation = ResourceUtils.class.getClassLoader().getResource(fileName);
File f = FileUtils.toFile(schemaLocation);
return f.getPath();
}
@Test
public void testValidConfiguration() throws Exception {
OcspFetchIntervalSchemaValidator validator = new OcspFetchIntervalSchemaValidator();
validator.validateFile(getClasspathFilename(VALID_FILE));
}
@Test
public void testEmptyConfigurationIsInvalid() throws Exception {
OcspFetchIntervalSchemaValidator validator = new OcspFetchIntervalSchemaValidator();
exception.expect(Exception.class);
validator.validateFile(getClasspathFilename(EMPTY_FILE));
}
@Test
public void testInvalidConfiguration() throws Exception {
OcspFetchIntervalSchemaValidator validator = new OcspFetchIntervalSchemaValidator();
exception.expect(Exception.class);
validator.validateFile(getClasspathFilename(INVALID_FILE));
}
}
| mit |
LachlanMcKee/gsonpath | sample/src/main/java/android/support/annotation/IntRange.java | 517 | package android.support.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.SOURCE;
@Retention(SOURCE)
@Target({METHOD, PARAMETER, FIELD, LOCAL_VARIABLE, ANNOTATION_TYPE})
public @interface IntRange {
/**
* Smallest value, inclusive
*/
long from() default Long.MIN_VALUE;
/**
* Largest value, inclusive
*/
long to() default Long.MAX_VALUE;
} | mit |
martrik/COMP101 | Term2/OOP/Lab3/SimpleOrderSystem/src/SimpleOrderSystem.java | 1774 |
public class SimpleOrderSystem
{
public static void main(String[] args)
{
Input in = new Input();
// The model is responsible for managing the data structure and the operations on it.
SimpleOrderSystemModel model = new DataManager();
initialiseExampleData(model);
// Create objects to manage the user interface
SimpleOrderSystemView ui = new SimpleOrderSystemTerminalUI(in,model);
OrderEntryController orderEntryController = new OrderEntryController(model,ui);
ui.addOrderEntryController(orderEntryController);
// Start off the main program loop
ui.run();
}
// Provide some default data to illustrate how the Customer, Order and LineItem
// classes are used, and to provide a quick way to add sample data while developing
// the code.
public static void initialiseExampleData(SimpleOrderSystemModel model)
{
model.addCustomer("First1", "Second1", "Address1", "Phone1", "Mobile1", "Email1");
model.addCustomer("First2", "Second2", "Address2", "Phone2", "Mobile2", "Email2");
model.addProduct(1,"Description1",100);
model.addProduct(2,"Description2",200);
LineItem item1 = new LineItem(1,model.getProduct(1));
Order order1 = new Order();
order1.add(item1);
model.getCustomer("First1", "Second1").addOrder(order1);
LineItem item2 = new LineItem(2,model.getProduct(1));
LineItem item3 = new LineItem(1,model.getProduct(2));
Order order2 = new Order();
order2.add(item2);
order2.add(item3);
LineItem item4 = new LineItem(4,model.getProduct(1));
Order order3 = new Order();
order3.add(item4);
model.getCustomer("First2", "Second2").addOrder(order2);
model.getCustomer("First2", "Second2").addOrder(order3);
}
}
| mit |
Hades1996/Proyectos-U | NetBeansProjects/Parcial/src/Control/Ejecutar.java | 1053 | /*
* 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 Control;
import Modelo.AdmonSalones;
import Vista.InOut;
/**
*
* @author Yair
*/
public class Ejecutar {
public static void main(String[] args) {
InOut ob1 = new InOut();
AdmonSalones ob2;
int numSalones;
ob1.mostrar("Parcial - administración de salones\n Yair Lopez Poveda"
+ " Código: 20141578024");
numSalones = ob1.solicitarNum("Ingrese el número de salones por piso:");
while(Modelo.AdmonSalones.validarDato(numSalones)==false){
numSalones = ob1.solicitarNum("¡Error!\n"
+ "Ingrese un tamaño válido de filas para la matriz 1:");
}
ob2 = new AdmonSalones(numSalones);
ob2.inicializarValores();
ob2.ejecutarMenu();
}
}
| mit |
uphold/uphold-sdk-android | src/app/src/androidTest/java/com/uphold/uphold_android_sdk/test/integration/service/ReserveServiceTest.java | 5024 | package com.uphold.uphold_android_sdk.test.integration.service;
import com.darylteo.rx.promises.java.Promise;
import com.darylteo.rx.promises.java.functions.RepromiseFunction;
import junit.framework.Assert;
import com.uphold.uphold_android_sdk.client.restadapter.UpholdRestAdapter;
import com.uphold.uphold_android_sdk.client.retrofitpromise.RetrofitPromise;
import com.uphold.uphold_android_sdk.model.Transaction;
import com.uphold.uphold_android_sdk.model.reserve.Deposit;
import com.uphold.uphold_android_sdk.model.reserve.ReserveStatistics;
import com.uphold.uphold_android_sdk.service.ReserveService;
import com.uphold.uphold_android_sdk.test.BuildConfig;
import com.uphold.uphold_android_sdk.test.util.MockRestAdapter;
import org.junit.Test;
import org.junit.runner.RunWith;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;
import java.lang.String;
import java.util.List;
import retrofit.client.Header;
import retrofit.client.Request;
/**
* ReserveService integration tests.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class ReserveServiceTest {
@Test
public void getLedgerShouldReturnTheRequest() throws Exception {
final MockRestAdapter<List<Deposit>> adapter = new MockRestAdapter<>(null, null);
adapter.request(new RepromiseFunction<UpholdRestAdapter, List<Deposit>>() {
@Override
public Promise<List<Deposit>> call(UpholdRestAdapter upholdRestAdapter) {
ReserveService reserveService = adapter.getRestAdapter().create(ReserveService.class);
RetrofitPromise<List<Deposit>> promise = new RetrofitPromise<>();
reserveService.getLedger("foobar", promise);
return promise;
}
});
Request request = adapter.getRequest();
Assert.assertEquals(request.getMethod(), "GET");
Assert.assertEquals(request.getUrl(), String.format("%s/v0/reserve/ledger", BuildConfig.API_SERVER_URL));
Assert.assertTrue(request.getHeaders().contains(new Header("Range", "foobar")));
}
@Test
public void getReserveTransactionByIdShouldReturnTheRequest() throws Exception {
final MockRestAdapter<Transaction> adapter = new MockRestAdapter<>(null, null);
adapter.request(new RepromiseFunction<UpholdRestAdapter, Transaction>() {
@Override
public Promise<Transaction> call(UpholdRestAdapter upholdRestAdapter) {
ReserveService reserveService = adapter.getRestAdapter().create(ReserveService.class);
RetrofitPromise<Transaction> promise = new RetrofitPromise<>();
reserveService.getReserveTransactionById("foobar", promise);
return promise;
}
});
Request request = adapter.getRequest();
Assert.assertEquals(request.getMethod(), "GET");
Assert.assertEquals(request.getUrl(), String.format("%s/v0/reserve/transactions/foobar", BuildConfig.API_SERVER_URL));
}
@Test
public void getReserveTransactionsShouldReturnTheRequest() throws Exception {
final MockRestAdapter<List<Transaction>> adapter = new MockRestAdapter<>(null, null);
adapter.request(new RepromiseFunction<UpholdRestAdapter, List<Transaction>>() {
@Override
public Promise<List<Transaction>> call(UpholdRestAdapter upholdRestAdapter) {
ReserveService reserveService = adapter.getRestAdapter().create(ReserveService.class);
RetrofitPromise<List<Transaction>> promise = new RetrofitPromise<>();
reserveService.getReserveTransactions("foobar", promise);
return promise;
}
});
Request request = adapter.getRequest();
Assert.assertEquals(request.getMethod(), "GET");
Assert.assertEquals(request.getUrl(), String.format("%s/v0/reserve/transactions", BuildConfig.API_SERVER_URL));
Assert.assertTrue(request.getHeaders().contains(new Header("Range", "foobar")));
}
@Test
public void getReserveStatisticsShouldReturnTheRequest() throws Exception {
final MockRestAdapter<List<ReserveStatistics>> adapter = new MockRestAdapter<>(null, null);
adapter.request(new RepromiseFunction<UpholdRestAdapter, List<ReserveStatistics>>() {
@Override
public Promise<List<ReserveStatistics>> call(UpholdRestAdapter upholdRestAdapter) {
ReserveService reserveService = adapter.getRestAdapter().create(ReserveService.class);
RetrofitPromise<List<ReserveStatistics>> promise = new RetrofitPromise<>();
reserveService.getStatistics(promise);
return promise;
}
});
Request request = adapter.getRequest();
Assert.assertEquals(request.getMethod(), "GET");
Assert.assertEquals(request.getUrl(), String.format("%s/v0/reserve/statistics", BuildConfig.API_SERVER_URL));
}
}
| mit |
Frankst2/SugarOnRest | sugaronrest/src/main/java/com/sugaronrest/modules/OutboundEmail.java | 3740 | /**
* <auto-generated />
* This file was generated by a StringTemplate 4 template.
* Don't change it directly as your change would get overwritten. Instead, make changes
* to the .stg file (i.e. the StringTemplate 4 template file) and save it to regenerate this file.
*
* For more infor on StringTemplate 4 template please go to -
* https://github.com/antlr/antlrcs
*
* @author Kola Oyewumi
* @version 1.0.0
* @since 2017-01-03
*
* A class which represents the outbound_email table.
*/
package com.sugaronrest.modules;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.sugaronrest.restapicalls.Module;
import com.sugaronrest.restapicalls.CustomDateDeserializer;
import com.sugaronrest.restapicalls.CustomDateSerializer;
@Module(name = "", tablename = "outbound_email")
@JsonRootName(value = "outbound_email")
@JsonIgnoreProperties(ignoreUnknown = true)
public class OutboundEmail {
public String getId() {
return id;
}
public void setId(String value) {
id = value;
}
public String getName() {
return name;
}
public void setName(String value) {
name = value;
}
public String getType() {
return type;
}
public void setType(String value) {
type = value;
}
public String getUserId() {
return userId;
}
public void setUserId(String value) {
userId = value;
}
public String getMailSendtype() {
return mailSendtype;
}
public void setMailSendtype(String value) {
mailSendtype = value;
}
public String getMailSmtptype() {
return mailSmtptype;
}
public void setMailSmtptype(String value) {
mailSmtptype = value;
}
public String getMailSmtpserver() {
return mailSmtpserver;
}
public void setMailSmtpserver(String value) {
mailSmtpserver = value;
}
public Integer getMailSmtpport() {
return mailSmtpport;
}
public void setMailSmtpport(Integer value) {
mailSmtpport = value;
}
public String getMailSmtpuser() {
return mailSmtpuser;
}
public void setMailSmtpuser(String value) {
mailSmtpuser = value;
}
public String getMailSmtppass() {
return mailSmtppass;
}
public void setMailSmtppass(String value) {
mailSmtppass = value;
}
public Integer getMailSmtpauthReq() {
return mailSmtpauthReq;
}
public void setMailSmtpauthReq(Integer value) {
mailSmtpauthReq = value;
}
public Integer getMailSmtpssl() {
return mailSmtpssl;
}
public void setMailSmtpssl(Integer value) {
mailSmtpssl = value;
}
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("type")
private String type;
@JsonProperty("user_id")
private String userId;
@JsonProperty("mail_sendtype")
private String mailSendtype;
@JsonProperty("mail_smtptype")
private String mailSmtptype;
@JsonProperty("mail_smtpserver")
private String mailSmtpserver;
@JsonProperty("mail_smtpport")
private Integer mailSmtpport;
@JsonProperty("mail_smtpuser")
private String mailSmtpuser;
@JsonProperty("mail_smtppass")
private String mailSmtppass;
@JsonProperty("mail_smtpauth_req")
private Integer mailSmtpauthReq;
@JsonProperty("mail_smtpssl")
private Integer mailSmtpssl;
}
| mit |
georghinkel/ttc2017smartGrids | solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61968/Metering/impl/EndDeviceControlImpl.java | 26820 | /**
*/
package gluemodel.CIM.IEC61968.Metering.impl;
import gluemodel.CIM.IEC61968.Common.DateTimeInterval;
import gluemodel.CIM.IEC61968.Customers.CustomerAgreement;
import gluemodel.CIM.IEC61968.Customers.CustomersPackage;
import gluemodel.CIM.IEC61968.Metering.DemandResponseProgram;
import gluemodel.CIM.IEC61968.Metering.EndDeviceAsset;
import gluemodel.CIM.IEC61968.Metering.EndDeviceControl;
import gluemodel.CIM.IEC61968.Metering.EndDeviceGroup;
import gluemodel.CIM.IEC61968.Metering.MeteringPackage;
import gluemodel.CIM.IEC61970.Core.impl.IdentifiedObjectImpl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>End Device Control</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link gluemodel.CIM.IEC61968.Metering.impl.EndDeviceControlImpl#getScheduledInterval <em>Scheduled Interval</em>}</li>
* <li>{@link gluemodel.CIM.IEC61968.Metering.impl.EndDeviceControlImpl#isDrProgramMandatory <em>Dr Program Mandatory</em>}</li>
* <li>{@link gluemodel.CIM.IEC61968.Metering.impl.EndDeviceControlImpl#getDrProgramLevel <em>Dr Program Level</em>}</li>
* <li>{@link gluemodel.CIM.IEC61968.Metering.impl.EndDeviceControlImpl#getCustomerAgreement <em>Customer Agreement</em>}</li>
* <li>{@link gluemodel.CIM.IEC61968.Metering.impl.EndDeviceControlImpl#getEndDeviceAsset <em>End Device Asset</em>}</li>
* <li>{@link gluemodel.CIM.IEC61968.Metering.impl.EndDeviceControlImpl#getType <em>Type</em>}</li>
* <li>{@link gluemodel.CIM.IEC61968.Metering.impl.EndDeviceControlImpl#getPriceSignal <em>Price Signal</em>}</li>
* <li>{@link gluemodel.CIM.IEC61968.Metering.impl.EndDeviceControlImpl#getEndDeviceGroup <em>End Device Group</em>}</li>
* <li>{@link gluemodel.CIM.IEC61968.Metering.impl.EndDeviceControlImpl#getDemandResponseProgram <em>Demand Response Program</em>}</li>
* </ul>
*
* @generated
*/
public class EndDeviceControlImpl extends IdentifiedObjectImpl implements EndDeviceControl {
/**
* The cached value of the '{@link #getScheduledInterval() <em>Scheduled Interval</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getScheduledInterval()
* @generated
* @ordered
*/
protected DateTimeInterval scheduledInterval;
/**
* The default value of the '{@link #isDrProgramMandatory() <em>Dr Program Mandatory</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isDrProgramMandatory()
* @generated
* @ordered
*/
protected static final boolean DR_PROGRAM_MANDATORY_EDEFAULT = false;
/**
* The cached value of the '{@link #isDrProgramMandatory() <em>Dr Program Mandatory</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isDrProgramMandatory()
* @generated
* @ordered
*/
protected boolean drProgramMandatory = DR_PROGRAM_MANDATORY_EDEFAULT;
/**
* The default value of the '{@link #getDrProgramLevel() <em>Dr Program Level</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDrProgramLevel()
* @generated
* @ordered
*/
protected static final int DR_PROGRAM_LEVEL_EDEFAULT = 0;
/**
* The cached value of the '{@link #getDrProgramLevel() <em>Dr Program Level</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDrProgramLevel()
* @generated
* @ordered
*/
protected int drProgramLevel = DR_PROGRAM_LEVEL_EDEFAULT;
/**
* The cached value of the '{@link #getCustomerAgreement() <em>Customer Agreement</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCustomerAgreement()
* @generated
* @ordered
*/
protected CustomerAgreement customerAgreement;
/**
* The cached value of the '{@link #getEndDeviceAsset() <em>End Device Asset</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getEndDeviceAsset()
* @generated
* @ordered
*/
protected EndDeviceAsset endDeviceAsset;
/**
* The default value of the '{@link #getType() <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected static final String TYPE_EDEFAULT = null;
/**
* The cached value of the '{@link #getType() <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected String type = TYPE_EDEFAULT;
/**
* The default value of the '{@link #getPriceSignal() <em>Price Signal</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPriceSignal()
* @generated
* @ordered
*/
protected static final float PRICE_SIGNAL_EDEFAULT = 0.0F;
/**
* The cached value of the '{@link #getPriceSignal() <em>Price Signal</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPriceSignal()
* @generated
* @ordered
*/
protected float priceSignal = PRICE_SIGNAL_EDEFAULT;
/**
* The cached value of the '{@link #getEndDeviceGroup() <em>End Device Group</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getEndDeviceGroup()
* @generated
* @ordered
*/
protected EndDeviceGroup endDeviceGroup;
/**
* The cached value of the '{@link #getDemandResponseProgram() <em>Demand Response Program</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDemandResponseProgram()
* @generated
* @ordered
*/
protected DemandResponseProgram demandResponseProgram;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EndDeviceControlImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return MeteringPackage.Literals.END_DEVICE_CONTROL;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DateTimeInterval getScheduledInterval() {
if (scheduledInterval != null && scheduledInterval.eIsProxy()) {
InternalEObject oldScheduledInterval = (InternalEObject)scheduledInterval;
scheduledInterval = (DateTimeInterval)eResolveProxy(oldScheduledInterval);
if (scheduledInterval != oldScheduledInterval) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL, oldScheduledInterval, scheduledInterval));
}
}
return scheduledInterval;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DateTimeInterval basicGetScheduledInterval() {
return scheduledInterval;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setScheduledInterval(DateTimeInterval newScheduledInterval) {
DateTimeInterval oldScheduledInterval = scheduledInterval;
scheduledInterval = newScheduledInterval;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL, oldScheduledInterval, scheduledInterval));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isDrProgramMandatory() {
return drProgramMandatory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDrProgramMandatory(boolean newDrProgramMandatory) {
boolean oldDrProgramMandatory = drProgramMandatory;
drProgramMandatory = newDrProgramMandatory;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY, oldDrProgramMandatory, drProgramMandatory));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getDrProgramLevel() {
return drProgramLevel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDrProgramLevel(int newDrProgramLevel) {
int oldDrProgramLevel = drProgramLevel;
drProgramLevel = newDrProgramLevel;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL, oldDrProgramLevel, drProgramLevel));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CustomerAgreement getCustomerAgreement() {
if (customerAgreement != null && customerAgreement.eIsProxy()) {
InternalEObject oldCustomerAgreement = (InternalEObject)customerAgreement;
customerAgreement = (CustomerAgreement)eResolveProxy(oldCustomerAgreement);
if (customerAgreement != oldCustomerAgreement) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT, oldCustomerAgreement, customerAgreement));
}
}
return customerAgreement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CustomerAgreement basicGetCustomerAgreement() {
return customerAgreement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetCustomerAgreement(CustomerAgreement newCustomerAgreement, NotificationChain msgs) {
CustomerAgreement oldCustomerAgreement = customerAgreement;
customerAgreement = newCustomerAgreement;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT, oldCustomerAgreement, newCustomerAgreement);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCustomerAgreement(CustomerAgreement newCustomerAgreement) {
if (newCustomerAgreement != customerAgreement) {
NotificationChain msgs = null;
if (customerAgreement != null)
msgs = ((InternalEObject)customerAgreement).eInverseRemove(this, CustomersPackage.CUSTOMER_AGREEMENT__END_DEVICE_CONTROLS, CustomerAgreement.class, msgs);
if (newCustomerAgreement != null)
msgs = ((InternalEObject)newCustomerAgreement).eInverseAdd(this, CustomersPackage.CUSTOMER_AGREEMENT__END_DEVICE_CONTROLS, CustomerAgreement.class, msgs);
msgs = basicSetCustomerAgreement(newCustomerAgreement, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT, newCustomerAgreement, newCustomerAgreement));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EndDeviceAsset getEndDeviceAsset() {
if (endDeviceAsset != null && endDeviceAsset.eIsProxy()) {
InternalEObject oldEndDeviceAsset = (InternalEObject)endDeviceAsset;
endDeviceAsset = (EndDeviceAsset)eResolveProxy(oldEndDeviceAsset);
if (endDeviceAsset != oldEndDeviceAsset) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_ASSET, oldEndDeviceAsset, endDeviceAsset));
}
}
return endDeviceAsset;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EndDeviceAsset basicGetEndDeviceAsset() {
return endDeviceAsset;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetEndDeviceAsset(EndDeviceAsset newEndDeviceAsset, NotificationChain msgs) {
EndDeviceAsset oldEndDeviceAsset = endDeviceAsset;
endDeviceAsset = newEndDeviceAsset;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_ASSET, oldEndDeviceAsset, newEndDeviceAsset);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setEndDeviceAsset(EndDeviceAsset newEndDeviceAsset) {
if (newEndDeviceAsset != endDeviceAsset) {
NotificationChain msgs = null;
if (endDeviceAsset != null)
msgs = ((InternalEObject)endDeviceAsset).eInverseRemove(this, MeteringPackage.END_DEVICE_ASSET__END_DEVICE_CONTROLS, EndDeviceAsset.class, msgs);
if (newEndDeviceAsset != null)
msgs = ((InternalEObject)newEndDeviceAsset).eInverseAdd(this, MeteringPackage.END_DEVICE_ASSET__END_DEVICE_CONTROLS, EndDeviceAsset.class, msgs);
msgs = basicSetEndDeviceAsset(newEndDeviceAsset, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_ASSET, newEndDeviceAsset, newEndDeviceAsset));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getType() {
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setType(String newType) {
String oldType = type;
type = newType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__TYPE, oldType, type));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getPriceSignal() {
return priceSignal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPriceSignal(float newPriceSignal) {
float oldPriceSignal = priceSignal;
priceSignal = newPriceSignal;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL, oldPriceSignal, priceSignal));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EndDeviceGroup getEndDeviceGroup() {
if (endDeviceGroup != null && endDeviceGroup.eIsProxy()) {
InternalEObject oldEndDeviceGroup = (InternalEObject)endDeviceGroup;
endDeviceGroup = (EndDeviceGroup)eResolveProxy(oldEndDeviceGroup);
if (endDeviceGroup != oldEndDeviceGroup) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP, oldEndDeviceGroup, endDeviceGroup));
}
}
return endDeviceGroup;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EndDeviceGroup basicGetEndDeviceGroup() {
return endDeviceGroup;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetEndDeviceGroup(EndDeviceGroup newEndDeviceGroup, NotificationChain msgs) {
EndDeviceGroup oldEndDeviceGroup = endDeviceGroup;
endDeviceGroup = newEndDeviceGroup;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP, oldEndDeviceGroup, newEndDeviceGroup);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setEndDeviceGroup(EndDeviceGroup newEndDeviceGroup) {
if (newEndDeviceGroup != endDeviceGroup) {
NotificationChain msgs = null;
if (endDeviceGroup != null)
msgs = ((InternalEObject)endDeviceGroup).eInverseRemove(this, MeteringPackage.END_DEVICE_GROUP__END_DEVICE_CONTROLS, EndDeviceGroup.class, msgs);
if (newEndDeviceGroup != null)
msgs = ((InternalEObject)newEndDeviceGroup).eInverseAdd(this, MeteringPackage.END_DEVICE_GROUP__END_DEVICE_CONTROLS, EndDeviceGroup.class, msgs);
msgs = basicSetEndDeviceGroup(newEndDeviceGroup, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP, newEndDeviceGroup, newEndDeviceGroup));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DemandResponseProgram getDemandResponseProgram() {
if (demandResponseProgram != null && demandResponseProgram.eIsProxy()) {
InternalEObject oldDemandResponseProgram = (InternalEObject)demandResponseProgram;
demandResponseProgram = (DemandResponseProgram)eResolveProxy(oldDemandResponseProgram);
if (demandResponseProgram != oldDemandResponseProgram) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM, oldDemandResponseProgram, demandResponseProgram));
}
}
return demandResponseProgram;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DemandResponseProgram basicGetDemandResponseProgram() {
return demandResponseProgram;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDemandResponseProgram(DemandResponseProgram newDemandResponseProgram, NotificationChain msgs) {
DemandResponseProgram oldDemandResponseProgram = demandResponseProgram;
demandResponseProgram = newDemandResponseProgram;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM, oldDemandResponseProgram, newDemandResponseProgram);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDemandResponseProgram(DemandResponseProgram newDemandResponseProgram) {
if (newDemandResponseProgram != demandResponseProgram) {
NotificationChain msgs = null;
if (demandResponseProgram != null)
msgs = ((InternalEObject)demandResponseProgram).eInverseRemove(this, MeteringPackage.DEMAND_RESPONSE_PROGRAM__END_DEVICE_CONTROLS, DemandResponseProgram.class, msgs);
if (newDemandResponseProgram != null)
msgs = ((InternalEObject)newDemandResponseProgram).eInverseAdd(this, MeteringPackage.DEMAND_RESPONSE_PROGRAM__END_DEVICE_CONTROLS, DemandResponseProgram.class, msgs);
msgs = basicSetDemandResponseProgram(newDemandResponseProgram, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM, newDemandResponseProgram, newDemandResponseProgram));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT:
if (customerAgreement != null)
msgs = ((InternalEObject)customerAgreement).eInverseRemove(this, CustomersPackage.CUSTOMER_AGREEMENT__END_DEVICE_CONTROLS, CustomerAgreement.class, msgs);
return basicSetCustomerAgreement((CustomerAgreement)otherEnd, msgs);
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_ASSET:
if (endDeviceAsset != null)
msgs = ((InternalEObject)endDeviceAsset).eInverseRemove(this, MeteringPackage.END_DEVICE_ASSET__END_DEVICE_CONTROLS, EndDeviceAsset.class, msgs);
return basicSetEndDeviceAsset((EndDeviceAsset)otherEnd, msgs);
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP:
if (endDeviceGroup != null)
msgs = ((InternalEObject)endDeviceGroup).eInverseRemove(this, MeteringPackage.END_DEVICE_GROUP__END_DEVICE_CONTROLS, EndDeviceGroup.class, msgs);
return basicSetEndDeviceGroup((EndDeviceGroup)otherEnd, msgs);
case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM:
if (demandResponseProgram != null)
msgs = ((InternalEObject)demandResponseProgram).eInverseRemove(this, MeteringPackage.DEMAND_RESPONSE_PROGRAM__END_DEVICE_CONTROLS, DemandResponseProgram.class, msgs);
return basicSetDemandResponseProgram((DemandResponseProgram)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT:
return basicSetCustomerAgreement(null, msgs);
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_ASSET:
return basicSetEndDeviceAsset(null, msgs);
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP:
return basicSetEndDeviceGroup(null, msgs);
case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM:
return basicSetDemandResponseProgram(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL:
if (resolve) return getScheduledInterval();
return basicGetScheduledInterval();
case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY:
return isDrProgramMandatory();
case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL:
return getDrProgramLevel();
case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT:
if (resolve) return getCustomerAgreement();
return basicGetCustomerAgreement();
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_ASSET:
if (resolve) return getEndDeviceAsset();
return basicGetEndDeviceAsset();
case MeteringPackage.END_DEVICE_CONTROL__TYPE:
return getType();
case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL:
return getPriceSignal();
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP:
if (resolve) return getEndDeviceGroup();
return basicGetEndDeviceGroup();
case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM:
if (resolve) return getDemandResponseProgram();
return basicGetDemandResponseProgram();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL:
setScheduledInterval((DateTimeInterval)newValue);
return;
case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY:
setDrProgramMandatory((Boolean)newValue);
return;
case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL:
setDrProgramLevel((Integer)newValue);
return;
case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT:
setCustomerAgreement((CustomerAgreement)newValue);
return;
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_ASSET:
setEndDeviceAsset((EndDeviceAsset)newValue);
return;
case MeteringPackage.END_DEVICE_CONTROL__TYPE:
setType((String)newValue);
return;
case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL:
setPriceSignal((Float)newValue);
return;
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP:
setEndDeviceGroup((EndDeviceGroup)newValue);
return;
case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM:
setDemandResponseProgram((DemandResponseProgram)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL:
setScheduledInterval((DateTimeInterval)null);
return;
case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY:
setDrProgramMandatory(DR_PROGRAM_MANDATORY_EDEFAULT);
return;
case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL:
setDrProgramLevel(DR_PROGRAM_LEVEL_EDEFAULT);
return;
case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT:
setCustomerAgreement((CustomerAgreement)null);
return;
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_ASSET:
setEndDeviceAsset((EndDeviceAsset)null);
return;
case MeteringPackage.END_DEVICE_CONTROL__TYPE:
setType(TYPE_EDEFAULT);
return;
case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL:
setPriceSignal(PRICE_SIGNAL_EDEFAULT);
return;
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP:
setEndDeviceGroup((EndDeviceGroup)null);
return;
case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM:
setDemandResponseProgram((DemandResponseProgram)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL:
return scheduledInterval != null;
case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY:
return drProgramMandatory != DR_PROGRAM_MANDATORY_EDEFAULT;
case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL:
return drProgramLevel != DR_PROGRAM_LEVEL_EDEFAULT;
case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT:
return customerAgreement != null;
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_ASSET:
return endDeviceAsset != null;
case MeteringPackage.END_DEVICE_CONTROL__TYPE:
return TYPE_EDEFAULT == null ? type != null : !TYPE_EDEFAULT.equals(type);
case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL:
return priceSignal != PRICE_SIGNAL_EDEFAULT;
case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP:
return endDeviceGroup != null;
case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM:
return demandResponseProgram != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (drProgramMandatory: ");
result.append(drProgramMandatory);
result.append(", drProgramLevel: ");
result.append(drProgramLevel);
result.append(", type: ");
result.append(type);
result.append(", priceSignal: ");
result.append(priceSignal);
result.append(')');
return result.toString();
}
} //EndDeviceControlImpl
| mit |
martinsawicki/azure-sdk-for-java | azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/RouteFiltersInner.java | 69813 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.implementation;
import com.microsoft.azure.management.resources.fluentcore.collection.InnerSupportsGet;
import com.microsoft.azure.management.resources.fluentcore.collection.InnerSupportsDelete;
import com.microsoft.azure.management.resources.fluentcore.collection.InnerSupportsListing;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.Validator;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.HTTP;
import retrofit2.http.PATCH;
import retrofit2.http.Path;
import retrofit2.http.PUT;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in RouteFilters.
*/
public class RouteFiltersInner implements InnerSupportsGet<RouteFilterInner>, InnerSupportsDelete<Void>, InnerSupportsListing<RouteFilterInner> {
/** The Retrofit service to perform REST calls. */
private RouteFiltersService service;
/** The service client containing this operation class. */
private NetworkManagementClientImpl client;
/**
* Initializes an instance of RouteFiltersInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public RouteFiltersInner(Retrofit retrofit, NetworkManagementClientImpl client) {
this.service = retrofit.create(RouteFiltersService.class);
this.client = client;
}
/**
* The interface defining all the services for RouteFilters to be
* used by Retrofit to perform actually REST calls.
*/
interface RouteFiltersService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters delete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> delete(@Path("resourceGroupName") String resourceGroupName, @Path("routeFilterName") String routeFilterName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters beginDelete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> beginDelete(@Path("resourceGroupName") String resourceGroupName, @Path("routeFilterName") String routeFilterName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters getByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}")
Observable<Response<ResponseBody>> getByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("routeFilterName") String routeFilterName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Query("$expand") String expand, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters createOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}")
Observable<Response<ResponseBody>> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("routeFilterName") String routeFilterName, @Path("subscriptionId") String subscriptionId, @Body RouteFilterInner routeFilterParameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters beginCreateOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}")
Observable<Response<ResponseBody>> beginCreateOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("routeFilterName") String routeFilterName, @Path("subscriptionId") String subscriptionId, @Body RouteFilterInner routeFilterParameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters update" })
@PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}")
Observable<Response<ResponseBody>> update(@Path("resourceGroupName") String resourceGroupName, @Path("routeFilterName") String routeFilterName, @Path("subscriptionId") String subscriptionId, @Body PatchRouteFilterInner routeFilterParameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters beginUpdate" })
@PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}")
Observable<Response<ResponseBody>> beginUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("routeFilterName") String routeFilterName, @Path("subscriptionId") String subscriptionId, @Body PatchRouteFilterInner routeFilterParameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters listByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters")
Observable<Response<ResponseBody>> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters list" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.Network/routeFilters")
Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters listByResourceGroupNext" })
@GET
Observable<Response<ResponseBody>> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.RouteFilters listNext" })
@GET
Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Deletes the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void delete(String resourceGroupName, String routeFilterName) {
deleteWithServiceResponseAsync(resourceGroupName, routeFilterName).toBlocking().last().body();
}
/**
* Deletes the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> deleteAsync(String resourceGroupName, String routeFilterName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, routeFilterName), serviceCallback);
}
/**
* Deletes the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<Void> deleteAsync(String resourceGroupName, String routeFilterName) {
return deleteWithServiceResponseAsync(resourceGroupName, routeFilterName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String routeFilterName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (routeFilterName == null) {
throw new IllegalArgumentException("Parameter routeFilterName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2017-08-01";
Observable<Response<ResponseBody>> observable = service.delete(resourceGroupName, routeFilterName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType());
}
/**
* Deletes the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void beginDelete(String resourceGroupName, String routeFilterName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, routeFilterName).toBlocking().single().body();
}
/**
* Deletes the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String routeFilterName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, routeFilterName), serviceCallback);
}
/**
* Deletes the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<Void> beginDeleteAsync(String resourceGroupName, String routeFilterName) {
return beginDeleteWithServiceResponseAsync(resourceGroupName, routeFilterName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String routeFilterName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (routeFilterName == null) {
throw new IllegalArgumentException("Parameter routeFilterName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2017-08-01";
return service.beginDelete(resourceGroupName, routeFilterName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = beginDeleteDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter())
.register(202, new TypeToken<Void>() { }.getType())
.register(200, new TypeToken<Void>() { }.getType())
.register(204, new TypeToken<Void>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the RouteFilterInner object if successful.
*/
public RouteFilterInner getByResourceGroup(String resourceGroupName, String routeFilterName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, routeFilterName).toBlocking().single().body();
}
/**
* Gets the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<RouteFilterInner> getByResourceGroupAsync(String resourceGroupName, String routeFilterName, final ServiceCallback<RouteFilterInner> serviceCallback) {
return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, routeFilterName), serviceCallback);
}
/**
* Gets the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the RouteFilterInner object
*/
public Observable<RouteFilterInner> getByResourceGroupAsync(String resourceGroupName, String routeFilterName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, routeFilterName).map(new Func1<ServiceResponse<RouteFilterInner>, RouteFilterInner>() {
@Override
public RouteFilterInner call(ServiceResponse<RouteFilterInner> response) {
return response.body();
}
});
}
/**
* Gets the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the RouteFilterInner object
*/
public Observable<ServiceResponse<RouteFilterInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String routeFilterName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (routeFilterName == null) {
throw new IllegalArgumentException("Parameter routeFilterName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2017-08-01";
final String expand = null;
return service.getByResourceGroup(resourceGroupName, routeFilterName, this.client.subscriptionId(), apiVersion, expand, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<RouteFilterInner>>>() {
@Override
public Observable<ServiceResponse<RouteFilterInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<RouteFilterInner> clientResponse = getByResourceGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
/**
* Gets the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param expand Expands referenced express route bgp peering resources.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the RouteFilterInner object if successful.
*/
public RouteFilterInner getByResourceGroup(String resourceGroupName, String routeFilterName, String expand) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, routeFilterName, expand).toBlocking().single().body();
}
/**
* Gets the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param expand Expands referenced express route bgp peering resources.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<RouteFilterInner> getByResourceGroupAsync(String resourceGroupName, String routeFilterName, String expand, final ServiceCallback<RouteFilterInner> serviceCallback) {
return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, routeFilterName, expand), serviceCallback);
}
/**
* Gets the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param expand Expands referenced express route bgp peering resources.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the RouteFilterInner object
*/
public Observable<RouteFilterInner> getByResourceGroupAsync(String resourceGroupName, String routeFilterName, String expand) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, routeFilterName, expand).map(new Func1<ServiceResponse<RouteFilterInner>, RouteFilterInner>() {
@Override
public RouteFilterInner call(ServiceResponse<RouteFilterInner> response) {
return response.body();
}
});
}
/**
* Gets the specified route filter.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param expand Expands referenced express route bgp peering resources.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the RouteFilterInner object
*/
public Observable<ServiceResponse<RouteFilterInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String routeFilterName, String expand) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (routeFilterName == null) {
throw new IllegalArgumentException("Parameter routeFilterName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2017-08-01";
return service.getByResourceGroup(resourceGroupName, routeFilterName, this.client.subscriptionId(), apiVersion, expand, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<RouteFilterInner>>>() {
@Override
public Observable<ServiceResponse<RouteFilterInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<RouteFilterInner> clientResponse = getByResourceGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<RouteFilterInner> getByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<RouteFilterInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<RouteFilterInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Creates or updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the create or update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the RouteFilterInner object if successful.
*/
public RouteFilterInner createOrUpdate(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).toBlocking().last().body();
}
/**
* Creates or updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the create or update route filter operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<RouteFilterInner> createOrUpdateAsync(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters, final ServiceCallback<RouteFilterInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters), serviceCallback);
}
/**
* Creates or updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the create or update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<RouteFilterInner> createOrUpdateAsync(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).map(new Func1<ServiceResponse<RouteFilterInner>, RouteFilterInner>() {
@Override
public RouteFilterInner call(ServiceResponse<RouteFilterInner> response) {
return response.body();
}
});
}
/**
* Creates or updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the create or update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<RouteFilterInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (routeFilterName == null) {
throw new IllegalArgumentException("Parameter routeFilterName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (routeFilterParameters == null) {
throw new IllegalArgumentException("Parameter routeFilterParameters is required and cannot be null.");
}
Validator.validate(routeFilterParameters);
final String apiVersion = "2017-08-01";
Observable<Response<ResponseBody>> observable = service.createOrUpdate(resourceGroupName, routeFilterName, this.client.subscriptionId(), routeFilterParameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<RouteFilterInner>() { }.getType());
}
/**
* Creates or updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the create or update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the RouteFilterInner object if successful.
*/
public RouteFilterInner beginCreateOrUpdate(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).toBlocking().single().body();
}
/**
* Creates or updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the create or update route filter operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<RouteFilterInner> beginCreateOrUpdateAsync(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters, final ServiceCallback<RouteFilterInner> serviceCallback) {
return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters), serviceCallback);
}
/**
* Creates or updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the create or update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the RouteFilterInner object
*/
public Observable<RouteFilterInner> beginCreateOrUpdateAsync(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).map(new Func1<ServiceResponse<RouteFilterInner>, RouteFilterInner>() {
@Override
public RouteFilterInner call(ServiceResponse<RouteFilterInner> response) {
return response.body();
}
});
}
/**
* Creates or updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the create or update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the RouteFilterInner object
*/
public Observable<ServiceResponse<RouteFilterInner>> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (routeFilterName == null) {
throw new IllegalArgumentException("Parameter routeFilterName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (routeFilterParameters == null) {
throw new IllegalArgumentException("Parameter routeFilterParameters is required and cannot be null.");
}
Validator.validate(routeFilterParameters);
final String apiVersion = "2017-08-01";
return service.beginCreateOrUpdate(resourceGroupName, routeFilterName, this.client.subscriptionId(), routeFilterParameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<RouteFilterInner>>>() {
@Override
public Observable<ServiceResponse<RouteFilterInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<RouteFilterInner> clientResponse = beginCreateOrUpdateDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<RouteFilterInner> beginCreateOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<RouteFilterInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<RouteFilterInner>() { }.getType())
.register(201, new TypeToken<RouteFilterInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the RouteFilterInner object if successful.
*/
public RouteFilterInner update(String resourceGroupName, String routeFilterName, PatchRouteFilterInner routeFilterParameters) {
return updateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).toBlocking().last().body();
}
/**
* Updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the update route filter operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<RouteFilterInner> updateAsync(String resourceGroupName, String routeFilterName, PatchRouteFilterInner routeFilterParameters, final ServiceCallback<RouteFilterInner> serviceCallback) {
return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters), serviceCallback);
}
/**
* Updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<RouteFilterInner> updateAsync(String resourceGroupName, String routeFilterName, PatchRouteFilterInner routeFilterParameters) {
return updateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).map(new Func1<ServiceResponse<RouteFilterInner>, RouteFilterInner>() {
@Override
public RouteFilterInner call(ServiceResponse<RouteFilterInner> response) {
return response.body();
}
});
}
/**
* Updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<RouteFilterInner>> updateWithServiceResponseAsync(String resourceGroupName, String routeFilterName, PatchRouteFilterInner routeFilterParameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (routeFilterName == null) {
throw new IllegalArgumentException("Parameter routeFilterName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (routeFilterParameters == null) {
throw new IllegalArgumentException("Parameter routeFilterParameters is required and cannot be null.");
}
Validator.validate(routeFilterParameters);
final String apiVersion = "2017-08-01";
Observable<Response<ResponseBody>> observable = service.update(resourceGroupName, routeFilterName, this.client.subscriptionId(), routeFilterParameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<RouteFilterInner>() { }.getType());
}
/**
* Updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the RouteFilterInner object if successful.
*/
public RouteFilterInner beginUpdate(String resourceGroupName, String routeFilterName, PatchRouteFilterInner routeFilterParameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).toBlocking().single().body();
}
/**
* Updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the update route filter operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<RouteFilterInner> beginUpdateAsync(String resourceGroupName, String routeFilterName, PatchRouteFilterInner routeFilterParameters, final ServiceCallback<RouteFilterInner> serviceCallback) {
return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters), serviceCallback);
}
/**
* Updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the RouteFilterInner object
*/
public Observable<RouteFilterInner> beginUpdateAsync(String resourceGroupName, String routeFilterName, PatchRouteFilterInner routeFilterParameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).map(new Func1<ServiceResponse<RouteFilterInner>, RouteFilterInner>() {
@Override
public RouteFilterInner call(ServiceResponse<RouteFilterInner> response) {
return response.body();
}
});
}
/**
* Updates a route filter in a specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param routeFilterName The name of the route filter.
* @param routeFilterParameters Parameters supplied to the update route filter operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the RouteFilterInner object
*/
public Observable<ServiceResponse<RouteFilterInner>> beginUpdateWithServiceResponseAsync(String resourceGroupName, String routeFilterName, PatchRouteFilterInner routeFilterParameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (routeFilterName == null) {
throw new IllegalArgumentException("Parameter routeFilterName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (routeFilterParameters == null) {
throw new IllegalArgumentException("Parameter routeFilterParameters is required and cannot be null.");
}
Validator.validate(routeFilterParameters);
final String apiVersion = "2017-08-01";
return service.beginUpdate(resourceGroupName, routeFilterName, this.client.subscriptionId(), routeFilterParameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<RouteFilterInner>>>() {
@Override
public Observable<ServiceResponse<RouteFilterInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<RouteFilterInner> clientResponse = beginUpdateDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<RouteFilterInner> beginUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<RouteFilterInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<RouteFilterInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets all route filters in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<RouteFilterInner> object if successful.
*/
public PagedList<RouteFilterInner> listByResourceGroup(final String resourceGroupName) {
ServiceResponse<Page<RouteFilterInner>> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single();
return new PagedList<RouteFilterInner>(response.body()) {
@Override
public Page<RouteFilterInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all route filters in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<RouteFilterInner>> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback<RouteFilterInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupSinglePageAsync(resourceGroupName),
new Func1<String, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all route filters in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<RouteFilterInner> object
*/
public Observable<Page<RouteFilterInner>> listByResourceGroupAsync(final String resourceGroupName) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName)
.map(new Func1<ServiceResponse<Page<RouteFilterInner>>, Page<RouteFilterInner>>() {
@Override
public Page<RouteFilterInner> call(ServiceResponse<Page<RouteFilterInner>> response) {
return response.body();
}
});
}
/**
* Gets all route filters in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<RouteFilterInner> object
*/
public Observable<ServiceResponse<Page<RouteFilterInner>>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) {
return listByResourceGroupSinglePageAsync(resourceGroupName)
.concatMap(new Func1<ServiceResponse<Page<RouteFilterInner>>, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(ServiceResponse<Page<RouteFilterInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all route filters in a resource group.
*
ServiceResponse<PageImpl<RouteFilterInner>> * @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<RouteFilterInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<RouteFilterInner>>> listByResourceGroupSinglePageAsync(final String resourceGroupName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2017-08-01";
return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<RouteFilterInner>> result = listByResourceGroupDelegate(response);
return Observable.just(new ServiceResponse<Page<RouteFilterInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<RouteFilterInner>> listByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<RouteFilterInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<RouteFilterInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets all route filters in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<RouteFilterInner> object if successful.
*/
public PagedList<RouteFilterInner> list() {
ServiceResponse<Page<RouteFilterInner>> response = listSinglePageAsync().toBlocking().single();
return new PagedList<RouteFilterInner>(response.body()) {
@Override
public Page<RouteFilterInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all route filters in a subscription.
*
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<RouteFilterInner>> listAsync(final ListOperationCallback<RouteFilterInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listSinglePageAsync(),
new Func1<String, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all route filters in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<RouteFilterInner> object
*/
public Observable<Page<RouteFilterInner>> listAsync() {
return listWithServiceResponseAsync()
.map(new Func1<ServiceResponse<Page<RouteFilterInner>>, Page<RouteFilterInner>>() {
@Override
public Page<RouteFilterInner> call(ServiceResponse<Page<RouteFilterInner>> response) {
return response.body();
}
});
}
/**
* Gets all route filters in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<RouteFilterInner> object
*/
public Observable<ServiceResponse<Page<RouteFilterInner>>> listWithServiceResponseAsync() {
return listSinglePageAsync()
.concatMap(new Func1<ServiceResponse<Page<RouteFilterInner>>, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(ServiceResponse<Page<RouteFilterInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all route filters in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<RouteFilterInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<RouteFilterInner>>> listSinglePageAsync() {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2017-08-01";
return service.list(this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<RouteFilterInner>> result = listDelegate(response);
return Observable.just(new ServiceResponse<Page<RouteFilterInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<RouteFilterInner>> listDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<RouteFilterInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<RouteFilterInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets all route filters in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<RouteFilterInner> object if successful.
*/
public PagedList<RouteFilterInner> listByResourceGroupNext(final String nextPageLink) {
ServiceResponse<Page<RouteFilterInner>> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<RouteFilterInner>(response.body()) {
@Override
public Page<RouteFilterInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all route filters in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<RouteFilterInner>> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture<List<RouteFilterInner>> serviceFuture, final ListOperationCallback<RouteFilterInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all route filters in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<RouteFilterInner> object
*/
public Observable<Page<RouteFilterInner>> listByResourceGroupNextAsync(final String nextPageLink) {
return listByResourceGroupNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<RouteFilterInner>>, Page<RouteFilterInner>>() {
@Override
public Page<RouteFilterInner> call(ServiceResponse<Page<RouteFilterInner>> response) {
return response.body();
}
});
}
/**
* Gets all route filters in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<RouteFilterInner> object
*/
public Observable<ServiceResponse<Page<RouteFilterInner>>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<RouteFilterInner>>, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(ServiceResponse<Page<RouteFilterInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all route filters in a resource group.
*
ServiceResponse<PageImpl<RouteFilterInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<RouteFilterInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<RouteFilterInner>>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<RouteFilterInner>> result = listByResourceGroupNextDelegate(response);
return Observable.just(new ServiceResponse<Page<RouteFilterInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<RouteFilterInner>> listByResourceGroupNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<RouteFilterInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<RouteFilterInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets all route filters in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<RouteFilterInner> object if successful.
*/
public PagedList<RouteFilterInner> listNext(final String nextPageLink) {
ServiceResponse<Page<RouteFilterInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<RouteFilterInner>(response.body()) {
@Override
public Page<RouteFilterInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all route filters in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<RouteFilterInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<RouteFilterInner>> serviceFuture, final ListOperationCallback<RouteFilterInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all route filters in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<RouteFilterInner> object
*/
public Observable<Page<RouteFilterInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<RouteFilterInner>>, Page<RouteFilterInner>>() {
@Override
public Page<RouteFilterInner> call(ServiceResponse<Page<RouteFilterInner>> response) {
return response.body();
}
});
}
/**
* Gets all route filters in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<RouteFilterInner> object
*/
public Observable<ServiceResponse<Page<RouteFilterInner>>> listNextWithServiceResponseAsync(final String nextPageLink) {
return listNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<RouteFilterInner>>, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(ServiceResponse<Page<RouteFilterInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all route filters in a subscription.
*
ServiceResponse<PageImpl<RouteFilterInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<RouteFilterInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<RouteFilterInner>>> listNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<RouteFilterInner>>>>() {
@Override
public Observable<ServiceResponse<Page<RouteFilterInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<RouteFilterInner>> result = listNextDelegate(response);
return Observable.just(new ServiceResponse<Page<RouteFilterInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<RouteFilterInner>> listNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<RouteFilterInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<RouteFilterInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/models/BlobQueryResponse.java | 710 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.storage.blob.models;
import com.azure.core.http.rest.ResponseBase;
/**
* This class contains the response information return from the server when querying a blob.
*/
public final class BlobQueryResponse extends ResponseBase<BlobQueryHeaders, Void> {
/**
* Constructs a {@link BlobQueryResponse}.
*
* @param response Response returned from the service.
*/
public BlobQueryResponse(BlobQueryAsyncResponse response) {
super(response.getRequest(), response.getStatusCode(), response.getHeaders(), null,
response.getDeserializedHeaders());
}
}
| mit |
opendatakraken/openbiwiki | openbiwiki-core/src/main/java/org/jamwiki/utils/Utilities.java | 17621 | /**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
/**
* This class provides a variety of basic utility methods that are not
* dependent on any other classes within the org.jamwiki package structure.
*/
public abstract class Utilities {
private static final WikiLogger logger = WikiLogger.getLogger(Utilities.class.getName());
private static final String ipv4Pattern = "(?:(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d\\d?|2[0-4]\\d|25[0-5])";
private static final String ipv6Pattern = "(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]){1,4}";
private static final Pattern VALID_IPV4_PATTERN = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE);
private static final Pattern VALID_IPV6_PATTERN = Pattern.compile(ipv6Pattern, Pattern.CASE_INSENSITIVE);
/**
* Convert a string value from one encoding to another.
*
* @param text The string that is to be converted.
* @param fromEncoding The encoding that the string is currently encoded in.
* @param toEncoding The encoding that the string is to be encoded to.
* @return The encoded string.
*/
public static String convertEncoding(String text, String fromEncoding, String toEncoding) {
if (StringUtils.isBlank(text)) {
return text;
}
if (StringUtils.isBlank(fromEncoding)) {
logger.warn("No character encoding specified to convert from, using UTF-8");
fromEncoding = "UTF-8";
}
if (StringUtils.isBlank(toEncoding)) {
logger.warn("No character encoding specified to convert to, using UTF-8");
toEncoding = "UTF-8";
}
try {
text = new String(text.getBytes(fromEncoding), toEncoding);
} catch (UnsupportedEncodingException e) {
// bad encoding
logger.warn("Unable to convert value " + text + " from " + fromEncoding + " to " + toEncoding, e);
}
return text;
}
/**
* Decode a value that has been retrieved from a servlet request. This
* method will replace any underscores with spaces.
*
* @param url The encoded value that is to be decoded.
* @param decodeUnderlines Set to <code>true</code> if underlines should
* be automatically converted to spaces.
* @return A decoded value.
*/
public static String decodeTopicName(String url, boolean decodeUnderlines) {
if (StringUtils.isBlank(url)) {
return url;
}
return (decodeUnderlines) ? StringUtils.replace(url, "_", " ") : url;
}
/**
* Decode a value that has been retrieved directly from a URL or file
* name. This method will URL decode the value and then replace any
* underscores with spaces. Note that this method SHOULD NOT be called
* for values retrieved using request.getParameter(), but only values
* taken directly from a URL.
*
* @param url The encoded value that is to be decoded.
* @param decodeUnderlines Set to <code>true</code> if underlines should
* be automatically converted to spaces.
* @return A decoded value.
*/
public static String decodeAndEscapeTopicName(String url, boolean decodeUnderlines) {
if (StringUtils.isBlank(url)) {
return url;
}
String result = url;
try {
result = URLDecoder.decode(result, "UTF-8");
} catch (UnsupportedEncodingException e) {
// this should never happen
throw new IllegalStateException("Unsupporting encoding UTF-8");
}
return Utilities.decodeTopicName(result, decodeUnderlines);
}
/**
* Convert a delimited string to a list.
*
* @param delimitedString A string consisting of the delimited list items.
* @param delimiter The string used as the delimiter.
* @return A list consisting of the delimited string items, or <code>null</code> if the
* string is <code>null</code> or empty.
*/
public static List<String> delimitedStringToList(String delimitedString, String delimiter) {
if (delimiter == null) {
throw new IllegalArgumentException("Attempt to call Utilities.delimitedStringToList with no delimiter specified");
}
if (StringUtils.isBlank(delimitedString)) {
return null;
}
return Arrays.asList(StringUtils.splitByWholeSeparator(delimitedString, delimiter));
}
/**
* Encode a value for use a topic name. This method will replace any
* spaces with underscores.
*
* @param url The decoded value that is to be encoded.
* @return An encoded value.
*/
public static String encodeTopicName(String url) {
if (StringUtils.isBlank(url)) {
return url;
}
return StringUtils.replace(url, " ", "_");
}
/**
* Encode a topic name for use in a URL. This method will replace spaces
* with underscores and URL encode the value, but it will not URL encode
* colons.
*
* @param url The topic name to be encoded for use in a URL.
* @return The encoded topic name value.
*/
public static String encodeAndEscapeTopicName(String url) {
if (StringUtils.isBlank(url)) {
return url;
}
String result = Utilities.encodeTopicName(url);
try {
result = URLEncoder.encode(result, "UTF-8");
} catch (UnsupportedEncodingException e) {
// this should never happen
throw new IllegalStateException("Unsupporting encoding UTF-8");
}
// un-encode colons
result = StringUtils.replace(result, "%3A", ":");
// un-encode forward slashes
result = StringUtils.replace(result, "%2F", "/");
return result;
}
/**
* Search through content, starting at a specific position, and search for the
* first position of a matching end tag for a specified start tag. For instance,
* if called with a start tag of "<b>" and an end tag of "</b>", this method
* will operate as follows:
*
* "01<b>567</b>23" returns 8.
* "01<b>56<b>01</b>67</b>23" returns 18.
*
* @param content The string to be searched.
* @param start The position within the string to start searching from (inclusive).
* Only characters after this position in the string will be examined.
* @param startToken The opening tag to match.
* @param endToken The closing tag to match.
* @return -1 if no matching end tag is found, or the index within the string of the first
* character of the end tag.
*/
public static int findMatchingEndTag(CharSequence content, int start, String startToken, String endToken) {
// do some initial searching to make sure the tokens are available
if (content == null || start < 0 || start >= content.length()) {
return -1;
}
String contentString = content.toString();
int lastEndToken = contentString.lastIndexOf(endToken);
if (lastEndToken == -1 || lastEndToken < start) {
return -1;
}
int firstStartToken = contentString.indexOf(startToken, start);
if (firstStartToken == -1) {
return -1;
}
int pos = firstStartToken;
int count = 0;
int nextStart = firstStartToken;
int nextEnd = lastEndToken;
// search for matches within the area that tokens have already been found
while (pos >= firstStartToken && pos < (lastEndToken + endToken.length())) {
if (nextStart != -1 && nextStart < nextEnd) {
// cursor is currently at the match of a start token
count++;
pos += startToken.length();
} else {
// cursor is currently at the match of an end token
count--;
if (count == 0) {
// this tag closes a match, return the position of the
// start of the tag
return pos;
}
pos += endToken.length();
}
// jump to the next start or end token
nextEnd = contentString.indexOf(endToken, pos);
if (nextEnd == -1) {
// no more matching end patterns, no match
break;
}
nextStart = contentString.indexOf(startToken, pos);
pos = (nextStart == -1) ? nextEnd : Math.min(nextStart, nextEnd);
}
return -1;
}
/**
* Search through content, starting at a specific position, and search backwards for the
* first position of a matching start tag for a specified end tag. For instance,
* if called with an end tag of "</b>" and a start tag of "<b>", this method
* will operate as follows:
*
* "01<b>567</b>23" returns 2.
* "01234567</b>23" returns -1.
*
* @param content The string to be searched.
* @param start The position within the string to start searching from (inclusive).
* Only characters before this position in the string will be examined.
* @param startToken The opening tag to match.
* @param endToken The closing tag to match.
* @return -1 if no matching start tag is found, or the index within the string of the first
* character of the start tag.
*/
public static int findMatchingStartTag(CharSequence content, int start, String startToken, String endToken) {
// do some initial searching to make sure the tokens are available
if (content == null || start < 0 || start >= content.length()) {
return -1;
}
int firstStartToken = StringUtils.indexOf(content, startToken);
if (firstStartToken == -1 || firstStartToken > start) {
return -1;
}
int lastEndToken = StringUtils.lastIndexOf(content, endToken, start);
if (lastEndToken == -1) {
return -1;
}
int pos = start;
if (pos >= (lastEndToken + endToken.length())) {
pos = lastEndToken + endToken.length() - 1;
}
int count = 0;
String contentString = content.toString();
String substring;
// search for matches within the area that tokens have already been found
while (pos >= firstStartToken && pos < (lastEndToken + endToken.length())) {
substring = contentString.substring(0, pos + 1);
// search for matches from end-to-beginning
if (substring.endsWith(endToken)) {
count++;
pos -= endToken.length();
} else if (substring.endsWith(startToken)) {
count--;
if (count == 0) {
// this tag opens a match, return the position of the
// start of the tag
return (pos - startToken.length()) + 1;
}
pos -= startToken.length();
} else {
pos--;
}
}
return -1;
}
/**
* Given a message key and locale return a locale-specific message.
*
* @param key The message key that corresponds to the formatted message
* being retrieved.
* @param locale The locale for the message that is to be retrieved.
* @return A formatted message string that is specific to the locale.
*/
public static String formatMessage(String key, Locale locale) {
ResourceBundle messages = ResourceBundle.getBundle("ApplicationResources", locale);
return messages.getString(key);
}
/**
* Given a message key, locale, and formatting parameters, return a
* locale-specific message.
*
* @param key The message key that corresponds to the formatted message
* being retrieved.
* @param locale The locale for the message that is to be retrieved.
* @param params An array of formatting parameters to use in the message
* being returned.
* @return A formatted message string that is specific to the locale.
*/
public static String formatMessage(String key, Locale locale, Object[] params) {
MessageFormat formatter = new MessageFormat("");
formatter.setLocale(locale);
String message = Utilities.formatMessage(key, locale);
formatter.applyPattern(message);
return formatter.format(params);
}
/**
* Utility method for retrieving a key from a map, case-insensitive. This method
* first tries to return an exact match, and if that fails it returns the first
* case-insensitive match.
*
* @param map The map being examined.
* @param key The key for the value being retrieved.
* @return A matching value for the key, or <code>null</code> if no match is found.
*/
public static <V> V getMapValueCaseInsensitive(Map<String, V> map, String key) {
if (map == null) {
return null;
}
if (map.containsKey(key)) {
return map.get(key);
}
for (Map.Entry<String, V> entry : map.entrySet()) {
if (StringUtils.equalsIgnoreCase(entry.getKey(), key)) {
return entry.getValue();
}
}
return null;
}
/**
* Utility method to help work around XSS attacks when executing request.getQueryString().
* If the query string contains ", <, or > then assume it is malicious and escape.
*
* @param request The current servlet request.
* @return The request query string, or an escaped version if it appears to be an XSS
* attack.
*/
public static String getQueryString(HttpServletRequest request) {
if (request == null) {
return null;
}
String queryString = request.getQueryString();
if (StringUtils.isBlank(queryString)) {
return queryString;
}
if (StringUtils.containsAny(queryString, "\"><")) {
queryString = queryString.replaceAll("\"", "%22");
queryString = queryString.replaceAll(">", "%3E");
queryString = queryString.replaceAll("<", "%3C");
}
return queryString;
}
/**
* Given a request, determine the server URL.
*
* @return A Server URL of the form http://www.example.com/
*/
public static String getServerUrl(HttpServletRequest request) {
return request.getScheme() + "://" + request.getServerName() + ((request.getServerPort() != 80) ? ":" + request.getServerPort() : "");
}
/**
* Initialize a hash map from a list of strings for use in lookups. The performance
* of a lookup against a hash map is superior to that of a list, so this approach is
* useful for critical-path lookups.
*/
public static Map<String, String> initializeLookupMap(String... args) {
Map<String, String> lookupMap = new HashMap<String, String>();
for (int i = 0; i < args.length; i++) {
lookupMap.put(args[i], args[i]);
}
return lookupMap;
}
/**
* Utility method for determining common elements in two Map objects.
*/
public static <K, V> Map<K, V> intersect(Map<K, V> map1, Map<K, V> map2) {
if (map1 == null || map2 == null) {
throw new IllegalArgumentException("Utilities.intersection() requires non-null arguments");
}
Map<K, V> result = new HashMap<K, V>();
for (Map.Entry<K, V> entry : map1.entrySet()) {
if (ObjectUtils.equals(entry.getValue(), map2.get(entry.getKey()))) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
/**
* Given a string, determine if it is a valid HTML entity (such as ™ or
*  ).
*
* @param text The text that is being examined.
* @return <code>true</code> if the text is a valid HTML entity.
*/
public static boolean isHtmlEntity(String text) {
if (text == null) {
return false;
}
// see if it was successfully converted, in which case it is an entity
try {
return (!text.equals(StringEscapeUtils.unescapeHtml4(text)));
} catch (IllegalArgumentException e) {
// "�" seems to be throwing errors
return false;
}
}
/**
* Determine if the given string is a valid IPv4 or IPv6 address. This method
* uses pattern matching to see if the given string could be a valid IP address.
*
* @param ipAddress A string that is to be examined to verify whether or not
* it could be a valid IP address.
* @return <code>true</code> if the string is a value that is a valid IP address,
* <code>false</code> otherwise.
*/
public static boolean isIpAddress(String ipAddress) {
if (StringUtils.isBlank(ipAddress)) {
return false;
}
Matcher m1 = Utilities.VALID_IPV4_PATTERN.matcher(ipAddress);
if (m1.matches()) {
return true;
}
Matcher m2 = Utilities.VALID_IPV6_PATTERN.matcher(ipAddress);
return m2.matches();
}
/**
* Convert a list to a delimited string.
*
* @param list The list to convert to a string.
* @param delimiter The string to use as a delimiter.
* @return A string consisting of the delimited list items, or <code>null</code> if the
* list is <code>null</code> or empty.
*/
public static String listToDelimitedString(List<String> list, String delimiter) {
if (delimiter == null) {
throw new IllegalArgumentException("Attempt to call Utilities.delimitedStringToList with no delimiter specified");
}
if (list == null || list.isEmpty()) {
return null;
}
String result = "";
for (String item : list) {
if (result.length() > 0) {
result += delimiter;
}
result += item;
}
return result;
}
/**
* Strip all HTML tags from a string. For example, "A <b>bold</b> word" will be
* returned as "A bold word". This method treats an tags that are between brackets
* as HTML, whether it is valid HTML or not.
*
* @param value The value that will have HTML stripped from it.
* @return The value submitted to this method with all HTML tags removed from it.
*/
public static String stripMarkup(String value) {
return StringUtils.trim(value.replaceAll("<[^>]+>", ""));
}
}
| mit |
CyanogenMod/android_external_mockito | test/org/mockito/internal/InvalidStateDetectionTest.java | 9109 | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.junit.After;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.StateMaster;
import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;
import org.mockito.exceptions.misusing.UnfinishedStubbingException;
import org.mockito.exceptions.misusing.UnfinishedVerificationException;
import org.mockitousage.IMethods;
import org.mockitoutil.TestBase;
/**
* invalid state happens if:
*
* -unfinished stubbing
* -unfinished stubVoid
* -unfinished doReturn()
* -stubbing without actual method call
* -verify without actual method call
*
* we should aim to detect invalid state in following scenarios:
*
* -on method call on mock
* -on verify
* -on verifyZeroInteractions
* -on verifyNoMoreInteractions
* -on verify in order
* -on stub
* -on stubVoid
*/
@SuppressWarnings({"unchecked", "deprecation"})
public class InvalidStateDetectionTest extends TestBase {
@Mock private IMethods mock;
@After
public void resetState() {
super.resetState();
}
@Test
public void shouldDetectUnfinishedStubbing() {
when(mock.simpleMethod());
detectsAndCleansUp(new OnMethodCallOnMock(), UnfinishedStubbingException.class);
when(mock.simpleMethod());
detectsAndCleansUp(new OnStub(), UnfinishedStubbingException.class);
when(mock.simpleMethod());
detectsAndCleansUp(new OnStubVoid(), UnfinishedStubbingException.class);
when(mock.simpleMethod());
detectsAndCleansUp(new OnVerify(), UnfinishedStubbingException.class);
when(mock.simpleMethod());
detectsAndCleansUp(new OnVerifyInOrder(), UnfinishedStubbingException.class);
when(mock.simpleMethod());
detectsAndCleansUp(new OnVerifyZeroInteractions(), UnfinishedStubbingException.class);
when(mock.simpleMethod());
detectsAndCleansUp(new OnVerifyNoMoreInteractions(), UnfinishedStubbingException.class);
when(mock.simpleMethod());
detectsAndCleansUp(new OnDoAnswer(), UnfinishedStubbingException.class);
}
@Test
public void shouldDetectUnfinishedStubbingVoid() {
stubVoid(mock);
detectsAndCleansUp(new OnMethodCallOnMock(), UnfinishedStubbingException.class);
stubVoid(mock);
detectsAndCleansUp(new OnStub(), UnfinishedStubbingException.class);
stubVoid(mock);
detectsAndCleansUp(new OnStubVoid(), UnfinishedStubbingException.class);
stubVoid(mock);
detectsAndCleansUp(new OnVerify(), UnfinishedStubbingException.class);
stubVoid(mock);
detectsAndCleansUp(new OnVerifyInOrder(), UnfinishedStubbingException.class);
stubVoid(mock);
detectsAndCleansUp(new OnVerifyZeroInteractions(), UnfinishedStubbingException.class);
stubVoid(mock);
detectsAndCleansUp(new OnVerifyNoMoreInteractions(), UnfinishedStubbingException.class);
stubVoid(mock);
detectsAndCleansUp(new OnDoAnswer(), UnfinishedStubbingException.class);
}
@Test
public void shouldDetectUnfinishedDoAnswerStubbing() {
doAnswer(null);
detectsAndCleansUp(new OnMethodCallOnMock(), UnfinishedStubbingException.class);
doAnswer(null);
detectsAndCleansUp(new OnStub(), UnfinishedStubbingException.class);
doAnswer(null);
detectsAndCleansUp(new OnStubVoid(), UnfinishedStubbingException.class);
doAnswer(null);
detectsAndCleansUp(new OnVerify(), UnfinishedStubbingException.class);
doAnswer(null);
detectsAndCleansUp(new OnVerifyInOrder(), UnfinishedStubbingException.class);
doAnswer(null);
detectsAndCleansUp(new OnVerifyZeroInteractions(), UnfinishedStubbingException.class);
doAnswer(null);
detectsAndCleansUp(new OnVerifyNoMoreInteractions(), UnfinishedStubbingException.class);
doAnswer(null);
detectsAndCleansUp(new OnDoAnswer(), UnfinishedStubbingException.class);
}
@Test
public void shouldDetectUnfinishedVerification() {
verify(mock);
detectsAndCleansUp(new OnStub(), UnfinishedVerificationException.class);
verify(mock);
detectsAndCleansUp(new OnStubVoid(), UnfinishedVerificationException.class);
verify(mock);
detectsAndCleansUp(new OnVerify(), UnfinishedVerificationException.class);
verify(mock);
detectsAndCleansUp(new OnVerifyInOrder(), UnfinishedVerificationException.class);
verify(mock);
detectsAndCleansUp(new OnVerifyZeroInteractions(), UnfinishedVerificationException.class);
verify(mock);
detectsAndCleansUp(new OnVerifyNoMoreInteractions(), UnfinishedVerificationException.class);
verify(mock);
detectsAndCleansUp(new OnDoAnswer(), UnfinishedVerificationException.class);
}
@Test
public void shouldDetectMisplacedArgumentMatcher() {
anyObject();
detectsAndCleansUp(new OnStubVoid(), InvalidUseOfMatchersException.class);
anyObject();
detectsAndCleansUp(new OnVerify(), InvalidUseOfMatchersException.class);
anyObject();
detectsAndCleansUp(new OnVerifyInOrder(), InvalidUseOfMatchersException.class);
anyObject();
detectsAndCleansUp(new OnVerifyZeroInteractions(), InvalidUseOfMatchersException.class);
anyObject();
detectsAndCleansUp(new OnVerifyNoMoreInteractions(), InvalidUseOfMatchersException.class);
anyObject();
detectsAndCleansUp(new OnDoAnswer(), InvalidUseOfMatchersException.class);
}
@Test
public void shouldCorrectStateAfterDetectingUnfinishedStubbing() {
stubVoid(mock).toThrow(new RuntimeException());
try {
stubVoid(mock).toThrow(new RuntimeException()).on().oneArg(true);
fail();
} catch (UnfinishedStubbingException e) {}
stubVoid(mock).toThrow(new RuntimeException()).on().oneArg(true);
try {
mock.oneArg(true);
fail();
} catch (RuntimeException e) {}
}
@Test
public void shouldCorrectStateAfterDetectingUnfinishedVerification() {
mock.simpleMethod();
verify(mock);
try {
verify(mock).simpleMethod();
fail();
} catch (UnfinishedVerificationException e) {}
verify(mock).simpleMethod();
}
private static interface DetectsInvalidState {
void detect(IMethods mock);
}
private static class OnVerify implements DetectsInvalidState {
public void detect(IMethods mock) {
verify(mock);
}
}
private static class OnVerifyInOrder implements DetectsInvalidState {
public void detect(IMethods mock) {
inOrder(mock).verify(mock);
}
}
private static class OnVerifyZeroInteractions implements DetectsInvalidState {
public void detect(IMethods mock) {
verifyZeroInteractions(mock);
}
}
private static class OnVerifyNoMoreInteractions implements DetectsInvalidState {
public void detect(IMethods mock) {
verifyNoMoreInteractions(mock);
}
}
private static class OnDoAnswer implements DetectsInvalidState {
public void detect(IMethods mock) {
doAnswer(null);
}
}
private static class OnStub implements DetectsInvalidState {
public void detect(IMethods mock) {
when(mock);
}
}
private static class OnStubVoid implements DetectsInvalidState {
public void detect(IMethods mock) {
stubVoid(mock);
}
}
private static class OnMethodCallOnMock implements DetectsInvalidState {
public void detect(IMethods mock) {
mock.simpleMethod();
}
}
private static class OnMockCreation implements DetectsInvalidState {
public void detect(IMethods mock) {
mock(IMethods.class);
}
}
private static class OnSpyCreation implements DetectsInvalidState {
public void detect(IMethods mock) {
spy(new Object());
}
}
private void detectsAndCleansUp(DetectsInvalidState detector, Class expected) {
try {
detector.detect(mock);
fail("Should throw an exception");
} catch (Exception e) {
assertEquals(expected, e.getClass());
}
//Make sure state is cleaned up
new StateMaster().validate();
}
} | mit |
icoding/Mapper | src/main/java/tk/mybatis/mapper/common/rowbounds/SelectRowBoundsMapper.java | 1772 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 abel533@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package tk.mybatis.mapper.common.rowbounds;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.session.RowBounds;
import tk.mybatis.mapper.provider.MapperProvider;
import java.util.List;
/**
* 通用Mapper接口,查询
*
* @param <T> 不能为空
* @author liuzh
*/
public interface SelectRowBoundsMapper<T> {
/**
* 根据实体属性和RowBounds进行分页查询
*
* @param record
* @param rowBounds
* @return
*/
@SelectProvider(type = MapperProvider.class, method = "dynamicSQL")
List<T> selectByRowBounds(T record, RowBounds rowBounds);
} | mit |
AllTheMods/CraftTweaker | CraftTweaker2-MC1120-Main/src/main/java/crafttweaker/mc1120/formatting/FormattedMarkupString.java | 1094 | package crafttweaker.mc1120.formatting;
import crafttweaker.api.formatting.IFormattedText;
import net.minecraft.util.text.TextFormatting;
/**
* @author Stan
*/
public class FormattedMarkupString implements IMCFormattedString {
private final TextFormatting markup;
private final IMCFormattedString contents;
public FormattedMarkupString(TextFormatting markup, IMCFormattedString contents) {
this.markup = markup;
this.contents = contents;
}
@Override
public String getTooltipString() {
return markup + contents.getTooltipString(markup.toString());
}
@Override
public String getTooltipString(String context) {
return markup + contents.getTooltipString(context + markup);
}
@Override
public IFormattedText add(IFormattedText other) {
return cat(other);
}
@Override
public IFormattedText cat(IFormattedText other) {
return new FormattedStringJoin(this, (IMCFormattedString) other);
}
@Override
public String getText() {
return getTooltipString();
}
}
| mit |
SCPTeam/Safe-Component-Provider | Sat4jCore/src/org/sat4j/tools/encoding/Ladder.java | 7433 | /*******************************************************************************
* SAT4J: a SATisfiability library for Java Copyright (C) 2004, 2012 Artois University and CNRS
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU Lesser General Public License Version 2.1 or later (the
* "LGPL"), in which case the provisions of the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of the LGPL, and not to allow others to use your version of
* this file under the terms of the EPL, indicate your decision by deleting
* the provisions above and replace them with the notice and other provisions
* required by the LGPL. If you do not delete the provisions above, a recipient
* may use your version of this file under the terms of the EPL or the LGPL.
*
* Based on the original MiniSat specification from:
*
* An extensible SAT solver. Niklas Een and Niklas Sorensson. Proceedings of the
* Sixth International Conference on Theory and Applications of Satisfiability
* Testing, LNCS 2919, pp 502-518, 2003.
*
* See www.minisat.se for the original solver in C++.
*
* Contributors:
* CRIL - initial API and implementation
*******************************************************************************/
package org.sat4j.tools.encoding;
import org.sat4j.core.ConstrGroup;
import org.sat4j.core.VecInt;
import org.sat4j.specs.ContradictionException;
import org.sat4j.specs.IConstr;
import org.sat4j.specs.ISolver;
import org.sat4j.specs.IVecInt;
/**
*
* Ladder encoding for the "at most one" and "exactly one" cases.
*
* The ladder encoding described in: I. P. Gent and P. Nightingale,
* "A new encoding for AllDifferent into SAT", in International Workshop on
* Modeling and Reformulating Constraint Satisfaction Problems, 2004
*
* @author sroussel
* @since 2.3.1
*/
public class Ladder extends EncodingStrategyAdapter {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
/**
* If n is the number of variables in the constraint,
* this encoding adds n variables and 4n clauses
* (3n+1 size 2 clauses and n-1 size 3 clauses)
*/
public IConstr addAtMostOne(ISolver solver, IVecInt literals)
throws ContradictionException {
ConstrGroup group = new ConstrGroup(false);
final int n = literals.size() + 1;
int xN = solver.nextFreeVarId(true);
int y[] = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
y[i] = solver.nextFreeVarId(true);
}
IVecInt clause = new VecInt();
// Constraint \bigwedge_{i=1}{n-2} (\neg y_{i+1} \vee y_i)
for (int i = 1; i <= n - 2; i++) {
clause.push(-y[i]);
clause.push(y[i - 1]);
group.add(solver.addClause(clause));
clause.clear();
}
// Constraint \bigwedge_{i=2}{n-1} (\neg y_{i-1} \vee y_i \vee x_i)
for (int i = 2; i <= n - 1; i++) {
clause.push(-y[i - 2]);
clause.push(y[i - 1]);
clause.push(literals.get(i - 1));
group.add(solver.addClause(clause));
clause.clear();
}
// Constraint \bigwedge_{i=2}{n-1} (\neg x_i \vee y_{i-1)})
for (int i = 2; i <= n - 1; i++) {
clause.push(-literals.get(i - 1));
clause.push(y[i - 2]);
group.add(solver.addClause(clause));
clause.clear();
}
// Constraint \bigwedge_{i=2}{n-1} (\neg x_i \vee \neg y_i)
for (int i = 2; i <= n - 1; i++) {
clause.push(-literals.get(i - 1));
clause.push(-y[i - 1]);
group.add(solver.addClause(clause));
clause.clear();
}
// Constraint y_1 \vee x_1
clause.push(y[0]);
clause.push(literals.get(0));
group.add(solver.addClause(clause));
clause.clear();
// Constraint \neg y_1 \vee \neg x_1
clause.push(-y[0]);
clause.push(-literals.get(0));
group.add(solver.addClause(clause));
clause.clear();
// Constraint \neg y_{n-1} \vee x_n
clause.push(-y[n - 2]);
clause.push(xN);
group.add(solver.addClause(clause));
clause.clear();
// Constraint y_{n-1} \vee \neg x_n
clause.push(y[n - 2]);
clause.push(-xN);
group.add(solver.addClause(clause));
clause.clear();
return group;
}
@Override
/**
* If n is the number of variables in the constraint,
* this encoding adds n-1 variables and 4(n-1) clauses
* (3n-2 size 2 clauses and n-2 size 3 clauses)
*/
public IConstr addExactlyOne(ISolver solver, IVecInt literals)
throws ContradictionException {
ConstrGroup group = new ConstrGroup(false);
final int n = literals.size();
IVecInt clause = new VecInt();
if (n == 1) {
clause.push(literals.get(0));
group.add(solver.addClause(clause));
return group;
}
int y[] = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
y[i] = solver.nextFreeVarId(true);
}
// Constraint \bigwedge_{i=1}{n-2} (\neg y_{i+1} \vee y_i)
for (int i = 1; i <= n - 2; i++) {
clause.push(-y[i]);
clause.push(y[i - 1]);
group.add(solver.addClause(clause));
clause.clear();
}
// Constraint \bigwedge_{i=2}{n-1} (\neg y_{i-1} \vee y_i \vee x_i)
for (int i = 2; i <= n - 1; i++) {
clause.push(-y[i - 2]);
clause.push(y[i - 1]);
clause.push(literals.get(i - 1));
group.add(solver.addClause(clause));
clause.clear();
}
// Constraint \bigwedge_{i=2}{n-1} (\neg x_i \vee y_{i-1)})
for (int i = 2; i <= n - 1; i++) {
clause.push(-literals.get(i - 1));
clause.push(y[i - 2]);
group.add(solver.addClause(clause));
clause.clear();
}
// Constraint \bigwedge_{i=2}{n-1} (\neg x_i \vee \neg y_i)
for (int i = 2; i <= n - 1; i++) {
clause.push(-literals.get(i - 1));
clause.push(-y[i - 1]);
group.add(solver.addClause(clause));
clause.clear();
}
// Constraint y_1 \vee x_1
clause.push(y[0]);
clause.push(literals.get(0));
group.add(solver.addClause(clause));
clause.clear();
// Constraint \neg y_1 \vee \neg x_1
clause.push(-y[0]);
clause.push(-literals.get(0));
group.add(solver.addClause(clause));
clause.clear();
// Constraint \neg y_{n-1} \vee x_n
clause.push(-y[n - 2]);
clause.push(literals.get(n - 1));
group.add(solver.addClause(clause));
clause.clear();
// Constraint y_{n-1} \vee \neg x_n
clause.push(y[n - 2]);
clause.push(-literals.get(n - 1));
group.add(solver.addClause(clause));
clause.clear();
return group;
}
}
| mit |
hpsa/hp-application-automation-tools-plugin | src/main/java/com/hp/application/automation/tools/model/SvDataModelSelection.java | 4092 | // (c) Copyright 2016 Hewlett Packard Enterprise Development LP
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package com.hp.application.automation.tools.model;
import javax.annotation.Nonnull;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.util.FormValidation;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
public class SvDataModelSelection extends AbstractDescribableImpl<SvDataModelSelection> {
protected final SelectionType selectionType;
protected final String dataModel;
@DataBoundConstructor
public SvDataModelSelection(SelectionType selectionType, String dataModel) {
this.selectionType = selectionType;
this.dataModel = StringUtils.trim(dataModel);
}
public static void validateField(FormValidation result) {
if (!result.equals(FormValidation.ok())) {
throw new IllegalArgumentException(StringEscapeUtils.unescapeXml(result.getMessage()));
}
}
@SuppressWarnings("unused")
public SelectionType getSelectionType() {
return selectionType;
}
public String getDataModel() {
return (StringUtils.isNotBlank(dataModel)) ? dataModel : null;
}
@SuppressWarnings("unused")
public boolean isSelected(String type) {
return SelectionType.valueOf(type) == this.selectionType;
}
public boolean isNoneSelected() {
return selectionType == SelectionType.NONE;
}
public boolean isDefaultSelected() {
return selectionType == SelectionType.DEFAULT;
}
@Override
public String toString() {
switch (selectionType) {
case BY_NAME:
return dataModel;
case NONE:
return "<none>";
case DEFAULT:
default:
return "<default>";
}
}
public String getSelectedModelName() {
switch (selectionType) {
case BY_NAME:
DescriptorImpl descriptor = (DescriptorImpl) getDescriptor();
validateField(descriptor.doCheckDataModel(dataModel));
return dataModel;
default:
return null;
}
}
public enum SelectionType {
BY_NAME,
NONE,
/**
* Default means first model in alphabetical order by model name
*/
DEFAULT,
}
@Extension
public static class DescriptorImpl extends Descriptor<SvDataModelSelection> {
@Nonnull
public String getDisplayName() {
return "Data model Selection";
}
@SuppressWarnings("unused")
public FormValidation doCheckDataModel(@QueryParameter String dataModel) {
if (StringUtils.isBlank(dataModel)) {
return FormValidation.error("Data model cannot be empty if 'Specific' model is selected");
}
return FormValidation.ok();
}
}
}
| mit |
tomcz/zookeeper-example | src/main/java/example/SpikeMessageRepository.java | 167 | package example;
import java.util.Collection;
public interface SpikeMessageRepository {
void add(SpikeMessage message);
Collection<SpikeMessage> list();
}
| mit |
sauliusg/jabref | src/main/java/org/jabref/logic/externalfiles/ExternalFilesContentImporter.java | 1554 | package org.jabref.logic.externalfiles;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.OpenDatabase;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.PdfContentImporter;
import org.jabref.logic.importer.fileformat.PdfXmpImporter;
import org.jabref.logic.preferences.TimestampPreferences;
import org.jabref.model.util.FileUpdateMonitor;
public class ExternalFilesContentImporter {
private final ImportFormatPreferences importFormatPreferences;
private final TimestampPreferences timestampPreferences;
public ExternalFilesContentImporter(ImportFormatPreferences importFormatPreferences, TimestampPreferences timestampPreferences) {
this.importFormatPreferences = importFormatPreferences;
this.timestampPreferences = timestampPreferences;
}
public ParserResult importPDFContent(Path file) {
return new PdfContentImporter(importFormatPreferences).importDatabase(file, StandardCharsets.UTF_8);
}
public ParserResult importXMPContent(Path file) {
return new PdfXmpImporter(importFormatPreferences.getXmpPreferences()).importDatabase(file, StandardCharsets.UTF_8);
}
public ParserResult importFromBibFile(Path bibFile, FileUpdateMonitor fileUpdateMonitor) throws IOException {
return OpenDatabase.loadDatabase(bibFile, importFormatPreferences, timestampPreferences, fileUpdateMonitor);
}
}
| mit |
epiphany27/Gitskarios | app/src/main/java/com/alorma/github/sdk/services/orgs/GetOrgsClient.java | 1469 | package com.alorma.github.sdk.services.orgs;
import com.alorma.github.sdk.services.client.GithubListClient;
import com.alorma.gitskarios.core.client.UsernameProvider;
import core.User;
import java.util.List;
import retrofit.RestAdapter;
public class GetOrgsClient extends GithubListClient<List<User>> {
private String username;
private int page = -1;
public GetOrgsClient(String username) {
super();
this.username = username;
}
public GetOrgsClient(String org, int page) {
super();
this.username = org;
this.page = page;
}
@Override
protected ApiSubscriber getApiObservable(RestAdapter restAdapter) {
return new ApiSubscriber() {
@Override
protected void call(RestAdapter restAdapter) {
String apiUsername =
UsernameProvider.getInstance() != null ? UsernameProvider.getInstance().getUsername()
: "";
if (username != null && username.equalsIgnoreCase(apiUsername)) {
username = null;
}
OrgsService orgsService = restAdapter.create(OrgsService.class);
if (page == -1) {
if (username == null) {
orgsService.orgs(this);
} else {
orgsService.orgsByUser(username, this);
}
} else {
if (username == null) {
orgsService.orgs(page, this);
} else {
orgsService.orgsByUser(username, page, this);
}
}
}
};
}
}
| mit |
mollstam/UnrealPy | UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/db-4.7.25.0/examples_java/src/collections/ship/index/Sample.java | 9635 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002,2008 Oracle. All rights reserved.
*
* $Id: Sample.java 63573 2008-05-23 21:43:21Z trent.nelson $
*/
package collections.ship.index;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Map;
import com.sleepycat.collections.TransactionRunner;
import com.sleepycat.collections.TransactionWorker;
import com.sleepycat.db.DatabaseException;
/**
* Sample is the main entry point for the sample program and may be run as
* follows:
*
* <pre>
* java collections.ship.index.Sample
* [-h <home-directory> ]
* </pre>
*
* <p> The default for the home directory is ./tmp -- the tmp subdirectory of
* the current directory where the sample is run. The home directory must exist
* before running the sample. To recreate the sample database from scratch,
* delete all files in the home directory before running the sample. </p>
*
* @author Mark Hayes
*/
public class Sample {
private SampleDatabase db;
private SampleViews views;
/**
* Run the sample program.
*/
public static void main(String[] args) {
System.out.println("\nRunning sample: " + Sample.class);
// Parse the command line arguments.
//
String homeDir = "./tmp";
for (int i = 0; i < args.length; i += 1) {
if (args[i].equals("-h") && i < args.length - 1) {
i += 1;
homeDir = args[i];
} else {
System.err.println("Usage:\n java " + Sample.class.getName() +
"\n [-h <home-directory>]");
System.exit(2);
}
}
// Run the sample.
//
Sample sample = null;
try {
sample = new Sample(homeDir);
sample.run();
} catch (Exception e) {
// If an exception reaches this point, the last transaction did not
// complete. If the exception is RunRecoveryException, follow
// the Berkeley DB recovery procedures before running again.
e.printStackTrace();
} finally {
if (sample != null) {
try {
// Always attempt to close the database cleanly.
sample.close();
} catch (Exception e) {
System.err.println("Exception during database close:");
e.printStackTrace();
}
}
}
}
/**
* Open the database and views.
*/
private Sample(String homeDir)
throws DatabaseException, FileNotFoundException {
db = new SampleDatabase(homeDir);
views = new SampleViews(db);
}
/**
* Close the database cleanly.
*/
private void close()
throws DatabaseException {
db.close();
}
/**
* Run two transactions to populate and print the database. A
* TransactionRunner is used to ensure consistent handling of transactions,
* including deadlock retries. But the best transaction handling mechanism
* to use depends on the application.
*/
private void run()
throws Exception {
TransactionRunner runner = new TransactionRunner(db.getEnvironment());
runner.run(new PopulateDatabase());
runner.run(new PrintDatabase());
}
/**
* Populate the database in a single transaction.
*/
private class PopulateDatabase implements TransactionWorker {
public void doWork()
throws Exception {
addSuppliers();
addParts();
addShipments();
}
}
/**
* Print the database in a single transaction. All entities are printed
* and the indices are used to print the entities for certain keys.
*
* <p> Note the use of special iterator() methods. These are used here
* with indices to find the shipments for certain keys.</p>
*/
private class PrintDatabase implements TransactionWorker {
public void doWork()
throws Exception {
printEntries("Parts",
views.getPartEntrySet().iterator());
printEntries("Suppliers",
views.getSupplierEntrySet().iterator());
printValues("Suppliers for City Paris",
views.getSupplierByCityMap().duplicates(
"Paris").iterator());
printEntries("Shipments",
views.getShipmentEntrySet().iterator());
printValues("Shipments for Part P1",
views.getShipmentByPartMap().duplicates(
new PartKey("P1")).iterator());
printValues("Shipments for Supplier S1",
views.getShipmentBySupplierMap().duplicates(
new SupplierKey("S1")).iterator());
}
}
/**
* Populate the part entities in the database. If the part map is not
* empty, assume that this has already been done.
*/
private void addParts() {
Map parts = views.getPartMap();
if (parts.isEmpty()) {
System.out.println("Adding Parts");
parts.put(new PartKey("P1"),
new PartData("Nut", "Red",
new Weight(12.0, Weight.GRAMS),
"London"));
parts.put(new PartKey("P2"),
new PartData("Bolt", "Green",
new Weight(17.0, Weight.GRAMS),
"Paris"));
parts.put(new PartKey("P3"),
new PartData("Screw", "Blue",
new Weight(17.0, Weight.GRAMS),
"Rome"));
parts.put(new PartKey("P4"),
new PartData("Screw", "Red",
new Weight(14.0, Weight.GRAMS),
"London"));
parts.put(new PartKey("P5"),
new PartData("Cam", "Blue",
new Weight(12.0, Weight.GRAMS),
"Paris"));
parts.put(new PartKey("P6"),
new PartData("Cog", "Red",
new Weight(19.0, Weight.GRAMS),
"London"));
}
}
/**
* Populate the supplier entities in the database. If the supplier map is
* not empty, assume that this has already been done.
*/
private void addSuppliers() {
Map suppliers = views.getSupplierMap();
if (suppliers.isEmpty()) {
System.out.println("Adding Suppliers");
suppliers.put(new SupplierKey("S1"),
new SupplierData("Smith", 20, "London"));
suppliers.put(new SupplierKey("S2"),
new SupplierData("Jones", 10, "Paris"));
suppliers.put(new SupplierKey("S3"),
new SupplierData("Blake", 30, "Paris"));
suppliers.put(new SupplierKey("S4"),
new SupplierData("Clark", 20, "London"));
suppliers.put(new SupplierKey("S5"),
new SupplierData("Adams", 30, "Athens"));
}
}
/**
* Populate the shipment entities in the database. If the shipment map
* is not empty, assume that this has already been done.
*/
private void addShipments() {
Map shipments = views.getShipmentMap();
if (shipments.isEmpty()) {
System.out.println("Adding Shipments");
shipments.put(new ShipmentKey("P1", "S1"),
new ShipmentData(300));
shipments.put(new ShipmentKey("P2", "S1"),
new ShipmentData(200));
shipments.put(new ShipmentKey("P3", "S1"),
new ShipmentData(400));
shipments.put(new ShipmentKey("P4", "S1"),
new ShipmentData(200));
shipments.put(new ShipmentKey("P5", "S1"),
new ShipmentData(100));
shipments.put(new ShipmentKey("P6", "S1"),
new ShipmentData(100));
shipments.put(new ShipmentKey("P1", "S2"),
new ShipmentData(300));
shipments.put(new ShipmentKey("P2", "S2"),
new ShipmentData(400));
shipments.put(new ShipmentKey("P2", "S3"),
new ShipmentData(200));
shipments.put(new ShipmentKey("P2", "S4"),
new ShipmentData(200));
shipments.put(new ShipmentKey("P4", "S4"),
new ShipmentData(300));
shipments.put(new ShipmentKey("P5", "S4"),
new ShipmentData(400));
}
}
/**
* Print the key/value objects returned by an iterator of Map.Entry
* objects.
*/
private void printEntries(String label, Iterator iterator) {
System.out.println("\n--- " + label + " ---");
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
System.out.println(entry.getKey().toString());
System.out.println(entry.getValue().toString());
}
}
/**
* Print the objects returned by an iterator of value objects.
*/
private void printValues(String label, Iterator iterator) {
System.out.println("\n--- " + label + " ---");
while (iterator.hasNext()) {
System.out.println(iterator.next().toString());
}
}
}
| mit |
jianghaolu/azure-sdk-for-java | azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ActiveDirectoryGroup.java | 1262 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.graphrbac;
import com.microsoft.azure.management.apigeneration.Beta;
import com.microsoft.azure.management.apigeneration.Fluent;
import com.microsoft.azure.management.graphrbac.implementation.ADGroupInner;
import com.microsoft.azure.management.graphrbac.implementation.GraphRbacManager;
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasId;
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasManager;
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasName;
import com.microsoft.azure.management.resources.fluentcore.model.HasInner;
/**
* An immutable client-side representation of an Azure AD group.
*/
@Fluent(ContainerName = "/Microsoft.Azure.Management.Graph.RBAC.Fluent")
@Beta
public interface ActiveDirectoryGroup extends
HasId,
HasName,
HasInner<ADGroupInner>,
HasManager<GraphRbacManager> {
/**
* @return security enabled field.
*/
boolean securityEnabled();
/**
* @return mail field.
*/
String mail();
}
| mit |
brucevsked/vskeddemolist | vskeddemos/mavenproject/springboot2list/springsecurity/3springsecurity/src/main/java/com/vsked/auth/repository/AuthorityRepository.java | 293 | package com.vsked.auth.repository;
import com.vsked.auth.model.Authority;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Spring Data JPA repository for the {@link Authority} entity.
*/
public interface AuthorityRepository extends JpaRepository<Authority, String> {
}
| mit |
hejunbinlan/nucleus | nucleus-example-with-fragments/src/androidTest/java/nucleus/example/main/FragmentStackTest.java | 4143 | package nucleus.example.main;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import nucleus.example.TestActivity;
import nucleus.factory.PresenterFactory;
import nucleus.presenter.Presenter;
import nucleus.view.ViewWithPresenter;
public class FragmentStackTest extends ActivityInstrumentationTestCase2<TestActivity> {
private static final int CONTAINER_ID = android.R.id.content;
private TestActivity activity;
public FragmentStackTest() {
super(TestActivity.class);
}
@Override
public void setUp() throws Exception {
activity = getActivity();
}
public static class TestPresenter extends Presenter {
public int onDestroy;
@Override
protected void onDestroy() {
super.onDestroy();
onDestroy++;
}
}
public static class TestFragment1 extends Fragment implements ViewWithPresenter<TestPresenter> {
public TestPresenter presenter = new TestPresenter();
@Override
public PresenterFactory<TestPresenter> getPresenterFactory() {
return null;
}
@Override
public void setPresenterFactory(PresenterFactory<TestPresenter> presenterFactory) {
}
@Override
public TestPresenter getPresenter() {
return presenter;
}
}
public static class TestFragment2 extends Fragment {
}
@UiThreadTest
public void testPushPop() throws Exception {
FragmentManager manager = activity.getSupportFragmentManager();
FragmentStack stack = new FragmentStack(manager, CONTAINER_ID);
TestFragment1 fragment = new TestFragment1();
stack.push(fragment);
assertTopFragment(manager, stack, fragment, 0);
TestFragment2 fragment2 = new TestFragment2();
stack.push(fragment2);
assertFragment(manager, fragment, 0);
assertTopFragment(manager, stack, fragment2, 1);
assertFalse(fragment.isAdded());
assertTrue(fragment2.isAdded());
assertTrue(stack.pop());
assertTopFragment(manager, stack, fragment, 0);
assertNull(manager.findFragmentByTag("1"));
assertFalse(stack.pop());
assertTopFragment(manager, stack, fragment, 0);
}
@UiThreadTest
public void testReplace() throws Exception {
FragmentManager manager = activity.getSupportFragmentManager();
FragmentStack stack = new FragmentStack(manager, CONTAINER_ID);
TestFragment1 fragment = new TestFragment1();
stack.replace(fragment);
assertTopFragment(manager, stack, fragment, 0);
TestFragment2 fragment2 = new TestFragment2();
stack.replace(fragment2);
assertTopFragment(manager, stack, fragment2, 0);
}
@UiThreadTest
public void testPushReplace() throws Exception {
FragmentManager manager = activity.getSupportFragmentManager();
FragmentStack stack = new FragmentStack(manager, CONTAINER_ID);
TestFragment1 fragment = new TestFragment1();
stack.push(fragment);
TestFragment2 fragment2 = new TestFragment2();
stack.push(fragment2);
assertEquals(0, fragment.presenter.onDestroy);
TestFragment1 fragment3 = new TestFragment1();
stack.replace(fragment3);
assertTopFragment(manager, stack, fragment3, 0);
assertEquals(1, fragment.presenter.onDestroy);
assertNull(manager.findFragmentByTag("1"));
}
private void assertTopFragment(FragmentManager manager, FragmentStack stack, Fragment fragment, int index) {
assertFragment(manager, fragment, index);
assertEquals(fragment, manager.findFragmentById(CONTAINER_ID));
assertEquals(fragment, stack.peek());
assertEquals(index, manager.getBackStackEntryCount());
}
private void assertFragment(FragmentManager manager, Fragment fragment, int index) {
assertEquals(fragment, manager.findFragmentByTag(Integer.toString(index)));
}
}
| mit |
faribas/RMG-Java | source/RMG/jing/chem/ReplaceThermoGAValueException.java | 2202 | ////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2011 Prof. William H. Green (whgreen@mit.edu) and the
// RMG Team (rmg_dev@mit.edu)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jing.chem;
import java.util.*;
//## package jing::chem
//----------------------------------------------------------------------------
// jing\chem\ReplaceThermoGAValueException.java
//----------------------------------------------------------------------------
//## class ReplaceThermoGAValueException
public class ReplaceThermoGAValueException extends RuntimeException{
// Constructors
public ReplaceThermoGAValueException() {
}
}
/*********************************************************************
File Path : RMG\RMG\jing\chem\ReplaceThermoGAValueException.java
*********************************************************************/
| mit |
wanghaohappy1/coding_problems | leetcode/medium/WordLadder.java | 1427 | /**
* Problem: Find the length of shortest transformation sequence
*
* Solution: BFS--for words in each level, try each possible letter a-z on each position of the word;
* Use queue to store words in a level and use a hashset to mark visited words.
*/
import java.util.*;
public class WordLadder{
public int ladderLength(String start, String end, Set<String> dict){
if(start==null || end==null || start.equals(end)){
return 0;
}
Queue<String> q = new LinkedList<String>();
q.offer(start);
HashSet<String> visited = new HashSet<String>();
int result = 1;
//for each depth
while(!q.isEmpty()){
Queue<String> nextDepth = new LinkedList<String>();
//for each word in current depth
while(!q.isEmpty()){
String s = q.poll();
char[] arr = s.toCharArray();
int len = s.length();
//change every character
for(int i=0; i<len; i++){
char prev = arr[i];
//try each letter
for(int j='a'; j<='z'; j++){
arr[i] = (char)j;
String temp = new String(arr);
//target found
if(temp.equals(end)){
return result;
}
//find a new word in the next level
if(dict.contains(temp) && !visited.contains(temp)){
nextDepth.offer(temp);
visited.add(temp);
}
}
//change letter back
arr[i] = prev;
}
}
//go to next level
q = nextDepth;
result ++;
}
return 0;
}
} | mit |
JeffRisberg/BING01 | src/main/java/com/microsoft/bingads/reporting/ReportingOperationInProgressException.java | 291 | package com.microsoft.bingads.reporting;
/**
* This exception is thrown when trying to download the result file for an operation that hasn't completed yet.
*/
public class ReportingOperationInProgressException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
| mit |
darshanhs90/Java-Coding | src/April2021PrepLeetcode/_0198HouseRobber.java | 355 | package April2021PrepLeetcode;
public class _0198HouseRobber {
public static void main(String[] args) {
System.out.println(rob(new int[] { 1, 2, 3, 1 }));
System.out.println(rob(new int[] { 2, 7, 9, 3, 1 }));
System.out.println(rob(new int[] { 1, 2 }));
System.out.println(rob(new int[] { 1 }));
}
public static int rob(int[] nums) {
}
}
| mit |
martinsawicki/azure-sdk-for-java | azure-mgmt-customerinsights/src/main/java/com/microsoft/azure/management/customerinsights/implementation/AuthorizationPoliciesInner.java | 43999 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.customerinsights.implementation;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.Validator;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in AuthorizationPolicies.
*/
public class AuthorizationPoliciesInner {
/** The Retrofit service to perform REST calls. */
private AuthorizationPoliciesService service;
/** The service client containing this operation class. */
private CustomerInsightsManagementClientImpl client;
/**
* Initializes an instance of AuthorizationPoliciesInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public AuthorizationPoliciesInner(Retrofit retrofit, CustomerInsightsManagementClientImpl client) {
this.service = retrofit.create(AuthorizationPoliciesService.class);
this.client = client;
}
/**
* The interface defining all the services for AuthorizationPolicies to be
* used by Retrofit to perform actually REST calls.
*/
interface AuthorizationPoliciesService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.customerinsights.AuthorizationPolicies createOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/authorizationPolicies/{authorizationPolicyName}")
Observable<Response<ResponseBody>> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("hubName") String hubName, @Path("authorizationPolicyName") String authorizationPolicyName, @Path("subscriptionId") String subscriptionId, @Body AuthorizationPolicyResourceFormatInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.customerinsights.AuthorizationPolicies get" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/authorizationPolicies/{authorizationPolicyName}")
Observable<Response<ResponseBody>> get(@Path("resourceGroupName") String resourceGroupName, @Path("hubName") String hubName, @Path("authorizationPolicyName") String authorizationPolicyName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.customerinsights.AuthorizationPolicies listByHub" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/authorizationPolicies")
Observable<Response<ResponseBody>> listByHub(@Path("resourceGroupName") String resourceGroupName, @Path("hubName") String hubName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.customerinsights.AuthorizationPolicies regeneratePrimaryKey" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/authorizationPolicies/{authorizationPolicyName}/regeneratePrimaryKey")
Observable<Response<ResponseBody>> regeneratePrimaryKey(@Path("resourceGroupName") String resourceGroupName, @Path("hubName") String hubName, @Path("authorizationPolicyName") String authorizationPolicyName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.customerinsights.AuthorizationPolicies regenerateSecondaryKey" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/authorizationPolicies/{authorizationPolicyName}/regenerateSecondaryKey")
Observable<Response<ResponseBody>> regenerateSecondaryKey(@Path("resourceGroupName") String resourceGroupName, @Path("hubName") String hubName, @Path("authorizationPolicyName") String authorizationPolicyName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.customerinsights.AuthorizationPolicies listByHubNext" })
@GET
Observable<Response<ResponseBody>> listByHubNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Creates an authorization policy or updates an existing authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param parameters Parameters supplied to the CreateOrUpdate authorization policy operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the AuthorizationPolicyResourceFormatInner object if successful.
*/
public AuthorizationPolicyResourceFormatInner createOrUpdate(String resourceGroupName, String hubName, String authorizationPolicyName, AuthorizationPolicyResourceFormatInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName, parameters).toBlocking().single().body();
}
/**
* Creates an authorization policy or updates an existing authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param parameters Parameters supplied to the CreateOrUpdate authorization policy operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<AuthorizationPolicyResourceFormatInner> createOrUpdateAsync(String resourceGroupName, String hubName, String authorizationPolicyName, AuthorizationPolicyResourceFormatInner parameters, final ServiceCallback<AuthorizationPolicyResourceFormatInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName, parameters), serviceCallback);
}
/**
* Creates an authorization policy or updates an existing authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param parameters Parameters supplied to the CreateOrUpdate authorization policy operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the AuthorizationPolicyResourceFormatInner object
*/
public Observable<AuthorizationPolicyResourceFormatInner> createOrUpdateAsync(String resourceGroupName, String hubName, String authorizationPolicyName, AuthorizationPolicyResourceFormatInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName, parameters).map(new Func1<ServiceResponse<AuthorizationPolicyResourceFormatInner>, AuthorizationPolicyResourceFormatInner>() {
@Override
public AuthorizationPolicyResourceFormatInner call(ServiceResponse<AuthorizationPolicyResourceFormatInner> response) {
return response.body();
}
});
}
/**
* Creates an authorization policy or updates an existing authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param parameters Parameters supplied to the CreateOrUpdate authorization policy operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the AuthorizationPolicyResourceFormatInner object
*/
public Observable<ServiceResponse<AuthorizationPolicyResourceFormatInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String hubName, String authorizationPolicyName, AuthorizationPolicyResourceFormatInner parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (hubName == null) {
throw new IllegalArgumentException("Parameter hubName is required and cannot be null.");
}
if (authorizationPolicyName == null) {
throw new IllegalArgumentException("Parameter authorizationPolicyName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
Validator.validate(parameters);
return service.createOrUpdate(resourceGroupName, hubName, authorizationPolicyName, this.client.subscriptionId(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<AuthorizationPolicyResourceFormatInner>>>() {
@Override
public Observable<ServiceResponse<AuthorizationPolicyResourceFormatInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<AuthorizationPolicyResourceFormatInner> clientResponse = createOrUpdateDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<AuthorizationPolicyResourceFormatInner> createOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<AuthorizationPolicyResourceFormatInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<AuthorizationPolicyResourceFormatInner>() { }.getType())
.register(201, new TypeToken<AuthorizationPolicyResourceFormatInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets an authorization policy in the hub.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the AuthorizationPolicyResourceFormatInner object if successful.
*/
public AuthorizationPolicyResourceFormatInner get(String resourceGroupName, String hubName, String authorizationPolicyName) {
return getWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName).toBlocking().single().body();
}
/**
* Gets an authorization policy in the hub.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<AuthorizationPolicyResourceFormatInner> getAsync(String resourceGroupName, String hubName, String authorizationPolicyName, final ServiceCallback<AuthorizationPolicyResourceFormatInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName), serviceCallback);
}
/**
* Gets an authorization policy in the hub.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the AuthorizationPolicyResourceFormatInner object
*/
public Observable<AuthorizationPolicyResourceFormatInner> getAsync(String resourceGroupName, String hubName, String authorizationPolicyName) {
return getWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName).map(new Func1<ServiceResponse<AuthorizationPolicyResourceFormatInner>, AuthorizationPolicyResourceFormatInner>() {
@Override
public AuthorizationPolicyResourceFormatInner call(ServiceResponse<AuthorizationPolicyResourceFormatInner> response) {
return response.body();
}
});
}
/**
* Gets an authorization policy in the hub.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the AuthorizationPolicyResourceFormatInner object
*/
public Observable<ServiceResponse<AuthorizationPolicyResourceFormatInner>> getWithServiceResponseAsync(String resourceGroupName, String hubName, String authorizationPolicyName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (hubName == null) {
throw new IllegalArgumentException("Parameter hubName is required and cannot be null.");
}
if (authorizationPolicyName == null) {
throw new IllegalArgumentException("Parameter authorizationPolicyName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.get(resourceGroupName, hubName, authorizationPolicyName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<AuthorizationPolicyResourceFormatInner>>>() {
@Override
public Observable<ServiceResponse<AuthorizationPolicyResourceFormatInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<AuthorizationPolicyResourceFormatInner> clientResponse = getDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<AuthorizationPolicyResourceFormatInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<AuthorizationPolicyResourceFormatInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<AuthorizationPolicyResourceFormatInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets all the authorization policies in a specified hub.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<AuthorizationPolicyResourceFormatInner> object if successful.
*/
public PagedList<AuthorizationPolicyResourceFormatInner> listByHub(final String resourceGroupName, final String hubName) {
ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>> response = listByHubSinglePageAsync(resourceGroupName, hubName).toBlocking().single();
return new PagedList<AuthorizationPolicyResourceFormatInner>(response.body()) {
@Override
public Page<AuthorizationPolicyResourceFormatInner> nextPage(String nextPageLink) {
return listByHubNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all the authorization policies in a specified hub.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<AuthorizationPolicyResourceFormatInner>> listByHubAsync(final String resourceGroupName, final String hubName, final ListOperationCallback<AuthorizationPolicyResourceFormatInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByHubSinglePageAsync(resourceGroupName, hubName),
new Func1<String, Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>> call(String nextPageLink) {
return listByHubNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all the authorization policies in a specified hub.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AuthorizationPolicyResourceFormatInner> object
*/
public Observable<Page<AuthorizationPolicyResourceFormatInner>> listByHubAsync(final String resourceGroupName, final String hubName) {
return listByHubWithServiceResponseAsync(resourceGroupName, hubName)
.map(new Func1<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>, Page<AuthorizationPolicyResourceFormatInner>>() {
@Override
public Page<AuthorizationPolicyResourceFormatInner> call(ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>> response) {
return response.body();
}
});
}
/**
* Gets all the authorization policies in a specified hub.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AuthorizationPolicyResourceFormatInner> object
*/
public Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>> listByHubWithServiceResponseAsync(final String resourceGroupName, final String hubName) {
return listByHubSinglePageAsync(resourceGroupName, hubName)
.concatMap(new Func1<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>, Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>> call(ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByHubNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all the authorization policies in a specified hub.
*
ServiceResponse<PageImpl<AuthorizationPolicyResourceFormatInner>> * @param resourceGroupName The name of the resource group.
ServiceResponse<PageImpl<AuthorizationPolicyResourceFormatInner>> * @param hubName The name of the hub.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<AuthorizationPolicyResourceFormatInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>> listByHubSinglePageAsync(final String resourceGroupName, final String hubName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (hubName == null) {
throw new IllegalArgumentException("Parameter hubName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.listByHub(resourceGroupName, hubName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<AuthorizationPolicyResourceFormatInner>> result = listByHubDelegate(response);
return Observable.just(new ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<AuthorizationPolicyResourceFormatInner>> listByHubDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<AuthorizationPolicyResourceFormatInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<AuthorizationPolicyResourceFormatInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Regenerates the primary policy key of the specified authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the AuthorizationPolicyInner object if successful.
*/
public AuthorizationPolicyInner regeneratePrimaryKey(String resourceGroupName, String hubName, String authorizationPolicyName) {
return regeneratePrimaryKeyWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName).toBlocking().single().body();
}
/**
* Regenerates the primary policy key of the specified authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<AuthorizationPolicyInner> regeneratePrimaryKeyAsync(String resourceGroupName, String hubName, String authorizationPolicyName, final ServiceCallback<AuthorizationPolicyInner> serviceCallback) {
return ServiceFuture.fromResponse(regeneratePrimaryKeyWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName), serviceCallback);
}
/**
* Regenerates the primary policy key of the specified authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the AuthorizationPolicyInner object
*/
public Observable<AuthorizationPolicyInner> regeneratePrimaryKeyAsync(String resourceGroupName, String hubName, String authorizationPolicyName) {
return regeneratePrimaryKeyWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName).map(new Func1<ServiceResponse<AuthorizationPolicyInner>, AuthorizationPolicyInner>() {
@Override
public AuthorizationPolicyInner call(ServiceResponse<AuthorizationPolicyInner> response) {
return response.body();
}
});
}
/**
* Regenerates the primary policy key of the specified authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the AuthorizationPolicyInner object
*/
public Observable<ServiceResponse<AuthorizationPolicyInner>> regeneratePrimaryKeyWithServiceResponseAsync(String resourceGroupName, String hubName, String authorizationPolicyName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (hubName == null) {
throw new IllegalArgumentException("Parameter hubName is required and cannot be null.");
}
if (authorizationPolicyName == null) {
throw new IllegalArgumentException("Parameter authorizationPolicyName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.regeneratePrimaryKey(resourceGroupName, hubName, authorizationPolicyName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<AuthorizationPolicyInner>>>() {
@Override
public Observable<ServiceResponse<AuthorizationPolicyInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<AuthorizationPolicyInner> clientResponse = regeneratePrimaryKeyDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<AuthorizationPolicyInner> regeneratePrimaryKeyDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<AuthorizationPolicyInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<AuthorizationPolicyInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Regenerates the secondary policy key of the specified authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the AuthorizationPolicyInner object if successful.
*/
public AuthorizationPolicyInner regenerateSecondaryKey(String resourceGroupName, String hubName, String authorizationPolicyName) {
return regenerateSecondaryKeyWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName).toBlocking().single().body();
}
/**
* Regenerates the secondary policy key of the specified authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<AuthorizationPolicyInner> regenerateSecondaryKeyAsync(String resourceGroupName, String hubName, String authorizationPolicyName, final ServiceCallback<AuthorizationPolicyInner> serviceCallback) {
return ServiceFuture.fromResponse(regenerateSecondaryKeyWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName), serviceCallback);
}
/**
* Regenerates the secondary policy key of the specified authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the AuthorizationPolicyInner object
*/
public Observable<AuthorizationPolicyInner> regenerateSecondaryKeyAsync(String resourceGroupName, String hubName, String authorizationPolicyName) {
return regenerateSecondaryKeyWithServiceResponseAsync(resourceGroupName, hubName, authorizationPolicyName).map(new Func1<ServiceResponse<AuthorizationPolicyInner>, AuthorizationPolicyInner>() {
@Override
public AuthorizationPolicyInner call(ServiceResponse<AuthorizationPolicyInner> response) {
return response.body();
}
});
}
/**
* Regenerates the secondary policy key of the specified authorization policy.
*
* @param resourceGroupName The name of the resource group.
* @param hubName The name of the hub.
* @param authorizationPolicyName The name of the policy.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the AuthorizationPolicyInner object
*/
public Observable<ServiceResponse<AuthorizationPolicyInner>> regenerateSecondaryKeyWithServiceResponseAsync(String resourceGroupName, String hubName, String authorizationPolicyName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (hubName == null) {
throw new IllegalArgumentException("Parameter hubName is required and cannot be null.");
}
if (authorizationPolicyName == null) {
throw new IllegalArgumentException("Parameter authorizationPolicyName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.regenerateSecondaryKey(resourceGroupName, hubName, authorizationPolicyName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<AuthorizationPolicyInner>>>() {
@Override
public Observable<ServiceResponse<AuthorizationPolicyInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<AuthorizationPolicyInner> clientResponse = regenerateSecondaryKeyDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<AuthorizationPolicyInner> regenerateSecondaryKeyDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<AuthorizationPolicyInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<AuthorizationPolicyInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets all the authorization policies in a specified hub.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<AuthorizationPolicyResourceFormatInner> object if successful.
*/
public PagedList<AuthorizationPolicyResourceFormatInner> listByHubNext(final String nextPageLink) {
ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>> response = listByHubNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<AuthorizationPolicyResourceFormatInner>(response.body()) {
@Override
public Page<AuthorizationPolicyResourceFormatInner> nextPage(String nextPageLink) {
return listByHubNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all the authorization policies in a specified hub.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<AuthorizationPolicyResourceFormatInner>> listByHubNextAsync(final String nextPageLink, final ServiceFuture<List<AuthorizationPolicyResourceFormatInner>> serviceFuture, final ListOperationCallback<AuthorizationPolicyResourceFormatInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByHubNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>> call(String nextPageLink) {
return listByHubNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all the authorization policies in a specified hub.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AuthorizationPolicyResourceFormatInner> object
*/
public Observable<Page<AuthorizationPolicyResourceFormatInner>> listByHubNextAsync(final String nextPageLink) {
return listByHubNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>, Page<AuthorizationPolicyResourceFormatInner>>() {
@Override
public Page<AuthorizationPolicyResourceFormatInner> call(ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>> response) {
return response.body();
}
});
}
/**
* Gets all the authorization policies in a specified hub.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AuthorizationPolicyResourceFormatInner> object
*/
public Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>> listByHubNextWithServiceResponseAsync(final String nextPageLink) {
return listByHubNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>, Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>> call(ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByHubNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all the authorization policies in a specified hub.
*
ServiceResponse<PageImpl<AuthorizationPolicyResourceFormatInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<AuthorizationPolicyResourceFormatInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>> listByHubNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listByHubNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<AuthorizationPolicyResourceFormatInner>> result = listByHubNextDelegate(response);
return Observable.just(new ServiceResponse<Page<AuthorizationPolicyResourceFormatInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<AuthorizationPolicyResourceFormatInner>> listByHubNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<AuthorizationPolicyResourceFormatInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<AuthorizationPolicyResourceFormatInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| mit |
benas/jPopulator | easy-random-core/src/main/java/org/jeasy/random/randomizers/time/DayRandomizer.java | 2191 | /**
* The MIT License
*
* Copyright (c) 2019, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jeasy.random.randomizers.time;
import org.jeasy.random.api.Randomizer;
import org.jeasy.random.randomizers.range.IntegerRangeRandomizer;
/**
* A {@link Randomizer} that generates a random day value between {@link DayRandomizer#MIN_DAY} and {@link DayRandomizer#MAX_DAY}.
*
* @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
*/
public class DayRandomizer implements Randomizer<Integer> {
public static final int MIN_DAY = 1;
public static final int MAX_DAY = 28; // 31 may break some LocalDateTime instances when the dayOfMonth is invalid
private final IntegerRangeRandomizer dayRandomizer;
public DayRandomizer() {
dayRandomizer = new IntegerRangeRandomizer(MIN_DAY, MAX_DAY);
}
public DayRandomizer(final long seed) {
dayRandomizer = new IntegerRangeRandomizer(MIN_DAY, MAX_DAY, seed);
}
@Override
public Integer getRandomValue() {
return dayRandomizer.getRandomValue();
}
}
| mit |
HenryHarper/Acquire-Reboot | gradle/src/tooling-api/org/gradle/tooling/internal/consumer/loader/DefaultToolingImplementationLoader.java | 6676 | /*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.tooling.internal.consumer.loader;
import org.gradle.initialization.BuildCancellationToken;
import org.gradle.internal.Factory;
import org.gradle.internal.classloader.FilteringClassLoader;
import org.gradle.internal.classloader.MultiParentClassLoader;
import org.gradle.internal.classloader.MutableURLClassLoader;
import org.gradle.internal.classpath.ClassPath;
import org.gradle.internal.service.ServiceLocator;
import org.gradle.logging.ProgressLoggerFactory;
import org.gradle.tooling.GradleConnectionException;
import org.gradle.tooling.UnsupportedVersionException;
import org.gradle.tooling.internal.adapter.ProtocolToModelAdapter;
import org.gradle.tooling.internal.consumer.ConnectionParameters;
import org.gradle.tooling.internal.consumer.Distribution;
import org.gradle.tooling.internal.consumer.connection.*;
import org.gradle.tooling.internal.consumer.converters.ConsumerTargetTypeProvider;
import org.gradle.tooling.internal.consumer.versioning.ModelMapping;
import org.gradle.tooling.internal.protocol.*;
import org.gradle.tooling.internal.protocol.test.InternalTestExecutionConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class DefaultToolingImplementationLoader implements ToolingImplementationLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultToolingImplementationLoader.class);
private final ClassLoader classLoader;
public DefaultToolingImplementationLoader() {
this(DefaultToolingImplementationLoader.class.getClassLoader());
}
DefaultToolingImplementationLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public ConsumerConnection create(Distribution distribution, ProgressLoggerFactory progressLoggerFactory, ConnectionParameters connectionParameters, BuildCancellationToken cancellationToken) {
LOGGER.debug("Using tooling provider from {}", distribution.getDisplayName());
ClassLoader classLoader = createImplementationClassLoader(distribution, progressLoggerFactory, connectionParameters.getGradleUserHomeDir(), cancellationToken);
ServiceLocator serviceLocator = new ServiceLocator(classLoader);
try {
Factory<ConnectionVersion4> factory = serviceLocator.findFactory(ConnectionVersion4.class);
if (factory == null) {
return new NoToolingApiConnection(distribution);
}
// ConnectionVersion4 is a part of the protocol and cannot be easily changed.
ConnectionVersion4 connection = factory.create();
ProtocolToModelAdapter adapter = new ProtocolToModelAdapter(new ConsumerTargetTypeProvider());
ModelMapping modelMapping = new ModelMapping();
// Adopting the connection to a refactoring friendly type that the consumer owns
AbstractConsumerConnection adaptedConnection;
if (connection instanceof InternalTestExecutionConnection){
adaptedConnection = new TestExecutionConsumerConnection(connection, modelMapping, adapter);
} else if (connection instanceof StoppableConnection) {
adaptedConnection = new ShutdownAwareConsumerConnection(connection, modelMapping, adapter);
} else if (connection instanceof InternalCancellableConnection) {
adaptedConnection = new CancellableConsumerConnection(connection, modelMapping, adapter);
} else if (connection instanceof ModelBuilder && connection instanceof InternalBuildActionExecutor) {
adaptedConnection = new ActionAwareConsumerConnection(connection, modelMapping, adapter);
} else if (connection instanceof ModelBuilder) {
adaptedConnection = new ModelBuilderBackedConsumerConnection(connection, modelMapping, adapter);
} else if (connection instanceof BuildActionRunner) {
adaptedConnection = new BuildActionRunnerBackedConsumerConnection(connection, modelMapping, adapter);
} else if (connection instanceof InternalConnection) {
adaptedConnection = new InternalConnectionBackedConsumerConnection(connection, modelMapping, adapter);
} else {
return new UnsupportedOlderVersionConnection(distribution, connection, adapter);
}
adaptedConnection.configure(connectionParameters);
if (!adaptedConnection.getVersionDetails().supportsCancellation()) {
return new NonCancellableConsumerConnectionAdapter(adaptedConnection);
}
return adaptedConnection;
} catch (UnsupportedVersionException e) {
throw e;
} catch (Throwable t) {
throw new GradleConnectionException(String.format("Could not create an instance of Tooling API implementation using the specified %s.", distribution.getDisplayName()), t);
}
}
private ClassLoader createImplementationClassLoader(Distribution distribution, ProgressLoggerFactory progressLoggerFactory, File userHomeDir, BuildCancellationToken cancellationToken) {
ClassPath implementationClasspath = distribution.getToolingImplementationClasspath(progressLoggerFactory, userHomeDir, cancellationToken);
LOGGER.debug("Using tooling provider classpath: {}", implementationClasspath);
// On IBM JVM 5, ClassLoader.getResources() uses a combination of findResources() and getParent() and traverses the hierarchy rather than just calling getResources()
// Wrap our real classloader in one that hides the parent.
// TODO - move this into FilteringClassLoader
MultiParentClassLoader parentObfuscatingClassLoader = new MultiParentClassLoader(classLoader);
FilteringClassLoader filteringClassLoader = new FilteringClassLoader(parentObfuscatingClassLoader);
filteringClassLoader.allowPackage("org.gradle.tooling.internal.protocol");
return new MutableURLClassLoader(filteringClassLoader, implementationClasspath.getAsURLArray());
}
}
| mit |
RyanBard/healthbam | src/main/java/org/hmhb/csv/CsvService.java | 1263 | package org.hmhb.csv;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import org.hmhb.program.Program;
import org.hmhb.user.HmhbUser;
/**
* A service to generate CSV from our data.
*/
public interface CsvService {
/**
* Generates the contents for a CSV from the passed in {@link Program}s.
*
* @param programs the list of {@link Program}s to generate CSV from
* @param expandCounties whether a program's counties should not be
* flattened into one row (comma delimited)
* @param expandProgramAreas whether a program's program areas should not
* be flattened into one row (comma delimited)
* @return the CSV of the passed in programs
*/
String generateFromPrograms(
@Nonnull List<Program> programs,
@Nullable Boolean expandCounties,
@Nullable Boolean expandProgramAreas
);
/**
* Generates the contents for a CSV from the passed in {@link HmhbUser}s.
*
* @param users the list of {@link HmhbUser}s to generate CSV from
* @return the CSV of the passed in users
*/
String generateFromUsers(
@Nonnull List<HmhbUser> users
);
}
| mit |
ladygagapowerbot/bachelor-thesis-implementation | lib/Encog/src/main/java/org/encog/ml/prg/extension/FunctionFactory.java | 9864 | /*
* Encog(tm) Core v3.2 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2013 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.ml.prg.extension;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.encog.ml.ea.exception.EACompileError;
import org.encog.ml.prg.EncogProgram;
import org.encog.ml.prg.EncogProgramContext;
import org.encog.ml.prg.ExpressionError;
import org.encog.ml.prg.ProgramNode;
import org.encog.ml.prg.expvalue.ValueType;
/**
* A function factory maps the opcodes contained in the EncogOpcodeRegistry into
* an EncogProgram. You rarely want to train with every available opcode. For
* example, if you are only looking to produce an equation, you should not make
* use of the if-statement and logical operators.
*/
public class FunctionFactory implements Serializable {
/**
* The serial id.
*/
private static final long serialVersionUID = 1L;
/**
* A map for quick lookup.
*/
private final Map<String, ProgramExtensionTemplate> templateMap =
new HashMap<String, ProgramExtensionTemplate>();
/**
* The opcodes.
*/
private final List<ProgramExtensionTemplate> opcodes =
new ArrayList<ProgramExtensionTemplate>();
/**
* Default constructor.
*/
public FunctionFactory() {
}
/**
* Add an opcode to the function factory. The opcode must exist in the
* opcode registry.
* <p/>
* @param ext
* The opcode to add.
*/
public void addExtension(final ProgramExtensionTemplate ext) {
addExtension(ext.getName(), ext.getChildNodeCount());
}
/**
* Add an opcode to the function factory from the opcode registry.
* <p/>
* @param name
* The name of the opcode.
* @param args
* The number of arguments.
*/
public void addExtension(final String name, final int args) {
final String key = EncogOpcodeRegistry.createKey(name, args);
if (!this.templateMap.containsKey(key)) {
final ProgramExtensionTemplate temp = EncogOpcodeRegistry.INSTANCE
.findOpcode(name, args);
if (temp == null) {
throw new EACompileError(
"Unknown extension " + name + " with " +
args + " arguments.");
}
this.opcodes.add(temp);
this.templateMap.put(key, temp);
}
}
/**
* Factor a new program node, based in a template object.
* <p/>
* @param temp
* The opcode.
* @param program
* The program.
* @param args
* The arguments for this node.
* <p/>
* @return The newly created ProgramNode.
*/
public ProgramNode factorProgramNode(final ProgramExtensionTemplate temp,
final EncogProgram program,
final ProgramNode[] args) {
return new ProgramNode(program, temp, args);
}
/**
* Factor a new program node, based on an opcode name and arguments.
* <p/>
* @param name
* The name of the opcode.
* @param program
* The program to factor for.
* @param args
* The arguements.
* <p/>
* @return The newly created ProgramNode.
*/
public ProgramNode factorProgramNode(final String name,
final EncogProgram program,
final ProgramNode[] args) {
final String key = EncogOpcodeRegistry.createKey(name, args.length);
if (!this.templateMap.containsKey(key)) {
throw new ExpressionError("Undefined function/operator: " + name +
" with " + args.length + " args.");
}
final ProgramExtensionTemplate temp = this.templateMap.get(key);
return new ProgramNode(program, temp, args);
}
/**
* Find a function with the specified name.
* <p/>
* @param name
* The name of the function.
* <p/>
* @return The function opcode.
*/
public ProgramExtensionTemplate findFunction(final String name) {
for (final ProgramExtensionTemplate opcode : this.opcodes) {
// only consider functions
if (opcode.getNodeType() == NodeType.Function) {
if (opcode.getName().equals(name)) {
return opcode;
}
}
}
return null;
}
/**
* Find all opcodes that match the search criteria.
* <p/>
* @param types
* The return types to consider.
* @param context
* The program context.
* @param includeTerminal
* True, to include the terminals.
* @param includeFunction
* True, to include the functions.
* <p/>
* @return The opcodes found.
*/
public List<ProgramExtensionTemplate> findOpcodes(
final List<ValueType> types, final EncogProgramContext context,
final boolean includeTerminal, final boolean includeFunction) {
final List<ProgramExtensionTemplate> result =
new ArrayList<ProgramExtensionTemplate>();
for (final ProgramExtensionTemplate temp : this.opcodes) {
for (final ValueType rtn : types) {
// it is a possible return type, but given our variables, is it
// possible
if (temp.isPossibleReturnType(context, rtn)) {
if (temp.getChildNodeCount() == 0 && includeTerminal) {
result.add(temp);
} else if (includeFunction) {
result.add(temp);
}
}
}
}
return result;
}
/**
* This method is used when parsing an expression. Consider x>=2. The parser
* first sees the > symbol. But it must also consider the =. So we first
* look for a 2-char operator, in this case there is one.
* <p/>
* @param ch1
* The first character of the potential operator.
* @param ch2
* The second character of the potential operator. Zero if none.
* <p/>
* @return The expression template for the operator found.
*/
public ProgramExtensionTemplate findOperator(final char ch1, final char ch2) {
ProgramExtensionTemplate result = null;
// if ch2==0 then we are only looking for a single char operator.
// this is rare, but supported.
if (ch2 == 0) {
return findOperatorExact("" + ch1);
}
// first, see if we can match an operator with both ch1 and ch2
result = findOperatorExact("" + ch1 + ch2);
if (result == null) {
// okay no 2-char operators matched, so see if we can find a single
// char
result = findOperatorExact("" + ch1);
}
// return the operator if we have one.
return result;
}
/**
* Find an exact match on opcode.
* <p/>
* @param str
* The string to match.
* <p/>
* @return The opcode found.
*/
private ProgramExtensionTemplate findOperatorExact(final String str) {
for (final ProgramExtensionTemplate opcode : this.opcodes) {
// only consider non-unary operators
if (opcode.getNodeType() == NodeType.OperatorLeft || opcode
.getNodeType() == NodeType.OperatorRight) {
if (opcode.getName().equals(str)) {
return opcode;
}
}
}
return null;
}
/**
* Get the specified opcode.
* <p/>
* @param theOpCode
* The opcode index.
* <p/>
* @return The opcode.
*/
public ProgramExtensionTemplate getOpCode(final int theOpCode) {
return this.opcodes.get(theOpCode);
}
/**
* @return The opcode list.
*/
public List<ProgramExtensionTemplate> getOpCodes() {
return this.opcodes;
}
/**
* @return the templateMap
*/
public Map<String, ProgramExtensionTemplate> getTemplateMap() {
return this.templateMap;
}
/**
* Determine if an opcode is in the function factory.
* <p/>
* @param name
* The name of the opcode.
* @param l
* The argument count for the opcode.
* <p/>
* @return True if the opcode exists.
*/
public boolean isDefined(final String name, final int l) {
final String key = EncogOpcodeRegistry.createKey(name, l);
return this.templateMap.containsKey(key);
}
/**
* @return The number of opcodes.
*/
public int size() {
return this.opcodes.size();
}
}
| mit |
kumuluz/kumuluzee | components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/ws/KumuluzWSInvoker.java | 3132 | /*
* Copyright (c) 2014-2018 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.jaxws.cxf.ws;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.jaxws.JAXWSMethodInvoker;
import org.apache.cxf.jaxws.context.WebServiceContextImpl;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.MessageContentsList;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.invoker.Factory;
import org.apache.cxf.service.invoker.Invoker;
import org.apache.cxf.service.invoker.MethodDispatcher;
import org.apache.cxf.service.model.BindingOperationInfo;
import javax.xml.ws.WebServiceContext;
import java.lang.reflect.Method;
import java.util.List;
/**
* @author gpor89
* @since 3.0.0
*/
public class KumuluzWSInvoker extends JAXWSMethodInvoker implements Invoker {
private Class<?> targetClass;
private Object targetBean;
public KumuluzWSInvoker(final Class<?> targetClass, final Object targetBean) {
super((Factory) null);
this.targetClass = targetClass;
this.targetBean = targetBean;
}
@Override
public Object invoke(Exchange exchange, Object o) {
BindingOperationInfo bop = exchange.get(BindingOperationInfo.class);
MethodDispatcher md = (MethodDispatcher) exchange.get(Service.class).get(MethodDispatcher.class.getName());
List<Object> params = null;
if (o instanceof List) {
params = CastUtils.cast((List<?>) o);
} else if (o != null) {
params = new MessageContentsList(o);
}
final Method method = adjustMethodAndParams(md.getMethod(bop), exchange, params, targetClass);
return invoke(exchange, targetBean, method, params);
}
@Override
protected Object performInvocation(Exchange exchange, final Object serviceObject, Method m, Object[] paramArray) throws Exception {
WebServiceContext wsContext = new WebServiceContextImpl(null);
try {
KumuluzWebServiceContext.getInstance().setMessageContext(wsContext);
return super.performInvocation(exchange, serviceObject, m, paramArray);
} finally {
KumuluzWebServiceContext.getInstance().setMessageContext(null);
}
}
}
| mit |
datalogics-coreyy/pdf-java-toolkit-samples | src/test/java/com/datalogics/pdf/samples/images/ImageDownsamplingTest.java | 12400 | /*
* Copyright 2015 Datalogics, Inc.
*/
package com.datalogics.pdf.samples.images;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertTrue;
import com.adobe.internal.io.ByteReader;
import com.adobe.internal.io.InputStreamByteReader;
import com.adobe.pdfjt.core.exceptions.PDFIOException;
import com.adobe.pdfjt.core.exceptions.PDFInvalidDocumentException;
import com.adobe.pdfjt.core.exceptions.PDFSecurityException;
import com.adobe.pdfjt.core.types.ASName;
import com.adobe.pdfjt.image.Resampler;
import com.adobe.pdfjt.pdf.document.PDFDocument;
import com.adobe.pdfjt.pdf.document.PDFOpenOptions;
import com.adobe.pdfjt.pdf.graphics.xobject.PDFXObject;
import com.adobe.pdfjt.pdf.graphics.xobject.PDFXObjectImage;
import com.adobe.pdfjt.pdf.graphics.xobject.PDFXObjectMap;
import com.adobe.pdfjt.pdf.page.PDFPage;
import com.adobe.pdfjt.services.imageconversion.ImageManager;
import com.datalogics.pdf.samples.SampleTest;
import com.datalogics.pdf.samples.util.Checksum;
import com.datalogics.pdf.samples.util.DocumentUtils;
import org.hamcrest.FeatureMatcher;
import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
/**
* Tests the ImageDownsamplingTest Sample.
*/
@RunWith(Parameterized.class)
public class ImageDownsamplingTest extends SampleTest {
private static final String FILE_NAME = "downsampled_ducky.pdf";
private static final String ORIGINAL_FILE_NAME = "ducky.pdf";
private static final double SCALE_FACTOR = 0.5;
private final DownsamplingTest params;
public ImageDownsamplingTest(final DownsamplingTest parameters) {
this.params = parameters;
}
/**
* Return an iterable with all the parameters for running these tests. In a parameterized test, a test case object
* is instantiated with each set of parameters, and then the runner runs the tests in the case. The beauty is that
* the name listed in the Parameters annotation is shown for each test, so it's easy to associate each image with
* the errors it gives.
*
* @return Iterable
* @throws Exception a general exception was thrown
*/
@Parameters(name = "image: {0}")
public static Iterable<Object[]> parameters() throws Exception {
final List<Object[]> parameters = new ArrayList<Object[]>() { // Create anonymous inner class.
private static final long serialVersionUID = 7720303970424830948L;
private void add(final DownsamplingTest params) {
add(new Object[] { params });
}
// Instance initialization block
{
final DownsamplingTest.Builder builder = new DownsamplingTest.Builder(FILE_NAME);
builder.imageColorSpace(ASName.k_ICCBased).imageCompression(ASName.k_DCTDecode);
// Note that you can modify the builder repeatedly and use it to make more tests.
add(builder.method(Resampler.kResampleBicubic)
.imageChecksum("f214dfd6bf398b1a66cf569350335d2c").build());
}
};
return parameters;
}
@Test
public void testDownsampleImage() throws Exception {
final File file = newOutputFileWithDelete(params.getFileName());
/*
* Run sample which generates files using all three methods: {NearestNeighbor, Bicubic, Linear}
*/
final URL inputUrl = ImageDownsamplingTest.class.getResource(ORIGINAL_FILE_NAME);
final URL outputUrl = newOutputFile(FILE_NAME).toURI().toURL();
ImageDownsampling.downsampleImage(inputUrl, outputUrl);
// Make sure the Output file exists.
assertTrue(file.getPath() + " must exist after run", file.exists());
// Downsample the original image PDF file.
final InputStream inputStream = inputUrl.openStream();
final ByteReader byteReader = new InputStreamByteReader(inputStream);
PDFDocument pdfDoc = PDFDocument.newInstance(byteReader, PDFOpenOptions.newInstance());
PDFPage page = pdfDoc.requirePages().getPage(0);
PDFXObjectMap objMap = page.getResources().getXObjectMap();
int images = 0;
int newWidth = -1;
int newHeight = -1;
for (final ASName name : objMap.keySet()) {
final PDFXObject o = objMap.get(name);
if (o instanceof PDFXObjectImage) {
assertThat("there should only be one image on the first page of the test document", images++,
equalTo(0));
final PDFXObjectImage originalImage = (PDFXObjectImage) o;
final PDFXObjectImage resampledImage = ImageManager.resampleXObjImage(pdfDoc, originalImage,
SCALE_FACTOR, SCALE_FACTOR,
params.getMethod());
newWidth = (int) Math.round(originalImage.getWidth() * SCALE_FACTOR);
newHeight = (int) Math.round(originalImage.getHeight() * SCALE_FACTOR);
objMap.set(name, resampledImage);
}
}
assertThat(images, equalTo(1));
// Read the document output from the ImageDownsampling Sample.
pdfDoc = DocumentUtils.openPdfDocument(file.toURI().toURL());
page = pdfDoc.requirePages().getPage(0);
objMap = page.getResources().getXObjectMap();
images = 0;
for (final ASName name : objMap.keySet()) {
final PDFXObject o = objMap.get(name);
if (o instanceof PDFXObjectImage) {
assertThat("there should only be one image on the first page of the test document", images++,
equalTo(0));
final PDFXObjectImage resampledImage = (PDFXObjectImage) o;
// Check characteristics of the main image
if (params.getImageChecksum() == null) {
assertThat("resampled image has correct size",
resampledImage, allOf(hasProperty("width", equalTo(newWidth)),
hasProperty("height", equalTo(newHeight))));
} else {
assertThat("resampled image has correct size and contents",
resampledImage, allOf(hasProperty("width", equalTo(newWidth)),
hasProperty("height", equalTo(newHeight)),
hasChecksum(params.getImageChecksum())));
}
assertThat("resampled image has one input filter",
resampledImage.getInputFilters().size(), equalTo(1));
assertThat("resampled image has expected compression",
resampledImage.getInputFilters().get(0).getFilterName(),
equalTo(params.getImageCompression()));
assertThat("resampled image has 8 bits per component",
resampledImage.getBitsPerComponent(), equalTo(8));
assertThat("resampled image has expected color space",
resampledImage.getColorSpace().getName(), equalTo(params.getImageColorSpace()));
}
}
assertThat(images, equalTo(1));
}
/**
* Check that a {@link PDFXObjectImage} has a particular checksum.
*
* @param checksum the image checksum to check for
* @return a {@link Matcher}
*/
private Matcher<PDFXObjectImage> hasChecksum(final String checksum) {
// see http://www.planetgeek.ch/2012/03/07/create-your-own-matcher/ for an explanation
return new ImageFeatureMatcher(equalTo(checksum), "has checksum", "checksum");
}
/**
* Supporting class for matching feature of an image.
*/
private static final class ImageFeatureMatcher extends FeatureMatcher<PDFXObjectImage, String> {
private ImageFeatureMatcher(final Matcher<? super String> subMatcher, final String featureDescription,
final String featureName) {
super(subMatcher, featureDescription, featureName);
}
private void throwChecksumError(final Throwable exception) {
throw new IllegalStateException("Getting an image checksum threw " + exception, exception);
}
@Override
protected String featureValueOf(final PDFXObjectImage image) {
final PDFXObjectImage xObjectImage = image;
try {
return Checksum.getMD5Checksum(xObjectImage.getImageStreamData());
} catch (final PDFInvalidDocumentException | PDFIOException | PDFSecurityException
| NoSuchAlgorithmException | IOException e) {
throwChecksumError(e);
}
return null;
}
}
/**
* Parameters for tests. Note that there are no setters; this class should be built with its Builder.
*/
private static class DownsamplingTest {
private String fileName;
private int method;
private String imageChecksum;
private ASName imageColorSpace;
private ASName imageCompression;
private DownsamplingTest() {}
private DownsamplingTest(final Builder builder) {
fileName = builder.fileName;
imageChecksum = builder.imageChecksum;
method = builder.method;
imageCompression = builder.imageCompression;
imageColorSpace = builder.imageColorSpace;
}
/**
* Get downsampling method (int).
*
* @return int
*/
public int getMethod() {
return method;
}
/**
* Get the image checksum.
*
* @return String
*/
public String getImageChecksum() {
return imageChecksum;
}
/**
* Get the file name.
*
* @return String
*/
public String getFileName() {
return fileName;
}
/**
* Get image Colorspace.
*
* @return ASName
*/
public ASName getImageColorSpace() {
return imageColorSpace;
}
/**
* Get image compression.
*
* @return ASName
*/
public ASName getImageCompression() {
return imageCompression;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "fileName=" + fileName;
}
public static class Builder {
private final String fileName;
private String imageChecksum = null;
private int method = 0;
private ASName imageColorSpace = null;
private ASName imageCompression = null;
public Builder(final String fileName) {
this.fileName = fileName;
}
public Builder method(final int method) {
this.method = method;
return this;
}
public Builder imageChecksum(final String imageChecksum) {
this.imageChecksum = imageChecksum;
return this;
}
public Builder imageColorSpace(final ASName imageColorSpace) {
this.imageColorSpace = imageColorSpace;
return this;
}
public Builder imageCompression(final ASName imageCompression) {
this.imageCompression = imageCompression;
return this;
}
public DownsamplingTest build() {
return new DownsamplingTest(this);
}
}
}
}
| mit |
github/codeql | java/ql/test/stubs/google-android-9.0.0/android/content/ContentProviderResult.java | 929 | // Generated automatically from android.content.ContentProviderResult for testing purposes
package android.content;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
public class ContentProviderResult implements Parcelable
{
protected ContentProviderResult() {}
public ContentProviderResult(Bundle p0){}
public ContentProviderResult(Parcel p0){}
public ContentProviderResult(Throwable p0){}
public ContentProviderResult(Uri p0){}
public ContentProviderResult(int p0){}
public String toString(){ return null; }
public final Bundle extras = null;
public final Integer count = null;
public final Throwable exception = null;
public final Uri uri = null;
public int describeContents(){ return 0; }
public static Parcelable.Creator<ContentProviderResult> CREATOR = null;
public void writeToParcel(Parcel p0, int p1){}
}
| mit |
nwmotogeek/HackedLights | AndroidClient/app/src/main/java/com/djs/lightStrandClient/IClient_Listener.java | 344 | package com.djs.lightStrandClient;
/**
* Deprecated interface, used by the Wifi code that is being deprecated
*
* Created by David Schmidlin on 7/4/2015.
*/
public interface IClient_Listener
{
/**
* places some message into the adb log
* @param msg The message the user wants to store
*/
void OnLog(String msg);
}
| mit |
cloudbearings/annoMVVM | src/main/java/de/davherrmann/mvvm/annotations/ProvidesState.java | 450 | package de.davherrmann.mvvm.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import de.davherrmann.mvvm.State;
@Documented
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ProvidesState {
Class<? extends State<?>> value();
}
| mit |
wesmaldonado/test-driven-javascript-example-application | public/js-common/jsunit/java/source_core/net/jsunit/utility/FileUtility.java | 658 | package net.jsunit.utility;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
public class FileUtility {
public static void delete(File file) {
if (file.exists())
file.delete();
}
public static void write(File file, String contents) {
try {
if (file.exists())
file.delete();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
out.write(contents.getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| mit |
brucevsked/vskeddemolist | vskeddemos/mavenproject/springmvcmybatismysql/src/main/java/com/vsked/controller/UserController.java | 439 | package com.vsked.controller;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class UserController {
public Logger log = Logger.getLogger(UserController.class);
@GetMapping("index")
public String index(){
System.out.println("get index");
log.info("here is messagea1");
return "index";
}
}
| mit |
kamdjouduplex/BPELviz | src/main/java/bpelviz/Main.java | 665 | package bpelviz;
import java.awt.*;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws BPELVizException {
Cli cli = new Cli(args);
Path bpelFile = cli.getBpelFile();
Path htmlFile = cli.getHtmlFile();
System.out.println("Transforming: " + bpelFile + " --> " + htmlFile);
// main logic
new BPELViz().bpel2html(bpelFile, htmlFile);
// post actions
if (cli.openHtmlInBrowser()) {
try {
Desktop.getDesktop().browse(htmlFile.toUri());
} catch (Exception ignore) {
}
}
}
}
| mit |
MrWooJ/WJLucene-Server | src/com/lucene/CommentNews.java | 3720 | package com.lucene;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
public class CommentNews {
public CommentNews() {
}
public ArrayList <Document> GenerateCommentData(Document document, String newsURL) throws IOException, BiffException {
File file = new File(LuceneConstants.FILE_PATH_COMMENTS);
ArrayList<Document> coreDocumentsArray = new ArrayList<Document>();
Workbook workBook = Workbook.getWorkbook(file);
Sheet sh1 = workBook.getSheet(0);
Cell columns0[] = sh1.getColumn(0);
for (int i = 0; i < columns0.length; i++) {
String value0 = columns0[i].getContents();
if (value0.equalsIgnoreCase(newsURL)) {
Cell columns1[] = sh1.getColumn(1);
Cell columns2[] = sh1.getColumn(2);
Cell columns3[] = sh1.getColumn(3);
Cell columns4[] = sh1.getColumn(4);
Cell columns5[] = sh1.getColumn(5);
Cell columns6[] = sh1.getColumn(6);
Cell columns7[] = sh1.getColumn(7);
Cell columns8[] = sh1.getColumn(8);
Cell columns9[] = sh1.getColumn(9);
String value1 = columns1[i].getContents();
String value2 = columns2[i].getContents();
String value3 = columns3[i].getContents();
String value4 = columns4[i].getContents();
String value5 = columns5[i].getContents();
String value6 = columns6[i].getContents();
String value7 = columns7[i].getContents();
String value8 = columns8[i].getContents();
String value9 = columns9[i].getContents();
Field COMMENT_ID = new Field(LuceneConstants.COMMENT_ID, value1, Field.Store.YES,Field.Index.NOT_ANALYZED,Field.TermVector.NO);
Field COMMENT_PARENTID = new Field(LuceneConstants.COMMENT_PARENTID, value2, Field.Store.YES,Field.Index.NOT_ANALYZED,Field.TermVector.NO);
Field COMMENT_COMMENTER = new Field(LuceneConstants.COMMENT_COMMENTER, value3, Field.Store.YES,Field.Index.ANALYZED,Field.TermVector.WITH_POSITIONS_OFFSETS);
Field COMMENT_LOCATION = new Field(LuceneConstants.COMMENT_LOCATION, value4, Field.Store.YES,Field.Index.ANALYZED,Field.TermVector.WITH_POSITIONS_OFFSETS);
Field COMMENT_DATE = new Field(LuceneConstants.COMMENT_DATE, value5, Field.Store.YES,Field.Index.NOT_ANALYZED,Field.TermVector.NO);
Field COMMENT_LIKECOMMENT = new Field(LuceneConstants.COMMENT_LIKECOMMENT, value6, Field.Store.YES,Field.Index.NOT_ANALYZED,Field.TermVector.NO);
Field COMMENT_DISLIKECOMMENT = new Field(LuceneConstants.COMMENT_DISLIKECOMMENT, value7, Field.Store.YES,Field.Index.NOT_ANALYZED,Field.TermVector.NO);
Field COMMENT_RESPONSECOUNT = new Field(LuceneConstants.COMMENT_RESPONSECOUNT, value8, Field.Store.YES,Field.Index.NOT_ANALYZED,Field.TermVector.NO);
Field COMMENT_BODY = new Field(LuceneConstants.COMMENT_BODY, value9, Field.Store.NO,Field.Index.ANALYZED,Field.TermVector.WITH_POSITIONS_OFFSETS);
Field fileNameField = new Field(LuceneConstants.FILE_NAME,file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED);
Field filePathField = new Field(LuceneConstants.FILE_PATH,file.getCanonicalPath(),Field.Store.YES,Field.Index.NOT_ANALYZED);
document.add(COMMENT_ID);
document.add(COMMENT_PARENTID);
document.add(COMMENT_COMMENTER);
document.add(COMMENT_LOCATION);
document.add(COMMENT_DATE);
document.add(COMMENT_LIKECOMMENT);
document.add(COMMENT_DISLIKECOMMENT);
document.add(COMMENT_RESPONSECOUNT);
document.add(COMMENT_BODY);
document.add(filePathField);
document.add(fileNameField);
coreDocumentsArray.add(document);
}
}
return coreDocumentsArray;
}
}
| mit |
Willie1234/Inforvellor-master | src/test/java/com/njyb/test/zhanghuacai/TestCountryField.java | 3241 | package com.njyb.test.zhanghuacai;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.njyb.gbdbase.dao.datasearch.country.IAllCountrySelectFieldDao;
import com.njyb.gbdbase.model.datasearch.allCountrySelectField.AllCountrySelectFieldModel;
import com.njyb.gbdbase.model.datasearch.common.SqlModel;
public class TestCountryField {
//定义需要参数的值
static ApplicationContext context=null;
String path="config\\core\\applicationContext.xml";;
IAllCountrySelectFieldDao dao=null;
@Test
public void testListCountryField(){
SqlModel model = new SqlModel();
String name = "原产国";
// String name = "产销国";
String country = "玻利维亚进口";
String n = "bolivia_import";
String sql = "select distinct fieldvalue from help_country_select_field where fieldname ='"+name+"' and country = '"+country+"'" ;
model.setSql(sql);
List<AllCountrySelectFieldModel> list = dao.queryAllCountrySelectField(model);
StringBuffer sbValue = new StringBuffer();
for (AllCountrySelectFieldModel allCountrySelectFieldModel : list) {
System.out.println(allCountrySelectFieldModel);
if(allCountrySelectFieldModel != null && !"".equals(allCountrySelectFieldModel))
{
String value = allCountrySelectFieldModel.getFieldValue().replaceAll("&", " ");
System.out.println(value);
sbValue.append(value + "~");
}
}
// String n = "nicaragua_export_origin";
setValueField(n, sbValue.toString());
// util.setValue("fieldName", sbName.toString());
}
//
@Test
public void a(){
String a = "aaaa&sdfd";
System.out.println(a.replaceAll("&", " "));
}
/**
* 设置属性的值 根据指定属性的名称
* @param key
* @param value
*/
public static void setValueField(String key, String value) {
File file = new File("E:\\allCountrySelectField.properties");
Properties p = null;
try {
InputStream in = new BufferedInputStream (new FileInputStream(file));
p = new Properties();
try {
p.load(in);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
p.setProperty(key, value);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("E:\\allCountrySelectField.properties"));
p.store(fos, key);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Before
public void initContext(){
System.out.println("启动类前..");
context=new ClassPathXmlApplicationContext(path);
dao=context.getBean(IAllCountrySelectFieldDao.class);
}
@After
public void destoryContext(){
System.out.println("结束后....spring is great!");
}
}
| mit |
shoma2da/android-youtube-data-api-client | android-youtube-data-api-client/src/androidTest/java/io/github/shoma2da/android_youtube_data_api_client/ApplicationTest.java | 381 | package io.github.shoma2da.android_youtube_data_api_client;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
odavison/scavenger | app/src/main/java/ca/dal/cs/scavenger/UserProfile.java | 339 | package ca.dal.cs.scavenger;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class UserProfile extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
}
}
| mit |