repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
beldenge/CFGReader | src/test/java/com/ciphertool/cfgreader/util/ContextFreeGrammarHelperTest.java | 1576 | /**
* Copyright 2015 George Belden
*
* This file is part of CFGReader.
*
* CFGReader is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* CFGReader 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* CFGReader. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ciphertool.cfgreader.util;
import java.io.File;
import javax.xml.bind.JAXBException;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ciphertool.cfgreader.datastructures.Tree;
import com.ciphertool.cfgreader.generated.ProductionType;
public class ContextFreeGrammarHelperTest {
private static Logger log = LoggerFactory.getLogger(ContextFreeGrammarHelperTest.class);
ContextFreeGrammarHelper cfgHelper;
@Before
public void setUp() throws Exception {
File grammarFile = new File("src/data/xml/EnglishSentenceCFG.xml");
cfgHelper = new ContextFreeGrammarHelper(grammarFile);
}
@Test
public void testGenerateRandomSyntaxTree() throws JAXBException {
Tree<ProductionType> syntaxTree = cfgHelper.generateRandomSyntaxTree();
log.info(syntaxTree.toString());
}
} | gpl-3.0 |
MissFreedom/AutoCode | src/main/java/com/mycompany/autocode/model/vo/JavaVO.java | 1090 | package com.mycompany.autocode.model.vo;
import java.io.Serializable;
/**
* author: JinBingBing
* description:
* time: 2017/2/17 14:07.
*/
public class JavaVO implements Serializable {
private static final long serialVersionUID = 3467569673879692122L;
/** javaId*/
private String JavaId;
/** 用户Id*/
private String userId;
/** java文件名*/
private String className;
/** java文件内容*/
private String classContext;
public String getJavaId() {
return JavaId;
}
public void setJavaId(String javaId) {
JavaId = javaId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getClassContext() {
return classContext;
}
public void setClassContext(String classContext) {
this.classContext = classContext;
}
}
| gpl-3.0 |
Team-2502/RobotCode2018 | src/com/team2502/robot2018/command/autonomous/ingredients/PurePursuitCommand.java | 4875 | package com.team2502.robot2018.command.autonomous.ingredients;
import com.team2502.robot2018.Constants;
import com.team2502.robot2018.Robot;
import com.team2502.robot2018.trajectory.ITankRobotBounds;
import com.team2502.robot2018.trajectory.Lookahead;
import com.team2502.robot2018.trajectory.PurePursuitMovementStrategy;
import com.team2502.robot2018.trajectory.Waypoint;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.joml.ImmutableVector2f;
import java.util.List;
public class PurePursuitCommand extends Command
{
private final ITankRobotBounds tankRobot;
private PurePursuitMovementStrategy purePursuitMovementStrategy;
private List<Waypoint> waypoints;
private Lookahead lookahead;
private float stopDistance;
public PurePursuitCommand(List<Waypoint> waypoints)
{
this(waypoints, Constants.LOOKAHEAD, Constants.STOP_DIST_TOLERANCE_FT);
}
public PurePursuitCommand(List<Waypoint> waypoints, Lookahead lookahead, float stopDistance)
{
this.waypoints = waypoints;
this.lookahead = lookahead;
this.stopDistance = stopDistance;
requires(Robot.DRIVE_TRAIN);
tankRobot = new ITankRobotBounds()
{
/**
* @return The max velocity the right wheels can travel
*/
@Override
public float getV_rMax()
{ return Float.NaN; } // Not used in PurePursuitMovementStrategy
@Override
public float getA_rMax()
{
return Float.NaN;
}
/**
* @return The max velocity the left wheels can travel
*/
@Override
public float getV_lMax()
{ return Float.NaN; }
@Override
public float getA_lMax()
{
return Float.NaN;
}
/**
* @return The min velocity the left wheels can travel
*/
@Override
public float getV_lMin()
{ return Float.NaN; }
@Override
public float getA_lMin()
{
return Float.NaN;
}
/**
* @return The min velocity the right wheels can travel
*/
@Override
public float getV_rMin()
{ return Float.NaN; }
@Override
public float getA_rMin()
{
return Float.NaN;
}
/**
* @return The lateral distance between wheels
*/
@Override
public float getLateralWheelDistance()
{ return Constants.LATERAL_WHEEL_DISTANCE_FT; }
};
// rotLocEstimator = new NavXLocationEstimator();
// transLocEstimator = new EncoderDifferentialDriveLocationEstimator(rotLocEstimator);
//
// sendableNavX = new SendableNavX(() -> MathUtils.rad2Deg(-rotLocEstimator.estimateHeading()), "purePursuitHeading");
}
@Override
protected void initialize()
{
Robot.writeLog("init PP", 80);
purePursuitMovementStrategy = new PurePursuitMovementStrategy(tankRobot, Robot.ROBOT_LOCALIZATION_COMMAND, Robot.ROBOT_LOCALIZATION_COMMAND, Robot.ROBOT_LOCALIZATION_COMMAND, waypoints, lookahead, stopDistance);
SmartDashboard.putBoolean("PPisClose", purePursuitMovementStrategy.isClose());
SmartDashboard.putBoolean("PPisSuccess", purePursuitMovementStrategy.isWithinTolerences());
}
@Override
protected void execute()
{
purePursuitMovementStrategy.update();
ImmutableVector2f usedEstimatedLocation = purePursuitMovementStrategy.getUsedEstimatedLocation();
SmartDashboard.putNumber("purePursuitLocX", usedEstimatedLocation.get(0));
SmartDashboard.putNumber("purePursuitLocY", usedEstimatedLocation.get(1));
ImmutableVector2f wheelVelocities = purePursuitMovementStrategy.getWheelVelocities();
float wheelL = wheelVelocities.get(0);
float wheelR = wheelVelocities.get(1);
SmartDashboard.putNumber("PPwheelL", wheelVelocities.get(0));
SmartDashboard.putNumber("PPwheelR", wheelVelocities.get(1));
Robot.DRIVE_TRAIN.runMotorsVelocity(wheelL, wheelR);
}
@Override
protected boolean isFinished()
{
boolean finishedPath = purePursuitMovementStrategy.isFinishedPath();
if(finishedPath)
{
SmartDashboard.putBoolean("PPisSuccess", purePursuitMovementStrategy.isWithinTolerences());
if(purePursuitMovementStrategy.isWithinTolerences())
{
System.out.println("\n\nSUCCESS!\n\n");
}
Robot.DRIVE_TRAIN.stop();
}
return finishedPath;
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/nd/util/PathMap.java | 5836 | /*******************************************************************************
* Copyright (c) 2015, 2016 Google, Inc and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Stefan Xenos (Google) - Initial implementation
*******************************************************************************/
package org.eclipse.jdt.internal.core.nd.util;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Maps IPath keys onto values.
*/
public class PathMap<T> {
private static class Node<T> {
int depth;
boolean exists;
T value;
Map<String, Node<T>> children;
Node(int depth) {
this.depth = depth;
}
String getSegment(IPath key) {
return key.segment(this.depth);
}
Node<T> createNode(IPath key) {
if (this.depth == key.segmentCount()) {
this.exists = true;
return this;
}
String nextSegment = getSegment(key);
Node<T> next = createChild(nextSegment);
return next.createNode(key);
}
public Node<T> createChild(String nextSegment) {
if (this.children == null) {
this.children = new HashMap<>();
}
Node<T> next = this.children.get(nextSegment);
if (next == null) {
next = new Node<>(this.depth + 1);
this.children.put(nextSegment, next);
}
return next;
}
/**
* Returns this node or one of its descendants whose path is the longest-possible prefix of the given key (or
* equal to it).
*/
public Node<T> getMostSpecificNode(IPath key) {
if (this.depth == key.segmentCount()) {
return this;
}
String nextSegment = getSegment(key);
Node<T> child = getChild(nextSegment);
if (child == null) {
return this;
}
Node<T> result = child.getMostSpecificNode(key);
if (result.exists) {
return result;
} else {
return this;
}
}
Node<T> getChild(String nextSegment) {
if (this.children == null) {
return null;
}
return this.children.get(nextSegment);
}
public void addAllKeys(Set<IPath> result, IPath parent) {
if (this.exists) {
result.add(parent);
}
if (this.children == null) {
return;
}
for (Entry<String, Node<T>> next : this.children.entrySet()) {
String key = next.getKey();
IPath nextPath = buildChildPath(parent, key);
next.getValue().addAllKeys(result, nextPath);
}
}
IPath buildChildPath(IPath parent, String key) {
IPath nextPath = parent.append(key);
return nextPath;
}
public void toString(StringBuilder builder, IPath parentPath) {
if (this.exists) {
builder.append("["); //$NON-NLS-1$
builder.append(parentPath);
builder.append("] = "); //$NON-NLS-1$
builder.append(this.value);
builder.append("\n"); //$NON-NLS-1$
}
if (this.children != null) {
for (Entry<String, Node<T>> next : this.children.entrySet()) {
String key = next.getKey();
IPath nextPath = buildChildPath(parentPath, key);
next.getValue().toString(builder, nextPath);
}
}
}
}
private static class DeviceNode<T> extends Node<T> {
Node<T> noDevice = new Node<>(0);
DeviceNode() {
super(-1);
}
@Override
String getSegment(IPath key) {
return key.getDevice();
}
@Override
public Node<T> createChild(String nextSegment) {
if (nextSegment == null) {
return this.noDevice;
}
return super.createChild(nextSegment);
}
@Override
Node<T> getChild(String nextSegment) {
if (nextSegment == null) {
return this.noDevice;
}
return super.getChild(nextSegment);
}
@Override
IPath buildChildPath(IPath parent, String key) {
IPath nextPath = Path.EMPTY.append(parent);
nextPath.setDevice(key);
return nextPath;
}
@Override
public void toString(StringBuilder builder, IPath parentPath) {
this.noDevice.toString(builder, parentPath);
super.toString(builder,parentPath);
}
}
private Node<T> root = new DeviceNode<T>();
/**
* Inserts the given key into the map.
*/
public T put(IPath key, T value) {
Node<T> node = this.root.createNode(key);
T result = node.value;
node.value = value;
return result;
}
/**
* Returns the value associated with the given key
*/
public T get(IPath key) {
Node<T> node = this.root.getMostSpecificNode(key);
if (!node.exists || node.depth < key.segmentCount()) {
return null;
}
return node.value;
}
/**
* Returns the value associated with the longest prefix of the given key
* that can be found in the map.
*/
public T getMostSpecific(IPath key) {
Node<T> node = this.root.getMostSpecificNode(key);
if (!node.exists) {
return null;
}
return node.value;
}
/**
* Returns true iff any key in this map is a prefix of the given path.
*/
public boolean containsPrefixOf(IPath path) {
Node<T> node = this.root.getMostSpecificNode(path);
return node.exists;
}
public Set<IPath> keySet() {
Set<IPath> result = new HashSet<>();
this.root.addAllKeys(result, Path.EMPTY);
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
this.root.toString(builder, Path.EMPTY);
return builder.toString();
}
/**
* Returns true iff this map contains any key that starts with the given prefix.
*/
public boolean containsKeyStartingWith(IPath next) {
Node<T> node = this.root.getMostSpecificNode(next);
return node.depth == next.segmentCount();
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java | 930 | package org.baeldung.voter;
import java.time.LocalDateTime;
import java.util.Collection;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
public class MinuteBasedVoter implements AccessDecisionVoter {
@Override
public boolean supports(ConfigAttribute attribute) {
return true;
}
@Override
public boolean supports(Class clazz) {
return true;
}
@Override
public int vote(Authentication authentication, Object object, Collection collection) {
return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0).findAny().map(s -> ACCESS_DENIED).orElseGet(() -> ACCESS_ABSTAIN);
}
}
| gpl-3.0 |
waikato-datamining/adams-base | adams-excel/src/test/java/adams/data/io/input/ExcelSpreadSheetReaderTest.java | 3067 | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ExcelSpreadSheetReaderTest.java
* Copyright (C) 2010-2016 University of Waikato, Hamilton, New Zealand
*/
package adams.data.io.input;
import junit.framework.Test;
import junit.framework.TestSuite;
import adams.env.Environment;
/**
* Tests the adams.core.io.ExcelSpreadSheetReader class. Run from commandline with: <br><br>
* java adams.core.io.ExcelSpreadSheetReader
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class ExcelSpreadSheetReaderTest
extends AbstractSpreadSheetReaderTestCase {
/**
* Initializes the test.
*
* @param name the name of the test
*/
public ExcelSpreadSheetReaderTest(String name) {
super(name);
}
/**
* Returns the filenames (without path) of the input data files to use
* in the regression test.
*
* @return the filenames
*/
@Override
protected String[] getRegressionInputFiles() {
return new String[]{
"sample.xls",
"sample2.xlsx",
"sample2.xlsx",
"sample2.xlsx",
"sample2.xlsx",
"sample2.xlsx",
};
}
/**
* Returns the setups to use in the regression test.
*
* @return the setups
*/
@Override
protected SpreadSheetReader[] getRegressionSetups() {
ExcelSpreadSheetReader[] result;
result = new ExcelSpreadSheetReader[6];
result[0] = new ExcelSpreadSheetReader();
result[1] = new ExcelSpreadSheetReader();
result[2] = new ExcelSpreadSheetReader();
result[2].setNoHeader(true);
result[3] = new ExcelSpreadSheetReader();
result[3].setNoHeader(true);
result[3].setCustomColumnHeaders("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54");
result[4] = new ExcelSpreadSheetReader();
result[4].setFirstRow(3);
result[4].setNumRows(2);
result[5] = new ExcelSpreadSheetReader();
result[5].setNoHeader(true);
result[5].setFirstRow(3);
result[5].setNumRows(2);
return result;
}
/**
* Returns a test suite.
*
* @return the test suite
*/
public static Test suite() {
return new TestSuite(ExcelSpreadSheetReaderTest.class);
}
/**
* Runs the test from commandline.
*
* @param args ignored
*/
public static void main(String[] args) {
Environment.setEnvironmentClass(Environment.class);
runTest(suite());
}
}
| gpl-3.0 |
icgc-dcc/SONG | song-server/src/main/java/bio/overture/song/server/service/id/RestClient.java | 4019 | /*
* Copyright (c) 2019. Ontario Institute for Cancer Research
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package bio.overture.song.server.service.id;
import static bio.overture.song.core.exceptions.ServerErrors.REST_CLIENT_UNEXPECTED_RESPONSE;
import static bio.overture.song.core.exceptions.ServerException.checkServer;
import static java.util.Objects.isNull;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import java.util.Optional;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.RetryOperations;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestOperations;
/** Simple REST client that executes HTTP GET requests for a specified url */
@RequiredArgsConstructor
public class RestClient {
/** Dependencies */
@NonNull private final RestOperations rest;
@NonNull private final RetryOperations retry;
public Optional<String> getString(String url) {
return getObject(url, String.class);
}
/**
* Executes a HTTP GET request for a url and returns an entity if it exists, otherwise returns an
* empty Optional
*/
public <T> Optional<T> getObject(@NonNull String url, @NonNull Class<T> responseType) {
try {
val response = get(url, responseType);
checkServer(
!isNull(response),
getClass(),
REST_CLIENT_UNEXPECTED_RESPONSE,
"The request 'GET %s' returned a NULL response, "
+ "but was expecting a 200 status code of type '%s'",
url,
responseType.getSimpleName());
checkServer(
!isNull(response.getBody()),
getClass(),
REST_CLIENT_UNEXPECTED_RESPONSE,
"The request 'GET %s' returned a NULL body, "
+ "but was expecting a 200 status code of type '%s'",
url,
responseType.getSimpleName());
return Optional.of(response.getBody());
} catch (HttpStatusCodeException e) {
if (NOT_FOUND.equals(e.getStatusCode())) {
return Optional.empty();
}
throw e;
}
}
/**
* Indicates if a resource exists. If the response status code is not an error, the result is
* true. If the response code is 404 (NOT_FOUND) the result is false. Any other response code or
* exception will throw an exception
*/
public boolean isFound(@NonNull String url) {
try {
// Any non-error response status code will result in True.
get(url, String.class);
return true;
} catch (HttpStatusCodeException e) {
// Any notfound error status code will return false, otherwise propagate the error
if (NOT_FOUND.equals(e.getStatusCode())) {
return false;
}
throw e;
}
}
/**
* Executes a HTTP GET request for the url and deserializes the response to the type specified by
* {@param responseType}
*/
public <T> ResponseEntity<T> get(String url, Class<T> responseType) {
return retry.execute(
retryContext -> {
val httpEntity = new HttpEntity<>(new HttpHeaders());
return rest.exchange(url, HttpMethod.GET, httpEntity, responseType);
});
}
}
| gpl-3.0 |
gboxsw/miniac | main/src/main/java/com/gboxsw/miniac/Devices.java | 1706 | package com.gboxsw.miniac;
/**
* The collection of device instances. The class simplifies management of device
* instances.
*/
public class Devices {
/**
* Internal register of devices.
*/
private static final InstanceRegister<Device> instances = new InstanceRegister<>(true);
/**
* Private constructor (no instances of the class are allowed).
*/
private Devices() {
}
/**
* Register instance of a single-instance device.
*
* @param device
* the device instance.
*/
public static void register(Device device) {
instances.register(device);
}
/**
* Register instance of a multi-instance device.
*
* @param device
* the device instance.
* @param id
* the identifier of the instance.
*/
public static void register(Device device, String id) {
instances.register(device, id);
}
/**
* Returns the registered instance of a single-instance module.
*
* @param deviceClass
* the class of the device.
* @param <T>
* the class of the device.
* @return the registered instance.
*/
public static <T extends Device> T getInstance(Class<T> deviceClass) {
return instances.get(deviceClass);
}
/**
* Returns the registered instance of a multi-instance device.
*
* @param deviceClass
* the class of the device.
* @param id
* the identifier of the instance.
* @param <T>
* the class of the device.
* @return the registered instance.
*/
public static <T extends Device> T getInstance(Class<T> deviceClass, String id) {
return instances.get(deviceClass, id);
}
}
| gpl-3.0 |
zhoukiller/shop | shop/src/main/java/com/it/shop/model/Product.java | 2342 | package com.it.shop.model;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
/**
* Created by 周宏 on 2017/2/2.
*/
@Entity
public class Product implements Serializable{
private Integer id;
private String name;
private BigDecimal price;
private String pic;
private String remark;
private String xremark;
private Timestamp date;
private Boolean commend;
private Boolean open;
private Category category;
@Id
@Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "price")
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
@Basic
@Column(name = "pic")
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
@Basic
@Column(name = "remark")
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Basic
@Column(name = "xremark")
public String getXremark() {
return xremark;
}
public void setXremark(String xremark) {
this.xremark = xremark;
}
@Basic
@Column(name = "date")
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
@Basic
@Column(name = "commend")
public Boolean getCommend() {
return commend;
}
public void setCommend(Boolean commend) {
this.commend = commend;
}
@Basic
@Column(name = "open")
public Boolean getOpen() {
return open;
}
public void setOpen(Boolean open) {
this.open = open;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
| gpl-3.0 |
wrk-fmd/CoCeSo | geocode/geocode-impl/src/main/java/at/wrk/geocode/impl/ChainedStreetnameAutocompleteSupplier.java | 732 | package at.wrk.geocode.impl;
import at.wrk.geocode.autocomplete.AutocompleteSupplier;
import at.wrk.geocode.autocomplete.StreetnameAutocompleteSupplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
@Component("ChainedStreetnameAutocomplete")
public class ChainedStreetnameAutocompleteSupplier extends ChainedAutocompleteSupplier {
@Autowired(required = false)
public ChainedStreetnameAutocompleteSupplier(final List<StreetnameAutocompleteSupplier<?>> autocomplete) {
super(autocomplete.stream().map(supplier -> (AutocompleteSupplier<?>) supplier).collect(Collectors.toList()));
}
}
| gpl-3.0 |
meefik/linuxdeploy | app/src/main/java/ru/meefik/linuxdeploy/receiver/PowerReceiver.java | 612 | package ru.meefik.linuxdeploy.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import ru.meefik.linuxdeploy.EnvUtils;
public class PowerReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
EnvUtils.execService(context, "stop", "core/power");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
EnvUtils.execService(context, "start", "core/power");
}
}
}
| gpl-3.0 |
AntonioNP/ajax-yield | src/main/java/net/daw/operaciones/EntregaRemove.java | 1594 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.daw.operaciones;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.daw.bean.EntregaBean;
import net.daw.dao.EntregaDao;
import net.daw.helper.Conexion;
/**
*
* @author al037805
*/
public class EntregaRemove implements GenericOperation {
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
EntregaDao oEntregaDAO = new EntregaDao(Conexion.getConection());
EntregaBean oEntrega = new EntregaBean();
oEntrega.setId(Integer.parseInt(request.getParameter("id")));
Map<String, String> data = new HashMap<>();
if (oEntrega != null) {
oEntregaDAO.remove(oEntrega);
data.put("status", "200");
data.put("message", "se ha eliminado el registro con id=" + oEntrega.getId());
} else {
data.put("status", "error");
data.put("message", "error");
}
Gson gson = new Gson();
String resultado = gson.toJson(data);
return resultado;
} catch (Exception e) {
throw new ServletException("EntregaRemoveJson: View Error: " + e.getMessage());
}
}
}
| gpl-3.0 |
optimizationBenchmarking/utils-base | src/main/java/org/optimizationBenchmarking/utils/config/package-info.java | 145 | /**
* The classes for loading and accessing the configuration of our
* applications.
*/
package org.optimizationBenchmarking.utils.config; | gpl-3.0 |
limelime/FilesHub | src/net/xngo/fileshub/test/db/TrashTest.java | 11629 | package net.xngo.fileshub.test.db;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import net.xngo.fileshub.Main;
import net.xngo.fileshub.Utils;
import net.xngo.fileshub.db.Connection;
import net.xngo.fileshub.db.Manager;
import net.xngo.fileshub.db.Trash;
import net.xngo.fileshub.struct.Document;
import net.xngo.fileshub.test.helpers.Data;
import net.xngo.utils.java.math.Random;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TrashTest
{
private static final boolean DEBUG = true;
private final int randomInt = java.lang.Math.abs(Random.Int())+1; // Must be positive.
private AtomicInteger atomicInt = new AtomicInteger(randomInt); // Must set initial value to more than 0. Duid can't be 0.
private Trash trash = new Trash();
@BeforeClass
public void DatabaseCreation()
{
// Make sure that the database file is created.
Manager manager = new Manager();
manager.createDbStructure();
}
@Test(description="Search by filename without wildcard: Test SQL query.")
public void searchDocsByFilenameNotWildcardQuery()
{
//*** Prepare data: Add unique file in Trash table.
File uniqueFile = Data.createTempFile("searchDocsByFilenameNotWildcard");
Document trashDoc = new Document(uniqueFile);
trashDoc.hash = Utils.getHash(uniqueFile);
trashDoc.uid = atomicInt.get(); // Fake duid.
this.trash.addDoc(trashDoc);
//*** Main test: Search by filename without wildcard
this.trash.searchDocsByFilename(uniqueFile.getName());
//*** Validations: Check the sql query has equal sign.
Connection connection = Main.connection;
String expectedSQLquery = String.format("SELECT duid, canonical_path, filename, last_modified, size, hash, comment FROM Trash WHERE filename = ? : %s", uniqueFile.getName());
assertEquals(connection.getQueryString(), expectedSQLquery);
//*** Clean up.
uniqueFile.delete();
}
@Test(description="Search by filename with wildcard: Test SQL query.")
public void searchDocsByFilenameWildcardQuery()
{
//*** Prepare data: Add unique file in Trash table.
File uniqueFile = Data.createTempFile("searchDocsByFilenameWildcardQuery");
Document trashDoc = new Document(uniqueFile);
trashDoc.hash = Utils.getHash(uniqueFile);
trashDoc.uid = atomicInt.get(); // Fake duid.
this.trash.addDoc(trashDoc);
//*** Main test: Search by filename with wildcard
final String filenameWildcard = uniqueFile.getName()+"*";
final String expectedFilenameWildcard = uniqueFile.getName()+"%";
this.trash.searchDocsByFilename(filenameWildcard);
//*** Validations: Check the sql query has the LIKE
Connection connection = Main.connection;
String expectedSQLquery = String.format("SELECT duid, canonical_path, filename, last_modified, size, hash, comment FROM Trash WHERE filename like ? : %s", expectedFilenameWildcard);
assertEquals(connection.getQueryString(), expectedSQLquery);
//*** Clean up.
uniqueFile.delete();
}
@Test(description="Search by filename with multiple adjacent wildcards: Test SQL query.")
public void searchDocsByFilenameAdjacentWildcardQuery()
{
//*** Prepare data: Add unique file in Trash table.
File uniqueFile = Data.createTempFile("searchDocsByFilenameAdjacentWildcardQuery");
Document trashDoc = new Document(uniqueFile);
trashDoc.hash = Utils.getHash(uniqueFile);
trashDoc.uid = atomicInt.get(); // Fake duid.
this.trash.addDoc(trashDoc);
//*** Main test: Search by filename with wildcard
final String filenameWildcard = uniqueFile.getName()+"**";
final String expectedFilenameWildcard = uniqueFile.getName()+"%";
this.trash.searchDocsByFilename(filenameWildcard);
//*** Validations: Check the sql query has not adjacent %.
Connection connection = Main.connection;
String expectedSQLquery = String.format("SELECT duid, canonical_path, filename, last_modified, size, hash, comment FROM Trash WHERE filename like ? : %s", expectedFilenameWildcard);
assertEquals(connection.getQueryString(), expectedSQLquery);
//*** Clean up.
uniqueFile.delete();
}
@Test(description="Search by exact filename.")
public void searchDocsByFilenameExact()
{
//*** Prepare data: Add unique file in Trash table.
File uniqueFile = Data.createTempFile("searchDocsByFilenameExact");
Document trashDoc = new Document(uniqueFile);
trashDoc.hash = Utils.getHash(uniqueFile);
trashDoc.uid = atomicInt.get(); // Fake duid.
this.trash.addDoc(trashDoc);
//*** Main test: Search by exact filename.
List<Document> searchResults = this.trash.searchDocsByFilename(uniqueFile.getName());
//*** Validations: Filename should be found.
assertEquals(searchResults.size(), 1, String.format("%s should be found in Trash.", uniqueFile.getName()));
assertEquals(searchResults.get(0).filename, uniqueFile.getName());
//*** Clean up.
uniqueFile.delete();
}
@Test(description="Search by filename using wildcard.")
public void searchDocsByFilenameUsingWildcard()
{
if(this.DEBUG)
{
try
{
Main.connection.setAutoCommit(true);
}
catch(SQLException ex) { ex.printStackTrace(); }
}
//*** Prepare data: Add multiple files in Trash table.
ArrayList<File> files = new ArrayList<File>();
final String filenamePattern = "searchDocsByFilenameUsingWildcard_TrashTable_";
for(int i=0; i<7; i++ )
{
File uniqueFile = Data.createTempFile(filenamePattern+i);
Document trashDoc = new Document(uniqueFile);
trashDoc.hash = Utils.getHash(uniqueFile);
trashDoc.uid = atomicInt.get(); // Fake duid.
this.trash.addDoc(trashDoc);
}
//*** Main test: Search by exact filename.
List<Document> searchResults = this.trash.searchDocsByFilename("*ByFilename*UsingWildcard*TrashTable");
//*** Validations: Filename should be found.
assertEquals(searchResults.size(), files.size(), "Number of files found in Trash table not expected.");
for(int i=0; i<files.size(); i++)
{
assertNotEquals(searchResults.get(i).filename.indexOf(filenamePattern), -1, String.format("Pattern '%s' not found in %s.", filenamePattern, searchResults.get(i).filename));
}
//*** Clean up.
for(File file: files)
{
file.delete();
}
}
@Test(description="Add simple document in Trash table.")
public void addDocSimple()
{
//*** Prepare data: Add unique file in Trash table.
File uniqueFile = Data.createTempFile("addDocSimple");
//*** Main test: Add simple doc in Trash table.
Document trashDoc = new Document(uniqueFile);
trashDoc.hash = Utils.getHash(uniqueFile);
trashDoc.uid = atomicInt.get(); // Fake duid.
this.trash.addDoc(trashDoc);
//*** Validation: Check all fields of document are correct.
Document actualTrashDoc = this.trash.getDocByFilename(uniqueFile.getName());
assertEquals(actualTrashDoc, trashDoc, String.format("\n%s\n"
+ "%s", actualTrashDoc.getInfo("Actual"), trashDoc.getInfo("Expected")));
//*** Clean up
uniqueFile.delete();
}
@Test(description="Add empty file in Trash table.")
public void addDocEmptyFileSize()
{
//*** Prepare data: Create a unique file in Trash table with empty content.
File uniqueFile = Data.createTempFile("addDocEmptyFileSize", null, "");
//*** Main test: Add file with empty content in Shelf table.
Document trashDoc = new Document(uniqueFile);
trashDoc.hash = Utils.getHash(uniqueFile);
trashDoc.uid = atomicInt.get(); // Fake duid.
this.trash.addDoc(trashDoc);
//*** Validation: Check all fields of document are correct.
Document actualTrashDoc = this.trash.getDocByFilename(uniqueFile.getName());
assertEquals(actualTrashDoc, trashDoc, String.format("\n%s\n"
+ "%s", actualTrashDoc.getInfo("Actual"), trashDoc.getInfo("Expected")));
//*** Clean up
uniqueFile.delete();
}
@Test(description="Test saveSize() with positive size.")
public void saveSizeWithPositiveSize()
{
//*** Prepare data: Add unique file in Shelf table.
File uniqueFile = Data.createTempFile("saveSizeWithPositiveSize");
//*** Main test: Add simple doc in Shelf table.
Document trashDoc = new Document(uniqueFile);
trashDoc.hash = Utils.getHash(uniqueFile);
trashDoc.uid = atomicInt.get(); // Fake duid.
this.trash.addDoc(trashDoc);
//*** Validation: Check specified size is saved.
final int expectedSize = 1;
this.trash.saveSize(trashDoc.hash, expectedSize);
Document actualTrashDoc = this.trash.getDocByFilename(uniqueFile.getName());
assertEquals(actualTrashDoc.size, expectedSize, "Trash.size doesn't match.");
//*** Clean up
uniqueFile.delete();
}
@Test(description="Test saveSize() with zero.")
public void saveSizeWithZero()
{
//*** Prepare data: Add unique file in Shelf table.
File uniqueFile = Data.createTempFile("saveSizeWithZero");
//*** Main test: Add simple doc in Shelf table.
Document trashDoc = new Document(uniqueFile);
trashDoc.hash = Utils.getHash(uniqueFile);
trashDoc.uid = atomicInt.get(); // Fake duid.
this.trash.addDoc(trashDoc);
//*** Validation: Check zero size is saved.
final int expectedSize = 0;
this.trash.saveSize(trashDoc.hash, expectedSize);
Document actualTrashDoc = this.trash.getDocByFilename(uniqueFile.getName());
assertEquals(actualTrashDoc.size, expectedSize, "Trash.size doesn't match.");
//*** Clean up
uniqueFile.delete();
}
@Test(description="Test saveSize() with negative size.", expectedExceptions={RuntimeException.class})
public void saveSizeWithNegativeSize()
{
//*** Prepare data: Add unique file in Shelf table.
File uniqueFile = Data.createTempFile("saveSizeWithNegativeSize");
try
{
//*** Main test: Add simple doc in Shelf table.
Document trashDoc = new Document(uniqueFile);
trashDoc.hash = Utils.getHash(uniqueFile);
trashDoc.uid = atomicInt.get(); // Fake duid.
this.trash.addDoc(trashDoc);
//*** Validation: Check exception is thrown because size is negative.
final int expectedSize = -1;
this.trash.saveSize(trashDoc.hash, expectedSize);
}
finally
{
//*** Clean up
uniqueFile.delete();
}
}
@Test(description="Test getDocsWithMissingFileSize() sql query.")
public void getDocsWithMissingFileSizeQuery()
{
this.trash.getDocsWithMissingFileSize();
String actualQuery = Main.connection.getQueryString();
System.out.println(actualQuery);
String expectedQuery = "SELECT duid, canonical_path, filename, last_modified, size, hash, comment FROM Trash WHERE size < ? : 1";
assertEquals(actualQuery, expectedQuery);
}
}
| gpl-3.0 |
sprax/java | wordcounts/HashCounterProfile.java | 4374 |
package sprax.wordcounts;
import java.util.stream.Stream;
/**
* Profile for a speaker or writer as collected from their sentences.
* Represents word-tuples as hashes, which saves space but loses a little accuracy.
*/
public class HashCounterProfile extends CounterProfile<Integer> {
private MapTupleCounter<Integer> hashWordCounts = new MapTupleCounter<>();
private MapTupleCounter<Integer> hashPairCounts = new MapTupleCounter<>();
private MapTupleCounter<Integer> hashTrebCounts = new MapTupleCounter<>();
/** Non-public default constructor to be used by a class factory */
HashCounterProfile() {}
/** Initializing constructor (1 of 2): from text file. */
public HashCounterProfile(final String corpusFileSpec) {
addCorpus(corpusFileSpec);
}
/** Initializing constructor (2 of 2): from sentence stream */
public HashCounterProfile(Stream<String> sentences) {
addSentences(sentences);
}
@Override
public int getWordPresence(String word) {
int wordHash = word.hashCode();
return hashWordCounts.getCount(wordHash);
}
@Override
public int getPairPresence(String wordA, String wordB) {
int hashA = wordA.hashCode();
int hashB = wordB.hashCode();
int hashAB = combineHashes(hashA, hashB);
return hashPairCounts.getCount(hashAB);
}
@Override
public int getTriadPresence(String wordA, String wordB, String wordC) {
int hashA = wordA.hashCode();
int hashB = wordB.hashCode();
int hashC = wordC.hashCode();
int hashAB = combineHashes(hashA, hashB);
int hashABC = combineHashes(hashAB, hashC);
return hashTrebCounts.getCount(hashABC);
}
@Override
public MapTupleCounter<Integer> getWordCounts() {
return hashWordCounts;
}
@Override
public MapTupleCounter<Integer> getPairCounts() {
return hashPairCounts;
}
@Override
public MapTupleCounter<Integer> getTrebCounts() {
return hashTrebCounts;
}
@Override
protected void templateAddWordsAndPairs(final String sentence)
{
String words[] = ProfileUtil.parseStringToWords(sentence);
String wordOld = null;
int hashOld = 0, hashNew = 0;
for (String wordNew : words) {
addWord(wordNew);
hashNew = wordNew.hashCode();
if (wordOld != null) {
addHashPair(hashPairCounts, hashOld, hashNew);
}
wordOld = wordNew;
hashOld = hashNew;
}
}
@Override
protected void templateAddWordsPairsAndTriads(final String sentence)
{
String words[] = ProfileUtil.parseStringToWords(sentence);
String wordA = null, wordB = null;
int hashB = 0, hashAB = 0;
for (String wordC : words) {
addWord(wordC);
int hashC = wordC.hashCode();
if (wordA != null) {
addHashPair(hashTrebCounts, hashAB, hashC);
hashAB = addHashPair(hashPairCounts, hashB, hashC);
} else if (wordB != null) {
hashAB = addHashPair(hashPairCounts, hashB, hashC);
}
wordA = wordB;
wordB = wordC;
hashB = hashC;
}
}
@Override
protected void templateAddWord(final String word) {
hashWordCounts.addCount(word.hashCode());
}
static int addHashPair(MapTupleCounter<Integer> hashCounts, int firstHash, int secondHash) {
int combinedHash = combineHashes(firstHash, secondHash);
hashCounts.addCount(combinedHash);
return combinedHash;
}
/**
* @param hashA
* @param hashB
* @return
*/
static int combineHashes(int hashA, int hashB) {
return hashA * HASH_COMBO_FACTOR + hashB;
}
public static void unit_test()
{
String testName = HashCounterProfile.class.getName() + ".unit_test";
System.out.println(testName + " BEGIN");
final String textFilePath = ProfileUtil.getTextFilePath("Melville_MobyDick.txt");
HashCounterProfile sp = new HashCounterProfile(textFilePath);
sp.showCounts(sp.getClass().getSimpleName());
System.out.println(testName + " END");
}
public static void main(String[] args) {
unit_test();
}
}
| gpl-3.0 |
iterate-ch/cyberduck | core/src/main/java/ch/cyberduck/core/worker/RetryTransferCallable.java | 1202 | package ch.cyberduck.core.worker;
/*
* Copyright (c) 2002-2016 iterate GmbH. All rights reserved.
* https://cyberduck.io/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*/
import ch.cyberduck.core.Host;
import ch.cyberduck.core.preferences.PreferencesFactory;
import ch.cyberduck.core.threading.AbstractRetryCallable;
import ch.cyberduck.core.transfer.TransferStatus;
public abstract class RetryTransferCallable extends AbstractRetryCallable<TransferStatus>
implements TransferWorker.TransferCallable {
public RetryTransferCallable(final Host host) {
super(host, PreferencesFactory.get().getInteger("transfer.connection.retry"),
PreferencesFactory.get().getInteger("transfer.connection.retry.delay"));
}
}
| gpl-3.0 |
HongRQ/springCloud-test | cloud-config-server/src/main/java/cloud/test/server/ConfigServerApplication.java | 434 | package cloud.test.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication
{
public static void main( String[] args ){
SpringApplication.run(ConfigServerApplication.class, args);
}
}
| gpl-3.0 |
dewtx29/dewdd_minecraft_plugins | new/minecraft_private/src/main/java/dewtx29/mi/private_sign/Main.java | 628 |
package dewtx29.mi.private_sign;
import java.util.logging.Logger;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
Logger log;
DigEventListener2 ax = new DigEventListener2();
@Override
public void onDisable() {
getServer().getPluginManager().disablePlugin(this);
dewtx29.mi.dprint.r.printAll("ptdew&dewdd : unloaded dewdd private");
}
@Override
public void onEnable() {
log = this.getLogger();
ax.ac = this;
getServer().getPluginManager().registerEvents(ax, this);
dewtx29.mi.dprint.r.printAll("ptdew&dewdd : loaded dewdd private");
}
}
| gpl-3.0 |
mbshopM/openconcerto | Modules/Module Project/src/org/openconcerto/modules/project/Module.java | 24842 | package org.openconcerto.modules.project;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import org.openconcerto.erp.action.CreateFrameAbstractAction;
import org.openconcerto.erp.config.MainFrame;
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.erp.core.sales.invoice.ui.SaisieVenteFactureItemTable;
import org.openconcerto.erp.core.sales.order.ui.CommandeClientItemTable;
import org.openconcerto.erp.core.sales.quote.component.DevisSQLComponent;
import org.openconcerto.erp.core.sales.quote.element.DevisSQLElement;
import org.openconcerto.erp.core.sales.quote.element.EtatDevisSQLElement;
import org.openconcerto.erp.core.sales.quote.report.DevisXmlSheet;
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProvider;
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProviderManager;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.erp.modules.AbstractModule;
import org.openconcerto.erp.modules.AlterTableRestricted;
import org.openconcerto.erp.modules.ComponentsContext;
import org.openconcerto.erp.modules.DBContext;
import org.openconcerto.erp.modules.MenuContext;
import org.openconcerto.erp.modules.ModuleFactory;
import org.openconcerto.modules.project.element.ProjectSQLElement;
import org.openconcerto.modules.project.element.ProjectStateSQLElement;
import org.openconcerto.modules.project.element.ProjectTypeSQLElement;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.utils.SQLCreateTable;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.IListFrame;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.column.ColumnFooterRenderer;
import org.openconcerto.sql.view.column.ColumnPanel;
import org.openconcerto.sql.view.column.ColumnPanelFetcher;
import org.openconcerto.sql.view.column.ColumnRowRenderer;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.cc.IClosure;
import org.openconcerto.utils.cc.ITransformer;
import org.openconcerto.utils.i18n.TranslationManager;
public final class Module extends AbstractModule {
public static final String PROJECT_TABLENAME = "AFFAIRE";
private List<String> listTableAffaire = Arrays.asList("SAISIE_VENTE_FACTURE", "AVOIR_CLIENT", "BON_DE_LIVRAISON", "COMMANDE_CLIENT", "DEVIS", "COMMANDE", "SAISIE_ACHAT", "AVOIR_FOURNISSEUR");
public Module(ModuleFactory f) throws IOException {
super(f);
}
@Override
protected void install(DBContext ctxt) {
super.install(ctxt);
if (ctxt.getLastInstalledVersion() == null) {
if (ctxt.getRoot().getTable(PROJECT_TABLENAME) == null) {
final SQLCreateTable createTableEtatAff = ctxt.getCreateTable("ETAT_AFFAIRE");
createTableEtatAff.addVarCharColumn("NOM", 128);
final SQLCreateTable createTableType = ctxt.getCreateTable("TYPE_AFFAIRE");
createTableType.addVarCharColumn("NOM", 256);
// AFFAIRE
final SQLCreateTable createTable = ctxt.getCreateTable(PROJECT_TABLENAME);
createTable.addVarCharColumn("NUMERO", 256);
createTable.addVarCharColumn("NOM", 1024);
createTable.addVarCharColumn("INFOS", 1024);
createTable.addForeignColumn("ID_CLIENT", ctxt.getRoot().getTable("CLIENT"));
createTable.addForeignColumn("ID_DEVIS", ctxt.getRoot().getTable("DEVIS"));
createTable.addColumn("DATE", "date");
createTable.addForeignColumn("ID_COMMERCIAL", ctxt.getRoot().getTable("COMMERCIAL"));
createTable.addForeignColumn("ID_ETAT_AFFAIRE", createTableEtatAff);
createTable.addForeignColumn("ID_TYPE_AFFAIRE", createTableType);
for (String table : this.listTableAffaire) {
SQLTable tableDevis = ctxt.getRoot().getTable(table);
if (!tableDevis.getFieldsName().contains("ID_AFFAIRE")) {
AlterTableRestricted alter = ctxt.getAlterTable(table);
alter.addForeignColumn("ID_AFFAIRE", createTable);
}
}
ctxt.manipulateData(new IClosure<DBRoot>() {
@Override
public void executeChecked(DBRoot input) {
// Undefined Affaire
SQLTable tableAff = input.getTable(PROJECT_TABLENAME);
SQLRowValues rowVals = new SQLRowValues(tableAff);
try {
rowVals.insert();
} catch (SQLException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
// Etat Affaire
SQLTable tableTypeAffaire = input.getTable("TYPE_AFFAIRE");
rowVals = new SQLRowValues(tableTypeAffaire);
try {
rowVals.put("NOM", "Indéfini");
rowVals.insert();
} catch (SQLException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
// Etat Affaire
SQLTable tableEtatAffaire = input.getTable("ETAT_AFFAIRE");
rowVals = new SQLRowValues(tableEtatAffaire);
try {
rowVals.put("NOM", "Indéfini");
rowVals.insert();
rowVals.clear();
rowVals.put("NOM", "A traiter");
rowVals.insert();
rowVals.clear();
rowVals.put("NOM", "En cours");
rowVals.insert();
rowVals.clear();
rowVals.put("NOM", "Traitement terminé");
rowVals.insert();
rowVals.clear();
rowVals.put("NOM", "A facturer");
rowVals.insert();
rowVals.clear();
rowVals.put("NOM", "Dossier clos");
rowVals.insert();
} catch (SQLException exn) {
exn.printStackTrace();
}
}
});
}
}
}
@Override
protected void setupElements(final SQLElementDirectory dir) {
super.setupElements(dir);
TranslationManager.getInstance().addTranslationStreamFromClass(this.getClass());
dir.addSQLElement(ProjectSQLElement.class);
dir.addSQLElement(ProjectStateSQLElement.class);
dir.addSQLElement(ProjectTypeSQLElement.class);
final SQLElement element = dir.getElement("DEVIS");
DevisSQLElement eltDevis = dir.getElement(DevisSQLElement.class);
eltDevis.getRowActions().clear();
eltDevis.addListColumn(new BaseSQLTableModelColumn("Temps Total", Double.class) {
SQLTable tableDevisElt = Configuration.getInstance().getDirectory().getElement("DEVIS_ELEMENT").getTable();
@Override
protected Object show_(SQLRowAccessor r) {
Collection<? extends SQLRowAccessor> rows = r.getReferentRows(tableDevisElt);
double time = 0;
for (SQLRowAccessor sqlRowAccessor : rows) {
time += OrderColumnRowRenderer.getHours(sqlRowAccessor);
}
return time;
}
@Override
public Set<FieldPath> getPaths() {
SQLTable table = Configuration.getInstance().getDirectory().getElement("DEVIS").getTable();
Path p = new Path(table).add(tableDevisElt.getField("ID_DEVIS"));
Path p2 = new Path(table).add(tableDevisElt.getField("ID_DEVIS")).addForeignField("ID_UNITE_VENTE");
return CollectionUtils.createSet(new FieldPath(p, "QTE"), new FieldPath(p, "QTE_UNITAIRE"), new FieldPath(p2, "CODE"));
}
});
// Transfert vers facture
RowAction factureAction = eltDevis.getDevis2FactureAction();
eltDevis.getRowActions().add(factureAction);
// Transfert vers commande
RowAction commandeAction = eltDevis.getDevis2CmdCliAction();
eltDevis.getRowActions().add(commandeAction);
// Marqué accepté
RowAction accepteAction = getAcceptAction();
eltDevis.getRowActions().add(accepteAction);
// Marqué accepté
RowAction refuseAction = eltDevis.getRefuseAction();
eltDevis.getRowActions().add(refuseAction);
// // Dupliquer
RowAction cloneAction = eltDevis.getCloneAction();
eltDevis.getRowActions().add(cloneAction);
MouseSheetXmlListeListener mouseSheetXmlListeListener = new MouseSheetXmlListeListener(DevisXmlSheet.class);
mouseSheetXmlListeListener.setGenerateHeader(true);
mouseSheetXmlListeListener.setShowHeader(true);
eltDevis.getRowActions().addAll(mouseSheetXmlListeListener.getRowActions());
element.addComponentFactory(SQLElement.DEFAULT_COMP_ID, new ITransformer<Tuple2<SQLElement, String>, SQLComponent>() {
@Override
public SQLComponent transformChecked(Tuple2<SQLElement, String> input) {
return new DevisSQLComponent(element) {
public int insert(SQLRow order) {
int id = super.insert(order);
checkAffaire(id);
return id;
}
public void update() {
super.update();
checkAffaire(getSelectedID());
}
};
}
});
final SQLElement elementCmd = dir.getElement("COMMANDE_CLIENT");
elementCmd.addListColumn(new BaseSQLTableModelColumn("Temps Total", Double.class) {
SQLTable tableCmdElt = dir.getElement("COMMANDE_CLIENT_ELEMENT").getTable();
@Override
protected Object show_(SQLRowAccessor r) {
Collection<? extends SQLRowAccessor> rows = r.getReferentRows(tableCmdElt);
double time = 0;
for (SQLRowAccessor sqlRowAccessor : rows) {
time += OrderColumnRowRenderer.getHours(sqlRowAccessor);
}
return time;
}
@Override
public Set<FieldPath> getPaths() {
final SQLTable table = elementCmd.getTable();
final Path p = new Path(table).add(tableCmdElt.getField("ID_COMMANDE_CLIENT"));
final Path p2 = new Path(table).add(tableCmdElt.getField("ID_COMMANDE_CLIENT")).addForeignField("ID_UNITE_VENTE");
return CollectionUtils.createSet(new FieldPath(p, "QTE"), new FieldPath(p, "QTE_UNITAIRE"), new FieldPath(p2, "CODE"));
}
});
NumerotationAutoSQLElement.addClass(ProjectSQLElement.class, PROJECT_TABLENAME);
new QuoteToOrderSQLInjector();
new QuoteToInvoiceSQLInjector();
new OrderToInvoiceSQLInjector();
}
public void checkAffaire(int id) {
final SQLTable tableDevis = Configuration.getInstance().getRoot().findTable("DEVIS");
final SQLTable tableNum = Configuration.getInstance().getRoot().findTable("NUMEROTATION_AUTO");
final SQLRow row = tableDevis.getRow(id);
final SQLRow rowAffaire = row.getForeign("ID_AFFAIRE");
if (rowAffaire == null || rowAffaire.isUndefined()) {
if (row.getInt("ID_ETAT_DEVIS") == EtatDevisSQLElement.ACCEPTE) {
// FIXME Vérifier si le devis n'est pas déjà rattaché à une affaire
final SQLTable table = tableDevis.getTable(PROJECT_TABLENAME);
final SQLRowValues rowVals = new SQLRowValues(table);
final String nextNumero = NumerotationAutoSQLElement.getNextNumero(ProjectSQLElement.class);
rowVals.put("NUMERO", nextNumero);
// incrémentation du numéro auto
final SQLRowValues rowValsNum = new SQLRowValues(tableNum);
int val = tableNum.getRow(2).getInt(NumerotationAutoSQLElement.getLabelNumberFor(ProjectSQLElement.class));
val++;
rowValsNum.put(NumerotationAutoSQLElement.getLabelNumberFor(ProjectSQLElement.class), new Integer(val));
try {
rowValsNum.update(2);
} catch (final SQLException e) {
e.printStackTrace();
}
rowVals.put("ID_DEVIS", row.getID());
rowVals.put("ID_CLIENT", row.getObject("ID_CLIENT"));
rowVals.put("ID_COMMERCIAL", row.getObject("ID_COMMERCIAL"));
rowVals.put("DATE", new Date());
rowVals.put("ID_ETAT_AFFAIRE", ProjectStateSQLElement.EN_COURS);
SQLRowValues rowValsDevis = row.asRowValues();
rowValsDevis.put("ID_AFFAIRE", rowVals);
try {
rowVals.commit();
} catch (SQLException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
}
} else {
SQLRowValues rowVals = rowAffaire.asRowValues();
rowVals.putEmptyLink("ID_DEVIS");
try {
rowVals.update();
} catch (SQLException exn) {
// TODO Bloc catch auto-généré
exn.printStackTrace();
}
}
}
public RowAction getAcceptAction() {
return new RowAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
SQLRow selectedRow = IListe.get(e).getSelectedRow().asRow();
SQLRowValues rowVals = selectedRow.createEmptyUpdateRow();
rowVals.put("ID_ETAT_DEVIS", EtatDevisSQLElement.ACCEPTE);
try {
rowVals.update();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
selectedRow.getTable().fireTableModified(selectedRow.getID());
checkAffaire(selectedRow.getID());
}
}, false, "project.accept") {
public boolean enabledFor(List<SQLRowAccessor> selection) {
if (selection != null && selection.size() == 1) {
if (selection.get(0).getInt("ID_ETAT_DEVIS") == EtatDevisSQLElement.EN_ATTENTE) {
return true;
}
}
return false;
};
};
}
@Override
protected void setupComponents(final ComponentsContext ctxt) {
for (String table : this.listTableAffaire) {
if (!table.equalsIgnoreCase("DEVIS"))
ctxt.putAdditionalField(table, "ID_AFFAIRE");
}
}
@Override
protected void setupMenu(final MenuContext ctxt) {
ctxt.addMenuItem(new CreateFrameAbstractAction("Liste des affaires") {
@Override
public JFrame createFrame() {
IListFrame frame = new IListFrame(new ListeAddPanel(ctxt.getElement(PROJECT_TABLENAME)));
return frame;
}
}, MainFrame.LIST_MENU);
ctxt.addMenuItem(new CreateFrameAbstractAction("Historique des affaires") {
@Override
public JFrame createFrame() {
ProjectHistory histo = new ProjectHistory();
return histo.getFrame();
}
}, MainFrame.LIST_MENU);
ctxt.addMenuItem(new CreateFrameAbstractAction("Saisie affaire") {
@Override
public JFrame createFrame() {
return new EditFrame(ctxt.getElement(PROJECT_TABLENAME));
}
}, MainFrame.CREATE_MENU);
}
@Override
protected void start() {
final JComponent quoteComponent = createQuotePanel();
final JComponent orderComponent = createOrderPanel();
MainFrame.getInstance().getTabbedPane().addTab("Commandes en cours", orderComponent);
MainFrame.getInstance().getTabbedPane().addTab("Devis en attente", quoteComponent);
MainFrame.getInstance().getTabbedPane().addTab("Affaires", new ListeAddPanel(Configuration.getInstance().getDirectory().getElement(PROJECT_TABLENAME)));
// Fix for classic XP Theme
quoteComponent.setOpaque(true);
quoteComponent.setBackground(Color.WHITE);
orderComponent.setOpaque(true);
orderComponent.setBackground(Color.WHITE);
// Select first tab
MainFrame.getInstance().getTabbedPane().setSelectedIndex(1);
CommandeClientItemTable.getVisibilityMap().put("POURCENT_ACOMPTE", Boolean.TRUE);
SaisieVenteFactureItemTable.getVisibilityMap().put("POURCENT_ACOMPTE", Boolean.TRUE);
AccountingRecordsProvider p = new AccountingRecordsProvider() {
@Override
public void putLabel(SQLRowAccessor rowSource, Map<String, Object> values) {
values.put("NOM", "Fact. vente " + rowSource.getString("NUMERO"));
}
@Override
public void putPieceLabel(SQLRowAccessor rowSource, SQLRowValues rowValsPiece) {
rowValsPiece.put("NOM", rowSource.getString("NUMERO"));
}
};
AccountingRecordsProviderManager.put(GenerationMvtSaisieVenteFacture.ID, p);
}
private JComponent createQuotePanel() {
ColumnRowRenderer cRenderer = new QuoteColumnRowRenderer();
ColumnFooterRenderer fRenderer = new QuoteColumnFooterRenderer();
final ColumnPanel columnPanel = new ColumnPanel(220, cRenderer, fRenderer);
columnPanel.setOpaque(false);
final SQLElement element = Configuration.getInstance().getDirectory().getElement("DEVIS_ELEMENT");
Path p = Path.get(element.getTable()).addForeignField("ID_ARTICLE").addForeignField("ID_FAMILLE_ARTICLE");
SQLRowValues values = new SQLRowValues(element.getTable());
values.put("NOM", null);
values.put("T_PV_HT", null);
SQLRowValues rowValsClient = new SQLRowValues(element.getTable().getTable("CLIENT"));
rowValsClient.put("NOM", null);
final SQLTable tableDevis = element.getTable().getTable("DEVIS");
SQLRowValues rowValsDevis = new SQLRowValues(tableDevis);
rowValsDevis.put("NUMERO", null);
rowValsDevis.put("DATE", null);
rowValsDevis.put("T_HT", null);
rowValsDevis.put("ID_CLIENT", rowValsClient);
values.put("ID_DEVIS", rowValsDevis);
SQLRowValues rowValsUnite = new SQLRowValues(element.getTable().getTable("UNITE_VENTE"));
rowValsUnite.put("CODE", null);
values.put("ID_UNITE_VENTE", rowValsUnite);
values.put("QTE", null);
values.put("QTE_UNITAIRE", null);
ITransformer<SQLSelect, SQLSelect> t = new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
input.andWhere(new Where(input.getAlias(tableDevis.getField("ID_ETAT_DEVIS")), "=", EtatDevisSQLElement.EN_ATTENTE));
return input;
}
};
final ColumnPanelFetcher projectFetcher = new ColumnPanelFetcher(values, new FieldPath(p, "NOM"), t);
columnPanel.setHeaderRenderer(new TotalHeaderRenderer());
columnPanel.setFetch(projectFetcher);
final JScrollPane comp = new JScrollPane(columnPanel);
comp.setBorder(null);
comp.getViewport().setOpaque(false);
return comp;
}
private JComponent createOrderPanel() {
ColumnRowRenderer cRenderer = new OrderColumnRowRenderer();
ColumnFooterRenderer fRenderer = new OrderColumnFooterRenderer();
final ColumnPanel columnPanel = new ColumnPanel(220, cRenderer, fRenderer);
columnPanel.setOpaque(false);
final SQLElement element = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT_ELEMENT");
final SQLTable tableOrder = element.getTable();
Path p = Path.get(tableOrder).addForeignField("ID_ARTICLE").addForeignField("ID_FAMILLE_ARTICLE");
SQLRowValues values = new SQLRowValues(tableOrder);
values.put("NOM", null);
values.put("T_PV_HT", null);
SQLRowValues rowValsClient = new SQLRowValues(tableOrder.getTable("CLIENT"));
rowValsClient.put("NOM", null);
SQLRowValues rowValsCmd = new SQLRowValues(tableOrder.getTable("COMMANDE_CLIENT"));
rowValsCmd.put("NUMERO", null);
rowValsCmd.put("DATE", null);
rowValsCmd.put("T_HT", null);
rowValsCmd.put("ID_CLIENT", rowValsClient);
values.put("ID_COMMANDE_CLIENT", rowValsCmd);
SQLRowValues rowValsUnite = new SQLRowValues(tableOrder.getTable("UNITE_VENTE"));
rowValsUnite.put("CODE", null);
values.put("ID_UNITE_VENTE", rowValsUnite);
values.put("QTE", null);
values.put("QTE_UNITAIRE", null);
final SQLTable tableAffaire = tableOrder.getTable(PROJECT_TABLENAME);
SQLRowValues rowValsAffaire = new SQLRowValues(tableAffaire);
rowValsAffaire.put("NUMERO", null);
rowValsAffaire.put("DATE", null);
rowValsCmd.put("ID_AFFAIRE", rowValsAffaire);
if (tableOrder.getDBRoot().contains("AFFAIRE_TEMPS")) {
final SQLTable tableAffaireTemps = tableOrder.getTable("AFFAIRE_TEMPS");
SQLRowValues rowValsAffaireTemps = new SQLRowValues(tableAffaireTemps);
rowValsAffaireTemps.put("TEMPS", null);
rowValsAffaireTemps.put("ID_COMMANDE_CLIENT_ELEMENT", values);
}
ITransformer<SQLSelect, SQLSelect> t = new ITransformer<SQLSelect, SQLSelect>() {
@Override
public SQLSelect transformChecked(SQLSelect input) {
input.andWhere(new Where(input.getAlias(tableAffaire.getField("ID_ETAT_AFFAIRE")), "=", ProjectStateSQLElement.EN_COURS));
return input;
}
};
final ColumnPanelFetcher projectFetcher = new ColumnPanelFetcher(values, new FieldPath(p, "NOM"), t);
columnPanel.setHeaderRenderer(new TotalHeaderRenderer());
columnPanel.setFetch(projectFetcher);
final JScrollPane comp = new JScrollPane(columnPanel);
comp.setBorder(null);
comp.getViewport().setOpaque(false);
return comp;
}
@Override
protected void stop() {
}
}
| gpl-3.0 |
IAAA-Lab/UNIZAR-BuildingsApp | src/main/java/com/uzapp/security/jwt/AuthenticatedUser.java | 1302 | package com.uzapp.security.jwt;
import java.util.Collection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
public class AuthenticatedUser implements Authentication {
/**
*
*/
private static final long serialVersionUID = -4207148204742371748L;
private String name;
private Collection<? extends GrantedAuthority> authorities;
private boolean authenticated = true;
AuthenticatedUser(String name){
this.name = name;
}
public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
this.authorities= authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getDetails() {
return null;
}
@Override
public Object getPrincipal() {
return null;
}
@Override
public boolean isAuthenticated() {
return this.authenticated;
}
@Override
public void setAuthenticated(boolean b) throws IllegalArgumentException {
this.authenticated = b;
}
@Override
public String getName() {
return this.name;
}
}
| gpl-3.0 |
ThirtyDegreesRay/OpenHub | app/src/main/java/com/thirtydegreesray/openhub/mvp/presenter/RepoInfoPresenter.java | 3741 |
package com.thirtydegreesray.openhub.mvp.presenter;
import com.thirtydegreesray.dataautoaccess.annotation.AutoAccess;
import com.thirtydegreesray.openhub.AppConfig;
import com.thirtydegreesray.openhub.dao.DaoSession;
import com.thirtydegreesray.openhub.http.core.HttpObserver;
import com.thirtydegreesray.openhub.http.core.HttpResponse;
import com.thirtydegreesray.openhub.http.error.HttpPageNoFoundError;
import com.thirtydegreesray.openhub.mvp.contract.IRepoInfoContract;
import com.thirtydegreesray.openhub.mvp.model.Repository;
import com.thirtydegreesray.openhub.mvp.presenter.base.BasePagerPresenter;
import com.thirtydegreesray.openhub.util.StringUtils;
import java.io.IOException;
import javax.inject.Inject;
import okhttp3.ResponseBody;
import retrofit2.Response;
import rx.Observable;
/**
* Created by ThirtyDegreesRay on 2017/8/11 11:34:31
*/
public class RepoInfoPresenter extends BasePagerPresenter<IRepoInfoContract.View>
implements IRepoInfoContract.Presenter{
@AutoAccess Repository repository;
@AutoAccess String curBranch = "";
private String readmeSource;
@Inject
public RepoInfoPresenter(DaoSession daoSession) {
super(daoSession);
}
@Override
public void onViewInitialized() {
super.onViewInitialized();
}
@Override
protected void loadData() {
mView.showRepoInfo(repository);
if(readmeSource == null){
loadReadMe();
}
}
@Override
public void loadReadMe() {
final String readmeFileUrl = AppConfig.GITHUB_API_BASE_URL + "repos/" + repository.getFullName()
+ "/" + "readme" + (StringUtils.isBlank(curBranch) ? "" : "?ref=" + curBranch);
String branch = StringUtils.isBlank(curBranch) ? repository.getDefaultBranch() : curBranch;
final String baseUrl = AppConfig.GITHUB_BASE_URL + repository.getFullName()
+ "/blob/" + branch + "/" + "README.md";
// if(!StringUtils.isBlank(readmeSource)){
// mView.showReadMe(readmeSource, baseUrl);
// return;
// }
mView.showReadMeLoader();
HttpObserver<ResponseBody> httpObserver = new HttpObserver<ResponseBody>() {
@Override
public void onError(Throwable error) {
if(error instanceof HttpPageNoFoundError){
mView.showNoReadMe();
} else {
mView.showErrorToast(getErrorTip(error));
}
}
@Override
public void onSuccess(HttpResponse<ResponseBody> response) {
try {
readmeSource = response.body().string();
mView.showReadMe(readmeSource, baseUrl);
} catch (IOException e) {
e.printStackTrace();
}
}
};
generalRxHttpExecute(new IObservableCreator<ResponseBody>() {
@Override
public Observable<Response<ResponseBody>> createObservable(boolean forceNetWork) {
return getRepoService().getFileAsHtmlStream(forceNetWork, readmeFileUrl);
}
}, httpObserver, true);
}
public Repository getRepository() {
return repository;
}
/**
* check if the string size is too large to save
*/
private void checkReadmeSourceSize(){
if(readmeSource != null && readmeSource.getBytes().length > 128 * 1024){
readmeSource = null;
}
}
public void setRepository(Repository repository) {
this.repository = repository;
}
public void setCurBranch(String curBranch) {
this.curBranch = curBranch;
readmeSource = null;
}
}
| gpl-3.0 |
sosilent/euca | clc/modules/authentication/src/main/java/com/eucalyptus/auth/policy/key/KeepAlive.java | 2224 | package com.eucalyptus.auth.policy.key;
import java.util.Date;
import org.apache.log4j.Logger;
import net.sf.json.JSONException;
import com.eucalyptus.auth.Contract;
import com.eucalyptus.auth.policy.PolicySpec;
import com.eucalyptus.auth.policy.condition.ConditionOp;
import com.eucalyptus.auth.policy.condition.NumericEquals;
@PolicyKey( Keys.EC2_KEEPALIVE )
public class KeepAlive extends ContractKey<Date> {
private static final Logger LOG = Logger.getLogger( KeepAlive.class );
private static final String KEY = Keys.EC2_KEEPALIVE;
private static final String ACTION_RUNINSTANCES = PolicySpec.VENDOR_EC2 + ":" + PolicySpec.EC2_RUNINSTANCES;
private static final long YEAR = 1000 * 60 * 60 * 24 * 365; // one year by default
private static final long MINUTE = 1000 * 60; // minute
@Override
public void validateConditionType( Class<? extends ConditionOp> conditionClass ) throws JSONException {
if ( NumericEquals.class != conditionClass ) {
throw new JSONException( KEY + " is not allowed in condition " + conditionClass.getName( ) + ". NumericEquals is required." );
}
}
@Override
public void validateValueType( String value ) throws JSONException {
KeyUtils.validateIntegerValue( value, KEY );
}
@Override
public Contract<Date> getContract( final String[] values ) {
return new Contract<Date>( ) {
@Override
public Contract.Type getType( ) {
return Contract.Type.EXPIRATION;
}
@Override
public Date getValue( ) {
return getExpiration( values[0] );
}
};
}
@Override
public boolean canApply( String action, String resourceType ) {
return ACTION_RUNINSTANCES.equals( action );
}
@Override
public boolean isBetter( Contract<Date> current, Contract<Date> update ) {
return update.getValue( ).after( current.getValue( ) );
}
/**
* @param keepAlive In minute.
* @return
*/
private static Date getExpiration( String keepAlive ) {
try {
return new Date( System.currentTimeMillis( ) + Long.valueOf( keepAlive ) * MINUTE );
} catch ( Exception e ) {
LOG.debug( e, e );
return new Date( System.currentTimeMillis( ) + YEAR );
}
}
}
| gpl-3.0 |
guiguilechat/EveOnline | model/esi/JCESI/src/generated/java/fr/guiguilechat/jcelechat/model/jcesi/compiler/compiled/responses/R_get_universe_groups_group_id.java | 1483 | package fr.guiguilechat.jcelechat.model.jcesi.compiler.compiled.responses;
public class R_get_universe_groups_group_id {
/**
* category_id integer
*/
public int category_id;
/**
* group_id integer
*/
public int group_id;
/**
* name string
*/
public String name;
/**
* published boolean
*/
public boolean published;
/**
* types array
*/
public int[] types;
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other == null)||(other.getClass()!= getClass())) {
return false;
}
R_get_universe_groups_group_id othersame = ((R_get_universe_groups_group_id) other);
if (category_id!= othersame.category_id) {
return false;
}
if (group_id!= othersame.group_id) {
return false;
}
if ((name!= othersame.name)&&((name == null)||(!name.equals(othersame.name)))) {
return false;
}
if (published!= othersame.published) {
return false;
}
if ((types!= othersame.types)&&((types == null)||(!types.equals(othersame.types)))) {
return false;
}
return true;
}
public int hashCode() {
return ((((category_id + group_id)+((name == null)? 0 :name.hashCode()))+ Boolean.hashCode(published))+((types == null)? 0 :types.hashCode()));
}
}
| gpl-3.0 |
micromata/projectforge | projectforge-wicket/src/main/java/org/projectforge/web/teamcal/event/TeamEventListForm.java | 8726 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2022 Micromata GmbH, Germany (www.micromata.com)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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 General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web.teamcal.event;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.validation.IFormValidator;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.projectforge.business.teamcal.admin.TeamCalCache;
import org.projectforge.business.teamcal.admin.TeamCalsComparator;
import org.projectforge.business.teamcal.admin.model.TeamCalDO;
import org.projectforge.business.teamcal.event.TeamEventFilter;
import org.projectforge.web.CSSColor;
import org.projectforge.web.calendar.QuickSelectPanel;
import org.projectforge.web.common.MultiChoiceListHelper;
import org.projectforge.web.teamcal.admin.TeamCalsProvider;
import org.projectforge.web.wicket.AbstractListForm;
import org.projectforge.web.wicket.WicketUtils;
import org.projectforge.web.wicket.components.DatePanelSettings;
import org.projectforge.web.wicket.components.LocalDateModel;
import org.projectforge.web.wicket.components.LocalDatePanel;
import org.projectforge.web.wicket.components.SingleButtonPanel;
import org.projectforge.web.wicket.flowlayout.*;
import org.slf4j.Logger;
import org.wicketstuff.select2.Select2MultiChoice;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Date;
/**
* @author Kai Reinhard (k.reinhard@micromata.de)
*/
public class TeamEventListForm extends AbstractListForm<TeamEventFilter, TeamEventListPage>
{
private static final long serialVersionUID = 3659495003810851072L;
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TeamEventListForm.class);
@SpringBean
TeamCalCache teamCalCache;
MultiChoiceListHelper<TeamCalDO> calendarsListHelper;
protected LocalDatePanel startDate;
protected LocalDatePanel endDate;
private final FormComponent<?>[] dependentFormComponents = new FormComponent<?>[2];
public TeamEventListForm(final TeamEventListPage parentPage)
{
super(parentPage);
}
/**
* @see org.projectforge.web.wicket.AbstractListForm#newSearchFilterInstance()
*/
@Override
protected TeamEventFilter newSearchFilterInstance()
{
return new TeamEventFilter();
}
/**
* @see org.projectforge.web.wicket.AbstractListForm#init()
*/
@SuppressWarnings("serial")
@Override
protected void init()
{
super.init();
getParentPage().onFormInit();
add(new IFormValidator()
{
@Override
public FormComponent<?>[] getDependentFormComponents()
{
return dependentFormComponents;
}
@Override
public void validate(final Form<?> form)
{
if (parentPage.isMassUpdateMode() == false) {
final Date from = startDate.getConvertedInput();
final Date to = endDate.getConvertedInput();
if (from != null && to != null && from.after(to) == true) {
error(getString("timePeriodPanel.startTimeAfterStopTime"));
}
}
}
});
{
final FieldsetPanel fs = gridBuilder.newFieldset(getString("templates")).suppressLabelForWarning();
fs.add(new SingleButtonPanel(fs.newChildId(), new Button(SingleButtonPanel.WICKET_ID, new Model<String>("all"))
{
@Override
public final void onSubmit()
{
final Collection<TeamCalDO> assignedItems = teamCalCache.getAllAccessibleCalendars();
calendarsListHelper.setAssignedItems(assignedItems);
}
}, getString("selectAll"), SingleButtonPanel.NORMAL));
fs.add(new SingleButtonPanel(fs.newChildId(), new Button(SingleButtonPanel.WICKET_ID, new Model<String>("own"))
{
@Override
public final void onSubmit()
{
final Collection<TeamCalDO> assignedItems = teamCalCache.getAllOwnCalendars();
calendarsListHelper.setAssignedItems(assignedItems);
}
}, getString("plugins.teamcal.own"), SingleButtonPanel.NORMAL));
}
}
/**
* @see org.projectforge.web.wicket.AbstractListForm#onOptionsPanelCreate(org.projectforge.web.wicket.flowlayout.FieldsetPanel,
* org.projectforge.web.wicket.flowlayout.DivPanel)
*/
@SuppressWarnings("serial")
@Override
protected void onOptionsPanelCreate(final FieldsetPanel optionsFieldsetPanel, final DivPanel optionsCheckBoxesPanel)
{
{
optionsFieldsetPanel.setOutputMarkupId(true);
startDate = new LocalDatePanel(optionsFieldsetPanel.newChildId(),
new LocalDateModel(new PropertyModel<LocalDate>(getSearchFilter(), "startDate")),
DatePanelSettings.get().withSelectPeriodMode(true), true);
optionsFieldsetPanel.add(dependentFormComponents[0] = startDate);
optionsFieldsetPanel.setLabelFor(startDate);
optionsFieldsetPanel.add(new DivTextPanel(optionsFieldsetPanel.newChildId(), " - "));
endDate = new LocalDatePanel(optionsFieldsetPanel.newChildId(), new LocalDateModel(new PropertyModel<LocalDate>(getSearchFilter(), "endDate")),
DatePanelSettings.get().withSelectPeriodMode(true), true);
optionsFieldsetPanel.add(dependentFormComponents[1] = endDate);
{
final SubmitLink unselectPeriod = new SubmitLink(IconLinkPanel.LINK_ID)
{
@Override
public void onSubmit()
{
getSearchFilter().setStartDate(null);
getSearchFilter().setEndDate(null);
clearInput();
parentPage.refresh();
}
};
unselectPeriod.setDefaultFormProcessing(false);
optionsFieldsetPanel
.add(new IconLinkPanel(optionsFieldsetPanel.newChildId(), IconType.REMOVE_SIGN, new ResourceModel(
"calendar.tooltip.unselectPeriod"), unselectPeriod).setColor(CSSColor.RED));
}
final QuickSelectPanel quickSelectPanel = new QuickSelectPanel(optionsFieldsetPanel.newChildId(), parentPage,
"quickSelect",
startDate);
optionsFieldsetPanel.add(quickSelectPanel);
quickSelectPanel.init();
optionsFieldsetPanel.add(new HtmlCommentPanel(optionsFieldsetPanel.newChildId(), new Model<String>()
{
@Override
public String getObject()
{
return WicketUtils.getUTCDates(getSearchFilter().getStartDate(), getSearchFilter().getEndDate());
}
}));
}
{
// Team calendar
final FieldsetPanel fs = gridBuilder.newFieldset(getString("plugins.teamcal.calendar"));// .setLabelSide(false);
final TeamCalsProvider calendarProvider = new TeamCalsProvider(teamCalCache);
calendarsListHelper = new MultiChoiceListHelper<TeamCalDO>().setComparator(new TeamCalsComparator()).setFullList(
calendarProvider.getSortedCalenders());
final Collection<Integer> list = getFilter().getTeamCals();
if (list != null) {
for (final Integer calId : list) {
final TeamCalDO cal = teamCalCache.getCalendar(calId);
calendarsListHelper.addOriginalAssignedItem(cal).assignItem(cal);
}
}
final Select2MultiChoice<TeamCalDO> calendars = new Select2MultiChoice<TeamCalDO>(fs.getSelect2MultiChoiceId(),
new PropertyModel<Collection<TeamCalDO>>(this.calendarsListHelper, "assignedItems"), calendarProvider);
fs.add(calendars);
}
}
/**
* @see org.projectforge.web.wicket.AbstractListForm#getLogger()
*/
@Override
protected Logger getLogger()
{
return log;
}
/**
* @return the filter
*/
public TeamEventFilter getFilter()
{
return getSearchFilter();
}
}
| gpl-3.0 |
emilioserra/UbikSim | src/sim/app/ubik/chart/DateComparator.java | 2944 | /*
* UbikSim2 has been developed by:
*
* Juan A. Botía , juanbot[at] um.es
* Pablo Campillo, pablocampillo[at] um.es
* Francisco Campuzano, fjcampuzano[at] um.es
* Emilio Serrano, emilioserra [at] dit.upm.es
*
* This file is part of UbikSimIDE.
*
* UbikSimIDE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* UbikSimIDE 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with UbikSimIDE. If not, see <http://www.gnu.org/licenses/>
*/
package sim.app.ubik.chart;
import java.util.Comparator;
import java.util.Date;
import java.util.Calendar;
public class DateComparator implements Comparator{
private static Calendar calendario = Calendar.getInstance();
private static int getMonth(String month){
if (month.equals("Jan")){
return Calendar.JANUARY;
}
else if (month.equals("Feb")){
return Calendar.FEBRUARY;
}
else if (month.equals("Mar")){
return Calendar.MARCH;
}
else if (month.equals("Apr")){
return Calendar.APRIL;
}
else if (month.equals("May")){
return Calendar.MAY;
}
else if (month.equals("Jun")){
return Calendar.JUNE;
}
else if (month.equals("Jul")){
return Calendar.JULY;
}
else if (month.equals("Aug")){
return Calendar.AUGUST;
}
else if (month.equals("Sep")){
return Calendar.SEPTEMBER;
}
else if (month.equals("Oct")){
return Calendar.OCTOBER;
}
else if (month.equals("Nov")){
return Calendar.NOVEMBER;
}
else if (month.equals("Dec")){
return Calendar.DECEMBER;
}
else {
return 0;
}
}
private static Date getDate(String cadena){
calendario.set(Integer.parseInt(cadena.substring(19,23)),getMonth(cadena.substring(3,6)),Integer.parseInt(cadena.substring(6,8)),Integer.parseInt(cadena.substring(8,10)),Integer.parseInt(cadena.substring(11,13)),Integer.parseInt(cadena.substring(14,16)));
return calendario.getTime();
}
@Override
public int compare(Object obj1, Object obj2) {
String s1 = (String)obj1;
String s2 = (String)obj2;
Date d1 = getDate(s1.substring(s1.indexOf(",")+1));
Date d2 = getDate(s2.substring(s2.indexOf(",")+1));
return d1.compareTo(d2);
}
}
| gpl-3.0 |
jimdowling/gvod | simulators/src/main/java/se/sics/gvod/simulator/video/VideoStreamingScenario.java | 5316 | package se.sics.gvod.simulator.video;
import java.util.Random;
import se.sics.gvod.net.VodAddress;
import se.sics.gvod.simulator.common.PeerJoin;
import se.sics.gvod.simulator.common.StartCollectData;
import se.sics.gvod.simulator.common.StopCollectData;
import se.sics.gvod.simulator.video.scenarios.VideoScenario;
import se.sics.kompics.p2p.experiment.dsl.SimulationScenario;
import se.sics.kompics.p2p.experiment.dsl.adaptor.Operation;
import se.sics.kompics.p2p.experiment.dsl.adaptor.Operation1;
/**
*
* @author Niklas Wahlén <nwahlen@kth.se>
*/
@SuppressWarnings("serial")
public class VideoStreamingScenario extends VideoScenario {
public static final int SOURCE_NODES = 1;
private static SimulationScenario scenario = new SimulationScenario() {
{
SimulationScenario.StochasticProcess firstNodesJoin = new SimulationScenario.StochasticProcess() {
{
eventInterArrivalTime(constant(10));
raise(FIRST, Operations.videoPeerJoin(VodAddress.NatType.OPEN),
uniform(0, 10000));
}
};
SimulationScenario.StochasticProcess sourceNodeJoin = new SimulationScenario.StochasticProcess() {
{
eventInterArrivalTime(constant(1));
raise(SOURCE_NODES, Operations.sourceJoin(VodAddress.NatType.OPEN),
uniform(0, 10000));
}
};
SimulationScenario.StochasticProcess nodesJoin1 = new SimulationScenario.StochasticProcess() {
{
eventInterArrivalTime(exponential(10));
raise(VideoScenario.PUBLIC, Operations.videoPeerJoin(VodAddress.NatType.OPEN),
uniform(0, 10000));
if (VideoScenario.PRIVATE > 0) {
raise(VideoScenario.PRIVATE, Operations.videoPeerJoin(VodAddress.NatType.NAT),
uniform(0, 10000));
}
}
};
SimulationScenario.StochasticProcess startCollectData = new SimulationScenario.StochasticProcess() {
{
eventInterArrivalTime(constant(1000));
raise(VideoScenario.COLLECT_VIDEO_RESULTS, Operations.startCollectData());
}
};
SimulationScenario.StochasticProcess stopCollectData = new SimulationScenario.StochasticProcess() {
{
eventInterArrivalTime(exponential(10));
raise(1, Operations.stopCollectData());
}
};
// Some nodes has to start initially (for Croupier)
firstNodesJoin.start();
sourceNodeJoin.startAfterTerminationOf(5000, firstNodesJoin);
nodesJoin1.startAfterTerminationOf(15000, firstNodesJoin);
startCollectData.startAfterTerminationOf(1000, nodesJoin1);
stopCollectData.startAfterTerminationOf(15 * 1000, startCollectData);
}
};
//-------------------------------------------------------------------
public VideoStreamingScenario() {
super(scenario);
}
public static class Operations {
private static int index = 0;
private static Random rnd = new Random();
static Operation1<SourceJoin, Long> sourceJoin(final VodAddress.NatType peerType) {
return new Operation1<SourceJoin, Long>() {
@Override
public SourceJoin generate(Long id) {
return new SourceJoin(id.intValue(), peerType, SourceJoin.NO_OPTION);
}
};
}
static Operation1<PeerJoin, Long> videoPeerJoin(final VodAddress.NatType peerType) {
return new Operation1<PeerJoin, Long>() {
@Override
public PeerJoin generate(Long id) {
return new PeerJoin(id.intValue(), peerType);
}
};
}
static Operation1<PeerJoin, Long> videoPeerJoin(final double privateNodesRatio) {
return new Operation1<PeerJoin, Long>() {
@Override
public PeerJoin generate(Long id) {
VodAddress.NatType peerType;
index++;
if (rnd.nextDouble() < privateNodesRatio) {
peerType = VodAddress.NatType.NAT;
} else {
peerType = VodAddress.NatType.OPEN;
}
return new PeerJoin(id.intValue(), peerType);
}
};
}
static Operation<StartCollectData> startCollectData() {
return new Operation<StartCollectData>() {
@Override
public StartCollectData generate() {
return new StartCollectData();
}
};
}
static Operation<StopCollectData> stopCollectData() {
return new Operation<StopCollectData>() {
@Override
public StopCollectData generate() {
return new StopCollectData();
}
};
}
}
}
| gpl-3.0 |
leandroacosta292/MeuComercio | src/meucomercio/dao/FazerPedidoDao.java | 5417 | /*
* 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 meucomercio.dao;
import apoio.ConexaoBD;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import meucomercio.entidades.Comanda;
import meucomercio.entidades.Pedido;
import meucomercio.entidades.Produto;
/**
*
* @author Leandro Acosta <leandro.acosta292@hotmail.com>
*/
public class FazerPedidoDao {
public int salvar(String idComanda, String idProduto) {
try {
Statement st = ConexaoBD.getInstance().getConnection().createStatement();
String sql = "INSERT INTO produto_comanda VALUES"
+ "(DEFAULT,"
+ idProduto + ","
+ idComanda + ","
+ "'Aberto'"
+ ") RETURNING id";
System.out.println("sql: " + sql);
ResultSet rs = st.executeQuery(sql);
int id = 0;
if (rs.next()) {
id = rs.getInt("id");
}
return id;
} catch (Exception e) {
System.out.println("Erro ao salvar Pedido = " + e);
return 0;
}
}
public boolean excluir(int id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public ArrayList<Object> consultarTodos() {
ArrayList pedidos = new ArrayList();
try {
Statement st = ConexaoBD.getInstance().getConnection().createStatement();
String sql = "SELECT * FROM produto_comanda ORDER BY 1";
// System.out.println("sql: " + sql);
ResultSet resultado = st.executeQuery(sql);
while (resultado.next()) {
Pedido tmpPedido = new Pedido();
tmpPedido.setIdComanda(resultado.getInt("comanda_id"));
Comanda tmpComanda = (Comanda) new ComandaDao().consultarId(Integer.valueOf(tmpPedido.getIdComanda()));
tmpPedido.setNomeComanda(tmpComanda.getNome());
tmpPedido.setIdPedido(resultado.getInt("id"));
tmpPedido.setIdProduto(resultado.getInt("produto_id"));
Produto tmpProduto = (Produto) new ProdutoDao().consultarId(Integer.valueOf(tmpPedido.getIdProduto()));
tmpPedido.setNomeProduto(tmpProduto.getProduto());
tmpPedido.setStatus(resultado.getString("status"));
pedidos.add(tmpPedido);
}
} catch (Exception e) {
System.out.println("Erro consultar Pedido= " + e);
return null;
}
return pedidos;
}
public boolean alterarEstadoCancelado(int idPedido) {
try {
Statement st = ConexaoBD.getInstance().getConnection().createStatement();
String sql = "UPDATE produto_comanda SET "
+ "status = 'Cancelado'"
+ " WHERE id = " + idPedido;
// System.out.println("sql: " + sql);
st.executeUpdate(sql);;
return true;
} catch (Exception e) {
System.out.println("Erro ao alterar estado do Pedido = " + e);
return false;
}
}
public boolean alterarEstadoFechado(int idPedido) {
try {
Statement st = ConexaoBD.getInstance().getConnection().createStatement();
String sql = "UPDATE produto_comanda SET "
+ "status = 'Fechado'"
+ " WHERE id = " + idPedido;
// System.out.println("sql: " + sql);
st.executeUpdate(sql);;
return true;
} catch (Exception e) {
System.out.println("Erro ao alterar estado do Pedido = " + e);
return false;
}
}
public ArrayList<Object> consultarTodosAbertos() {
ArrayList pedidos = new ArrayList();
try {
Statement st = ConexaoBD.getInstance().getConnection().createStatement();
String sql = "SELECT * FROM produto_comanda WHERE status = 'Aberto' ORDER BY 1 ";
System.out.println("sql: " + sql);
ResultSet resultado = st.executeQuery(sql);
while (resultado.next()) {
Pedido tmpPedido = new Pedido();
tmpPedido.setIdComanda(resultado.getInt("comanda_id"));
Comanda tmpComanda = (Comanda) new ComandaDao().consultarId(Integer.valueOf(tmpPedido.getIdComanda()));
tmpPedido.setNomeComanda(tmpComanda.getNome());
tmpPedido.setIdPedido(resultado.getInt("id"));
tmpPedido.setIdProduto(resultado.getInt("produto_id"));
Produto tmpProduto = (Produto) new ProdutoDao().consultarId(Integer.valueOf(tmpPedido.getIdProduto()));
tmpPedido.setNomeProduto(tmpProduto.getProduto());
tmpPedido.setStatus(resultado.getString("status"));
pedidos.add(tmpPedido);
}
} catch (Exception e) {
System.out.println("Erro consultar Pedido= " + e);
return null;
}
return pedidos;
}
}
| gpl-3.0 |
silentbalanceyh/lyra | lyra-bus/util-comet/src/test/java/com/test/lyra/util/instance/SortedSetTestCase.java | 1839 | package com.test.lyra.util.instance;
import static com.lyra.util.instance.SortedSetInstance.linkedHashSet;
import static com.lyra.util.instance.SortedSetInstance.treeSet;
import static org.junit.Assert.assertNotNull;
import java.util.Set;
import net.sf.oval.exception.ConstraintsViolatedException;
import org.junit.Test;
import com.lyra.util.test.AbstractTestCase;
import com.test.lyra.util.assist.InstanceModel;
import com.test.lyra.util.assist.ModelComparator;
/**
* 测试类:com.lyra.util.instance.SortedInstance
*
* @author Lang
* @see
*/
public class SortedSetTestCase extends AbstractTestCase implements
InstanceConstant {
// ~ Constructors ========================================
/**
*
*/
public SortedSetTestCase() {
super(TestClasses.SORTEDSET);
// final Set<String> treeSet = treeSet(null); Compile Error
}
// ~ Methods =============================================
/**
* SortedInstance.linkedHashSet(Collection<T>)
*/
@Test(expected = ConstraintsViolatedException.class)
public void testLinkedHashSet1() {
setMethod(M_LHASHSET1);
final Set<String> linkedSet = linkedHashSet(null);
failure(linkedSet);
}
/**
* SortedSetInstance.linkedHashSet()
*/
@Test
public void testLinkedHashSet2(){
setMethod(M_LHASHSET2);
final Set<String> set = linkedHashSet();
assertNotNull(getPosition(),set);
}
/**
* SortedSetInstance.linkedHashSet(Collection<T>)
*/
@Test
public void testLinkedHashSet3(){
setMethod(M_LHASHSET1);
final Set<String> set = treeSet();
final Set<String> retSet = linkedHashSet(set);
assertNotNull(getPosition(),retSet);
}
/**
* SortedSetInstance.treeSet(Comparator<T>)
*/
@Test
public void testTreeSet1(){
setMethod(M_TREESET2);
final Set<InstanceModel> set = treeSet(new ModelComparator());
assertNotNull(getPosition(),set);
}
}
| gpl-3.0 |
flibbertigibbet/SEPTA-Android | app/src/main/java/org/septa/android/app/models/servicemodels/AlertModel.java | 5662 | /*
* AlertModel.java
* Last modified on 05-16-2014 20:24-0400 by brianhmayo
*
* Copyright (c) 2014 SEPTA. All rights reserved.
*/
package org.septa.android.app.models.servicemodels;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
public class AlertModel implements Comparable<AlertModel> {
public static final String TAG = AlertModel.class.getName();
@SerializedName("isSnow") private String isSnow;
@SerializedName("isadvisory") private String isAdvisory;
@SerializedName("isalert") private String isAlert;
@SerializedName("isdetour") private String isDetour;
@SerializedName("issuppend") private String isSuspended;
@SerializedName("last_updated") private Date lastUpdate;
@SerializedName("mode") private String mode;
@SerializedName("route_id") private String routeId;
@SerializedName("route_name") private String routeName;
@SerializedName("current_message") private String currentMessage;
public AlertModel(){
this.mode = "Empty";
this.routeId = null;
this.routeName = "Empty";
this.currentMessage = "Empty";
this.isAlert = "N";
this.isDetour = "N";
this.isSuspended ="N";
this.isAdvisory = "No";
this.isSnow = "N";
this.lastUpdate = new Date();
}
public boolean isGeneral() {
if (mode.equals("generic")) {
return true;
}
return false;
}
public boolean isBSL() {
if (mode.equals("Broad Street Line")) {
return true;
}
return false;
}
public boolean isBus() {
if (mode.equals("Bus")) {
return true;
}
return false;
}
public boolean isTrolley () {
if (mode.equals("Trolley")) {
return true;
}
return false;
}
public boolean isRegionalRail() {
if (mode.equals("Regional Rail")) {
return true;
}
return false;
}
public boolean isMFL() {
if (mode.equals("Market/ Frankford")) {
return true;
}
return false;
}
public boolean isNHSL() {
if (mode.equals("Norristown High Speed Line")) {
return true;
}
return false;
}
public boolean hasSnowFlag() {
if (isSnow.toUpperCase().equals("Y")) {
return true;
}
return false;
}
public boolean hasAdvisoryFlag() {
if (isAdvisory.toUpperCase().equals("YES")) {
return true;
}
return false;
}
public boolean hasAlertFlag() {
if (isAlert.toUpperCase().equals("Y")) {
return true;
}
return false;
}
public boolean hasDetourFlag() {
if (isDetour.toUpperCase().equals("Y")) {
return true;
}
return false;
}
public boolean hasSuspendedFlag() {
if (isSuspended.toUpperCase().equals("Y")) {
return true;
}
return false;
}
public boolean isSuspended() {
return hasSuspendedFlag();
}
public boolean hasFlag() {
if (hasSuspendedFlag() || hasAlertFlag() || hasAdvisoryFlag() || hasDetourFlag()) {
return true;
}
return false;
}
public String getRouteName() {
return routeName;
}
public String getRouteId() {
return routeId;
}
@Override
public int compareTo(AlertModel another) {
int result = 0;
Integer thisRouteName = null;
Integer otherRouteName = null;
boolean thisIsString = false;
boolean otherIsString = false;
// first check if the row is for elevators, if yes, it will go at the top
if (mode.equals("elevator")) {
return -1;
} else {
if (another.mode.equals("elevator")) {
return 1;
}
}
// next check if the row is for general, if yes, it goes just below the elevator
if (mode.equals("generic")) {
return -1;
} else {
if (another.mode.equals("generic")) {
return 1;
}
}
// we assume a route short name is either a number (only numerics), a number with a trailing character, or
// not a number (all characters.
// first check if it is a number, then remove the last character and check for a number
// if those two fail, it must not be or have a number
try {
thisRouteName = Integer.valueOf(this.routeName);
} catch (NumberFormatException nfe) {
thisIsString = true;
}
try {
otherRouteName = Integer.valueOf(another.routeName);
} catch (NumberFormatException nfe) {
otherIsString = true;
}
// this is a string and other is not, thus other comes first
if (thisIsString && !otherIsString) {
return 1;
}
// this is not a string and other is, thus this comes first
if (!thisIsString && otherIsString) {
return -1;
}
// both are strings, just compare outright;
if (thisIsString && otherIsString) {
return this.routeName.compareTo(another.routeName);
}
// if we got here, we converted both to Integers and can compare outright.
return thisRouteName.compareTo(otherRouteName);
}
public String getCurrentMessage() {
return currentMessage;
}
public Date getLastUpdate() {
return lastUpdate;
}
}
| gpl-3.0 |
Rubbiroid/VVIDE | src/vvide/utils/xmlitems/CheckBoxMenuItemItem.java | 1484 | /*
* This file is part of the VVIDE project.
*
* Copyright (C) 2011 Pavel Fischer rubbiroid@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package vvide.utils.xmlitems;
import javax.swing.JCheckBoxMenuItem;
import org.w3c.dom.Element;
import vvide.Application;
/**
* An XML Item for CheckBoxMenu Item
*/
public class CheckBoxMenuItemItem extends AbstractXMLItem {
/*
* ============================ Methods ==================================
*/
@Override
public Object parseXMLElement( Element element ) {
// Getting an action
String actionName = (String) xmlUtils.getItem( "String" ).parseXMLElement(
xmlUtils.getElementNodeList( element.getChildNodes() )
.firstElement() );
return new JCheckBoxMenuItem( Application.actionManager.getAction( actionName ) );
}
}
| gpl-3.0 |
w359405949/RunJS | RunJS/src/net/oschina/runjs/action/PluginAction.java | 12690 | package net.oschina.runjs.action;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import net.oschina.common.servlet.Annotation.JSONOutputEnabled;
import net.oschina.common.servlet.Annotation.PostMethod;
import net.oschina.common.servlet.Annotation.UserRoleRequired;
import net.oschina.common.servlet.IUser;
import net.oschina.common.servlet.RequestContext;
import net.oschina.runjs.beans.Code;
import net.oschina.runjs.beans.Plugin;
import net.oschina.runjs.beans.PluginCode;
import net.oschina.runjs.beans.Project;
import net.oschina.runjs.beans.User;
import net.oschina.runjs.beans.UserFile;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import com.google.gson.Gson;
public class PluginAction {
private Gson gson = new Gson();
/**
* 添加到市场
*
* @param ctx
* @throws IOException
*/
@UserRoleRequired(role = IUser.ROLE_ADMIN)
@PostMethod
@JSONOutputEnabled
public void add_to_market(RequestContext ctx) throws IOException {
long id = ctx.id();
Code code = Code.INSTANCE.Get(id);
if (code == null)
throw ctx.error("code_not_exist");
PluginCode sc = new PluginCode();
sc.setCodeid(id);
sc.setCreate_time(new Timestamp(new Date().getTime()));
sc.setCss(code.getCss());
sc.setHtml(code.getHtml());
sc.setJs(code.getJs());
sc.setUpdate_time(code.getUpdate_time());
if (0 < sc.Save()) {
ctx.print(gson.toJson(sc));
PluginCode.evictCache(PluginCode.INSTANCE.CacheRegion(),
PluginCode.NEW_LIST);
} else
throw ctx.error("operation_failed");
}
/**
* 更新到市场
*
* @param ctx
* @throws IOException
*/
@UserRoleRequired(role = IUser.ROLE_ADMIN)
@PostMethod
@JSONOutputEnabled
public void update_to_market(RequestContext ctx) throws IOException {
long id = ctx.id();
Code code = Code.INSTANCE.Get(id);
if (code == null)
throw ctx.error("code_not_exist");
PluginCode sc = PluginCode.INSTANCE.GetPluginCodeByCode(id);
if (sc == null)
throw ctx.error("code_not_in_square");
sc.setCss(code.getCss());
sc.setHtml(code.getHtml());
sc.setJs(code.getJs());
Timestamp time = new Timestamp(new Date().getTime());
sc.setUpdate_time(time);
sc.setCss(code.getCss());
sc.setHtml(code.getHtml());
sc.setJs(code.getJs());
sc.setUpdate_time(code.getUpdate_time());
if (sc.Update())
ctx.print(gson.toJson(sc));
else
throw ctx.error("operation_failed");
}
/**
* 从市场删除
*/
@UserRoleRequired(role = IUser.ROLE_ADMIN)
@PostMethod
@JSONOutputEnabled
public void delete_from_market(RequestContext ctx) throws IOException {
long id = ctx.id();
PluginCode sc = PluginCode.INSTANCE.Get(id);
if (sc == null)
throw ctx.error("square_code_null");
if (sc.Delete()) {
PluginCode.evictCache(PluginCode.INSTANCE.CacheRegion(),
PluginCode.NEW_LIST);
ctx.print(gson.toJson(sc));
} else
throw ctx.error("operation_failed");
}
/**
* 将代码设为插件
*
* @param ctx
* @throws IOException
*/
@UserRoleRequired
@PostMethod
@JSONOutputEnabled
public void set_code_plugin(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
int sys = ctx.param("sys", 0);
long id = ctx.id();
Code code = Code.INSTANCE.Get(id);
if (null == code)
throw ctx.error("code_not_exist");
Plugin plugin = Plugin.INSTANCE.GetPluginByCode(id);
Timestamp time = new Timestamp(new Date().getTime());
if (plugin == null) {
plugin = new Plugin();
plugin.setCode(id);
plugin.setUser(code.getUser());
plugin.setStatus(Plugin.UNCHECK);
plugin.setType((user.IsAdmin() && sys == 1) ? Plugin.SYS_PLUGIN
: Plugin.PLUGIN);
plugin.setCreate_time(time);
plugin.setUpdate_time(time);
if (0 < plugin.Save()) {
ctx.print(gson.toJson(code));
} else
throw ctx.error("operation_failed");
} else
throw ctx.error("plugin_exist");
}
@UserRoleRequired(role = IUser.ROLE_ADMIN)
@PostMethod
@JSONOutputEnabled
public void create_sys_plugin(RequestContext ctx) throws IOException {
create_plugin(ctx, Plugin.SYS_PLUGIN);
}
@UserRoleRequired
@PostMethod
@JSONOutputEnabled
public void create_normal_plugin(RequestContext ctx) throws IOException {
create_plugin(ctx, Plugin.PLUGIN);
}
/**
* 添加系统插件
*
* @param ctx
* @throws IOException
*/
@SuppressWarnings("rawtypes")
@UserRoleRequired(role = IUser.ROLE_ADMIN)
@PostMethod
@JSONOutputEnabled
public void add_sys_plugin(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
File file = ctx.file("file");
if (null == file)
throw ctx.error("file_not_found");
// 判断是否超出大小限制
if (file.length() > UserFile.MAX_SIZE)
throw ctx.error("user_file_max_size", UserFile.MAX_SIZE
/ (1024 * 1024));
String pro_name = ctx.param("name", "");
if (pro_name.length() < 1 || pro_name.length() > 20)
throw ctx.error("pro_name_invalid");
// 判断该用户是否已经存在该项目,项目名不能重名。
if (Project.isProjectExist(pro_name, user.getId()))
throw ctx.error("pro_exist");
String html = "";
String js = "";
String css = "";
try {
ZipFile zip = new ZipFile(file);
Enumeration e = zip.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
if (!ze.isDirectory()) {
String name = ze.getName();
if (FilenameUtils.isExtension(name, "html"))
html = IOUtils
.toString(zip.getInputStream(ze), "utf-8");
else if (FilenameUtils.isExtension(name, "js"))
js = IOUtils.toString(zip.getInputStream(ze), "utf-8");
else if (FilenameUtils.isExtension(name, "css"))
css = IOUtils.toString(zip.getInputStream(ze), "utf-8");
}
}
zip.close();
if (StringUtils.isBlank(html) && StringUtils.isBlank(js)
&& StringUtils.isBlank(css))
throw ctx.error("file_code_null");
Code code = new Code();
code.setName(pro_name);
code.setCss(css);
code.setJs(js);
code.setHtml(html);
code.setUser(user.getId());
code.setNum(Project.INIT_VERSION);
Timestamp time = new Timestamp(new Date().getTime());
code.setCreate_time(time);
code.setUpdate_time(time);
Project p = new Project();
p.setName(pro_name);
p.setUser(user.getId());
p.setVersion(Project.INIT_VERSION);
p.setCreate_time(time);
p.setUpdate_time(time);
long pid = p.Save();
if (0 < pid) {
// 清除用户项目列表的缓存
Project.evictCache(p.CacheRegion(), Project.USER_PRO_LIST
+ user.getId());
code.setProject(pid);
long cid = code.Save();
if (0 < cid) {
Plugin plugin = new Plugin();
plugin.setCode(cid);
plugin.setUser(code.getUser());
plugin.setStatus(Plugin.UNCHECK);
plugin.setType(Plugin.SYS_PLUGIN);
plugin.setCreate_time(time);
plugin.setUpdate_time(time);
if (0 < plugin.Save()) {
ctx.print(gson.toJson(code));
} else {
code.Delete();
p.Delete();
throw ctx.error("operation_failed");
}
} else {
p.Delete();
throw ctx.error("operation_failed");
}
} else
throw ctx.error("operation_failed");
} catch (ZipException e) {
e.printStackTrace();
throw ctx.error("zip_not_valid");
}
}
@UserRoleRequired
@PostMethod
@JSONOutputEnabled
public void check(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
long id = ctx.id();
Plugin plugin = Plugin.INSTANCE.Get(id);
if (plugin == null) {
throw ctx.error("plugin_not_exist");
}
if (!user.IsAdmin(plugin))
throw ctx.error("operation_forbidden");
plugin.setStatus(Plugin.CHECKED);
plugin.UpdateField("status", Plugin.CHECKED);
plugin.EvictListCache();
Plugin.evictCache(plugin.CacheRegion(),
Plugin.PLUGIN_CODE + plugin.getCode());
ctx.print(gson.toJson(plugin));
}
@UserRoleRequired
@PostMethod
@JSONOutputEnabled
public void uncheck(RequestContext ctx) throws IOException {
User user = (User) ctx.user();
long id = ctx.id();
Plugin plugin = Plugin.INSTANCE.Get(id);
if (plugin == null) {
throw ctx.error("plugin_not_exist");
}
if (!user.IsAdmin(plugin))
throw ctx.error("operation_forbidden");
plugin.setStatus(Plugin.UNCHECK);
plugin.UpdateField("status", Plugin.UNCHECK);
plugin.EvictListCache();
Plugin.evictCache(plugin.CacheRegion(),
Plugin.PLUGIN_CODE + plugin.getCode());
ctx.print(gson.toJson(plugin));
}
/**
* 创建不同类型的插件
*
* @param ctx
* @param type
* @throws IOException
*/
private void create_plugin(RequestContext ctx, int type) throws IOException {
User user = (User) ctx.user();
String pro_name = ctx.param("name", "");
if (pro_name.length() < 1 || pro_name.length() > 20)
throw ctx.error("pro_name_invalid");
// 判断该用户是否已经存在该项目,项目名不能重名。
if (Project.isProjectExist(pro_name, user.getId()))
throw ctx.error("pro_exist");
String html = ctx.param("html", "");
String js = ctx.param("js", "");
String css = ctx.param("css", "");
Timestamp time = new Timestamp(new Date().getTime());
Code code = new Code();
code.setName(pro_name);
code.setCss(css);
code.setJs(js);
code.setHtml(html);
code.setUser(user.getId());
code.setNum(Project.INIT_VERSION);
code.setCreate_time(time);
code.setUpdate_time(time);
code.setCode_type(Code.DEFAULT_TYPE);
Project p = new Project();
p.setName(pro_name);
p.setUser(user.getId());
p.setVersion(Project.INIT_VERSION);
p.setCreate_time(time);
p.setUpdate_time(time);
long pid = p.Save();
if (0 < pid) {
// 清除用户项目列表的缓存
Project.evictCache(p.CacheRegion(),
Project.USER_PRO_LIST + user.getId());
code.setProject(pid);
long cid = code.Save();
if (0 < cid) {
Plugin plugin = new Plugin();
plugin.setCode(cid);
plugin.setUser(code.getUser());
plugin.setStatus(Plugin.UNCHECK);
plugin.setType(type);
plugin.setCreate_time(time);
plugin.setUpdate_time(time);
if (0 < plugin.Save()) {
ctx.print(gson.toJson(code));
} else {
code.Delete();
p.Delete();
throw ctx.error("operation_failed");
}
} else {
p.Delete();
throw ctx.error("operation_failed");
}
} else
throw ctx.error("operation_failed");
}
/*
* public void install(RequestContext ctx) throws IOException { User user =
* (User) ctx.user(); long id = ctx.id(); Code fork_code =
* Code.INSTANCE.Get(id); if (null == fork_code) throw
* ctx.error("code_not_exist"); if (fork_code.IsPosted()) throw
* ctx.error("code_not_publish"); Timestamp time = new Timestamp(new
* Date().getTime()); // 克隆代码 Code code = new Code();
* code.setName(fork_code.getName()+"_"+fork_code.getIdent());
* code.setFork(fork_code.getId()); code.setUser(user.getId()); //
* 清除fork列表缓存 Code.evictCache(code.CacheRegion(), Code.FORK_LIST +
* code.getFork()); code.setProject(0); code.setCss(fork_code.getCss());
* code.setHtml(fork_code.getHtml()); code.setJs(fork_code.getJs());
* code.setNum(1); code.setCreate_time(time); code.setUpdate_time(time);
* code.setCode_type(fork_code.getCode_type()); code.setId(code.Save()); if
* (0 != code.getId()) { // 添加动态 Dynamic.INSTANCE.add_fork_dy(code); if
* (fork_code.getUser() != code.getUser()) { // 添加通知 String notify =
* ResourceUtils.getString("description", "fork_notify", user.getName(),
* fork_code.getIdent(), fork_code.getName(), code.getIdent());
* Msg.INSTANCE.addMsg(code.getUser(), fork_code.getUser(), Msg.NULL_REFER,
* Msg.TYPE_FORK, notify); } Code.evictCache(code.CacheRegion(),
* Code.FORK_COUNT + fork_code.getId()); } else throw
* ctx.error("operation_failed"); Plugin plugin =
* Plugin.INSTANCE.GetPluginByCode(id); plugin = new Plugin();
* plugin.setCode(code.getId()); plugin.setUser(user.getId());
* plugin.setStatus(Plugin.UNCHECK); plugin.setType(Plugin.PLUGIN);
* plugin.setCreate_time(time); plugin.setUpdate_time(time); if (0 <
* plugin.Save()) { ctx.print(gson.toJson(code)); } else throw
* ctx.error("operation_failed"); }
*/
} | gpl-3.0 |
skurski/know-how | src/main/java/know/how/reflection/InfoAboutClass.java | 2501 | package know.how.reflection;
import java.io.Serializable;
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class InfoAboutClass {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
// 3 ways to get object of Class
Class clazz = Class.forName("know.how.reflection.Example");
// Class clazz = knowhow.reflection.Example.class;
// Class clazz = new Example().getClass();
Object objInFly = clazz.newInstance();
Class[] interfaces = clazz.getInterfaces();
for (Class cls : interfaces) {
System.out.println("Interface: " + cls.getName());
}
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Object value = field.get(objInFly);
TestAnnotation ann = field.getAnnotation(TestAnnotation.class);
System.out.println("Field name: " + field.getName()
+ ", value: " + value
+ ", annotation: " + ann.value());
}
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println("Method name: " + method.getName());
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println("Method annotation: "
+ annotation.toString());
}
Class[] parameters = method.getParameterTypes();
for (Class cls : parameters) {
System.out.println("Method parameter: " + cls.getName());
}
//invoke method
Object[] params = {new ArrayList<String>(), 10};
method.invoke(objInFly, params);
}
}
}
class Example implements Serializable {
@TestAnnotation
private String text = "Text";
@TestAnnotation(value = "another")
private int number = 10;
public Example() {
}
@Deprecated
public void run(List<String> list, int num) {
System.out.println("Method run executed");
}
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface TestAnnotation {
String value() default "initial";
}
| gpl-3.0 |
pantelis60/L2Scripts_Underground | gameserver/src/main/java/l2s/gameserver/data/xml/parser/SpawnParser.java | 7093 | package l2s.gameserver.data.xml.parser;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.dom4j.Element;
import l2s.commons.collections.MultiValueSet;
import l2s.commons.data.xml.AbstractDirParser;
import l2s.commons.geometry.Circle;
import l2s.commons.geometry.Polygon;
import l2s.commons.geometry.Rectangle;
import l2s.gameserver.Config;
import l2s.gameserver.data.xml.holder.SpawnHolder;
import l2s.gameserver.model.Territory;
import l2s.gameserver.templates.StatsSet;
import l2s.gameserver.templates.spawn.PeriodOfDay;
import l2s.gameserver.templates.spawn.SpawnNpcInfo;
import l2s.gameserver.templates.spawn.SpawnTemplate;
import l2s.gameserver.utils.Location;
/**
* @author VISTALL
* @date 18:38/10.12.2010
*/
public final class SpawnParser extends AbstractDirParser<SpawnHolder>
{
private static final SpawnParser _instance = new SpawnParser();
public static SpawnParser getInstance()
{
return _instance;
}
protected SpawnParser()
{
super(SpawnHolder.getInstance());
}
@Override
public File getXMLDir()
{
return new File(Config.DATAPACK_ROOT, "data/spawn/");
}
@Override
public boolean isIgnored(File f)
{
return false;
}
@Override
protected void readData(Element rootElement) throws Exception
{
Map<String, Territory> territories = new HashMap<String, Territory>();
for(Iterator<Element> spawnIterator = rootElement.elementIterator(); spawnIterator.hasNext();)
{
Element spawnElement = spawnIterator.next();
if(spawnElement.getName().equalsIgnoreCase("territory"))
{
String terName = spawnElement.attributeValue("name");
Territory territory = parseTerritory(terName, spawnElement);
territories.put(terName, territory);
}
else if(spawnElement.getName().equalsIgnoreCase("spawn"))
{
String group = spawnElement.attributeValue("group");
String name = spawnElement.attributeValue("name") == null ? (group == null ? "" : group) : spawnElement.attributeValue("name");
int respawn = spawnElement.attributeValue("respawn") == null ? 60 : Integer.parseInt(spawnElement.attributeValue("respawn"));
int respawnRandom = spawnElement.attributeValue("respawn_random") == null ? 0 : Integer.parseInt(spawnElement.attributeValue("respawn_random"));
int count = spawnElement.attributeValue("count") == null ? 1 : Integer.parseInt(spawnElement.attributeValue("count"));
PeriodOfDay periodOfDay = spawnElement.attributeValue("period_of_day") == null ? PeriodOfDay.NONE : PeriodOfDay.valueOf(spawnElement.attributeValue("period_of_day").toUpperCase());
if(group == null)
group = periodOfDay.name();
SpawnTemplate template = new SpawnTemplate(name, periodOfDay, count, respawn, respawnRandom);
for(Iterator<Element> subIterator = spawnElement.elementIterator(); subIterator.hasNext();)
{
Element subElement = subIterator.next();
if(subElement.getName().equalsIgnoreCase("point"))
{
int x = Integer.parseInt(subElement.attributeValue("x"));
int y = Integer.parseInt(subElement.attributeValue("y"));
int z = Integer.parseInt(subElement.attributeValue("z"));
int h = subElement.attributeValue("h") == null ? -1 : Integer.parseInt(subElement.attributeValue("h"));
template.addSpawnRange(new Location(x, y, z, h));
}
else if(subElement.getName().equalsIgnoreCase("rectangle"))
{
int x1 = Integer.parseInt(subElement.attributeValue("x1"));
int y1 = Integer.parseInt(subElement.attributeValue("y1"));
int x2 = Integer.parseInt(subElement.attributeValue("x2"));
int y2 = Integer.parseInt(subElement.attributeValue("y2"));
int zmin = Integer.parseInt(subElement.attributeValue("zmin"));
int zmax = Integer.parseInt(subElement.attributeValue("zmax"));
Rectangle rectangle = new Rectangle(x1, y1, x2, y2);
rectangle.setZmin(zmin);
rectangle.setZmax(zmax);
Territory territory = new Territory();
territory.add(rectangle);
template.addSpawnRange(territory);
}
else if(subElement.getName().equalsIgnoreCase("circle"))
{
int x = Integer.parseInt(subElement.attributeValue("x"));
int y = Integer.parseInt(subElement.attributeValue("y"));
int zmin = Integer.parseInt(subElement.attributeValue("zmin"));
int zmax = Integer.parseInt(subElement.attributeValue("zmax"));
int radius = Integer.parseInt(subElement.attributeValue("radius"));
Circle circle = new Circle(x, y, radius);
circle.setZmin(zmin);
circle.setZmax(zmax);
Territory territory = new Territory();
territory.add(circle);
template.addSpawnRange(territory);
}
else if(subElement.getName().equalsIgnoreCase("territory"))
{
String terName = subElement.attributeValue("name");
if(terName != null)
{
Territory g = territories.get(terName);
if(g == null)
{
error("Invalid territory name: " + terName + "; " + getCurrentFileName());
continue;
}
template.addSpawnRange(g);
}
else
{
Territory temp = parseTerritory(null, subElement);
template.addSpawnRange(temp);
}
}
else if(subElement.getName().equalsIgnoreCase("npc"))
{
int npcId = Integer.parseInt(subElement.attributeValue("id"));
int max = subElement.attributeValue("max") == null ? 0 : Integer.parseInt(subElement.attributeValue("max"));
MultiValueSet<String> parameters = StatsSet.EMPTY;
for(Element e : subElement.elements())
{
if(parameters.isEmpty())
parameters = new MultiValueSet<String>();
parameters.set(e.attributeValue("name"), e.attributeValue("value"));
}
template.addNpc(new SpawnNpcInfo(npcId, max, parameters));
}
}
if(template.getNpcSize() == 0)
{
warn("Npc id is zero! File: " + getCurrentFileName());
continue;
}
if(template.getSpawnRangeSize() == 0)
{
warn("No points to spawn! File: " + getCurrentFileName());
continue;
}
getHolder().addSpawn(group, template);
}
}
}
private Territory parseTerritory(String name, Element e)
{
Territory t = new Territory();
t.add(parsePolygon0(name, e));
for(Iterator<Element> iterator = e.elementIterator("banned_territory"); iterator.hasNext();)
t.addBanned(parsePolygon0(name, iterator.next()));
return t;
}
private Polygon parsePolygon0(String name, Element e)
{
Polygon temp = new Polygon();
for(Iterator<Element> addIterator = e.elementIterator("add"); addIterator.hasNext();)
{
Element addElement = addIterator.next();
int x = Integer.parseInt(addElement.attributeValue("x"));
int y = Integer.parseInt(addElement.attributeValue("y"));
int zmin = Integer.parseInt(addElement.attributeValue("zmin"));
int zmax = Integer.parseInt(addElement.attributeValue("zmax"));
temp.add(x, y).setZmin(zmin).setZmax(zmax);
}
if(!temp.validate())
error("Invalid polygon: " + name + "{" + temp + "}. File: " + getCurrentFileName());
return temp;
}
}
| gpl-3.0 |
rforge/biocep | src_patch_iplots/org/rosuda/ibase/SVarDouble.java | 15733 | //
// SVarDouble.java
// Klimt
//
// Created by Simon Urbanek on Fri Nov 14 2003.
// Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//
package org.rosuda.ibase;
import java.util.*;
import org.rosuda.util.*;
/** SVar implementation for ed-length doubles variable
*/
public class SVarDouble extends SVar {
/** the actual content */
public double[] cont;
/** insertion point for add */
int insertPos=0;
/** list of categories if cat. var. */
List cats;
/** list if counts per category */
List ccnts;
int[] ranks=null;
static double[] temp;
/** construct new variable
* @param Name variable name
* @param len length of the ed variable
*/
public SVarDouble(String Name, int len) {
super(Name, false);
if (len<0) len=0;
guessing=false;
contentsType=CT_Number;
isnum=true;
cont=new double[len];
for (int i = 0; i < cont.length; i++) cont[i] = Double.NaN;
insertPos = len;
}
public SVarDouble(String Name, double[] d) {
this(Name, d, true);
}
public SVarDouble(String Name, double[] d, boolean copyContents) {
super(Name, false);
if (copyContents) {
cont=new double[d.length];
System.arraycopy(d, 0, cont, 0, d.length);
} else cont=d;
updateCache();
insertPos=d.length;
guessing=false;
contentsType=CT_Number;
isnum=true;
}
private void updateCache() {
boolean firstValid=true;
min=max=0;
int i=0;
while (i<cont.length) {
if (Double.isNaN(cont[i])) missingCount++;
else {
if (firstValid) {
min=max=cont[i];
firstValid=false;
} else {
if (cont[i]>max) max=cont[i]; else
if (cont[i]<min) min=cont[i];
}
}
i++;
}
}
public int size() { return cont.length; }
/** define the variable explicitely as categorical
* @param rebuild if set to <code>true</code> force rebuild even if the variable is already categorial. */
public void categorize(boolean rebuild) {
if (cat && !rebuild) return;
cats=new ArrayList(); ccnts=new ArrayList();
cat=true;
if (!isEmpty()) {
int ci=0;
while (ci<cont.length) {
String oo=Double.isNaN(cont[ci])?missingCat:Double.toString(cont[ci]);
int i=cats.indexOf(oo);
if (i==-1) {
cats.add(oo);
ccnts.add(new Integer(1));
} else {
ccnts.set(i,new Integer(((Integer)ccnts.get(i)).intValue()+1));
}
ci++;
}
if (isNum()) { // if numerical and categorical then sort categories for convenience
sortCategories(SM_num);
}
}
NotifyAll(new NotifyMsg(this,Common.NM_VarTypeChange));
}
/** sort categories by specifeid method
* @param method sort method, see SM_xxx constants */
public void sortCategories(int method) {
if (!isCat() || cats.size()<2) return;
Stopwatch sw=null;
if (Global.DEBUG>0) {
sw=new Stopwatch();
System.out.println("Sorting variable \""+name+"\"");
}
List ocats=cats; List occnts=ccnts;
cats=new ArrayList(ocats.size()); ccnts=new ArrayList(occnts.size());
boolean found=true;
int cs=ocats.size();
while (found) {
found=false; int i=0,p=-1;
double min=-0.01; boolean gotmin=false;
String mino=null;
while (i<cs) {
Object o=ocats.get(i);
if (o!=null) {
if (method==SM_num) {
double val=-0.01;
try {
val=((Number)o).doubleValue();
} catch(Exception e) {};
if (!gotmin) {
gotmin=true; min=val; p=i;
} else {
if (val<min) {
min=val; p=i;
}
}
} else {
if (!gotmin) {
gotmin=true; mino=o.toString(); p=i;
} else {
if (mino.compareTo(o.toString())>0) {
mino=o.toString(); p=i;
}
}
}
}
i++;
}
if (found=gotmin) {
cats.add(ocats.get(p)); ccnts.add(occnts.get(p));
ocats.set(p,null);
}
}
if (Global.DEBUG>0) {
sw.profile("sorted");
}
}
/** define the variable explicitely as non-categorial (drop category list) */
public void dropCat() {
cats=null; ccnts=null; cat=false;
NotifyAll(new NotifyMsg(this,Common.NM_VarTypeChange));
}
public void setCategorical(boolean nc) {
if (!nc) {
cat=false;
} else {
if (cats==null) categorize(); else cat=true;
}
}
/** adds a new case to the variable (NEVER use addElement! see package header) Also beware, categorial varaibles are classified by object not by value!
* @param o object to be added. First call to <code>add</code> (even implicit if an object was specified on the call to the constructor) does also decide whether the variable will be numeric or not. If the first object is a subclass of <code>Number</code> then the variable is defined as numeric. There is a significant difference in handling numeric and non-numeric variabels, see package header.
* @return <code>true<code> if element was successfully added, or <code>false</code> upon failure - currently when non-numerical value is inserted in a numerical variable. It is strongly recommended to check the result and act upon it, because failing to do so can result in non-consistent datasets - i.e. mismatched row IDs */
public boolean add(Object o) {
if (insertPos>=cont.length) return false;
if (cacheRanks && ranks!=null) ranks=null; // remove ranks - we don't update them so far...
double val=double_NA;
if (o!=null) {
try {
val=Double.parseDouble(o.toString());
} catch(NumberFormatException nfe) {
return false;
}
}
return add(val);
}
public boolean add(int i) { return add((i==int_NA)?double_NA:((double)i)); }
public boolean add(double d) {
if (insertPos>=cont.length) return false;
if (cat) {
Object oo=Double.isNaN(d)?missingCat:Double.toString(d);
int i=cats.indexOf(oo);
if (i==-1) {
cats.add(oo);
ccnts.add(new Integer(1));
} else {
ccnts.set(i,new Integer(((Integer)ccnts.get(i)).intValue()+1));
}
}
if (!Double.isNaN(d)) {
if (d>max) max=d;
if (d<min) min=d;
} else
missingCount++;
cont[insertPos++]=d;
NotifyAll(new NotifyMsg(this,Common.NM_VarContentChange));
return true;
}
/** replaces an element at specified position - use with care!. this doesn't work for categorical variables.
* in that case you need to dropCat(), make modifications and categorize().
* also numerical variables only "grow" their min/max - i.e. if min/max was the removed
* element, then min/max is not adapted to shrink the range
*/
public boolean replace(int i, Object o) {
try {replace(i,Double.parseDouble(o.toString())); return true;} catch (Exception e) {}
return false;
}
public boolean replace(int i, double d) {
if (i<0 || i>=cont.length || isCat()) return false;
if (Double.isNaN(cont[i])) missingCount--;
cont[i]=d;
if (Double.isNaN(d)) missingCount++;
return true;
}
public boolean replaceAll(double d[]) {
if (cont.length != d.length) return false;
System.arraycopy(d, 0, cont, 0, d.length);
updateCache();
return true;
}
public boolean replaceAll(int i[]) {
if (cont.length != i.length) return false;
int j=0;
while (j<i.length) {
cont[j]=(i[j]==int_NA)?double_NA:i[j];
j++;
}
updateCache();
return true;
}
public Object at(int i) {
return (i<0||i>=insertPos||Double.isNaN(cont[i]))?null:new Double(cont[i]);
}
public double atD(int i) { return (i<0||i>=insertPos)?double_NA:cont[i]; }
public double atF(int i) { return (i<0||i>=insertPos)?0:cont[i]; }
public int atI(int i) { return (i<0||i>=insertPos||Double.isNaN(cont[i]))?int_NA:((int)(cont[i]+0.5)); }
public String asS(int i) { return (i<0||i>=insertPos||isNA(cont[i]))?null:Double.toString(cont[i]); }
/** returns the ID of the category of the object
* @param object
* @return category ID
*/
public int getCatIndex(Object o) {
if (cats==null) return -1;
Object oo=o; if(o==null) oo=missingCat;
return cats.indexOf(oo);
}
/** returns ID of the category of i-th case in the variable or -1 if i oob */
public int getCatIndex(int i) {
try {
return getCatIndex(elementAt(i));
} catch (Exception e) {
return -1;
}
}
/** returns the category with index ID or <code>null</code> if variable is not categorial */
public Object getCatAt(int i) {
if (cats==null) return null;
try {
return cats.get(i);
} catch (Exception e) {
return null;
}
}
/** returns size of the category with index ID or -1 if variable is not categorial or index oob */
public int getSizeCatAt(int i) {
if (cats==null) return -1;
try { // catch exception if cat ID is out of bounds
return ((Integer)ccnts.get(i)).intValue();
} catch (Exception e) {
return -1;
}
}
/** returns size of the category o. If category does not exist or variable is not categorial, -1 is returned. */
public int getSizeCat(Object o) {
if (cats==null) return -1;
int i=cats.indexOf(o);
return (i==1)?-1:((Integer)ccnts.get(i)).intValue();
}
/** returns the number of categories for this variable or 0 if the variable is not categorial */
public int getNumCats() {
if (cats==null) return 0;
return cats.size();
}
/** returns new, ed array of categories */
public Object[] getCategories() {
if (cats==null) return null;
Object c[] = new Object[cats.size()];
cats.toArray(c);
return c;
}
/** we don't support replace [[ME: replace needs to re-alloc the vector or something like that ... ]] */
public boolean remove(int index) {
int length = size();
temp = new double[--length];
try {
for (int i = 0, z = 0; z < cont.length && i < temp.length; i++, z++) {
if (i == index) z++;
temp[i] = cont[z];
}
cont = temp;
insertPos = cont.length;
return true;
} catch (Exception e) {
return false;
}
}
public boolean insert(Object o, int index) {
int length = size();
temp = new double[++length];
try {
for (int i = 0, z = 0; z < cont.length && i < temp.length; i++, z++) {
if (i == index) z--;
else temp[i] = cont[z];
}
cont = temp;
cont[index] = o==null?double_NA:Double.parseDouble(o.toString());
insertPos = cont.length;
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/** returns list of indexes ordered by rank, for non-cat, num vars only. missing
* values are omitted.
* @param v variable (should be obtained by at(..))
* @param m marker to use for filtering. if <code>null</code> all cases will be checked
* @param markspec mark for filtering, i.e. cases with that mark will be used only
* @return list of indexes or <code>null</code> is any of the following
* cases: variable is not numerical or is categorical, no cases matching
* specification are present */
public int[] getRanked(SMarkerInterface m, int markspec) {
Stopwatch sw=new Stopwatch();
if (isCat() || !isNum() || size()==0) return null;
if (m==null && cacheRanks && ranks!=null) return ranks; // we can cache only ranks w/o a marker
int[] r=null;
/* okay in fact we always get the full ranks and then pick those marked (if desired) */
if (!cacheRanks || ranks==null) {
int ct=size();
r = new int[ct];
double[] da = cont;
sw.profile("getRanked: pass 1: store relevant values");
// use Collections.sort to compute the ranks
class SortDouble implements Comparable{
double d;
int index;
public SortDouble(double d, int index){
this.d=d;
this.index=index;
}
public int compareTo(Object o) {
double od = ((SortDouble)o).d;
if(od>d) return -1;
if(od<d) return 1;
return 0;
}
}
List data = new ArrayList(da.length);
for(int i=0; i<da.length; i++) data.add(new SortDouble(da[i],i));
Collections.sort(data);
for(int i=0; i<da.length; i++) r[i] = ((SortDouble)data.get(i)).index;
} else {
r=ranks;
}
// we got the full list - now we need to thin it out if a marker was specified
if (m!=null && r!=null) {
int x=r.length;
int ct=0;
int i=0; // pass 1 : find the # of relevant cases
while(i<x) {
if (m.get(i)==markspec)
ct++;
i++;
}
if (ct==0) return null;
int[] mr=new int[ct];
i=0;
int mri=0;
while(i<x) {
if (m.get(r[i])==markspec)
mr[mri++]=r[i];
i++;
}
r=null;
r=mr;
}
// return the resulting list
return r;
}
public boolean hasEqualContents(double d2[]) {
if (cont.length!=d2.length) return false;
int i=0;
while (i<cont.length) {
if (cont[i]!=d2[i]) return false;
i++;
}
return true;
}
public String toString() {
return "SVarDouble(\""+name+"\","+(cat?"cat,":"cont,")+(isnum?"num,":"txt,")+"n="+size()+"/"+cont.length+",miss="+missingCount+")";
}
}
| gpl-3.0 |
chrisvdweth/onespace | android-application/app/src/main/java/com/sesame/onespace/service/fcm/FCMCallbackService.java | 5187 | package com.sesame.onespace.service.fcm;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.google.gson.JsonObject;
import com.sesame.onespace.R;
import com.sesame.onespace.activities.MainActivity;
import com.sesame.onespace.managers.SettingsManager;
import com.sesame.onespace.models.chat.ChatMessage;
import com.sesame.onespace.service.xmpp.QAMessageManager;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by christian on 1/2/17.
*/
public class FCMCallbackService extends FirebaseMessagingService {
private static final String TAG = "FCMCallbackService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
//Log.d(TAG, ">>>>>>>>>>> From:" + remoteMessage.getFrom());
//Log.d(TAG, ">>>>>>>>>>> Message Body:" + remoteMessage.getNotification().getBody());
//Log.d(TAG, ">>>>>>>>>>> Message Data:" + remoteMessage.getData());
//sendNotification(remoteMessage.getNotification());
String msgFrom;
String msgType;
String msgBody;
JSONObject dataJson;
dataJson = new JSONObject(remoteMessage.getData());
try {
msgFrom = dataJson.getString("msgfrom");
msgBody = dataJson.getString("msgbody");
JSONObject bodyJson = new JSONObject(msgBody);
msgType = bodyJson.getString("message-type");
} catch (JSONException e) {
Log.e(TAG, "[ERROR] FCMCallbackService.onMessageReceived() " + e);
return;
}
if (msgType.equalsIgnoreCase(ChatMessage.MessageType.QUERY.getString())){
QAMessageManager.getInstance(getApplicationContext()).addMessageBody(msgFrom, msgBody, "FCM");
}
}
// private void sendNotification(RemoteMessage.Notification notification) {
// //int color = getResources().getColor(R.color.not);
// Log.i(TAG, ">>>>>>>> sendNotification");
//
// Intent intent = new Intent(this, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
// PendingIntent.FLAG_ONE_SHOT);
//
// NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
// //.setContentTitle(notification.getTitle())
// //.setContentText(notification.getBody())
// .setContentTitle("OneSpace Notification:")
// .setContentText("You have received new questions.")
// .setAutoCancel(true)
// .setSmallIcon(R.drawable.ic_app_notification)
// //.setColor(color)
// .setStyle(new NotificationCompat.BigTextStyle().bigText("You have received new questions."))
// .setContentIntent(pendingIntent);
//
// Notification builtNotification = builder.build();
//
// SettingsManager settingsManager = SettingsManager.getSettingsManager(getApplicationContext());
//
// if (settingsManager.notificationSound)
// builtNotification.sound = Uri.parse(settingsManager.notificationRingtone);
//
// if (settingsManager.notificationVibrate)
// builtNotification.vibrate = new long[]{25, 100, 100, 200};
//
// Log.i(TAG, ">>>>>>>> LED setting???");
// if (settingsManager.notificationLED) {
// Log.i(TAG, ">>>>>>>> LED setting");
// builtNotification.ledOnMS = 1000;
// builtNotification.ledOffMS = 2000;
// builtNotification.ledARGB = Color.MAGENTA;
// builtNotification.flags |= Notification.FLAG_SHOW_LIGHTS;
// }
//
//
// NotificationManager notificationManager = (NotificationManager)
// getSystemService(Context.NOTIFICATION_SERVICE);
// com.sesame.onespace.utils.Log.i(">>>>>>>>>>>>>> Push put FCM Notification");
// notificationManager.notify(111222, builtNotification);
// }
} | gpl-3.0 |
DivineCooperation/bco.registry.editor | src/main/java/org/openbase/bco/registry/editor/struct/preset/RotationTreeItem.java | 3046 | package org.openbase.bco.registry.editor.struct.preset;
/*-
* #%L
* BCO Registry Editor
* %%
* Copyright (C) 2014 - 2020 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import com.google.protobuf.Descriptors.FieldDescriptor;
import javafx.scene.Node;
import javafx.scene.control.TreeTableCell;
import org.openbase.bco.registry.editor.struct.AbstractBuilderLeafTreeItem;
import org.openbase.bco.registry.editor.struct.ValueType;
import org.openbase.bco.registry.editor.struct.editing.RotationEditingGraphic;
import org.openbase.jul.exception.InitializationException;
import org.openbase.jul.processing.QuaternionEulerTransform;
import org.openbase.type.geometry.RotationType.Rotation.Builder;
import javax.vecmath.Quat4d;
import javax.vecmath.Vector3d;
import java.text.DecimalFormat;
/**
* @author <a href="mailto:pleminoq@openbase.org">Tamino Huxohl</a>
*/
public class RotationTreeItem extends AbstractBuilderLeafTreeItem<Builder> {
private final DecimalFormat decimalFormat;
public RotationTreeItem(FieldDescriptor fieldDescriptor, Builder builder, Boolean editable) throws InitializationException {
super(fieldDescriptor, builder, editable);
decimalFormat = new DecimalFormat("##.##");
}
@Override
protected String createValueRepresentation() {
final Vector3d euler;
/* Even though the rotation type has defined default values they do not seem to be used.
* Thus assume the default rotation as none.
* Tts enough to check if only qw is not set because these fields are required.
* So if one is not set then every other value is not set either.
*/
if (!getBuilder().hasQw()) {
euler = new Vector3d(0.0, 0.0, 0.0);
} else {
euler = QuaternionEulerTransform.transform(new Quat4d(getBuilder().getQx(), getBuilder().getQy(), getBuilder().getQz(), getBuilder().getQw()));
euler.x = Math.toDegrees(euler.x);
euler.y = Math.toDegrees(euler.y);
euler.z = Math.toDegrees(euler.z);
}
return "Roll = " + decimalFormat.format(euler.x) + ", Pitch = " + decimalFormat.format(euler.y) + ", Yaw = " + decimalFormat.format(euler.z);
}
@Override
public Node getEditingGraphic(TreeTableCell<ValueType, ValueType> cell) {
return new RotationEditingGraphic(getValueCasted(), cell).getControl();
}
}
| gpl-3.0 |
luozheng1985/Android-Animexxenger | src/de/meisterfuu/animexxenger/service/XmppConnectionAdapter.java | 24022 | /*
This Software(Animexxenger) is based on BEEM:\n\nBEEM is a videoconference application on the Android Platform.
Copyright (C) 2009 by Frederic-Charles Barthelery,
Jean-Manuel Da Silva,
Nikita Kozlov,
Philippe Lago,
Jean Baptiste Vergely,
Vincent Veronis.
This file is part of BEEM.
BEEM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
BEEM 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with BEEM. If not, see <http://www.gnu.org/licenses/>.
Please send bug reports with examples or suggestions to
contact@beem-project.com or http://dev.beem-project.com/
Epitech, hereby disclaims all copyright interest in the program "Beem"
written by Frederic-Charles Barthelery,
Jean-Manuel Da Silva,
Nikita Kozlov,
Philippe Lago,
Jean Baptiste Vergely,
Vincent Veronis.
Nicolas Sadirac, November 26, 2009
President of Epitech.
Flavien Astraud, November 26, 2009
Head of the EIP Laboratory.
*/
package de.meisterfuu.animexxenger.service;
import java.util.Iterator;
import java.util.List;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;
import de.meisterfuu.animexxenger.BeemApplication;
import de.meisterfuu.animexxenger.BeemService;
import de.meisterfuu.animexxenger.R;
import de.meisterfuu.animexxenger.service.aidl.IBeemConnectionListener;
import de.meisterfuu.animexxenger.service.aidl.IChatManager;
import de.meisterfuu.animexxenger.service.aidl.IRoster;
import de.meisterfuu.animexxenger.service.aidl.IXmppConnection;
import de.meisterfuu.animexxenger.smack.avatar.AvatarCache;
import de.meisterfuu.animexxenger.smack.avatar.AvatarListener;
import de.meisterfuu.animexxenger.smack.avatar.AvatarMetadataExtension;
import de.meisterfuu.animexxenger.smack.pep.PepSubManager;
import de.meisterfuu.animexxenger.smack.ping.PingExtension;
import de.meisterfuu.animexxenger.ui.ChangeStatus;
import de.meisterfuu.animexxenger.ui.ContactList;
import de.meisterfuu.animexxenger.ui.Subscription;
import de.meisterfuu.animexxenger.utils.BeemBroadcastReceiver;
import de.meisterfuu.animexxenger.utils.Status;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.PrivacyListManager;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.ChatStateManager;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.packet.DiscoverInfo;
/**
* This class implements an adapter for XMPPConnection.
*
* @author darisk
*/
public class XmppConnectionAdapter extends IXmppConnection.Stub {
/**
* Beem connection closed Intent name.
*/
private static final int SMACK_PRIORITY_MIN = -128;
private static final int SMACK_PRIORITY_MAX = 128;
private static final String TAG = "XMPPConnectionAdapter";
private final XMPPConnection mAdaptee;
private IChatManager mChatManager;
private final String mLogin;
private final String mPassword;
private String mResource;
private String mErrorMsg;
private RosterAdapter mRoster;
private int mPreviousPriority;
private int mPreviousMode;
private String mPreviousStatus;
private PrivacyListManagerAdapter mPrivacyListManager;
private ChatStateManager mChatStateManager;
private final BeemService mService;
private BeemApplication mApplication;
private BeemAvatarManager mAvatarManager;
private PepSubManager mPepManager;
private SharedPreferences mPref;
private final RemoteCallbackList<IBeemConnectionListener> mRemoteConnListeners = new RemoteCallbackList<IBeemConnectionListener>();
private final SubscribePacketListener mSubscribePacketListener = new SubscribePacketListener();
private final PingListener mPingListener = new PingListener();
private final ConnexionListenerAdapter mConListener = new ConnexionListenerAdapter();
private UserInfo mUserInfo;
private final UserInfoManager mUserInfoManager = new UserInfoManager();
/**
* Constructor.
*
* @param config
* Configuration to use in order to connect
* @param login
* login to use on connect
* @param password
* password to use on connect
* @param service
* the background service associated with the connection.
*/
public XmppConnectionAdapter(final ConnectionConfiguration config, final String login, final String password, final BeemService service) {
this(new XMPPConnection(config), login, password, service);
}
/**
* Constructor.
*
* @param serviceName
* name of the service to connect to
* @param login
* login to use on connect
* @param password
* password to use on connect
* @param service
* the background service associated with the connection.
*/
public XmppConnectionAdapter(final String serviceName, final String login, final String password, final BeemService service) {
this(new XMPPConnection(serviceName), login, password, service);
}
/**
* Constructor.
*
* @param con
* The connection to adapt
* @param login
* The login to use
* @param password
* The password to use
* @param service
* the background service associated with the connection.
*/
public XmppConnectionAdapter(final XMPPConnection con, final String login, final String password, final BeemService service) {
mAdaptee = con;
PrivacyListManager.getInstanceFor(mAdaptee);
mLogin = login;
mPassword = password;
mService = service;
Context ctx = mService.getApplicationContext();
if (ctx instanceof BeemApplication) {
mApplication = (BeemApplication) ctx;
}
mPref = mService.getServicePreference();
try {
mPreviousPriority = Integer.parseInt(mPref.getString(BeemApplication.CONNECTION_PRIORITY_KEY, "0"));
} catch (NumberFormatException ex) {
mPreviousPriority = 0;
}
mResource = mPref.getString(BeemApplication.CONNECTION_RESOURCE_KEY, "Android Animexxenger");
}
/**
* {@inheritDoc}
*/
@Override
public void addConnectionListener(IBeemConnectionListener listen) throws RemoteException {
if (listen != null) mRemoteConnListeners.register(listen);
}
@Override
public boolean connect() throws RemoteException {
if (mAdaptee.isConnected())
return true;
else {
try {
mAdaptee.connect();
mAdaptee.addConnectionListener(mConListener);
return true;
} catch (XMPPException e) {
Log.e(TAG, "Error while connecting", e);
try {
// TODO NIKITA DOES SOME SHIT !!! Fix this monstruosity
String str = mService.getResources().getString(
mService.getResources().getIdentifier(e.getXMPPError().getCondition().replace("-", "_"), "string", "de.meisterfuu.animexxenger"));
mErrorMsg = str;
} catch (NullPointerException e2) {
if (!"".equals(e.getMessage()))
mErrorMsg = e.getMessage();
else
mErrorMsg = e.toString();
}
}
return false;
}
}
@Override
public boolean login() throws RemoteException {
if (mAdaptee.isAuthenticated()) return true;
if (!mAdaptee.isConnected()) return false;
try {
this.initFeatures(); // pour declarer les features xmpp qu'on
// supporte
PacketFilter filter = new PacketFilter() {
@Override
public boolean accept(Packet packet) {
if (packet instanceof Presence) {
Presence pres = (Presence) packet;
if (pres.getType() == Presence.Type.subscribe) return true;
}
return false;
}
};
mAdaptee.addPacketListener(mSubscribePacketListener, filter);
filter = new PacketTypeFilter(PingExtension.class);
mAdaptee.addPacketListener(mPingListener, filter);
mAdaptee.login(mLogin, mPassword, mResource);
mUserInfo = new UserInfo(mAdaptee.getUser());
mChatManager = new BeemChatManager(mAdaptee.getChatManager(), mService, mAdaptee.getRoster());
// nikita: I commented this line because of the logs provided in http://www.beem-project.com/issues/321
// Also, since the privacylistmanager isn't finished and used, it will be safer to not initialize it
// mPrivacyListManager = new PrivacyListManagerAdapter(PrivacyListManager.getInstanceFor(mAdaptee));
mService.initJingle(mAdaptee);
discoverServerFeatures();
mRoster = new RosterAdapter(mAdaptee.getRoster(), mService, mAvatarManager);
mApplication.setConnected(true);
int mode = mPref.getInt(BeemApplication.STATUS_KEY, 0);
String status = mPref.getString(BeemApplication.STATUS_TEXT_KEY, "");
changeStatus(mode, status);
return true;
} catch (XMPPException e) {
Log.e(TAG, "Error while connecting", e);
mErrorMsg = mService.getString(R.string.error_login_authentication);
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public final void connectAsync() throws RemoteException {
if (mAdaptee.isConnected() || mAdaptee.isAuthenticated()) return;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
connectSync();
} catch (RemoteException e) {
Log.e(TAG, "Error while connecting asynchronously", e);
}
}
});
t.start();
}
/**
* {@inheritDoc}
*/
@Override
public boolean connectSync() throws RemoteException {
if (connect()) return login();
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void changeStatusAndPriority(int status, String msg, int priority) {
Presence pres = new Presence(Presence.Type.available);
String m;
if (msg != null)
m = msg;
else
m = mPreviousStatus;
pres.setStatus(m);
mPreviousStatus = m;
Presence.Mode mode = Status.getPresenceModeFromStatus(status);
if (mode != null) {
pres.setMode(mode);
mPreviousMode = status;
} else {
pres.setMode(Status.getPresenceModeFromStatus(mPreviousMode));
}
int p = priority;
if (priority < SMACK_PRIORITY_MIN) p = SMACK_PRIORITY_MIN;
if (priority > SMACK_PRIORITY_MAX) p = SMACK_PRIORITY_MAX;
mPreviousPriority = p;
pres.setPriority(p);
mAdaptee.sendPacket(pres);
updateNotification(Status.getStatusFromPresence(pres), m);
}
/**
* {@inheritDoc}
*/
@Override
public void changeStatus(int status, String msg) {
changeStatusAndPriority(status, msg, mPreviousPriority);
}
/**
* Get the AvatarManager of this connection.
*
* @return the AvatarManager or null if there is not
*/
public BeemAvatarManager getAvatarManager() {
return mAvatarManager;
}
/**
* get the previous status.
*
* @return previous status.
*/
public String getPreviousStatus() {
return mPreviousStatus;
}
/**
* get the previous mode.
*
* @return previous mode.
*/
public int getPreviousMode() {
return mPreviousMode;
}
/**
* Update the notification for the Beem status.
*
* @param status
* the status to display.
* @param text
* the text to display.
*/
private void updateNotification(int status, String text) {
Notification mStatusNotification;
mStatusNotification = new Notification(Status.getIconBarFromStatus(status), text, System.currentTimeMillis());
mStatusNotification.defaults = Notification.DEFAULT_LIGHTS;
mStatusNotification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
mStatusNotification.setLatestEventInfo(mService, "Animexxenger", text, PendingIntent.getActivity(mService, 0, new Intent(mService, ContactList.class), 0));
// bypass the preferences for notification
mService.getNotificationManager().notify(BeemService.NOTIFICATION_STATUS_ID, mStatusNotification);
}
/**
* {@inheritDoc}
*/
@Override
public boolean disconnect() {
if (mAdaptee != null && mAdaptee.isConnected()) mAdaptee.disconnect();
return true;
}
/**
* Get the Smack XmppConnection.
*
* @return Smack XmppConnection
*/
public XMPPConnection getAdaptee() {
return mAdaptee;
}
/**
* {@inheritDoc}
*/
@Override
public IChatManager getChatManager() throws RemoteException {
return mChatManager;
}
/**
* {@inheritDoc}
*/
@Override
public IRoster getRoster() throws RemoteException {
if (mRoster != null) return mRoster;
Roster adap = mAdaptee.getRoster();
if (adap == null) return null;
mRoster = new RosterAdapter(adap, mService, mAvatarManager);
return mRoster;
}
/**
* Get the user informations.
*
* @return the user infos or null if not logged
*/
public UserInfo getUserInfo() {
return mUserInfo;
}
/**
* Returns true if currently authenticated by successfully calling the login method.
*
* @return true when successfully authenticated
*/
public boolean isAuthentificated() {
return mAdaptee.isAuthenticated();
}
/**
* {@inheritDoc}
*/
@Override
public void removeConnectionListener(IBeemConnectionListener listen) throws RemoteException {
if (listen != null) mRemoteConnListeners.unregister(listen);
}
/**
* PrivacyListManagerAdapter mutator.
*
* @param privacyListManager
* the privacy list manager
*/
public void setPrivacyListManager(PrivacyListManagerAdapter privacyListManager) {
this.mPrivacyListManager = privacyListManager;
}
/**
* PrivacyListManagerAdapter accessor.
*
* @return the mPrivacyList
*/
public PrivacyListManagerAdapter getPrivacyListManager() {
return mPrivacyListManager;
}
/**
* {@inheritDoc}
*/
@Override
public String getErrorMessage() {
return mErrorMsg;
}
/**
* Initialize the features provided by beem.
*/
private void initFeatures() {
ServiceDiscoveryManager.setIdentityName("Beem");
ServiceDiscoveryManager.setIdentityType("phone");
ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mAdaptee);
if (sdm == null) sdm = new ServiceDiscoveryManager(mAdaptee);
sdm.addFeature("http://jabber.org/protocol/disco#info");
// nikita: must be uncommented when the feature will be enabled
// sdm.addFeature("jabber:iq:privacy");
sdm.addFeature("http://jabber.org/protocol/caps");
sdm.addFeature("urn:xmpp:avatar:metadata");
sdm.addFeature("urn:xmpp:avatar:metadata+notify");
sdm.addFeature("urn:xmpp:avatar:data");
sdm.addFeature("http://jabber.org/protocol/nick");
sdm.addFeature("http://jabber.org/protocol/nick+notify");
sdm.addFeature(PingExtension.NAMESPACE);
mChatStateManager = ChatStateManager.getInstance(mAdaptee);
BeemCapsManager caps = new BeemCapsManager(sdm, mAdaptee, mService);
caps.setNode("http://www.beem-project.com");
}
/**
* Discover the features provided by the server.
*/
private void discoverServerFeatures() {
try {
// jid et server
ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mAdaptee);
DiscoverInfo info = sdm.discoverInfo(mAdaptee.getServiceName());
Iterator<DiscoverInfo.Identity> it = info.getIdentities();
while (it.hasNext()) {
DiscoverInfo.Identity identity = it.next();
if ("pubsub".equals(identity.getCategory()) && "pep".equals(identity.getType())) {
initPEP();
}
}
} catch (XMPPException e) {
Log.w(TAG, "Unable to discover server features", e);
}
}
/**
* Initialize PEP.
*/
private void initPEP() {
// Enable pep sending
Log.d(TAG, "Pep enabled");
// API 8
// mService.getExternalCacheDir()
mPepManager = new PepSubManager(mAdaptee);
AvatarCache avatarCache = new BeemAvatarCache(mService);
mAvatarManager = new BeemAvatarManager(mService, mAdaptee, mPepManager, avatarCache, true);
mAvatarManager.addAvatarListener(mUserInfoManager);
mApplication.setPepEnabled(true);
}
/**
* Reset the application state.
*/
private void resetApplication() {
mApplication.setConnected(false);
mApplication.setPepEnabled(false);
}
/**
* Listener for XMPP connection events. It will calls the remote listeners for connection events.
*/
private class ConnexionListenerAdapter implements ConnectionListener {
/**
* Defaut constructor.
*/
public ConnexionListenerAdapter() {
}
/**
* {@inheritDoc}
*/
@Override
public void connectionClosed() {
Log.d(TAG, "closing connection");
mRoster = null;
Intent intent = new Intent(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED);
intent.putExtra("message", mService.getString(R.string.BeemBroadcastReceiverDisconnect));
intent.putExtra("normally", true);
mService.sendBroadcast(intent);
mService.stopSelf();
resetApplication();
}
/**
* {@inheritDoc}
*/
@Override
public void connectionClosedOnError(Exception exception) {
Log.d(TAG, "connectionClosedOnError");
mRoster = null;
Intent intent = new Intent(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED);
intent.putExtra("message", exception.getMessage());
mService.sendBroadcast(intent);
mService.stopSelf();
resetApplication();
}
/**
* Connection failed callback.
*
* @param errorMsg
* smack failure message
*/
public void connectionFailed(String errorMsg) {
Log.d(TAG, "Connection Failed");
final int n = mRemoteConnListeners.beginBroadcast();
for (int i = 0; i < n; i++) {
IBeemConnectionListener listener = mRemoteConnListeners.getBroadcastItem(i);
try {
if (listener != null) listener.connectionFailed(errorMsg);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing the
// dead listeners.
Log.w(TAG, "Error while triggering remote connection listeners", e);
}
}
mRemoteConnListeners.finishBroadcast();
mService.stopSelf();
resetApplication();
}
/**
* {@inheritDoc}
*/
@Override
public void reconnectingIn(int arg0) {
Log.d(TAG, "reconnectingIn");
final int n = mRemoteConnListeners.beginBroadcast();
for (int i = 0; i < n; i++) {
IBeemConnectionListener listener = mRemoteConnListeners.getBroadcastItem(i);
try {
if (listener != null) listener.reconnectingIn(arg0);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing the
// dead listeners.
Log.w(TAG, "Error while triggering remote connection listeners", e);
}
}
mRemoteConnListeners.finishBroadcast();
}
/**
* {@inheritDoc}
*/
@Override
public void reconnectionFailed(Exception arg0) {
Log.d(TAG, "reconnectionFailed");
final int r = mRemoteConnListeners.beginBroadcast();
for (int i = 0; i < r; i++) {
IBeemConnectionListener listener = mRemoteConnListeners.getBroadcastItem(i);
try {
if (listener != null) listener.reconnectionFailed();
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing the
// dead listeners.
Log.w(TAG, "Error while triggering remote connection listeners", e);
}
}
mRemoteConnListeners.finishBroadcast();
}
/**
* {@inheritDoc}
*/
@Override
public void reconnectionSuccessful() {
Log.d(TAG, "reconnectionSuccessful");
mApplication.setConnected(true);
PacketFilter filter = new PacketFilter() {
@Override
public boolean accept(Packet packet) {
if (packet instanceof Presence) {
Presence pres = (Presence) packet;
if (pres.getType() == Presence.Type.subscribe) return true;
}
return false;
}
};
mAdaptee.addPacketListener(new PacketListener() {
@Override
public void processPacket(Packet packet) {
String from = packet.getFrom();
Notification notif = new Notification(android.R.drawable.stat_notify_more, mService.getString(R.string.AcceptContactRequest, from), System.currentTimeMillis());
notif.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(mService, Subscription.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("from", from);
notif.setLatestEventInfo(mService, from, mService.getString(R.string.AcceptContactRequestFrom, from),
PendingIntent.getActivity(mService, 0, intent, PendingIntent.FLAG_ONE_SHOT));
int id = packet.hashCode();
mService.sendNotification(id, notif);
Presence p = (Presence) packet;
updateNotification(Status.getStatusFromPresence(p), p.getStatus());
}
}, filter);
final int n = mRemoteConnListeners.beginBroadcast();
for (int i = 0; i < n; i++) {
IBeemConnectionListener listener = mRemoteConnListeners.getBroadcastItem(i);
try {
if (listener != null) listener.reconnectionSuccessful();
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing the
// dead listeners.
Log.w(TAG, "Error while triggering remote connection listeners", e);
}
}
mRemoteConnListeners.finishBroadcast();
}
}
/**
* This PacketListener will set a notification when you got a subscribtion request.
*
* @author Da Risk <da_risk@elyzion.net>
*/
private class SubscribePacketListener implements PacketListener {
/**
* Constructor.
*/
public SubscribePacketListener() {
}
@Override
public void processPacket(Packet packet) {
if (!(packet instanceof Presence)) return;
Presence p = (Presence) packet;
if (p.getType() != Presence.Type.subscribe) return;
String from = p.getFrom();
Notification notification = new Notification(android.R.drawable.stat_notify_more, mService.getString(R.string.AcceptContactRequest, from), System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(mService, Subscription.class);
intent.setData(Contact.makeXmppUri(from));
notification
.setLatestEventInfo(mService, from, mService.getString(R.string.AcceptContactRequestFrom, from), PendingIntent.getActivity(mService, 0, intent, PendingIntent.FLAG_ONE_SHOT));
int id = p.hashCode();
mService.sendNotification(id, notification);
}
}
/**
* The UserInfoManager listen to XMPP events and update the user information accoldingly.
*/
private class UserInfoManager implements AvatarListener {
/**
* Constructor.
*/
public UserInfoManager() {
}
@Override
public void onAvatarChange(String from, String avatarId, List<AvatarMetadataExtension.Info> avatarInfos) {
String jid = StringUtils.parseBareAddress(mUserInfo.getJid());
String mfrom = StringUtils.parseBareAddress(from);
if (jid.equalsIgnoreCase(mfrom)) {
mUserInfo.setAvatarId(avatarId);
}
}
}
/**
* Listener for Ping request. It will respond with a Pong.
*/
private class PingListener implements PacketListener {
/**
* Constructor.
*/
public PingListener() {
}
@Override
public void processPacket(Packet packet) {
if (!(packet instanceof PingExtension)) return;
PingExtension p = (PingExtension) packet;
if (p.getType() == IQ.Type.GET) {
PingExtension pong = new PingExtension();
pong.setType(IQ.Type.RESULT);
pong.setTo(p.getFrom());
pong.setPacketID(p.getPacketID());
mAdaptee.sendPacket(pong);
}
}
}
}
| gpl-3.0 |
emmanuel-keller/opensearchserver | src/main/java/com/jaeksoft/searchlib/crawler/database/DatabaseCassandraFieldMap.java | 4494 | /*
* License Agreement for OpenSearchServer
* <p>
* Copyright (C) 2010-2017 Emmanuel Keller / Jaeksoft
* <p>
* http://www.open-search-server.com
* <p>
* This file is part of OpenSearchServer.
* <p>
* OpenSearchServer is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* OpenSearchServer 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 General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with OpenSearchServer.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.jaeksoft.searchlib.crawler.database;
import com.datastax.driver.core.ColumnDefinitions;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.Row;
import com.jaeksoft.searchlib.SearchLibException;
import com.jaeksoft.searchlib.crawler.FieldMapContext;
import com.jaeksoft.searchlib.crawler.common.database.CommonFieldTarget;
import com.jaeksoft.searchlib.function.expression.SyntaxError;
import com.jaeksoft.searchlib.index.IndexDocument;
import com.jaeksoft.searchlib.query.ParseException;
import com.jaeksoft.searchlib.util.map.GenericLink;
import com.jaeksoft.searchlib.util.map.SourceField;
import com.qwazr.utils.StringUtils;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Set;
class DatabaseCassandraFieldMap extends DatabaseFieldMap {
final void mapRow(FieldMapContext context, Row row, ColumnDefinitions columns, IndexDocument target,
Set<String> filePathSet)
throws InstantiationException, IllegalAccessException, ClassNotFoundException, SearchLibException,
ParseException, IOException, SyntaxError, URISyntaxException, InterruptedException {
for (GenericLink<SourceField, CommonFieldTarget> link : getList()) {
final String columnName = link.getSource().getUniqueName();
if (!columns.contains(columnName))
continue;
final DataType columnType = columns.getType(columnName);
final CommonFieldTarget targetField = link.getTarget();
if (targetField.isCrawlFile() && columnType.getName().isCompatibleWith(DataType.Name.BLOB)) {
handleBlob(context, row, columns, target, filePathSet, columnName, targetField);
continue;
}
final Object rowValue = row.getObject(columnName);
if (rowValue != null) {
if (rowValue instanceof Collection) {
for (Object value : ((Collection) rowValue))
if (value != null)
mapFieldTarget(context, link.getTarget(), false, value.toString(), target, filePathSet);
} else
mapFieldTarget(context, link.getTarget(), false, rowValue.toString(), target, filePathSet);
}
}
}
private boolean doBlob(Row row, File binaryPath, String columnName) throws IOException {
final ByteBuffer byteBuffer = row.getBytes(columnName);
if (byteBuffer == null)
return false;
try (final FileChannel out = new FileOutputStream(binaryPath).getChannel()) {
out.write(byteBuffer);
return true;
}
}
private void handleBlob(FieldMapContext context, Row row, ColumnDefinitions columns, IndexDocument target,
Set<String> filePathSet, String columnName, CommonFieldTarget targetField)
throws IOException, SearchLibException, InterruptedException, ParseException, SyntaxError,
InstantiationException, URISyntaxException, IllegalAccessException, ClassNotFoundException {
final String filePath = columns.contains(targetField.getFilePathPrefix()) ?
row.getString(targetField.getFilePathPrefix()) :
null;
if (StringUtils.isBlank(filePath))
return;
final String fileName = FilenameUtils.getName(filePath);
Path binaryPath = null;
try {
binaryPath = Files.createTempFile("oss", fileName);
File binaryFile = binaryPath.toFile();
if (!doBlob(row, binaryFile, columnName))
return;
mapFieldTarget(context, targetField, true, binaryPath.toString(), target, filePathSet);
} finally {
if (binaryPath != null)
Files.deleteIfExists(binaryPath);
}
}
}
| gpl-3.0 |
supriseli163/supriseli.java.github | java-util/src/main/java/com/base/java/util/json/serializers/LocalDateTimeSerializer.java | 691 | package com.base.java.util.json.serializers;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value));
}
}
| gpl-3.0 |
lecogiteur/csvbang | src/main/java/com/github/lecogiteur/csvbang/factory/CsvFilePoolFactory.java | 3724 | /**
* com.github.lecogiteur.csvbang.file.CsvFilePoolFactory
*
* Copyright (C) 2013-2014 Tony EMMA
*
* This file is part of Csvbang.
*
* Csvbang is a comma-separated values ( CSV ) API, written in JAVA and thread-safe.
*
* Csvbang is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Csvbang 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Csvbang. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.lecogiteur.csvbang.factory;
import java.io.File;
import com.github.lecogiteur.csvbang.configuration.CsvBangConfiguration;
import com.github.lecogiteur.csvbang.exception.CsvBangException;
import com.github.lecogiteur.csvbang.file.FileName;
import com.github.lecogiteur.csvbang.pool.CsvFilePool;
import com.github.lecogiteur.csvbang.pool.MultiCsvFilePool;
import com.github.lecogiteur.csvbang.pool.OneByOneCsvFilePool;
import com.github.lecogiteur.csvbang.pool.SimpleCsvFilePool;
import com.github.lecogiteur.csvbang.util.CsvbangUti;
/**
* File pool factory. A file pool is used in order to delivery a CSV file
* to CsvBang for processing the writing and reading
* @author Tony EMMA
* @version 0.1.0
* @since 0.1.0
*/
public class CsvFilePoolFactory {
/**
* Create a pool of file for a CSV bean
* @param conf CsvBang configuration of CSV bean
* @param file base directory or override the CSV file
* @param customHeader the custom header
* @param customFooter the custom footer
* @return the pool of CSV file
* @throws CsvBangException if a problem occurred during creation of pool
* @since 0.1.0
*/
public static final CsvFilePool createPool(final CsvBangConfiguration conf, final File file,
final Object customHeader, final Object customFooter) throws CsvBangException{
FileName filename = null;
if (file != null){
if (file.exists() && file.isDirectory()){
//it's the base directory
filename = conf.fileName.clone();
filename.setBaseDirectory(file);
}else{
//it's file. we must override the filename define in configuration
filename = new FileName(file.getAbsolutePath(), conf.fileDatePattern);
}
}else{
filename = conf.fileName.clone();
}
if (conf.maxFileSize < 0 && conf.maxRecordByFile < 0){
//create a simple pool
return new SimpleCsvFilePool(conf, filename, customHeader, customFooter);
}else if (conf.isFileByFile || conf.maxFile <= 1){
return new OneByOneCsvFilePool(conf, filename, customHeader, customFooter);
}
return new MultiCsvFilePool(conf, filename, customHeader, customFooter);
}
/**
* Create a pool of file for a CSV bean
* @param conf CsvBang configuration of CSV bean
* @param file base directory or override the CSV file
* @param customHeader the custom header
* @param customFooter the custom footer
* @return the pool of CSV file
* @throws CsvBangException if a problem occurred during creation of pool
* @since 0.1.0
*/
public static final CsvFilePool createPool(final CsvBangConfiguration conf, final String file,
final Object customHeader, final Object customFooter) throws CsvBangException{
if (CsvbangUti.isStringNotBlank(file)){
return createPool(conf, new File(file), customHeader, customFooter);
}
return createPool(conf, (File)null, customHeader, customFooter);
}
}
| gpl-3.0 |
tvesalainen/util | util/src/test/java/org/vesalainen/nio/file/attribute/UserDefinedFileAttributesTest.java | 2483 | /*
* Copyright (C) 2016 Timo Vesalainen <timo.vesalainen@iki.fi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.vesalainen.nio.file.attribute;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;
/**
*
* @author Timo Vesalainen <timo.vesalainen@iki.fi>
*/
public class UserDefinedFileAttributesTest
{
private Path temp;
public UserDefinedFileAttributesTest()
{
}
@Before
public void init() throws IOException
{
temp = Files.createTempFile("test", null);
}
@After
public void cleanup() throws IOException
{
Files.deleteIfExists(temp);
}
@Test
public void test0() throws IOException, ClassNotFoundException
{
UserDefinedFileAttributes udfa = new UserDefinedFileAttributes(temp, 100);
String exp = "Kärkkäinen";
udfa.setString("test", exp);
assertEquals(exp, udfa.getString("test"));
udfa.setBoolean("boolean", true);
assertTrue(udfa.getBoolean("boolean"));
udfa.setInt("int", 1234);
assertEquals(1234, udfa.getInt("int"));
udfa.setLong("long", 12345678L);
assertEquals(12345678L, udfa.getLong("long"));
udfa.setDouble("double", 1234.56789);
assertEquals(1234.56789, udfa.getDouble("double"), 1e-10);
}
@Test
public void test1() throws IOException, ClassNotFoundException
{
UserDefinedFileAttributes udfa = new UserDefinedFileAttributes(temp, 100);
for (int ii=0;ii<10;ii++)
{
udfa.setInt("int", ii);
assertEquals(ii, udfa.getInt("int"));
}
}
}
| gpl-3.0 |
johnzweng/bankomatinfos | src/at/zweng/bankomatinfos/iso7816emv/TagValueType.java | 826 | /*
* Copyright 2010 sasc
*
* 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 at.zweng.bankomatinfos.iso7816emv;
/**
* source https://code.google.com/p/javaemvreader/
*
* @author sasc
*/
public enum TagValueType {
// COMPRESSED_NUMERIC (trailing 'F's),
BINARY, NUMERIC, TEXT, MIXED, DOL, TEMPLATE,
}
| gpl-3.0 |
khmMinecraftProjects/Hats | hats/client/core/TickHandlerClient.java | 10312 | package hats.client.core;
import hats.api.RenderOnEntityHelper;
import hats.client.gui.GuiHatUnlocked;
import hats.common.Hats;
import hats.common.core.HatHandler;
import hats.common.core.HatInfo;
import hats.common.entity.EntityHat;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.packet.Packet131MapData;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.network.PacketDispatcher;
public class TickHandlerClient
implements ITickHandler
{
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData)
{
if (type.equals(EnumSet.of(TickType.RENDER)))
{
if(Minecraft.getMinecraft().theWorld != null)
{
preRenderTick(Minecraft.getMinecraft(), Minecraft.getMinecraft().theWorld, (Float)tickData[0]); //only ingame
}
}
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData)
{
if (type.equals(EnumSet.of(TickType.CLIENT)))
{
if(Minecraft.getMinecraft().theWorld != null)
{
worldTick(Minecraft.getMinecraft(), Minecraft.getMinecraft().theWorld);
}
}
else if (type.equals(EnumSet.of(TickType.PLAYER)))
{
playerTick((World)((EntityPlayer)tickData[0]).worldObj, (EntityPlayer)tickData[0]);
}
else if (type.equals(EnumSet.of(TickType.RENDER)))
{
if(Minecraft.getMinecraft().theWorld != null)
{
renderTick(Minecraft.getMinecraft(), Minecraft.getMinecraft().theWorld, (Float)tickData[0]); //only ingame
}
}
}
@Override
public EnumSet<TickType> ticks()
{
return EnumSet.of(TickType.CLIENT, TickType.PLAYER, TickType.RENDER);
}
@Override
public String getLabel()
{
return "TickHandlerClientHats";
}
public void worldTick(Minecraft mc, WorldClient world)
{
if(worldInstance != world)
{
worldInstance = world;
mobHats.clear();
hats.clear();
requestMobHats.clear();
requestedMobHats.clear();
requestCooldown = 40;
}
if(showJoinMessage)
{
showJoinMessage = false;
mc.thePlayer.addChatMessage(StatCollector.translateToLocal("hats.firstJoin.hatHunting"));
}
if(Hats.enableInServersWithoutMod == 1 && !serverHasMod || serverHasMod)
{
for(int i = 0; i < world.playerEntities.size(); i++)
{
EntityPlayer player = (EntityPlayer)world.playerEntities.get(i);
if(!serverHasMod && Hats.shouldOtherPlayersHaveHats == 0 && player != Minecraft.getMinecraft().thePlayer || !player.isEntityAlive())
{
continue;
}
EntityHat hat = hats.get(player.username);
if(hat == null || hat.isDead)
{
if(player.username.equalsIgnoreCase(mc.thePlayer.username))
{
//Assume respawn
for(Entry<String, EntityHat> e : hats.entrySet())
{
e.getValue().setDead();
}
for(Entry<Integer, EntityHat> e : mobHats.entrySet())
{
e.getValue().setDead();
}
requestedMobHats.clear();
}
HatInfo hatInfo = (serverHasMod ? getPlayerHat(player.username) : ((Hats.randomHat == 1 || Hats.randomHat == 2 && player != mc.thePlayer) ? HatHandler.getRandomHat() : Hats.favouriteHatInfo));
hat = new EntityHat(world, player, hatInfo);
hats.put(player.username, hat);
world.spawnEntityInWorld(hat);
}
}
}
if(requestCooldown > 0)
{
requestCooldown--;
}
if(world.getWorldTime() % 5L == 0L && requestCooldown <= 0)
{
if(requestMobHats.size() > 0)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream stream = new DataOutputStream(bytes);
try
{
for(int i = 0 ; i < requestMobHats.size(); i++)
{
stream.writeBoolean(true);
stream.writeInt(requestMobHats.get(i));
}
stream.writeBoolean(false);
PacketDispatcher.sendPacketToServer(new Packet131MapData((short)Hats.getNetId(), (short)3, bytes.toByteArray()));
}
catch(IOException e)
{}
requestMobHats.clear();
}
}
if(Hats.randomMobHat > 0 && !(serverHasMod && serverHatMode == 4) || serverHasMod && serverHatMode == 4)
{
for(int i = 0; i < world.loadedEntityList.size(); i++)
{
Entity ent = (Entity)world.loadedEntityList.get(i);
if(!(ent instanceof EntityLivingBase) || !(serverHasMod && serverHatMode == 4) && !HatHandler.canMobHat((EntityLivingBase)ent) || ent instanceof EntityPlayer)
{
continue;
}
EntityLivingBase living = (EntityLivingBase)ent;
EntityHat hat = mobHats.get(living.entityId);
if(hat == null || hat.isDead)
{
if(!serverHasMod || serverHatMode != 4)
{
HatInfo hatInfo = living.getRNG().nextFloat() < ((float)Hats.randomMobHat / 100F) ? (Hats.randomHat >= 1 ? HatHandler.getRandomHat() : Hats.favouriteHatInfo) : new HatInfo();
hat = new EntityHat(world, living, hatInfo);
mobHats.put(living.entityId, hat);
world.spawnEntityInWorld(hat);
}
else if(!requestMobHats.contains(living.entityId) && !requestedMobHats.contains(living.entityId))
{
requestMobHats.add(living.entityId);
requestedMobHats.add(living.entityId);
}
}
}
}
Iterator<Entry<String, EntityHat>> ite = hats.entrySet().iterator();
while(ite.hasNext())
{
Entry<String, EntityHat> e = ite.next();
if(e.getValue().worldObj.provider.dimensionId != world.provider.dimensionId || (world.getWorldTime() - e.getValue().lastUpdate) > 10L)
{
e.getValue().setDead();
ite.remove();
}
}
Iterator<Entry<Integer, EntityHat>> ite1 = mobHats.entrySet().iterator();
while(ite1.hasNext())
{
Entry<Integer, EntityHat> e = ite1.next();
if(e.getValue().worldObj.provider.dimensionId != world.provider.dimensionId || (world.getWorldTime() - e.getValue().lastUpdate) > 10L)
{
e.getValue().setDead();
ite1.remove();
}
}
if(mc.currentScreen == null && !hasScreen)
{
if(!guiKeyDown && isPressed(Hats.guiKeyBind))
{
if(Hats.playerHatsMode == 3)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream stream = new DataOutputStream(bytes);
try
{
stream.writeByte(0);
PacketDispatcher.sendPacketToServer(new Packet131MapData((short)Hats.getNetId(), (short)2, bytes.toByteArray()));
}
catch(IOException e)
{}
}
else
{
Hats.proxy.openHatsGui();
}
}
}
hasScreen = mc.currentScreen != null;
guiKeyDown = isPressed(Hats.guiKeyBind);
}
public static boolean isPressed(int key)
{
if(key < 0)
{
return Mouse.isButtonDown(key + 100);
}
return Keyboard.isKeyDown(key);
}
public void playerTick(World world, EntityPlayer player)
{
}
public void preRenderTick(Minecraft mc, World world, float renderTick)
{
currentHatRenders = 0;
Iterator<Entry<String, EntityHat>> iterator = hats.entrySet().iterator();
while(iterator.hasNext())
{
Entry<String, EntityHat> e = iterator.next();
if(e.getValue().parent != null)
{
EntityHat hat = e.getValue();
updateHatPosAndAngle(hat, hat.renderingParent);
}
}
Iterator<Entry<Integer, EntityHat>> iterator1 = mobHats.entrySet().iterator();
while(iterator1.hasNext())
{
Entry<Integer, EntityHat> e = iterator1.next();
if(e.getValue().parent != null)
{
EntityHat hat = e.getValue();
updateHatPosAndAngle(hat, hat.parent);
}
}
}
public void updateHatPosAndAngle(EntityHat hat, EntityLivingBase parent)
{
hat.lastTickPosX = hat.parent.lastTickPosX;
hat.lastTickPosY = hat.parent.lastTickPosY;
hat.lastTickPosZ = hat.parent.lastTickPosZ;
hat.prevPosX = hat.parent.prevPosX;
hat.prevPosY = hat.parent.prevPosY;
hat.prevPosZ = hat.parent.prevPosZ;
hat.posX = hat.parent.posX;
hat.posY = hat.parent.posY;
hat.posZ = hat.parent.posZ;
RenderOnEntityHelper helper = HatHandler.getRenderHelper(parent.getClass());
if(helper != null)
{
hat.prevRotationPitch = helper.getPrevRotationPitch(parent);
hat.rotationPitch = helper.getRotationPitch(parent);
hat.prevRotationYaw = helper.getPrevRotationYaw(parent);
hat.rotationYaw = helper.getRotationYaw(parent);
}
}
public void renderTick(Minecraft mc, World world, float renderTick)
{
if(guiHatUnlocked == null)
{
guiHatUnlocked = new GuiHatUnlocked(mc);
}
guiHatUnlocked.updateGui();
}
public HatInfo getPlayerHat(String s)
{
HatInfo name = playerWornHats.get(s);
if(name == null)
{
return new HatInfo();
}
return name;
}
public HashMap<String, HatInfo> playerWornHats = new HashMap<String, HatInfo>();
public HashMap<String, EntityHat> hats = new HashMap<String, EntityHat>();
public HashMap<Integer, EntityHat> mobHats = new HashMap<Integer, EntityHat>();
public HashMap<Integer, EntityHat> rendered = new HashMap<Integer, EntityHat>();
public ArrayList<String> availableHats = new ArrayList<String>();
public ArrayList<String> requestedHats = new ArrayList<String>();
public ArrayList<String> serverHats = new ArrayList<String>();
public ArrayList<Integer> requestMobHats = new ArrayList<Integer>();
public ArrayList<Integer> requestedMobHats = new ArrayList<Integer>();
public int serverHatMode;
public String serverHat;
public World worldInstance;
public boolean serverHasMod = false;
public boolean showJoinMessage = false;
public boolean guiKeyDown;
public boolean hasScreen;
public int currentHatRenders;
public int requestCooldown;
public GuiHatUnlocked guiHatUnlocked;
}
| gpl-3.0 |
carlos-korovsky/5PRO302-2016-2 | Exemplo4/src/br/udesc/ceplan/prog3/BordaCatupiry.java | 1257 | /*
* Copyright (C) 2016 Carlos Alberto Cipriano Korovsky <carlos.korovsky at gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package br.udesc.ceplan.prog3;
/**
*
* @author Carlos Alberto Cipriano Korovsky <carlos.korovsky at gmail.com>
*/
public class BordaCatupiry extends PizzaDecorator {
public BordaCatupiry(Pizza pizza) {
super(pizza);
}
@Override
public String getDescricao() {
return this.getPizza().getDescricao() + " + borda de catupiry";
}
@Override
public Double getValor() {
return this.getPizza().getValor() + 5.60;
}
}
| gpl-3.0 |
jub77/grafikon | grafikon-output2/src/main/java/net/parostroj/timetable/output2/gt/GTDrawFactory.java | 283 | package net.parostroj.timetable.output2.gt;
import net.parostroj.timetable.model.Route;
/**
* GTDrawFactory for GTView.
*
* @author jub
*/
public interface GTDrawFactory {
GTDraw createInstance(GTDraw.Type type, GTDrawSettings settings, Route route, GTStorage storage);
}
| gpl-3.0 |
slavidlancer/JavaEEWebDevelopment | 06_SpringMVC/Homework/Topic6HomeworkSpringMVC/src/main/java/com/jeewd/bank/services/CurrencyConversion.java | 212 | package com.jeewd.bank.services;
import java.math.BigDecimal;
public interface CurrencyConversion {
BigDecimal convert(BigDecimal changeAmount, String changeCurrency,
String accountCurrency);
}
| gpl-3.0 |
rock007/cloud-starter | cloud-cms/src/main/java/org/cloud/cms/config/security/ShiroAuthRealm.java | 3901 | /**
* @Title ShiroAuthRealm.java
* @date 2013-11-2 下午3:52:21
* @Copyright: 2013
*/
package org.cloud.cms.config.security;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.cloud.core.shiro.jwt.JwtToken;
import org.cloud.core.shiro.jwt.TokenProvider;
import org.cloud.core.utils.EncriptUtil;
import org.cloud.db.sys.entity.SysUser;
import org.cloud.db.sys.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
public class ShiroAuthRealm extends AuthorizingRealm{
private static final Logger logger = LoggerFactory.getLogger(ShiroAuthRealm.class);
@Autowired
private UserService userService;
@Autowired
protected RestTemplate restTemplate;
@Autowired
private TokenProvider tokenUtil;
@Override
public boolean supports(AuthenticationToken token) {
//表示此Realm只支持JwtToken类型
return token instanceof JwtToken || token instanceof UsernamePasswordToken;
}
/**
* 授权:验证权限时调用
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//String username = (String) principalCollection.getPrimaryPrincipal();
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
return simpleAuthorizationInfo;
}
/**
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException{
String username,password;
//判断是否token
if (authenticationToken instanceof JwtToken) {
JwtToken jwtToken = (JwtToken) authenticationToken;
// 获取token
String token = jwtToken.getToken();
if (token == null || "".equals(token)) {
throw new IncorrectCredentialsException();
}
// 从token中获取用户名
username = tokenUtil.getUsernameFromToken(token);
password = tokenUtil.getPasswordFromToken(token);
// 查询用户信息
SysUser loginUser = userService.findUserByName(username);
if (null == loginUser) {
throw new UnknownAccountException();
}
if (!StringUtils.isEmpty(password)
&& !loginUser.getPassword().equals(EncriptUtil.md5(password + loginUser.getSalt()))) {
throw new IncorrectCredentialsException();
}
// 用户被禁用
if (loginUser.getLocked() != null && loginUser.getLocked() == 1) {
throw new LockedAccountException();
}
try {
return new SimpleAuthenticationInfo(loginUser.getUserId(), token, getName());
} catch (Exception e) {
throw new AuthenticationException(e);
}
}else {
username = (String) authenticationToken.getPrincipal();
password =authenticationToken.getCredentials()==null?"": new String((char[]) authenticationToken.getCredentials());
// 查询用户信息
SysUser loginUser = userService.findUserByName(username);
if (null == loginUser) {
throw new UnknownAccountException();
}
//MD5Util.MD5(password + upmsUser.getSalt())
if (!"".equals(password)&&!loginUser.getPassword().equals(EncriptUtil.md5(password + loginUser.getSalt()))) {
//if (!"".contains(password)&&!upmsUser.getPassword().equals(password )) {
throw new IncorrectCredentialsException();
}
if (loginUser.getLocked()!=null&&loginUser.getLocked() == 1) {
throw new LockedAccountException();
}
return new SimpleAuthenticationInfo(loginUser.getUserId(), password, getName());
}
}
}
| gpl-3.0 |
Techwave-dev/OpenGlModernGameEngine | src/com/teckcoder/crashengine/shaders/Shader3DBasicSoloLight.java | 1131 | package com.teckcoder.crashengine.shaders;
import com.teckcoder.crashengine.utils.Constants;
public class Shader3DBasicSoloLight extends Shader3D{
protected int isTextureSetUniformLocation;
protected int textureUniformLocation;
public Shader3DBasicSoloLight() {
super("Shaders/vertexSources/3DBasicSoloLight.vert", "Shaders/fragmentSources/3DBasicSoloLight.frag");
}
@Override
protected void bindAllAttributes() {
bindAttribute(Constants.VERTEX_POSITION_ATTRIB, "in_Vertex");
bindAttribute(Constants.COLORS_POSITION_ATTRIB, "in_Color");
bindAttribute(Constants.NORMALS_POSITION_ATTRIB, "in_normals");
bindAttribute(Constants.TEXTURE_POSITION_0_POSITION_ATTRIB, "in_TexCoord0");
}
@Override
protected void getAllUniformLocation() {
super.getAllUniformLocation();
isTextureSetUniformLocation = getUniformLocation("in_isTextureSet");
textureUniformLocation = getUniformLocation("textureSampler");
}
public void uploadIsTextureSet(boolean isTextureSet){
uploadBoolean(isTextureSetUniformLocation, isTextureSet);
}
public void uploadTexture(){
uploadInt(textureUniformLocation, 0);
}
}
| gpl-3.0 |
jendave/mochadoom | src/main/java/net/sourceforge/mochadoom/rendering/mappatch_t.java | 1015 | package net.sourceforge.mochadoom.rendering;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import net.sourceforge.mochadoom.wad.CacheableDoomObject;
/**
* Texture definition.
* Each texture is composed of one or more patches,
* with patches being lumps stored in the WAD.
* The lumps are referenced by number, and patched
* into the rectangular texture space using origin
* and possibly other attributes.
*/
public class mappatch_t implements CacheableDoomObject {
public short originx;
public short originy;
public short patch;
public short stepdir;
public short colormap;
@Override
public void unpack(ByteBuffer buf)
throws IOException {
buf.order(ByteOrder.LITTLE_ENDIAN);
originx = buf.getShort();
originy = buf.getShort();
patch = buf.getShort();
stepdir = buf.getShort();
colormap = buf.getShort();
}
public static final int size() {
return 10;
}
};
| gpl-3.0 |
cpinan/AlgorithmTraining | Training01/java/DataStructures/src/heaps/MinIntHeap.java | 2595 | package heaps;
import java.util.Arrays;
public class MinIntHeap {
private int capacity = 10;
private int size = 0;
int[] items = new int[capacity];
private int getLeftChildIndex(int parentIndex) {
return 2 * parentIndex + 1;
}
private int getRightChildIndex(int parentIndex) {
return 2 * parentIndex + 2;
}
private int getParentIndex(int childIndex) {
return (childIndex - 1) / 2;
}
private boolean hasLeftChild(int index) {
return getLeftChildIndex(index) < size;
}
private boolean hasRightChild(int index) {
return getRightChildIndex(index) < size;
}
private boolean hasParent(int index) {
return getParentIndex(index) >= 0;
}
private int leftChild(int index) {
return items[getLeftChildIndex(index)];
}
private int rightChlid(int index) {
return items[getRightChildIndex(index)];
}
private int parent(int index) {
return items[getParentIndex(index)];
}
private void swap(int indexOne, int indexTwo) {
int temp = items[indexOne];
items[indexOne] = items[indexTwo];
items[indexTwo] = temp;
}
private void ensureExtraCapacity() {
if (size == capacity) {
items = Arrays.copyOf(items, capacity * 2);
capacity *= 2;
}
}
public int peek() {
if (size == 0) throw new IllegalStateException();
return items[0];
}
public int poll() {
if (size == 0) throw new IllegalArgumentException();
int item = items[0];
items[0] = items[size - 1];
size--;
heapifyDown();
return item;
}
public void add(int item) {
ensureExtraCapacity();
items[size++] = item;
heapifyUp();
}
public void heapifyDown() {
int index = 0;
while (hasLeftChild(index)) {
int smallerChildIndex = getLeftChildIndex(index);
if (hasRightChild(index) && rightChlid(index) < leftChild(index)) {
smallerChildIndex = getRightChildIndex(index);
}
if (items[index] < items[smallerChildIndex]) {
break;
} else {
swap(index, smallerChildIndex);
index = smallerChildIndex;
}
}
}
public void heapifyUp() {
int index = size - 1;
while (hasParent(index) && parent(index) > items[index]) {
swap(getParentIndex(index), index);
index = getParentIndex(index);
}
}
}
| gpl-3.0 |
EastWestFM/logit | src/main/java/io/github/lucaseasedup/logit/config/validators/NonNegativeValidator.java | 1255 | /*
* NonNegativeValidator.java
*
* Copyright (C) 2012-2014 LucasEasedUp
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.github.lucaseasedup.logit.config.validators;
import io.github.lucaseasedup.logit.config.PropertyType;
import io.github.lucaseasedup.logit.config.PropertyValidator;
public final class NonNegativeValidator implements PropertyValidator
{
@Override
public boolean validate(String path, PropertyType type, Object value)
{
if (value instanceof Number)
{
return ((Number) value).intValue() >= 0;
}
return false;
}
}
| gpl-3.0 |
vladimir-ironvlack/algoritmosPlanificacion | src/vistas/BcpVista.java | 2726 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vistas;
import java.awt.Label;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import proceso.Bcp;
import proceso.List;
/**
*
* @author raul
*/
public class BcpVista extends JPanel {
int x = 10, y = 20, with = 50, height = 20; //bcp de trabajos generales
int xp = 10, yp = 20, withp = 50, heightp = 20; //bcp preparados
//repintar bcp
public int rx = 10, ry = 20, rwith = 50, rheight = 20;
public JPanel vistaBcp(int id, JPanel contenedorGeneral) {
JPanel contbcp;
JLabel lblvalorBcp;
contbcp = new JPanel();
lblvalorBcp = new JLabel();
contbcp.setBackground(new java.awt.Color(0, 0, 0));
contbcp.setForeground(new java.awt.Color(51, 255, 0));
contbcp.setBounds(x, y, with, height);
lblvalorBcp.setForeground(new java.awt.Color(51, 255, 0));
lblvalorBcp.setBounds(1, 1, 50, 20);
lblvalorBcp.setText("P" + id);
lblvalorBcp.setVisible(true);
contbcp.add(lblvalorBcp);
contbcp.setVisible(true);
contenedorGeneral.add(contbcp);
x = x + 50;
return contbcp;
}
public JPanel vistaBcpPreparados(int id, JPanel contenedorGeneral) {
JPanel contbcp;
JLabel lblvalorBcp;
contbcp = new JPanel();
lblvalorBcp = new JLabel();
contbcp.setBackground(new java.awt.Color(0, 0, 0));
contbcp.setForeground(new java.awt.Color(51, 255, 0));
contbcp.setBounds(xp, yp, withp, heightp);
lblvalorBcp.setForeground(new java.awt.Color(51, 255, 0));
lblvalorBcp.setBounds(1, 1, 50, 20);
lblvalorBcp.setText("P" + id);
lblvalorBcp.setVisible(true);
contbcp.add(lblvalorBcp);
contbcp.setVisible(true);
contenedorGeneral.add(contbcp);
xp = xp + 50;
return contbcp;
}
public void repintarBCP(int id, JPanel contenedorGeneral) {
JPanel contbcp;
JLabel lblvalorBcp;
contbcp = new JPanel();
lblvalorBcp = new JLabel();
contbcp.setBackground(new java.awt.Color(0, 0, 0));
contbcp.setForeground(new java.awt.Color(51, 255, 0));
contbcp.setBounds(rx, ry, rwith, rheight);
lblvalorBcp.setForeground(new java.awt.Color(51, 255, 0));
lblvalorBcp.setBounds(1, 1, 50, 20);
lblvalorBcp.setText("P" + id);
lblvalorBcp.setVisible(true);
contbcp.add(lblvalorBcp);
contbcp.setVisible(true);
contenedorGeneral.add(contbcp);
rx = rx + 50;
}
public void resetPosicones() {
rx = 10;
}
}
| gpl-3.0 |
yangwenjing/START | movement/operation/SpeedManager.java | 2128 | package movement.operation;
import core.Settings;
import core.SimClock;
import java.util.Random;
/**
* Created by ywj on 15/5/7.
*/
public class SpeedManager {
/**
* a=0.11798
b=0.0058637
*/
public static double A0 = 0.11798;
public static double A1 = 0.0058637;
private static SpeedManager ourInstance = null;
private static Random rng = new Random(SimClock.getIntTime());
public static SpeedManager getInstance(Settings settings)
{
if(ourInstance==null)
{
ourInstance = new SpeedManager(settings);
}
return ourInstance;
}
private SpeedManager(Settings settings) {
}
public double generateSpeed(int status) {
//TODO 实现按函数分布生成速度
return 0;
}
protected double generateSpeed(double status)
{
// TODO get speed by the status
if(status==0)
return generateSpeedForStatus0();
else
return generateSpeedForStatus1();
}
private double generateSpeedForStatus0() {
double seed = rng.nextDouble()*speed_dis_for_status0(44.4);
double sp = reverse_speed_for_status0(seed);
// if(sp<0||sp>44.4)
// System.out.println(sp);
// if(sp>10)
// System.out.print(sp);
return sp;
}
private double generateSpeedForStatus1() {
double seed = rng.nextDouble()*speed_dis_for_status1(44.4);
//System.out.println(seed);
double sp = reverse_speed_for_status1(seed);
// if(sp<0||sp>44.4)
// System.out.println(sp);
// if(sp>10)
// System.out.print(sp);
return sp;
}
private double speed_dis_for_status0(double x){
return 1-1/Math.exp(A0*Math.pow(x, 1.5));
}
private double speed_dis_for_status1(double x)
{
return 1-1/Math.exp(A1*Math.pow(x, 2.5));
}
private double reverse_speed_for_status0(double result)
{
return Math.pow(Math.log(1/(1-result))/A0,1/1.5);
}
private double reverse_speed_for_status1(double result)
{
return Math.pow(Math.log(1/(1-result))/A1,1/2.5);
}
}
| gpl-3.0 |
ableiten/foldem | src/main/java/codes/derive/foldem/Poker.java | 15089 | /*
* This file is part of Fold'em, a Java library for Texas Hold 'em Poker.
*
* Fold'em is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Fold'em 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Fold'em. If not, see <http://www.gnu.org/licenses/>.
*/
package codes.derive.foldem;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import codes.derive.foldem.board.Board;
import codes.derive.foldem.board.Boards;
import codes.derive.foldem.board.Street;
import codes.derive.foldem.eval.DefaultEvaluator;
import codes.derive.foldem.eval.Evaluator;
import codes.derive.foldem.eval.HandValue;
import codes.derive.foldem.tool.EquityCalculationBuilder;
import codes.derive.foldem.tool.EquityCalculationBuilder.Equity;
import codes.derive.foldem.util.PrettyFormat;
import codes.derive.foldem.util.RandomContext;
/**
* This class consists of static methods, a lot of them just aliases, to aid in
* using this library.
*/
public class Poker {
private Poker() { /* No external instantiation */ }
/**
* Constructs a {@link Card} with the specified card value and suit.
*
* @param value
* The card value, must be one of the card value constants
* defined in {@link Card}.
* @param suit
* The suit.
* @return A new {@link Card} with the specified value and suit.
*/
public static Card card(int value, Suit suit) {
return new Card(value, suit);
}
/**
* Constructs a new {@link Card} using the specified shorthand string. For
* information on the shorthand format see
* {@link codes.derive.foldem.Card#Card(String)}.
*
* @param text
* The shorthand for the card.
* @return A new {@link Card} using the specified shorthand.
* @see codes.derive.foldem.Card#Card(String)
*/
public static Card card(String text) {
return new Card(text);
}
/**
* Constructs a new {@link Card} dealt from the specified {@link Deck}.
*
* <p>
* Alias for {@link Deck#pop()}.
* </p>
*
* @param deck
* The deck to deal from
* @return The {@link Card} dealt from the specified deck.
*/
public static Card card(Deck deck) {
return deck.pop();
}
/**
* Constructs a new {@link java.util.Collection} containing an unordered
* enumeration of all cards.
*
* @return A {@link java.util.Collection} containing every {@link Card}, in
* no specific order.
*/
public static Collection<Card> cards() {
List<Card> cards = new ArrayList<>();
for (Suit suit : Suit.values()) {
for (int value = Card.ACE; value <= Card.KING; value++) {
cards.add(new Card(value, suit));
}
}
return cards;
}
/**
* Creates a {@link java.util.Collection} containing cards for the specified
* sequential shorthand. for example, "Ac2d3h4s", would return a
* {@link java.util.Collection} containing the ace of spades, deuce of
* diamonds, trey of hearts, and the four of spaces.
*
* @param shorthand
* The shorthand.
* @return A {@link java.util.Collection} containing the created cards.
*/
public static Collection<Card> cards(String shorthand) {
if (shorthand.length() % 2 != 0) {
throw new IllegalArgumentException("Invalid shorthand");
}
List<Card> cards = new ArrayList<>();
for (int i = 0; i < shorthand.length(); i += 2) {
cards.add(card(shorthand.substring(i, i + 2)));
}
return cards;
}
/**
* Constructs a new {@link Hand} using the specified cards.
*
* @param cards
* The cards to use in the created hand.
* @return A new hand using the specified cards.
*/
public static Hand hand(Card... cards) {
return new Hand(cards);
}
/**
* Constructs a new {@link Hand} by dealing it from the specified
* {@link Deck}.
*
* @param deck
* The deck to deal the hand from.
* @return A {@link Hand} containing cards dealt from the specified deck.
*/
public static Hand hand(Deck deck) {
return hand(deck.pop(), deck.pop());
}
/**
* Constructs a new {@link Hand} using specified cards shorthand text. For
* information on the format see
* {@link codes.derive.foldem.Hand#Hand(String)}.
*
* @param cards
* The shorthand text.
* @return A new hand using the specified shorthand text.
*/
public static Hand hand(String cards) {
return new Hand(cards);
}
/**
* Constructs a new {@link java.util.Collection} containing an unordered
* enumeration of all hands.
*
* @return A {@link java.util.Collection} containing every possible
* {@link Hand}, in no specific order.
*
*/
public static Collection<Hand> hands() {
List<Hand> hands = new ArrayList<>();
for (Card a : cards()) {
for (Card b : cards()) {
Hand h = hand(a, b);
if (a.equals(b) || hands.contains(h)) {
continue;
}
hands.add(h);
}
}
return hands;
}
/**
* Constructs a new {@link java.util.Collection} containing a group of hands
* specified by shorthand with no suit information.
*
* <p>
* The syntax is the same as creating hands, except you do not need to
* specify suit information, a hand with each combination of suits will be
* created for you. For example, shorthand "TT" would produce every
* combination of a hand containing two tens in
* </p>
*
* <p>
* Additionally, you can specify hands be suited using the "s" modifier.
* This will produce only suited combinations of the specified hand. For
* example, "TJs" would produce TJ of hearts, spaces, clubs and diamonds
* only. Conversely "TJo" would produce only off-suited hands.
* </p>
*
* @param shorthand
* The shorthand to use to generate the hands.
* @return A new {@link java.util.Collection} containing the hands specified
* in shorthand format.
*/
public static Collection<Hand> handGroup(String shorthand) {
List<Hand> hands = new ArrayList<>();
/*
* Find the numeric values of the card labels provided.
*/
int a = -1, b = -1;
for (int i = 0; i < Card.LABEL.length; i++) {
if (Card.LABEL[i] == shorthand.charAt(0)) {
a = i;
}
if (Card.LABEL[i] == shorthand.charAt(1)) {
b = i;
}
}
int length = shorthand.length();
/*
* Include suited hands if we have not specified any specific suit
* information or if we have specified to include suited hands.
*/
if (length == 2 || (length == 3 && shorthand.charAt(2) == 's')) {
if (a != b) {
for (Suit suit : Suit.values()) {
hands.add(hand(card(a, suit), card(b, suit)));
}
} else if (length == 3) {
throw new IllegalArgumentException(
"A hand cannot have identical cards of the same suit");
}
}
/*
* Included non-suited hands if we have not specified any specific suit
* information or if we have specified to include non-suited hands.
*/
if (length == 2 || (length == 3 && shorthand.charAt(2) == 'o')) {
/*
* Add all off-suit combinations of the provided hand.
*/
for (Suit[] suits : Constants.OFFSUIT_COMBINATIONS) {
Hand h = hand(card(a, suits[0]), card(b, suits[1]));
if (!hands.contains(h)) {
hands.add(hand(card(a, suits[0]), card(b, suits[1])));
}
/*
* We only need to reverse the suits if A and B aren't
* equivalent.
*/
if (a != b) {
hands.add(hand(card(a, suits[1]), card(b, suits[0])));
}
}
}
return hands;
}
/**
* Constructs a new {@link Range} with no hands.
*
* @return A new empty {@link Range}.
*/
public static Range range() {
return new Range();
}
/**
* Constructs a new {@link Range} with the specified hands.
*
* @param hands
* The hands.
* @return The new {@link Range} containing the specified hands.
*/
public static Range range(Hand... hands) {
return range().define(hands);
}
/**
* Constructs a new {@link Board} using the specified cards.
*
* <p>
* Alias for {@link Boards#board(Card...)}.
* </p>
*
* @param cards
* The cards to use.
* @return A new {@link Board} using the specified cards.
*/
public static Board board(Card... cards) {
return Boards.board(cards);
}
/**
* Constructs a new {@link Board} using the specified card shorthand.
*
* <p>
* Alias for {@link Boards#board(String)}.
* </p>
*
* @param cards
* The cards shorthand, see {@link Boards#board(String)} for
* information on formatting.
* @return A new {@link Board} using the specified cards.
*/
public static Board board(String cards) {
return Boards.board(cards);
}
/**
* Constructs a new {@link Board}, dealing the cards from the specified
* {@link Deck}.
*
* <p>
* Alias for {@link Boards#board(Deck, Street)}
* </p>
*
* @param deck
* The deck to deal from.
* @param street
* The street to deal.
* @return A new {@link Board} using cards from the specified {@link Deck}.
*/
public static Board board(Deck deck, Street street) {
return Boards.board(deck, street);
}
/**
* Constructs a new {@link Deck}.
*
* @return A new {@link Deck} with no cards drawn.
*/
public static Deck deck() {
return new Deck();
}
/**
* Constructs a new {@link Deck} and shuffles it.
*
* @return A new shuffled {@link Deck} with no cards drawn.
*/
public static Deck shuffledDeck() {
return new Deck().shuffle(RandomContext.get());
}
/**
* Finds the value of the specified {@link Hand} on the specified
* {@link Board}.
*
* @param hand
* The hand.
* @param board
* The board.
* @return The specified hand's value on the specified board.
*/
public static HandValue value(Hand hand, Board board) {
return new DefaultEvaluator().value(hand, board);
}
/**
* Obtains the equity that the specified hands have against each other,
* returning them as keys mapped to their calculated equity.
*
* @param hands
* The hands to calculate equity for.
* @return The hands mapped to their calculated equity.
*/
public static Map<Hand, Equity> equity(Hand... hands) {
return calculationBuilder().calculate(hands);
}
/**
* Obtains the equity that the specified hands have against each other on
* the specified board, returning them as keys mapped to their calculated
* equity.
*
* @param board
* The board to calculate equity on.
* @param hands
* The hands to calculate equity for.
* @return The hands mapped to their calculated equity.
*/
public static Map<Hand, Equity> equity(Board board, Hand... hands) {
return calculationBuilder().useBoard(board).calculate(hands);
}
/**
* Obtains the equity that the specified hand ranges have against each
* other, returning them as keys mapped to their calculated equity.
*
* @param ranges
* The hand ranges to calculate equity for.
* @return The hand ranges mapped to their calculated equity.
*/
public static Map<Range, Equity> equity(Range... ranges) {
return calculationBuilder().calculate(ranges);
}
/**
* Obtains the equity that the specified hand ranges have against each other
* on the specified board, returning them as keys mapped to their calculated
* equity.
*
* @param board
* The board to calculate equity on.
* @param ranges
* The hand ranges to calculate equity for
* @return The hand ranges mapped to their calculated equity.
*/
public static Map<Range, Equity> equity(Board board, Range... ranges) {
return calculationBuilder().useBoard(board).calculate(ranges);
}
/**
* Formats the {@link Suit} specified using pretty formatting. Is an alias
* for {@link codes.derive.foldem.util.PrettyFormat#get(Suit)}
*
* @param suit
* The {@link Suit} to format.
* @return A pretty formatted {@link String} representing the specified {@link Suit}
* .
*/
public static char format(Suit suit) {
return PrettyFormat.get(suit);
}
/**
* Formats the {@link Card} specified using pretty formatting. Is an alias
* for {@link codes.derive.foldem.util.PrettyFormat#get(Card)}
*
* @param card
* The {@link Card} to format.
* @return A pretty formatted {@link String} representing the specified {@link Card}
* .
*/
public static String format(Card card) {
return PrettyFormat.get(card);
}
/**
* Formats the {@link Hand} specified using pretty formatting. Is an alias for
* {@link codes.derive.foldem.util.PrettyFormat#get(Hand)}
*
* @param hand
* The hand to format.
* @return A pretty formatted {@link String} representing the specified {@link Hand}.
*/
public static String format(Hand hand) {
return PrettyFormat.get(hand);
}
/**
* Formats the {@link Board} specified using pretty formatting. Is an alias
* for {@link codes.derive.foldem.util.PrettyFormat#get(Board)}
*
* @param board
* The {@link Board} to format.
* @return A pretty formatted string representing the specified {@link Board}.
*/
public static String format(Board board) {
return PrettyFormat.get(board);
}
/**
* Formats the {@link Equity} specified using percentages.
*
* @param equity
* The equity to format.
* @return A string containing the w/l/s in a format of
* "Win: ww.ww% Lose: ll.ll% Split: ss.ss%".
*/
public static String format(Equity equity) {
StringBuilder b = new StringBuilder();
b.append("Win: ").append(percent(equity.win())).append("% ");
b.append("Lose: ").append(percent(equity.lose())).append("% ");
b.append("Split: ").append(percent(equity.split())).append("%");
return b.toString();
}
/**
* Represents the specified decimal as a percentage rounded to two decimal
* places.
*
* @param d
* The decimal to convert.
* @return The percentage.
*/
public static double percent(double d) {
return new BigDecimal(d * 100).setScale(2, RoundingMode.HALF_UP)
.doubleValue();
}
/**
* Constructs a new evaluator using the {@link DefaultEvaluator} type
* provided with this library.
*
* <p>
* Alias for {@link DefaultEvaluator#DefaultEvaluator}
* </p>
*
* @return An evaluator.
*/
public static Evaluator evaluator() {
return new DefaultEvaluator();
}
/**
* Constructs a new {@link EquityCalculationBuilder}.
*
* @return A new {@link EquityCalculationBuilder} for use in equity
* calculations.
*/
public static EquityCalculationBuilder calculationBuilder() {
return new EquityCalculationBuilder();
}
}
| gpl-3.0 |
railbu/jshoper3x | src/com/jshop/entity/SerialT.java | 2036 | package com.jshop.entity;
// Generated 2014-10-9 18:51:28 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* SerialT generated by hbm2java
*/
@Entity
@Table(name = "serial_t", catalog = "jshoper3")
public class SerialT implements java.io.Serializable {
private String biz;
private String head;
private String lastid;
private int increment;
private Date updatetime;
public SerialT() {
}
public SerialT(String biz, String lastid, int increment, Date updatetime) {
this.biz = biz;
this.lastid = lastid;
this.increment = increment;
this.updatetime = updatetime;
}
public SerialT(String biz, String head, String lastid, int increment,
Date updatetime) {
this.biz = biz;
this.head = head;
this.lastid = lastid;
this.increment = increment;
this.updatetime = updatetime;
}
@Id
@Column(name = "BIZ", unique = true, nullable = false, length = 45)
public String getBiz() {
return this.biz;
}
public void setBiz(String biz) {
this.biz = biz;
}
@Column(name = "HEAD", length = 20)
public String getHead() {
return this.head;
}
public void setHead(String head) {
this.head = head;
}
@Column(name = "LASTID", nullable = false, length = 20)
public String getLastid() {
return this.lastid;
}
public void setLastid(String lastid) {
this.lastid = lastid;
}
@Column(name = "INCREMENT", nullable = false)
public int getIncrement() {
return this.increment;
}
public void setIncrement(int increment) {
this.increment = increment;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "UPDATETIME", nullable = false, length = 0)
public Date getUpdatetime() {
return this.updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
}
| gpl-3.0 |
matthiaskoenig/cy2sbml | src/cysbml/biomodel/SearchBioModel.java | 3557 | package cysbml.biomodel;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import cytoscape.Cytoscape;
import cytoscape.task.ui.JTaskConfig;
import cytoscape.task.util.TaskManager;
import uk.ac.ebi.biomodels.ws.SimpleModel;
public class SearchBioModel {
private SearchContent searchContent;
private List<String> modelIds;
private LinkedHashMap<String, SimpleModel> simpleModels;
private BioModelWSInterface bmInterface;
public SearchBioModel(String proxyHost, String proxyPort){
bmInterface = new BioModelWSInterface(proxyHost, proxyPort);
resetSearch();
}
private void resetSearch(){
searchContent = null;
modelIds = new LinkedList<String>();
simpleModels = new LinkedHashMap<String, SimpleModel>();
}
public List<String> getModelIds() {
return modelIds;
}
public String getModelId(int index){
return modelIds.get(index);
}
public LinkedHashMap<String, SimpleModel> getSimpleModels(){
return simpleModels;
}
public SimpleModel getSimpleModel(int index){
return simpleModels.get(index);
}
public int getSize(){
return modelIds.size();
}
public void searchBioModels(SearchContent sContent){
resetSearch();
searchContent = sContent;
modelIds = searchModelIdsForSearchContent(searchContent);
simpleModels = getSimpleModelsForSearchResult(modelIds);
}
public void getBioModelsByParsedIds(Set<String> parsedIds){
resetSearch();
HashMap<String, String> map = new HashMap<String, String>();
map.put(SearchContent.CONTENT_MODE, SearchContent.PARSED_IDS);
searchContent = new SearchContent(map);
modelIds = new LinkedList<String>(parsedIds);
simpleModels = getSimpleModelsForSearchResult(modelIds);
}
private LinkedHashMap<String, SimpleModel> getSimpleModelsForSearchResult(List<String> idsList){
String[] ids = (String[]) idsList.toArray();
return bmInterface.getSimpleModelsByIds(ids);
}
private List<String> searchModelIdsForSearchContent(SearchContent content){
SearchBioModelTask task = new SearchBioModelTask(content, bmInterface);
JTaskConfig jTaskConfig = new JTaskConfig();
jTaskConfig.setOwner(Cytoscape.getDesktop());
jTaskConfig.displayCloseButton(false);
jTaskConfig.displayCancelButton(true);
jTaskConfig.displayStatus(true);
jTaskConfig.setAutoDispose(true);
TaskManager.executeTask(task, jTaskConfig);
return task.getIds();
}
public static void addIdsToResultIds(final List<String> ids, List<String> resultIds, final String mode){
// OR -> combine all results
if (mode.equals(SearchContent.CONNECT_OR)){
resultIds.addAll(ids);
}
// AND -> only the combination results of all search terms
if (mode.equals(SearchContent.CONNECT_AND)){
if (resultIds.size() > 0){
resultIds.retainAll(ids);
} else {
resultIds.addAll(ids);
}
}
}
public String getHTMLInformation(final List<String> selectedModelIds){
String info = getHTMLHeaderForModelSearch();
info += BioModelWSInterfaceTools.getHTMLInformationForSimpleModels(simpleModels, selectedModelIds);
return BioModelGUIText.getString(info);
}
private String getHTMLHeaderForModelSearch(){
String info = String.format(
"<h2>%d BioModels found for </h2>" +
"<hr>", getSize());
info += searchContent.toHTML();
info += "<hr>";
return info;
}
public String getHTMLInformationForModel(int modelIndex){
SimpleModel simpleModel = getSimpleModel(modelIndex);
return BioModelWSInterfaceTools.getHTMLInformationForSimpleModel(simpleModel);
}
}
| gpl-3.0 |
sudo-rm-rf-523/RideShare-AndroidApp | RideShare/app/src/main/java/sudo_rm_rf/rideshare/OneFragment.java | 13644 | package sudo_rm_rf.rideshare;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
//import android.icu.text.SimpleDateFormat;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.content.Intent;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TimePicker;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import android.view.View.OnClickListener;
import java.util.Calendar;
import java.util.Locale;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class OneFragment extends Fragment implements View.OnClickListener {
//UI References
private EditText fromDateEtxt;
private EditText toDateEtxt;
private EditText timeEtxt;
private EditText fromPlace;
private EditText toPlace;
private Spinner mspin;
private DatePickerDialog fromDatePickerDialog;
private DatePickerDialog toDatePickerDialog;
private TimePickerDialog timePickerDialog;
private boolean fromPlaceclicked = false;
private boolean toPlaceclicked = false;
private SimpleDateFormat dateFormatter;
private int mYear, mMonth, mDay, mHour, mMinute;
private static final int PLACE_PICKER_REQUEST = 1;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
RadioGroup radio_group;
public OneFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void findViewsById(View myView) {
fromDateEtxt = (EditText) myView.findViewById(R.id.etxt_fromdate);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
//toDateEtxt = (EditText) myView.findViewById(R.id.etxt_todate);
//toDateEtxt.setInputType(InputType.TYPE_NULL);
timeEtxt = (EditText) myView.findViewById(R.id.etxt_time);
timeEtxt.setInputType(InputType.TYPE_NULL);
fromPlace = (EditText) myView.findViewById(R.id.from_place);
fromPlace.setInputType(InputType.TYPE_NULL);
toPlace = (EditText) myView.findViewById(R.id.to_place);
toPlace.setInputType(InputType.TYPE_NULL);
mspin=(Spinner) myView.findViewById(R.id.spinner1);
Integer[] items = new Integer[]{1,2,3,4};
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(getActivity(),android.R.layout.simple_spinner_item, items);
mspin.setAdapter(adapter);
}
@Override
public void onClick(View view) {
if(view == fromDateEtxt) {
fromDatePickerDialog.show();
} else if(view == timeEtxt) {
timePickerDialog.show();
}
// else if (view == toDateEtxt)
// {
// //toDatePickerDialog.show();
// }
}
private void setDateTimeField() {
fromPlace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
fromPlaceclicked = true;
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
Intent intent = intentBuilder.build(getActivity());
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
toPlace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
toPlaceclicked = true;
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
Intent intent = intentBuilder.build(getActivity());
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
Calendar toCalendar = Calendar.getInstance();
// toDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
//
// public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// Calendar newDate = Calendar.getInstance();
// newDate.set(year, monthOfYear, dayOfMonth);
// toDateEtxt.setText(dateFormatter.format(newDate.getTime()));
// }
//
// }, toCalendar.get(Calendar.YEAR), toCalendar.get(Calendar.MONTH), toCalendar.get(Calendar.DAY_OF_MONTH));
// Get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
timePickerDialog = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
timeEtxt.setText(hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View myView = inflater.inflate(R.layout.fragment_one, container, false);
final Button v = (Button) myView.findViewById(R.id.button);
final Button last = (Button) myView.findViewById(R.id.button2);
dateFormatter = new java.text.SimpleDateFormat("dd-MM-yyyy", Locale.US);
findViewsById(myView);
setDateTimeField();
fromDateEtxt.setOnClickListener(this);
//toDateEtxt.setOnClickListener(this);
timeEtxt.setOnClickListener(this);
fromDateEtxt.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (!hasFocus)
{
if (fromDateEtxt.getText().length() != 0)
{
fromDateEtxt.setError(null);
}
}
}
});
fromPlace.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (!hasFocus)
{
if (fromPlace.getText().length() != 0)
{
fromPlace.setError(null);
}
}
}
});
toPlace.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (!hasFocus)
{
if (toPlace.getText().length() != 0)
{
toPlace.setError(null);
}
}
}
});
timeEtxt.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
if (!hasFocus)
{
if (timeEtxt.getText().length() != 0)
{
timeEtxt.setError(null);
}
}
}
});
v.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean valid = true;
if (fromDateEtxt.getText().length() == 0)
{
valid = false;
fromDateEtxt.setError("Please enter a starting date");
}
else
fromDateEtxt.setError(null);
if (fromPlace.getText().length() == 0)
{
valid = false;
fromPlace.setError("Please enter a starting place");
}
else
fromPlace.setError(null);
if (toPlace.getText().length() == 0)
{
valid = false;
toPlace.setError("Please enter a destination");
}
else
toPlace.setError(null);
if (timeEtxt.getText().length() == 0) {
valid = false;
timeEtxt.setError("Please enter a convenient time");
}
else {
timeEtxt.setError(null);
}
if (valid){
startActivity(new Intent(getActivity(), NewsFeed.class));
}
}
});
last.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
fromPlace.setText("Champaign");
toPlace.setText("Chicago");
}
});
//radio_group = (RadioGroup) myView.findViewById(R.id.trip_type);
//radio_group.check(0);
return myView;
}
// public void onRadioButtonClicked(View view) {
// // Is the button now checked?
// boolean checked = ((RadioButton) view).isChecked();
//
// // Check which radio button was clicked
// switch(view.getId()) {
// case R.id.one_way:
// if (checked)
// toDateEtxt.setEnabled(false);
// toDateEtxt.setVisibility(View.GONE);
// // Pirates are the best
// break;
// case R.id.round_trip:
// if (checked)
// // Ninjas rule
// toDateEtxt.setEnabled(true);
// toDateEtxt.setVisibility(View.VISIBLE);
// break;
// }
// }
@Override
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(getActivity(), data);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
String temp = name.toString() + address.toString().replaceAll("\\)", "");
if (fromPlaceclicked == true) {
fromPlace.setText(name.toString());
fromPlaceclicked = false;
}
else
{
toPlace.setText(name.toString());
toPlaceclicked = false;
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
| gpl-3.0 |
Tabishk/_funtool | Restaurante/src/main/java/com/net/resto/App.java | 176 | package com.net.resto;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| gpl-3.0 |
Dica-Developer/weplantaforest | user/src/test/java/org/dicadeveloper/weplantaforest/user/UserServiceTest.java | 16207 | package org.dicadeveloper.weplantaforest.user;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.dicadeveloper.weplantaforest.common.errorhandling.ErrorCodes;
import org.dicadeveloper.weplantaforest.common.errorhandling.IpatException;
import org.dicadeveloper.weplantaforest.common.support.Language;
import org.dicadeveloper.weplantaforest.encryption.PasswordEncrypter;
import org.dicadeveloper.weplantaforest.testsupport.DbInjecter;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest({ "spring.profiles.active=test" })
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class UserServiceTest {
@Autowired
private UserRepository _userRepository;
@Autowired
UserService _userService;
@Autowired
private PasswordEncrypter _passwordEncrypter;
@Autowired
private DbInjecter _dbInjecter;
private static String userName = "User";
@Test
public void testARegistrateUserUserNameAlreadyExists() {
_dbInjecter.injectUser("Adam", "adam@iplantatree.de");
UserRegistrationData userRegistrationData = new UserRegistrationData();
userRegistrationData.setUsername("Adam");
try {
_userService.registrateUser(userRegistrationData);
} catch (IpatException e) {
assertEquals(ErrorCodes.USER_ALREADY_EXISTS, e.getErrorInfos().get(0).getErrorCode());
}
assertEquals(1, _userRepository.count());
}
@Test
public void testBARegistrateUserInvalidMail() {
UserRegistrationData userRegistrationData = new UserRegistrationData();
userRegistrationData.setUsername(userName);
userRegistrationData.setMail("invalid-mail");
;
try {
_userService.registrateUser(userRegistrationData);
} catch (IpatException e) {
assertEquals(ErrorCodes.INVALID_MAIL, e.getErrorInfos().get(0).getErrorCode());
}
assertEquals(1, _userRepository.count());
}
@Test
public void testCARegistrateUserMailAlreadyExists() {
UserRegistrationData userRegistrationData = new UserRegistrationData();
userRegistrationData.setUsername(userName);
userRegistrationData.setMail("adam@iplantatree.de");
;
try {
_userService.registrateUser(userRegistrationData);
} catch (IpatException e) {
assertEquals(ErrorCodes.MAIL_ALREADY_EXISTS, e.getErrorInfos().get(0).getErrorCode());
}
assertEquals(1, _userRepository.count());
}
@Test
public void testDARegistrateUserSuccess() {
UserRegistrationData userRegistrationData = new UserRegistrationData();
userRegistrationData.setUsername(userName);
userRegistrationData.setMail("user@iplantatree.de");
userRegistrationData.setOrgType(OrganizationType.PRIVATE.toString());
userRegistrationData.setLanguage(Language.DEUTSCH.toString());
try {
_userService.registrateUser(userRegistrationData);
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("user registration should not fail here\nerrorCode:" + errorCode);
}
assertEquals(2, _userRepository.count());
User registratedUser = _userRepository.findByName(userName);
assertEquals(false, registratedUser.isEnabled());
}
@Test
public void testEactivateUserInvalidKey() {
User registratedUser = _userRepository.findByName(userName);
String activationKey = "invalid_key";
try {
_userService.activateUser(2L, activationKey);
} catch (IpatException e) {
assertEquals(ErrorCodes.INVALID_ACTIVATION_KEY, e.getErrorInfos().get(0).getErrorCode());
}
registratedUser = _userRepository.findByName(userName);
assertEquals(false, registratedUser.isEnabled());
}
@Test
public void testFcreatePasswordResetMailUserNotActivated() {
try {
_userService.createPasswordResetMail(userName);
} catch (IpatException e) {
assertEquals(ErrorCodes.USER_NOT_ACTIVATED, e.getErrorInfos().get(0).getErrorCode());
}
}
@Test
public void testGactivateUserSuccess() {
User registratedUser = _userRepository.findByName(userName);
String activationKey = registratedUser.getActivationKey();
try {
_userService.activateUser(2L, activationKey);
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("user registration should not fail here\nerrorCode:" + errorCode);
}
registratedUser = _userRepository.findByName(userName);
assertEquals(true, registratedUser.isEnabled());
}
@Test
public void testHactivateUserAlreadyActivated() {
User registratedUser = _userRepository.findByName(userName);
String activationKey = registratedUser.getActivationKey();
try {
_userService.activateUser(2L, activationKey);
} catch (IpatException e) {
assertEquals(ErrorCodes.USER_ALREADY_ACTIVATED, e.getErrorInfos().get(0).getErrorCode());
}
registratedUser = _userRepository.findByName(userName);
assertEquals(true, registratedUser.isEnabled());
}
@Test
public void testIcreatePasswordResetMailSuccess() {
try {
_userService.createPasswordResetMail(userName);
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("creating password reset mail should not fail here\nerrorCode:" + errorCode);
}
}
@Test
public void testJverifyPasswordResetLinkInvalidKey() {
String activationKey = "invalidKey";
try {
_userService.verifiyPasswordResetLink(2L, activationKey);
} catch (IpatException e) {
assertEquals(ErrorCodes.INVALID_ACTIVATION_KEY, e.getErrorInfos().get(0).getErrorCode());
}
}
@Test
public void testKverifyPasswordResetLinkSuccess() {
User registratedUser = _userRepository.findByName(userName);
String activationKey = registratedUser.getActivationKey();
try {
_userService.verifiyPasswordResetLink(2L, activationKey);
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("verify password reset link should not fail here\nerrorCode:" + errorCode);
}
}
@Test
public void testLresetPasswordForUserInvalidKey() {
String activationKey = "invalidKey";
try {
_userService.resetPasswordForUser(2L, activationKey, "newPassword");
} catch (IpatException e) {
assertEquals(ErrorCodes.INVALID_ACTIVATION_KEY, e.getErrorInfos().get(0).getErrorCode());
}
}
@Test
public void testMresetPasswordForUserSuccess() {
User registratedUser = _userRepository.findByName(userName);
String activationKey = registratedUser.getActivationKey();
try {
_userService.resetPasswordForUser(2L, activationKey, "newPassword");
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("reset password should not fail here\nerrorCode:" + errorCode);
}
registratedUser = _userRepository.findByName(userName);
assertNotNull(registratedUser.getPassword());
}
@Test
public void testNcreateAnonymousUser() {
User user = null;
try {
user = _userService.createAnonymous();
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("creating anonymous should not fail here\nerrorCode:" + errorCode);
}
assertNotNull(user);
}
@Test
public void testOAtestEditUserEditNameAlreadyExists() {
try {
_userService.editUser(userName, "NAME", "Adam");
} catch (IpatException e) {
assertEquals(ErrorCodes.USER_ALREADY_EXISTS, e.getErrorInfos().get(0).getErrorCode());
}
}
@Test
public void testOBtestEditUserEditNameSuccess() {
try {
_userService.editUser(userName, "NAME", "Edited_User");
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("edit username should not fail here\nerrorCode:" + errorCode);
}
userName = "Edited_User";
}
@Test
public void testOCeditUserEditAboutMe() {
try {
_userService.editUser(userName, "ABOUTME", "aboutme");
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("edit aboutme should not fail here\nerrorCode:" + errorCode);
}
User editedUser = _userRepository.findById(2L).orElse(null);
assertNotNull(editedUser);
assertEquals("aboutme", editedUser.getAboutMe());
}
@Test
public void testODeditUserEditLocation() {
try {
_userService.editUser(userName, "LOCATION", "location");
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("edit location should not fail here\nerrorCode:" + errorCode);
}
User editedUser = _userRepository.findById(2L).orElse(null);
assertNotNull(editedUser);
assertEquals("location", editedUser.getLocation());
}
@Test
public void testOEeditUserEditOrganisation() {
try {
_userService.editUser(userName, "ORGANISATION", "organisation");
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("edit organisation should not fail here\nerrorCode:" + errorCode);
}
User editedUser = _userRepository.findById(2L).orElse(null);
assertNotNull(editedUser);
assertEquals("organisation", editedUser.getOrganisation());
}
@Test
public void testOFeditUserEditHomepage() {
try {
_userService.editUser(userName, "HOMEPAGE", "homepage");
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("edit homepage should not fail here\nerrorCode:" + errorCode);
}
User editedUser = _userRepository.findById(2L).orElse(null);
assertNotNull(editedUser);
assertEquals("homepage", editedUser.getHomepage());
}
@Test
public void testOGeditUserEditMailInvalidMail() {
try {
_userService.editUser(userName, "MAIL", "invalid_mail");
} catch (IpatException e) {
assertEquals(ErrorCodes.INVALID_MAIL, e.getErrorInfos().get(0).getErrorCode());
}
}
@Test
public void testOHeditUserEditMailAlreadyExists() {
try {
_userService.editUser(userName, "MAIL", "adam@iplantatree.de");
} catch (IpatException e) {
assertEquals(ErrorCodes.MAIL_ALREADY_EXISTS, e.getErrorInfos().get(0).getErrorCode());
}
}
@Test
public void testOIeditUserEditMailSuccess() {
try {
_userService.editUser(userName, "MAIL", "edited_user@iplantatree.de");
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("edit mail should not fail here\nerrorCode:" + errorCode);
}
User editedUser = _userRepository.findById(2L).orElse(null);
assertNotNull(editedUser);
assertEquals("edited_user@iplantatree.de", editedUser.getMail());
}
@Test
public void testOJeditUserEditNewsletter() {
try {
_userService.editUser(userName, "NEWSLETTER", "JA");
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("edit newsletter should not fail here\nerrorCode:" + errorCode);
}
User editedUser = _userRepository.findById(2L).orElse(null);
assertNotNull(editedUser);
assertEquals(true, editedUser.isNewsletter());
}
@Test
public void testOKeditUserEditOrganizationType() {
try {
_userService.editUser(userName, "ORGANIZATION_TYPE", OrganizationType.COMMERCIAL.toString());
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("edit organiization type should not fail here\nerrorCode:" + errorCode);
}
User editedUser = _userRepository.findById(2L).orElse(null);
assertNotNull(editedUser);
assertEquals(OrganizationType.COMMERCIAL, editedUser.getOrganizationType());
}
@Test
public void testOLeditUserEditLanguage() {
try {
_userService.editUser(userName, "LANGUAGE", Language.ENGLISH.toString());
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("edit language should not fail here\nerrorCode:" + errorCode);
}
User editedUser = _userRepository.findById(2L).orElse(null);
assertNotNull(editedUser);
assertEquals(Language.ENGLISH, editedUser.getLang());
}
@Test
public void testOMeditPassword() {
try {
_userService.editUser(userName, "PASSWORD", "new_password");
} catch (IpatException e) {
String errorCode = e.getErrorInfos().get(0).getErrorCode();
fail("edit language should not fail here\nerrorCode:" + errorCode);
}
User editedUser = _userRepository.findById(2L).orElse(null);
assertNotNull(editedUser);
assertEquals(_passwordEncrypter.encryptPassword("new_password"), editedUser.getPassword());
}
@Test
public void testPgetUserDetails() {
_dbInjecter.injectTreeType("wood", "desc", 0.5);
_dbInjecter.injectProject("Project", "Adam", "very n1 project", true, 0, 0);
_dbInjecter.injectProjectArticle("wood", "Project", 3.0);
_dbInjecter.injectTreeToProject("wood", userName, 1, 900000L, "Project");
_dbInjecter.injectTreeToProject("wood", "Adam", 2, 900000L, "Project");
UserReportData userData = _userService.getUserDetails(userName, true);
assertEquals(userName, userData.getUserName());
assertEquals(2, userData.getRank());
assertEquals(1L, userData.getCo2Data().getTreesCount().longValue());
assertEquals("aboutme", userData.getAboutMe());
assertEquals("location", userData.getLocation());
assertEquals("organisation", userData.getOrganisation());
assertEquals("homepage", userData.getHomepage());
assertEquals("edited_user@iplantatree.de", userData.getMail());
assertEquals("JA", userData.getNewsletter());
assertEquals(OrganizationType.COMMERCIAL, userData.getOrganizationType());
assertEquals(Language.ENGLISH, userData.getLang());
}
@Test
public void testQAnonymizeUser() {
_dbInjecter.injectUser("UserToAnonymize", "userToAnonymize@iplantatree.de");
User user = null;
try {
user = _userService.anonymizeUser("Adam");
} catch (IpatException e) {
}
assertThat(user.getName(), containsString("Anonymous"));
assertEquals(user.getMail(), "");
}
}
| gpl-3.0 |
liyi-david/ePMC | plugins/jani-model/src/main/java/epmc/jani/model/type/JANITypeInt.java | 2409 | /****************************************************************************
ePMC - an extensible probabilistic model checker
Copyright (C) 2017
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
package epmc.jani.model.type;
import javax.json.JsonString;
import javax.json.JsonValue;
import epmc.jani.model.JANINode;
import epmc.jani.model.ModelJANI;
import epmc.jani.model.UtilModelParser;
import epmc.util.UtilJSON;
import epmc.value.TypeInteger;
import epmc.value.UtilValue;
import epmc.value.Value;
public final class JANITypeInt implements JANIType {
public final static String IDENTIFIER = "int";
/** Identifier for integer type. */
private final static String INT = "int";
private ModelJANI model;
@Override
public void setModel(ModelJANI model) {
this.model = model;
}
@Override
public ModelJANI getModel() {
return model;
}
@Override
public JANINode parse(JsonValue value) {
return parseAsJANIType(value);
}
@Override
public JANIType parseAsJANIType(JsonValue value) {
if (!(value instanceof JsonString)) {
return null;
}
JsonString valueString = (JsonString) value;
if (!valueString.getString().equals(INT)) {
return null;
}
return this;
}
@Override
public JsonValue generate() {
return UtilJSON.toStringValue(INT);
}
@Override
public TypeInteger toType() {
return TypeInteger.get();
}
@Override
public Value getDefaultValue() {
return UtilValue.newValue(toType(), 0);
}
@Override
public String toString() {
return UtilModelParser.toString(this);
}
}
| gpl-3.0 |
ghacupha/paycal | src/main/java/com/babel88/paycal/config/factory/GeneralFactory.java | 1309 | package com.babel88.paycal.config.factory;
import com.babel88.paycal.api.view.Tables;
import com.babel88.paycal.view.tables.TablesImpl;
import org.jetbrains.annotations.Contract;
/**
* factory containing general purpose objects
*
* Created by edwin.njeru on 8/23/17.
*/
@Deprecated
public class GeneralFactory {
private static GeneralFactory instance = new GeneralFactory();
@Contract(pure = true)
public static GeneralFactory getInstance() {
return instance;
}
// public static InvoiceDetails createInvoice(){
//
// return Invoice.getInstance();
// }
// public static FeedBack createFeedback(){
//
// return FeedBackImpl.getInstance();
// }
// public static LoggingAspect createLoggingAspect(){
//
// return LoggingAspect.getInstance();
// }
// public static Tables createTables(){
//
// return TablesImpl.getInstance();
// }
// public static PrepaymentDetails createPrepaymentDetails(){
//
// return (PrepaymentDetails)createInvoice();
// }
//
// public static ForeignPaymentDetails createForeignPaymentDetails(){
//
// return (ForeignPaymentDetails)createInvoice();
// }
// public static PaymentFactory createPaymentFactory(){
//
// return PaymentFactory.getInstance();
// }
}
| gpl-3.0 |
wariotx/pixel-dungeon-remix | PixelDungeon/src/main/java/com/nyrds/pixeldungeon/mobs/guts/YogsTeeth.java | 673 | package com.nyrds.pixeldungeon.mobs.guts;
import com.watabou.pixeldungeon.actors.Char;
import com.watabou.pixeldungeon.actors.mobs.Mob;
import com.watabou.pixeldungeon.items.Gold;
import com.watabou.utils.Random;
/**
* Created by DeadDie on 12.02.2016
*/
public class YogsTeeth extends Mob {
{
hp(ht(60));
defenseSkill = 24;
EXP = 16;
loot = Gold.class;
lootChance = 0.5f;
}
@Override
public int damageRoll() {
return Random.NormalIntRange(10, 50);
}
@Override
public int attackSkill( Char target ) {
return 26;
}
@Override
public int dr() {
return 2;
}
}
| gpl-3.0 |
sudo-rm-rf-523/RideShare-AndroidApp | RideShare/app/src/androidTest/java/sudo_rm_rf/rideshare/ExampleInstrumentedTest.java | 744 | package sudo_rm_rf.rideshare;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("sudo_rm_rf.rideshare", appContext.getPackageName());
}
}
| gpl-3.0 |
ImagoTrigger/sdrtrunk | src/main/java/io/github/dsheirer/source/tuner/hackrf/HackRFTunerController.java | 23860 | /*
*
* * ******************************************************************************
* * Copyright (C) 2014-2020 Dennis Sheirer
* *
* * This program is free software: you can redistribute it and/or modify
* * it under the terms of the GNU General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * 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 General Public License for more details.
* *
* * You should have received a copy of the GNU General Public License
* * along with this program. If not, see <http://www.gnu.org/licenses/>
* * *****************************************************************************
*
*
*/
package io.github.dsheirer.source.tuner.hackrf;
import io.github.dsheirer.source.SourceException;
import io.github.dsheirer.source.tuner.configuration.TunerConfiguration;
import io.github.dsheirer.source.tuner.usb.USBTransferProcessor;
import io.github.dsheirer.source.tuner.usb.USBTunerController;
import io.github.dsheirer.source.tuner.usb.converter.ByteSampleConverter;
import io.github.dsheirer.source.tuner.usb.converter.NativeBufferConverter;
import org.apache.commons.io.EndianUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
import javax.usb.UsbException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
public class HackRFTunerController extends USBTunerController
{
private final static Logger mLog = LoggerFactory.getLogger(HackRFTunerController.class);
public final static long USB_TIMEOUT_US = 1000000l; //uSeconds
public static final byte USB_ENDPOINT = (byte)0x81;
public static final byte USB_INTERFACE = (byte)0x0;
public static final int USB_TRANSFER_BUFFER_SIZE = 262144;
public static final byte REQUEST_TYPE_IN = (byte)(LibUsb.ENDPOINT_IN | LibUsb.REQUEST_TYPE_VENDOR | LibUsb.RECIPIENT_DEVICE);
public static final byte REQUEST_TYPE_OUT = (byte)(LibUsb.ENDPOINT_OUT | LibUsb.REQUEST_TYPE_VENDOR | LibUsb.RECIPIENT_DEVICE);
public static final long MIN_FREQUENCY = 10000000l;
public static final long MAX_FREQUENCY = 6000000000l;
public static final long DEFAULT_FREQUENCY = 101100000;
public static final double USABLE_BANDWIDTH_PERCENT = 0.95;
public static final int DC_SPIKE_AVOID_BUFFER = 5000;
private NativeBufferConverter mNativeBufferConverter = new ByteSampleConverter();
private USBTransferProcessor mUSBTransferProcessor;
private HackRFSampleRate mSampleRate = HackRFSampleRate.RATE2_016MHZ;
private boolean mAmplifierEnabled = false;
private Device mDevice;
private DeviceDescriptor mDeviceDescriptor;
private DeviceHandle mDeviceHandle;
public HackRFTunerController(Device device, DeviceDescriptor descriptor) throws SourceException
{
super(MIN_FREQUENCY, MAX_FREQUENCY, DC_SPIKE_AVOID_BUFFER, USABLE_BANDWIDTH_PERCENT);
mDevice = device;
mDeviceDescriptor = descriptor;
}
@Override
public int getBufferSampleCount()
{
return USB_TRANSFER_BUFFER_SIZE / 2;
}
public void init() throws SourceException
{
mDeviceHandle = new DeviceHandle();
int result = LibUsb.open(mDevice, mDeviceHandle);
if(result != 0)
{
if(result == LibUsb.ERROR_ACCESS)
{
mLog.error("Unable to access HackRF - insufficient permissions. "
+ "If you are running a Linux OS, have you installed the "
+ "hackRF rules file in \\etc\\udev\\rules.d ??");
}
throw new SourceException("Couldn't open hackrf device - " +
LibUsb.strError(result));
}
try
{
claimInterface();
setMode(Mode.RECEIVE);
setFrequency(DEFAULT_FREQUENCY);
}
catch(Exception e)
{
throw new SourceException("HackRF Tuner Controller - couldn't "
+ "claim USB interface or get endpoint or pipe", e);
}
String name;
try
{
name = "HackRF " + getSerial().getSerialNumber();
}
catch(UsbException ue)
{
//Do nothing, we couldn't determine the serial number
name = "HackRF - Unidentified Serial";
}
mUSBTransferProcessor = new USBTransferProcessor(name, mDeviceHandle, mNativeBufferConverter,
USB_TRANSFER_BUFFER_SIZE, this);
}
@Override
public void dispose()
{
if(mDeviceHandle != null)
{
mLog.info("Releasing HackRF Tuner");
try
{
LibUsb.close(mDeviceHandle);
}
catch(Exception e)
{
mLog.error("error while closing device handle", e);
}
mDeviceHandle = null;
}
}
@Override
protected USBTransferProcessor getUSBTransferProcessor()
{
return mUSBTransferProcessor;
}
/**
* Claims the USB interface. If another application currently has
* the interface claimed, the USB_FORCE_CLAIM_INTERFACE setting
* will dictate if the interface is forcibly claimed from the other
* application
*/
private void claimInterface() throws SourceException
{
if(mDeviceHandle != null)
{
int result = LibUsb.kernelDriverActive(mDeviceHandle, USB_INTERFACE);
if(result == 1)
{
result = LibUsb.detachKernelDriver(mDeviceHandle, USB_INTERFACE);
if(result != LibUsb.SUCCESS)
{
mLog.error("failed attempt to detach kernel driver [" +
LibUsb.errorName(result) + "]");
throw new SourceException("couldn't detach kernel driver "
+ "from device");
}
}
result = LibUsb.claimInterface(mDeviceHandle, USB_INTERFACE);
if(result != LibUsb.SUCCESS)
{
throw new SourceException("couldn't claim usb interface [" +
LibUsb.errorName(result) + "]");
}
}
else
{
throw new SourceException("couldn't claim usb interface - no "
+ "device handle");
}
}
/**
* HackRF board identifier/type
*/
public BoardID getBoardID() throws UsbException
{
int id = readByte(Request.BOARD_ID_READ, (byte)0, (byte)0, false);
return BoardID.lookup(id);
}
/**
* HackRF firmware version string
*/
public String getFirmwareVersion() throws UsbException
{
ByteBuffer buffer = readArray(Request.VERSION_STRING_READ, 0, 0, 255);
byte[] data = new byte[255];
buffer.get(data);
return new String(data);
}
/**
* HackRF part id number and serial number
*/
public Serial getSerial() throws UsbException
{
ByteBuffer buffer = readArray(Request.BOARD_PARTID_SERIALNO_READ, 0, 0, 24);
return new Serial(buffer);
}
/**
* Sets the HackRF transceiver mode
*/
public void setMode(Mode mode) throws UsbException
{
write(Request.SET_TRANSCEIVER_MODE, mode.getNumber(), 0);
}
/**
* Sets the HackRF baseband filter
*/
public void setBasebandFilter(BasebandFilter filter) throws UsbException
{
write(Request.BASEBAND_FILTER_BANDWIDTH_SET,
filter.getLowValue(),
filter.getHighValue());
}
/**
* Enables (true) or disables (false) the amplifier
*/
public void setAmplifierEnabled(boolean enabled) throws UsbException
{
write(Request.AMP_ENABLE, (enabled ? 1 : 0), 0);
mAmplifierEnabled = enabled;
}
public boolean getAmplifier()
{
return mAmplifierEnabled;
}
/**
* Sets the IF LNA Gain
*/
public void setLNAGain(HackRFLNAGain gain) throws UsbException
{
int result = readByte(Request.SET_LNA_GAIN, 0, gain.getValue(), true);
if(result != 1)
{
throw new UsbException("couldn't set lna gain to " + gain);
}
}
/**
* Sets the Baseband VGA Gain
*/
public void setVGAGain(HackRFVGAGain gain) throws UsbException
{
int result = readByte(Request.SET_VGA_GAIN, 0, gain.getValue(), true);
if(result != 1)
{
throw new UsbException("couldn't set vga gain to " + gain);
}
}
/**
* Not implemented
*/
public long getTunedFrequency() throws SourceException
{
return mFrequencyController.getTunedFrequency();
}
@Override
public void setTunedFrequency(long frequency) throws SourceException
{
ByteBuffer buffer = ByteBuffer.allocateDirect(8);
buffer.order(ByteOrder.LITTLE_ENDIAN);
int mhz = (int)(frequency / 1E6);
int hz = (int)(frequency - (mhz * 1E6));
buffer.putInt(mhz);
buffer.putInt(hz);
buffer.rewind();
try
{
write(Request.SET_FREQUENCY, 0, 0, buffer);
}
catch(UsbException e)
{
mLog.error("error setting frequency [" + frequency + "]", e);
throw new SourceException("error setting frequency [" +
frequency + "]", e);
}
}
@Override
public double getCurrentSampleRate()
{
return mSampleRate.getRate();
}
@Override
public void apply(TunerConfiguration config) throws SourceException
{
if(config instanceof HackRFTunerConfiguration)
{
HackRFTunerConfiguration hackRFConfig =
(HackRFTunerConfiguration)config;
try
{
setSampleRate(hackRFConfig.getSampleRate());
setFrequencyCorrection(hackRFConfig.getFrequencyCorrection());
setAmplifierEnabled(hackRFConfig.getAmplifierEnabled());
setLNAGain(hackRFConfig.getLNAGain());
setVGAGain(hackRFConfig.getVGAGain());
setFrequency(getFrequency());
}
catch(UsbException e)
{
throw new SourceException("Error while applying tuner "
+ "configuration", e);
}
try
{
setFrequency(hackRFConfig.getFrequency());
}
catch(SourceException se)
{
//Do nothing, we couldn't set the frequency
}
}
else
{
throw new IllegalArgumentException("Invalid tuner configuration "
+ "type [" + config.getClass() + "]");
}
}
public ByteBuffer readArray(Request request,
int value,
int index,
int length) throws UsbException
{
if(mDeviceHandle != null)
{
ByteBuffer buffer = ByteBuffer.allocateDirect(length);
int transferred = LibUsb.controlTransfer(mDeviceHandle,
REQUEST_TYPE_IN,
request.getRequestNumber(),
(short)value,
(short)index,
buffer,
USB_TIMEOUT_US);
if(transferred < 0)
{
throw new LibUsbException("read error", transferred);
}
return buffer;
}
else
{
throw new LibUsbException("device handle is null",
LibUsb.ERROR_NO_DEVICE);
}
}
public int read(Request request, int value, int index, int length)
throws UsbException
{
if(!(length == 1 || length == 2 || length == 4))
{
throw new IllegalArgumentException("invalid length [" + length +
"] must be: byte=1, short=2, int=4 to read a primitive");
}
ByteBuffer buffer = readArray(request, value, index, length);
byte[] data = new byte[buffer.capacity()];
buffer.get(data);
switch(data.length)
{
case 1:
return data[0];
case 2:
return EndianUtils.readSwappedShort(data, 0);
case 4:
return EndianUtils.readSwappedInteger(data, 0);
default:
throw new UsbException("read() primitive returned an "
+ "unrecognized byte array " + Arrays.toString(data));
}
}
public int readByte(Request request, int value, int index, boolean signed)
throws UsbException
{
ByteBuffer buffer = readArray(request, value, index, 1);
if(signed)
{
return (int)(buffer.get());
}
else
{
return (int)(buffer.get() & 0xFF);
}
}
public void write(Request request,
int value,
int index,
ByteBuffer buffer) throws UsbException
{
if(mDeviceHandle != null)
{
int transferred = LibUsb.controlTransfer(mDeviceHandle,
REQUEST_TYPE_OUT,
request.getRequestNumber(),
(short)value,
(short)index,
buffer,
USB_TIMEOUT_US);
if(transferred < 0)
{
throw new LibUsbException("error writing byte buffer",
transferred);
}
else if(transferred != buffer.capacity())
{
throw new LibUsbException("transferred bytes [" +
transferred + "] is not what was expected [" +
buffer.capacity() + "]", transferred);
}
}
else
{
throw new LibUsbException("device handle is null",
LibUsb.ERROR_NO_DEVICE);
}
}
/**
* Sends a request that doesn't have a data payload
*/
public void write(Request request,
int value,
int index) throws UsbException
{
write(request, value, index, ByteBuffer.allocateDirect(0));
}
/**
* Sample Rate
*
* Note: the libhackrf set sample rate method is designed to allow fractional
* sample rates. However, since we're only using integral sample rates, we
* simply invoke the setSampleRateManual method directly.
*/
public void setSampleRate(HackRFSampleRate rate) throws UsbException, SourceException
{
setSampleRateManual(rate.getRate(), 1);
mFrequencyController.setSampleRate(rate.getRate());
setBasebandFilter(rate.getFilter());
mSampleRate = rate;
}
public void setSampleRateManual(int frequency, int divider)
throws UsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect(8);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(frequency);
buffer.putInt(divider);
write(Request.SET_SAMPLE_RATE, 0, 0, buffer);
}
public double getSampleRate()
{
return mSampleRate.getRate();
}
public enum Request
{
SET_TRANSCEIVER_MODE(1),
MAX2837_TRANSCEIVER_WRITE(2),
MAX2837_TRANSCEIVER_READ(3),
SI5351C_CLOCK_GENERATOR_WRITE(4),
SI5351C_CLOCK_GENERATOR_READ(5),
SET_SAMPLE_RATE(6),
BASEBAND_FILTER_BANDWIDTH_SET(7),
RFFC5071_MIXER_WRITE(8),
RFFC5071_MIXER_READ(9),
SPIFLASH_ERASE(10),
SPIFLASH_WRITE(11),
SPIFLASH_READ(12),
BOARD_ID_READ(14),
VERSION_STRING_READ(15),
SET_FREQUENCY(16),
AMP_ENABLE(17),
BOARD_PARTID_SERIALNO_READ(18),
SET_LNA_GAIN(19),
SET_VGA_GAIN(20),
SET_TXVGA_GAIN(21),
ANTENNA_ENABLE(23),
SET_FREQUENCY_EXPLICIT(24);
private byte mRequestNumber;
private Request(int number)
{
mRequestNumber = (byte)number;
}
public byte getRequestNumber()
{
return mRequestNumber;
}
}
public enum HackRFSampleRate
{
RATE2_016MHZ(2016000, "2.016 MHz", BasebandFilter.F3_50),
RATE3_024MHZ(3024000, "3.024 MHz", BasebandFilter.F5_00),
RATE4_464MHZ(4464000, "4.464 MHz", BasebandFilter.F6_00),
RATE5_376MHZ(5376000, "5.376 MHz", BasebandFilter.F7_00),
RATE7_488MHZ(7488000, "7.488 MHz", BasebandFilter.F9_00),
RATE10_080MHZ(10080000, "10.080 MHz", BasebandFilter.F12_00),
RATE12_000MHZ(12000000, "12.000 MHz", BasebandFilter.F14_00),
RATE13_440MHZ(13440000, "13.440 MHz", BasebandFilter.F15_00),
RATE14_976MHZ(14976000, "14.976 MHz", BasebandFilter.F20_00),
RATE19_968MHZ(19968000, "19.968 MHz", BasebandFilter.F24_00);
private int mRate;
private String mLabel;
private BasebandFilter mFilter;
private HackRFSampleRate(int rate,
String label,
BasebandFilter filter)
{
mRate = rate;
mLabel = label;
mFilter = filter;
}
public int getRate()
{
return mRate;
}
public String getLabel()
{
return mLabel;
}
public String toString()
{
return mLabel;
}
public BasebandFilter getFilter()
{
return mFilter;
}
}
public enum BasebandFilter
{
FAUTO(0, "AUTO"),
F1_75(1750000, "1.75 MHz"),
F2_50(2500000, "2.50 MHz"),
F3_50(3500000, "3.50 MHz"),
F5_00(5000000, "5.00 MHz"),
F5_50(5500000, "5.50 MHz"),
F6_00(6000000, "6.00 MHz"),
F7_00(7000000, "7.00 MHz"),
F8_00(8000000, "8.00 MHz"),
F9_00(9000000, "9.00 MHz"),
F10_00(10000000, "10.00 MHz"),
F12_00(12000000, "12.00 MHz"),
F14_00(14000000, "14.00 MHz"),
F15_00(15000000, "15.00 MHz"),
F20_00(20000000, "20.00 MHz"),
F24_00(24000000, "24.00 MHz"),
F28_00(28000000, "28.00 MHz");
private int mBandwidth;
private String mLabel;
private BasebandFilter(int bandwidth, String label)
{
mBandwidth = bandwidth;
mLabel = label;
}
public int getBandwidth()
{
return mBandwidth;
}
public int getHighValue()
{
return mBandwidth >> 16;
}
public int getLowValue()
{
return mBandwidth & 0xFFFF;
}
public String getLabel()
{
return mLabel;
}
}
public enum BoardID
{
JELLYBEAN(0x00, "HackRF Jelly Bean"),
JAWBREAKER(0x01, "HackRF Jaw Breaker"),
HACKRF_ONE(0x02, "HackRF One"),
INVALID(0xFF, "HackRF Unknown Board");
private byte mIDNumber;
private String mLabel;
private BoardID(int number, String label)
{
mIDNumber = (byte)number;
mLabel = label;
}
public String toString()
{
return mLabel;
}
public String getLabel()
{
return mLabel;
}
public byte getNumber()
{
return mIDNumber;
}
public static BoardID lookup(int value)
{
switch(value)
{
case 0:
return JELLYBEAN;
case 1:
return JAWBREAKER;
case 2:
return HACKRF_ONE;
default:
return INVALID;
}
}
}
public enum Mode
{
OFF(0, "Off"),
RECEIVE(1, "Receive"),
TRANSMIT(2, "Transmit"),
SS(3, "SS");
private byte mNumber;
private String mLabel;
private Mode(int number, String label)
{
mNumber = (byte)number;
mLabel = label;
}
public byte getNumber()
{
return mNumber;
}
public String getLabel()
{
return mLabel;
}
public String toString()
{
return mLabel;
}
}
public enum HackRFLNAGain
{
GAIN_0(0),
GAIN_8(8),
GAIN_16(16),
GAIN_24(24),
GAIN_32(32),
GAIN_40(40);
private int mValue;
private HackRFLNAGain(int value)
{
mValue = value;
}
public int getValue()
{
return mValue;
}
public String toString()
{
return String.valueOf(mValue) + " dB";
}
}
/**
* Receive (baseband) VGA Gain values
*/
public enum HackRFVGAGain
{
GAIN_0(0),
GAIN_2(2),
GAIN_4(4),
GAIN_6(6),
GAIN_8(8),
GAIN_10(10),
GAIN_12(12),
GAIN_14(14),
GAIN_16(16),
GAIN_18(18),
GAIN_20(20),
GAIN_22(22),
GAIN_23(24),
GAIN_26(26),
GAIN_28(28),
GAIN_30(30),
GAIN_32(32),
GAIN_34(34),
GAIN_36(36),
GAIN_38(38),
GAIN_40(40),
GAIN_42(42),
GAIN_44(44),
GAIN_46(46),
GAIN_48(48),
GAIN_50(50),
GAIN_52(52),
GAIN_54(54),
GAIN_56(56),
GAIN_58(58),
GAIN_60(60),
GAIN_62(62);
private int mValue;
private HackRFVGAGain(int value)
{
mValue = value;
}
public int getValue()
{
return mValue;
}
public String toString()
{
return String.valueOf(mValue) + " dB";
}
}
/**
* HackRF part id and serial number parsing class
*/
public class Serial
{
private byte[] mData;
public Serial(ByteBuffer buffer)
{
mData = new byte[buffer.capacity()];
buffer.get(mData);
}
public String getPartID()
{
int part0 = EndianUtils.readSwappedInteger(mData, 0);
int part1 = EndianUtils.readSwappedInteger(mData, 4);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%08X", part0));
sb.append("-");
sb.append(String.format("%08X", part1));
return sb.toString();
}
public String getSerialNumber()
{
int serial0 = EndianUtils.readSwappedInteger(mData, 8);
int serial1 = EndianUtils.readSwappedInteger(mData, 12);
int serial2 = EndianUtils.readSwappedInteger(mData, 16);
int serial3 = EndianUtils.readSwappedInteger(mData, 20);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%08X", serial0));
sb.append("-");
sb.append(String.format("%08X", serial1));
sb.append("-");
sb.append(String.format("%08X", serial2));
sb.append("-");
sb.append(String.format("%08X", serial3));
return sb.toString();
}
}
} | gpl-3.0 |
cams7/casa_das_quentinhas | app-base/src/main/java/br/com/cams7/app/utils/AppHelper.java | 5667 | /**
*
*/
package br.com.cams7.app.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import br.com.cams7.app.AppInvalidDataException;
import br.com.cams7.app.AppNotFoundException;
import br.com.cams7.app.entity.AbstractEntity;
/**
* @author César Magalhães
*
*/
public final class AppHelper {
/**
* Cria uma nova entidade
*
* @param entityType
* Tipo de classe Entity
* @return Entity
*/
public static <E extends AbstractEntity<?>> E getNewEntity(Class<E> entityType) {
try {
E entity = entityType.newInstance();
return entity;
} catch (InstantiationException | IllegalAccessException e) {
throw new AppInvalidDataException(e.getMessage());
}
}
/**
* Retorna o tipo de classe
*
* @param entityType
* Tipo de classe Entity
* @param attributeName
* Nome do atributo da entidade
* @return Tipo de classe
*/
@SuppressWarnings("unchecked")
public static <E extends AbstractEntity<?>> FieldTypes<E> getFieldTypes(Class<E> entityType, String attributeName) {
int index = attributeName.indexOf(".");
String entityName = null;
if (index > -1) {
entityName = attributeName.substring(0, index);
attributeName = attributeName.substring(index + 1);
}
try {
if (entityName != null) {
Field field = entityType.getDeclaredField(entityName);
entityType = (Class<E>) field.getType();
return getFieldTypes(entityType, attributeName);
}
Field field = entityType.getDeclaredField(attributeName);
return new FieldTypes<E>(entityType, field.getType());
} catch (NoSuchFieldException | SecurityException e) {
throw new AppNotFoundException(String.format("O atributo '%s' não foi encontrado na entidade '%s'",
attributeName, entityType.getName()));
}
}
/**
* Converte o valor para o tipo correto
*
* @param entityType
* Tipo da entidade
* @param fieldName
* Nome do atributo
* @param fieldValue
* Vator do atributo
* @return
*/
public static <E extends AbstractEntity<?>> Object getFieldValue(Class<E> entityType, String fieldName,
Object fieldValue) {
Class<?> attributeType = getFieldTypes(entityType, fieldName).getAttributeType();
fieldValue = getCorrectValue(fieldValue);
if (fieldValue == null)
return null;
if (attributeType.equals(String.class) || isEnum(attributeType))
return fieldValue;
try {
Constructor<?> constructor = attributeType.getDeclaredConstructor(String.class);
Object value = constructor.newInstance(String.valueOf(fieldValue));
return value;
} catch (SecurityException | IllegalArgumentException | NoSuchMethodException | InstantiationException
| IllegalAccessException | InvocationTargetException e) {
// throw new AppException(e.getMessage(), e.getCause());
}
return null;
}
/**
* Corrige o valor
*
* @param value
* @return
*/
private static Object getCorrectValue(Object value) {
if (value == null)
return null;
if (value instanceof String) {
String stringValue = (String) value;
if (stringValue.isEmpty())
return null;
return stringValue.trim();
}
return value;
}
/**
* Verifica se o tipo infomado é "Boolean"
*
* @param type
* Tipo de classe
* @return
*/
public static boolean isBoolean(Class<?> type) {
return type.equals(Boolean.class) || type.equals(Boolean.TYPE);
}
/**
* Verifica se o tipo infomado é "Number"
*
* @param type
* Tipo de classe
* @return
*/
public static boolean isNumber(Class<?> type) {
if (isInteger(type))
return true;
if (isFloat(type))
return true;
return false;
}
private static boolean isInteger(Class<?> type) {
if (type.equals(Byte.class) || type.equals(Byte.TYPE))
return true;
if (type.equals(Short.class) || type.equals(Short.TYPE))
return true;
if (type.equals(Integer.class) || type.equals(Integer.TYPE))
return true;
if (type.equals(Long.class) || type.equals(Long.TYPE))
return true;
return false;
}
/**
* Verifica se o tipo infomado é "Float"
*
* @param type
* Tipo de classe
* @return
*/
private static boolean isFloat(Class<?> type) {
if (type.equals(Float.class) || type.equals(Float.TYPE))
return true;
if (type.equals(Double.class) || type.equals(Double.TYPE))
return true;
return false;
}
/**
* Verifica se o tipo infomado é "Date"
*
* @param type
* Tipo de classe
* @return
*/
public static boolean isDate(Class<?> type) {
return type.equals(Date.class);
}
/**
* Verifica se o tipo infomado é "enum"
*
* @param type
* Tipo de classe
* @return
*/
public static boolean isEnum(Class<?> type) {
return type.isEnum();
}
/**
* @param values
* @return
*/
public static String getString(String[] values) {
String stringValue = "";
if (values == null)
return stringValue;
stringValue += "[";
for (int i = 0; i < values.length; i++) {
stringValue += values[i];
if (i < values.length - 1)
stringValue += ", ";
}
stringValue += "]";
return stringValue;
}
public static class FieldTypes<E extends AbstractEntity<?>> {
private Class<E> entityType;
private Class<?> attributeType;
private FieldTypes(Class<E> entityType, Class<?> attributeType) {
super();
this.entityType = entityType;
this.attributeType = attributeType;
}
public Class<E> getEntityType() {
return entityType;
}
public Class<?> getAttributeType() {
return attributeType;
}
}
}
| gpl-3.0 |
cFerg/MineJava | src/main/java/minejava/reg/security/CodeSigner.java | 2320 | package minejava.reg.security;
import minejava.reg.io.*;
import minejava.reg.security.cert.CertPath;
public final class CodeSigner implements Serializable{
private static final long serialVersionUID = 6819288105193937581L;
private CertPath signerCertPath;
private Timestamp timestamp;
private transient int myhash = -1;
public CodeSigner(CertPath signerCertPath, Timestamp timestamp){
if (signerCertPath == null){
throw new NullPointerException();
}
this.signerCertPath = signerCertPath;
this.timestamp = timestamp;
}
public CertPath getSignerCertPath(){
return signerCertPath;
}
public Timestamp getTimestamp(){
return timestamp;
}
@Override
public int hashCode(){
if (myhash == -1){
if (timestamp == null){
myhash = signerCertPath.hashCode();
}else{
myhash = signerCertPath.hashCode() + timestamp.hashCode();
}
}
return myhash;
}
@Override
public boolean equals(Object obj){
if (obj == null || (!(obj instanceof CodeSigner))){
return false;
}
CodeSigner that = (CodeSigner) obj;
if (this == that){
return true;
}
Timestamp thatTimestamp = that.getTimestamp();
if (timestamp == null){
if (thatTimestamp != null){
return false;
}
}else{
if (thatTimestamp == null || (!timestamp.equals(thatTimestamp))){
return false;
}
}
return signerCertPath.equals(that.getSignerCertPath());
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("(");
sb.append("Signer: ").append(signerCertPath.getCertificates().get(0));
if (timestamp != null){
sb.append("timestamp: " + timestamp);
}
sb.append(")");
return sb.toString();
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException{
ois.defaultReadObject();
myhash = -1;
}
} | mpl-2.0 |
encapturemd/MirthConnect | server/src/com/mirth/connect/connectors/http/HttpDispatcherProperties.java | 7214 | /*
* Copyright (c) Mirth Corporation. All rights reserved.
*
* http://www.mirthcorp.com
*
* The software in this package is published under the terms of the MPL license a copy of which has
* been included with this distribution in the LICENSE.txt file.
*/
package com.mirth.connect.connectors.http;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.mirth.connect.donkey.model.channel.ConnectorProperties;
import com.mirth.connect.donkey.model.channel.DispatcherConnectorPropertiesInterface;
import com.mirth.connect.donkey.model.channel.QueueConnectorProperties;
public class HttpDispatcherProperties extends ConnectorProperties implements DispatcherConnectorPropertiesInterface {
private QueueConnectorProperties queueConnectorProperties;
private String host;
private String method;
private Map<String, String> headers;
private Map<String, String> parameters;
private boolean includeHeadersInResponse;
private boolean multipart;
private boolean useAuthentication;
private String authenticationType;
private String username;
private String password;
private String content;
private String contentType;
private String charset;
private String socketTimeout;
public HttpDispatcherProperties() {
queueConnectorProperties = new QueueConnectorProperties();
this.host = "";
this.method = "post";
this.headers = new LinkedHashMap<String, String>();
this.parameters = new LinkedHashMap<String, String>();
this.includeHeadersInResponse = false;
this.multipart = false;
this.useAuthentication = false;
this.authenticationType = "Basic";
this.username = "";
this.password = "";
this.content = "";
this.contentType = "text/plain";
this.charset = "UTF-8";
this.socketTimeout = "30000";
}
public HttpDispatcherProperties(HttpDispatcherProperties props) {
queueConnectorProperties = new QueueConnectorProperties(props.getQueueConnectorProperties());
host = props.getHost();
method = props.getMethod();
headers = new LinkedHashMap<String, String>(props.getHeaders());
parameters = new LinkedHashMap<String, String>(props.getParameters());
includeHeadersInResponse = props.isIncludeHeadersInResponse();
multipart = props.isMultipart();
useAuthentication = props.isUseAuthentication();
authenticationType = props.getAuthenticationType();
username = props.getUsername();
password = props.getPassword();
content = props.getContent();
contentType = props.getContentType();
charset = props.getCharset();
socketTimeout = props.getSocketTimeout();
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public boolean isIncludeHeadersInResponse() {
return includeHeadersInResponse;
}
public void setIncludeHeadersInResponse(boolean includeHeadersInResponse) {
this.includeHeadersInResponse = includeHeadersInResponse;
}
public boolean isMultipart() {
return multipart;
}
public void setMultipart(boolean multipart) {
this.multipart = multipart;
}
public boolean isUseAuthentication() {
return useAuthentication;
}
public void setUseAuthentication(boolean useAuthentication) {
this.useAuthentication = useAuthentication;
}
public String getAuthenticationType() {
return authenticationType;
}
public void setAuthenticationType(String authenticationType) {
this.authenticationType = authenticationType;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public String getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(String socketTimeout) {
this.socketTimeout = socketTimeout;
}
@Override
public String getProtocol() {
return "HTTP";
}
@Override
public String getName() {
return "HTTP Sender";
}
@Override
public String toFormattedString() {
StringBuilder builder = new StringBuilder();
String newLine = "\n";
builder.append("URL: ");
builder.append(host);
builder.append(newLine);
builder.append("METHOD: ");
builder.append(method.toUpperCase());
builder.append(newLine);
if (StringUtils.isNotBlank(username)) {
builder.append("USERNAME: ");
builder.append(username);
builder.append(newLine);
}
builder.append(newLine);
builder.append("[HEADERS]");
for (Map.Entry<String, String> header : headers.entrySet()) {
builder.append(newLine);
builder.append(header.getKey() + ": " + header.getValue());
}
builder.append(newLine);
builder.append(newLine);
builder.append("[PARAMETERS]");
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
builder.append(newLine);
builder.append(parameter.getKey() + ": " + parameter.getValue());
}
builder.append(newLine);
builder.append(newLine);
builder.append("[CONTENT]");
builder.append(newLine);
builder.append(content);
return builder.toString();
}
@Override
public QueueConnectorProperties getQueueConnectorProperties() {
return queueConnectorProperties;
}
@Override
public ConnectorProperties clone() {
return new HttpDispatcherProperties(this);
}
} | mpl-2.0 |
k-joseph/openmrs-module-openhmis.inventory | api/src/main/java/org/openmrs/module/openhmis/inventory/api/search/StockOperationSearch.java | 4975 | /*
* The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.openhmis.inventory.api.search;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.openmrs.module.openhmis.commons.api.entity.search.BaseObjectTemplateSearch;
public class StockOperationSearch extends BaseObjectTemplateSearch<StockOperationTemplate> {
public StockOperationSearch() {
this(new StockOperationTemplate());
}
public StockOperationSearch(StockOperationTemplate template) {
super(template);
}
private StringComparisonType operationNumberComparisonType;
private ComparisonType sourceComparisonType;
private ComparisonType destinationComparisonType;
private ComparisonType patientComparisonType;
private ComparisonType institutionComparisonType;
private DateComparisonType dateCreatedComparisonType;
public void setOperationNumberComparisonType(StringComparisonType operationNumberComparisonType) {
this.operationNumberComparisonType = operationNumberComparisonType;
}
public StringComparisonType getOperationNumberComparisonType() {
return operationNumberComparisonType;
}
public ComparisonType getSourceComparisonType() {
return sourceComparisonType;
}
public void setSourceComparisonType(ComparisonType sourceComparisonType) {
this.sourceComparisonType = sourceComparisonType;
}
public ComparisonType getDestinationComparisonType() {
return destinationComparisonType;
}
public void setDestinationComparisonType(ComparisonType destinationComparisonType) {
this.destinationComparisonType = destinationComparisonType;
}
public DateComparisonType getDateCreatedComparisonType() {
return dateCreatedComparisonType;
}
public void setDateCreatedComparisonType(DateComparisonType dateCreatedComparisonType) {
this.dateCreatedComparisonType = dateCreatedComparisonType;
}
public ComparisonType getPatientComparisonType() {
return patientComparisonType;
}
public void setPatientComparisonType(ComparisonType patientComparisonType) {
this.patientComparisonType = patientComparisonType;
}
public ComparisonType getInstitutionComparisonType() {
return institutionComparisonType;
}
public void setInstitutionComparisonType(ComparisonType institutionComparisonType) {
this.institutionComparisonType = institutionComparisonType;
}
@Override
public void updateCriteria(Criteria criteria) {
super.updateCriteria(criteria);
StockOperationTemplate operation = getTemplate();
if(operation.getItem() != null) {
criteria.createAlias("items", "items").add(Restrictions.eq("items.item", operation.getItem()));
}
if (operation.getOperationNumber() != null) {
criteria.add(createCriterion("operationNumber", operation.getOperationNumber(), operationNumberComparisonType));
}
if (operation.getInstanceType() != null) {
criteria.add(Restrictions.eq("instanceType", operation.getInstanceType()));
}
if (operation.getStatus() != null) {
criteria.add(Restrictions.eq("status", operation.getStatus()));
}
if (operation.getSource() != null ||
(sourceComparisonType != null && sourceComparisonType != ComparisonType.EQUAL)) {
criteria.add(createCriterion("source", operation.getSource(), sourceComparisonType));
}
if (operation.getDestination() != null ||
(destinationComparisonType != null && destinationComparisonType != ComparisonType.EQUAL)) {
criteria.add(createCriterion("destination", operation.getDestination(), destinationComparisonType));
}
if (operation.getPatient() != null ||
(patientComparisonType != null && patientComparisonType != ComparisonType.EQUAL)) {
criteria.add(createCriterion("patient", operation.getPatient(), patientComparisonType));
}
if (operation.getInstitution() != null ||
(institutionComparisonType != null && institutionComparisonType != ComparisonType.EQUAL)) {
criteria.add(createCriterion("institution", operation.getInstitution(), institutionComparisonType));
}
if (operation.getDateCreated() != null ||
(dateCreatedComparisonType != null && dateCreatedComparisonType != DateComparisonType.EQUAL)) {
criteria.add(createCriterion("dateCreated", operation.getDateCreated(), dateCreatedComparisonType));
}
if (operation.getStockroom() != null) {
criteria.add(Restrictions.or(
Restrictions.eq("source", operation.getStockroom()),
Restrictions.eq("destination", operation.getStockroom())
));
}
}
}
| mpl-2.0 |
Bhamni/openmrs-core | api/src/main/java/org/openmrs/notification/AlertService.java | 5795 | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.notification;
import java.util.Collection;
import java.util.List;
import org.openmrs.User;
import org.openmrs.annotation.Authorized;
import org.openmrs.api.APIException;
import org.openmrs.api.OpenmrsService;
import org.openmrs.notification.db.AlertDAO;
import org.openmrs.util.PrivilegeConstants;
/**
* Contains methods pertaining to creating/deleting/voiding Alerts in the system Use:<br/>
*
* <pre>
* Alert alert = new Alert();
* alert.set___(___);
* ...etc
* Context.getAlertService().saveAlert(alert);
* </pre>
*/
public interface AlertService extends OpenmrsService {
/**
* Used by Spring to set the specific/chosen database access implementation
*
* @param dao The dao implementation to use
*/
public void setAlertDAO(AlertDAO dao);
/**
* Save the given <code>alert</code> in the database
*
* @param alert the Alert object to save
* @return The saved alert object
* @throws APIException
* @should save simple alert with one user
* @should save alerts by role
* @should assign uuid to alert
*/
@Authorized(PrivilegeConstants.MANAGE_ALERTS)
public Alert saveAlert(Alert alert) throws APIException;
/**
* @deprecated use {@link #saveAlert(Alert)}
*/
@Deprecated
public void createAlert(Alert alert) throws APIException;
/**
* Use AlertService.saveAlert(new Alert(text, user))
*
* @deprecated use {@link #saveAlert(Alert)}
*/
@Deprecated
public void createAlert(String text, User user) throws APIException;
/**
* Use AlertService.saveAlert(new Alert(text, users))
*
* @deprecated use {@link #saveAlert(Alert)}
*/
@Deprecated
public void createAlert(String text, Collection<User> users) throws APIException;
/**
* Get alert by internal identifier
*
* @param alertId internal alert identifier
* @return alert with given internal identifier
* @throws APIException
*/
public Alert getAlert(Integer alertId) throws APIException;
/**
* @deprecated use {@link #saveAlert(Alert)}
*/
@Deprecated
public void updateAlert(Alert alert) throws APIException;
/**
* Completely delete the given alert from the database
*
* @param alert the Alert to purge/delete
* @throws APIException
*/
@Authorized(PrivilegeConstants.MANAGE_ALERTS)
public void purgeAlert(Alert alert) throws APIException;
/**
* Use AlertService.saveAlert(alert.markAlertRead())
*
* @deprecated use {@link #saveAlert(Alert)}
*/
@Deprecated
public void markAlertRead(Alert alert) throws APIException;
/**
* @deprecated use #getAlerts(User, boolean, boolean)
*/
@Deprecated
public List<Alert> getAllAlerts(User user) throws APIException;
/**
* Find all alerts for a user that have not expired
*
* @param user
* @return alerts that are unread _or_ read that have not expired
* @see #getAlerts(User, boolean, boolean)
* @throws APIException
*/
public List<Alert> getAllActiveAlerts(User user) throws APIException;
/**
* @deprecated use {@link #getAlertsByUser(User)}
*/
@Deprecated
public List<Alert> getAlerts(User user) throws APIException;
/**
* Find the alerts that are not read and have not expired for a user This will probably be the
* most commonly called method If null is passed in for <code>user</code>, find alerts for the
* currently authenticated user. If no user is authenticated, search on "new
* User()" (for "Anonymous" role alert possibilities)
*
* @param user the user that is assigned to the returned alerts
* @return alerts that are unread and not expired
* @throws APIException
*/
public List<Alert> getAlertsByUser(User user) throws APIException;
/**
* @deprecated use {@link #getAlertsByUser(User)} and pass "null" as the parameter for
* <code>user</code>
*/
@Deprecated
public List<Alert> getAlerts() throws APIException;
/**
* Finds alerts for the given user with the given status
*
* @param user to restrict to
* @param includeRead
* @param includeExpired
* @return alerts for this user with these options
* @throws APIException
*/
public List<Alert> getAlerts(User user, boolean includeRead, boolean includeExpired) throws APIException;
/**
* Get all unexpired alerts for all users
*
* @return list of unexpired alerts
* @throws APIException
*/
public List<Alert> getAllAlerts() throws APIException;
/**
* Get alerts for all users while obeying includeExpired
*
* @param includeExpired
* @return list of alerts
* @throws APIException
*/
public List<Alert> getAllAlerts(boolean includeExpired) throws APIException;
/**
* Sends an alert to all superusers
*
* @param messageCode The alert message code from messages.properties
* @param cause The exception that was thrown, method will work if cause is null
* @param messageArguments The arguments for the coded message
* @should add an alert to the database
*/
@Authorized(PrivilegeConstants.MANAGE_ALERTS)
public void notifySuperUsers(String messageCode, Exception cause, Object... messageArguments);
}
| mpl-2.0 |
llggkk1117/TextFile | src/org/gene/modules/textFile/charset/Charset.java | 3846 | package org.gene.modules.textFile.charset;
import java.util.HashMap;
public enum Charset
{
ISO_8859_1(
"ISO-8859-1",
new ByteRange[]{},
new String[]{}
),
// utf 8 code table
// http://www.utf8-chartable.de/
UTF_8(
"UTF-8",
new ByteRange[]{
new ByteRange("00", "7F"),
new ByteRange("E0A080", "EFBFBF"),
new ByteRange("C280", "DFBF"),
new ByteRange("F0908080", "F48083BF")
},
new String[]{
"\uFEFF" //UTF-8 BOM
}
),
// euc-kr code table
// http://www.fileformat.info/info/charset/EUC-KR/list.htm
// http://www.mkexdev.net/Community/Content.aspx?parentCategoryID=4&categoryID=14&ID=125
EUC_KR(
"EUC-KR",
new ByteRange[]{
new ByteRange("00", "7F"),
new ByteRange("A1A1", "FDFE")
},
new String[]{}
);
private static HashMap<String, Charset> instanceRegistry;
private String displayName;
private ByteRange[] byteRanges;
private String[] lettersToBeIgnored;
private Charset(String displayName, ByteRange[] byteRanges, String[] lettersToBeIgnored)
{
this.init(displayName, byteRanges, lettersToBeIgnored);
}
private void init(String displayName, ByteRange[] byteRanges, String[] lettersToBeIgnored)
{
if(instanceRegistry==null)
{
instanceRegistry = new HashMap<String, Charset>();
}
instanceRegistry.put(displayName, this);
this.displayName = displayName;
this.byteRanges = byteRanges;
this.lettersToBeIgnored = lettersToBeIgnored;
}
public String getDisplayName()
{
return this.displayName;
}
public ByteRange[] getByteRanges()
{
return this.byteRanges;
}
public String[] getLettersToBeIgnored()
{
return this.lettersToBeIgnored;
}
public static synchronized Charset getCharset(String charsetCode)
{
return instanceRegistry.get(charsetCode);
}
public int[] getNumOfBytesSupported()
{
int[] numOfBytesSupported = new int[this.byteRanges.length];
for(int i=0; i<this.byteRanges.length; ++i)
{
numOfBytesSupported[i] = this.byteRanges[i].getNumOfBytes();
}
return numOfBytesSupported;
}
public boolean inRange(String hexString)
{
byte[] byteArray = Hex2Byte.h2b(hexString);
return this.inRange(byteArray);
}
public boolean inRange(byte[] byteArray)
{
int numOfByte = byteArray.length;
boolean inRange = false;
for(int i=0; i<this.byteRanges.length; ++i)
{
if(this.byteRanges[i].getNumOfBytes() == numOfByte)
{
if((compareBytes(this.byteRanges[i].getStartingByte(), byteArray)<=0)&&(compareBytes(this.byteRanges[i].getEndingByte(), byteArray)>=0))
{
inRange = true;
break;
}
}
}
return inRange;
}
private static final int[] bitMask = new int[]{0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
private static synchronized Integer compareBytes(byte[] bytes1, byte[] bytes2)
{
Integer result = null;
if(bytes1!=null && bytes2!=null)
{
int range = bytes1.length >= bytes2.length ? bytes1.length-1 : bytes2.length-1;
for(int i=range; i>=0; --i)
{
for(int j=7; j>=0; --j)
{
int num1 = 0;
int num2 = 0;
if(i<=bytes1.length-1)
{
num1 = (int)(bytes1[i] & bitMask[j]);
}
if(i<=bytes2.length-1)
{
num2 = (int)(bytes2[i] & bitMask[j]);
}
if(num1>num2)
{
result = 1;
break;
}
else if(num1<num2)
{
result = -1;
break;
}
else
{
result = 0;
}
}
if(result!=null)
{
break;
}
}
}
return result;
}
public static void main(String[] args)
{
System.out.println(Charset.UTF_8.inRange("EFBF80"));
System.out.println(compareBytes(new byte[]{(byte)0x81}, new byte[]{(byte)0x81, (byte)0x81}));
}
}
| mpl-2.0 |
Devexperts/QD | dxfeed-impl/src/main/java/com/dxfeed/event/market/impl/QuoteMapping.java | 9385 | /*
* !++
* QDS - Quick Data Signalling Library
* !-
* Copyright (C) 2002 - 2021 Devexperts LLC
* !-
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
* !__
*/
package com.dxfeed.event.market.impl;
import com.devexperts.qd.DataRecord;
import com.devexperts.qd.ng.RecordCursor;
import com.devexperts.qd.util.MappingUtil;
import com.devexperts.util.TimeUtil;
public class QuoteMapping extends MarketEventMapping {
// BEGIN: CODE AUTOMATICALLY GENERATED: DO NOT MODIFY. IT IS REGENERATED BY com.dxfeed.api.codegen.ImplCodeGen
private final int iSequence;
private final int iTimeNanoPart;
private final int iBidTime;
private final int iBidExchangeCode;
private final int iBidPrice;
private final int iBidSize;
private final int iAskTime;
private final int iAskExchangeCode;
private final int iAskPrice;
private final int iAskSize;
public QuoteMapping(DataRecord record) {
super(record);
iSequence = MappingUtil.findIntField(record, "Sequence", false);
iTimeNanoPart = MappingUtil.findIntField(record, "TimeNanoPart", false);
iBidTime = MappingUtil.findIntField(record, "Bid.Time", false);
iBidExchangeCode = MappingUtil.findIntField(record, "Bid.Exchange", false);
iBidPrice = findIntField("Bid.Price", true);
iBidSize = findIntField("Bid.Size", true);
iAskTime = MappingUtil.findIntField(record, "Ask.Time", false);
iAskExchangeCode = MappingUtil.findIntField(record, "Ask.Exchange", false);
iAskPrice = findIntField("Ask.Price", true);
iAskSize = findIntField("Ask.Size", true);
putNonDefaultPropertyName("Bid.Exchange", "BidExchangeCode");
putNonDefaultPropertyName("Ask.Exchange", "AskExchangeCode");
}
public int getSequence(RecordCursor cursor) {
if (iSequence < 0)
return 0;
return getInt(cursor, iSequence);
}
public void setSequence(RecordCursor cursor, int sequence) {
if (iSequence < 0)
return;
setInt(cursor, iSequence, sequence);
}
public int getTimeNanoPart(RecordCursor cursor) {
if (iTimeNanoPart < 0)
return 0;
return getInt(cursor, iTimeNanoPart);
}
public void setTimeNanoPart(RecordCursor cursor, int timeNanoPart) {
if (iTimeNanoPart < 0)
return;
setInt(cursor, iTimeNanoPart, timeNanoPart);
}
public long getBidTimeMillis(RecordCursor cursor) {
if (iBidTime < 0)
return 0;
return getInt(cursor, iBidTime) * 1000L;
}
public void setBidTimeMillis(RecordCursor cursor, long bidTime) {
if (iBidTime < 0)
return;
setInt(cursor, iBidTime, TimeUtil.getSecondsFromTime(bidTime));
}
public int getBidTimeSeconds(RecordCursor cursor) {
if (iBidTime < 0)
return 0;
return getInt(cursor, iBidTime);
}
public void setBidTimeSeconds(RecordCursor cursor, int bidTime) {
if (iBidTime < 0)
return;
setInt(cursor, iBidTime, bidTime);
}
@Deprecated
public char getBidExchange(RecordCursor cursor) {
if (iBidExchangeCode < 0)
return recordExchange;
return (char) getInt(cursor, iBidExchangeCode);
}
@Deprecated
public void setBidExchange(RecordCursor cursor, char bidExchange) {
if (iBidExchangeCode < 0)
return;
setInt(cursor, iBidExchangeCode, bidExchange);
}
public char getBidExchangeCode(RecordCursor cursor) {
if (iBidExchangeCode < 0)
return recordExchange;
return (char) getInt(cursor, iBidExchangeCode);
}
public void setBidExchangeCode(RecordCursor cursor, char bidExchangeCode) {
if (iBidExchangeCode < 0)
return;
setInt(cursor, iBidExchangeCode, bidExchangeCode);
}
public double getBidPrice(RecordCursor cursor) {
return getAsDouble(cursor, iBidPrice);
}
public void setBidPrice(RecordCursor cursor, double bidPrice) {
setAsDouble(cursor, iBidPrice, bidPrice);
}
public int getBidPriceDecimal(RecordCursor cursor) {
return getAsTinyDecimal(cursor, iBidPrice);
}
public void setBidPriceDecimal(RecordCursor cursor, int bidPrice) {
setAsTinyDecimal(cursor, iBidPrice, bidPrice);
}
public long getBidPriceWideDecimal(RecordCursor cursor) {
return getAsWideDecimal(cursor, iBidPrice);
}
public void setBidPriceWideDecimal(RecordCursor cursor, long bidPrice) {
setAsWideDecimal(cursor, iBidPrice, bidPrice);
}
public int getBidSize(RecordCursor cursor) {
return getAsInt(cursor, iBidSize);
}
public void setBidSize(RecordCursor cursor, int bidSize) {
setAsInt(cursor, iBidSize, bidSize);
}
public long getBidSizeLong(RecordCursor cursor) {
return getAsLong(cursor, iBidSize);
}
public void setBidSizeLong(RecordCursor cursor, long bidSize) {
setAsLong(cursor, iBidSize, bidSize);
}
public double getBidSizeDouble(RecordCursor cursor) {
return getAsDouble(cursor, iBidSize);
}
public void setBidSizeDouble(RecordCursor cursor, double bidSize) {
setAsDouble(cursor, iBidSize, bidSize);
}
public int getBidSizeDecimal(RecordCursor cursor) {
return getAsTinyDecimal(cursor, iBidSize);
}
public void setBidSizeDecimal(RecordCursor cursor, int bidSize) {
setAsTinyDecimal(cursor, iBidSize, bidSize);
}
public long getBidSizeWideDecimal(RecordCursor cursor) {
return getAsWideDecimal(cursor, iBidSize);
}
public void setBidSizeWideDecimal(RecordCursor cursor, long bidSize) {
setAsWideDecimal(cursor, iBidSize, bidSize);
}
public long getAskTimeMillis(RecordCursor cursor) {
if (iAskTime < 0)
return 0;
return getInt(cursor, iAskTime) * 1000L;
}
public void setAskTimeMillis(RecordCursor cursor, long askTime) {
if (iAskTime < 0)
return;
setInt(cursor, iAskTime, TimeUtil.getSecondsFromTime(askTime));
}
public int getAskTimeSeconds(RecordCursor cursor) {
if (iAskTime < 0)
return 0;
return getInt(cursor, iAskTime);
}
public void setAskTimeSeconds(RecordCursor cursor, int askTime) {
if (iAskTime < 0)
return;
setInt(cursor, iAskTime, askTime);
}
@Deprecated
public char getAskExchange(RecordCursor cursor) {
if (iAskExchangeCode < 0)
return recordExchange;
return (char) getInt(cursor, iAskExchangeCode);
}
@Deprecated
public void setAskExchange(RecordCursor cursor, char askExchange) {
if (iAskExchangeCode < 0)
return;
setInt(cursor, iAskExchangeCode, askExchange);
}
public char getAskExchangeCode(RecordCursor cursor) {
if (iAskExchangeCode < 0)
return recordExchange;
return (char) getInt(cursor, iAskExchangeCode);
}
public void setAskExchangeCode(RecordCursor cursor, char askExchangeCode) {
if (iAskExchangeCode < 0)
return;
setInt(cursor, iAskExchangeCode, askExchangeCode);
}
public double getAskPrice(RecordCursor cursor) {
return getAsDouble(cursor, iAskPrice);
}
public void setAskPrice(RecordCursor cursor, double askPrice) {
setAsDouble(cursor, iAskPrice, askPrice);
}
public int getAskPriceDecimal(RecordCursor cursor) {
return getAsTinyDecimal(cursor, iAskPrice);
}
public void setAskPriceDecimal(RecordCursor cursor, int askPrice) {
setAsTinyDecimal(cursor, iAskPrice, askPrice);
}
public long getAskPriceWideDecimal(RecordCursor cursor) {
return getAsWideDecimal(cursor, iAskPrice);
}
public void setAskPriceWideDecimal(RecordCursor cursor, long askPrice) {
setAsWideDecimal(cursor, iAskPrice, askPrice);
}
public int getAskSize(RecordCursor cursor) {
return getAsInt(cursor, iAskSize);
}
public void setAskSize(RecordCursor cursor, int askSize) {
setAsInt(cursor, iAskSize, askSize);
}
public long getAskSizeLong(RecordCursor cursor) {
return getAsLong(cursor, iAskSize);
}
public void setAskSizeLong(RecordCursor cursor, long askSize) {
setAsLong(cursor, iAskSize, askSize);
}
public double getAskSizeDouble(RecordCursor cursor) {
return getAsDouble(cursor, iAskSize);
}
public void setAskSizeDouble(RecordCursor cursor, double askSize) {
setAsDouble(cursor, iAskSize, askSize);
}
public int getAskSizeDecimal(RecordCursor cursor) {
return getAsTinyDecimal(cursor, iAskSize);
}
public void setAskSizeDecimal(RecordCursor cursor, int askSize) {
setAsTinyDecimal(cursor, iAskSize, askSize);
}
public long getAskSizeWideDecimal(RecordCursor cursor) {
return getAsWideDecimal(cursor, iAskSize);
}
public void setAskSizeWideDecimal(RecordCursor cursor, long askSize) {
setAsWideDecimal(cursor, iAskSize, askSize);
}
// END: CODE AUTOMATICALLY GENERATED
}
| mpl-2.0 |
GreenDelta/olca-converter | src/main/java/org/openlca/olcatdb/ecospold2/ES2LogNormalDistribution.java | 1797 | package org.openlca.olcatdb.ecospold2;
import org.openlca.olcatdb.parsing.Context;
import org.openlca.olcatdb.parsing.ContextField;
import org.openlca.olcatdb.parsing.ContextObject;
import org.openlca.olcatdb.parsing.ContextField.Type;
/**
* The Lognormal-distribution with average value (MeanValue parameter) and
* variance s (Variance parameter) is a Normal-distribution, shaping the natural
* logarithm of the characteristic values ln(x) instead of x-values.
*
* @Element lognormal
*/
@Context(name = "lognormal", parentName = "uncertainty")
public class ES2LogNormalDistribution extends ContextObject {
/**
* @Attribute meanValue
* @DataType TFloatNumber
*/
@ContextField(name = "lognormal", parentName = "uncertainty", isAttribute = true, attributeName = "meanValue", type = Type.Double)
public Double meanValue;
/**
* @Attribute standardDeviation95
* @DataType TFloatNumber
*/
@ContextField(name = "lognormal", parentName = "uncertainty", isAttribute = true, attributeName = "standardDeviation95", type = Type.Double)
public Double standardDeviation95;
/**
* @Attribute mu
* @DataType TFloatNumber
*/
@ContextField(name = "lognormal", parentName = "uncertainty", isAttribute = true, attributeName = "mu", type = Type.Double)
public Double mu;
/**
* @Attribute variance
* @DataType TFloatNumber
*/
@ContextField(name = "lognormal", parentName = "uncertainty", isAttribute = true, attributeName = "variance", type = Type.Double)
public Double variance;
/**
* @Attribute varianceWithPedigreeUncertainty
* @DataType TFloatNumber
*/
@ContextField(name = "lognormal", parentName = "uncertainty", isAttribute = true, attributeName = "varianceWithPedigreeUncertainty", type = Type.Double)
public Double varianceWithPedigreeUncertainty;
}
| mpl-2.0 |
a1837634447/Shw | src/test/java/top/itning/ta/LogTest.java | 554 | package top.itning.ta;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.util.StatusPrinter;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogTest {
private static final Logger logger = LoggerFactory.getLogger(LogTest.class);
@Test
public void logTest() {
// LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
// StatusPrinter.print(lc);
logger.debug("debug");
logger.info("info");
logger.error("error");
}
}
| mpl-2.0 |
mcomella/FirefoxAccounts-android | download/src/main/java/org/mozilla/fxa_data/login/WebViewUtils.java | 888 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.fxa_data.login;
import android.os.Build;
import android.support.annotation.UiThread;
import android.webkit.WebView;
class WebViewUtils {
private WebViewUtils() {}
/**
* Evaluates JavaScript code in an API-level independent way.
*
* Note: all WebView methods must be called from the UIThread.
*/
@UiThread
static void evalJS(final WebView webView, final String script) {
// implementation via http://stackoverflow.com/a/30828985/
if (Build.VERSION.SDK_INT >= 19) {
webView.evaluateJavascript(script, null);
} else {
webView.loadUrl("javascript:" + script);
}
}
}
| mpl-2.0 |
seedstack/seedstack-maven-plugin | src/main/java/org/seedstack/maven/components/prompter/Prompter.java | 868 | /*
* Copyright © 2013-2021, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.maven.components.prompter;
import java.util.List;
import java.util.Set;
public interface Prompter {
String promptChoice(String message, List<Value> values) throws PromptException;
String promptList(String message, List<Value> values, String defaultValue) throws PromptException;
Set<String> promptCheckbox(String message, List<Value> values) throws PromptException;
String promptInput(String message, String defaultValue) throws PromptException;
boolean promptConfirmation(String message, String defaultValue) throws PromptException;
}
| mpl-2.0 |
digidotcom/XBeeJavaLibrary | library/src/main/java/com/digi/xbee/api/packet/XBeePacketParser.java | 21449 | /*
* Copyright 2017-2019, Digi International Inc.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.digi.xbee.api.packet;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import com.digi.xbee.api.exceptions.InvalidPacketException;
import com.digi.xbee.api.models.SpecialByte;
import com.digi.xbee.api.models.OperatingMode;
import com.digi.xbee.api.packet.bluetooth.BluetoothUnlockPacket;
import com.digi.xbee.api.packet.bluetooth.BluetoothUnlockResponsePacket;
import com.digi.xbee.api.packet.cellular.RXSMSPacket;
import com.digi.xbee.api.packet.cellular.TXSMSPacket;
import com.digi.xbee.api.packet.common.ATCommandPacket;
import com.digi.xbee.api.packet.common.ATCommandQueuePacket;
import com.digi.xbee.api.packet.common.ATCommandResponsePacket;
import com.digi.xbee.api.packet.common.ExplicitAddressingPacket;
import com.digi.xbee.api.packet.common.ExplicitRxIndicatorPacket;
import com.digi.xbee.api.packet.common.IODataSampleRxIndicatorPacket;
import com.digi.xbee.api.packet.common.ModemStatusPacket;
import com.digi.xbee.api.packet.common.ReceivePacket;
import com.digi.xbee.api.packet.common.RemoteATCommandPacket;
import com.digi.xbee.api.packet.common.RemoteATCommandResponsePacket;
import com.digi.xbee.api.packet.common.TransmitPacket;
import com.digi.xbee.api.packet.common.TransmitStatusPacket;
import com.digi.xbee.api.packet.devicecloud.DeviceRequestPacket;
import com.digi.xbee.api.packet.devicecloud.DeviceResponsePacket;
import com.digi.xbee.api.packet.devicecloud.DeviceResponseStatusPacket;
import com.digi.xbee.api.packet.devicecloud.FrameErrorPacket;
import com.digi.xbee.api.packet.devicecloud.SendDataRequestPacket;
import com.digi.xbee.api.packet.devicecloud.SendDataResponsePacket;
import com.digi.xbee.api.packet.ip.RXIPv4Packet;
import com.digi.xbee.api.packet.ip.TXIPv4Packet;
import com.digi.xbee.api.packet.ip.TXTLSProfilePacket;
import com.digi.xbee.api.packet.raw.RX16IOPacket;
import com.digi.xbee.api.packet.raw.RX16Packet;
import com.digi.xbee.api.packet.raw.RX64IOPacket;
import com.digi.xbee.api.packet.raw.RX64Packet;
import com.digi.xbee.api.packet.raw.TX16Packet;
import com.digi.xbee.api.packet.raw.TX64Packet;
import com.digi.xbee.api.packet.raw.TXStatusPacket;
import com.digi.xbee.api.packet.relay.UserDataRelayOutputPacket;
import com.digi.xbee.api.packet.relay.UserDataRelayPacket;
import com.digi.xbee.api.packet.thread.CoAPRxResponsePacket;
import com.digi.xbee.api.packet.thread.CoAPTxRequestPacket;
import com.digi.xbee.api.packet.thread.IPv6IODataSampleRxIndicator;
import com.digi.xbee.api.packet.thread.IPv6RemoteATCommandRequestPacket;
import com.digi.xbee.api.packet.thread.IPv6RemoteATCommandResponsePacket;
import com.digi.xbee.api.packet.thread.RXIPv6Packet;
import com.digi.xbee.api.packet.thread.TXIPv6Packet;
import com.digi.xbee.api.packet.wifi.IODataSampleRxIndicatorWifiPacket;
import com.digi.xbee.api.packet.wifi.RemoteATCommandResponseWifiPacket;
import com.digi.xbee.api.packet.wifi.RemoteATCommandWifiPacket;
import com.digi.xbee.api.utils.HexUtils;
/**
* This class reads and parses XBee packets from the input stream returning
* a generic {@code XBeePacket} which can be casted later to the corresponding
* high level specific API packet.
*
* <p>All the API and API2 logic is already included so all packet reads are
* independent of the XBee operating mode.</p>
*
* <p>Two API modes are supported and both can be enabled using the {@code AP}
* (API Enable) command:
*
* <ul>
* <li><b>API1 - API Without Escapes</b>
* <p>The data frame structure is defined as follows:</p>
*
* <pre>
* {@code
* Start Delimiter Length Frame Data Checksum
* (Byte 1) (Bytes 2-3) (Bytes 4-n) (Byte n + 1)
* +----------------+ +-------------------+ +--------------------------- + +----------------+
* | 0x7E | | MSB | LSB | | API-specific Structure | | 1 Byte |
* +----------------+ +-------------------+ +----------------------------+ +----------------+
* MSB = Most Significant Byte, LSB = Least Significant Byte
* }
* </pre>
* </li>
*
* <li><b>API2 - API With Escapes</b>
* <p>The data frame structure is defined as follows:</p>
*
* <pre>
* {@code
* Start Delimiter Length Frame Data Checksum
* (Byte 1) (Bytes 2-3) (Bytes 4-n) (Byte n + 1)
* +----------------+ +-------------------+ +--------------------------- + +----------------+
* | 0x7E | | MSB | LSB | | API-specific Structure | | 1 Byte |
* +----------------+ +-------------------+ +----------------------------+ +----------------+
* \___________________________________ _________________________________/
* \/
* Characters Escaped If Needed
*
* MSB = Most Significant Byte, LSB = Least Significant Byte
* }
* </pre>
*
* <p>When sending or receiving an API2 frame, specific data values must be
* escaped (flagged) so they do not interfere with the data frame sequencing.
* To escape an interfering data byte, the byte {@code 0x7D} is inserted before
* the byte to be escaped XOR'd with {@code 0x20}.</p>
*
* <p>The data bytes that need to be escaped:</p>
* <ul>
* <li>{@code 0x7E} - Frame Delimiter ({@link SpecialByte#HEADER_BYTE})</li>
* <li>{@code 0x7D} - Escape ({@link SpecialByte#ESCAPE_BYTE})</li>
* <li>{@code 0x11} - XON ({@link SpecialByte#XON_BYTE})</li>
* <li>{@code 0x13} - XOFF ({@link SpecialByte#XOFF_BYTE})</li>
* </ul>
*
* </li>
* </ul>
*
* <p>The <b>length</b> field has a two-byte value that specifies the number of
* bytes that will be contained in the frame data field. It does not include the
* checksum field.</p>
*
* <p>The <b>frame data</b> forms an API-specific structure as follows:</p>
*
* <pre>
* {@code
* Start Delimiter Length Frame Data Checksum
* (Byte 1) (Bytes 2-3) (Bytes 4-n) (Byte n + 1)
* +----------------+ +-------------------+ +--------------------------- + +----------------+
* | 0x7E | | MSB | LSB | | API-specific Structure | | 1 Byte |
* +----------------+ +-------------------+ +----------------------------+ +----------------+
* / \
* / API Identifier Identifier specific data \
* +------------------+ +------------------------------+
* | cmdID | | cmdData |
* +------------------+ +------------------------------+
* }
* </pre>
*
* <p>The {@code cmdID} frame (API-identifier) indicates which API messages
* will be contained in the {@code cmdData} frame (Identifier-specific data).
* </p>
*
* <p>To test data integrity, a <b>checksum</b> is calculated and verified on
* non-escaped data.</p>
*
* @see APIFrameType
* @see XBeePacket
* @see com.digi.xbee.api.models.OperatingMode
*/
public class XBeePacketParser {
/**
* Parses the bytes from the given input stream depending on the provided
* operating mode and returns the API packet.
*
* <p>The operating mode must be {@link OperatingMode#API} or
* {@link OperatingMode#API_ESCAPE}.</p>
*
* @param inputStream Input stream to read bytes from.
* @param mode XBee device operating mode.
*
* @return Parsed packet from the input stream.
*
* @throws IllegalArgumentException if {@code mode != OperatingMode.API } and
* if {@code mode != OperatingMode.API_ESCAPE}.
* @throws InvalidPacketException if there is not enough data in the stream or
* if there is an error verifying the checksum or
* if the payload is invalid for the specified frame type.
* @throws NullPointerException if {@code inputStream == null} or
* if {@code mode == null}.
*
* @see XBeePacket
* @see com.digi.xbee.api.models.OperatingMode#API
* @see com.digi.xbee.api.models.OperatingMode#API_ESCAPE
*/
public XBeePacket parsePacket(InputStream inputStream, OperatingMode mode) throws InvalidPacketException {
if (inputStream == null)
throw new NullPointerException("Input stream cannot be null.");
if (mode == null)
throw new NullPointerException("Operating mode cannot be null.");
if (mode != OperatingMode.API && mode != OperatingMode.API_ESCAPE)
throw new IllegalArgumentException("Operating mode must be API or API Escaped.");
try {
// Read packet size.
int hSize = readByte(inputStream, mode);
int lSize = readByte(inputStream, mode);
int length = hSize << 8 | lSize;
// Read the payload.
byte[] payload = readBytes(inputStream, mode, length);
// Calculate the expected checksum.
XBeeChecksum checksum = new XBeeChecksum();
checksum.add(payload);
byte expectedChecksum = (byte)(checksum.generate() & 0xFF);
// Read checksum from the input stream.
byte readChecksum = (byte)(readByte(inputStream, mode) & 0xFF);
// Verify the checksum of the read bytes.
if (readChecksum != expectedChecksum)
throw new InvalidPacketException("Invalid checksum (expected 0x"
+ HexUtils.byteToHexString(expectedChecksum) + ").");
return parsePayload(payload);
} catch (IOException e) {
throw new InvalidPacketException("Error parsing packet: " + e.getMessage(), e);
}
}
/**
* Parses the bytes from the given array depending on the provided operating
* mode and returns the API packet.
*
* <p>The operating mode must be {@link OperatingMode#API} or
* {@link OperatingMode#API_ESCAPE}.</p>
*
* @param packetByteArray Byte array with the complete frame, starting from
* the header and ending in the checksum.
* @param mode XBee device operating mode.
*
* @return Parsed packet from the given byte array.
*
* @throws InvalidPacketException if there is not enough data in the array or
* if there is an error verifying the checksum or
* if the payload is invalid for the specified frame type.
* @throws IllegalArgumentException if {@code mode != OperatingMode.API } and
* if {@code mode != OperatingMode.API_ESCAPE}.
* @throws NullPointerException if {@code packetByteArray == null} or
* if {@code mode == null}.
*
* @see XBeePacket
* @see com.digi.xbee.api.models.OperatingMode#API
* @see com.digi.xbee.api.models.OperatingMode#API_ESCAPE
*/
public XBeePacket parsePacket(byte[] packetByteArray, OperatingMode mode) throws InvalidPacketException {
if (packetByteArray == null)
throw new NullPointerException("Packet byte array cannot be null.");
if (mode == null)
throw new NullPointerException("Operating mode cannot be null.");
if (mode != OperatingMode.API && mode != OperatingMode.API_ESCAPE)
throw new IllegalArgumentException("Operating mode must be API or API Escaped.");
// Check the byte array has at least 4 bytes.
if (packetByteArray.length < 4)
throw new InvalidPacketException("Error parsing packet: Incomplete packet.");
// Check the header of the frame.
if ((packetByteArray[0] & 0xFF) != SpecialByte.HEADER_BYTE.getValue())
throw new InvalidPacketException("Invalid start delimiter (expected 0x"
+ HexUtils.byteToHexString((byte)SpecialByte.HEADER_BYTE.getValue()) + ").");
return parsePacket(new ByteArrayInputStream(packetByteArray, 1, packetByteArray.length - 1), mode);
}
/**
* Parses the given API payload to get the right API packet, depending
* on its API type ({@code payload[0]}).
*
* @param payload The payload of the API frame.
*
* @return The corresponding API packet or {@code UnknownXBeePacket} if
* the frame API type is unknown.
*
* @throws InvalidPacketException if the payload is invalid for the
* specified frame type.
*
* @see APIFrameType
* @see XBeePacket
*/
private XBeePacket parsePayload(byte[] payload) throws InvalidPacketException {
// Get the API frame type.
APIFrameType apiType = APIFrameType.get(payload[0] & 0xFF);
if (apiType == null)
// Create unknown packet.
return UnknownXBeePacket.createPacket(payload);
// Parse API payload depending on API ID.
XBeePacket packet = null;
switch (apiType) {
case TX_64:
packet = TX64Packet.createPacket(payload);
break;
case TX_16:
packet = TX16Packet.createPacket(payload);
break;
case REMOTE_AT_COMMAND_REQUEST_WIFI:
packet = RemoteATCommandWifiPacket.createPacket(payload);
break;
case AT_COMMAND:
packet = ATCommandPacket.createPacket(payload);
break;
case AT_COMMAND_QUEUE:
packet = ATCommandQueuePacket.createPacket(payload);
break;
case TRANSMIT_REQUEST:
packet = TransmitPacket.createPacket(payload);
break;
case EXPLICIT_ADDRESSING_COMMAND_FRAME:
packet = ExplicitAddressingPacket.createPacket(payload);
break;
case REMOTE_AT_COMMAND_REQUEST:
packet = RemoteATCommandPacket.createPacket(payload);
break;
case IPV6_REMOTE_AT_COMMAND_REQUEST:
packet = IPv6RemoteATCommandRequestPacket.createPacket(payload);
break;
case TX_SMS:
packet = TXSMSPacket.createPacket(payload);
break;
case TX_IPV4:
packet = TXIPv4Packet.createPacket(payload);
break;
case TX_REQUEST_TLS_PROFILE:
packet = TXTLSProfilePacket.createPacket(payload);
break;
case TX_IPV6:
packet = TXIPv6Packet.createPacket(payload);
break;
case SEND_DATA_REQUEST:
packet = SendDataRequestPacket.createPacket(payload);
break;
case DEVICE_RESPONSE:
packet = DeviceResponsePacket.createPacket(payload);
break;
case BLE_UNLOCK:
packet = BluetoothUnlockPacket.createPacket(payload);
break;
case USER_DATA_RELAY:
packet = UserDataRelayPacket.createPacket(payload);
break;
case RX_64:
packet = RX64Packet.createPacket(payload);
break;
case RX_16:
packet = RX16Packet.createPacket(payload);
break;
case RX_IPV6:
packet = RXIPv6Packet.createPacket(payload);
break;
case RX_IO_64:
packet = RX64IOPacket.createPacket(payload);
break;
case RX_IO_16:
packet = RX16IOPacket.createPacket(payload);
break;
case REMOTE_AT_COMMAND_RESPONSE_WIFI:
packet = RemoteATCommandResponseWifiPacket.createPacket(payload);
break;
case AT_COMMAND_RESPONSE:
packet = ATCommandResponsePacket.createPacket(payload);
break;
case TX_STATUS:
packet = TXStatusPacket.createPacket(payload);
break;
case MODEM_STATUS:
packet = ModemStatusPacket.createPacket(payload);
break;
case TRANSMIT_STATUS:
packet = TransmitStatusPacket.createPacket(payload);
break;
case IO_DATA_SAMPLE_RX_INDICATOR_WIFI:
packet = IODataSampleRxIndicatorWifiPacket.createPacket(payload);
break;
case RECEIVE_PACKET:
packet = ReceivePacket.createPacket(payload);
break;
case EXPLICIT_RX_INDICATOR:
packet = ExplicitRxIndicatorPacket.createPacket(payload);
break;
case IO_DATA_SAMPLE_RX_INDICATOR:
packet = IODataSampleRxIndicatorPacket.createPacket(payload);
break;
case IPV6_IO_DATA_SAMPLE_RX_INDICATOR:
packet = IPv6IODataSampleRxIndicator.createPacket(payload);
break;
case REMOTE_AT_COMMAND_RESPONSE:
packet = RemoteATCommandResponsePacket.createPacket(payload);
break;
case IPV6_REMOTE_AT_COMMAND_RESPONSE:
packet = IPv6RemoteATCommandResponsePacket.createPacket(payload);
break;
case RX_SMS:
packet = RXSMSPacket.createPacket(payload);
break;
case BLE_UNLOCK_RESPONSE:
packet = BluetoothUnlockResponsePacket.createPacket(payload);
break;
case USER_DATA_RELAY_OUTPUT:
packet = UserDataRelayOutputPacket.createPacket(payload);
break;
case RX_IPV4:
packet = RXIPv4Packet.createPacket(payload);
break;
case SEND_DATA_RESPONSE:
packet = SendDataResponsePacket.createPacket(payload);
break;
case DEVICE_REQUEST:
packet = DeviceRequestPacket.createPacket(payload);
break;
case DEVICE_RESPONSE_STATUS:
packet = DeviceResponseStatusPacket.createPacket(payload);
break;
case COAP_TX_REQUEST:
packet = CoAPTxRequestPacket.createPacket(payload);
break;
case COAP_RX_RESPONSE:
packet = CoAPRxResponsePacket.createPacket(payload);
break;
case FRAME_ERROR:
packet = FrameErrorPacket.createPacket(payload);
break;
case GENERIC:
packet = GenericXBeePacket.createPacket(payload);
break;
case UNKNOWN:
default:
packet = UnknownXBeePacket.createPacket(payload);
}
return packet;
}
/**
* Reads one byte from the input stream.
*
* <p>This operation checks several things like the working mode in order
* to consider escaped bytes.</p>
*
* @param inputStream Input stream to read bytes from.
* @param mode XBee device working mode.
*
* @return The read byte.
*
* @throws InvalidPacketException if there is not enough data in the stream or
* if there is an error verifying the checksum.
* @throws IOException if the first byte cannot be read for any reason other than end of file, or
* if the input stream has been closed, or
* if some other I/O error occurs.
*/
private int readByte(InputStream inputStream, OperatingMode mode) throws InvalidPacketException, IOException {
int timeout = 300;
int b = readByteFrom(inputStream, timeout);
if (b == -1)
throw new InvalidPacketException("Error parsing packet: Incomplete packet.");
/* Process the byte for API1. */
if (mode == OperatingMode.API)
return b;
/* Process the byte for API2. */
// Check if the byte is special.
if (!SpecialByte.isSpecialByte(b))
return b;
// Check if the byte is ESCAPE.
if (b == SpecialByte.ESCAPE_BYTE.getValue()) {
// Read next byte and escape it.
b = readByteFrom(inputStream, timeout);
if (b == -1)
throw new InvalidPacketException("Error parsing packet: Incomplete packet.");
b ^= 0x20;
} else
// If the byte is not a escape there is a special byte not escaped.
throw new InvalidPacketException("Special byte not escaped: 0x" + HexUtils.byteToHexString((byte)(b & 0xFF)) + ".");
return b;
}
/**
* Reads the given amount of bytes from the input stream.
*
* <p>This operation checks several things like the working mode in order
* to consider escaped bytes.</p>
*
* @param inputStream Input stream to read bytes from.
* @param mode XBee device working mode.
* @param numBytes Number of bytes to read.
*
* @return The read byte array.
*
* @throws IOException if the first byte cannot be read for any reason other than end of file, or
* if the input stream has been closed, or
* if some other I/O error occurs.
* @throws InvalidPacketException if there is not enough data in the stream or
* if there is an error verifying the checksum.
*/
private byte[] readBytes(InputStream inputStream, OperatingMode mode, int numBytes) throws IOException, InvalidPacketException {
byte[] data = new byte[numBytes];
for (int i = 0; i < numBytes; i++)
data[i] = (byte)readByte(inputStream, mode);
return data;
}
/**
* Reads a byte from the given input stream.
*
* @param inputStream The input stream to read the byte.
* @param timeout Timeout to wait for a byte in the input stream
* in milliseconds.
*
* @return The read byte or {@code -1} if the timeout expires or the end
* of the stream is reached.
*
* @throws IOException if an I/O errors occurs while reading the byte.
*/
private int readByteFrom(InputStream inputStream, int timeout) throws IOException {
long deadline = new Date().getTime() + timeout;
int b = inputStream.read();
// Let's try again if the byte is -1.
while (b == -1 && new Date().getTime() < deadline) {
b = inputStream.read();
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
}
return b;
}
}
| mpl-2.0 |
diging/giles-eco-giles-web | giles-eco/src/main/java/edu/asu/diging/gilesecosystem/web/web/LoginFailedController.java | 316 | package edu.asu.diging.gilesecosystem.web.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginFailedController {
@RequestMapping(value="/signin")
public String loginFailed() {
return "signin";
}
}
| mpl-2.0 |
Elviond/Wurst-Client | Wurst Client/src/tk/wurst_client/commands/AuthorCmd.java | 1122 | /*
* Copyright © 2014 - 2016 | Wurst-Imperium | All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package tk.wurst_client.commands;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagString;
import tk.wurst_client.commands.Cmd.Info;
@Info(help = "Changes the held book's author.",
name = "author",
syntax = {"<author>"})
public class AuthorCmd extends Cmd
{
@Override
public void execute(String[] args) throws Cmd.Error
{
if(args.length == 0)
syntaxError();
if(!mc.thePlayer.capabilities.isCreativeMode)
error("Creative mode only.");
ItemStack item = mc.thePlayer.inventory.getCurrentItem();
if(item == null || Item.getIdFromItem(item.getItem()) != 387)
error("You are not holding a written book in your hand.");
String author = args[0];
for(int i = 1; i < args.length; i++)
author += " " + args[i];
item.setTagInfo("author", new NBTTagString(author));
}
}
| mpl-2.0 |
cFerg/MineJava | src/main/java/minejava/yaml/nodes/NodeId.java | 106 | package minejava.yaml.nodes;
public enum NodeId{
scalar,
sequence,
mapping,
anchor;
}
| mpl-2.0 |
yonadev/yona-app-android | app/src/main/java/nu/yona/app/ui/friends/OverviewFragment.java | 6222 | /*
* Copyright (c) 2018 Stichting Yona Foundation
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package nu.yona.app.ui.friends;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersTouchListener;
import java.util.ArrayList;
import java.util.List;
import nu.yona.app.R;
import nu.yona.app.YonaApplication;
import nu.yona.app.analytics.AnalyticsConstant;
import nu.yona.app.analytics.YonaAnalytics;
import nu.yona.app.api.manager.APIManager;
import nu.yona.app.api.model.ErrorMessage;
import nu.yona.app.api.model.YonaBuddies;
import nu.yona.app.api.model.YonaBuddy;
import nu.yona.app.api.model.YonaHeaderTheme;
import nu.yona.app.enums.IntentEnum;
import nu.yona.app.enums.StatusEnum;
import nu.yona.app.listener.DataLoadListener;
import nu.yona.app.recyclerViewDecor.DividerDecoration;
import nu.yona.app.state.EventChangeListener;
import nu.yona.app.state.EventChangeManager;
import nu.yona.app.ui.BaseFragment;
import nu.yona.app.ui.YonaActivity;
import nu.yona.app.utils.AppConstant;
/**
* Created by kinnarvasa on 21/03/16.
*/
public class OverviewFragment extends BaseFragment implements EventChangeListener
{
private List<YonaBuddy> mListBuddy;
private OverViewAdapter mOverViewAdapter;
private RecyclerView mFriendsRecyclerView;
private boolean isCurrentTabInView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.friends_overview_fragment, null);
mListBuddy = new ArrayList<>();
mFriendsRecyclerView = (RecyclerView) view.findViewById(R.id.listView);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(YonaActivity.getActivity());
mFriendsRecyclerView.setLayoutManager(mLayoutManager);
mOverViewAdapter = new OverViewAdapter(mListBuddy, YonaActivity.getActivity(), new OnFriendsItemClickListener()
{
@Override
public void onFriendsItemClick(View v)
{
YonaBuddy yonaBuddy = (YonaBuddy) v.getTag();
if (yonaBuddy != null && !yonaBuddy.getSendingStatus().equals(StatusEnum.REQUESTED.getStatus()))
{
Intent friendIntent = new Intent(IntentEnum.ACTION_DASHBOARD.getActionString());
Bundle bundle = new Bundle();
YonaAnalytics.createTapEventWithCategory(getString(R.string.overiview), AnalyticsConstant.FRIEND_TIMELINE);
if (yonaBuddy.getLinks() != null)
{
bundle.putSerializable(AppConstant.YONA_THEME_OBJ, new YonaHeaderTheme(true, yonaBuddy.getLinks().getYonaDailyActivityReports(), yonaBuddy.getLinks().getYonaWeeklyActivityReports(), 0, 0, yonaBuddy.getEmbedded().getYonaUser().getFirstName() + " " + yonaBuddy.getEmbedded().getYonaUser().getLastName(), R.color.mid_blue_two, R.drawable.triangle_shadow_blue));
}
else
{
bundle.putSerializable(AppConstant.YONA_THEME_OBJ, new YonaHeaderTheme(true, null, null, 0, 0, yonaBuddy.getEmbedded().getYonaUser().getFirstName() + " " + yonaBuddy.getEmbedded().getYonaUser().getLastName(), R.color.mid_blue_two, R.drawable.triangle_shadow_blue));
}
friendIntent.putExtra(AppConstant.YONA_BUDDY_OBJ, yonaBuddy);
friendIntent.putExtras(bundle);
YonaActivity.getActivity().replaceFragment(friendIntent);
}
}
@Override
public void onFriendsItemDeleteClick(View v)
{
}
@Override
public void onItemClick(View v)
{
}
});
mFriendsRecyclerView.setAdapter(mOverViewAdapter);
setRecyclerHeaderAdapterUpdate(new StickyRecyclerHeadersDecoration(mOverViewAdapter));
YonaApplication.getEventChangeManager().registerListener(this);
getBuddies();
return view;
}
@Override
public void onDestroy()
{
super.onDestroy();
YonaApplication.getEventChangeManager().unRegisterListener(this);
}
public void setIsInView(boolean isInView)
{
isCurrentTabInView = isInView;
}
/**
* Get Buddies
*/
private void getBuddies()
{
YonaActivity.getActivity().displayLoadingView();
APIManager.getInstance().getBuddyManager().getBuddies(new DataLoadListener()
{
@Override
public void onDataLoad(Object result)
{
if (result instanceof YonaBuddies)
{
YonaBuddies buddies = (YonaBuddies) result;
mListBuddy.clear();
if (buddies != null && buddies.getEmbedded() != null && buddies.getEmbedded().getYonaBuddies() != null)
{
mListBuddy = buddies.getEmbedded().getYonaBuddies();
mOverViewAdapter.notifyDataSetChange(mListBuddy);
}
}
YonaActivity.getActivity().dismissLoadingView();
}
@Override
public void onError(Object errorMessage)
{
YonaActivity.getActivity().dismissLoadingView();
YonaActivity.getActivity().showError((ErrorMessage) errorMessage);
}
});
}
/**
* update RecyclerView item header for grouping section
*
* @param headerDecor
*/
private void setRecyclerHeaderAdapterUpdate(StickyRecyclerHeadersDecoration headerDecor)
{
mFriendsRecyclerView.addItemDecoration(headerDecor);
// Add decoration for dividers between list items
mFriendsRecyclerView.addItemDecoration(new DividerDecoration(getActivity()));
// Add touch listeners
StickyRecyclerHeadersTouchListener touchListener =
new StickyRecyclerHeadersTouchListener(mFriendsRecyclerView, headerDecor);
touchListener.setOnHeaderClickListener(
new StickyRecyclerHeadersTouchListener.OnHeaderClickListener()
{
@Override
public void onHeaderClick(View header, int position, long headerId)
{
}
});
}
@Override
public void onStateChange(int eventType, Object object)
{
switch (eventType)
{
case EventChangeManager.EVENT_UPDATE_FRIEND_OVERVIEW:
getBuddies();
break;
default:
break;
}
}
}
| mpl-2.0 |
hyb1996/NoRootScriptDroid | autojs/src/main/java/com/stardust/autojs/core/ui/widget/JsButton.java | 903 | package com.stardust.autojs.core.ui.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
/**
* Created by Stardust on 2017/5/15.
*/
@SuppressLint("AppCompatCustomView")
public class JsButton extends Button {
public JsButton(Context context) {
super(context);
}
public JsButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public JsButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public JsButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public String text() {
return getText().toString();
}
public void text(CharSequence text) {
setText(text);
}
}
| mpl-2.0 |
null-dev/EvenWurse | Wurst Client/src/tk/wurst_client/gui/options/config/GuiConfigEntryManager.java | 3917 | /*
* Copyright � 2014 - 2015 Alexander01998 and contributors
* All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package tk.wurst_client.gui.options.config;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import tk.wurst_client.WurstClient;
import tk.wurst_client.api.Module;
import tk.wurst_client.api.ModuleConfiguration;
import tk.wurst_client.utils.ModuleUtils;
import java.io.IOException;
public class GuiConfigEntryManager extends GuiScreen {
public GuiConfigEntryList configList;
private GuiScreen prevMenu;
private Module module;
public GuiConfigEntryManager(GuiScreen par1GuiScreen, Module m) {
this.module = m;
prevMenu = par1GuiScreen;
}
void reloadList() {
configList = new GuiConfigEntryList(mc, module, this);
configList.registerScrollButtons(7, 8);
configList.elementClicked(-1, false, 0, 0);
}
@SuppressWarnings("unchecked")
@Override
public void initGui() {
reloadList();
buttonList.clear();
buttonList.add(new GuiButton(0, width / 2 - 100, height - 52, 98, 20, "Edit"));
buttonList.add(new GuiButton(1, width / 2 + 2, height - 52, 98, 20, "Remove"));
buttonList.add(new GuiButton(2, width / 2 - 100, height - 28, 98, 20, "Add"));
buttonList.add(new GuiButton(3, width / 2 + 2, height - 28, 98, 20, "Back"));
}
/**
* Called from the main game loop to update the screen.
*/
@Override
public void updateScreen() {
boolean selected = configList.getSelectedSlot() != -1 && !ModuleConfiguration.CONFIGURATION.isEmpty();
((GuiButton) buttonList.get(0)).enabled = selected;
((GuiButton) buttonList.get(1)).enabled = selected;
}
String getSelectedKey() {
return configList.elements.get(configList.getSelectedSlot()).getKey();
}
String getSelectedValue() {
return configList.elements.get(configList.getSelectedSlot()).getValue();
}
@Override
protected void actionPerformed(GuiButton clickedButton) {
if (clickedButton.enabled) {
if (clickedButton.id == 0) {
mc.displayGuiScreen(new GuiConfigEdit(this, module, getSelectedKey(), getSelectedValue()));
} else if (clickedButton.id == 1) {
ModuleConfiguration.forModule(module).getConfig().remove(getSelectedKey());
WurstClient.INSTANCE.files.saveModuleConfigs();
reloadList();
} else if (clickedButton.id == 2) {
mc.displayGuiScreen(new GuiConfigAdd(this, module));
} else if (clickedButton.id == 3) mc.displayGuiScreen(prevMenu);
}
}
/**
* Called when the mouse is clicked.
*
* @throws IOException
*/
@Override
protected void mouseClicked(int par1, int par2, int par3) throws IOException {
if (par2 >= 36 && par2 <= height - 57) {
if (par1 >= width / 2 + 140 || par1 <= width / 2 - 126) configList.elementClicked(-1, false, 0, 0);
}
super.mouseClicked(par1, par2, par3);
}
/**
* Draws the screen and all the components in it.
*/
@Override
public void drawScreen(int par1, int par2, float par3) {
drawDefaultBackground();
configList.drawScreen(par1, par2, par3);
drawCenteredString(fontRendererObj, ModuleUtils.getModuleName(module) + " Configuration", width / 2, 8,
16777215);
drawCenteredString(fontRendererObj,
"Total Configurable Entries: " + ModuleConfiguration.forModule(module).getConfig().size(), width / 2,
20, 16777215);
super.drawScreen(par1, par2, par3);
}
}
| mpl-2.0 |
magenta-aps/mox | agents/MoxRestFrontend/src/main/java/dk/magenta/mox/moxrestfrontend/ObjectType.java | 11325 | /*
Copyright (C) 2015-2019 Magenta ApS, https://magenta.dk.
Contact: info@magenta.dk.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package dk.magenta.mox.moxrestfrontend;
import dk.magenta.mox.agent.messages.*;
import org.apache.log4j.Logger;
import javax.naming.OperationNotSupportedException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
/**
* Created by lars on 30-07-15.
*/
public class ObjectType {
private String name;
private HashMap<String, Operation> operations;
private Logger log = Logger.getLogger(ObjectType.class);
public enum Method {
GET,
POST,
PUT,
DELETE,
HEAD
}
public class Operation {
private String name;
public Method method;
public String path;
public Operation(String name) {
this.name = name;
}
public String toString() {
return "Operation { \"name\":\""+this.name+"\", \"method\":\""+this.method.toString()+"\", \"path\":\""+this.path+"\" }";
}
}
private static class Inheritance {
public String inheritFrom;
public String basePath;
}
public ObjectType(String name) {
this.name = name;
this.operations = new HashMap<String, Operation>();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ObjectType { ");
sb.append("\"name\":\""+this.name+"\",");
sb.append("\"operations\":[");
for (String operationName : this.operations.keySet()) {
sb.append("\""+operationName+"\":");
sb.append(this.operations.get(operationName).toString());
sb.append(",");
}
sb.append("]");
sb.append("}");
return sb.toString();
}
private Operation addOperation(String name) {
Operation operation = new Operation(name);
this.operations.put(name, operation);
return operation;
}
public Operation addOperation(String name, Method method, String path) {
if (name != null) {
Operation operation = this.addOperation(name);
operation.method = method;
operation.path = path;
return operation;
}
return null;
}
public Operation getOperation(String name) {
return this.getOperation(name, false);
}
public Operation getOperation(String name, boolean createIfMissing) {
try {
return this.getOperation(name, createIfMissing, false);
} catch (OperationNotSupportedException e) {
e.printStackTrace(); // This can't really happen
return null;
}
}
public Operation getOperation(String name, boolean createIfMissing, boolean failIfMissing) throws OperationNotSupportedException {
Operation operation = this.operations.get(name);
if (operation == null) {
if (createIfMissing) {
return this.addOperation(name);
} else if (failIfMissing) {
this.testOperationSupported(name);
}
}
return operation;
}
public boolean hasOperation(String operationName) {
return this.operations.containsKey(operationName);
}
public static Map<String, ObjectType> load(String propertiesFileName) throws IOException {
return load(new File(propertiesFileName));
}
public static Map<String, ObjectType> load(File propertiesFile) throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream(propertiesFile));
return load(properties);
}
public static Map<String, ObjectType> load(Properties properties) {
HashMap<String, ObjectType> objectTypes = new HashMap<String, ObjectType>();
HashMap<ObjectType, Inheritance> inheritances = new HashMap<>();
for (String key : properties.stringPropertyNames()) {
String[] path = key.split("\\.");
if (path[0].equals("type")) {
String name = path[1];
ObjectType objectType = objectTypes.get(name);
if (objectType == null) {
objectType = new ObjectType(name);
objectTypes.put(name, objectType);
}
String attributeValue = properties.getProperty(key);
if (path.length >= 4 && !path[2].startsWith("_")) {
String operationName = path[2];
Operation operation = objectType.getOperation(operationName, true);
String attributeName = path[3].trim();
if (attributeName.equals("method")) {
try {
operation.method = Method.valueOf(attributeValue);
} catch (IllegalArgumentException e) {
String[] strings = new String[Method.values().length];
int i = 0;
for (Method m : Method.values()) {
strings[i++] = m.toString();
}
System.err.println("Error loading properties: method '" + attributeName + "' is not recognized. Recognized methods are: " + String.join(", ", strings));
}
} else if (attributeName.equals("path")) {
operation.path = attributeValue;
}
} else if (path.length == 3 && path[2].startsWith("_")){
Inheritance inheritance = inheritances.get(objectType);
if (inheritance == null) {
inheritance = new Inheritance();
inheritances.put(objectType, inheritance);
}
if (path[2].equals("_basetype")) {
inheritance.inheritFrom = attributeValue;
} else if (path[2].equals("_basepath")) {
inheritance.basePath = attributeValue;
}
}
}
}
for (ObjectType objectType : inheritances.keySet()) {
Inheritance inheritance = inheritances.get(objectType);
ObjectType dependee = objectTypes.get(inheritance.inheritFrom);
if (dependee == null) {
System.err.println("Object type "+objectType.getName()+" inherits from Object type"+ inheritance.inheritFrom +", but it is not found");
} else {
String basepath = inheritance.basePath;
for (String operationName : dependee.operations.keySet()) {
Operation dependeeOperation = dependee.getOperation(operationName);
Operation operation = objectType.getOperation(operationName, true);
operation.method = dependeeOperation.method;
operation.path = dependeeOperation.path.replace("[basepath]", basepath);
}
}
}
String[] neededOperations = {
DocumentMessage.OPERATION_CREATE,
DocumentMessage.OPERATION_READ,
DocumentMessage.OPERATION_SEARCH,
DocumentMessage.OPERATION_LIST,
DocumentMessage.OPERATION_UPDATE,
DocumentMessage.OPERATION_PASSIVATE,
DocumentMessage.OPERATION_DELETE
};
for (ObjectType objectType : objectTypes.values()) {
for (String operation : neededOperations) {
if (!objectType.operations.containsKey(operation)) {
System.err.println("Warning: Object type "+objectType.name+" does not contain the "+operation+" operation. Calls to methods using that operation will fail.");
}
}
}
return objectTypes;
}
public String getName() {
return name;
}
/*
public CreateDocumentMessage create(String authorization, JSONObject data) {
return new CreateDocumentMessage(authorization, data);
}
public ReadDocumentMessage read(String authorization, UUID uuid) {
return new ReadDocumentMessage(authorization, uuid);
}
public SearchDocumentMessage search(ParameterMap<String, String> query, String authorization) {
return new SearchDocumentMessage(authorization, query);
}
public ListDocumentMessage list(UUID uuid, String authorization) {
return new ListDocumentMessage(authorization, uuid);
}
public ListDocumentMessage list(List<UUID> uuids, String authorization) {
return new ListDocumentMessage(authorization, uuids);
}
public UpdateDocumentMessage update(UUID uuid, JSONObject data, String authorization) {
return new UpdateDocumentMessage(authorization, uuid, data);
}
public PassivateDocumentMessage passivate(UUID uuid, String note, String authorization) {
return new PassivateDocumentMessage(authorization, uuid, note);
}
public DeleteDocumentMessage delete(UUID uuid, String note, String authorization) throws IOException, OperationNotSupportedException {
return new DeleteDocumentMessage(authorization, uuid, note);
}
*/
/*
public Future<String> sendCommand(MessageSender sender, String operationName, UUID uuid, JSONObject data) throws IOException {
return this.sendCommand(sender, operationName, uuid, data, null, null);
}
public Future<String> sendCommand(MessageSender sender, String operationName, UUID uuid, JSONObject data, String authorization) throws IOException {
return this.sendCommand(sender, operationName, uuid, data, authorization, null);
}
public Future<String> sendCommand(MessageSender sender, String operationName, UUID uuid, JSONObject data, String authorization, JSONObject query) throws IOException {
HashMap<String, Object> headers = new HashMap<String, Object>();
headers.put(MessageInterface.HEADER_OBJECTTYPE, this.name);
headers.put(MessageInterface.HEADER_OPERATION, operationName);
if (uuid != null) {
headers.put(MessageInterface.HEADER_MESSAGEID, uuid.toString());
}
if (authorization != null) {
headers.put(MessageInterface.HEADER_AUTHORIZATION, authorization);
}
if (query != null) {
headers.put(MessageInterface.HEADER_QUERY, query.toString());
}
try {
return sender.sendJSON(headers, data);
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
}*/
private static String capitalize(String s) {
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
public void testOperationSupported(String operationName) throws OperationNotSupportedException {
if (!this.hasOperation(operationName)) {
throw new OperationNotSupportedException("Operation " + operationName + " is not defined for Object type " + this.name);
}
}
}
| mpl-2.0 |
Wurst-Imperium/Wurst-Enigma | Wurst Enigma/src/cuchaz/enigma/bytecode/accessors/StringInfoAccessor.java | 1454 | /*******************************************************************************
* Copyright (c) 2015 Jeff Martin.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public
* License v3.0 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* Contributors:
* Jeff Martin - initial API and implementation
******************************************************************************/
package cuchaz.enigma.bytecode.accessors;
import java.lang.reflect.Field;
public class StringInfoAccessor
{
private static Class<?> m_class;
private static Field m_stringIndex;
static
{
try
{
m_class = Class.forName("javassist.bytecode.StringInfo");
m_stringIndex = m_class.getDeclaredField("string");
m_stringIndex.setAccessible(true);
}catch(Exception ex)
{
throw new Error(ex);
}
}
public static boolean isType(ConstInfoAccessor accessor)
{
return m_class.isAssignableFrom(accessor.getItem().getClass());
}
private Object m_item;
public StringInfoAccessor(Object item)
{
m_item = item;
}
public int getStringIndex()
{
try
{
return (Integer)m_stringIndex.get(m_item);
}catch(Exception ex)
{
throw new Error(ex);
}
}
public void setStringIndex(int val)
{
try
{
m_stringIndex.set(m_item, val);
}catch(Exception ex)
{
throw new Error(ex);
}
}
}
| mpl-2.0 |
gnosygnu/xowa_android | _400_xowa/src/main/java/gplx/xowa/wikis/tdbs/xdats/Xob_xdat_file.java | 10564 | package gplx.xowa.wikis.tdbs.xdats; import gplx.*; import gplx.xowa.*; import gplx.xowa.wikis.*; import gplx.xowa.wikis.tdbs.*;
import gplx.core.ios.*; import gplx.core.ios.streams.*;
import gplx.core.encoders.*;
public class Xob_xdat_file {
public byte[] Src() {return src;} private byte[] src;
public int Src_len() {return src_len;} public Xob_xdat_file Src_len_(int v) {src_len = v; return this;} private int src_len; // NOTE: src_len can be different than src.length (occurs when reusing brys)
public Xob_xdat_file Update(Bry_bfr bfr, Xob_xdat_itm itm, byte[] v) {
int ary_len = itm_ends.length;
int itm_idx = itm.Itm_idx();
int prv = itm_idx == 0 ? 0 : itm_ends[itm_idx - 1];
int old_end = itm_ends[itm_idx];
int new_end = prv + v.length;
int dif = new_end - old_end;
itm_ends[itm_idx] = new_end;
for (int i = itm_idx + 1; i < ary_len; i++) {
itm_ends[i] += dif;
}
Src_rebuild_hdr(bfr, ary_len);
bfr.Add_mid(src, itm_0_bgn, itm.Itm_bgn());
bfr.Add(v);
bfr.Add_mid(src, itm.Itm_end() + 1, src.length); // NOTE: + 1 to skip nl
src = bfr.To_bry_and_clear();
return this;
}
byte[][] Src_extract_brys(int ary_len) {
byte[][] rv = new byte[ary_len][];
int itm_bgn = this.itm_0_bgn;
for (int i = 0; i < ary_len; i++) {
int itm_end = itm_ends[i] + itm_0_bgn;
rv[i] = Bry_.Mid(src, itm_bgn, itm_end);
itm_bgn = itm_end;
}
return rv;
}
public void Sort(Bry_bfr bfr, gplx.core.lists.ComparerAble comparer) {
int ary_len = itm_ends.length;
byte[][] brys = Src_extract_brys(ary_len);
Array_.Sort(brys, comparer);
Src_rebuild_hdr(bfr, ary_len);
itm_0_bgn = (ary_len * Len_idx_itm) + Len_itm_dlm;
int itm_bgn = 0;
for (int i = 0; i < ary_len; i++) {
byte[] bry = brys[i];
int bry_len = bry.length;
int itm_end = itm_bgn + bry_len;
itm_ends[i] = itm_end;
itm_bgn = itm_end;
bfr.Add(bry);
}
src = bfr.To_bry_and_clear();
}
public void Insert(Bry_bfr bfr, byte[] itm) {
int ary_len = itm_ends.length;
itm_ends = (int[])Array_.Resize(itm_ends, ary_len + 1);
int prv_pos = ary_len == 0 ? 0 : itm_ends[ary_len - 1];
itm_ends[ary_len] = prv_pos + itm.length;
Src_rebuild(bfr, ary_len + 1, itm);
}
private void Src_rebuild_hdr(Bry_bfr bfr, int ary_len) {
int bgn = 0;
for (int i = 0; i < ary_len; i++) {
int end = itm_ends[i];
int len = end - bgn;
bfr.Add_base85_len_5(len).Add_byte(Dlm_hdr_fld);
bgn = end;
}
bfr.Add_byte(Dlm_row);
}
private void Src_rebuild(Bry_bfr bfr, int ary_len, byte[] new_itm) {
Src_rebuild_hdr(bfr, ary_len);
Src_rebuild_brys(bfr, ary_len, new_itm);
}
private void Src_rebuild_brys(Bry_bfr bfr, int ary_len, byte[] new_itm) {
int bgn = itm_0_bgn;
boolean insert = new_itm != null;
int ary_end = insert ? ary_len - 1 : ary_len;
for (int i = 0; i < ary_end; i++) {
int end = itm_ends[i] + itm_0_bgn;
bfr.Add_mid(src, bgn, end);
bgn = end;
}
if (insert) bfr.Add(new_itm);
itm_0_bgn = (ary_len * Len_idx_itm) + Len_itm_dlm;
src = bfr.To_bry_and_clear();
} private static final byte Dlm_hdr_fld = Byte_ascii.Pipe, Dlm_row = Byte_ascii.Nl;
public void Save(Io_url url) {
Bry_bfr bfr = Bry_bfr_.New();
Srl_save_bry(bfr);
Io_stream_wtr wtr = Io_stream_wtr_.New_by_url(url);
try {
wtr.Open();
wtr.Write(bfr.Bfr(), 0, bfr.Len());
wtr.Flush();
}
catch (Exception e) {throw Err_.new_exc(e, "xo", "failed to save file", "url", url.Xto_api());}
finally {
wtr.Rls();
}
}
public void Srl_save_bry(Bry_bfr bfr) {
int itm_ends_len = itm_ends.length;
int prv_bgn = 0;
for (int i = 0; i < itm_ends_len; i++) {
int itm_end = itm_ends[i];
bfr.Add_base85_len_5(itm_end - prv_bgn).Add_byte(Dlm_hdr_fld);
prv_bgn = itm_end;
}
bfr.Add_byte(Dlm_row);
bfr.Add_mid(src, itm_0_bgn, src.length);
}
public byte[] Get_bry(int i) {
int bgn = i == 0 ? itm_0_bgn : itm_0_bgn + itm_ends[i - 1];
int end = itm_0_bgn + itm_ends[i];
return Bry_.Mid(src, bgn, end);
}
public int Count() {return itm_ends.length;}
public Xob_xdat_file GetAt(Xob_xdat_itm itm, int idx) {
itm.Src_(src);
itm.Itm_idx_(idx);
itm.Itm_bgn_(itm_0_bgn + (idx == 0 ? 0 : itm_ends[idx - 1]));
itm.Itm_end_(itm_0_bgn + itm_ends[idx] - Len_itm_dlm);
return this;
}
public Xob_xdat_file Find(Xob_xdat_itm itm, byte[] lkp, int lkp_bgn, byte lkp_dlm, boolean exact) {
itm.Clear();
int itm_idx = Xob_xdat_file_.BinarySearch(itm_0_bgn, src, itm_ends, lkp, lkp_bgn, lkp_dlm, 1, exact, itm); if (itm_idx == String_.Find_none) {return this;}
GetAt(itm, itm_idx);
return this;
}
public Xob_xdat_file Clear() {src = null; itm_ends = Int_.Ary_empty; return this;}
private int[] itm_ends = Int_.Ary_empty; private int itm_0_bgn;
public Xob_xdat_file Parse(byte[] src, int src_len, Io_url url) {// SEE:NOTE_1;xdat format
if (src_len == 0) throw Err_.new_wo_type("file cannot be empty for parse", "url", url.Raw());
int itm_count = 0, tmp_len = Parse_tmp_len; int[] tmp = Parse_tmp;
try {
int slot_bgn = 0, slot_old = 0, slot_new = 0;
while (true) {
slot_bgn = itm_count * Len_idx_itm;
if (slot_bgn >= src_len) break;
if (src[slot_bgn] == Byte_ascii.Nl) break;
int tmp_val = Base85_.To_int_by_bry(src, slot_bgn, slot_bgn + Offset_base85);
slot_new = slot_old + tmp_val;
int new_idx = itm_count + 1;
if (tmp_len < new_idx) {
tmp_len = new_idx * 2;
tmp = (int[])Array_.Resize(tmp, tmp_len);
}
tmp[itm_count] = slot_new;
itm_count = new_idx;
slot_old = slot_new;
}
int itm_ends_last = slot_new;
itm_ends = new int[itm_count];
for (int i = 0; i < itm_count; i++)
itm_ends[i] = tmp[i];
itm_0_bgn = slot_bgn + Len_itm_dlm;
this.src = Bry_.Mid(src, 0, itm_ends_last + itm_0_bgn);
} catch (Exception e) {throw Err_.new_exc(e, "xo", "failed to parse idx", "itm_count", itm_count, "url", url.Raw());}
return this;
} private static final int Parse_tmp_len = 8 * 1024; static int[] Parse_tmp = new int[Parse_tmp_len];
static final int Len_itm_dlm = 1, Len_idx_itm = 6, Offset_base85 = 4; // 6 = 5 (base85_int) + 1 (new_line/pipe)
static final String GRP_KEY = "xowa.xdat_fil";
public static byte[] Rebuid_header(byte[] orig, byte[] dlm) {
byte[][] rows = Bry_split_.Split(orig, dlm);
int rows_len = rows.length;
Bry_bfr bfr = Bry_bfr_.New();
int dlm_len = dlm.length;
for (int i = 1; i < rows_len; i++) { // i=1; skip 1st row (which is empty header)
byte[] row = rows[i];
int row_len = row.length + dlm_len;
bfr.Add_base85_len_5(row_len).Add_byte(Byte_ascii.Pipe);
}
bfr.Add_byte(Byte_ascii.Nl);
for (int i = 1; i < rows_len; i++) { // i=1; skip 1st row (which is empty header)
byte[] row = rows[i];
bfr.Add(row);
bfr.Add(dlm);
}
return bfr.To_bry_and_clear();
}
}
class Xob_xdat_file_ {
public static int BinarySearch(int itm_0_bgn, byte[] src, int[] itm_ends, byte[] lkp, int lkp_bgn, byte lkp_dlm, int itm_end_adj, boolean exact, Xob_xdat_itm xdat_itm) {if (lkp == null) throw Err_.new_null();
int itm_ends_len = itm_ends.length; if (itm_ends_len == 0) throw Err_.new_wo_type("itm_ends_len cannot have 0 itms");
int lo = -1, hi = itm_ends_len - 1; // NOTE: -1 is necessary; see test
int itm_idx = (hi - lo) / 2;
int lkp_len = lkp.length;
int delta = 1;
boolean flagged = false;
while (true) {
int itm_bgn = itm_0_bgn + (itm_idx == 0 ? 0 : itm_ends[itm_idx - 1]);
int itm_end = itm_0_bgn + itm_ends[itm_idx] - itm_end_adj; // itm_end_adj to handle ttl .xdat and trailing \n
int fld_bgn = itm_bgn + lkp_bgn, lkp_pos = -1;
int comp = CompareAble_.Same;
for (int i = fld_bgn; i < itm_end; i++) { // see if current itm matches lkp; NOTE: that i < itm_end but will end much earlier (since itm_end includes page text)
byte b = src[i];
if (b == lkp_dlm) { // fld is done
if (lkp_pos != lkp_len - 1) comp = CompareAble_.More; // lkp has more chars than itm; lkp_dlm reached early
break;
}
lkp_pos = i - fld_bgn;
if (lkp_pos >= lkp_len) {
comp = CompareAble_.Less; // lkp has less chars than itm
break;
}
comp = (lkp[lkp_pos] & 0xff) - (b & 0xff); // subtract src[i] from lkp[lkp_pos] // PATCH.JAVA:need to convert to unsigned byte
if (comp != CompareAble_.Same) break; // if comp != 0 then not equal; break; otherwise if bytes are the same, then comp == 0;
}
if (comp > CompareAble_.Same || (comp == CompareAble_.Same && itm_end - fld_bgn < lkp_len)) {lo = itm_idx; delta = 1;}
else if (comp == CompareAble_.Same) {xdat_itm.Found_exact_y_(); return itm_idx;}
else if (comp < CompareAble_.Same) {hi = itm_idx; delta = -1;}
int itm_dif = hi - lo;
// if (itm_end - 1 > fld_bgn) Tfds.Dbg(comp, itm_dif, String_.new_u8(src, fld_bgn, itm_end - 1));
switch (itm_dif) {
case 0: return exact ? String_.Find_none : hi; // NOTE: can be 0 when src.length == 1 || 2; also, sometimes 0 in some situations
case -1:
if (flagged) return exact ? String_.Find_none : lo;
else {
itm_idx--;
flagged = true;
}
break;
case 1:
if (flagged) return exact ? String_.Find_none : hi;
else {
itm_idx++; // ++ to always take higher value when !exact???; EX: "ab,ad,af"
if (itm_idx >= itm_ends_len) return String_.Find_none; // NOTE: occurs when there is only 1 item
flagged = true;
}
break;
default:
itm_idx += ((itm_dif / 2) * delta);
break;
}
}
}
}
/*
NOTE_1:xdat format
line 0 : delimited String of article lengths; EX: "00012|00004|00005\n"
line 1+: articles
pseudo example: (note that ints/dates will be replaced with base85 variants)
== BOF ==
00025|00024|00026
2006-01-01 Ttl1 Abcd
2006-02-01 Ttl2 Abc
2006-03-01 Ttl3 Abcde
== EOF ==
other notes:
. itm_len is entire length of article including text, title, date and any other fields
. line 0 uses len instead of bgn or end b/c len is independent (single len can be changed without having to recalculate entire array)
. however, note that in memory, itm_end_ary will be stored; this will make article extraction quicker: getting nth article means getting nth item in array;
. Parse is written for speed, not correctness; if correctness is needed, write a separate method that validates and call it before calling parse
*/
| agpl-3.0 |
heniancheng/FRODO | src/frodo2/communication/tcp/QueueOutputPipeTCP.java | 13215 | /*
FRODO: a FRamework for Open/Distributed Optimization
Copyright (C) 2008-2013 Thomas Leaute, Brammert Ottens & Radoslaw Szymanek
FRODO is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
FRODO 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
How to contact the authors:
<http://frodo2.sourceforge.net/>
*/
/** Contains classes used for communication between agents via TCP */
package frodo2.communication.tcp;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import frodo2.communication.Message;
import frodo2.communication.MessageWithRawData;
import frodo2.communication.MessageWrapper;
import frodo2.communication.QueueOutputPipeInterface;
/** This is a queue output pipe that sends messages through TCP
* @author Thomas Leaute
* @todo Use ZIP streams to reduce information exchange?...
*/
public class QueueOutputPipeTCP implements Runnable, QueueOutputPipeInterface {
/** List into which pushed messages should be added, until they are sent */
private LinkedList <Message> messages = new LinkedList <Message> ();
/** IP address to which recipients should connect to request raw data */
private String rawDataIP;
/** Port number on which the pipe should wait for requests for raw data */
private int rawDataPort;
/** Used to tell the thread to stop */
private boolean keepGoing = true;
/** Output stream to which outgoing messages should be written */
private ObjectOutputStream output;
/** The name of this pipe, used only by QueueOutputPipeTCP#toDOT() */
private String name;
/** The ID incremented each time a message with raw data is sent */
private Integer rawDataID = 0;
/** Lock for the rawDataID field */
private final ReentrantLock rawDataID_lock = new ReentrantLock();
/** Lock for the rawDataInfos field */
private final ReentrantLock rawDataInfos_lock = new ReentrantLock();
/** Lock for the messages field */
private final ReentrantLock messages_lock = new ReentrantLock();
/** Condition used to signal that the messages list is not empty */
private final Condition messageReceived = messages_lock.newCondition(); /// @todo Use a BlockingQueue instead?
/** A convenience class used to store information about raw data */
private static class RawDataInfo {
/** A message with associated raw data */
public MessageWithRawData msg;
/** The number of recipients potentially interested in the raw data */
public Integer counter;
/** Constructor
* @param msg the message with raw data
* @param counter the number of recipients potentially interested in the raw data
*/
public RawDataInfo(MessageWithRawData msg, Integer counter) {
this.msg = msg;
this.counter = counter;
}
}
/** For each raw data ID, the information about the corresponding raw data */
private HashMap<Integer, RawDataInfo> rawDataInfos = new HashMap<Integer, RawDataInfo> ();
/** A thread that listens for requests to serialize or discard raw data */
private class RawDataSender extends Thread {
/** The socket used to communicate with the potential raw data recipient */
private Socket socket;
/** Constructor
* @param socket the socket used to communicate with the potential raw data recipient
*/
public RawDataSender(Socket socket) {
super("RawDataSender");
this.socket = socket;
start();
}
/** @see java.lang.Thread#start() */
@Override
public void start () {
this.setDaemon(true);
super.start();
}
/** Waits for requests concerning raw data */
public void run () {
// Get the info about the requested raw data
ObjectInputStream inStream;
Integer rawDataID;
try {
inStream = new ObjectInputStream (socket.getInputStream());
rawDataID = inStream.readInt();
} catch (IOException e2) {
System.err.println("Failed to read the raw data ID");
e2.printStackTrace();
return;
}
RawDataInfo rawDataInfo;
try {
rawDataInfos_lock.lock();
assert rawDataInfos.containsKey(rawDataID) : "Received a request for an unknown raw data ID " + rawDataID;
rawDataInfo = rawDataInfos.get(rawDataID);
} finally {
rawDataInfos_lock.unlock();
}
// Increment the number of potential recipients for the raw data
synchronized (rawDataInfo) {
rawDataInfo.counter++;
}
// Check whether we must send the raw data
try {
if (inStream.readBoolean()) {
try {
ObjectOutputStream outStream = new ObjectOutputStream(socket.getOutputStream());
rawDataInfo.msg.serializeRawData(outStream);
try {
outStream.close();
} catch (IOException e) { }
} catch (IOException e1) {
System.err.println("Unable to set up the stream to send raw data in the following message:\n" + rawDataInfo.msg);
e1.printStackTrace();
}
}
} catch (IOException e1) {
System.err.println("Failed to determine whether the recipients wants the raw data of the following message:\n"
+ rawDataInfo.msg);
e1.printStackTrace();
}
try {
inStream.close();
} catch (IOException e) { }
// Check whether there are no more potential recipients for the raw data
synchronized (rawDataInfo) {
if (--rawDataInfo.counter <= 0) { // no more potential recipients; discard the data
synchronized (rawDataInfos) {
rawDataInfos.remove(rawDataID);
}
}
}
}
}
/** The thread responsible for waiting for requests for raw data */
private class RawDataServer extends Thread {
/** Server socket used to wait for requests for raw data */
private ServerSocket servSocket;
/** Constructor
* @throws IOException thrown if an I/O errors occurs when creating the server socket
*/
public RawDataServer() throws IOException {
super("RawDataServer");
servSocket = new ServerSocket (rawDataPort);
start();
}
/** @see java.lang.Thread#start() */
@Override
public void start () {
this.setDaemon(true);
super.start();
}
/** Waits for requests for raw data
* @see java.lang.Thread#run()
*/
public void run () {
while (true) {
// Wait for a request and spawn a new RawDataSender
try {
new RawDataSender (servSocket.accept());
} catch (IOException e) { // the socket server was closed
return;
}
}
}
}
/** The thread responsible for waiting for requests for raw data */
private RawDataServer rawDataServer;
/** The QueueOutputPipeTCP's thread */
private Thread myThread;
/** The name of this QueueOutputPipeTCP's thread */
private static String myThreadName = "QueueOutputPipeTCP";
/** Initializes the output pipe
* @param output output stream to which outgoing messages should be written
* @param address IP address of the recipient (only used by QueueOutputPipeTCP#toDOT())
* @param port port number of the recipient (only used by QueueOutputPipeTCP#toDOT())
* @param rawDataIP IP address to which recipients should connect to request raw data
* @param rawDataPort port number on which the pipe should wait for requests for raw data
*/
private void init (ObjectOutputStream output, String address, int port, String rawDataIP, int rawDataPort) {
this.output = output;
if (address.equals("localhost")) {
this.name = "TCPpipe_port" + port;
} else {
this.name = "TCTpipe_IP" + address + "_port" + port;
}
this.rawDataPort = rawDataPort;
this.rawDataIP = rawDataIP;
myThread = new Thread(this, myThreadName);
myThread.setDaemon(true);
myThread.start();
}
/** Constructor
* @param address IP address of the recipient
* @param port port number of the recipient
* @param rawDataIP IP address to which recipients should connect to request raw data
* @param rawDataPort port number on which the pipe should wait for requests for raw data
* @throws IOException thrown if an I/O error occurs while setting up the connection
* @throws UnknownHostException thrown if the provided address does not work
*/
QueueOutputPipeTCP(String address, int port, String rawDataIP, int rawDataPort) throws UnknownHostException, IOException {
ObjectOutputStream out = null;
for (int i = 0; ; i++) {
try {
out = new ObjectOutputStream (new Socket (address, port).getOutputStream());
} catch (UnknownHostException e) {
throw e;
} catch (IOException e) {
if (i >= 1000) {
throw e;
} else
continue;
}
break;
}
init(out, address, port, rawDataIP, rawDataPort);
}
/** Constructor
*
* Sets the raw data port to \ port + 1 and the raw data IP to "localhost."
* @param address IP address of the recipient
* @param port port number of the recipient
* @throws IOException thrown if an I/O error occurs while setting up the connection
* @throws UnknownHostException thrown if the provided address does not work
*/
QueueOutputPipeTCP(String address, int port) throws UnknownHostException, IOException {
ObjectOutputStream out = null;
for (int i = 0; ; i++) {
try {
out = new ObjectOutputStream (new Socket (address, port).getOutputStream());
} catch (UnknownHostException e) {
throw e;
} catch (IOException e) {
if (i >= 1000) {
throw e;
} else
continue;
}
break;
}
init(out, address, port, "localhost", port + 1);
}
/** @see frodo2.communication.QueueOutputPipeInterface#pushMessage(frodo2.communication.MessageWrapper) */
public void pushMessage(MessageWrapper msgWrap) {
try {
messages_lock.lock();
messages.add(msgWrap.getMessage());
messageReceived.signal();
} finally {
messages_lock.unlock();
}
}
/** Close all pipes, and tells the thread to stop */
public void close () {
keepGoing = false;
myThread.interrupt();
if (rawDataServer != null) {
try {
rawDataServer.servSocket.close();
try {
rawDataServer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/** Continuously checks if there are messages to be sent and sends them */
public void run () {
while (keepGoing) {
Message msg = null;
try {
messages_lock.lock();
if (messages.isEmpty()) { // wait for notification of new message
// Flush the stream before going to sleep
try {
output.flush();
} catch (IOException e1) {
e1.printStackTrace();
return;
}
// Go to sleep
try {
messageReceived.await();
} catch (InterruptedException e) { // the method close() has been called
return;
}
continue;
} else
msg = messages.removeFirst();
} finally {
if(messages_lock.isHeldByCurrentThread())
messages_lock.unlock();
}
// First check whether this message is of type MessageWithRawData
if (msg instanceof MessageWithRawData) {
MessageWithRawData msgCast = (MessageWithRawData) msg;
// Check whether the raw data still remains to be serialized
if (msgCast.getHandler() == null) {
// Create and start the RawDataServer if it is not already running
if (rawDataServer == null) {
try {
rawDataServer = new RawDataServer ();
} catch (IOException e) {
System.err.println("Unable to create RawDataServer");
e.printStackTrace();
continue;
}
}
// Record the info about these new raw data
try {
rawDataID_lock.lock();
rawDataInfos_lock.lock();
rawDataInfos.put(++rawDataID, new RawDataInfo (msgCast, 0));
// Set up the raw data handler for this message
msgCast.setHandler(new RawDataHandlerTCP (rawDataID, rawDataIP, rawDataPort));
} finally {
rawDataID_lock.unlock();
if(rawDataInfos_lock.isHeldByCurrentThread())
rawDataInfos_lock.unlock();
}
}
/// @todo There is a privacy issue when the raw data is already serialized:
/// the recipients learn the IP address of the sender of the raw data
}
// Now, send the message
try {
output.writeObject(msg.getClass());
msg.writeExternal(output);
} catch (IOException e) {
e.printStackTrace();
return;
}
/// @todo Reset the streams regularly to get rid of references to previously sent objects that prevent garbage collection?
}
// Close the stream
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/** @see frodo2.communication.QueueOutputPipeInterface#toDOT() */
public String toDOT() {
return name;
}
}
| agpl-3.0 |
rpsl4j/rpsl4j-parser | src/main/java/net/ripe/db/whois/common/rpsl/AttributeLexerWrapper.java | 10448 | /*
* Copyright (c) 2015 Benjamin Roberts, Nathan Kelly, Andrew Maxwell
* All rights reserved.
*/
package net.ripe.db.whois.common.rpsl;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import net.ripe.db.whois.common.domain.CIString;
import org.apache.commons.lang3.text.WordUtils;
import org.apache.commons.lang3.tuple.Pair;
/**
* This class provides a wrapper for the {@link AttributeLexer}s and associated parsers generated by the RIPE RPSL package.
* It runs the lexer in order to generate a usable representation, "[(keyword, [values])", of the parsed attribute.
* @author Benjamin George Roberts
*/
public class AttributeLexerWrapper {
private static final String classLocation = "net.ripe.db.whois.common.generated.";
private static Map<String, Map<Integer, String>> stateTableCache = new HashMap<String, Map<Integer, String>>();
private static Pattern statePattern = Pattern.compile("((TKN)|(OP)|(KEYW))_[A-Z0-9]+");
private String attributeType;
private AttributeLexer lexer;
private Map<Integer, String> stateTable;
/**
* Construct the lexer for the provided field
* @param fieldName The name of the attribute/field to instantiate the lexer for. Example: import, filter.
* @throws ClassNotFoundException Thrown if the attribute does not have an assocaited parser & lexer, or if the classes are uninstantiable.
*/
public AttributeLexerWrapper(String fieldName) throws ClassNotFoundException {
attributeType = WordUtils.capitalize(fieldName);
lexer = loadLexerInstance(attributeType);
stateTable = generateStateTable(attributeType);
}
/**
* @see AttributeLexerWrapper#Lexer(String, Reader)
* @param in source of text to parse. Will be wrapped by a reader in {@link AttributeLexerWrapper#Lexer(String, Reader)}
*/
public AttributeLexerWrapper(String fieldName, InputStream in) throws ClassNotFoundException {
}
/**
* Locates and instantiates an AttributeLexer instance from the JVM's classpath
* @param attributeType the attribute to load a lexer for. Example: import, filter
* @param in Reader to instantiate the lexer with
* @return The an instance of the lexer of the provided attributeType
* @throws ClassNotFoundException Thrown if the attribute does not have an associated lexer or if the class is uninstantiable.
*/
private static AttributeLexer loadLexerInstance(String attributeType) throws ClassNotFoundException {
//Attempt to load the lexer class from the classpath. Will throw ClassNotFoundException on fail
String lexerClassName = classLocation + attributeType + "Lexer";
@SuppressWarnings("unchecked")
Class<AttributeLexer> lexerClass = (Class<AttributeLexer>) Class.forName(lexerClassName);
//This section instantiates the lexer, lots of things can go wrong which we throw upstream as a modified ClassNotFoundException
try {
Constructor<AttributeLexer> lexerConstructor = lexerClass.getConstructor(Reader.class);
Reader nullReader = null;
return lexerConstructor.newInstance(nullReader); //Pass null now and give a real input when parse is called
} catch (Exception e) {
throw (new ClassNotFoundException(lexerClass.getName() + " is not a valid AttributeParser", e));
}
}
/**
* Generates a map of state-numbers to state names from the parser of the provided attribute type.
* Successfully generated maps are cached.
* @param attributeType the attribute to load the state table of.
* @return Map of state to name
* @throws ClassNotFoundException Thrown if the attribute does not have an associated parser.
*/
private static Map<Integer, String> generateStateTable(String attributeType) throws ClassNotFoundException {
//Check if we've already cached a state table for this parser
if(stateTableCache.containsKey(attributeType))
return stateTableCache.get(attributeType);
//Attempt to load the parser class from the classpath. Will throw ClassNotFoundException on fail
String parserClassName = classLocation + attributeType + "Parser";
@SuppressWarnings("unchecked")
Class<AttributeLexer> parserClass = (Class<AttributeLexer>) Class.forName(parserClassName);
//Build a new stateTable by finding state variables in the parser class
Map<Integer, String> stateTable = new HashMap<Integer, String>();
for(Field field : parserClass.getDeclaredFields()) {
//State fields have the signature PUBLIC FINAL STATIC short {KEYW}|{OP}|{TKN}_\w.
int modifierMask = Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC;
if(field.getModifiers() == modifierMask
&& field.getType() == short.class
&& statePattern.matcher(field.getName()).matches()) {
//This shouldn't fail as we've already typechecked, but we skip on failure.
try {
stateTable.put(new Integer(field.getShort(null)), field.getName());
} catch (IllegalArgumentException | IllegalAccessException e) {
System.err.println("Failed to extract value for state table: " + field.getName());
e.printStackTrace();
}
}
}
//Cache and return new table
stateTableCache.put(attributeType, stateTable);
return stateTable;
}
/**
* @see AttributeLexerWrapper#parse(Reader)
* @param in source of text to parse. Will be wrapped by a reader in {@link AttributeLexerWrapper#parse(Reader)}
*/
public List<Pair<String, List<String>>> parse(InputStream in) throws IOException {
return parse(new InputStreamReader(in));
}
/**
* Runs the lexer over the input text and builds a more usable representation.
* This representation is structured as a List of {@link Pair}s.
* The left value is the last keyword (or combination of keywords) encountered,
* whilst the right value is a (not null) list of captured tokens and operators.
* If the first item to be encountered is a token (ie ifaddr attributes), the left value
* is the name of the token (ie DNS).
*
* All keywords and operations (and/or/not) are lowercase
*
* Example:
* the string "import: from AS2 accept AS1, 1.2.3.4/5" would be returned as
* "[(from, [AS2]), (accept, [AS1, 1.2.3.4/5])]"
*
*
* @param in Source of the text to parse
* @return representation of the parsed text
* @throws IOException thrown if an error occurs reading the stream
*/
public List<Pair<String, List<String>>> parse(Reader in) throws IOException {
lexer.yyreset(in);
int lexerState = lexer.yylex(); //take initial state
boolean capturingKeyword = false; //concat strings of keywords
String previousKeyWord = null;
List<String> previousTokenList = null;
List<Pair<String, List<String>>> contextMap = new LinkedList<Pair<String, List<String>>>();
while(lexerState > 2 && lexerState != 256) { //256 is parser error code, [-1,2] are parser error (including EOF)
String stateName;
//Some characters return unnamed states, print them as errors and continue
if (!stateTable.containsKey(lexerState)) {
lexerState = lexer.yylex();
continue;
} else {
stateName = stateTable.get(lexerState);
}
//Capture the keywords or store the tokens
if(stateName.startsWith("KEYW_")) {
//Remove KEYW_ from the statename
stateName = stateName.substring(5).toLowerCase();
//Start a new keyword concat if we'ce just come off a token or this is first run
if(!capturingKeyword || previousKeyWord == null) {
previousKeyWord = stateName;
previousTokenList = null;
capturingKeyword = true;
} else {
previousKeyWord += "&" + stateName;
}
lexerState = lexer.yylex();
continue;
} else {
capturingKeyword = false;
//If the first thing we encounter in the attribute is a token, make an entry for it using its state name
if(previousKeyWord == null)
previousKeyWord = stateName.substring(4).toLowerCase(); //remove TKN_
//append the token
if(lexer.yylength() > 0) {
//Add an entry into the contextmap
if(previousTokenList == null) {
previousTokenList = new LinkedList<String>();
contextMap.add(Pair.of(previousKeyWord, previousTokenList));
}
String text = lexer.yytext();
//Skip adding the attribute key (ie import in import: ...)
if(text.toLowerCase().equals(attributeType.toLowerCase())) {
lexerState = lexer.yylex();
continue;
}
//Remove OP_ from operations
if(text.startsWith("OP_"))
text = text.substring(3).toLowerCase();
//Append to token list
previousTokenList.add(text);
}
}
//Advance to next state
lexerState = lexer.yylex();
}
//Remove empty entires from context map
List<Pair<String, List<String>>> emptyEntries = new LinkedList<Pair<String, List<String>>>();
for(Pair<String, List<String>> entry : contextMap) {
if(entry.getRight().size() == 0)
emptyEntries.add(entry);
}
contextMap.removeAll(emptyEntries);
//Return map
return contextMap;
}
/**
* Parse an {@link RpslAttribute} object
* If the lexer class is not found for the provided attribute, a simple token list is built
* from the attribute ie: [(Attr-Type, [cleanValues...])]
* @see AttributeLexerWrapper#parse(Reader)
* @return representation of the parsed text or empty list.
*/
public static List<Pair<String, List<String>>> parse(RpslAttribute attr) throws ClassNotFoundException{
try {
AttributeLexerWrapper lexer = new AttributeLexerWrapper(attr.getType().getName());
return lexer.parse(new StringReader(attr.toString()));
} catch (IOException | ClassNotFoundException e) {
//System.err.println("IO error parsing attribute: " + attr.toString());
if(attr.getCleanValues().size() > 1) {
//Case for multiple values
List<String> values = new LinkedList<String>();
for(CIString val : attr.getCleanValues())
values.add(val.toString());
return Arrays.asList(Pair.of(attr.getType().getName(), values));
} else if (attr.getCleanValues().size() == 1) {
//One value
return Arrays.asList(Pair.of(attr.getType().getName(), Arrays.asList(attr.getCleanValue().toString())));
} else {
//No value
return Arrays.asList();
}
}
}
}
| agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/operator/generator/Dot.java | 1338 | /**
* Copyright (C) 2001-2017 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.generator;
/**
* Helper class containing all information about a dot.
*
* @author Ingo Mierswa
*/
public class Dot {
double x;
double y;
double radius;
Dot(double x, double y, double radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
public boolean contains(double x, double y) {
double xDiff = this.x - x;
double yDiff = this.y - y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff) < this.radius;
}
}
| agpl-3.0 |
DemandCube/NeverwinterDP | registry/core/src/main/java/com/neverwinterdp/registry/task/TaskExecutorDescriptor.java | 1260 | package com.neverwinterdp.registry.task;
import java.util.ArrayList;
import java.util.List;
public class TaskExecutorDescriptor {
static public enum TasExecutorStatus {
INIT, ACTIVE, IDLE, TERMINATED, TERMINATED_WITH_INTERRUPT, TERMINATED_WITH_ERROR
}
private String id;
private String workerRef;
private TasExecutorStatus status = TasExecutorStatus.INIT;
private List<String> assignedTaskIds = new ArrayList<>();
public TaskExecutorDescriptor() {}
public TaskExecutorDescriptor(String id, String workerRef) {
this.id = id;
this.workerRef = workerRef;
}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getWorkerRef() { return workerRef; }
public void setWorkerRef(String workerRef) { this.workerRef = workerRef; }
public TasExecutorStatus getStatus() { return status; }
public void setStatus(TasExecutorStatus status) { this.status = status; }
public List<String> getAssignedTaskIds() { return assignedTaskIds; }
public void setAssignedTaskIds(List<String> assignedTaskIds) { this.assignedTaskIds = assignedTaskIds; }
public void addAssignedTask(String taskId) {
assignedTaskIds.add(taskId);
}
}
| agpl-3.0 |
enviroCar/enviroCar-server | rest/src/main/java/org/envirocar/server/rest/resources/ResetPasswordResource.java | 2315 | /*
* Copyright (C) 2013-2022 The enviroCar project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.envirocar.server.rest.resources;
import org.envirocar.server.core.exception.BadRequestException;
import org.envirocar.server.rest.MediaTypes;
import org.envirocar.server.rest.Schemas;
import org.envirocar.server.rest.entity.ResetPasswordRequest;
import org.envirocar.server.rest.schema.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.core.Response;
public class ResetPasswordResource extends AbstractResource {
private static final Logger LOG = LoggerFactory.getLogger(ResetPasswordResource.class);
@POST
@Schema(request = Schemas.PASSWORD_RESET_REQUEST)
@Consumes({MediaTypes.JSON})
public Response get(ResetPasswordRequest resetPassword) throws BadRequestException {
checkRights(getRights().canAccessPasswordReset());
getUserService().requestPasswordReset(resetPassword.getUser());
LOG.info("Successfully processed password reset request for user {}", resetPassword.getUser());
return Response.noContent().build();
}
@PUT
@Schema(request = Schemas.PASSWORD_RESET_VERIFICATION)
@Consumes({MediaTypes.JSON})
public Response resetPassword(ResetPasswordRequest resetPassword) throws BadRequestException {
checkRights(getRights().canAccessPasswordReset());
getUserService().resetPassword(resetPassword.getUser(), resetPassword.getCode());
LOG.info("Password reset for user {}", resetPassword.getUser());
return Response.noContent().build();
}
}
| agpl-3.0 |
giustini/vitakey | src/main/java/com/giustini/vitakey/ui/LoginLayoutController.java | 633 | package com.giustini.vitakey.ui;
import javafx.fxml.FXML;
import org.controlsfx.dialog.Dialogs;
public class LoginLayoutController {
@FXML
private void handleAbout() {
Dialogs.create()
.title("Vitakey")
.masthead("Acerca de...")
.message("Vitakey, versión 1.0 beta\n"
+ "Copyright \u00a9 2017 Giustini Apps. Todos los derechos reservados"
+ "\nAutor: Andrés Giustini (http://github.com/giustini)")
.showInformation();
}
@FXML
private void handleExit() {
System.exit(0);
}
}
| agpl-3.0 |
NicolasEYSSERIC/Silverpeas-Core | lib-core/src/main/java/com/stratelia/silverpeas/notificationManager/model/SendedNotificationInterfaceImpl.java | 5351 | /**
* Copyright (C) 2000 - 2012 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stratelia.silverpeas.notificationManager.model;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.silverpeas.SilverpeasServiceProvider;
import com.stratelia.silverpeas.notificationManager.NotificationManagerException;
import com.stratelia.silverpeas.notificationManager.NotificationMetaData;
import com.stratelia.silverpeas.notificationManager.UserRecipient;
import com.stratelia.webactiv.util.DBUtil;
import com.stratelia.webactiv.util.JNDINames;
import com.stratelia.webactiv.util.exception.SilverpeasException;
import com.stratelia.webactiv.util.exception.SilverpeasRuntimeException;
/**
* Interface declaration
* @author
*/
public class SendedNotificationInterfaceImpl implements SendedNotificationInterface {
public SendedNotificationInterfaceImpl() {
}
@Override
public void saveNotifUser(NotificationMetaData metaData, Set<UserRecipient> usersSet)
throws NotificationManagerException {
Connection con = initCon();
try {
List<String> users = new ArrayList<String>();
for (UserRecipient user : usersSet) {
users.add(user.getUserId());
}
String language =
SilverpeasServiceProvider.getPersonalizationService()
.getUserSettings(metaData.getSender()).getLanguage();
SendedNotificationDetail notif =
new SendedNotificationDetail(Integer.parseInt(metaData.getSender()), metaData.
getMessageType(), metaData.getDate(), metaData.getTitle(language), metaData.getSource(),
metaData.getLink(), metaData.getSessionId(), metaData.getComponentId(), metaData.
getContent(language));
notif.setUsers(users);
int id = SendedNotificationDAO.saveNotifUser(con, notif);
notif.setNotifId(id);
} catch (Exception e) {
throw new NotificationManagerException("NotificationInterface.saveNotifUser()",
SilverpeasRuntimeException.ERROR, "root.MSG_GET_NOTIFICATION", e);
} finally {
DBUtil.close(con);
}
}
@Override
public List<SendedNotificationDetail> getAllNotifByUser(String userId)
throws NotificationManagerException {
Connection con = initCon();
try {
return SendedNotificationDAO.getAllNotifByUser(con, userId);
} catch (Exception e) {
throw new NotificationManagerException("NotificationInterface.getAllNotifByUser()",
SilverpeasRuntimeException.ERROR, "root.MSG_GET_NOTIFICATION", e);
} finally {
DBUtil.close(con);
}
}
@Override
public SendedNotificationDetail getNotification(int notifId) throws NotificationManagerException {
Connection con = initCon();
try {
return SendedNotificationDAO.getNotif(con, notifId);
} catch (Exception e) {
throw new NotificationManagerException("NotificationInterface.getNotification()",
SilverpeasRuntimeException.ERROR, "root.MSG_GET_NOTIFICATION", e);
} finally {
DBUtil.close(con);
}
}
@Override
public void deleteNotif(int notifId) throws NotificationManagerException {
Connection con = initCon();
try {
SendedNotificationDAO.deleteNotif(con, notifId);
} catch (Exception e) {
throw new NotificationManagerException("NotificationInterface.deleteNotif()",
SilverpeasRuntimeException.ERROR, "root.MSG_GET_NOTIFICATION", e);
} finally {
DBUtil.close(con);
}
}
@Override
public void deleteNotifByUser(String userId) throws NotificationManagerException {
Connection con = initCon();
try {
SendedNotificationDAO.deleteNotifByUser(con, userId);
} catch (Exception e) {
throw new NotificationManagerException("NotificationInterface.deleteNotifByUser()",
SilverpeasRuntimeException.ERROR, "root.MSG_GET_NOTIFICATION", e);
} finally {
DBUtil.close(con);
}
}
private Connection initCon() throws NotificationManagerException {
try {
return DBUtil.makeConnection(JNDINames.DATABASE_DATASOURCE);
} catch (Exception e) {
throw new NotificationManagerException("NotificationInterfaceImpl.initCon()",
SilverpeasException.ERROR, "root.EX_CONNECTION_OPEN_FAILED", e);
}
}
} | agpl-3.0 |
VietOpenCPS/opencps-v2 | modules/backend-api-rest/src/main/java/backend/api/rest/application/BackendAPIRestApplication.java | 16528 |
package backend.api.rest.application;
import static javax.ws.rs.core.HttpHeaders.AUTHORIZATION;
import static javax.ws.rs.core.Response.Status.UNAUTHORIZED;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.Company;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.search.Sort;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.Validator;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.HttpURLConnection;
import java.security.Key;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.UriInfo;
import org.opencps.api.constants.ConstantUtils;
import org.opencps.api.controller.impl.*;
import org.opencps.api.controller.util.MessageUtil;
import org.opencps.api.filter.KeyGenerator;
import org.opencps.api.filter.OpenCPSKeyGenerator;
import org.opencps.auth.api.BackendAuth;
import org.opencps.auth.api.BackendAuthImpl;
import org.opencps.auth.api.exception.UnauthenticationException;
import org.opencps.background.model.CountEntity;
import org.opencps.communication.model.Notificationtemplate;
import org.opencps.communication.service.NotificationtemplateLocalServiceUtil;
import org.opencps.dossiermgt.action.DossierActions;
import org.opencps.dossiermgt.action.DossierTemplateActions;
import org.opencps.dossiermgt.action.impl.DossierActionsImpl;
import org.opencps.dossiermgt.action.impl.DossierTemplateActionsImpl;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.model.impl.DossierStatisticImpl;
import org.opencps.dossiermgt.service.DossierLocalServiceUtil;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import uk.org.okapibarcode.backend.Code128;
import uk.org.okapibarcode.backend.HumanReadableLocation;
import uk.org.okapibarcode.backend.QrCode;
import uk.org.okapibarcode.backend.Symbol;
import uk.org.okapibarcode.output.Java2DRenderer;
@Component(property = {
JaxrsWhiteboardConstants.JAX_RS_APPLICATION_BASE + "=/secure/rest/v2",
JaxrsWhiteboardConstants.JAX_RS_NAME + "=OpenCPS.restv2",
"javax.portlet.resource-bundle=content.Language"
}, service = Application.class)
public class BackendAPIRestApplication extends Application {
private static final Log _log = LogFactoryUtil.getLog(BackendAPIRestApplication.class);
public Set<Object> getSingletons() {
Set<Object> singletons = new HashSet<>();
// add REST endpoints (resources)
singletons.add(new ApplicantManagementImpl());
singletons.add(new ServiceInfoManagementImpl());
singletons.add(new ServiceConfigManagementImpl());
singletons.add(new DossierTemplateManagementImpl());
singletons.add(new ServiceProcessManagementImpl());
singletons.add(new PaymentConfigManagementImpl());
singletons.add(new PaymentFileManagementImpl());
singletons.add(new DossierManagementImpl());
singletons.add(new DossierFileManagementImpl());
singletons.add(new DossierActionManagementImpl());
singletons.add(new DossierLogManagementImpl());
singletons.add(new ServerConfigManagementImpl());
singletons.add(new DataManagementImpl());
singletons.add(new HolidayManagementImpl());
singletons.add(new WorkTimeManagementImpl());
singletons.add(new NotificationTemplateImpl());
singletons.add(new NotificationTypeManagementImpl());
singletons.add(new NotificationQueueManagementImpl());
singletons.add(new OfficeSiteManagementImpl());
singletons.add(new WorkingUnitManagementImpl());
singletons.add(new JobposManagementImpl());
singletons.add(new UserManagementImpl());
singletons.add(new EmployeeManagementImpl());
singletons.add(new DossierStatisticImpl());
singletons.add(new FileAttachManagementImpl());
singletons.add(new StatisticManagementImpl());
singletons.add(new DeliverableTypesManagementImpl());
//
singletons.add(new DeliverablesManagementImpl());
singletons.add(new DeliverablesLogManagementImpl());
//
singletons.add(new RegistrationTemplatesManagementImpl());
singletons.add(new CommentManagementImpl());
singletons.add(new RegistrationManagementImpl());
singletons.add(new RegistrationFormManagementImpl());
singletons.add(new RegistrationLogManagementImpl());
singletons.add(new ProcessPluginManagementImpl());
singletons.add(new SignatureManagementImpl());
singletons.add(new UserInfoLogManagementImpl());
//
singletons.add(new CertNumberManagementImpl());
singletons.add(new OneGateControllerImpl());
singletons.add(new DossierDocumentManagementImpl());
singletons.add(new DossierSyncManagementImpl());
singletons.add(new SystemManagementImpl());
singletons.add(new VotingManagementImpl());
singletons.add(new DossierActionUserManagementImpl());
singletons.add(new DefaultSignatureManagementImpl());
singletons.add(new MenuRoleManagementImpl());
singletons.add(new SMSManagementImpl());
singletons.add(new BackupDataManagementImpl());
singletons.add(new NotificationManagementImpl());
singletons.add(new FaqManagementImpl());
singletons.add(new CacheTestManagementImpl());
singletons.add(new ImportDataManagementImpl());
singletons.add(new EFormManagementImpl());
singletons.add(new BookingManagementImpl());
singletons.add(new AdminConfigManagementImpl());
singletons.add(new ProxyManagementImpl());
singletons.add(new MenuConfigManagementImpl());
singletons.add(new JasperUtilsManagermentImpl());
singletons.add(new DVCQGSSOManagementImpl());
singletons.add(new DVCQGIManagementImpl());
singletons.add(new ConfigCounterManagementImpl());
singletons.add(new VGCAManagementImpl());
//Test send mail
singletons.add(new MailTestManagementImpl());
singletons.add(new NotarizationManagementImpl());
singletons.add(new ReportRoleManagementImpl());
singletons.add(new OAIManagementImpl());
singletons.add(new NewsBroadManagementImpl());
//Applicant Data
singletons.add(new ApplicantDataManagementImpl());
singletons.add(new AccessStatisticsManagementImpl());
singletons.add(new LGSPIntegrationManagementImpl());
singletons.add(new FileItemManagementImpl());
singletons.add(new SaveFieldPickManagementImpl());
singletons.add(new VNPostManagementImpl());
singletons.add(this);
// add service provider
singletons.add(_serviceContextProvider);
singletons.add(_companyContextProvider);
singletons.add(_localeContextProvider);
singletons.add(_userContextProvider);
return singletons;
}
@GET
@Path("chao")
@Produces("text/plain")
public String working() {
return "It works!";
}
@GET
@Path("ping")
@Produces("text/plain")
public String ping() {
return "ok";
}
@GET
@Path("/barcode")
@Consumes({
MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON
})
@Produces({
MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON
})
public Response getBarcode(
@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@QueryParam("value") String value, @QueryParam("font") String font,
@QueryParam("location") String location) {
try {
Code128 barcode = new Code128();
barcode.setFontName(ConstantUtils.MONOSPACED);
barcode.setFontSize(
Validator.isNotNull(font)
? Integer.valueOf(font) : ConstantUtils.DEFAULT_FONT_SIZE);
barcode.setModuleWidth(2);
barcode.setBarHeight(50);
if (Validator.isNotNull(location) && Boolean.valueOf(location)) {
barcode.setHumanReadableLocation(HumanReadableLocation.NONE);
}
else {
barcode.setHumanReadableLocation(HumanReadableLocation.BOTTOM);
}
barcode.setContent(value);
int width = barcode.getWidth();
int height = barcode.getHeight();
BufferedImage image =
new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g2d = image.createGraphics();
Java2DRenderer renderer =
new Java2DRenderer(g2d, 1, Color.WHITE, Color.BLACK);
renderer.render(barcode);
String uuid = UUID.randomUUID().toString();
File destDir = new File(ConstantUtils.BARCODE);
if (!destDir.exists()) {
destDir.mkdir();
}
String barcodeFilename = String.format(MessageUtil.getMessage(ConstantUtils.BARCODE_FILENAME), uuid);
File file = new File(barcodeFilename);
if (!file.exists()) {
file.createNewFile();
}
if (file.exists()) {
ImageIO.write(image, ConstantUtils.PNG, file);
// String fileType = Files.probeContentType(file.toPath());
ResponseBuilder responseBuilder = Response.ok((Object) file);
String fileName = String.format(MessageUtil.getMessage(ConstantUtils.ATTACHMENT_FILENAME), file.getName());
responseBuilder.header(
ConstantUtils.CONTENT_DISPOSITION,
fileName);
responseBuilder.header(HttpHeaders.CONTENT_TYPE, ConstantUtils.MEDIA_TYPE_PNG);
return responseBuilder.build();
}
else {
return Response.status(
HttpURLConnection.HTTP_NO_CONTENT).build();
}
}
catch (Exception e) {
// e.printStackTrace();
_log.debug(e);
return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
}
}
@GET
@Path("/qrcode")
@Consumes({
MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON
})
@Produces({
MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON
})
public Response getQRcode(
@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@QueryParam("value") String value) {
try {
QrCode qrcode = new QrCode();
qrcode.setHumanReadableLocation(HumanReadableLocation.BOTTOM);
qrcode.setDataType(Symbol.DataType.ECI);
qrcode.setContent(value);
int width = qrcode.getWidth();
int height = qrcode.getHeight();
BufferedImage image =
new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g2d = image.createGraphics();
Java2DRenderer renderer =
new Java2DRenderer(g2d, 1, Color.WHITE, Color.BLACK);
renderer.render(qrcode);
String uuid = UUID.randomUUID().toString();
File destDir = new File(ConstantUtils.BARCODE);
if (!destDir.exists()) {
destDir.mkdir();
}
String barCodeFileName = String.format(MessageUtil.getMessage(ConstantUtils.BARCODE_FILENAME), uuid);
File file = new File(barCodeFileName);
if (!file.exists()) {
file.createNewFile();
}
if (file.exists()) {
ImageIO.write(image, ConstantUtils.PNG, file);
// String fileType = Files.probeContentType(file.toPath());
ResponseBuilder responseBuilder = Response.ok((Object) file);
String fileName = String.format(MessageUtil.getMessage(ConstantUtils.ATTACHMENT_FILENAME), file.getName());
responseBuilder.header(
ConstantUtils.CONTENT_DISPOSITION,
fileName);
responseBuilder.header(HttpHeaders.CONTENT_TYPE, ConstantUtils.MEDIA_TYPE_PNG);
return responseBuilder.build();
}
else {
return Response.status(
HttpURLConnection.HTTP_NO_CONTENT).build();
}
}
catch (Exception e) {
// e.printStackTrace();
_log.debug(e);
return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
}
}
@POST
@Path("/login")
@Consumes({
MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON,
MediaType.APPLICATION_FORM_URLENCODED
})
@Produces({
MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON
})
public Response authenticateUser(
@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext) {
BackendAuth auth = new BackendAuthImpl();
try {
if (!auth.isAuth(serviceContext)) {
throw new UnauthenticationException();
}
// Issue a token for the user
String token = issueToken(user.getEmailAddress());
JSONObject result = JSONFactoryUtil.createJSONObject();
result.put(ConstantUtils.TOKEN, token);
// Return the token on the response
String authorization = String.format(MessageUtil.getMessage(ConstantUtils.HTTP_HEADER_BEARER), token);
return Response.ok().header(
AUTHORIZATION, authorization).entity(
result.toJSONString()).build();
}
catch (Exception e) {
// e.printStackTrace();
_log.debug(e);
return Response.status(UNAUTHORIZED).build();
}
}
private String issueToken(String login) {
KeyGenerator keyGenerator = new OpenCPSKeyGenerator();
Key key = keyGenerator.generateKey();
String jwtToken = Jwts.builder().setSubject(login).setIssuer(
uriInfo.getAbsolutePath().toString()).setIssuedAt(
new Date()).setExpiration(
toDate(LocalDateTime.now().plusMinutes(15L))).signWith(
key, SignatureAlgorithm.HS512).compact();
return jwtToken;
}
private Date toDate(LocalDateTime localDateTime) {
return Date.from(
localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
@GET
@Path("/count/{className}")
@Consumes({
MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON
})
@Produces({
MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON
})
public Response countEntity(
@Context HttpServletRequest request, @Context HttpHeaders header,
@Context Company company, @Context Locale locale, @Context User user,
@Context ServiceContext serviceContext,
@PathParam("className") String className) {
CountEntity result = new CountEntity();
long groupId = GetterUtil.getLong(header.getHeaderString(Field.GROUP_ID));
long countDatabase = 0;
long countLucene = 0;
if (Notificationtemplate.class.getName().equals(className)) {
countDatabase =
NotificationtemplateLocalServiceUtil.countNotificationTemplateByGroupId(
groupId);
LinkedHashMap<String, Object> params =
new LinkedHashMap<String, Object>();
DossierTemplateActions actions = new DossierTemplateActionsImpl();
params.put(Field.GROUP_ID, String.valueOf(groupId));
Sort[] sorts = new Sort[] {};
JSONObject jsonData;
try {
jsonData = actions.getDossierTemplates(
user.getUserId(), serviceContext.getCompanyId(), groupId,
params, sorts, QueryUtil.ALL_POS, QueryUtil.ALL_POS,
serviceContext);
countLucene = jsonData.getInt(ConstantUtils.TOTAL);
}
catch (PortalException e) {
_log.error(e);
}
}
else if (Dossier.class.getName().equals(className)) {
LinkedHashMap<String, Object> params =
new LinkedHashMap<String, Object>();
params.put(Field.GROUP_ID, String.valueOf(groupId));
DossierActions actions = new DossierActionsImpl();
JSONObject jsonData = actions.getDossiers(
user.getUserId(), company.getCompanyId(), groupId, params, null,
-1, -1, serviceContext);
countLucene = jsonData.getLong(ConstantUtils.TOTAL);
countDatabase =
DossierLocalServiceUtil.countDossierByGroup(groupId);
}
result.setDatabase(countDatabase);
result.setLucene(countLucene);
return Response.status(HttpURLConnection.HTTP_OK).entity(result).build();
}
@Context
private UriInfo uriInfo;
@Reference
private CompanyContextProvider _companyContextProvider;
@Reference
private LocaleContextProvider _localeContextProvider;
@Reference
private UserContextProvider _userContextProvider;
@Reference
private ServiceContextProvider _serviceContextProvider;
} | agpl-3.0 |
printedheart/opennars | nars_gui/src/main/java/org/jewelsea/willow/sidebar/BenchPanel.java | 4814 | /*
* Copyright 2013 John Smith
*
* This file is part of Willow.
*
* Willow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Willow 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Willow. If not, see <http://www.gnu.org/licenses/>.
*
* Contact details: http://jewelsea.wordpress.com
*/
package org.jewelsea.willow.sidebar;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import org.jewelsea.willow.browser.WebBrowser;
import org.jewelsea.willow.util.ResourceUtil;
import static org.jewelsea.willow.util.ResourceUtil.getString;
/**
* Sidebar panel for showing Benchmark information
*/
public class BenchPanel extends TitledPane {
public BenchPanel(final WebBrowser chrome) {
// create a layout container for the panel.
VBox benchPanel = new VBox();
benchPanel.setSpacing(5);
benchPanel.setStyle("-fx-padding: 5");
// info on benchmarks.
// format: name, link, icon, (if link and icon are empty, then defines a benchmark category).
final String[][] benchmarkLinks = {
{getString("bench-panel.compliance"), "", ""},
{"HTML 5 Test", "http://www.html5test.com", "HTML5_Badge_32.png"},
{"Acid 3 Test", "http://acid3.acidtests.org/", "acid.png"},
{getString("bench-panel.javascript-performance"), "", ""},
{"WebKit SunSpider", "http://www.webkit.org/perf/sunspider-1.0.2/sunspider-1.0.2/driver.html", "webkit.png"},
{"Google Octane", "http://octane-benchmark.googlecode.com/svn/latest/index.html", "google.png"},
// the kraken may not be unleashed - it hangs on the first ai-star test - maybe later...
// {"Mozilla Kraken", "http://krakenbenchmark.mozilla.org", "firefox_32.png"},
{getString("bench-panel.rendering-performance"), ""},
{"Bubble Mark", "http://bubblemark.com/dhtml.htm", "ball.png"},
{"Guimark", "http://www.craftymind.com/factory/guimark/GUIMark_HTML4.html", "guimark.png"}
};
// create the panel contents and insert it into the panel.
ToggleGroup benchToggleGroup = new ToggleGroup();
boolean firstCategory = true;
for (final String[] link : benchmarkLinks) {
if ("".equals(link[1])) {
// a category of benchmarks.
final Label categoryLabel = new Label(link[0]);
categoryLabel.setStyle("-fx-text-fill: midnightblue; -fx-font-size: 16px;");
VBox.setMargin(categoryLabel, new Insets(firstCategory ? 1 : 8, 0, 0, 0));
benchPanel.getChildren().add(categoryLabel);
firstCategory = false;
} else {
// create a toggle button to navigate to the given benchmark.
final ToggleButton benchLink = new ToggleButton(link[0]);
benchLink.getStyleClass().add("icon-button");
benchLink.setAlignment(Pos.CENTER_LEFT);
benchLink.setContentDisplay(ContentDisplay.LEFT);
benchLink.setOnAction(actionEvent -> chrome.getBrowser().go(link[1]));
benchPanel.getChildren().add(benchLink);
benchLink.setMaxWidth(Double.MAX_VALUE);
VBox.setMargin(benchLink, new Insets(0, 5, 0, 5));
// place the link in a toggle group.
benchLink.setToggleGroup(benchToggleGroup);
// add a graphic to the link.
if (!link[2].isEmpty()) {
final Image image = ResourceUtil.getImage(link[2]);
final ImageView imageView = new ImageView(image);
imageView.setPreserveRatio(true);
imageView.setFitHeight(16);
benchLink.setGraphic(imageView);
}
}
}
// add a spacer to pad out the panel.
final Region spacer = new Region();
spacer.setPrefHeight(5);
benchPanel.getChildren().add(spacer);
setText(getString("bench-panel.title"));
setContent(benchPanel);
setStyle("-fx-font-size: 16px;");
setExpanded(false);
}
}
| agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/operator/SimpleResultObject.java | 1715 | /**
* Copyright (C) 2001-2017 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator;
/**
* A SimpleResulObject is only a helper class for very simple results with only a name and
* descriptive text. May be usefull for intermediate results which should only be displayed but
* actually not used by other operators.
*
* @author Ingo Mierswa, Simon Fischer Exp $
*/
public class SimpleResultObject extends ResultObjectAdapter {
private static final long serialVersionUID = 4406724006750155688L;
private String name;
private String text;
public SimpleResultObject(String name, String text) {
this.name = name;
this.text = text;
}
@Override
public String getName() {
return name;
}
@Override
public String toString() {
return text;
}
public String getExtension() {
return "srs";
}
public String getFileDescription() {
return "simple result";
}
}
| agpl-3.0 |
kamax-io/matrix-appservice-email | src/main/java/io/kamax/matrix/bridge/email/model/email/EmailFetcher.java | 7261 | /*
* matrix-appservice-email - Matrix Bridge to E-mail
* Copyright (C) 2017 Kamax Sarl
*
* https://www.kamax.io/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.kamax.matrix.bridge.email.model.email;
import io.kamax.matrix.bridge.email.config.email.EmailReceiverConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class EmailFetcher implements _EmailFetcher, InitializingBean {
private Logger log = LoggerFactory.getLogger(EmailFetcher.class);
@Autowired
private EmailReceiverConfig recv;
private final int sleepTime = 1000;
private final String keyGroupName = "key";
private Store store;
private Folder folder;
private Thread runner;
private Pattern recvPattern;
private List<_EmailMessageListener> listeners;
@Override
public void afterPropertiesSet() throws Exception {
recvPattern = Pattern.compile(recv.getEmail().replace("+", "\\+").replace("%KEY%", "(?<" + keyGroupName + ">.+?)"));
listeners = new ArrayList<>();
}
private void doConnect() {
try {
if (store != null && store.isConnected() && folder != null && folder.isOpen()) {
return;
}
if (store == null || !store.isConnected()) {
Session session = Session.getDefaultInstance(System.getProperties());
store = session.getStore(recv.getType());
store.connect(recv.getHost(), recv.getPort(), recv.getLogin(), recv.getPassword());
}
if (folder != null && folder.isOpen()) {
folder.close(true);
folder = null;
}
if (folder == null) {
folder = store.getFolder("inbox");
folder.open(Folder.READ_WRITE);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void doDisconnect() {
try {
log.info("Closing folder {}", folder.getName());
folder.close(true);
} catch (Exception e) {
log.warn("Error when closing folder", e);
} finally {
try {
folder = null;
log.info("Closing store {}", store.getURLName());
store.close();
} catch (Exception e) {
log.warn("Error when closing store", e);
} finally {
store = null;
}
}
}
@Override
public void connect() {
log.info("Connect: start");
try {
doConnect();
runner = new Thread(() -> {
log.info("Email receiver thread: start");
while (!Thread.interrupted()) {
try {
doConnect();
while (store.isConnected()) {
Thread.sleep(sleepTime);
Message[] messages = folder.getMessages();
for (Message message : messages) {
if (message.isExpunged() || message.getFlags().contains(Flags.Flag.DELETED)) {
continue;
}
if (message.getFrom().length > 0) {
Address[] recipients = message.getAllRecipients();
for (Address recipient : recipients) {
InternetAddress address = (InternetAddress) recipient;
Matcher m = recvPattern.matcher(address.getAddress());
if (m.matches()) {
String key = m.group(keyGroupName);
log.info("Got email with key {}", key);
for (_EmailMessageListener listener : listeners) {
listener.push(key, message);
}
break;
}
}
} else {
log.info("Received unsupported email: no sender");
}
message.setFlag(Flags.Flag.DELETED, true);
}
folder.expunge();
}
} catch (InterruptedException e) {
log.info("Email receiver thread was interrupted");
} catch (MessagingException e) {
log.error("Error in e-mail backend: {}", e.getMessage());
doDisconnect();
} catch (Throwable t) {
log.error("Error in e-mail fetcher", t);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
log.debug("Got interrupted while waiting with error back-off");
}
}
}
log.info("Email receiver thread: stop");
});
runner.setName("email-receiver-daemon");
runner.setDaemon(true);
runner.start();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
log.info("Connect: end");
}
}
@Override
public void disconnect() {
log.info("Disconnect: start");
log.info("Disconnect: interrupt receiver daemon");
runner.interrupt();
try {
log.info("Disconnect: receiver daemon join: start");
runner.join(sleepTime * 5L);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
log.info("Disconnect: receiver daemon join: end");
}
doDisconnect();
log.info("Disconnect: end");
}
@Override
public void addListener(_EmailMessageListener listener) {
listeners.add(listener);
}
}
| agpl-3.0 |
geomajas/geomajas-project-client-gwt2 | plugin/corewidget/corewidget/src/main/java/org/geomajas/gwt2/plugin/corewidget/client/feature/featureinfo/builder/DoubleAttributeWidgetBuilder.java | 961 | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2015 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.gwt2.plugin.corewidget.client.feature.featureinfo.builder;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import org.geomajas.layer.feature.attribute.DoubleAttribute;
/**
* Widget builder for {@link Double} attributes.
*
* @author Youri Flement
*/
public class DoubleAttributeWidgetBuilder implements AttributeWidgetBuilder<DoubleAttribute> {
@Override
public Widget buildAttributeWidget(DoubleAttribute attribute) {
return new Label(attribute.getValue() + "");
}
}
| agpl-3.0 |
RestComm/jss7 | cap/cap-api/src/main/java/org/restcomm/protocols/ss7/cap/api/service/gprs/CAPServiceGprs.java | 1850 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.protocols.ss7.cap.api.service.gprs;
import org.restcomm.protocols.ss7.cap.api.CAPApplicationContext;
import org.restcomm.protocols.ss7.cap.api.CAPException;
import org.restcomm.protocols.ss7.cap.api.CAPServiceBase;
import org.restcomm.protocols.ss7.sccp.parameter.SccpAddress;
/**
*
* @author sergey vetyutnev
*
*/
public interface CAPServiceGprs extends CAPServiceBase {
CAPDialogGprs createNewDialog(CAPApplicationContext appCntx, SccpAddress origAddress, SccpAddress destAddress, Long localTrId) throws CAPException;
CAPDialogGprs createNewDialog(CAPApplicationContext appCntx, SccpAddress origAddress, SccpAddress destAddress) throws CAPException;
void addCAPServiceListener(CAPServiceGprsListener capServiceListener);
void removeCAPServiceListener(CAPServiceGprsListener capServiceListener);
} | agpl-3.0 |
pianairco/piana-project | piana-sample/src/main/java/ir/piana/dev/sample/rest/HelloWorldRest.java | 2784 | package ir.piana.dev.sample.rest;
import ir.piana.dev.server.response.PianaResponse;
import ir.piana.dev.server.session.Session;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;
/**
* @author Mohammad Rahmati, 5/22/2017 7:25 AM
*/
public class HelloWorldRest {
public static PianaResponse getHelloWorld(
Session session) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new PianaResponse(Response.Status.OK, 1,
"Hello World!",
MediaType.TEXT_PLAIN);
}
public static PianaResponse getHelloWorld(
Session session,
Map<String, List<String>> mapParams) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new PianaResponse(Response.Status.OK, 1,
"Hello World!",
MediaType.TEXT_PLAIN);
}
public static PianaResponse getHelloToName(
Session session,
String name) {
return new PianaResponse(Response.Status.OK, 1,
"Hello ".concat(name),
MediaType.TEXT_PLAIN);
}
public static PianaResponse getHelloToName(
Session session,
Map<String, List<String>> mapParams) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new PianaResponse(Response.Status.OK, 1,
"Hello ".concat(mapParams.get("name").get(0)),
MediaType.TEXT_PLAIN);
}
public static PianaResponse getMessageToNameFamily(
Session session,
String name, String family,
String message) {
return new PianaResponse(Response.Status.OK, 1,
message.concat(" ")
.concat(name)
.concat(" ")
.concat(family),
MediaType.TEXT_PLAIN);
}
public static PianaResponse getMessageToNameFamily(
Session session,
Map<String, List<String>> mapParams) {
MultivaluedMap d = new MultivaluedHashMap(mapParams);
return new PianaResponse(Response.Status.OK, 1,
mapParams.get("message").get(0)
.concat(" ")
.concat(mapParams.get("name").get(0))
.concat(" ")
.concat(mapParams.get("family").get(0)),
MediaType.TEXT_PLAIN);
}
}
| agpl-3.0 |
quikkian-ua-devops/will-financials | kfs-kns/src/main/java/org/kuali/kfs/krad/uif/field/AttributeQuery.java | 15331 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.krad.uif.field;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.krad.uif.component.BindingInfo;
import org.kuali.kfs.krad.uif.component.MethodInvokerConfig;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Holds configuration for executing a dynamic query on an <code>InputField</code> to
* pull data for updating the UI
* <p>
* <p>
* There are two types of query types that can be configured and executed. The first is provided
* completely by the framework using the <code>LookupService</code> and will perform a query
* against the configured dataObjectClassName using the query parameters and return field mapping.
* The second type will invoke a method that will perform the query. This can be configured using the
* queryMethodToCall (if the method is on the view helper service), or using the queryMethodInvoker if
* the method is on another class or object.
* </p>
*/
public class AttributeQuery implements Serializable {
private static final long serialVersionUID = -4569905665441735255L;
private String dataObjectClassName;
private boolean renderNotFoundMessage;
private String returnMessageText;
private String returnMessageStyleClasses;
private Map<String, String> queryFieldMapping;
private Map<String, String> returnFieldMapping;
private Map<String, String> additionalCriteria;
private List<String> sortPropertyNames;
private String queryMethodToCall;
private List<String> queryMethodArgumentFieldList;
private MethodInvokerConfig queryMethodInvokerConfig;
public AttributeQuery() {
renderNotFoundMessage = true;
queryFieldMapping = new HashMap<String, String>();
returnFieldMapping = new HashMap<String, String>();
additionalCriteria = new HashMap<String, String>();
sortPropertyNames = new ArrayList<String>();
queryMethodArgumentFieldList = new ArrayList<String>();
}
/**
* Adjusts the path on the query field mapping from property to match the binding
* path prefix of the given <code>BindingInfo</code>
*
* @param bindingInfo - binding info instance to copy binding path prefix from
*/
public void updateQueryFieldMapping(BindingInfo bindingInfo) {
Map<String, String> adjustedQueryFieldMapping = new HashMap<String, String>();
for (String fromFieldPath : getQueryFieldMapping().keySet()) {
String toField = getQueryFieldMapping().get(fromFieldPath);
String adjustedFromFieldPath = bindingInfo.getPropertyAdjustedBindingPath(fromFieldPath);
adjustedQueryFieldMapping.put(adjustedFromFieldPath, toField);
}
this.queryFieldMapping = adjustedQueryFieldMapping;
}
/**
* Adjusts the path on the return field mapping to property to match the binding
* path prefix of the given <code>BindingInfo</code>
*
* @param bindingInfo - binding info instance to copy binding path prefix from
*/
public void updateReturnFieldMapping(BindingInfo bindingInfo) {
Map<String, String> adjustedReturnFieldMapping = new HashMap<String, String>();
for (String fromFieldPath : getReturnFieldMapping().keySet()) {
String toFieldPath = getReturnFieldMapping().get(fromFieldPath);
String adjustedToFieldPath = bindingInfo.getPropertyAdjustedBindingPath(toFieldPath);
adjustedReturnFieldMapping.put(fromFieldPath, adjustedToFieldPath);
}
this.returnFieldMapping = adjustedReturnFieldMapping;
}
/**
* Adjusts the path on the query method arguments field list to match the binding
* path prefix of the given <code>BindingInfo</code>
*
* @param bindingInfo - binding info instance to copy binding path prefix from
*/
public void updateQueryMethodArgumentFieldList(BindingInfo bindingInfo) {
List<String> adjustedArgumentFieldList = new ArrayList<String>();
for (String argumentFieldPath : getQueryMethodArgumentFieldList()) {
String adjustedFieldPath = bindingInfo.getPropertyAdjustedBindingPath(argumentFieldPath);
adjustedArgumentFieldList.add(adjustedFieldPath);
}
this.queryMethodArgumentFieldList = adjustedArgumentFieldList;
}
/**
* Builds String for passing the queryFieldMapping Map as a Javascript object
* parameter
*
* @return String js parameter string
*/
public String getQueryFieldMappingJsString() {
String queryFieldMappingJs = "{";
for (String queryField : queryFieldMapping.keySet()) {
if (!StringUtils.equals(queryFieldMappingJs, "{")) {
queryFieldMappingJs += ",";
}
queryFieldMappingJs += "\"" + queryField + "\":\"" + queryFieldMapping.get(queryField) + "\"";
}
queryFieldMappingJs += "}";
return queryFieldMappingJs;
}
/**
* Builds String for passing the returnFieldMapping Map as a Javascript object
* parameter
*
* @return String js parameter string
*/
public String getReturnFieldMappingJsString() {
String returnFieldMappingJs = "{";
for (String fromField : returnFieldMapping.keySet()) {
if (!StringUtils.equals(returnFieldMappingJs, "{")) {
returnFieldMappingJs += ",";
}
returnFieldMappingJs += "\"" + returnFieldMapping.get(fromField) + "\":\"" + fromField + "\"";
}
returnFieldMappingJs += "}";
return returnFieldMappingJs;
}
/**
* Builds String for passing the queryMethodArgumentFieldList as a Javascript array
*
* @return String js parameter string
*/
public String getQueryMethodArgumentFieldsJsString() {
String queryMethodArgsJs = "[";
for (String methodArg : queryMethodArgumentFieldList) {
if (!StringUtils.equals(queryMethodArgsJs, "{")) {
queryMethodArgsJs += ",";
}
queryMethodArgsJs += "\"" + methodArg + "\"";
}
queryMethodArgsJs += "]";
return queryMethodArgsJs;
}
/**
* Indicates whether this attribute query is configured to invoke a custom
* method as opposed to running the general object query. If either the query method
* to call is given, or the query method invoker is not null it is assumed the
* intention is to call a custom method
*
* @return boolean true if a custom method is configured, false if not
*/
public boolean hasConfiguredMethod() {
boolean configuredMethod = false;
if (StringUtils.isNotBlank(getQueryMethodToCall())) {
configuredMethod = true;
} else if (getQueryMethodInvokerConfig() != null) {
configuredMethod = true;
}
return configuredMethod;
}
/**
* Class name for the data object the query should be performed against
*
* @return String data object class name
*/
public String getDataObjectClassName() {
return dataObjectClassName;
}
/**
* Setter for the query data object class name
*
* @param dataObjectClassName
*/
public void setDataObjectClassName(String dataObjectClassName) {
this.dataObjectClassName = dataObjectClassName;
}
/**
* Configures the query parameters by mapping fields in the view
* to properties on the data object class for the query
* <p>
* <p>
* Each map entry configures one parameter for the query, where
* the map key is the field name to pull the value from, and the
* map value is the property name on the object the parameter should
* populate.
* </p>
*
* @return Map<String, String> mapping of query parameters
*/
public Map<String, String> getQueryFieldMapping() {
return queryFieldMapping;
}
/**
* Setter for the query parameter mapping
*
* @param queryFieldMapping
*/
public void setQueryFieldMapping(Map<String, String> queryFieldMapping) {
this.queryFieldMapping = queryFieldMapping;
}
/**
* Maps properties from the result object of the query to
* fields in the view
* <p>
* <p>
* Each map entry configures one return mapping, where the map
* key is the field name for the field to populate, and the map
* values is the name of the property on the result object to
* pull the value from
* </p>
*
* @return Map<String, String> return field mapping
*/
public Map<String, String> getReturnFieldMapping() {
return returnFieldMapping;
}
/**
* Setter for the return field mapping
*
* @param returnFieldMapping
*/
public void setReturnFieldMapping(Map<String, String> returnFieldMapping) {
this.returnFieldMapping = returnFieldMapping;
}
/**
* Fixed criteria that will be appended to the dynamic criteria generated
* for the query. Map key gives name of the property the criteria should
* apply to, and the map value is the value (literal) for the criteria. Standard
* lookup wildcards are allowed
*
* @return Map<String, String> field name/value pairs for query criteria
*/
public Map<String, String> getAdditionalCriteria() {
return additionalCriteria;
}
/**
* Setter for the query's additional criteria map
*
* @param additionalCriteria
*/
public void setAdditionalCriteria(Map<String, String> additionalCriteria) {
this.additionalCriteria = additionalCriteria;
}
/**
* List of property names to sort the query results by. The sort
* will be performed on each property in the order they are contained
* within the list. Each property must be a valid property of the
* return query object (the data object in case of the general query)
*
* @return List<String> property names
*/
public List<String> getSortPropertyNames() {
return sortPropertyNames;
}
/**
* Setter for the list of property names to sort results by
*
* @param sortPropertyNames
*/
public void setSortPropertyNames(List<String> sortPropertyNames) {
this.sortPropertyNames = sortPropertyNames;
}
/**
* Indicates whether a message should be added to the query result
* object and displayed when the query return object is null
*
* @return boolean true if not found message should be added, false otherwise
*/
public boolean isRenderNotFoundMessage() {
return renderNotFoundMessage;
}
/**
* Setter for the render not found message indicator
*
* @param renderNotFoundMessage
*/
public void setRenderNotFoundMessage(boolean renderNotFoundMessage) {
this.renderNotFoundMessage = renderNotFoundMessage;
}
/**
* Message text to display along with the query result
*
* @return String literal message text
*/
public String getReturnMessageText() {
return returnMessageText;
}
/**
* Setter for the return message text
*
* @param returnMessageText
*/
public void setReturnMessageText(String returnMessageText) {
this.returnMessageText = returnMessageText;
}
/**
* CSS Style classes that should be applied to the return message.
* Multiple style classes should be delimited by a space
*
* @return String style classes
*/
public String getReturnMessageStyleClasses() {
return returnMessageStyleClasses;
}
/**
* Setter for the return messages style classes
*
* @param returnMessageStyleClasses
*/
public void setReturnMessageStyleClasses(String returnMessageStyleClasses) {
this.returnMessageStyleClasses = returnMessageStyleClasses;
}
/**
* Configures the name of the method that should be invoked to perform
* the query
* <p>
* <p>
* Should contain only the method name (no parameters or return type). If only
* the query method name is configured it is assumed to be on the <code>ViewHelperService</code>
* for the contained view.
* </p>
*
* @return String query method name
*/
public String getQueryMethodToCall() {
return queryMethodToCall;
}
/**
* Setter for the query method name
*
* @param queryMethodToCall
*/
public void setQueryMethodToCall(String queryMethodToCall) {
this.queryMethodToCall = queryMethodToCall;
}
/**
* List of field names that should be passed as arguments to the query method
* <p>
* <p>
* Each entry in the list maps to a method parameter, in the other contained within
* the list. The value for the field within the view will be pulled and passed
* to the query method as an argument
* </p>
*
* @return List<String> query method argument list
*/
public List<String> getQueryMethodArgumentFieldList() {
return queryMethodArgumentFieldList;
}
/**
* Setter for the query method argument list
*
* @param queryMethodArgumentFieldList
*/
public void setQueryMethodArgumentFieldList(List<String> queryMethodArgumentFieldList) {
this.queryMethodArgumentFieldList = queryMethodArgumentFieldList;
}
/**
* Configures the query method target class/object and method name
* <p>
* <p>
* When the query method is not contained on the <code>ViewHelperService</code>, this
* can be configured for declaring the target class/object and method. The target class
* can be set in which case a new instance will be created and the given method invoked.
* Alternatively, the target object instance for the invocation can be given. Or finally
* a static method can be configured
* </p>
*
* @return MethodInvokerConfig query method config
*/
public MethodInvokerConfig getQueryMethodInvokerConfig() {
return queryMethodInvokerConfig;
}
/**
* Setter for the query method config
*
* @param queryMethodInvokerConfig
*/
public void setQueryMethodInvokerConfig(MethodInvokerConfig queryMethodInvokerConfig) {
this.queryMethodInvokerConfig = queryMethodInvokerConfig;
}
}
| agpl-3.0 |