repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
vivekprahlad/frankenstein | src/com/thoughtworks/frankenstein/events/SelectTreeEvent.java | 2800 | package com.thoughtworks.frankenstein.events;
import javax.swing.*;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import com.thoughtworks.frankenstein.playback.MatchStrategy;
/**
* Understands tree selection
*
* @author Vivek Prahlad
*/
public class SelectTreeEvent extends AbstractFrankensteinEvent {
private String treeName;
private String[] path;
public SelectTreeEvent(String treeName, String[] path) {
this.treeName = treeName;
this.path = path;
}
public SelectTreeEvent(String scriptLine) {
this(TreeUtil.name(scriptLine), TreeUtil.path(scriptLine));
}
public String toString() {
return "SelectTreeEvent: Tree: " + treeName + ", Path: " + TreeUtil.pathString(path, ">");
}
public String scriptLine() {
return (underscore(action()) + " \"" + target() + "\"," + TreeUtil.pathString(path, ",", "\""));
}
private void select(JTree tree) {
String[] nodeNames = path;
TreePath path = findRoot(tree, nodeNames[0]);
for (int i = 1; i < nodeNames.length; i++) {
path = findChild(tree, path, nodeNames[i]);
}
tree.setLeadSelectionPath(path);
tree.setSelectionPath(path);
}
private TreePath findRoot(JTree tree, String rootPath) {
Object root = tree.getModel().getRoot();
if (MatchStrategy.matchValues(root.toString(), rootPath)) {
return new TreePath(root);
}
throw new RuntimeException("Root does not exist. Test specified " + rootPath + " but was " + root.toString());
}
private TreePath findChild(JTree tree, TreePath currentPath, String path) {
Object lastPathComponent = currentPath.getLastPathComponent();
TreeModel model = tree.getModel();
int childCount = model.getChildCount(lastPathComponent);
for (int j = 0; j < childCount; j++) {
Object child = model.getChild(lastPathComponent, j);
if (MatchStrategy.matchValues(child.toString(), path)) {
TreePath newPath = currentPath.pathByAddingChild(child);
tree.expandPath(newPath);
return newPath;
}
}
throw new RuntimeException("Root does not exist. Test specified " + path + " but did not exist.");
}
public String target() {
return treeName;
}
public String parameters() {
return TreeUtil.pathString(path, ">");
}
public void run() {
JTree tree = (JTree) finder.findComponent(context, treeName);
select(tree);
}
public String scriptLine(ScriptStrategy scriptStrategy) {
return scriptStrategy.toMethod(action()) + scriptStrategy.enclose(quote(target()) + ", " + scriptStrategy.array(path));
}
}
| apache-2.0 |
hjz/messagebus-java-sdk | test/src/com/messagebus/client/spi/SessionsCreateRequestTest.java | 1277 | /*
* Copyright (c) 2013 Mail Bypass, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
*/
package com.messagebus.client.spi;
import junit.framework.TestCase;
public class SessionsCreateRequestTest extends TestCase {
public void testJsonFormat() throws Exception {
SessionsCreateRequest sessionsCreateRequest = new SessionsCreateRequest("Marketing 101 Session");
String correctJson = "{\"sessionName\":\"Marketing 101 Session\"}";
assertEquals(correctJson, JsonFormatHelper.toWireFormat(sessionsCreateRequest));
sessionsCreateRequest.setSessionName("Marketing 202 Session");
correctJson = "{\"sessionName\":\"Marketing 202 Session\"}";
assertEquals(correctJson, JsonFormatHelper.toWireFormat(sessionsCreateRequest));
}
}
| apache-2.0 |
qq1588518/JRediClients | src/test/java/redis/clients/redisson/BaseTest.java | 2725 | package redis.clients.redisson;
import java.io.IOException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import redis.clients.redisson.api.RedissonClient;
import redis.clients.redisson.config.Config;
public abstract class BaseTest {
protected RedissonClient redisson;
protected static RedissonClient defaultRedisson;
@BeforeClass
public static void beforeClass() throws IOException, InterruptedException {
if (!RedissonRuntimeEnvironment.isTravis) {
RedisRunner.startDefaultRedisServerInstance();
defaultRedisson = createInstance();
}
}
@AfterClass
public static void afterClass() throws IOException, InterruptedException {
if (!RedissonRuntimeEnvironment.isTravis) {
defaultRedisson.shutdown();
RedisRunner.shutDownDefaultRedisServerInstance();
}
}
@Before
public void before() throws IOException, InterruptedException {
if (RedissonRuntimeEnvironment.isTravis) {
RedisRunner.startDefaultRedisServerInstance();
redisson = createInstance();
} else {
if (redisson == null) {
redisson = defaultRedisson;
}
if (flushBetweenTests()) {
redisson.getKeys().flushall();
}
}
}
@After
public void after() throws InterruptedException {
if (RedissonRuntimeEnvironment.isTravis) {
redisson.shutdown();
RedisRunner.shutDownDefaultRedisServerInstance();
}
}
public static Config createConfig() {
// String redisAddress = System.getProperty("redisAddress");
// if (redisAddress == null) {
// redisAddress = "127.0.0.1:6379";
// }
Config config = new Config();
// config.setCodec(new MsgPackJacksonCodec());
// config.useSentinelServers().setMasterName("mymaster").addSentinelAddress("127.0.0.1:26379", "127.0.0.1:26389");
// config.useClusterServers().addNodeAddress("127.0.0.1:7004", "127.0.0.1:7001", "127.0.0.1:7000");
config.useSingleServer()
.setAddress(RedisRunner.getDefaultRedisServerBindAddressAndPort());
// .setPassword("mypass1");
// config.useMasterSlaveConnection()
// .setMasterAddress("127.0.0.1:6379")
// .addSlaveAddress("127.0.0.1:6399")
// .addSlaveAddress("127.0.0.1:6389");
return config;
}
public static RedissonClient createInstance() {
Config config = createConfig();
return Redisson.create(config);
}
protected boolean flushBetweenTests() {
return true;
}
}
| apache-2.0 |
ashvina/heron | heron/healthmgr/tests/java/org/apache/heron/healthmgr/detectors/WaitQueueSkewDetectorTest.java | 3638 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.heron.healthmgr.detectors;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import com.microsoft.dhalion.core.Measurement;
import com.microsoft.dhalion.core.Symptom;
import com.microsoft.dhalion.core.SymptomsTable;
import com.microsoft.dhalion.policy.PoliciesExecutor;
import org.junit.Test;
import org.apache.heron.healthmgr.HealthPolicyConfig;
import static org.apache.heron.healthmgr.detectors.WaitQueueSkewDetector.CONF_SKEW_RATIO;
import static org.apache.heron.healthmgr.sensors.BaseSensor.MetricName.METRIC_WAIT_Q_SIZE;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class WaitQueueSkewDetectorTest {
@Test
public void testConfigAndFilter() {
HealthPolicyConfig config = mock(HealthPolicyConfig.class);
when(config.getConfig(CONF_SKEW_RATIO, 20.0)).thenReturn(15.0);
Measurement measurement1
= new Measurement("bolt", "i1", METRIC_WAIT_Q_SIZE.text(), Instant.ofEpochSecond
(1497892222), 1501);
Measurement measurement2
= new Measurement("bolt", "i2", METRIC_WAIT_Q_SIZE.text(), Instant.ofEpochSecond
(1497892222), 100.0);
Collection<Measurement> metrics = new ArrayList<>();
metrics.add(measurement1);
metrics.add(measurement2);
WaitQueueSkewDetector detector = new WaitQueueSkewDetector(config);
PoliciesExecutor.ExecutionContext context = mock(PoliciesExecutor.ExecutionContext.class);
when(context.checkpoint()).thenReturn(Instant.now());
detector.initialize(context);
Collection<Symptom> symptoms = detector.detect(metrics);
assertEquals(3, symptoms.size());
SymptomsTable symptomsTable = SymptomsTable.of(symptoms);
assertEquals(1, symptomsTable.type("POSITIVE "+ BaseDetector.SymptomType
.SYMPTOM_WAIT_Q_SIZE_SKEW).size());
assertEquals(1, symptomsTable.type("NEGATIVE "+ BaseDetector.SymptomType
.SYMPTOM_WAIT_Q_SIZE_SKEW).size());
assertEquals(1, symptomsTable.type("POSITIVE "+ BaseDetector.SymptomType
.SYMPTOM_WAIT_Q_SIZE_SKEW).assignment("i1").size());
assertEquals(1, symptomsTable.type("NEGATIVE "+ BaseDetector.SymptomType
.SYMPTOM_WAIT_Q_SIZE_SKEW).assignment("i2").size());
measurement1
= new Measurement("bolt", "i1", METRIC_WAIT_Q_SIZE.text(), Instant.ofEpochSecond
(1497892222), 1500);
measurement2
= new Measurement("bolt", "i2", METRIC_WAIT_Q_SIZE.text(), Instant.ofEpochSecond
(1497892222), 110.0);
metrics = new ArrayList<>();
metrics.add(measurement1);
metrics.add(measurement2);
detector = new WaitQueueSkewDetector(config);
detector.initialize(context);
symptoms = detector.detect(metrics);
assertEquals(0, symptoms.size());
}
}
| apache-2.0 |
jmad/aloha | src/next/proj/data/CorrectorConfig.java | 402 | /*
* $Id: CorrectorConfig.java,v 1.1 2008-12-19 13:55:27 kfuchsbe Exp $
*
* $Date: 2008-12-19 13:55:27 $
* $Revision: 1.1 $
* $Author: kfuchsbe $
*
* Copyright CERN, All Rights Reserved.
*/
package cern.accsoft.steering.aloha.proj.data;
import org.simpleframework.xml.Root;
/**
* @author kfuchsbe
*
*/
@Root(name = "corrector")
public class CorrectorConfig extends ElementConfig {
}
| apache-2.0 |
fusesource/hawtdispatch | hawtdispatch/src/main/java/org/fusesource/hawtdispatch/internal/util/StringSupport.java | 1254 | /**
* Copyright (C) 2012 FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.hawtdispatch.internal.util;
import java.util.Arrays;
/**
* Helper class to hold common text/string manipulation methods.
*
* @author chirino
*/
public class StringSupport {
public static String indent(String value, int spaces) {
if( value == null ) {
return null;
}
String indent = fillString(spaces, ' ');
return value.replaceAll("(\\r?\\n)", "$1"+indent);
}
public static String fillString(int count, char character) {
char t[] = new char[count];
Arrays.fill(t, character);
return new String(t);
}
}
| apache-2.0 |
eug48/hapi-fhir | hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/model/Device.java | 120643 | package org.hl7.fhir.r4.model;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Sat, Jul 8, 2017 23:19+1000 for FHIR v3.1.0
import java.util.*;
import org.hl7.fhir.utilities.Utilities;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.api.annotation.SearchParamDefinition;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.ChildOrder;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.Block;
import org.hl7.fhir.instance.model.api.*;
import org.hl7.fhir.exceptions.FHIRException;
/**
* This resource identifies an instance or a type of a manufactured item that is used in the provision of healthcare without being substantially changed through that activity. The device may be a medical or non-medical device. Medical devices include durable (reusable) medical equipment, implantable devices, as well as disposable equipment used for diagnostic, treatment, and research for healthcare and public health. Non-medical devices may include items such as a machine, cellphone, computer, application, etc.
*/
@ResourceDef(name="Device", profile="http://hl7.org/fhir/Profile/Device")
public class Device extends DomainResource {
public enum UDIEntryType {
/**
* A Barcode scanner captured the data from the device label
*/
BARCODE,
/**
* An RFID chip reader captured the data from the device label
*/
RFID,
/**
* The data was read from the label by a person and manually entered. (e.g. via a keyboard)
*/
MANUAL,
/**
* The data originated from a patient's implant card and read by an operator.
*/
CARD,
/**
* The data originated from a patient source and not directly scanned or read from a label or card.
*/
SELFREPORTED,
/**
* The method of data capture has not been determined
*/
UNKNOWN,
/**
* added to help the parsers with the generic types
*/
NULL;
public static UDIEntryType fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("barcode".equals(codeString))
return BARCODE;
if ("rfid".equals(codeString))
return RFID;
if ("manual".equals(codeString))
return MANUAL;
if ("card".equals(codeString))
return CARD;
if ("self-reported".equals(codeString))
return SELFREPORTED;
if ("unknown".equals(codeString))
return UNKNOWN;
if (Configuration.isAcceptInvalidEnums())
return null;
else
throw new FHIRException("Unknown UDIEntryType code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case BARCODE: return "barcode";
case RFID: return "rfid";
case MANUAL: return "manual";
case CARD: return "card";
case SELFREPORTED: return "self-reported";
case UNKNOWN: return "unknown";
default: return "?";
}
}
public String getSystem() {
switch (this) {
case BARCODE: return "http://hl7.org/fhir/udi-entry-type";
case RFID: return "http://hl7.org/fhir/udi-entry-type";
case MANUAL: return "http://hl7.org/fhir/udi-entry-type";
case CARD: return "http://hl7.org/fhir/udi-entry-type";
case SELFREPORTED: return "http://hl7.org/fhir/udi-entry-type";
case UNKNOWN: return "http://hl7.org/fhir/udi-entry-type";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case BARCODE: return "A Barcode scanner captured the data from the device label";
case RFID: return "An RFID chip reader captured the data from the device label";
case MANUAL: return "The data was read from the label by a person and manually entered. (e.g. via a keyboard)";
case CARD: return "The data originated from a patient's implant card and read by an operator.";
case SELFREPORTED: return "The data originated from a patient source and not directly scanned or read from a label or card.";
case UNKNOWN: return "The method of data capture has not been determined";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case BARCODE: return "BarCode";
case RFID: return "RFID";
case MANUAL: return "Manual";
case CARD: return "Card";
case SELFREPORTED: return "Self Reported";
case UNKNOWN: return "Unknown";
default: return "?";
}
}
}
public static class UDIEntryTypeEnumFactory implements EnumFactory<UDIEntryType> {
public UDIEntryType fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("barcode".equals(codeString))
return UDIEntryType.BARCODE;
if ("rfid".equals(codeString))
return UDIEntryType.RFID;
if ("manual".equals(codeString))
return UDIEntryType.MANUAL;
if ("card".equals(codeString))
return UDIEntryType.CARD;
if ("self-reported".equals(codeString))
return UDIEntryType.SELFREPORTED;
if ("unknown".equals(codeString))
return UDIEntryType.UNKNOWN;
throw new IllegalArgumentException("Unknown UDIEntryType code '"+codeString+"'");
}
public Enumeration<UDIEntryType> fromType(Base code) throws FHIRException {
if (code == null)
return null;
if (code.isEmpty())
return new Enumeration<UDIEntryType>(this);
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("barcode".equals(codeString))
return new Enumeration<UDIEntryType>(this, UDIEntryType.BARCODE);
if ("rfid".equals(codeString))
return new Enumeration<UDIEntryType>(this, UDIEntryType.RFID);
if ("manual".equals(codeString))
return new Enumeration<UDIEntryType>(this, UDIEntryType.MANUAL);
if ("card".equals(codeString))
return new Enumeration<UDIEntryType>(this, UDIEntryType.CARD);
if ("self-reported".equals(codeString))
return new Enumeration<UDIEntryType>(this, UDIEntryType.SELFREPORTED);
if ("unknown".equals(codeString))
return new Enumeration<UDIEntryType>(this, UDIEntryType.UNKNOWN);
throw new FHIRException("Unknown UDIEntryType code '"+codeString+"'");
}
public String toCode(UDIEntryType code) {
if (code == UDIEntryType.BARCODE)
return "barcode";
if (code == UDIEntryType.RFID)
return "rfid";
if (code == UDIEntryType.MANUAL)
return "manual";
if (code == UDIEntryType.CARD)
return "card";
if (code == UDIEntryType.SELFREPORTED)
return "self-reported";
if (code == UDIEntryType.UNKNOWN)
return "unknown";
return "?";
}
public String toSystem(UDIEntryType code) {
return code.getSystem();
}
}
public enum FHIRDeviceStatus {
/**
* The Device is available for use. Note: This means for *implanted devices* the device is implanted in the patient.
*/
ACTIVE,
/**
* The Device is no longer available for use (e.g. lost, expired, damaged). Note: This means for *implanted devices* the device has been removed from the patient.
*/
INACTIVE,
/**
* The Device was entered in error and voided.
*/
ENTEREDINERROR,
/**
* The status of the device has not been determined.
*/
UNKNOWN,
/**
* added to help the parsers with the generic types
*/
NULL;
public static FHIRDeviceStatus fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("active".equals(codeString))
return ACTIVE;
if ("inactive".equals(codeString))
return INACTIVE;
if ("entered-in-error".equals(codeString))
return ENTEREDINERROR;
if ("unknown".equals(codeString))
return UNKNOWN;
if (Configuration.isAcceptInvalidEnums())
return null;
else
throw new FHIRException("Unknown FHIRDeviceStatus code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case ACTIVE: return "active";
case INACTIVE: return "inactive";
case ENTEREDINERROR: return "entered-in-error";
case UNKNOWN: return "unknown";
default: return "?";
}
}
public String getSystem() {
switch (this) {
case ACTIVE: return "http://hl7.org/fhir/device-status";
case INACTIVE: return "http://hl7.org/fhir/device-status";
case ENTEREDINERROR: return "http://hl7.org/fhir/device-status";
case UNKNOWN: return "http://hl7.org/fhir/device-status";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case ACTIVE: return "The Device is available for use. Note: This means for *implanted devices* the device is implanted in the patient.";
case INACTIVE: return "The Device is no longer available for use (e.g. lost, expired, damaged). Note: This means for *implanted devices* the device has been removed from the patient.";
case ENTEREDINERROR: return "The Device was entered in error and voided.";
case UNKNOWN: return "The status of the device has not been determined.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case ACTIVE: return "Active";
case INACTIVE: return "Inactive";
case ENTEREDINERROR: return "Entered in Error";
case UNKNOWN: return "Unknown";
default: return "?";
}
}
}
public static class FHIRDeviceStatusEnumFactory implements EnumFactory<FHIRDeviceStatus> {
public FHIRDeviceStatus fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("active".equals(codeString))
return FHIRDeviceStatus.ACTIVE;
if ("inactive".equals(codeString))
return FHIRDeviceStatus.INACTIVE;
if ("entered-in-error".equals(codeString))
return FHIRDeviceStatus.ENTEREDINERROR;
if ("unknown".equals(codeString))
return FHIRDeviceStatus.UNKNOWN;
throw new IllegalArgumentException("Unknown FHIRDeviceStatus code '"+codeString+"'");
}
public Enumeration<FHIRDeviceStatus> fromType(Base code) throws FHIRException {
if (code == null)
return null;
if (code.isEmpty())
return new Enumeration<FHIRDeviceStatus>(this);
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("active".equals(codeString))
return new Enumeration<FHIRDeviceStatus>(this, FHIRDeviceStatus.ACTIVE);
if ("inactive".equals(codeString))
return new Enumeration<FHIRDeviceStatus>(this, FHIRDeviceStatus.INACTIVE);
if ("entered-in-error".equals(codeString))
return new Enumeration<FHIRDeviceStatus>(this, FHIRDeviceStatus.ENTEREDINERROR);
if ("unknown".equals(codeString))
return new Enumeration<FHIRDeviceStatus>(this, FHIRDeviceStatus.UNKNOWN);
throw new FHIRException("Unknown FHIRDeviceStatus code '"+codeString+"'");
}
public String toCode(FHIRDeviceStatus code) {
if (code == FHIRDeviceStatus.ACTIVE)
return "active";
if (code == FHIRDeviceStatus.INACTIVE)
return "inactive";
if (code == FHIRDeviceStatus.ENTEREDINERROR)
return "entered-in-error";
if (code == FHIRDeviceStatus.UNKNOWN)
return "unknown";
return "?";
}
public String toSystem(FHIRDeviceStatus code) {
return code.getSystem();
}
}
@Block()
public static class DeviceUdiComponent extends BackboneElement implements IBaseBackboneElement {
/**
* The device identifier (DI) is a mandatory, fixed portion of a UDI that identifies the labeler and the specific version or model of a device.
*/
@Child(name = "deviceIdentifier", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Mandatory fixed portion of UDI", formalDefinition="The device identifier (DI) is a mandatory, fixed portion of a UDI that identifies the labeler and the specific version or model of a device." )
protected StringType deviceIdentifier;
/**
* Name of device as used in labeling or catalog.
*/
@Child(name = "name", type = {StringType.class}, order=2, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Device Name as appears on UDI label", formalDefinition="Name of device as used in labeling or catalog." )
protected StringType name;
/**
* The identity of the authoritative source for UDI generation within a jurisdiction. All UDIs are globally unique within a single namespace. with the appropriate repository uri as the system. For example, UDIs of devices managed in the U.S. by the FDA, the value is http://hl7.org/fhir/NamingSystem/fda-udi.
*/
@Child(name = "jurisdiction", type = {UriType.class}, order=3, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Regional UDI authority", formalDefinition="The identity of the authoritative source for UDI generation within a jurisdiction. All UDIs are globally unique within a single namespace. with the appropriate repository uri as the system. For example, UDIs of devices managed in the U.S. by the FDA, the value is http://hl7.org/fhir/NamingSystem/fda-udi." )
protected UriType jurisdiction;
/**
* The full UDI carrier as the human readable form (HRF) representation of the barcode string as printed on the packaging of the device.
*/
@Child(name = "carrierHRF", type = {StringType.class}, order=4, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="UDI Human Readable Barcode String", formalDefinition="The full UDI carrier as the human readable form (HRF) representation of the barcode string as printed on the packaging of the device." )
protected StringType carrierHRF;
/**
* The full UDI carrier of the Automatic Identification and Data Capture (AIDC) technology representation of the barcode string as printed on the packaging of the device - E.g a barcode or RFID. Because of limitations on character sets in XML and the need to round-trip JSON data through XML, AIDC Formats *SHALL* be base64 encoded.
*/
@Child(name = "carrierAIDC", type = {Base64BinaryType.class}, order=5, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="UDI Machine Readable Barcode String", formalDefinition="The full UDI carrier of the Automatic Identification and Data Capture (AIDC) technology representation of the barcode string as printed on the packaging of the device - E.g a barcode or RFID. Because of limitations on character sets in XML and the need to round-trip JSON data through XML, AIDC Formats *SHALL* be base64 encoded." )
protected Base64BinaryType carrierAIDC;
/**
* Organization that is charged with issuing UDIs for devices. For example, the US FDA issuers include :
1) GS1:
http://hl7.org/fhir/NamingSystem/gs1-di,
2) HIBCC:
http://hl7.org/fhir/NamingSystem/hibcc-dI,
3) ICCBBA for blood containers:
http://hl7.org/fhir/NamingSystem/iccbba-blood-di,
4) ICCBA for other devices:
http://hl7.org/fhir/NamingSystem/iccbba-other-di.
*/
@Child(name = "issuer", type = {UriType.class}, order=6, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="UDI Issuing Organization", formalDefinition="Organization that is charged with issuing UDIs for devices. For example, the US FDA issuers include :\n1) GS1: \nhttp://hl7.org/fhir/NamingSystem/gs1-di, \n2) HIBCC:\nhttp://hl7.org/fhir/NamingSystem/hibcc-dI, \n3) ICCBBA for blood containers:\nhttp://hl7.org/fhir/NamingSystem/iccbba-blood-di, \n4) ICCBA for other devices:\nhttp://hl7.org/fhir/NamingSystem/iccbba-other-di." )
protected UriType issuer;
/**
* A coded entry to indicate how the data was entered.
*/
@Child(name = "entryType", type = {CodeType.class}, order=7, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="barcode | rfid | manual +", formalDefinition="A coded entry to indicate how the data was entered." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/udi-entry-type")
protected Enumeration<UDIEntryType> entryType;
private static final long serialVersionUID = -1105798343L;
/**
* Constructor
*/
public DeviceUdiComponent() {
super();
}
/**
* @return {@link #deviceIdentifier} (The device identifier (DI) is a mandatory, fixed portion of a UDI that identifies the labeler and the specific version or model of a device.). This is the underlying object with id, value and extensions. The accessor "getDeviceIdentifier" gives direct access to the value
*/
public StringType getDeviceIdentifierElement() {
if (this.deviceIdentifier == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create DeviceUdiComponent.deviceIdentifier");
else if (Configuration.doAutoCreate())
this.deviceIdentifier = new StringType(); // bb
return this.deviceIdentifier;
}
public boolean hasDeviceIdentifierElement() {
return this.deviceIdentifier != null && !this.deviceIdentifier.isEmpty();
}
public boolean hasDeviceIdentifier() {
return this.deviceIdentifier != null && !this.deviceIdentifier.isEmpty();
}
/**
* @param value {@link #deviceIdentifier} (The device identifier (DI) is a mandatory, fixed portion of a UDI that identifies the labeler and the specific version or model of a device.). This is the underlying object with id, value and extensions. The accessor "getDeviceIdentifier" gives direct access to the value
*/
public DeviceUdiComponent setDeviceIdentifierElement(StringType value) {
this.deviceIdentifier = value;
return this;
}
/**
* @return The device identifier (DI) is a mandatory, fixed portion of a UDI that identifies the labeler and the specific version or model of a device.
*/
public String getDeviceIdentifier() {
return this.deviceIdentifier == null ? null : this.deviceIdentifier.getValue();
}
/**
* @param value The device identifier (DI) is a mandatory, fixed portion of a UDI that identifies the labeler and the specific version or model of a device.
*/
public DeviceUdiComponent setDeviceIdentifier(String value) {
if (Utilities.noString(value))
this.deviceIdentifier = null;
else {
if (this.deviceIdentifier == null)
this.deviceIdentifier = new StringType();
this.deviceIdentifier.setValue(value);
}
return this;
}
/**
* @return {@link #name} (Name of device as used in labeling or catalog.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value
*/
public StringType getNameElement() {
if (this.name == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create DeviceUdiComponent.name");
else if (Configuration.doAutoCreate())
this.name = new StringType(); // bb
return this.name;
}
public boolean hasNameElement() {
return this.name != null && !this.name.isEmpty();
}
public boolean hasName() {
return this.name != null && !this.name.isEmpty();
}
/**
* @param value {@link #name} (Name of device as used in labeling or catalog.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value
*/
public DeviceUdiComponent setNameElement(StringType value) {
this.name = value;
return this;
}
/**
* @return Name of device as used in labeling or catalog.
*/
public String getName() {
return this.name == null ? null : this.name.getValue();
}
/**
* @param value Name of device as used in labeling or catalog.
*/
public DeviceUdiComponent setName(String value) {
if (Utilities.noString(value))
this.name = null;
else {
if (this.name == null)
this.name = new StringType();
this.name.setValue(value);
}
return this;
}
/**
* @return {@link #jurisdiction} (The identity of the authoritative source for UDI generation within a jurisdiction. All UDIs are globally unique within a single namespace. with the appropriate repository uri as the system. For example, UDIs of devices managed in the U.S. by the FDA, the value is http://hl7.org/fhir/NamingSystem/fda-udi.). This is the underlying object with id, value and extensions. The accessor "getJurisdiction" gives direct access to the value
*/
public UriType getJurisdictionElement() {
if (this.jurisdiction == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create DeviceUdiComponent.jurisdiction");
else if (Configuration.doAutoCreate())
this.jurisdiction = new UriType(); // bb
return this.jurisdiction;
}
public boolean hasJurisdictionElement() {
return this.jurisdiction != null && !this.jurisdiction.isEmpty();
}
public boolean hasJurisdiction() {
return this.jurisdiction != null && !this.jurisdiction.isEmpty();
}
/**
* @param value {@link #jurisdiction} (The identity of the authoritative source for UDI generation within a jurisdiction. All UDIs are globally unique within a single namespace. with the appropriate repository uri as the system. For example, UDIs of devices managed in the U.S. by the FDA, the value is http://hl7.org/fhir/NamingSystem/fda-udi.). This is the underlying object with id, value and extensions. The accessor "getJurisdiction" gives direct access to the value
*/
public DeviceUdiComponent setJurisdictionElement(UriType value) {
this.jurisdiction = value;
return this;
}
/**
* @return The identity of the authoritative source for UDI generation within a jurisdiction. All UDIs are globally unique within a single namespace. with the appropriate repository uri as the system. For example, UDIs of devices managed in the U.S. by the FDA, the value is http://hl7.org/fhir/NamingSystem/fda-udi.
*/
public String getJurisdiction() {
return this.jurisdiction == null ? null : this.jurisdiction.getValue();
}
/**
* @param value The identity of the authoritative source for UDI generation within a jurisdiction. All UDIs are globally unique within a single namespace. with the appropriate repository uri as the system. For example, UDIs of devices managed in the U.S. by the FDA, the value is http://hl7.org/fhir/NamingSystem/fda-udi.
*/
public DeviceUdiComponent setJurisdiction(String value) {
if (Utilities.noString(value))
this.jurisdiction = null;
else {
if (this.jurisdiction == null)
this.jurisdiction = new UriType();
this.jurisdiction.setValue(value);
}
return this;
}
/**
* @return {@link #carrierHRF} (The full UDI carrier as the human readable form (HRF) representation of the barcode string as printed on the packaging of the device.). This is the underlying object with id, value and extensions. The accessor "getCarrierHRF" gives direct access to the value
*/
public StringType getCarrierHRFElement() {
if (this.carrierHRF == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create DeviceUdiComponent.carrierHRF");
else if (Configuration.doAutoCreate())
this.carrierHRF = new StringType(); // bb
return this.carrierHRF;
}
public boolean hasCarrierHRFElement() {
return this.carrierHRF != null && !this.carrierHRF.isEmpty();
}
public boolean hasCarrierHRF() {
return this.carrierHRF != null && !this.carrierHRF.isEmpty();
}
/**
* @param value {@link #carrierHRF} (The full UDI carrier as the human readable form (HRF) representation of the barcode string as printed on the packaging of the device.). This is the underlying object with id, value and extensions. The accessor "getCarrierHRF" gives direct access to the value
*/
public DeviceUdiComponent setCarrierHRFElement(StringType value) {
this.carrierHRF = value;
return this;
}
/**
* @return The full UDI carrier as the human readable form (HRF) representation of the barcode string as printed on the packaging of the device.
*/
public String getCarrierHRF() {
return this.carrierHRF == null ? null : this.carrierHRF.getValue();
}
/**
* @param value The full UDI carrier as the human readable form (HRF) representation of the barcode string as printed on the packaging of the device.
*/
public DeviceUdiComponent setCarrierHRF(String value) {
if (Utilities.noString(value))
this.carrierHRF = null;
else {
if (this.carrierHRF == null)
this.carrierHRF = new StringType();
this.carrierHRF.setValue(value);
}
return this;
}
/**
* @return {@link #carrierAIDC} (The full UDI carrier of the Automatic Identification and Data Capture (AIDC) technology representation of the barcode string as printed on the packaging of the device - E.g a barcode or RFID. Because of limitations on character sets in XML and the need to round-trip JSON data through XML, AIDC Formats *SHALL* be base64 encoded.). This is the underlying object with id, value and extensions. The accessor "getCarrierAIDC" gives direct access to the value
*/
public Base64BinaryType getCarrierAIDCElement() {
if (this.carrierAIDC == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create DeviceUdiComponent.carrierAIDC");
else if (Configuration.doAutoCreate())
this.carrierAIDC = new Base64BinaryType(); // bb
return this.carrierAIDC;
}
public boolean hasCarrierAIDCElement() {
return this.carrierAIDC != null && !this.carrierAIDC.isEmpty();
}
public boolean hasCarrierAIDC() {
return this.carrierAIDC != null && !this.carrierAIDC.isEmpty();
}
/**
* @param value {@link #carrierAIDC} (The full UDI carrier of the Automatic Identification and Data Capture (AIDC) technology representation of the barcode string as printed on the packaging of the device - E.g a barcode or RFID. Because of limitations on character sets in XML and the need to round-trip JSON data through XML, AIDC Formats *SHALL* be base64 encoded.). This is the underlying object with id, value and extensions. The accessor "getCarrierAIDC" gives direct access to the value
*/
public DeviceUdiComponent setCarrierAIDCElement(Base64BinaryType value) {
this.carrierAIDC = value;
return this;
}
/**
* @return The full UDI carrier of the Automatic Identification and Data Capture (AIDC) technology representation of the barcode string as printed on the packaging of the device - E.g a barcode or RFID. Because of limitations on character sets in XML and the need to round-trip JSON data through XML, AIDC Formats *SHALL* be base64 encoded.
*/
public byte[] getCarrierAIDC() {
return this.carrierAIDC == null ? null : this.carrierAIDC.getValue();
}
/**
* @param value The full UDI carrier of the Automatic Identification and Data Capture (AIDC) technology representation of the barcode string as printed on the packaging of the device - E.g a barcode or RFID. Because of limitations on character sets in XML and the need to round-trip JSON data through XML, AIDC Formats *SHALL* be base64 encoded.
*/
public DeviceUdiComponent setCarrierAIDC(byte[] value) {
if (value == null)
this.carrierAIDC = null;
else {
if (this.carrierAIDC == null)
this.carrierAIDC = new Base64BinaryType();
this.carrierAIDC.setValue(value);
}
return this;
}
/**
* @return {@link #issuer} (Organization that is charged with issuing UDIs for devices. For example, the US FDA issuers include :
1) GS1:
http://hl7.org/fhir/NamingSystem/gs1-di,
2) HIBCC:
http://hl7.org/fhir/NamingSystem/hibcc-dI,
3) ICCBBA for blood containers:
http://hl7.org/fhir/NamingSystem/iccbba-blood-di,
4) ICCBA for other devices:
http://hl7.org/fhir/NamingSystem/iccbba-other-di.). This is the underlying object with id, value and extensions. The accessor "getIssuer" gives direct access to the value
*/
public UriType getIssuerElement() {
if (this.issuer == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create DeviceUdiComponent.issuer");
else if (Configuration.doAutoCreate())
this.issuer = new UriType(); // bb
return this.issuer;
}
public boolean hasIssuerElement() {
return this.issuer != null && !this.issuer.isEmpty();
}
public boolean hasIssuer() {
return this.issuer != null && !this.issuer.isEmpty();
}
/**
* @param value {@link #issuer} (Organization that is charged with issuing UDIs for devices. For example, the US FDA issuers include :
1) GS1:
http://hl7.org/fhir/NamingSystem/gs1-di,
2) HIBCC:
http://hl7.org/fhir/NamingSystem/hibcc-dI,
3) ICCBBA for blood containers:
http://hl7.org/fhir/NamingSystem/iccbba-blood-di,
4) ICCBA for other devices:
http://hl7.org/fhir/NamingSystem/iccbba-other-di.). This is the underlying object with id, value and extensions. The accessor "getIssuer" gives direct access to the value
*/
public DeviceUdiComponent setIssuerElement(UriType value) {
this.issuer = value;
return this;
}
/**
* @return Organization that is charged with issuing UDIs for devices. For example, the US FDA issuers include :
1) GS1:
http://hl7.org/fhir/NamingSystem/gs1-di,
2) HIBCC:
http://hl7.org/fhir/NamingSystem/hibcc-dI,
3) ICCBBA for blood containers:
http://hl7.org/fhir/NamingSystem/iccbba-blood-di,
4) ICCBA for other devices:
http://hl7.org/fhir/NamingSystem/iccbba-other-di.
*/
public String getIssuer() {
return this.issuer == null ? null : this.issuer.getValue();
}
/**
* @param value Organization that is charged with issuing UDIs for devices. For example, the US FDA issuers include :
1) GS1:
http://hl7.org/fhir/NamingSystem/gs1-di,
2) HIBCC:
http://hl7.org/fhir/NamingSystem/hibcc-dI,
3) ICCBBA for blood containers:
http://hl7.org/fhir/NamingSystem/iccbba-blood-di,
4) ICCBA for other devices:
http://hl7.org/fhir/NamingSystem/iccbba-other-di.
*/
public DeviceUdiComponent setIssuer(String value) {
if (Utilities.noString(value))
this.issuer = null;
else {
if (this.issuer == null)
this.issuer = new UriType();
this.issuer.setValue(value);
}
return this;
}
/**
* @return {@link #entryType} (A coded entry to indicate how the data was entered.). This is the underlying object with id, value and extensions. The accessor "getEntryType" gives direct access to the value
*/
public Enumeration<UDIEntryType> getEntryTypeElement() {
if (this.entryType == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create DeviceUdiComponent.entryType");
else if (Configuration.doAutoCreate())
this.entryType = new Enumeration<UDIEntryType>(new UDIEntryTypeEnumFactory()); // bb
return this.entryType;
}
public boolean hasEntryTypeElement() {
return this.entryType != null && !this.entryType.isEmpty();
}
public boolean hasEntryType() {
return this.entryType != null && !this.entryType.isEmpty();
}
/**
* @param value {@link #entryType} (A coded entry to indicate how the data was entered.). This is the underlying object with id, value and extensions. The accessor "getEntryType" gives direct access to the value
*/
public DeviceUdiComponent setEntryTypeElement(Enumeration<UDIEntryType> value) {
this.entryType = value;
return this;
}
/**
* @return A coded entry to indicate how the data was entered.
*/
public UDIEntryType getEntryType() {
return this.entryType == null ? null : this.entryType.getValue();
}
/**
* @param value A coded entry to indicate how the data was entered.
*/
public DeviceUdiComponent setEntryType(UDIEntryType value) {
if (value == null)
this.entryType = null;
else {
if (this.entryType == null)
this.entryType = new Enumeration<UDIEntryType>(new UDIEntryTypeEnumFactory());
this.entryType.setValue(value);
}
return this;
}
protected void listChildren(List<Property> children) {
super.listChildren(children);
children.add(new Property("deviceIdentifier", "string", "The device identifier (DI) is a mandatory, fixed portion of a UDI that identifies the labeler and the specific version or model of a device.", 0, 1, deviceIdentifier));
children.add(new Property("name", "string", "Name of device as used in labeling or catalog.", 0, 1, name));
children.add(new Property("jurisdiction", "uri", "The identity of the authoritative source for UDI generation within a jurisdiction. All UDIs are globally unique within a single namespace. with the appropriate repository uri as the system. For example, UDIs of devices managed in the U.S. by the FDA, the value is http://hl7.org/fhir/NamingSystem/fda-udi.", 0, 1, jurisdiction));
children.add(new Property("carrierHRF", "string", "The full UDI carrier as the human readable form (HRF) representation of the barcode string as printed on the packaging of the device.", 0, 1, carrierHRF));
children.add(new Property("carrierAIDC", "base64Binary", "The full UDI carrier of the Automatic Identification and Data Capture (AIDC) technology representation of the barcode string as printed on the packaging of the device - E.g a barcode or RFID. Because of limitations on character sets in XML and the need to round-trip JSON data through XML, AIDC Formats *SHALL* be base64 encoded.", 0, 1, carrierAIDC));
children.add(new Property("issuer", "uri", "Organization that is charged with issuing UDIs for devices. For example, the US FDA issuers include :\n1) GS1: \nhttp://hl7.org/fhir/NamingSystem/gs1-di, \n2) HIBCC:\nhttp://hl7.org/fhir/NamingSystem/hibcc-dI, \n3) ICCBBA for blood containers:\nhttp://hl7.org/fhir/NamingSystem/iccbba-blood-di, \n4) ICCBA for other devices:\nhttp://hl7.org/fhir/NamingSystem/iccbba-other-di.", 0, 1, issuer));
children.add(new Property("entryType", "code", "A coded entry to indicate how the data was entered.", 0, 1, entryType));
}
@Override
public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException {
switch (_hash) {
case 1322005407: /*deviceIdentifier*/ return new Property("deviceIdentifier", "string", "The device identifier (DI) is a mandatory, fixed portion of a UDI that identifies the labeler and the specific version or model of a device.", 0, 1, deviceIdentifier);
case 3373707: /*name*/ return new Property("name", "string", "Name of device as used in labeling or catalog.", 0, 1, name);
case -507075711: /*jurisdiction*/ return new Property("jurisdiction", "uri", "The identity of the authoritative source for UDI generation within a jurisdiction. All UDIs are globally unique within a single namespace. with the appropriate repository uri as the system. For example, UDIs of devices managed in the U.S. by the FDA, the value is http://hl7.org/fhir/NamingSystem/fda-udi.", 0, 1, jurisdiction);
case 806499972: /*carrierHRF*/ return new Property("carrierHRF", "string", "The full UDI carrier as the human readable form (HRF) representation of the barcode string as printed on the packaging of the device.", 0, 1, carrierHRF);
case -768521825: /*carrierAIDC*/ return new Property("carrierAIDC", "base64Binary", "The full UDI carrier of the Automatic Identification and Data Capture (AIDC) technology representation of the barcode string as printed on the packaging of the device - E.g a barcode or RFID. Because of limitations on character sets in XML and the need to round-trip JSON data through XML, AIDC Formats *SHALL* be base64 encoded.", 0, 1, carrierAIDC);
case -1179159879: /*issuer*/ return new Property("issuer", "uri", "Organization that is charged with issuing UDIs for devices. For example, the US FDA issuers include :\n1) GS1: \nhttp://hl7.org/fhir/NamingSystem/gs1-di, \n2) HIBCC:\nhttp://hl7.org/fhir/NamingSystem/hibcc-dI, \n3) ICCBBA for blood containers:\nhttp://hl7.org/fhir/NamingSystem/iccbba-blood-di, \n4) ICCBA for other devices:\nhttp://hl7.org/fhir/NamingSystem/iccbba-other-di.", 0, 1, issuer);
case -479362356: /*entryType*/ return new Property("entryType", "code", "A coded entry to indicate how the data was entered.", 0, 1, entryType);
default: return super.getNamedProperty(_hash, _name, _checkValid);
}
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case 1322005407: /*deviceIdentifier*/ return this.deviceIdentifier == null ? new Base[0] : new Base[] {this.deviceIdentifier}; // StringType
case 3373707: /*name*/ return this.name == null ? new Base[0] : new Base[] {this.name}; // StringType
case -507075711: /*jurisdiction*/ return this.jurisdiction == null ? new Base[0] : new Base[] {this.jurisdiction}; // UriType
case 806499972: /*carrierHRF*/ return this.carrierHRF == null ? new Base[0] : new Base[] {this.carrierHRF}; // StringType
case -768521825: /*carrierAIDC*/ return this.carrierAIDC == null ? new Base[0] : new Base[] {this.carrierAIDC}; // Base64BinaryType
case -1179159879: /*issuer*/ return this.issuer == null ? new Base[0] : new Base[] {this.issuer}; // UriType
case -479362356: /*entryType*/ return this.entryType == null ? new Base[0] : new Base[] {this.entryType}; // Enumeration<UDIEntryType>
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public Base setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case 1322005407: // deviceIdentifier
this.deviceIdentifier = castToString(value); // StringType
return value;
case 3373707: // name
this.name = castToString(value); // StringType
return value;
case -507075711: // jurisdiction
this.jurisdiction = castToUri(value); // UriType
return value;
case 806499972: // carrierHRF
this.carrierHRF = castToString(value); // StringType
return value;
case -768521825: // carrierAIDC
this.carrierAIDC = castToBase64Binary(value); // Base64BinaryType
return value;
case -1179159879: // issuer
this.issuer = castToUri(value); // UriType
return value;
case -479362356: // entryType
value = new UDIEntryTypeEnumFactory().fromType(castToCode(value));
this.entryType = (Enumeration) value; // Enumeration<UDIEntryType>
return value;
default: return super.setProperty(hash, name, value);
}
}
@Override
public Base setProperty(String name, Base value) throws FHIRException {
if (name.equals("deviceIdentifier")) {
this.deviceIdentifier = castToString(value); // StringType
} else if (name.equals("name")) {
this.name = castToString(value); // StringType
} else if (name.equals("jurisdiction")) {
this.jurisdiction = castToUri(value); // UriType
} else if (name.equals("carrierHRF")) {
this.carrierHRF = castToString(value); // StringType
} else if (name.equals("carrierAIDC")) {
this.carrierAIDC = castToBase64Binary(value); // Base64BinaryType
} else if (name.equals("issuer")) {
this.issuer = castToUri(value); // UriType
} else if (name.equals("entryType")) {
value = new UDIEntryTypeEnumFactory().fromType(castToCode(value));
this.entryType = (Enumeration) value; // Enumeration<UDIEntryType>
} else
return super.setProperty(name, value);
return value;
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case 1322005407: return getDeviceIdentifierElement();
case 3373707: return getNameElement();
case -507075711: return getJurisdictionElement();
case 806499972: return getCarrierHRFElement();
case -768521825: return getCarrierAIDCElement();
case -1179159879: return getIssuerElement();
case -479362356: return getEntryTypeElement();
default: return super.makeProperty(hash, name);
}
}
@Override
public String[] getTypesForProperty(int hash, String name) throws FHIRException {
switch (hash) {
case 1322005407: /*deviceIdentifier*/ return new String[] {"string"};
case 3373707: /*name*/ return new String[] {"string"};
case -507075711: /*jurisdiction*/ return new String[] {"uri"};
case 806499972: /*carrierHRF*/ return new String[] {"string"};
case -768521825: /*carrierAIDC*/ return new String[] {"base64Binary"};
case -1179159879: /*issuer*/ return new String[] {"uri"};
case -479362356: /*entryType*/ return new String[] {"code"};
default: return super.getTypesForProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("deviceIdentifier")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.deviceIdentifier");
}
else if (name.equals("name")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.name");
}
else if (name.equals("jurisdiction")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.jurisdiction");
}
else if (name.equals("carrierHRF")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.carrierHRF");
}
else if (name.equals("carrierAIDC")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.carrierAIDC");
}
else if (name.equals("issuer")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.issuer");
}
else if (name.equals("entryType")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.entryType");
}
else
return super.addChild(name);
}
public DeviceUdiComponent copy() {
DeviceUdiComponent dst = new DeviceUdiComponent();
copyValues(dst);
dst.deviceIdentifier = deviceIdentifier == null ? null : deviceIdentifier.copy();
dst.name = name == null ? null : name.copy();
dst.jurisdiction = jurisdiction == null ? null : jurisdiction.copy();
dst.carrierHRF = carrierHRF == null ? null : carrierHRF.copy();
dst.carrierAIDC = carrierAIDC == null ? null : carrierAIDC.copy();
dst.issuer = issuer == null ? null : issuer.copy();
dst.entryType = entryType == null ? null : entryType.copy();
return dst;
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof DeviceUdiComponent))
return false;
DeviceUdiComponent o = (DeviceUdiComponent) other;
return compareDeep(deviceIdentifier, o.deviceIdentifier, true) && compareDeep(name, o.name, true)
&& compareDeep(jurisdiction, o.jurisdiction, true) && compareDeep(carrierHRF, o.carrierHRF, true)
&& compareDeep(carrierAIDC, o.carrierAIDC, true) && compareDeep(issuer, o.issuer, true) && compareDeep(entryType, o.entryType, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof DeviceUdiComponent))
return false;
DeviceUdiComponent o = (DeviceUdiComponent) other;
return compareValues(deviceIdentifier, o.deviceIdentifier, true) && compareValues(name, o.name, true)
&& compareValues(jurisdiction, o.jurisdiction, true) && compareValues(carrierHRF, o.carrierHRF, true)
&& compareValues(carrierAIDC, o.carrierAIDC, true) && compareValues(issuer, o.issuer, true) && compareValues(entryType, o.entryType, true)
;
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(deviceIdentifier, name, jurisdiction
, carrierHRF, carrierAIDC, issuer, entryType);
}
public String fhirType() {
return "Device.udi";
}
}
/**
* Unique instance identifiers assigned to a device by manufacturers other organizations or owners.
*/
@Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="Instance identifier", formalDefinition="Unique instance identifiers assigned to a device by manufacturers other organizations or owners." )
protected List<Identifier> identifier;
/**
* [Unique device identifier (UDI)](device.html#5.11.3.2.2) assigned to device label or package.
*/
@Child(name = "udi", type = {}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Unique Device Identifier (UDI) Barcode string", formalDefinition="[Unique device identifier (UDI)](device.html#5.11.3.2.2) assigned to device label or package." )
protected DeviceUdiComponent udi;
/**
* Status of the Device availability.
*/
@Child(name = "status", type = {CodeType.class}, order=2, min=0, max=1, modifier=true, summary=true)
@Description(shortDefinition="active | inactive | entered-in-error | unknown", formalDefinition="Status of the Device availability." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/device-status")
protected Enumeration<FHIRDeviceStatus> status;
/**
* Code or identifier to identify a kind of device.
*/
@Child(name = "type", type = {CodeableConcept.class}, order=3, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="What kind of device this is", formalDefinition="Code or identifier to identify a kind of device." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/device-kind")
protected CodeableConcept type;
/**
* Lot number assigned by the manufacturer.
*/
@Child(name = "lotNumber", type = {StringType.class}, order=4, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Lot number of manufacture", formalDefinition="Lot number assigned by the manufacturer." )
protected StringType lotNumber;
/**
* A name of the manufacturer.
*/
@Child(name = "manufacturer", type = {StringType.class}, order=5, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Name of device manufacturer", formalDefinition="A name of the manufacturer." )
protected StringType manufacturer;
/**
* The date and time when the device was manufactured.
*/
@Child(name = "manufactureDate", type = {DateTimeType.class}, order=6, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Date when the device was made", formalDefinition="The date and time when the device was manufactured." )
protected DateTimeType manufactureDate;
/**
* The date and time beyond which this device is no longer valid or should not be used (if applicable).
*/
@Child(name = "expirationDate", type = {DateTimeType.class}, order=7, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Date and time of expiry of this device (if applicable)", formalDefinition="The date and time beyond which this device is no longer valid or should not be used (if applicable)." )
protected DateTimeType expirationDate;
/**
* The "model" is an identifier assigned by the manufacturer to identify the product by its type. This number is shared by the all devices sold as the same type.
*/
@Child(name = "model", type = {StringType.class}, order=8, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Model id assigned by the manufacturer", formalDefinition="The \"model\" is an identifier assigned by the manufacturer to identify the product by its type. This number is shared by the all devices sold as the same type." )
protected StringType model;
/**
* The version of the device, if the device has multiple releases under the same model, or if the device is software or carries firmware.
*/
@Child(name = "version", type = {StringType.class}, order=9, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Version number (i.e. software)", formalDefinition="The version of the device, if the device has multiple releases under the same model, or if the device is software or carries firmware." )
protected StringType version;
/**
* Patient information, If the device is affixed to a person.
*/
@Child(name = "patient", type = {Patient.class}, order=10, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Patient to whom Device is affixed", formalDefinition="Patient information, If the device is affixed to a person." )
protected Reference patient;
/**
* The actual object that is the target of the reference (Patient information, If the device is affixed to a person.)
*/
protected Patient patientTarget;
/**
* An organization that is responsible for the provision and ongoing maintenance of the device.
*/
@Child(name = "owner", type = {Organization.class}, order=11, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Organization responsible for device", formalDefinition="An organization that is responsible for the provision and ongoing maintenance of the device." )
protected Reference owner;
/**
* The actual object that is the target of the reference (An organization that is responsible for the provision and ongoing maintenance of the device.)
*/
protected Organization ownerTarget;
/**
* Contact details for an organization or a particular human that is responsible for the device.
*/
@Child(name = "contact", type = {ContactPoint.class}, order=12, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="Details for human/organization for support", formalDefinition="Contact details for an organization or a particular human that is responsible for the device." )
protected List<ContactPoint> contact;
/**
* The place where the device can be found.
*/
@Child(name = "location", type = {Location.class}, order=13, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Where the resource is found", formalDefinition="The place where the device can be found." )
protected Reference location;
/**
* The actual object that is the target of the reference (The place where the device can be found.)
*/
protected Location locationTarget;
/**
* A network address on which the device may be contacted directly.
*/
@Child(name = "url", type = {UriType.class}, order=14, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Network address to contact device", formalDefinition="A network address on which the device may be contacted directly." )
protected UriType url;
/**
* Descriptive information, usage information or implantation information that is not captured in an existing element.
*/
@Child(name = "note", type = {Annotation.class}, order=15, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="Device notes and comments", formalDefinition="Descriptive information, usage information or implantation information that is not captured in an existing element." )
protected List<Annotation> note;
/**
* Provides additional safety characteristics about a medical device. For example devices containing latex.
*/
@Child(name = "safety", type = {CodeableConcept.class}, order=16, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Safety Characteristics of Device", formalDefinition="Provides additional safety characteristics about a medical device. For example devices containing latex." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/device-safety")
protected List<CodeableConcept> safety;
private static final long serialVersionUID = -1056263930L;
/**
* Constructor
*/
public Device() {
super();
}
/**
* @return {@link #identifier} (Unique instance identifiers assigned to a device by manufacturers other organizations or owners.)
*/
public List<Identifier> getIdentifier() {
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
return this.identifier;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Device setIdentifier(List<Identifier> theIdentifier) {
this.identifier = theIdentifier;
return this;
}
public boolean hasIdentifier() {
if (this.identifier == null)
return false;
for (Identifier item : this.identifier)
if (!item.isEmpty())
return true;
return false;
}
public Identifier addIdentifier() { //3
Identifier t = new Identifier();
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return t;
}
public Device addIdentifier(Identifier t) { //3
if (t == null)
return this;
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist
*/
public Identifier getIdentifierFirstRep() {
if (getIdentifier().isEmpty()) {
addIdentifier();
}
return getIdentifier().get(0);
}
/**
* @return {@link #udi} ([Unique device identifier (UDI)](device.html#5.11.3.2.2) assigned to device label or package.)
*/
public DeviceUdiComponent getUdi() {
if (this.udi == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.udi");
else if (Configuration.doAutoCreate())
this.udi = new DeviceUdiComponent(); // cc
return this.udi;
}
public boolean hasUdi() {
return this.udi != null && !this.udi.isEmpty();
}
/**
* @param value {@link #udi} ([Unique device identifier (UDI)](device.html#5.11.3.2.2) assigned to device label or package.)
*/
public Device setUdi(DeviceUdiComponent value) {
this.udi = value;
return this;
}
/**
* @return {@link #status} (Status of the Device availability.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value
*/
public Enumeration<FHIRDeviceStatus> getStatusElement() {
if (this.status == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.status");
else if (Configuration.doAutoCreate())
this.status = new Enumeration<FHIRDeviceStatus>(new FHIRDeviceStatusEnumFactory()); // bb
return this.status;
}
public boolean hasStatusElement() {
return this.status != null && !this.status.isEmpty();
}
public boolean hasStatus() {
return this.status != null && !this.status.isEmpty();
}
/**
* @param value {@link #status} (Status of the Device availability.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value
*/
public Device setStatusElement(Enumeration<FHIRDeviceStatus> value) {
this.status = value;
return this;
}
/**
* @return Status of the Device availability.
*/
public FHIRDeviceStatus getStatus() {
return this.status == null ? null : this.status.getValue();
}
/**
* @param value Status of the Device availability.
*/
public Device setStatus(FHIRDeviceStatus value) {
if (value == null)
this.status = null;
else {
if (this.status == null)
this.status = new Enumeration<FHIRDeviceStatus>(new FHIRDeviceStatusEnumFactory());
this.status.setValue(value);
}
return this;
}
/**
* @return {@link #type} (Code or identifier to identify a kind of device.)
*/
public CodeableConcept getType() {
if (this.type == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.type");
else if (Configuration.doAutoCreate())
this.type = new CodeableConcept(); // cc
return this.type;
}
public boolean hasType() {
return this.type != null && !this.type.isEmpty();
}
/**
* @param value {@link #type} (Code or identifier to identify a kind of device.)
*/
public Device setType(CodeableConcept value) {
this.type = value;
return this;
}
/**
* @return {@link #lotNumber} (Lot number assigned by the manufacturer.). This is the underlying object with id, value and extensions. The accessor "getLotNumber" gives direct access to the value
*/
public StringType getLotNumberElement() {
if (this.lotNumber == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.lotNumber");
else if (Configuration.doAutoCreate())
this.lotNumber = new StringType(); // bb
return this.lotNumber;
}
public boolean hasLotNumberElement() {
return this.lotNumber != null && !this.lotNumber.isEmpty();
}
public boolean hasLotNumber() {
return this.lotNumber != null && !this.lotNumber.isEmpty();
}
/**
* @param value {@link #lotNumber} (Lot number assigned by the manufacturer.). This is the underlying object with id, value and extensions. The accessor "getLotNumber" gives direct access to the value
*/
public Device setLotNumberElement(StringType value) {
this.lotNumber = value;
return this;
}
/**
* @return Lot number assigned by the manufacturer.
*/
public String getLotNumber() {
return this.lotNumber == null ? null : this.lotNumber.getValue();
}
/**
* @param value Lot number assigned by the manufacturer.
*/
public Device setLotNumber(String value) {
if (Utilities.noString(value))
this.lotNumber = null;
else {
if (this.lotNumber == null)
this.lotNumber = new StringType();
this.lotNumber.setValue(value);
}
return this;
}
/**
* @return {@link #manufacturer} (A name of the manufacturer.). This is the underlying object with id, value and extensions. The accessor "getManufacturer" gives direct access to the value
*/
public StringType getManufacturerElement() {
if (this.manufacturer == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.manufacturer");
else if (Configuration.doAutoCreate())
this.manufacturer = new StringType(); // bb
return this.manufacturer;
}
public boolean hasManufacturerElement() {
return this.manufacturer != null && !this.manufacturer.isEmpty();
}
public boolean hasManufacturer() {
return this.manufacturer != null && !this.manufacturer.isEmpty();
}
/**
* @param value {@link #manufacturer} (A name of the manufacturer.). This is the underlying object with id, value and extensions. The accessor "getManufacturer" gives direct access to the value
*/
public Device setManufacturerElement(StringType value) {
this.manufacturer = value;
return this;
}
/**
* @return A name of the manufacturer.
*/
public String getManufacturer() {
return this.manufacturer == null ? null : this.manufacturer.getValue();
}
/**
* @param value A name of the manufacturer.
*/
public Device setManufacturer(String value) {
if (Utilities.noString(value))
this.manufacturer = null;
else {
if (this.manufacturer == null)
this.manufacturer = new StringType();
this.manufacturer.setValue(value);
}
return this;
}
/**
* @return {@link #manufactureDate} (The date and time when the device was manufactured.). This is the underlying object with id, value and extensions. The accessor "getManufactureDate" gives direct access to the value
*/
public DateTimeType getManufactureDateElement() {
if (this.manufactureDate == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.manufactureDate");
else if (Configuration.doAutoCreate())
this.manufactureDate = new DateTimeType(); // bb
return this.manufactureDate;
}
public boolean hasManufactureDateElement() {
return this.manufactureDate != null && !this.manufactureDate.isEmpty();
}
public boolean hasManufactureDate() {
return this.manufactureDate != null && !this.manufactureDate.isEmpty();
}
/**
* @param value {@link #manufactureDate} (The date and time when the device was manufactured.). This is the underlying object with id, value and extensions. The accessor "getManufactureDate" gives direct access to the value
*/
public Device setManufactureDateElement(DateTimeType value) {
this.manufactureDate = value;
return this;
}
/**
* @return The date and time when the device was manufactured.
*/
public Date getManufactureDate() {
return this.manufactureDate == null ? null : this.manufactureDate.getValue();
}
/**
* @param value The date and time when the device was manufactured.
*/
public Device setManufactureDate(Date value) {
if (value == null)
this.manufactureDate = null;
else {
if (this.manufactureDate == null)
this.manufactureDate = new DateTimeType();
this.manufactureDate.setValue(value);
}
return this;
}
/**
* @return {@link #expirationDate} (The date and time beyond which this device is no longer valid or should not be used (if applicable).). This is the underlying object with id, value and extensions. The accessor "getExpirationDate" gives direct access to the value
*/
public DateTimeType getExpirationDateElement() {
if (this.expirationDate == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.expirationDate");
else if (Configuration.doAutoCreate())
this.expirationDate = new DateTimeType(); // bb
return this.expirationDate;
}
public boolean hasExpirationDateElement() {
return this.expirationDate != null && !this.expirationDate.isEmpty();
}
public boolean hasExpirationDate() {
return this.expirationDate != null && !this.expirationDate.isEmpty();
}
/**
* @param value {@link #expirationDate} (The date and time beyond which this device is no longer valid or should not be used (if applicable).). This is the underlying object with id, value and extensions. The accessor "getExpirationDate" gives direct access to the value
*/
public Device setExpirationDateElement(DateTimeType value) {
this.expirationDate = value;
return this;
}
/**
* @return The date and time beyond which this device is no longer valid or should not be used (if applicable).
*/
public Date getExpirationDate() {
return this.expirationDate == null ? null : this.expirationDate.getValue();
}
/**
* @param value The date and time beyond which this device is no longer valid or should not be used (if applicable).
*/
public Device setExpirationDate(Date value) {
if (value == null)
this.expirationDate = null;
else {
if (this.expirationDate == null)
this.expirationDate = new DateTimeType();
this.expirationDate.setValue(value);
}
return this;
}
/**
* @return {@link #model} (The "model" is an identifier assigned by the manufacturer to identify the product by its type. This number is shared by the all devices sold as the same type.). This is the underlying object with id, value and extensions. The accessor "getModel" gives direct access to the value
*/
public StringType getModelElement() {
if (this.model == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.model");
else if (Configuration.doAutoCreate())
this.model = new StringType(); // bb
return this.model;
}
public boolean hasModelElement() {
return this.model != null && !this.model.isEmpty();
}
public boolean hasModel() {
return this.model != null && !this.model.isEmpty();
}
/**
* @param value {@link #model} (The "model" is an identifier assigned by the manufacturer to identify the product by its type. This number is shared by the all devices sold as the same type.). This is the underlying object with id, value and extensions. The accessor "getModel" gives direct access to the value
*/
public Device setModelElement(StringType value) {
this.model = value;
return this;
}
/**
* @return The "model" is an identifier assigned by the manufacturer to identify the product by its type. This number is shared by the all devices sold as the same type.
*/
public String getModel() {
return this.model == null ? null : this.model.getValue();
}
/**
* @param value The "model" is an identifier assigned by the manufacturer to identify the product by its type. This number is shared by the all devices sold as the same type.
*/
public Device setModel(String value) {
if (Utilities.noString(value))
this.model = null;
else {
if (this.model == null)
this.model = new StringType();
this.model.setValue(value);
}
return this;
}
/**
* @return {@link #version} (The version of the device, if the device has multiple releases under the same model, or if the device is software or carries firmware.). This is the underlying object with id, value and extensions. The accessor "getVersion" gives direct access to the value
*/
public StringType getVersionElement() {
if (this.version == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.version");
else if (Configuration.doAutoCreate())
this.version = new StringType(); // bb
return this.version;
}
public boolean hasVersionElement() {
return this.version != null && !this.version.isEmpty();
}
public boolean hasVersion() {
return this.version != null && !this.version.isEmpty();
}
/**
* @param value {@link #version} (The version of the device, if the device has multiple releases under the same model, or if the device is software or carries firmware.). This is the underlying object with id, value and extensions. The accessor "getVersion" gives direct access to the value
*/
public Device setVersionElement(StringType value) {
this.version = value;
return this;
}
/**
* @return The version of the device, if the device has multiple releases under the same model, or if the device is software or carries firmware.
*/
public String getVersion() {
return this.version == null ? null : this.version.getValue();
}
/**
* @param value The version of the device, if the device has multiple releases under the same model, or if the device is software or carries firmware.
*/
public Device setVersion(String value) {
if (Utilities.noString(value))
this.version = null;
else {
if (this.version == null)
this.version = new StringType();
this.version.setValue(value);
}
return this;
}
/**
* @return {@link #patient} (Patient information, If the device is affixed to a person.)
*/
public Reference getPatient() {
if (this.patient == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.patient");
else if (Configuration.doAutoCreate())
this.patient = new Reference(); // cc
return this.patient;
}
public boolean hasPatient() {
return this.patient != null && !this.patient.isEmpty();
}
/**
* @param value {@link #patient} (Patient information, If the device is affixed to a person.)
*/
public Device setPatient(Reference value) {
this.patient = value;
return this;
}
/**
* @return {@link #patient} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Patient information, If the device is affixed to a person.)
*/
public Patient getPatientTarget() {
if (this.patientTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.patient");
else if (Configuration.doAutoCreate())
this.patientTarget = new Patient(); // aa
return this.patientTarget;
}
/**
* @param value {@link #patient} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Patient information, If the device is affixed to a person.)
*/
public Device setPatientTarget(Patient value) {
this.patientTarget = value;
return this;
}
/**
* @return {@link #owner} (An organization that is responsible for the provision and ongoing maintenance of the device.)
*/
public Reference getOwner() {
if (this.owner == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.owner");
else if (Configuration.doAutoCreate())
this.owner = new Reference(); // cc
return this.owner;
}
public boolean hasOwner() {
return this.owner != null && !this.owner.isEmpty();
}
/**
* @param value {@link #owner} (An organization that is responsible for the provision and ongoing maintenance of the device.)
*/
public Device setOwner(Reference value) {
this.owner = value;
return this;
}
/**
* @return {@link #owner} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (An organization that is responsible for the provision and ongoing maintenance of the device.)
*/
public Organization getOwnerTarget() {
if (this.ownerTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.owner");
else if (Configuration.doAutoCreate())
this.ownerTarget = new Organization(); // aa
return this.ownerTarget;
}
/**
* @param value {@link #owner} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (An organization that is responsible for the provision and ongoing maintenance of the device.)
*/
public Device setOwnerTarget(Organization value) {
this.ownerTarget = value;
return this;
}
/**
* @return {@link #contact} (Contact details for an organization or a particular human that is responsible for the device.)
*/
public List<ContactPoint> getContact() {
if (this.contact == null)
this.contact = new ArrayList<ContactPoint>();
return this.contact;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Device setContact(List<ContactPoint> theContact) {
this.contact = theContact;
return this;
}
public boolean hasContact() {
if (this.contact == null)
return false;
for (ContactPoint item : this.contact)
if (!item.isEmpty())
return true;
return false;
}
public ContactPoint addContact() { //3
ContactPoint t = new ContactPoint();
if (this.contact == null)
this.contact = new ArrayList<ContactPoint>();
this.contact.add(t);
return t;
}
public Device addContact(ContactPoint t) { //3
if (t == null)
return this;
if (this.contact == null)
this.contact = new ArrayList<ContactPoint>();
this.contact.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #contact}, creating it if it does not already exist
*/
public ContactPoint getContactFirstRep() {
if (getContact().isEmpty()) {
addContact();
}
return getContact().get(0);
}
/**
* @return {@link #location} (The place where the device can be found.)
*/
public Reference getLocation() {
if (this.location == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.location");
else if (Configuration.doAutoCreate())
this.location = new Reference(); // cc
return this.location;
}
public boolean hasLocation() {
return this.location != null && !this.location.isEmpty();
}
/**
* @param value {@link #location} (The place where the device can be found.)
*/
public Device setLocation(Reference value) {
this.location = value;
return this;
}
/**
* @return {@link #location} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The place where the device can be found.)
*/
public Location getLocationTarget() {
if (this.locationTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.location");
else if (Configuration.doAutoCreate())
this.locationTarget = new Location(); // aa
return this.locationTarget;
}
/**
* @param value {@link #location} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The place where the device can be found.)
*/
public Device setLocationTarget(Location value) {
this.locationTarget = value;
return this;
}
/**
* @return {@link #url} (A network address on which the device may be contacted directly.). This is the underlying object with id, value and extensions. The accessor "getUrl" gives direct access to the value
*/
public UriType getUrlElement() {
if (this.url == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Device.url");
else if (Configuration.doAutoCreate())
this.url = new UriType(); // bb
return this.url;
}
public boolean hasUrlElement() {
return this.url != null && !this.url.isEmpty();
}
public boolean hasUrl() {
return this.url != null && !this.url.isEmpty();
}
/**
* @param value {@link #url} (A network address on which the device may be contacted directly.). This is the underlying object with id, value and extensions. The accessor "getUrl" gives direct access to the value
*/
public Device setUrlElement(UriType value) {
this.url = value;
return this;
}
/**
* @return A network address on which the device may be contacted directly.
*/
public String getUrl() {
return this.url == null ? null : this.url.getValue();
}
/**
* @param value A network address on which the device may be contacted directly.
*/
public Device setUrl(String value) {
if (Utilities.noString(value))
this.url = null;
else {
if (this.url == null)
this.url = new UriType();
this.url.setValue(value);
}
return this;
}
/**
* @return {@link #note} (Descriptive information, usage information or implantation information that is not captured in an existing element.)
*/
public List<Annotation> getNote() {
if (this.note == null)
this.note = new ArrayList<Annotation>();
return this.note;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Device setNote(List<Annotation> theNote) {
this.note = theNote;
return this;
}
public boolean hasNote() {
if (this.note == null)
return false;
for (Annotation item : this.note)
if (!item.isEmpty())
return true;
return false;
}
public Annotation addNote() { //3
Annotation t = new Annotation();
if (this.note == null)
this.note = new ArrayList<Annotation>();
this.note.add(t);
return t;
}
public Device addNote(Annotation t) { //3
if (t == null)
return this;
if (this.note == null)
this.note = new ArrayList<Annotation>();
this.note.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #note}, creating it if it does not already exist
*/
public Annotation getNoteFirstRep() {
if (getNote().isEmpty()) {
addNote();
}
return getNote().get(0);
}
/**
* @return {@link #safety} (Provides additional safety characteristics about a medical device. For example devices containing latex.)
*/
public List<CodeableConcept> getSafety() {
if (this.safety == null)
this.safety = new ArrayList<CodeableConcept>();
return this.safety;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Device setSafety(List<CodeableConcept> theSafety) {
this.safety = theSafety;
return this;
}
public boolean hasSafety() {
if (this.safety == null)
return false;
for (CodeableConcept item : this.safety)
if (!item.isEmpty())
return true;
return false;
}
public CodeableConcept addSafety() { //3
CodeableConcept t = new CodeableConcept();
if (this.safety == null)
this.safety = new ArrayList<CodeableConcept>();
this.safety.add(t);
return t;
}
public Device addSafety(CodeableConcept t) { //3
if (t == null)
return this;
if (this.safety == null)
this.safety = new ArrayList<CodeableConcept>();
this.safety.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #safety}, creating it if it does not already exist
*/
public CodeableConcept getSafetyFirstRep() {
if (getSafety().isEmpty()) {
addSafety();
}
return getSafety().get(0);
}
protected void listChildren(List<Property> children) {
super.listChildren(children);
children.add(new Property("identifier", "Identifier", "Unique instance identifiers assigned to a device by manufacturers other organizations or owners.", 0, java.lang.Integer.MAX_VALUE, identifier));
children.add(new Property("udi", "", "[Unique device identifier (UDI)](device.html#5.11.3.2.2) assigned to device label or package.", 0, 1, udi));
children.add(new Property("status", "code", "Status of the Device availability.", 0, 1, status));
children.add(new Property("type", "CodeableConcept", "Code or identifier to identify a kind of device.", 0, 1, type));
children.add(new Property("lotNumber", "string", "Lot number assigned by the manufacturer.", 0, 1, lotNumber));
children.add(new Property("manufacturer", "string", "A name of the manufacturer.", 0, 1, manufacturer));
children.add(new Property("manufactureDate", "dateTime", "The date and time when the device was manufactured.", 0, 1, manufactureDate));
children.add(new Property("expirationDate", "dateTime", "The date and time beyond which this device is no longer valid or should not be used (if applicable).", 0, 1, expirationDate));
children.add(new Property("model", "string", "The \"model\" is an identifier assigned by the manufacturer to identify the product by its type. This number is shared by the all devices sold as the same type.", 0, 1, model));
children.add(new Property("version", "string", "The version of the device, if the device has multiple releases under the same model, or if the device is software or carries firmware.", 0, 1, version));
children.add(new Property("patient", "Reference(Patient)", "Patient information, If the device is affixed to a person.", 0, 1, patient));
children.add(new Property("owner", "Reference(Organization)", "An organization that is responsible for the provision and ongoing maintenance of the device.", 0, 1, owner));
children.add(new Property("contact", "ContactPoint", "Contact details for an organization or a particular human that is responsible for the device.", 0, java.lang.Integer.MAX_VALUE, contact));
children.add(new Property("location", "Reference(Location)", "The place where the device can be found.", 0, 1, location));
children.add(new Property("url", "uri", "A network address on which the device may be contacted directly.", 0, 1, url));
children.add(new Property("note", "Annotation", "Descriptive information, usage information or implantation information that is not captured in an existing element.", 0, java.lang.Integer.MAX_VALUE, note));
children.add(new Property("safety", "CodeableConcept", "Provides additional safety characteristics about a medical device. For example devices containing latex.", 0, java.lang.Integer.MAX_VALUE, safety));
}
@Override
public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException {
switch (_hash) {
case -1618432855: /*identifier*/ return new Property("identifier", "Identifier", "Unique instance identifiers assigned to a device by manufacturers other organizations or owners.", 0, java.lang.Integer.MAX_VALUE, identifier);
case 115642: /*udi*/ return new Property("udi", "", "[Unique device identifier (UDI)](device.html#5.11.3.2.2) assigned to device label or package.", 0, 1, udi);
case -892481550: /*status*/ return new Property("status", "code", "Status of the Device availability.", 0, 1, status);
case 3575610: /*type*/ return new Property("type", "CodeableConcept", "Code or identifier to identify a kind of device.", 0, 1, type);
case 462547450: /*lotNumber*/ return new Property("lotNumber", "string", "Lot number assigned by the manufacturer.", 0, 1, lotNumber);
case -1969347631: /*manufacturer*/ return new Property("manufacturer", "string", "A name of the manufacturer.", 0, 1, manufacturer);
case 416714767: /*manufactureDate*/ return new Property("manufactureDate", "dateTime", "The date and time when the device was manufactured.", 0, 1, manufactureDate);
case -668811523: /*expirationDate*/ return new Property("expirationDate", "dateTime", "The date and time beyond which this device is no longer valid or should not be used (if applicable).", 0, 1, expirationDate);
case 104069929: /*model*/ return new Property("model", "string", "The \"model\" is an identifier assigned by the manufacturer to identify the product by its type. This number is shared by the all devices sold as the same type.", 0, 1, model);
case 351608024: /*version*/ return new Property("version", "string", "The version of the device, if the device has multiple releases under the same model, or if the device is software or carries firmware.", 0, 1, version);
case -791418107: /*patient*/ return new Property("patient", "Reference(Patient)", "Patient information, If the device is affixed to a person.", 0, 1, patient);
case 106164915: /*owner*/ return new Property("owner", "Reference(Organization)", "An organization that is responsible for the provision and ongoing maintenance of the device.", 0, 1, owner);
case 951526432: /*contact*/ return new Property("contact", "ContactPoint", "Contact details for an organization or a particular human that is responsible for the device.", 0, java.lang.Integer.MAX_VALUE, contact);
case 1901043637: /*location*/ return new Property("location", "Reference(Location)", "The place where the device can be found.", 0, 1, location);
case 116079: /*url*/ return new Property("url", "uri", "A network address on which the device may be contacted directly.", 0, 1, url);
case 3387378: /*note*/ return new Property("note", "Annotation", "Descriptive information, usage information or implantation information that is not captured in an existing element.", 0, java.lang.Integer.MAX_VALUE, note);
case -909893934: /*safety*/ return new Property("safety", "CodeableConcept", "Provides additional safety characteristics about a medical device. For example devices containing latex.", 0, java.lang.Integer.MAX_VALUE, safety);
default: return super.getNamedProperty(_hash, _name, _checkValid);
}
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier
case 115642: /*udi*/ return this.udi == null ? new Base[0] : new Base[] {this.udi}; // DeviceUdiComponent
case -892481550: /*status*/ return this.status == null ? new Base[0] : new Base[] {this.status}; // Enumeration<FHIRDeviceStatus>
case 3575610: /*type*/ return this.type == null ? new Base[0] : new Base[] {this.type}; // CodeableConcept
case 462547450: /*lotNumber*/ return this.lotNumber == null ? new Base[0] : new Base[] {this.lotNumber}; // StringType
case -1969347631: /*manufacturer*/ return this.manufacturer == null ? new Base[0] : new Base[] {this.manufacturer}; // StringType
case 416714767: /*manufactureDate*/ return this.manufactureDate == null ? new Base[0] : new Base[] {this.manufactureDate}; // DateTimeType
case -668811523: /*expirationDate*/ return this.expirationDate == null ? new Base[0] : new Base[] {this.expirationDate}; // DateTimeType
case 104069929: /*model*/ return this.model == null ? new Base[0] : new Base[] {this.model}; // StringType
case 351608024: /*version*/ return this.version == null ? new Base[0] : new Base[] {this.version}; // StringType
case -791418107: /*patient*/ return this.patient == null ? new Base[0] : new Base[] {this.patient}; // Reference
case 106164915: /*owner*/ return this.owner == null ? new Base[0] : new Base[] {this.owner}; // Reference
case 951526432: /*contact*/ return this.contact == null ? new Base[0] : this.contact.toArray(new Base[this.contact.size()]); // ContactPoint
case 1901043637: /*location*/ return this.location == null ? new Base[0] : new Base[] {this.location}; // Reference
case 116079: /*url*/ return this.url == null ? new Base[0] : new Base[] {this.url}; // UriType
case 3387378: /*note*/ return this.note == null ? new Base[0] : this.note.toArray(new Base[this.note.size()]); // Annotation
case -909893934: /*safety*/ return this.safety == null ? new Base[0] : this.safety.toArray(new Base[this.safety.size()]); // CodeableConcept
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public Base setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case -1618432855: // identifier
this.getIdentifier().add(castToIdentifier(value)); // Identifier
return value;
case 115642: // udi
this.udi = (DeviceUdiComponent) value; // DeviceUdiComponent
return value;
case -892481550: // status
value = new FHIRDeviceStatusEnumFactory().fromType(castToCode(value));
this.status = (Enumeration) value; // Enumeration<FHIRDeviceStatus>
return value;
case 3575610: // type
this.type = castToCodeableConcept(value); // CodeableConcept
return value;
case 462547450: // lotNumber
this.lotNumber = castToString(value); // StringType
return value;
case -1969347631: // manufacturer
this.manufacturer = castToString(value); // StringType
return value;
case 416714767: // manufactureDate
this.manufactureDate = castToDateTime(value); // DateTimeType
return value;
case -668811523: // expirationDate
this.expirationDate = castToDateTime(value); // DateTimeType
return value;
case 104069929: // model
this.model = castToString(value); // StringType
return value;
case 351608024: // version
this.version = castToString(value); // StringType
return value;
case -791418107: // patient
this.patient = castToReference(value); // Reference
return value;
case 106164915: // owner
this.owner = castToReference(value); // Reference
return value;
case 951526432: // contact
this.getContact().add(castToContactPoint(value)); // ContactPoint
return value;
case 1901043637: // location
this.location = castToReference(value); // Reference
return value;
case 116079: // url
this.url = castToUri(value); // UriType
return value;
case 3387378: // note
this.getNote().add(castToAnnotation(value)); // Annotation
return value;
case -909893934: // safety
this.getSafety().add(castToCodeableConcept(value)); // CodeableConcept
return value;
default: return super.setProperty(hash, name, value);
}
}
@Override
public Base setProperty(String name, Base value) throws FHIRException {
if (name.equals("identifier")) {
this.getIdentifier().add(castToIdentifier(value));
} else if (name.equals("udi")) {
this.udi = (DeviceUdiComponent) value; // DeviceUdiComponent
} else if (name.equals("status")) {
value = new FHIRDeviceStatusEnumFactory().fromType(castToCode(value));
this.status = (Enumeration) value; // Enumeration<FHIRDeviceStatus>
} else if (name.equals("type")) {
this.type = castToCodeableConcept(value); // CodeableConcept
} else if (name.equals("lotNumber")) {
this.lotNumber = castToString(value); // StringType
} else if (name.equals("manufacturer")) {
this.manufacturer = castToString(value); // StringType
} else if (name.equals("manufactureDate")) {
this.manufactureDate = castToDateTime(value); // DateTimeType
} else if (name.equals("expirationDate")) {
this.expirationDate = castToDateTime(value); // DateTimeType
} else if (name.equals("model")) {
this.model = castToString(value); // StringType
} else if (name.equals("version")) {
this.version = castToString(value); // StringType
} else if (name.equals("patient")) {
this.patient = castToReference(value); // Reference
} else if (name.equals("owner")) {
this.owner = castToReference(value); // Reference
} else if (name.equals("contact")) {
this.getContact().add(castToContactPoint(value));
} else if (name.equals("location")) {
this.location = castToReference(value); // Reference
} else if (name.equals("url")) {
this.url = castToUri(value); // UriType
} else if (name.equals("note")) {
this.getNote().add(castToAnnotation(value));
} else if (name.equals("safety")) {
this.getSafety().add(castToCodeableConcept(value));
} else
return super.setProperty(name, value);
return value;
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -1618432855: return addIdentifier();
case 115642: return getUdi();
case -892481550: return getStatusElement();
case 3575610: return getType();
case 462547450: return getLotNumberElement();
case -1969347631: return getManufacturerElement();
case 416714767: return getManufactureDateElement();
case -668811523: return getExpirationDateElement();
case 104069929: return getModelElement();
case 351608024: return getVersionElement();
case -791418107: return getPatient();
case 106164915: return getOwner();
case 951526432: return addContact();
case 1901043637: return getLocation();
case 116079: return getUrlElement();
case 3387378: return addNote();
case -909893934: return addSafety();
default: return super.makeProperty(hash, name);
}
}
@Override
public String[] getTypesForProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -1618432855: /*identifier*/ return new String[] {"Identifier"};
case 115642: /*udi*/ return new String[] {};
case -892481550: /*status*/ return new String[] {"code"};
case 3575610: /*type*/ return new String[] {"CodeableConcept"};
case 462547450: /*lotNumber*/ return new String[] {"string"};
case -1969347631: /*manufacturer*/ return new String[] {"string"};
case 416714767: /*manufactureDate*/ return new String[] {"dateTime"};
case -668811523: /*expirationDate*/ return new String[] {"dateTime"};
case 104069929: /*model*/ return new String[] {"string"};
case 351608024: /*version*/ return new String[] {"string"};
case -791418107: /*patient*/ return new String[] {"Reference"};
case 106164915: /*owner*/ return new String[] {"Reference"};
case 951526432: /*contact*/ return new String[] {"ContactPoint"};
case 1901043637: /*location*/ return new String[] {"Reference"};
case 116079: /*url*/ return new String[] {"uri"};
case 3387378: /*note*/ return new String[] {"Annotation"};
case -909893934: /*safety*/ return new String[] {"CodeableConcept"};
default: return super.getTypesForProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("identifier")) {
return addIdentifier();
}
else if (name.equals("udi")) {
this.udi = new DeviceUdiComponent();
return this.udi;
}
else if (name.equals("status")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.status");
}
else if (name.equals("type")) {
this.type = new CodeableConcept();
return this.type;
}
else if (name.equals("lotNumber")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.lotNumber");
}
else if (name.equals("manufacturer")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.manufacturer");
}
else if (name.equals("manufactureDate")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.manufactureDate");
}
else if (name.equals("expirationDate")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.expirationDate");
}
else if (name.equals("model")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.model");
}
else if (name.equals("version")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.version");
}
else if (name.equals("patient")) {
this.patient = new Reference();
return this.patient;
}
else if (name.equals("owner")) {
this.owner = new Reference();
return this.owner;
}
else if (name.equals("contact")) {
return addContact();
}
else if (name.equals("location")) {
this.location = new Reference();
return this.location;
}
else if (name.equals("url")) {
throw new FHIRException("Cannot call addChild on a primitive type Device.url");
}
else if (name.equals("note")) {
return addNote();
}
else if (name.equals("safety")) {
return addSafety();
}
else
return super.addChild(name);
}
public String fhirType() {
return "Device";
}
public Device copy() {
Device dst = new Device();
copyValues(dst);
if (identifier != null) {
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
};
dst.udi = udi == null ? null : udi.copy();
dst.status = status == null ? null : status.copy();
dst.type = type == null ? null : type.copy();
dst.lotNumber = lotNumber == null ? null : lotNumber.copy();
dst.manufacturer = manufacturer == null ? null : manufacturer.copy();
dst.manufactureDate = manufactureDate == null ? null : manufactureDate.copy();
dst.expirationDate = expirationDate == null ? null : expirationDate.copy();
dst.model = model == null ? null : model.copy();
dst.version = version == null ? null : version.copy();
dst.patient = patient == null ? null : patient.copy();
dst.owner = owner == null ? null : owner.copy();
if (contact != null) {
dst.contact = new ArrayList<ContactPoint>();
for (ContactPoint i : contact)
dst.contact.add(i.copy());
};
dst.location = location == null ? null : location.copy();
dst.url = url == null ? null : url.copy();
if (note != null) {
dst.note = new ArrayList<Annotation>();
for (Annotation i : note)
dst.note.add(i.copy());
};
if (safety != null) {
dst.safety = new ArrayList<CodeableConcept>();
for (CodeableConcept i : safety)
dst.safety.add(i.copy());
};
return dst;
}
protected Device typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Device))
return false;
Device o = (Device) other;
return compareDeep(identifier, o.identifier, true) && compareDeep(udi, o.udi, true) && compareDeep(status, o.status, true)
&& compareDeep(type, o.type, true) && compareDeep(lotNumber, o.lotNumber, true) && compareDeep(manufacturer, o.manufacturer, true)
&& compareDeep(manufactureDate, o.manufactureDate, true) && compareDeep(expirationDate, o.expirationDate, true)
&& compareDeep(model, o.model, true) && compareDeep(version, o.version, true) && compareDeep(patient, o.patient, true)
&& compareDeep(owner, o.owner, true) && compareDeep(contact, o.contact, true) && compareDeep(location, o.location, true)
&& compareDeep(url, o.url, true) && compareDeep(note, o.note, true) && compareDeep(safety, o.safety, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Device))
return false;
Device o = (Device) other;
return compareValues(status, o.status, true) && compareValues(lotNumber, o.lotNumber, true) && compareValues(manufacturer, o.manufacturer, true)
&& compareValues(manufactureDate, o.manufactureDate, true) && compareValues(expirationDate, o.expirationDate, true)
&& compareValues(model, o.model, true) && compareValues(version, o.version, true) && compareValues(url, o.url, true)
;
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, udi, status
, type, lotNumber, manufacturer, manufactureDate, expirationDate, model, version
, patient, owner, contact, location, url, note, safety);
}
@Override
public ResourceType getResourceType() {
return ResourceType.Device;
}
/**
* Search parameter: <b>udi-di</b>
* <p>
* Description: <b>The udi Device Identifier (DI)</b><br>
* Type: <b>string</b><br>
* Path: <b>Device.udi.deviceIdentifier</b><br>
* </p>
*/
@SearchParamDefinition(name="udi-di", path="Device.udi.deviceIdentifier", description="The udi Device Identifier (DI)", type="string" )
public static final String SP_UDI_DI = "udi-di";
/**
* <b>Fluent Client</b> search parameter constant for <b>udi-di</b>
* <p>
* Description: <b>The udi Device Identifier (DI)</b><br>
* Type: <b>string</b><br>
* Path: <b>Device.udi.deviceIdentifier</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam UDI_DI = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_UDI_DI);
/**
* Search parameter: <b>identifier</b>
* <p>
* Description: <b>Instance id from manufacturer, owner, and others</b><br>
* Type: <b>token</b><br>
* Path: <b>Device.identifier</b><br>
* </p>
*/
@SearchParamDefinition(name="identifier", path="Device.identifier", description="Instance id from manufacturer, owner, and others", type="token" )
public static final String SP_IDENTIFIER = "identifier";
/**
* <b>Fluent Client</b> search parameter constant for <b>identifier</b>
* <p>
* Description: <b>Instance id from manufacturer, owner, and others</b><br>
* Type: <b>token</b><br>
* Path: <b>Device.identifier</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER);
/**
* Search parameter: <b>udi-carrier</b>
* <p>
* Description: <b>UDI Barcode (RFID or other technology) string either in HRF format or AIDC format converted to base64 string.</b><br>
* Type: <b>string</b><br>
* Path: <b>Device.udi.carrierHRF, Device.udi.carrierAIDC</b><br>
* </p>
*/
@SearchParamDefinition(name="udi-carrier", path="Device.udi.carrierHRF | Device.udi.carrierAIDC", description="UDI Barcode (RFID or other technology) string either in HRF format or AIDC format converted to base64 string.", type="string" )
public static final String SP_UDI_CARRIER = "udi-carrier";
/**
* <b>Fluent Client</b> search parameter constant for <b>udi-carrier</b>
* <p>
* Description: <b>UDI Barcode (RFID or other technology) string either in HRF format or AIDC format converted to base64 string.</b><br>
* Type: <b>string</b><br>
* Path: <b>Device.udi.carrierHRF, Device.udi.carrierAIDC</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam UDI_CARRIER = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_UDI_CARRIER);
/**
* Search parameter: <b>device-name</b>
* <p>
* Description: <b>A server defined search that may match any of the string fields in the Device.udi.name or Device.type.coding.display or Device.type.text</b><br>
* Type: <b>string</b><br>
* Path: <b>Device.udi.name, Device.type.text, Device.type.coding.display</b><br>
* </p>
*/
@SearchParamDefinition(name="device-name", path="Device.udi.name | Device.type.text | Device.type.coding.display", description="A server defined search that may match any of the string fields in the Device.udi.name or Device.type.coding.display or Device.type.text", type="string" )
public static final String SP_DEVICE_NAME = "device-name";
/**
* <b>Fluent Client</b> search parameter constant for <b>device-name</b>
* <p>
* Description: <b>A server defined search that may match any of the string fields in the Device.udi.name or Device.type.coding.display or Device.type.text</b><br>
* Type: <b>string</b><br>
* Path: <b>Device.udi.name, Device.type.text, Device.type.coding.display</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam DEVICE_NAME = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_DEVICE_NAME);
/**
* Search parameter: <b>patient</b>
* <p>
* Description: <b>Patient information, if the resource is affixed to a person</b><br>
* Type: <b>reference</b><br>
* Path: <b>Device.patient</b><br>
* </p>
*/
@SearchParamDefinition(name="patient", path="Device.patient", description="Patient information, if the resource is affixed to a person", type="reference", target={Patient.class } )
public static final String SP_PATIENT = "patient";
/**
* <b>Fluent Client</b> search parameter constant for <b>patient</b>
* <p>
* Description: <b>Patient information, if the resource is affixed to a person</b><br>
* Type: <b>reference</b><br>
* Path: <b>Device.patient</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam PATIENT = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_PATIENT);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>Device:patient</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_PATIENT = new ca.uhn.fhir.model.api.Include("Device:patient").toLocked();
/**
* Search parameter: <b>organization</b>
* <p>
* Description: <b>The organization responsible for the device</b><br>
* Type: <b>reference</b><br>
* Path: <b>Device.owner</b><br>
* </p>
*/
@SearchParamDefinition(name="organization", path="Device.owner", description="The organization responsible for the device", type="reference", target={Organization.class } )
public static final String SP_ORGANIZATION = "organization";
/**
* <b>Fluent Client</b> search parameter constant for <b>organization</b>
* <p>
* Description: <b>The organization responsible for the device</b><br>
* Type: <b>reference</b><br>
* Path: <b>Device.owner</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam ORGANIZATION = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_ORGANIZATION);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>Device:organization</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_ORGANIZATION = new ca.uhn.fhir.model.api.Include("Device:organization").toLocked();
/**
* Search parameter: <b>model</b>
* <p>
* Description: <b>The model of the device</b><br>
* Type: <b>string</b><br>
* Path: <b>Device.model</b><br>
* </p>
*/
@SearchParamDefinition(name="model", path="Device.model", description="The model of the device", type="string" )
public static final String SP_MODEL = "model";
/**
* <b>Fluent Client</b> search parameter constant for <b>model</b>
* <p>
* Description: <b>The model of the device</b><br>
* Type: <b>string</b><br>
* Path: <b>Device.model</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam MODEL = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_MODEL);
/**
* Search parameter: <b>location</b>
* <p>
* Description: <b>A location, where the resource is found</b><br>
* Type: <b>reference</b><br>
* Path: <b>Device.location</b><br>
* </p>
*/
@SearchParamDefinition(name="location", path="Device.location", description="A location, where the resource is found", type="reference", target={Location.class } )
public static final String SP_LOCATION = "location";
/**
* <b>Fluent Client</b> search parameter constant for <b>location</b>
* <p>
* Description: <b>A location, where the resource is found</b><br>
* Type: <b>reference</b><br>
* Path: <b>Device.location</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam LOCATION = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_LOCATION);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>Device:location</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_LOCATION = new ca.uhn.fhir.model.api.Include("Device:location").toLocked();
/**
* Search parameter: <b>type</b>
* <p>
* Description: <b>The type of the device</b><br>
* Type: <b>token</b><br>
* Path: <b>Device.type</b><br>
* </p>
*/
@SearchParamDefinition(name="type", path="Device.type", description="The type of the device", type="token" )
public static final String SP_TYPE = "type";
/**
* <b>Fluent Client</b> search parameter constant for <b>type</b>
* <p>
* Description: <b>The type of the device</b><br>
* Type: <b>token</b><br>
* Path: <b>Device.type</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam TYPE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_TYPE);
/**
* Search parameter: <b>url</b>
* <p>
* Description: <b>Network address to contact device</b><br>
* Type: <b>uri</b><br>
* Path: <b>Device.url</b><br>
* </p>
*/
@SearchParamDefinition(name="url", path="Device.url", description="Network address to contact device", type="uri" )
public static final String SP_URL = "url";
/**
* <b>Fluent Client</b> search parameter constant for <b>url</b>
* <p>
* Description: <b>Network address to contact device</b><br>
* Type: <b>uri</b><br>
* Path: <b>Device.url</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.UriClientParam URL = new ca.uhn.fhir.rest.gclient.UriClientParam(SP_URL);
/**
* Search parameter: <b>manufacturer</b>
* <p>
* Description: <b>The manufacturer of the device</b><br>
* Type: <b>string</b><br>
* Path: <b>Device.manufacturer</b><br>
* </p>
*/
@SearchParamDefinition(name="manufacturer", path="Device.manufacturer", description="The manufacturer of the device", type="string" )
public static final String SP_MANUFACTURER = "manufacturer";
/**
* <b>Fluent Client</b> search parameter constant for <b>manufacturer</b>
* <p>
* Description: <b>The manufacturer of the device</b><br>
* Type: <b>string</b><br>
* Path: <b>Device.manufacturer</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam MANUFACTURER = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_MANUFACTURER);
/**
* Search parameter: <b>status</b>
* <p>
* Description: <b>active | inactive | entered-in-error | unknown</b><br>
* Type: <b>token</b><br>
* Path: <b>Device.status</b><br>
* </p>
*/
@SearchParamDefinition(name="status", path="Device.status", description="active | inactive | entered-in-error | unknown", type="token" )
public static final String SP_STATUS = "status";
/**
* <b>Fluent Client</b> search parameter constant for <b>status</b>
* <p>
* Description: <b>active | inactive | entered-in-error | unknown</b><br>
* Type: <b>token</b><br>
* Path: <b>Device.status</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam STATUS = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_STATUS);
}
| apache-2.0 |
gawkermedia/googleads-java-lib | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201511/DeleteLineItemCreativeAssociations.java | 2670 | /**
* DeleteLineItemCreativeAssociations.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201511;
/**
* The action used for deleting {@link LineItemCreativeAssociation}
* objects.
*/
public class DeleteLineItemCreativeAssociations extends com.google.api.ads.dfp.axis.v201511.LineItemCreativeAssociationAction implements java.io.Serializable {
public DeleteLineItemCreativeAssociations() {
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof DeleteLineItemCreativeAssociations)) return false;
DeleteLineItemCreativeAssociations other = (DeleteLineItemCreativeAssociations) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj);
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(DeleteLineItemCreativeAssociations.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "DeleteLineItemCreativeAssociations"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
askneller/DestinationSol | main/src/org/destinationsol/game/AbilityCommonConfigs.java | 2178 | /*
* Copyright 2015 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.destinationsol.game;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.JsonValue;
import org.destinationsol.TextureManager;
import org.destinationsol.files.FileManager;
import org.destinationsol.game.particle.EffectTypes;
import org.destinationsol.game.sound.SoundManager;
public class AbilityCommonConfigs {
public final AbilityCommonConfig teleport;
public final AbilityCommonConfig emWave;
public final AbilityCommonConfig unShield;
public final AbilityCommonConfig knockBack;
public final AbilityCommonConfig sloMo;
public AbilityCommonConfigs(EffectTypes effectTypes, TextureManager textureManager, GameColors cols, SoundManager soundManager) {
JsonReader r = new JsonReader();
FileHandle configFile = FileManager.getInstance().getConfigDirectory().child("abilities.json");
JsonValue node = r.parse(configFile);
teleport = AbilityCommonConfig.load(node.get("teleport"), effectTypes, textureManager, cols, configFile, soundManager);
emWave = AbilityCommonConfig.load(node.get("emWave"), effectTypes, textureManager, cols, configFile, soundManager);
unShield = AbilityCommonConfig.load(node.get("unShield"), effectTypes, textureManager, cols, configFile, soundManager);
knockBack = AbilityCommonConfig.load(node.get("knockBack"), effectTypes, textureManager, cols, configFile, soundManager);
sloMo = AbilityCommonConfig.load(node.get("sloMo"), effectTypes, textureManager, cols, configFile, soundManager);
}
}
| apache-2.0 |
summerDp/dpCms | src/main/java/org/summer/dp/cms/vo/Menu.java | 112 | package org.summer.dp.cms.vo;
/**
* DPCMS菜单
* @author 赵宝东
*
*/
public class Menu {
}
| apache-2.0 |
seeburger-ag/jakarta-slide-webdavclient | clientlib/src/java/org/apache/webdav/lib/methods/ReportMethod.java | 12130 | /*
* $Header: /home/cvs/jakarta-slide/webdavclient/clientlib/src/java/org/apache/webdav/lib/methods/ReportMethod.java,v 1.1.2.2 2004/02/05 15:51:22 mholz Exp $
* $Revision: 1.1.2.2 $
* $Date: 2004/02/05 15:51:22 $
*
* ====================================================================
*
* Copyright 1999-2002 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.webdav.lib.methods;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import org.apache.commons.httpclient.HttpConnection;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpState;
import org.apache.util.XMLPrinter;
import org.apache.webdav.lib.PropertyName;
/**
* This class implements the WebDAV REPORT Method.
*
* <P> The REPORT method retrieves properties defined on the resource
* identified by the Request-URI, if the resource does not have any internal
* members, or on the resource identified by the Request-URI and potentially
* its member resources, if the resource is a collection that has internal
* member URIs.
*
* <P> A typical request looks like this:
*
* @author Mathias Luber
*/
public class ReportMethod extends XMLResponseMethodBase
implements DepthSupport {
// -------------------------------------------------------------- Constants
/**
* Request specified properties.
*/
public static final int SUB_SET = 0;
/**
* Request of all properties name and value.
*/
public static final int ALL = 1;
public static final int LOCATE_HISTORY = 2;
public String sVersionHistory ="";
private String preloadedQuery = null;
// ----------------------------------------------------------- Constructors
/**
* Method constructor.
*/
public ReportMethod() {
}
/**
* Method constructor.
*/
public ReportMethod(String path) {
super(path);
}
/**
* Method constructor.
*/
public ReportMethod(String path, int depth) {
this(path);
setDepth(depth);
}
/**
* Method constructor.
*/
public ReportMethod(String path, Enumeration propertyNames) {
this(path);
setDepth(1);
setPropertyNames(propertyNames);
setType(SUB_SET);
}
/**
* Method constructor.
*/
public ReportMethod(String path, int depth, Enumeration propertyNames, Enumeration histUrl) {
this(path);
setDepth(depth);
setPropertyNames(propertyNames);
setHistoryURLs(histUrl);
setType(LOCATE_HISTORY);
}
/**
* Method constructor.
*/
public ReportMethod(String path, int depth, Enumeration propertyNames) {
this(path);
setDepth(depth);
setPropertyNames(propertyNames);
setType(SUB_SET);
}
public ReportMethod(String path, int depth, String sBody) {
this(path);
setDepth(depth);
setType(SUB_SET);
preloadedQuery = sBody;
}
// ----------------------------------------------------- Instance Variables
/**
* Type of the Propfind.
*/
protected int type = ALL;
/**
* Property name list.
*/
protected PropertyName[] propertyNames;
/**
* Depth.
*/
protected int depth = DEPTH_INFINITY;
/**
* The namespace abbreviation that prefixes DAV tags
*/
protected String prefix = null;
// ------------------------------------------------------------- Properties
/**
* Set a header value, redirecting attempts to set the "Depth" header to
* a {@link #setDepth} call.
*
* @param headerName Header name
* @param headerValue Header value
*/
public void setRequestHeader(String headerName, String headerValue) {
if (headerName.equalsIgnoreCase("Depth")){
int depth = -1;
if (headerValue.equals("0")){
depth = DEPTH_0;
}
if (headerValue.equals("1")){
depth = DEPTH_1;
}
else if (headerValue.equalsIgnoreCase("infinity")){
depth = DEPTH_INFINITY;
}
setDepth(depth);
}
else{
super.setRequestHeader(headerName, headerValue);
}
}
/**
* Type setter.
*
* @param type New type value
*/
public void setType(int type) {
checkNotUsed();
this.type = type;
}
/**
* Type getter.
*
* @return int type value
*/
public int getType() {
return type;
}
/**
* Depth setter.
*
* @param depth New depth value
*/
public void setDepth(int depth) {
checkNotUsed();
this.depth = depth;
}
/**
* Depth getter.
*
* @return int depth value
*/
public int getDepth() {
return depth;
}
/**
* Property names setter.
* The enumeration may contain strings with or without a namespace prefix
* but the preferred way is to provide PropertyName objects.
*
* @param propertyNames List of the property names
*/
public void setPropertyNames(Enumeration propertyNames) {
checkNotUsed();
Vector list = new Vector();
while (propertyNames.hasMoreElements()) {
Object item = propertyNames.nextElement();
if (item instanceof PropertyName)
{
list.add(item);
}
else if (item instanceof String)
{
String propertyName = (String) item;
int length = propertyName.length();
boolean found = false;
int i = 1;
while (!found && (i <= length)) {
char chr = propertyName.charAt(length - i);
if (!Character.isUnicodeIdentifierPart(chr)
&& chr!='-' && chr!='_' && chr!='.') {
found = true;
} else {
i++;
}
}
if ((i == 1) || (i >= length)) {
list.add(new PropertyName("DAV:",propertyName));
} else {
String namespace = propertyName.substring(0, length + 1 - i);
String localName = propertyName.substring(length + 1 - i);
list.add(new PropertyName(namespace,localName));
}
}
else
{
// unknown type
// ignore
}
}
this.propertyNames = (PropertyName[])list.toArray(new PropertyName[list.size()]);
}
/**
* sets History URL for locate by history Report
*/
public void setHistoryURLs(Enumeration historyURLs) {
sVersionHistory = "<D:version-history-set>";
while (historyURLs.hasMoreElements())
{
sVersionHistory += "<D:href>"+ historyURLs.nextElement().toString() + "</D:href>";
}
sVersionHistory += "</D:version-history-set>";
}
// --------------------------------------------------- WebdavMethod Methods
public String getName() {
return "REPORT";
}
public void recycle() {
super.recycle();
prefix = null;
}
/**
* Generate additional headers needed by the request.
*
* @param state State token
* @param conn The connection being used to make the request.
*/
public void addRequestHeaders(HttpState state, HttpConnection conn)
throws IOException, HttpException {
// set the default utf-8 encoding, if not already present
if (getRequestHeader("Content-Type") == null ) super.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
super.addRequestHeaders(state, conn);
switch (depth) {
case DEPTH_0:
super.setRequestHeader("Depth", "0");
break;
case DEPTH_1:
super.setRequestHeader("Depth", "1");
break;
case DEPTH_INFINITY:
super.setRequestHeader("Depth", "infinity");
break;
}
}
/**
* DAV requests that contain a body must override this function to
* generate that body.
*
* <p>The default behavior simply returns an empty body.</p>
*/
protected String generateRequestBody() {
if (preloadedQuery != null)
return preloadedQuery;
XMLPrinter printer = new XMLPrinter();
printer.writeXMLHeader();
if (type!= LOCATE_HISTORY)
printer.writeElement("D", "DAV:", "version-tree",
XMLPrinter.OPENING);
switch (type) {
case ALL:
printer.writeElement("D", "allprop", XMLPrinter.NO_CONTENT);
printer.writeElement("D", "version-tree", XMLPrinter.CLOSING);
break;
case SUB_SET:
printer.writeElement("D", "prop", XMLPrinter.OPENING);
for (int i=0 ; i<propertyNames.length ; i++)
{
String namespace = propertyNames[i].getNamespaceURI();
String localname = propertyNames[i].getLocalName();
if ("DAV:".equals(namespace)) {
printer.writeElement("D", localname, XMLPrinter.NO_CONTENT);
} else {
printer.writeElement("ZZ", namespace,localname , XMLPrinter.NO_CONTENT);
}
}
printer.writeElement("D", "prop", XMLPrinter.CLOSING);
printer.writeElement("D", "version-tree", XMLPrinter.CLOSING);
break;
case LOCATE_HISTORY:
printer.writeElement("D", "DAV:", "locate-by-history", XMLPrinter.OPENING);
printer.writeText(sVersionHistory);
printer.writeElement("D", "prop", XMLPrinter.OPENING);
for (int i=0 ; i<propertyNames.length ; i++)
{
String namespace = propertyNames[i].getNamespaceURI();
String localname = propertyNames[i].getLocalName();
if ("DAV:".equals(namespace)) {
printer.writeElement("D", localname, XMLPrinter.NO_CONTENT);
} else {
printer.writeElement("ZZ", namespace,localname , XMLPrinter.NO_CONTENT);
}
}
printer.writeElement("D", "prop", XMLPrinter.CLOSING);
printer.writeElement("D", "locate-by-history", XMLPrinter.CLOSING);
break;
}
//System.out.println(query);
return printer.toString();
}
/**
* This method returns an enumeration of URL paths. If the ReportMethod
* was sent to the URL of a collection, then there will be multiple URLs.
* The URLs are picked out of the <code><D:href></code> elements
* of the response.
*
* @return an enumeration of URL paths as Strings
*/
public Enumeration getAllResponseURLs() {
checkUsed();
return getResponseURLs().elements();
}
/**
* Returns an enumeration of <code>Property</code> objects.
*/
public Enumeration getResponseProperties(String urlPath) {
checkUsed();
Response response = (Response) getResponseHashtable().get(urlPath);
if (response != null) {
return response.getProperties();
} else {
return (new Vector()).elements();
}
}
}
| apache-2.0 |
apparentlymart/shindig | java/gadgets/src/test/java/org/apache/shindig/gadgets/rewrite/image/JPEGOptimizerTest.java | 7337 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.apache.shindig.gadgets.rewrite.image;
import org.apache.sanselan.ImageReadException;
import org.apache.shindig.gadgets.http.HttpResponse;
import org.apache.shindig.gadgets.http.HttpResponseBuilder;
import org.junit.Test;
import java.io.IOException;
/**
* Test JPEG rewiting.
*/
public class JPEGOptimizerTest extends BaseOptimizerTest {
@Test
public void testSmallJPEGToPNG() throws Exception {
// Should be significantly smaller
HttpResponse resp =
createResponse("org/apache/shindig/gadgets/rewrite/image/small.jpg", "image/jpeg");
HttpResponse rewritten = rewrite(resp);
assertEquals("image/png", rewritten.getHeader("Content-Type"));
assertTrue(rewritten.getContentLength() * 100 / resp.getContentLength() < 70);
}
@Test
public void testSmallJPEGIsNotConvertedToPNGWithJpegConversionDisabled() throws Exception {
HttpResponse resp =
createResponse("org/apache/shindig/gadgets/rewrite/image/small.jpg", "image/jpeg");
HttpResponse rewritten = rewrite(resp, getDefaultConfigWithJpegConversionDisabled());
assertEquals("image/jpeg", rewritten.getHeader("Content-Type"));
assertTrue(rewritten.getContentLength() <= resp.getContentLength());
}
@Test
public void testRetainSubsmaplingDisabled() throws Exception {
HttpResponse resp =
createResponse("org/apache/shindig/gadgets/rewrite/image/testImage444.jpg", "image/jpeg");
HttpResponse rewritten = rewrite(resp, getConfigWithRetainSampling(false, 0.70f));
JpegImageUtils.JpegImageParams params =
JpegImageUtils.getJpegImageData(rewritten.getResponse(), "");
assertTrue(rewritten.getContentLength() < resp.getContentLength());
assertEquals(JpegImageUtils.SamplingModes.YUV420, params.getSamplingMode());
}
@Test
public void testRetainSubsmaplingEnabled() throws Exception {
HttpResponse resp =
createResponse("org/apache/shindig/gadgets/rewrite/image/testImage444.jpg", "image/jpeg");
HttpResponse rewritten = rewrite(resp, getConfigWithRetainSampling(true, 0.70f));
JpegImageUtils.JpegImageParams params =
JpegImageUtils.getJpegImageData(rewritten.getResponse(), "");
assertTrue(rewritten.getContentLength() < resp.getContentLength());
assertEquals(JpegImageUtils.SamplingModes.YUV444, params.getSamplingMode());
}
@Test
public void testLargeJPEG() throws Exception {
HttpResponse resp =
createResponse("org/apache/shindig/gadgets/rewrite/image/large.jpg", "image/jpeg");
HttpResponse rewritten = rewrite(resp);
assertEquals("image/jpeg", resp.getHeader("Content-Type"));
assertTrue(rewritten.getContentLength() <= resp.getContentLength());
}
@Test
public void testLargeJPEGWithEtagAndCacheHeaders() throws Exception {
HttpResponseBuilder responseBuilder =
createResponseBuilder("org/apache/shindig/gadgets/rewrite/image/large.jpg", "image/jpeg");
responseBuilder.addHeader("ETag", "wereertret");
responseBuilder.addHeader("Cache-Control", "public, max-age=86400");
HttpResponse resp = responseBuilder.create();
HttpResponse rewritten = rewrite(resp, getConfigWithRetainSampling(false, 0.70f));
assertEquals("image/jpeg", resp.getHeader("Content-Type"));
assertEquals("public, max-age=86400", resp.getHeader("Cache-Control"));
assertNull(rewritten.getHeader("ETag"));
assertTrue(rewritten.getContentLength() < resp.getContentLength());
}
@Test(expected=Throwable.class)
public void testBadImage() throws Exception {
// Not a JPEG
HttpResponse resp =
createResponse("org/apache/shindig/gadgets/rewrite/image/bad.jpg", "image/jpeg");
rewrite(resp);
}
@Test(expected=Throwable.class)
public void xtestBadICC1() throws Exception {
// ICC section too long
HttpResponse resp = createResponse("org/apache/shindig/gadgets/rewrite/image/badicc.jpg", "image/jpeg");
rewrite(resp);
}
@Test(expected=Throwable.class)
public void testBadICC2() throws Exception {
// ICC section too long
HttpResponse resp = createResponse("org/apache/shindig/gadgets/rewrite/image/badicc2.jpg", "image/jpeg");
rewrite(resp);
}
@Test(expected=Throwable.class)
public void testBadICC3() throws Exception {
// ICC length lies
HttpResponse resp = createResponse("org/apache/shindig/gadgets/rewrite/image/badicc3.jpg", "image/jpeg");
rewrite(resp);
}
@Test
public void testBadICC4() throws Exception {
// ICC count too large
HttpResponse resp =
createResponse("org/apache/shindig/gadgets/rewrite/image/badicc4.jpg", "image/jpeg");
try {
rewrite(resp);
fail("Should have failed with OutOfMemory exception");
} catch (OutOfMemoryError oome) {
// Currently we expect an OutOfMemory error. Working on this with Sanselan
} catch (NullPointerException npe) {
// For IBM JVM, NPE is thrown, bug: SANSELAN-23
}
}
@Test
public void testBadICC5() throws Exception {
// ICC length too large. Should be readable by most VMs
HttpResponse resp =
createResponse("org/apache/shindig/gadgets/rewrite/image/2ndjpgbad.jpg", "image/jpeg");
rewrite(resp);
}
HttpResponse rewrite(HttpResponse original) throws Exception {
return rewrite(original, new OptimizerConfig());
}
HttpResponse rewrite(HttpResponse original, OptimizerConfig config)
throws IOException, ImageReadException {
HttpResponseBuilder builder = new HttpResponseBuilder(original);
new JPEGOptimizer(config, builder,
JpegImageUtils.getJpegImageData(builder.getContentBytes(), ""))
.rewrite(JPEGOptimizer.readJpeg(original.getResponse()));
return builder.create();
}
OptimizerConfig getDefaultConfigWithJpegConversionDisabled() {
OptimizerConfig defaultConfig = new OptimizerConfig();
return new OptimizerConfig(defaultConfig.getMaxInMemoryBytes(),
defaultConfig.getMaxPaletteSize(), false,
defaultConfig.getJpegCompression(), defaultConfig.getMinThresholdBytes(),
defaultConfig.getJpegHuffmanOptimization(), defaultConfig.getJpegRetainSubsampling());
}
OptimizerConfig getConfigWithRetainSampling(boolean enabled, float quality) {
OptimizerConfig defaultConfig = new OptimizerConfig();
return new OptimizerConfig(defaultConfig.getMaxInMemoryBytes(),
defaultConfig.getMaxPaletteSize(), defaultConfig.isJpegConversionAllowed(),
quality, defaultConfig.getMinThresholdBytes(), defaultConfig.getJpegHuffmanOptimization(),
enabled);
}
}
| apache-2.0 |
matedo1/pnc | messaging/src/main/java/org/jboss/pnc/messaging/DefaultMessageSender.java | 5770 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.messaging;
import org.jboss.pnc.messaging.spi.Message;
import org.jboss.pnc.messaging.spi.MessageSender;
import org.jboss.pnc.messaging.spi.MessagingRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.Collections;
import java.util.Map;
/**
* @author <a href="mailto:matejonnet@gmail.com">Matej Lazar</a>
*/
@Singleton
public class DefaultMessageSender implements MessageSender {
private Logger logger = LoggerFactory.getLogger(DefaultMessageSender.class);
@Resource(mappedName = "java:/ConnectionFactory")
protected ConnectionFactory connectionFactory;
@Resource(lookup = "java:/jms/queue/pncTopic")
protected Destination destination;
protected Connection connection;
@Override
public String getMessageSenderId() {
return DefaultMessageSender.class.getName();
}
@Override
public void init() {
try {
connection = connectionFactory.createConnection();
logger.info("JMS client ID {}.", connection.getClientID());
ExceptionListener internalExceptionListener = e -> {
logger.error("JMS exception.", e);
};
connection.setExceptionListener(internalExceptionListener);
} catch (Exception e) {
throw new MessagingRuntimeException("Failed to initialize JMS.", e);
}
}
@PreDestroy
public void destroy() {
closeConnection();
}
protected void closeConnection() {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
logger.error("Failed to close JMS connection.", e);
}
}
}
@Override
public void sendToTopic(Message message) {
sendToTopic(message.toJson());
}
@Override
public void sendToTopic(Message message, Map<String, String> headers) {
sendToTopic(message.toJson(), headers);
}
@Override
public void sendToTopic(String message) {
sendToTopic(message, Collections.EMPTY_MAP);
}
@Override
public void sendToTopic(String message, Map<String, String> headers) {
doSendMessage(message, headers);
}
/**
* @param message
* @param headers
* @throws MessagingRuntimeException
*/
protected void doSendMessage(String message, Map<String, String> headers) {
Session session = null;
MessageProducer messageProducer = null;
try {
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
messageProducer = session.createProducer(destination);
sendUsingProducer(message, headers, session, messageProducer);
} catch (Exception e) {
throw new MessagingRuntimeException(
"Cannot send the message: " + message + "; with headers: " + headers + ".",
e);
} finally {
if (session != null) {
try {
session.close();
} catch (JMSException e) {
logger.error("Cannot close JMS session.");
}
}
if (messageProducer != null) {
try {
messageProducer.close();
} catch (JMSException e) {
logger.error("Cannot close JMS messageProducer.");
}
}
}
}
protected void sendUsingProducer(
String message,
Map<String, String> headers,
Session session,
MessageProducer messageProducer) {
TextMessage textMessage;
try {
textMessage = session.createTextMessage(message);
textMessage.setStringProperty("producer", "PNC");
} catch (JMSException e) {
throw new MessagingRuntimeException(e);
}
if (textMessage == null) {
logger.error("Unable to create textMessage.");
throw new MessagingRuntimeException("Unable to create textMessage.");
}
StringBuilder headerBuilder = new StringBuilder();
headers.forEach((k, v) -> {
try {
textMessage.setStringProperty(k, v);
headerBuilder.append(k + ":" + v + "; ");
} catch (JMSException e) {
throw new MessagingRuntimeException(e);
}
});
try {
logger.debug("Sending message with headers: {}.", headerBuilder.toString());
messageProducer.send(textMessage);
} catch (JMSException e) {
throw new MessagingRuntimeException(e);
}
}
}
| apache-2.0 |
opetrovski/development | oscm-app-openstack/javasrc/org/oscm/app/openstack/data/AbstractStackRequest.java | 2862 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: Nov 29, 2013
*
*******************************************************************************/
package org.oscm.app.openstack.data;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
/**
* Build a JSON structure for sending a request to the Heat API to create a
* stack.
*/
public abstract class AbstractStackRequest {
private JSONObject request = new JSONObject();
protected void put(String key, Object value) {
if (key == null) {
throw new IllegalArgumentException(
"JSON object key must not be null!");
}
if (!(value instanceof String) && !(value instanceof JSONObject)) {
throw new IllegalArgumentException("Object type "
+ (value == null ? "NULL" : value.getClass().getName())
+ " not allowed as JSON value.");
}
try {
request.put(key, value);
} catch (JSONException e) {
// this can basically not happen
throw new IllegalArgumentException(e.getMessage());
}
}
public AbstractStackRequest withTemplateUrl(String templateUrl) {
put("template_url", templateUrl);
return this;
}
public AbstractStackRequest withTemplate(String template) {
put("template", template);
return this;
}
public AbstractStackRequest withParameters(JSONObject parameters) {
put("parameters", parameters);
return this;
}
public AbstractStackRequest withParameter(String parameterName,
String parameterValue) {
JSONObject parameters = request.optJSONObject("parameters");
if (parameters == null) {
parameters = new JSONObject();
put("parameters", parameters);
}
try {
parameters.put(parameterName, parameterValue);
} catch (JSONException e) {
// this can basically not happen
throw new IllegalArgumentException(e.getMessage());
}
return this;
}
/**
* Get the JSON text of this request. For compactness, no whitespace is
* added. If this would not result in a syntactically correct JSON text,
* then null will be returned instead.
*
* @return JSON text or null if syntax is not correct
*/
public String getJSON() {
return request.toString();
}
}
| apache-2.0 |
eic-cefet-rj/sagitarii | src/main/java/br/cefetrj/sagitarii/persistence/infra/PersistenceContext.java | 132 | package br.cefetrj.sagitarii.persistence.infra;
public class PersistenceContext {
public static final int HIBERNATE = 0;
}
| apache-2.0 |
glahiru/airavata | modules/xbaya-gui/src/main/java/org/apache/airavata/xbaya/interpretor/StandaloneNotificationSender.java | 4212 | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.xbaya.interpretor;
import java.net.URI;
import java.util.List;
import org.apache.airavata.common.utils.StringUtil;
import org.apache.airavata.workflow.model.graph.Node.NodeExecutionState;
import org.apache.airavata.workflow.model.graph.system.InputNode;
import org.apache.airavata.workflow.model.graph.system.OutputNode;
import org.apache.airavata.workflow.model.graph.util.GraphUtil;
import org.apache.airavata.workflow.model.wf.Workflow;
import org.apache.airavata.xbaya.XBayaConstants;
import org.apache.airavata.xbaya.graph.controller.NodeController;
import org.apache.airavata.xbaya.jython.lib.ServiceNotifiable;
import org.apache.airavata.xbaya.jython.lib.StandaloneServiceNotificationSender;
import org.apache.airavata.xbaya.jython.lib.WorkflowNotifiable;
import org.apache.airavata.xbaya.ui.monitor.MonitorEventHandler.NodeState;
import org.apache.axis2.addressing.EndpointReference;
import org.python.core.PyObject;
public class StandaloneNotificationSender implements WorkflowNotifiable {
private Workflow workflow;
private URI workflowID;
public StandaloneNotificationSender(String topic, Workflow workflow) {
this.workflow = workflow;
this.workflowID = URI.create(StringUtil.convertToJavaIdentifier(topic));
}
@Override
public EndpointReference getEventSink() {
return new EndpointReference(XBayaConstants.DEFAULT_BROKER_URL.toString());
}
@Override
public void workflowStarted(PyObject[] args, String[] keywords) {
List<InputNode> inputs = GraphUtil.getInputNodes(this.workflow.getGraph());
for (InputNode inputNode : inputs) {
inputNode.setState(NodeExecutionState.FINISHED);
}
}
@Override
public void workflowStarted(Object[] args, String[] keywords) {
List<InputNode> inputs = GraphUtil.getInputNodes(this.workflow.getGraph());
for (InputNode inputNode : inputs) {
inputNode.setState(NodeExecutionState.FINISHED);
}
}
@Override
public void workflowFinished(Object[] args, String[] keywords) {
List<OutputNode> outputs = GraphUtil.getOutputNodes(this.workflow.getGraph());
for (OutputNode outputNode : outputs) {
outputNode.setState(NodeExecutionState.EXECUTING);
}
}
@Override
public void sendingPartialResults(Object[] args, String[] keywords) {
// noop
}
@Override
public void workflowFinished(PyObject[] args, String[] keywords) {
List<OutputNode> outputs = GraphUtil.getOutputNodes(this.workflow.getGraph());
for (OutputNode outputNode : outputs) {
outputNode.setState(NodeExecutionState.EXECUTING);
}
}
@Override
public void workflowTerminated() {
// noop
}
@Override
public void workflowFailed(String message) {
// noop
}
@Override
public void workflowFailed(Throwable e) {
// noop
}
@Override
public void workflowFailed(String message, Throwable e) {
// noop
}
@Override
public ServiceNotifiable createServiceNotificationSender(String nodeID) {
return new StandaloneServiceNotificationSender(this.workflow, this.workflowID);
}
@Override
public void cleanup(){
}
public String getTopic() {
return this.workflowID.toASCIIString();
}
}
| apache-2.0 |
jbertram/activemq-artemis-old | artemis-protocols/artemis-openwire-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/openwire/amq/AMQConsumerBrokerExchange.java | 2416 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.core.protocol.openwire.amq;
public class AMQConsumerBrokerExchange
{
private AMQConnectionContext connectionContext;
private AMQDestination regionDestination;
private AMQSubscription subscription;
private boolean wildcard;
/**
* @return the connectionContext
*/
public AMQConnectionContext getConnectionContext()
{
return this.connectionContext;
}
/**
* @param connectionContext
* the connectionContext to set
*/
public void setConnectionContext(AMQConnectionContext connectionContext)
{
this.connectionContext = connectionContext;
}
/**
* @return the regionDestination
*/
public AMQDestination getRegionDestination()
{
return this.regionDestination;
}
/**
* @param regionDestination
* the regionDestination to set
*/
public void setRegionDestination(AMQDestination regionDestination)
{
this.regionDestination = regionDestination;
}
/**
* @return the subscription
*/
public AMQSubscription getSubscription()
{
return this.subscription;
}
/**
* @param subscription
* the subscription to set
*/
public void setSubscription(AMQSubscription subscription)
{
this.subscription = subscription;
}
/**
* @return the wildcard
*/
public boolean isWildcard()
{
return this.wildcard;
}
/**
* @param wildcard
* the wildcard to set
*/
public void setWildcard(boolean wildcard)
{
this.wildcard = wildcard;
}
}
| apache-2.0 |
ImOlli/MyWarp | src/de/imolli/mywarp/warp/WarpHologramManager.java | 7572 | package de.imolli.mywarp.warp;
import de.imolli.mywarp.MyWarp;
import de.imolli.mywarp.utils.MathUtils;
import de.imolli.mywarp.utils.SQLHandle;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerArmorStandManipulateEvent;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
public class WarpHologramManager implements Listener {
private static ArrayList<WarpHologram> holograms;
public static void init() {
holograms = new ArrayList<>();
removeOldHolograms();
try {
loadHolograms();
} catch (SQLException e) {
e.printStackTrace();
}
for (WarpHologram hologram : holograms) hologram.spawn();
}
private static void removeOldHolograms() { //TODO: Check
int i = 0;
for (World world : Bukkit.getWorlds()) {
for (Entity entity : world.getEntities()) {
if (entity.getType().equals(EntityType.ARMOR_STAND)) {
ArmorStand as = (ArmorStand) entity;
if (as.hasMetadata("mywarp")) {
as.remove();
i++;
}
}
}
}
if (i != 0) {
MyWarp.getPlugin().getLogger().log(Level.INFO, "Removed " + i + " old WarpHolograms...");
if (i > 3) {
MyWarp.getPlugin().getLogger().log(Level.INFO, "Seems like the server has crashed last time! Please shut down the server correctly. Else the MyWarp plugin can't save all data correctly.");
}
}
}
private static void loadHolograms() throws SQLException {
ResultSet rs = SQLHandle.query("Select * FROM `holograms`");
while (rs.next()) {
String[] locRaw = rs.getString("location").split(":");
Location loc = new Location(Bukkit.getWorld(locRaw[0]), Double.valueOf(locRaw[1]), Double.valueOf(locRaw[2]), Double.valueOf(locRaw[3]));
WarpHologram hologram = new WarpHologram(WarpManager.getWarp(rs.getString("warp")), loc, rs.getInt("id"));
holograms.add(hologram);
}
if (holograms.size() != 0)
MyWarp.getPlugin().getLogger().log(Level.INFO, "Loaded " + holograms.size() + " holograms from database!");
}
@EventHandler
public static void onInteract(PlayerArmorStandManipulateEvent e) {
for (WarpHologram hologram : holograms) {
if (e.getRightClicked().getEntityId() == hologram.getArmorStand().getEntityId()) {
e.setCancelled(true);
}
}
}
@EventHandler
public static void onInteract(PlayerInteractAtEntityEvent e) {
Player p = e.getPlayer();
if (e.getRightClicked().getType() == EntityType.ARMOR_STAND) {
System.out.println(e.getRightClicked().getScoreboardTags());
for (WarpHologram hologram : holograms) {
if (hologram.isSpawned(hologram.getArmorStand2())) {
if (hologram.getArmorStand2().getEntityId() == e.getRightClicked().getEntityId()) {
confirmInteract(p, hologram);
e.setCancelled(true);
}
}
if (hologram.isSpawned(hologram.getArmorStand())) {
if (hologram.getArmorStand().getEntityId() == e.getRightClicked().getEntityId()) {
confirmInteract(p, hologram);
e.setCancelled(true);
}
}
}
}
}
private static void confirmInteract(Player p, WarpHologram hologram) {
p.performCommand("warp " + hologram.getWarp().getName());
}
public static void addWarpHologram(Player p, Warp warp, Location location) {
String x = String.valueOf(MathUtils.round(location.getX(), 1));
String y = String.valueOf(MathUtils.round(location.getY(), 1));
String z = String.valueOf(MathUtils.round(location.getZ(), 1));
//TODO: Check if id throws sync errors.
int id = 0;
try {
id = SQLHandle.query("SELECT `seq` FROM `sqlite_sequence` WHERE `name` = 'holograms';").getInt("seq");
} catch (SQLException e) {
e.printStackTrace();
}
SQLHandle.update("INSERT INTO `holograms` (`warp`,`location`, `active`) VALUES ('" + warp.getName() + "','" + location.getWorld().getName() + ":" + x + ":" + y + ":" + z + "', '1')");
WarpHologram hologram = new WarpHologram(warp, location, id + 1);
hologram.spawn();
holograms.add(hologram);
}
public static void removeWarpHolograms(ArrayList<WarpHologram> hologramlist) {
if (hologramlist == null) return;
String query = "DELETE FROM `holograms` WHERE `id` = '" + hologramlist.get(0).getId() + "'";
for (WarpHologram hologram : hologramlist) {
if (hologram != null) {
if (!hologramlist.get(0).equals(hologram)) query = query + " OR `id` = '" + hologram.getId() + "'";
hologram.disappear();
holograms.remove(hologram);
}
}
System.out.println(query); //TODO: Remove debug message!
SQLHandle.update(query);
}
public static void removeWarpHologram(WarpHologram hologram) {
if (hologram == null) return;
//TODO: Was wenn das hologram nicht mehr existiert?
SQLHandle.update("DELETE FROM `holograms` WHERE `id` = '" + hologram.getId() + "'");
hologram.disappear();
holograms.remove(hologram);
}
public static void disappearAll() {
for (WarpHologram hologram : holograms) {
hologram.disappear();
}
}
public static Boolean isHologram(Entity entity) {
for (WarpHologram hologram : holograms) {
if (hologram.isSpawned(hologram.getArmorStand2())) {
if (hologram.getArmorStand2().getEntityId() == entity.getEntityId()) {
return true;
}
}
if (hologram.isSpawned(hologram.getArmorStand())) {
if (hologram.getArmorStand().getEntityId() == entity.getEntityId()) {
return true;
}
}
}
return false;
}
public static WarpHologram getHologram(Integer id) {
for (WarpHologram hologram : holograms) {
if (hologram.getId().equals(id)) {
return hologram;
}
}
return null;
}
public static WarpHologram getHologram(Entity entity) {
for (WarpHologram hologram : holograms) {
if (hologram.isSpawned(hologram.getArmorStand2())) {
if (hologram.getArmorStand2().getEntityId() == entity.getEntityId()) {
return hologram;
}
}
if (hologram.isSpawned(hologram.getArmorStand())) {
if (hologram.getArmorStand().getEntityId() == entity.getEntityId()) {
return hologram;
}
}
}
return null;
}
}
| apache-2.0 |
psadusumilli/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/rest/GridRestProcessor.java | 36851 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.rest;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.configuration.ConnectorConfiguration;
import org.apache.ignite.configuration.ConnectorMessageInterceptor;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.processors.GridProcessorAdapter;
import org.apache.ignite.internal.processors.rest.client.message.GridClientTaskResultBean;
import org.apache.ignite.internal.processors.rest.handlers.GridRestCommandHandler;
import org.apache.ignite.internal.processors.rest.handlers.cache.GridCacheCommandHandler;
import org.apache.ignite.internal.processors.rest.handlers.cluster.GridChangeStateCommandHandler;
import org.apache.ignite.internal.processors.rest.handlers.datastructures.DataStructuresCommandHandler;
import org.apache.ignite.internal.processors.rest.handlers.log.GridLogCommandHandler;
import org.apache.ignite.internal.processors.rest.handlers.query.QueryCommandHandler;
import org.apache.ignite.internal.processors.rest.handlers.task.GridTaskCommandHandler;
import org.apache.ignite.internal.processors.rest.handlers.top.GridTopologyCommandHandler;
import org.apache.ignite.internal.processors.rest.handlers.version.GridVersionCommandHandler;
import org.apache.ignite.internal.processors.rest.protocols.tcp.GridTcpRestProtocol;
import org.apache.ignite.internal.processors.rest.request.GridRestCacheRequest;
import org.apache.ignite.internal.processors.rest.request.GridRestRequest;
import org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest;
import org.apache.ignite.internal.processors.rest.request.RestQueryRequest;
import org.apache.ignite.internal.processors.security.SecurityContext;
import org.apache.ignite.internal.util.GridSpinReadWriteLock;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.typedef.C1;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.LT;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.SB;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.util.worker.GridWorker;
import org.apache.ignite.internal.util.worker.GridWorkerFuture;
import org.apache.ignite.internal.visor.util.VisorClusterGroupEmptyException;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.lang.IgniteInClosure;
import org.apache.ignite.plugin.security.AuthenticationContext;
import org.apache.ignite.plugin.security.SecurityCredentials;
import org.apache.ignite.plugin.security.SecurityException;
import org.apache.ignite.plugin.security.SecurityPermission;
import org.apache.ignite.thread.IgniteThread;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_REST_START_ON_CLIENT;
import static org.apache.ignite.internal.processors.rest.GridRestResponse.STATUS_AUTH_FAILED;
import static org.apache.ignite.internal.processors.rest.GridRestResponse.STATUS_FAILED;
import static org.apache.ignite.internal.processors.rest.GridRestResponse.STATUS_SECURITY_CHECK_FAILED;
import static org.apache.ignite.plugin.security.SecuritySubjectType.REMOTE_CLIENT;
/**
* Rest processor implementation.
*/
public class GridRestProcessor extends GridProcessorAdapter {
/** HTTP protocol class name. */
private static final String HTTP_PROTO_CLS =
"org.apache.ignite.internal.processors.rest.protocols.http.jetty.GridJettyRestProtocol";
/** Delay between sessions timeout checks. */
private static final int SES_TIMEOUT_CHECK_DELAY = 1_000;
/** Default session timout. */
private static final int DEFAULT_SES_TIMEOUT = 30_000;
/** Protocols. */
private final Collection<GridRestProtocol> protos = new ArrayList<>();
/** Command handlers. */
protected final Map<GridRestCommand, GridRestCommandHandler> handlers = new EnumMap<>(GridRestCommand.class);
/** */
private final CountDownLatch startLatch = new CountDownLatch(1);
/** Busy lock. */
private final GridSpinReadWriteLock busyLock = new GridSpinReadWriteLock();
/** Workers count. */
private final LongAdder workersCnt = new LongAdder();
/** ClientId-SessionId map. */
private final ConcurrentMap<UUID, UUID> clientId2SesId = new ConcurrentHashMap<>();
/** SessionId-Session map. */
private final ConcurrentMap<UUID, Session> sesId2Ses = new ConcurrentHashMap<>();
/** */
private final Thread sesTimeoutCheckerThread;
/** Protocol handler. */
private final GridRestProtocolHandler protoHnd = new GridRestProtocolHandler() {
@Override public GridRestResponse handle(GridRestRequest req) throws IgniteCheckedException {
return handleAsync(req).get();
}
@Override public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest req) {
return handleAsync0(req);
}
};
/** Session time to live. */
private final long sesTtl;
/**
* @param req Request.
* @return Future.
*/
private IgniteInternalFuture<GridRestResponse> handleAsync0(final GridRestRequest req) {
if (!busyLock.tryReadLock())
return new GridFinishedFuture<>(
new IgniteCheckedException("Failed to handle request (received request while stopping grid)."));
try {
final GridWorkerFuture<GridRestResponse> fut = new GridWorkerFuture<>();
workersCnt.increment();
GridWorker w = new GridWorker(ctx.igniteInstanceName(), "rest-proc-worker", log) {
@Override protected void body() {
try {
IgniteInternalFuture<GridRestResponse> res = handleRequest(req);
res.listen(new IgniteInClosure<IgniteInternalFuture<GridRestResponse>>() {
@Override public void apply(IgniteInternalFuture<GridRestResponse> f) {
try {
fut.onDone(f.get());
}
catch (IgniteCheckedException e) {
fut.onDone(e);
}
}
});
}
catch (Throwable e) {
if (e instanceof Error)
U.error(log, "Client request execution failed with error.", e);
fut.onDone(U.cast(e));
if (e instanceof Error)
throw e;
}
finally {
workersCnt.decrement();
}
}
};
fut.setWorker(w);
try {
ctx.getRestExecutorService().execute(w);
}
catch (RejectedExecutionException e) {
U.error(log, "Failed to execute worker due to execution rejection " +
"(increase upper bound on REST executor service). " +
"Will attempt to process request in the current thread instead.", e);
w.run();
}
return fut;
}
finally {
busyLock.readUnlock();
}
}
/**
* @param req Request.
* @return Future.
*/
private IgniteInternalFuture<GridRestResponse> handleRequest(final GridRestRequest req) {
if (startLatch.getCount() > 0) {
try {
startLatch.await();
}
catch (InterruptedException e) {
return new GridFinishedFuture<>(new IgniteCheckedException("Failed to handle request " +
"(protocol handler was interrupted when awaiting grid start).", e));
}
}
if (log.isDebugEnabled())
log.debug("Received request from client: " + req);
if (ctx.security().enabled()) {
Session ses;
try {
ses = session(req);
}
catch (IgniteCheckedException e) {
GridRestResponse res = new GridRestResponse(STATUS_FAILED, e.getMessage());
return new GridFinishedFuture<>(res);
}
assert ses != null;
req.clientId(ses.clientId);
req.sessionToken(U.uuidToBytes(ses.sesId));
if (log.isDebugEnabled())
log.debug("Next clientId and sessionToken were extracted according to request: " +
"[clientId="+req.clientId()+", sesTok="+Arrays.toString(req.sessionToken())+"]");
SecurityContext secCtx0 = ses.secCtx;
try {
if (secCtx0 == null)
ses.secCtx = secCtx0 = authenticate(req);
authorize(req, secCtx0);
}
catch (SecurityException e) {
assert secCtx0 != null;
GridRestResponse res = new GridRestResponse(STATUS_SECURITY_CHECK_FAILED, e.getMessage());
return new GridFinishedFuture<>(res);
}
catch (IgniteCheckedException e) {
return new GridFinishedFuture<>(new GridRestResponse(STATUS_AUTH_FAILED, e.getMessage()));
}
}
interceptRequest(req);
GridRestCommandHandler hnd = handlers.get(req.command());
IgniteInternalFuture<GridRestResponse> res = hnd == null ? null : hnd.handleAsync(req);
if (res == null)
return new GridFinishedFuture<>(
new IgniteCheckedException("Failed to find registered handler for command: " + req.command()));
return res.chain(new C1<IgniteInternalFuture<GridRestResponse>, GridRestResponse>() {
@Override public GridRestResponse apply(IgniteInternalFuture<GridRestResponse> f) {
GridRestResponse res;
boolean failed = false;
try {
res = f.get();
}
catch (Exception e) {
failed = true;
if (!X.hasCause(e, VisorClusterGroupEmptyException.class))
LT.error(log, e, "Failed to handle request: " + req.command());
if (log.isDebugEnabled())
log.debug("Failed to handle request [req=" + req + ", e=" + e + "]");
// Prepare error message:
SB sb = new SB(256);
sb.a("Failed to handle request: [req=").a(req.command());
if (req instanceof GridRestTaskRequest) {
GridRestTaskRequest tskReq = (GridRestTaskRequest)req;
sb.a(", taskName=").a(tskReq.taskName())
.a(", params=").a(tskReq.params());
}
sb.a(", err=").a(e.getMessage() != null ? e.getMessage() : e.getClass().getName()).a(']');
res = new GridRestResponse(STATUS_FAILED, sb.toString());
}
assert res != null;
if (ctx.security().enabled() && !failed)
res.sessionTokenBytes(req.sessionToken());
interceptResponse(res, req);
return res;
}
});
}
/**
* @param req Request.
* @return Not null session.
* @throws IgniteCheckedException If failed.
*/
private Session session(final GridRestRequest req) throws IgniteCheckedException {
final UUID clientId = req.clientId();
final byte[] sesTok = req.sessionToken();
while (true) {
if (F.isEmpty(sesTok) && clientId == null) {
Session ses = Session.random();
UUID oldSesId = clientId2SesId.put(ses.clientId, ses.sesId);
assert oldSesId == null : "Got an illegal state for request: " + req;
Session oldSes = sesId2Ses.put(ses.sesId, ses);
assert oldSes == null : "Got an illegal state for request: " + req;
return ses;
}
if (F.isEmpty(sesTok) && clientId != null) {
UUID sesId = clientId2SesId.get(clientId);
if (sesId == null) {
Session ses = Session.fromClientId(clientId);
if (clientId2SesId.putIfAbsent(ses.clientId, ses.sesId) != null)
continue; // Another thread already register session with the clientId.
Session prevSes = sesId2Ses.put(ses.sesId, ses);
assert prevSes == null : "Got an illegal state for request: " + req;
return ses;
}
else {
Session ses = sesId2Ses.get(sesId);
if (ses == null || !ses.touch())
continue; // Need to wait while timeout thread complete removing of timed out sessions.
return ses;
}
}
if (!F.isEmpty(sesTok) && clientId == null) {
UUID sesId = U.bytesToUuid(sesTok, 0);
Session ses = sesId2Ses.get(sesId);
if (ses == null)
throw new IgniteCheckedException("Failed to handle request - unknown session token " +
"(maybe expired session) [sesTok=" + U.byteArray2HexString(sesTok) + "]");
if (!ses.touch())
continue; // Need to wait while timeout thread complete removing of timed out sessions.
return ses;
}
if (!F.isEmpty(sesTok) && clientId != null) {
UUID sesId = clientId2SesId.get(clientId);
if (sesId == null || !sesId.equals(U.bytesToUuid(sesTok, 0)))
throw new IgniteCheckedException("Failed to handle request - unsupported case (misamatched " +
"clientId and session token) [clientId=" + clientId + ", sesTok=" +
U.byteArray2HexString(sesTok) + "]");
Session ses = sesId2Ses.get(sesId);
if (ses == null)
throw new IgniteCheckedException("Failed to handle request - unknown session token " +
"(maybe expired session) [sesTok=" + U.byteArray2HexString(sesTok) + "]");
if (!ses.touch())
continue; // Need to wait while timeout thread complete removing of timed out sessions.
return ses;
}
assert false : "Got an unreachable state.";
}
}
/**
* @param ctx Context.
*/
public GridRestProcessor(GridKernalContext ctx) {
super(ctx);
long sesExpTime0;
String sesExpTime = null;
try {
sesExpTime = System.getProperty(IgniteSystemProperties.IGNITE_REST_SESSION_TIMEOUT);
if (sesExpTime != null)
sesExpTime0 = Long.valueOf(sesExpTime) * 1000;
else
sesExpTime0 = DEFAULT_SES_TIMEOUT;
}
catch (NumberFormatException ignore) {
U.warn(log, "Failed parsing IGNITE_REST_SESSION_TIMEOUT system variable [IGNITE_REST_SESSION_TIMEOUT="
+ sesExpTime + "]");
sesExpTime0 = DEFAULT_SES_TIMEOUT;
}
sesTtl = sesExpTime0;
sesTimeoutCheckerThread = new IgniteThread(ctx.igniteInstanceName(), "session-timeout-worker",
new GridWorker(ctx.igniteInstanceName(), "session-timeout-worker", log) {
@Override protected void body() throws InterruptedException {
while (!isCancelled()) {
Thread.sleep(SES_TIMEOUT_CHECK_DELAY);
for (Map.Entry<UUID, Session> e : sesId2Ses.entrySet()) {
Session ses = e.getValue();
if (ses.isTimedOut(sesTtl)) {
sesId2Ses.remove(ses.sesId, ses);
clientId2SesId.remove(ses.clientId, ses.sesId);
}
}
}
}
});
}
/** {@inheritDoc} */
@Override public void start() throws IgniteCheckedException {
if (isRestEnabled()) {
if (notStartOnClient()) {
U.quietAndInfo(log, "REST protocols do not start on client node. " +
"To start the protocols on client node set '-DIGNITE_REST_START_ON_CLIENT=true' system property.");
return;
}
// Register handlers.
addHandler(new GridCacheCommandHandler(ctx));
addHandler(new GridTaskCommandHandler(ctx));
addHandler(new GridTopologyCommandHandler(ctx));
addHandler(new GridVersionCommandHandler(ctx));
addHandler(new DataStructuresCommandHandler(ctx));
addHandler(new QueryCommandHandler(ctx));
addHandler(new GridLogCommandHandler(ctx));
addHandler(new GridChangeStateCommandHandler(ctx));
// Start protocols.
startTcpProtocol();
startHttpProtocol();
for (GridRestProtocol proto : protos) {
Collection<IgniteBiTuple<String, Object>> props = proto.getProperties();
if (props != null) {
for (IgniteBiTuple<String, Object> p : props) {
String key = p.getKey();
if (key == null)
continue;
if (ctx.hasNodeAttribute(key))
throw new IgniteCheckedException(
"Node attribute collision for attribute [processor=GridRestProcessor, attr=" + key + ']');
ctx.addNodeAttribute(key, p.getValue());
}
}
}
}
}
/**
* @return {@code True} if rest processor should not start on client node.
*/
private boolean notStartOnClient() {
return ctx.clientNode() && !IgniteSystemProperties.getBoolean(IGNITE_REST_START_ON_CLIENT);
}
/** {@inheritDoc} */
@Override public void onKernalStart(boolean active) throws IgniteCheckedException {
if (isRestEnabled()) {
for (GridRestProtocol proto : protos)
proto.onKernalStart();
sesTimeoutCheckerThread.setDaemon(true);
sesTimeoutCheckerThread.start();
startLatch.countDown();
if (log.isDebugEnabled())
log.debug("REST processor started.");
}
}
/** {@inheritDoc} */
@SuppressWarnings("BusyWait")
@Override public void onKernalStop(boolean cancel) {
if (isRestEnabled()) {
busyLock.writeLock();
boolean interrupted = Thread.interrupted();
while (workersCnt.sum() != 0) {
try {
Thread.sleep(200);
}
catch (InterruptedException ignored) {
interrupted = true;
}
}
U.interrupt(sesTimeoutCheckerThread);
if (interrupted)
Thread.currentThread().interrupt();
for (GridRestProtocol proto : protos)
proto.stop();
// Safety.
startLatch.countDown();
if (log.isDebugEnabled())
log.debug("REST processor stopped.");
}
}
/**
* Applies {@link ConnectorMessageInterceptor}
* from {@link ConnectorConfiguration#getMessageInterceptor()} ()}
* to all user parameters in the request.
*
* @param req Client request.
*/
private void interceptRequest(GridRestRequest req) {
ConnectorMessageInterceptor interceptor = config().getMessageInterceptor();
if (interceptor == null)
return;
if (req instanceof GridRestCacheRequest) {
GridRestCacheRequest req0 = (GridRestCacheRequest) req;
req0.key(interceptor.onReceive(req0.key()));
req0.value(interceptor.onReceive(req0.value()));
req0.value2(interceptor.onReceive(req0.value2()));
Map<Object, Object> oldVals = req0.values();
if (oldVals != null) {
Map<Object, Object> newVals = U.newHashMap(oldVals.size());
for (Map.Entry<Object, Object> e : oldVals.entrySet())
newVals.put(interceptor.onReceive(e.getKey()), interceptor.onReceive(e.getValue()));
req0.values(U.sealMap(newVals));
}
}
else if (req instanceof GridRestTaskRequest) {
GridRestTaskRequest req0 = (GridRestTaskRequest) req;
List<Object> oldParams = req0.params();
if (oldParams != null) {
Collection<Object> newParams = new ArrayList<>(oldParams.size());
for (Object o : oldParams)
newParams.add(interceptor.onReceive(o));
req0.params(U.sealList(newParams));
}
}
}
/**
* Applies {@link ConnectorMessageInterceptor} from
* {@link ConnectorConfiguration#getMessageInterceptor()}
* to all user objects in the response.
*
* @param res Response.
* @param req Request.
*/
private void interceptResponse(GridRestResponse res, GridRestRequest req) {
ConnectorMessageInterceptor interceptor = config().getMessageInterceptor();
if (interceptor != null && res.getResponse() != null) {
switch (req.command()) {
case CACHE_CONTAINS_KEYS:
case CACHE_CONTAINS_KEY:
case CACHE_GET:
case CACHE_GET_ALL:
case CACHE_PUT:
case CACHE_ADD:
case CACHE_PUT_ALL:
case CACHE_REMOVE:
case CACHE_REMOVE_ALL:
case CACHE_CLEAR:
case CACHE_REPLACE:
case ATOMIC_INCREMENT:
case ATOMIC_DECREMENT:
case CACHE_CAS:
case CACHE_APPEND:
case CACHE_PREPEND:
res.setResponse(interceptSendObject(res.getResponse(), interceptor));
break;
case EXE:
if (res.getResponse() instanceof GridClientTaskResultBean) {
GridClientTaskResultBean taskRes = (GridClientTaskResultBean)res.getResponse();
taskRes.setResult(interceptor.onSend(taskRes.getResult()));
}
break;
default:
break;
}
}
} /**
* Applies interceptor to a response object.
* Specially handler {@link Map} and {@link Collection} responses.
*
* @param obj Response object.
* @param interceptor Interceptor to apply.
* @return Intercepted object.
*/
private static Object interceptSendObject(Object obj, ConnectorMessageInterceptor interceptor) {
if (obj instanceof Map) {
Map<Object, Object> original = (Map<Object, Object>)obj;
Map<Object, Object> m = new HashMap<>();
for (Map.Entry e : original.entrySet())
m.put(interceptor.onSend(e.getKey()), interceptor.onSend(e.getValue()));
return m;
}
else if (obj instanceof Collection) {
Collection<Object> original = (Collection<Object>)obj;
Collection<Object> c = new ArrayList<>(original.size());
for (Object e : original)
c.add(interceptor.onSend(e));
return c;
}
else
return interceptor.onSend(obj);
}
/**
* Authenticates remote client.
*
* @param req Request to authenticate.
* @return Authentication subject context.
* @throws IgniteCheckedException If authentication failed.
*/
private SecurityContext authenticate(GridRestRequest req) throws IgniteCheckedException {
assert req.clientId() != null;
AuthenticationContext authCtx = new AuthenticationContext();
authCtx.subjectType(REMOTE_CLIENT);
authCtx.subjectId(req.clientId());
authCtx.nodeAttributes(Collections.<String, Object>emptyMap());
SecurityCredentials cred;
if (req.credentials() instanceof SecurityCredentials)
cred = (SecurityCredentials)req.credentials();
else if (req.credentials() instanceof String) {
String credStr = (String)req.credentials();
int idx = credStr.indexOf(':');
cred = idx >= 0 && idx < credStr.length() ?
new SecurityCredentials(credStr.substring(0, idx), credStr.substring(idx + 1)) :
new SecurityCredentials(credStr, null);
}
else {
cred = new SecurityCredentials();
cred.setUserObject(req.credentials());
}
authCtx.address(req.address());
authCtx.credentials(cred);
SecurityContext subjCtx = ctx.security().authenticate(authCtx);
if (subjCtx == null) {
if (req.credentials() == null)
throw new IgniteCheckedException("Failed to authenticate remote client (secure session SPI not set?): " + req);
else
throw new IgniteCheckedException("Failed to authenticate remote client (invalid credentials?): " + req);
}
return subjCtx;
}
/**
* @param req REST request.
* @param sCtx Security context.
* @throws SecurityException If authorization failed.
*/
private void authorize(GridRestRequest req, SecurityContext sCtx) throws SecurityException {
SecurityPermission perm = null;
String name = null;
switch (req.command()) {
case CACHE_GET:
case CACHE_CONTAINS_KEY:
case CACHE_CONTAINS_KEYS:
case CACHE_GET_ALL:
perm = SecurityPermission.CACHE_READ;
name = ((GridRestCacheRequest)req).cacheName();
break;
case EXECUTE_SQL_QUERY:
case EXECUTE_SQL_FIELDS_QUERY:
case EXECUTE_SCAN_QUERY:
case CLOSE_SQL_QUERY:
case FETCH_SQL_QUERY:
perm = SecurityPermission.CACHE_READ;
name = ((RestQueryRequest)req).cacheName();
break;
case CACHE_PUT:
case CACHE_ADD:
case CACHE_PUT_ALL:
case CACHE_REPLACE:
case CACHE_CAS:
case CACHE_APPEND:
case CACHE_PREPEND:
case CACHE_GET_AND_PUT:
case CACHE_GET_AND_REPLACE:
case CACHE_GET_AND_PUT_IF_ABSENT:
case CACHE_PUT_IF_ABSENT:
case CACHE_REPLACE_VALUE:
perm = SecurityPermission.CACHE_PUT;
name = ((GridRestCacheRequest)req).cacheName();
break;
case CACHE_REMOVE:
case CACHE_REMOVE_ALL:
case CACHE_CLEAR:
case CACHE_GET_AND_REMOVE:
case CACHE_REMOVE_VALUE:
perm = SecurityPermission.CACHE_REMOVE;
name = ((GridRestCacheRequest)req).cacheName();
break;
case EXE:
case RESULT:
perm = SecurityPermission.TASK_EXECUTE;
name = ((GridRestTaskRequest)req).taskName();
break;
case GET_OR_CREATE_CACHE:
case DESTROY_CACHE:
perm = SecurityPermission.ADMIN_CACHE;
name = ((GridRestCacheRequest)req).cacheName();
break;
case CACHE_METRICS:
case CACHE_SIZE:
case CACHE_METADATA:
case TOPOLOGY:
case NODE:
case VERSION:
case NOOP:
case QUIT:
case ATOMIC_INCREMENT:
case ATOMIC_DECREMENT:
case NAME:
case LOG:
case CLUSTER_CURRENT_STATE:
case CLUSTER_ACTIVE:
case CLUSTER_INACTIVE:
break;
default:
throw new AssertionError("Unexpected command: " + req.command());
}
if (perm != null)
ctx.security().authorize(name, perm, sCtx);
}
/**
*
* @return Whether or not REST is enabled.
*/
private boolean isRestEnabled() {
return !ctx.config().isDaemon() && ctx.config().getConnectorConfiguration() != null;
}
/**
* @param hnd Command handler.
*/
private void addHandler(GridRestCommandHandler hnd) {
assert !handlers.containsValue(hnd);
if (log.isDebugEnabled())
log.debug("Added REST command handler: " + hnd);
for (GridRestCommand cmd : hnd.supportedCommands()) {
assert !handlers.containsKey(cmd) : cmd;
handlers.put(cmd, hnd);
}
}
/**
* Starts TCP protocol.
*
* @throws IgniteCheckedException In case of error.
*/
private void startTcpProtocol() throws IgniteCheckedException {
startProtocol(new GridTcpRestProtocol(ctx));
}
/**
* Starts HTTP protocol if it exists on classpath.
*
* @throws IgniteCheckedException In case of error.
*/
private void startHttpProtocol() throws IgniteCheckedException {
try {
Class<?> cls = Class.forName(HTTP_PROTO_CLS);
Constructor<?> ctor = cls.getConstructor(GridKernalContext.class);
GridRestProtocol proto = (GridRestProtocol)ctor.newInstance(ctx);
startProtocol(proto);
}
catch (ClassNotFoundException ignored) {
if (log.isDebugEnabled())
log.debug("Failed to initialize HTTP REST protocol (consider adding ignite-rest-http " +
"module to classpath).");
}
catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new IgniteCheckedException("Failed to initialize HTTP REST protocol.", e);
}
}
/**
* @return Client configuration.
*/
private ConnectorConfiguration config() {
return ctx.config().getConnectorConfiguration();
}
/**
* @param proto Protocol.
* @throws IgniteCheckedException If protocol initialization failed.
*/
private void startProtocol(GridRestProtocol proto) throws IgniteCheckedException {
assert proto != null;
assert !protos.contains(proto);
protos.add(proto);
proto.start(protoHnd);
if (log.isDebugEnabled())
log.debug("Added REST protocol: " + proto);
}
/** {@inheritDoc} */
@Override public void printMemoryStats() {
X.println(">>>");
X.println(">>> REST processor memory stats [igniteInstanceName=" + ctx.igniteInstanceName() + ']');
X.println(">>> protosSize: " + protos.size());
X.println(">>> handlersSize: " + handlers.size());
}
/**
* Session.
*/
private static class Session {
/** Expiration flag. It's a final state of lastToucnTime. */
private static final Long TIMEDOUT_FLAG = 0L;
/** Client id. */
private final UUID clientId;
/** Session token id. */
private final UUID sesId;
/**
* Time when session is used last time.
* If this time was set at TIMEDOUT_FLAG, then it should never be changed.
*/
private final AtomicLong lastTouchTime = new AtomicLong(U.currentTimeMillis());
/** Security context. */
private volatile SecurityContext secCtx;
/**
* @param clientId Client ID.
* @param sesId session ID.
*/
private Session(UUID clientId, UUID sesId) {
this.clientId = clientId;
this.sesId = sesId;
}
/**
* Static constructor.
*
* @return New session instance with random client ID and random session ID.
*/
static Session random() {
return new Session(UUID.randomUUID(), UUID.randomUUID());
}
/**
* Static constructor.
*
* @param clientId Client ID.
* @return New session instance with given client ID and random session ID.
*/
static Session fromClientId(UUID clientId) {
return new Session(clientId, UUID.randomUUID());
}
/**
* Static constructor.
*
* @param sesTokId Session token ID.
* @return New session instance with random client ID and given session ID.
*/
static Session fromSessionToken(UUID sesTokId) {
return new Session(UUID.randomUUID(), sesTokId);
}
/**
* Checks expiration of session and if expired then sets TIMEDOUT_FLAG.
*
* @param sesTimeout Session timeout.
* @return <code>True</code> if expired.
* @see #touch()
*/
boolean isTimedOut(long sesTimeout) {
long time0 = lastTouchTime.get();
if (time0 == TIMEDOUT_FLAG)
return true;
return U.currentTimeMillis() - time0 > sesTimeout && lastTouchTime.compareAndSet(time0, TIMEDOUT_FLAG);
}
/**
* Checks whether session at expired state (EXPIRATION_FLAG) or not, if not then tries to update last touch time.
*
* @return {@code False} if session timed out (not successfully touched).
* @see #isTimedOut(long)
*/
boolean touch() {
while (true) {
long time0 = lastTouchTime.get();
if (time0 == TIMEDOUT_FLAG)
return false;
boolean success = lastTouchTime.compareAndSet(time0, U.currentTimeMillis());
if (success)
return true;
}
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Session))
return false;
Session ses = (Session)o;
if (clientId != null ? !clientId.equals(ses.clientId) : ses.clientId != null)
return false;
if (sesId != null ? !sesId.equals(ses.sesId) : ses.sesId != null)
return false;
return true;
}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = clientId != null ? clientId.hashCode() : 0;
res = 31 * res + (sesId != null ? sesId.hashCode() : 0);
return res;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(Session.class, this);
}
}
}
| apache-2.0 |
wenzhucjy/tomcat_source | tomcat-8.0.9-sourcecode/java/org/apache/tomcat/jni/Procattr.java | 7439 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.jni;
/** Procattr
*
* @author Mladen Turk
*/
public class Procattr {
/**
* Create and initialize a new procattr variable
* @param cont The pool to use
* @return The newly created procattr.
*/
public static native long create(long cont)
throws Error;
/**
* Determine if any of stdin, stdout, or stderr should be linked to pipes
* when starting a child process.
* @param attr The procattr we care about.
* @param in Should stdin be a pipe back to the parent?
* @param out Should stdout be a pipe back to the parent?
* @param err Should stderr be a pipe back to the parent?
*/
public static native int ioSet(long attr, int in, int out, int err);
/**
* Set the child_in and/or parent_in values to existing apr_file_t values.
* <br />
* This is NOT a required initializer function. This is
* useful if you have already opened a pipe (or multiple files)
* that you wish to use, perhaps persistently across multiple
* process invocations - such as a log file. You can save some
* extra function calls by not creating your own pipe since this
* creates one in the process space for you.
* @param attr The procattr we care about.
* @param in apr_file_t value to use as child_in. Must be a valid file.
* @param parent apr_file_t value to use as parent_in. Must be a valid file.
*/
public static native int childInSet(long attr, long in, long parent);
/**
* Set the child_out and parent_out values to existing apr_file_t values.
* <br />
* This is NOT a required initializer function. This is
* useful if you have already opened a pipe (or multiple files)
* that you wish to use, perhaps persistently across multiple
* process invocations - such as a log file.
* @param attr The procattr we care about.
* @param out apr_file_t value to use as child_out. Must be a valid file.
* @param parent apr_file_t value to use as parent_out. Must be a valid file.
*/
public static native int childOutSet(long attr, long out, long parent);
/**
* Set the child_err and parent_err values to existing apr_file_t values.
* <br />
* This is NOT a required initializer function. This is
* useful if you have already opened a pipe (or multiple files)
* that you wish to use, perhaps persistently across multiple
* process invocations - such as a log file.
* @param attr The procattr we care about.
* @param err apr_file_t value to use as child_err. Must be a valid file.
* @param parent apr_file_t value to use as parent_err. Must be a valid file.
*/
public static native int childErrSet(long attr, long err, long parent);
/**
* Set which directory the child process should start executing in.
* @param attr The procattr we care about.
* @param dir Which dir to start in. By default, this is the same dir as
* the parent currently resides in, when the createprocess call
* is made.
*/
public static native int dirSet(long attr, String dir);
/**
* Set what type of command the child process will call.
* @param attr The procattr we care about.
* @param cmd The type of command. One of:
* <PRE>
* APR_SHELLCMD -- Anything that the shell can handle
* APR_PROGRAM -- Executable program (default)
* APR_PROGRAM_ENV -- Executable program, copy environment
* APR_PROGRAM_PATH -- Executable program on PATH, copy env
* </PRE>
*/
public static native int cmdtypeSet(long attr, int cmd);
/**
* Determine if the child should start in detached state.
* @param attr The procattr we care about.
* @param detach Should the child start in detached state? Default is no.
*/
public static native int detachSet(long attr, int detach);
/**
* Specify that apr_proc_create() should do whatever it can to report
* failures to the caller of apr_proc_create(), rather than find out in
* the child.
* @param attr The procattr describing the child process to be created.
* @param chk Flag to indicate whether or not extra work should be done
* to try to report failures to the caller.
* <br />
* This flag only affects apr_proc_create() on platforms where
* fork() is used. This leads to extra overhead in the calling
* process, but that may help the application handle such
* errors more gracefully.
*/
public static native int errorCheckSet(long attr, int chk);
/**
* Determine if the child should start in its own address space or using the
* current one from its parent
* @param attr The procattr we care about.
* @param addrspace Should the child start in its own address space? Default
* is no on NetWare and yes on other platforms.
*/
public static native int addrspaceSet(long attr, int addrspace);
/**
* Specify an error function to be called in the child process if APR
* encounters an error in the child prior to running the specified program.
* @param attr The procattr describing the child process to be created.
* @param pool The the pool to use.
* @param o The Object to call in the child process.
* <br />
* At the present time, it will only be called from apr_proc_create()
* on platforms where fork() is used. It will never be called on other
* platforms, on those platforms apr_proc_create() will return the error
* in the parent process rather than invoke the callback in the now-forked
* child process.
*/
public static native void errfnSet(long attr, long pool, Object o);
/**
* Set the username used for running process
* @param attr The procattr we care about.
* @param username The username used
* @param password User password if needed. Password is needed on WIN32
* or any other platform having
* APR_PROCATTR_USER_SET_REQUIRES_PASSWORD set.
*/
public static native int userSet(long attr, String username, String password);
/**
* Set the group used for running process
* @param attr The procattr we care about.
* @param groupname The group name used
*/
public static native int groupSet(long attr, String groupname);
}
| apache-2.0 |
HuangLS/neo4j | community/kernel/src/main/java/org/neo4j/kernel/impl/store/AbstractStore.java | 3734 | /*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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.neo4j.kernel.impl.store;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.neo4j.io.pagecache.PageCache;
import org.neo4j.io.pagecache.PageCursor;
import org.neo4j.io.pagecache.PagedFile;
import org.neo4j.kernel.IdGeneratorFactory;
import org.neo4j.kernel.IdType;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.store.id.IdGenerator;
import org.neo4j.kernel.impl.store.record.Record;
import org.neo4j.logging.LogProvider;
/**
* An abstract representation of a store. A store is a file that contains
* records. Each record has a fixed size (<CODE>getRecordSize()</CODE>) so
* the position for a record can be calculated by
* <CODE>id * getRecordSize()</CODE>.
* <p>
* A store has an {@link IdGenerator} managing the records that are free or in
* use.
*/
public abstract class AbstractStore extends CommonAbstractStore
{
public AbstractStore(
File fileName,
Config conf,
IdType idType,
IdGeneratorFactory idGeneratorFactory,
PageCache pageCache,
LogProvider logProvider )
{
super( fileName, conf, idType, idGeneratorFactory, pageCache, logProvider );
}
/**
* Returns the fixed size of each record in this store.
*
* @return The record size
*/
public abstract int getRecordSize();
@Override
protected void readAndVerifyBlockSize() throws IOException
{
// record size is fixed for non-dynamic stores, so nothing to do here
}
@Override
protected boolean isInUse( byte inUseByte )
{
return (inUseByte & 0x1) == Record.IN_USE.intValue();
}
@Override
protected void initialiseNewStoreFile( PagedFile file ) throws IOException
{
ByteBuffer headerRecord = createHeaderRecord();
if ( headerRecord != null )
{
try ( PageCursor pageCursor = file.io( 0, PagedFile.PF_EXCLUSIVE_LOCK ) )
{
if ( pageCursor.next() )
{
do
{
pageCursor.setOffset( 0 );
pageCursor.putBytes( headerRecord.array() );
}
while ( pageCursor.shouldRetry() );
}
}
}
File idFileName = new File( storageFileName.getPath() + ".id" );
idGeneratorFactory.create( idFileName, 0, true );
if ( headerRecord != null )
{
IdGenerator idGenerator = idGeneratorFactory.open( idFileName, 1, idType, 0 );
initialiseNewIdGenerator( idGenerator );
idGenerator.close();
}
}
protected void initialiseNewIdGenerator( IdGenerator idGenerator )
{
idGenerator.nextId(); // reserve first for blockSize
}
protected ByteBuffer createHeaderRecord()
{
return null;
}
}
| apache-2.0 |
ctc-g/sinavi-jfw | web/jfw-web-core/src/main/java/jp/co/ctc_g/jse/core/framework/PostBackAroundAdvice.java | 3251 | /*
* Copyright (c) 2013 ITOCHU Techno-Solutions Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.co.ctc_g.jse.core.framework;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
/**
* <p>
* このクラスは{@link PostBack.Action} によって注釈されたコントローラのハンドラ・メソッドのアドバイスとして機能し、
* {@link PostBack.Action} 注釈の属性として定義されたポストバック・アクションを実行します。<br/>
* </p>
*
* @author ITOCHU Techno-Solutions corporation.
*/
@Aspect
public class PostBackAroundAdvice {
/**
* デフォルトコンストラクタです。
*/
public PostBackAroundAdvice() {}
/**
* ポストバックアクションを実行するためのインターセプタです。
* @param joinPoint ポイント
* @return 実行結果
* @throws Throwable 予期しない例外
*/
@Around("execution(@org.springframework.web.bind.annotation.RequestMapping * *(..)) && (execution(@jp.co.ctc_g.jse.core.framework.PostBack.Action * *(..)) || execution(@jp.co.ctc_g.jse.core.framework.PostBack.Action.List * *(..)))")
public Object processPostBackAction(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
Object model = null;
try {
PostBackManager manager = PostBackManager.getCurrentPostBackManager();
Class<?> modelAttributeType = manager.getModelAttributeType();
if (modelAttributeType != null) {
for (Object o : joinPoint.getArgs()) {
if (o.getClass().getName().equals(modelAttributeType.getName())) {
model = o;
}
}
}
result = joinPoint.proceed();
} catch (Throwable t) {
result = build(t, model);
}
return result;
}
/**
* 例外に設定されているエラーメッセージをそれぞれのスコープに格納し、
* PostBack.Actionアノテーションで指定されている遷移先の情報を取得します。
* @param t 例外
* @param model モデルオブジェクト
* @return 遷移先
* @throws Throwable 予期しない例外
*/
protected Object build(Throwable t, Object model) throws Throwable {
if (PostBackManager.isPostBackTargetException(t)) {
PostBackManager.save(new PostBack(t));
PostBackManager.saveMessage(t);
return PostBackManager.buildUri(t, model, true);
} else {
throw t;
}
}
}
| apache-2.0 |
domaframework/doma | doma-processor/src/test/java/org/seasar/doma/internal/apt/processor/entity/NotTopLevelEntity.java | 164 | package org.seasar.doma.internal.apt.processor.entity;
import org.seasar.doma.Entity;
public class NotTopLevelEntity {
@Entity
public static class Hoge {}
}
| apache-2.0 |
tfisher1226/ARIES | nam/nam-engine/src/main/java/nam/data/src/test/java/DaoITGenerator.java | 274 | package nam.data.src.test.java;
import aries.codegen.AbstractBeanGenerator;
import aries.generation.engine.GenerationContext;
public class DaoITGenerator extends AbstractBeanGenerator {
public DaoITGenerator(GenerationContext context) {
this.context = context;
}
}
| apache-2.0 |
SAGROUP2/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/WikiDrawerLayout.java | 3292 | package org.wikipedia.views;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.FixedDrawerLayout;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import org.wikipedia.util.log.L;
import java.lang.reflect.Field;
/**
* A thin wrapper around {@link FixedDrawerLayout} with additional functionality:
* <ul>
* <li>Expose enable state.</li>
* <li>Expose drag margin width state.</li>
* </ul>
*/
public class WikiDrawerLayout extends FixedDrawerLayout {
public WikiDrawerLayout(Context context) {
this(context, null);
}
public WikiDrawerLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WikiDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public boolean getSlidingEnabled(int gravity) {
return getDrawerLockMode(gravity) == DrawerLayout.LOCK_MODE_UNLOCKED;
}
public void setSlidingEnabled(boolean enable) {
if (enable) {
this.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
} else {
this.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
}
/**
* Set the drag margin width.
* @param width Width in pixels.
*/
public void setDragEdgeWidth(final int width) {
this.post(new Runnable() {
@Override
public void run() {
try {
// Use a little bit of reflection to set a private member in DrawerLayout that extends the
// "drag edge" from which the drawer can be pulled by the user.
// A bit hacky, but what are you gonna do...
View pullOutView = getChildAt(1);
int absGravity = GravityCompat.getAbsoluteGravity(((LayoutParams)pullOutView.getLayoutParams()).gravity,
ViewCompat.getLayoutDirection(pullOutView));
// Determine whether to modify the left or right dragger, based on RTL/LTR orientation
@SuppressLint("RtlHardcoded")
Field mDragger = (absGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT
? WikiDrawerLayout.this.getClass().getSuperclass().getSuperclass().getDeclaredField("mLeftDragger")
: WikiDrawerLayout.this.getClass().getSuperclass().getSuperclass().getDeclaredField("mRightDragger");
mDragger.setAccessible(true);
ViewDragHelper dragHelper = (ViewDragHelper) mDragger.get(WikiDrawerLayout.this);
Field edgeWidth = dragHelper.getClass().getDeclaredField("mEdgeSize");
edgeWidth.setAccessible(true);
edgeWidth.setInt(dragHelper, width);
} catch (Exception e) {
L.e("Setting the draggable zone for the drawer failed!", e);
}
}
});
}
}
| apache-2.0 |
leopardoooo/cambodia | ycsoft-lib/src/main/java/com/ycsoft/beans/core/cust/CCustDeviceBuymodeProp.java | 3591 | /**
* CCustDeviceBuymodeProp.java 2012/08/13
*/
package com.ycsoft.beans.core.cust;
import java.io.Serializable ;
import java.util.Date ;
import com.ycsoft.daos.config.POJO ;
/**
* CCustDeviceBuymodeProp -> C_CUST_DEVICE_BUYMODE_PROP mapping
*/
@POJO(
tn="C_CUST_DEVICE_BUYMODE_PROP",
sn="",
pk="")
public class CCustDeviceBuymodeProp implements Serializable {
// CCustDeviceBuymodeProp all properties
/**
*
*/
private static final long serialVersionUID = -4093559525443738169L;
private Integer done_code ;
private String cust_id ;
private String device_type ;
private String old_device_id ;
private String old_device_code ;
private String old_buy_mode ;
private String new_device_id ;
private String new_device_code ;
private String new_buy_mode ;
private Date create_time ;
private String optr_id ;
private String county_id ;
private String area_id ;
/**
* default empty constructor
*/
public CCustDeviceBuymodeProp() {}
// done_code getter and setter
public Integer getDone_code(){
return this.done_code ;
}
public void setDone_code(Integer done_code){
this.done_code = done_code ;
}
// cust_id getter and setter
public String getCust_id(){
return this.cust_id ;
}
public void setCust_id(String cust_id){
this.cust_id = cust_id ;
}
// device_type getter and setter
public String getDevice_type(){
return this.device_type ;
}
public void setDevice_type(String device_type){
this.device_type = device_type ;
}
// old_device_id getter and setter
public String getOld_device_id(){
return this.old_device_id ;
}
public void setOld_device_id(String old_device_id){
this.old_device_id = old_device_id ;
}
// old_device_code getter and setter
public String getOld_device_code(){
return this.old_device_code ;
}
public void setOld_device_code(String old_device_code){
this.old_device_code = old_device_code ;
}
// old_buy_mode getter and setter
public String getOld_buy_mode(){
return this.old_buy_mode ;
}
public void setOld_buy_mode(String old_buy_mode){
this.old_buy_mode = old_buy_mode ;
}
// new_device_id getter and setter
public String getNew_device_id(){
return this.new_device_id ;
}
public void setNew_device_id(String new_device_id){
this.new_device_id = new_device_id ;
}
// new_device_code getter and setter
public String getNew_device_code(){
return this.new_device_code ;
}
public void setNew_device_code(String new_device_code){
this.new_device_code = new_device_code ;
}
// new_buy_mode getter and setter
public String getNew_buy_mode(){
return this.new_buy_mode ;
}
public void setNew_buy_mode(String new_buy_mode){
this.new_buy_mode = new_buy_mode ;
}
// create_time getter and setter
public Date getCreate_time(){
return this.create_time ;
}
public void setCreate_time(Date create_time){
this.create_time = create_time ;
}
// optr_id getter and setter
public String getOptr_id(){
return this.optr_id ;
}
public void setOptr_id(String optr_id){
this.optr_id = optr_id ;
}
// county_id getter and setter
public String getCounty_id(){
return this.county_id ;
}
public void setCounty_id(String county_id){
this.county_id = county_id ;
}
// area_id getter and setter
public String getArea_id(){
return this.area_id ;
}
public void setArea_id(String area_id){
this.area_id = area_id ;
}
} | apache-2.0 |
ceylon/ceylon | cmr/impl/src/main/java/org/eclipse/ceylon/cmr/impl/FlatRepositoryBuilder.java | 2163 | /********************************************************************************
* Copyright (c) 2011-2017 Red Hat Inc. and/or its affiliates and others
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/
package org.eclipse.ceylon.cmr.impl;
import java.io.File;
import org.eclipse.ceylon.cmr.api.CmrRepository;
import org.eclipse.ceylon.cmr.api.RepositoryBuilder;
import org.eclipse.ceylon.common.FileUtil;
/**
* Repository builder for FlatRepository
*
* @author Tako Schotanus (tako@ceylon-lang.org)
*/
public class FlatRepositoryBuilder implements RepositoryBuilder {
@Override
public String absolute(File cwd, String token) {
if (token.startsWith("flat:")) {
token = token.substring(5);
File f = FileUtil.absoluteFile(FileUtil.applyCwd(cwd, new File(token)));
token = f.getAbsolutePath();
return "flat:" + token;
} else {
return null;
}
}
@Override
public CmrRepository[] buildRepository(String token) throws Exception {
return buildRepository(token, EMPTY_CONFIG);
}
@Override
public CmrRepository[] buildRepository(String token, RepositoryBuilderConfig config) throws Exception {
if (token.startsWith("flat:")) {
return new CmrRepository[] { createFlatRepository(token) };
} else {
return null;
}
}
private CmrRepository createFlatRepository(String token) {
final File file = new File(token.substring(5));
if (file.exists() == false)
throw new IllegalArgumentException("Directory does not exist: " + token);
if (file.isDirectory() == false)
throw new IllegalArgumentException("Repository exists but is not a directory: " + token);
FileContentStore cs = new FileContentStore(file);
return new FlatRepository(cs.createRoot());
}
}
| apache-2.0 |
contactlab/soap-api-java-client-next | src/main/java/com/contactlab/api/ws/FindMessagesInfo.java | 2764 | /**
* Copyright 2012-2015 ContactLab, Italy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.contactlab.api.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import com.contactlab.api.ws.domain.AuthToken;
import com.contactlab.api.ws.domain.LookupPreferences;
/**
* <p>Java class for findMessagesInfo complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="findMessagesInfo">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="token" type="{domain.ws.api.contactlab.com}AuthToken" minOccurs="0"/>
* <element name="lookupPrefs" type="{domain.ws.api.contactlab.com}LookupPreferences" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "findMessagesInfo", propOrder = {
"token",
"lookupPrefs"
})
public class FindMessagesInfo {
protected AuthToken token;
protected LookupPreferences lookupPrefs;
/**
* Gets the value of the token property.
*
* @return
* possible object is
* {@link AuthToken }
*
*/
public AuthToken getToken() {
return token;
}
/**
* Sets the value of the token property.
*
* @param value
* allowed object is
* {@link AuthToken }
*
*/
public void setToken(AuthToken value) {
this.token = value;
}
/**
* Gets the value of the lookupPrefs property.
*
* @return
* possible object is
* {@link LookupPreferences }
*
*/
public LookupPreferences getLookupPrefs() {
return lookupPrefs;
}
/**
* Sets the value of the lookupPrefs property.
*
* @param value
* allowed object is
* {@link LookupPreferences }
*
*/
public void setLookupPrefs(LookupPreferences value) {
this.lookupPrefs = value;
}
}
| apache-2.0 |
JaewookByun/epcis | epcis-client/src/main/java/org/oliot/epcis_client/AggregationEvent.java | 6237 | package org.oliot.epcis_client;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bson.BsonDocument;
/**
* Copyright (C) 2014-17 Jaewook Byun
*
* This project is part of Oliot (oliot.org), pursuing the implementation of
* Electronic Product Code Information Service(EPCIS) v1.1 specification in
* EPCglobal.
* [http://www.gs1.org/gsmp/kc/epcglobal/epcis/epcis_1_1-standard-20140520.pdf]
*
*
* @author Jaewook Jack Byun, Ph.D student
*
* Korea Advanced Institute of Science and Technology (KAIST)
*
* Real-time Embedded System Laboratory(RESL)
*
* bjw0829@kaist.ac.kr, bjw0829@gmail.com
*/
public class AggregationEvent extends EPCISEvent {
// EventTime, EventTimeZoneOffset,Action required
private String action;
private String parentID;
private List<String> childEPCs;
private List<QuantityElement> childQuantityList;
private String bizStep;
private String disposition;
private String readPoint;
private String bizLocation;
private Map<String, List<String>> bizTransactionList;
private Map<String, List<String>> sourceList;
private Map<String, List<String>> destinationList;
private Map<String, String> namespaces;
private BsonDocument extensions;
public AggregationEvent() {
super();
action = "OBSERVE";
childEPCs = new ArrayList<String>();
childQuantityList = new ArrayList<QuantityElement>();
bizTransactionList = new HashMap<String, List<String>>();
sourceList = new HashMap<String, List<String>>();
destinationList = new HashMap<String, List<String>>();
namespaces = new HashMap<String, String>();
extensions = new BsonDocument();
}
public AggregationEvent(long eventTime, String eventTimeZoneOffset, String action) {
super(eventTime, eventTimeZoneOffset);
this.action = action;
childEPCs = new ArrayList<String>();
childQuantityList = new ArrayList<QuantityElement>();
bizTransactionList = new HashMap<String, List<String>>();
sourceList = new HashMap<String, List<String>>();
destinationList = new HashMap<String, List<String>>();
namespaces = new HashMap<String, String>();
extensions = new BsonDocument();
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getBizStep() {
return bizStep;
}
public void setBizStep(String bizStep) {
this.bizStep = bizStep;
}
public String getDisposition() {
return disposition;
}
public void setDisposition(String disposition) {
this.disposition = disposition;
}
public String getReadPoint() {
return readPoint;
}
public void setReadPoint(String readPoint) {
this.readPoint = readPoint;
}
public String getBizLocation() {
return bizLocation;
}
public void setBizLocation(String bizLocation) {
this.bizLocation = bizLocation;
}
public Map<String, List<String>> getBizTransactionList() {
return bizTransactionList;
}
public void setBizTransactionList(Map<String, List<String>> bizTransactionList) {
this.bizTransactionList = bizTransactionList;
}
public Map<String, List<String>> getSourceList() {
return sourceList;
}
public void setSourceList(Map<String, List<String>> sourceList) {
this.sourceList = sourceList;
}
public Map<String, List<String>> getDestinationList() {
return destinationList;
}
public void setDestinationList(Map<String, List<String>> destinationList) {
this.destinationList = destinationList;
}
public Map<String, String> getNamespaces() {
return namespaces;
}
public String getParentID() {
return parentID;
}
public void setParentID(String parentID) {
this.parentID = parentID;
}
public List<String> getChildEPCs() {
return childEPCs;
}
public void setChildEPCs(List<String> childEPCs) {
this.childEPCs = childEPCs;
}
public List<QuantityElement> getChildQuantityList() {
return childQuantityList;
}
public void setChildQuantityList(List<QuantityElement> childQuantityList) {
this.childQuantityList = childQuantityList;
}
public void setNamespaces(Map<String, String> namespaces) {
this.namespaces = namespaces;
}
public BsonDocument getExtensions() {
return extensions;
}
public void setExtensions(BsonDocument extensions) {
this.extensions = extensions;
}
public BsonDocument asBsonDocument() {
CaptureUtil util = new CaptureUtil();
BsonDocument aggregationEvent = super.asBsonDocument();
// Required Fields
aggregationEvent = util.putEventType(aggregationEvent, "AggregationEvent");
aggregationEvent = util.putAction(aggregationEvent, action);
// Optional Fields
if (this.parentID != null) {
aggregationEvent = util.putParentID(aggregationEvent, parentID);
}
if (this.childEPCs != null && this.childEPCs.size() != 0) {
aggregationEvent = util.putChildEPCs(aggregationEvent, childEPCs);
}
if (this.bizStep != null) {
aggregationEvent = util.putBizStep(aggregationEvent, bizStep);
}
if (this.disposition != null) {
aggregationEvent = util.putDisposition(aggregationEvent, disposition);
}
if (this.readPoint != null) {
aggregationEvent = util.putReadPoint(aggregationEvent, readPoint);
}
if (this.bizLocation != null) {
aggregationEvent = util.putBizLocation(aggregationEvent, bizLocation);
}
if (this.bizTransactionList != null && this.bizTransactionList.isEmpty() == false) {
aggregationEvent = util.putBizTransactionList(aggregationEvent, bizTransactionList);
}
if (this.extensions != null && this.extensions.isEmpty() == false) {
aggregationEvent = util.putExtensions(aggregationEvent, namespaces, extensions);
}
BsonDocument extension = new BsonDocument();
if (this.childQuantityList != null && this.childQuantityList.isEmpty() == false) {
extension = util.putChildQuantityList(extension, childQuantityList);
}
if (this.sourceList != null && this.sourceList.isEmpty() == false) {
extension = util.putSourceList(extension, sourceList);
}
if (this.destinationList != null && this.destinationList.isEmpty() == false) {
extension = util.putDestinationList(extension, destinationList);
}
if (extension.isEmpty() == false)
aggregationEvent.put("extension", extension);
return aggregationEvent;
}
}
| apache-2.0 |
jackycaojiaqi/FuBang_Live | app/src/main/java/com/xlg/android/protocol/RoomBaseInfo.java | 796 | package com.xlg.android.protocol;
import com.xlg.android.utils.Tools;
public class RoomBaseInfo {
@StructOrder(0)
private int vcbid; //房间ID
@StructOrder(1)
private int userid; //操作者ID
@StructOrder(2)
private byte[] theme = new byte[64];//房间描述
public int getVcbid() {
return vcbid;
}
public void setVcbid(int vcbid) {
this.vcbid = vcbid;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getTheme() {
return Tools.ByteArray2StringGBK(theme);
}
public void setTheme(String theme) {
Tools.String2ByteArrayGBK(this.theme, theme);
}
}
| apache-2.0 |
igeldev/gradle-plugins | plugins/sonar/src/test/files/compatibility/multi_project/java/src/main/java/igel/example_java/Logger.java | 353 | package igel.example_java;
public class Logger {
private final Converter converter;
private final Printer printer;
public Logger(Converter converter, Printer printer) {
this.converter = converter;
this.printer = printer;
}
public void log(Object value) {
printer.print(converter.convert(value));
}
}
| apache-2.0 |
illicitonion/buck | test/com/facebook/buck/rules/TestCellBuilder.java | 3956 | /*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.rules;
import static com.facebook.buck.io.Watchman.NULL_WATCHMAN;
import com.facebook.buck.android.AndroidDirectoryResolver;
import com.facebook.buck.android.FakeAndroidDirectoryResolver;
import com.facebook.buck.cli.BuckConfig;
import com.facebook.buck.cli.FakeBuckConfig;
import com.facebook.buck.config.CellConfig;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.io.Watchman;
import com.facebook.buck.io.WatchmanDiagnosticCache;
import com.facebook.buck.json.ProjectBuildFileParserFactory;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.util.DefaultProcessExecutor;
import com.facebook.buck.util.ProcessExecutor;
import java.io.IOException;
import javax.annotation.Nullable;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
public class TestCellBuilder {
private ProjectFilesystem filesystem;
private BuckConfig buckConfig;
private AndroidDirectoryResolver androidDirectoryResolver;
@Nullable
private ProjectBuildFileParserFactory parserFactory;
private Watchman watchman = NULL_WATCHMAN;
private CellConfig cellConfig;
public TestCellBuilder() throws InterruptedException, IOException {
filesystem = new FakeProjectFilesystem();
androidDirectoryResolver = new FakeAndroidDirectoryResolver();
cellConfig = CellConfig.of();
}
public TestCellBuilder setFilesystem(ProjectFilesystem filesystem) {
this.filesystem = filesystem;
return this;
}
public TestCellBuilder setBuckConfig(BuckConfig buckConfig) {
this.buckConfig = buckConfig;
return this;
}
public TestCellBuilder setWatchman(Watchman watchman) {
this.watchman = watchman;
return this;
}
public TestCellBuilder setCellConfigOverride(CellConfig cellConfig) {
this.cellConfig = cellConfig;
return this;
}
public Cell build() throws IOException, InterruptedException {
ProcessExecutor executor = new DefaultProcessExecutor(new TestConsole());
BuckConfig config = buckConfig == null ?
FakeBuckConfig.builder().setFilesystem(filesystem).build() :
buckConfig;
KnownBuildRuleTypesFactory typesFactory = new KnownBuildRuleTypesFactory(
executor,
androidDirectoryResolver);
if (parserFactory == null) {
return CellProvider.createForLocalBuild(
filesystem,
watchman,
config,
cellConfig,
typesFactory,
new WatchmanDiagnosticCache()).getCellByPath(filesystem.getRootPath());
}
// The constructor for `Cell` is private, and it's in such a central location I don't really
// want to make it public. Brace yourselves.
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(Cell.class);
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
if ("createBuildFileParserFactory".equals(method.getName())) {
return parserFactory;
}
return proxy.invokeSuper(obj, args);
});
return (Cell) enhancer.create();
}
public static CellPathResolver createCellRoots(
@Nullable ProjectFilesystem filesystem) {
ProjectFilesystem toUse = filesystem == null ? new FakeProjectFilesystem() : filesystem;
return new FakeCellPathResolver(toUse);
}
}
| apache-2.0 |
leonhong/hadoop-20-warehouse | src/hdfs/org/apache/hadoop/hdfs/protocol/ClientDatanodeProtocol.java | 2760 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.protocol;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.ipc.VersionedProtocol;
/** An client-datanode protocol for block recovery
*/
public interface ClientDatanodeProtocol extends VersionedProtocol {
public static final Log LOG = LogFactory.getLog(ClientDatanodeProtocol.class);
public static final long GET_BLOCKINFO_VERSION = 4L;
public static final long COPY_BLOCK_VERSION = 5L;
/**
* 3: add keepLength parameter.
* 4: added getBlockInfo
* 5: add copyBlock parameter.
*/
public static final long versionID = 5L;
/** Start generation-stamp recovery for specified block
* @param block the specified block
* @param keepLength keep the block length
* @param targets the list of possible locations of specified block
* @return the new blockid if recovery successful and the generation stamp
* got updated as part of the recovery, else returns null if the block id
* not have any data and the block was deleted.
* @throws IOException
*/
LocatedBlock recoverBlock(Block block, boolean keepLength,
DatanodeInfo[] targets) throws IOException;
/** Returns a block object that contains the specified block object
* from the specified Datanode.
* @param block the specified block
* @return the Block object from the specified Datanode
* @throws IOException if the block does not exist
*/
public Block getBlockInfo(Block block) throws IOException;
/** Instruct the datanode to copy a block to specified target.
* @param srcBlock the specified block on this datanode
* @param destinationBlock the block identifier on the destination datanode
* @param target the locations where this block needs to be copied
* @throws IOException
*/
public void copyBlock(Block srcblock, Block destBlock,
DatanodeInfo target) throws IOException;
}
| apache-2.0 |
ModernMT/MMT | src/core/src/main/java/eu/modernmt/training/BatchCopyProcess.java | 3293 | package eu.modernmt.training;
import eu.modernmt.io.Corpora;
import eu.modernmt.model.corpus.Corpus;
import eu.modernmt.model.corpus.MultilingualCorpus;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by davide on 28/08/17.
*/
public class BatchCopyProcess {
public interface OutputCorpusFactory {
MultilingualCorpus getOutput(MultilingualCorpus corpus);
Corpus getOutput(Corpus corpus);
}
private static final int MAX_IO_THREADS = 10;
private ArrayList<MultilingualCorpus> multilingualCorpora = new ArrayList<>();
private ArrayList<Corpus> monolingualCorpora = new ArrayList<>();
private final OutputCorpusFactory outputFactory;
private int ioThreads = MAX_IO_THREADS;
public BatchCopyProcess(OutputCorpusFactory outputFactory) {
this.outputFactory = outputFactory;
}
public void add(MultilingualCorpus corpus) {
this.multilingualCorpora.add(corpus);
}
public void add(Corpus corpus) {
this.monolingualCorpora.add(corpus);
}
public int getIoThreads() {
return ioThreads;
}
public void setIoThreads(int ioThreads) {
if (ioThreads < 1)
throw new IllegalArgumentException();
this.ioThreads = ioThreads;
}
public void run() throws IOException {
if (this.multilingualCorpora.isEmpty() && this.monolingualCorpora.isEmpty())
return;
int totalCorporaCount = this.multilingualCorpora.size() + this.monolingualCorpora.size();
int ioThreads = Math.min(Math.min(this.ioThreads, MAX_IO_THREADS), totalCorporaCount);
ExecutorService executor = Executors.newFixedThreadPool(ioThreads);
List<Future<?>> futures = new ArrayList<>(totalCorporaCount);
// Enqueue multilingual corpora tasks
for (MultilingualCorpus corpus : multilingualCorpora) {
final MultilingualCorpus output = outputFactory.getOutput(corpus);
futures.add(executor.submit(() -> {
Corpora.copy(corpus, output);
return null;
}));
}
// Enqueue monolingual corpora tasks
for (Corpus corpus : monolingualCorpora) {
final Corpus output = outputFactory.getOutput(corpus);
futures.add(executor.submit(() -> {
Corpora.copy(corpus, output);
return null;
}));
}
try {
for (Future<?> future : futures)
future.get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException)
throw (IOException) cause;
else if (cause instanceof RuntimeException)
throw (RuntimeException) cause;
else
throw new Error("Unexpected exception", cause);
} catch (InterruptedException e) {
throw new IOException("Execution interrupted", e);
} finally {
executor.shutdownNow();
try {
executor.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// Nothing to do
}
}
}
}
| apache-2.0 |
semagrow/semagrow | core/src/main/java/org/semagrow/plan/querygraph/QueryGraphDecomposerContext.java | 465 | package org.semagrow.plan.querygraph;
import org.eclipse.rdf4j.query.algebra.TupleExpr;
import org.semagrow.plan.DecomposerContext;
/**
* Created by angel on 23/6/2016.
*/
public class QueryGraphDecomposerContext extends DecomposerContext {
private QueryGraph graph;
protected QueryGraphDecomposerContext(TupleExpr expr) {
super(expr);
graph = QueryGraph.create(expr);
}
public QueryGraph getQueryGraph() { return graph; }
}
| apache-2.0 |
sutine/webant | webant-commons/src/main/java/org/webant/commons/utils/BeanUtils.java | 1386 | package org.webant.commons.utils;
import org.apache.commons.lang3.ArrayUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
import static org.apache.commons.beanutils.PropertyUtils.isReadable;
import static org.apache.commons.beanutils.PropertyUtils.isWriteable;
public class BeanUtils extends org.apache.commons.beanutils.BeanUtils {
public static Field[] getDeclaredFields(Object bean) {
Field[] fields = new Field[0];
Class clazz = bean.getClass();
for (; clazz != null; clazz = clazz.getSuperclass()) {
Field[] superFields = clazz.getDeclaredFields();
fields = (Field[]) ArrayUtils.addAll(fields, superFields);
}
return Arrays.stream(fields).filter(field -> isReadable(bean, field.getName()) && isWriteable(bean, field.getName())).toArray(Field[]::new);
}
public static Field[] getDeclaredFields(Class clazz) {
Field[] fields = new Field[0];
for (; clazz != null; clazz = clazz.getSuperclass()) {
Field[] superFields = clazz.getDeclaredFields();
fields = (Field[]) ArrayUtils.addAll(fields, superFields);
}
return fields;
}
public static String[] getDeclaredFieldNames(Class clazz) {
Field[] fields = getDeclaredFields(clazz);
return Arrays.stream(fields).map(Field::getName).toArray(String[]::new);
}
} | apache-2.0 |
pponec/ujorm | project-m2/ujo-core/src/main/java/org/ujorm/core/enums/OptionEnum.java | 1321 | /*
* Copyright 2018-2022 Pavel Ponec
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ujorm.core.enums;
/**
* Common attribues for many methods.
* @author Pavel Ponec
* @see org.ujorm.tools.Check#firstItem(java.lang.Object, java.lang.Object...)
*/
public enum OptionEnum {
/** Most methods with this property return a <strong>non null</strong> object,
* otherwise it throws an <strong>exception</strong>.
* See the usage method for more information.
*/
REQUIRED,
/** A result of the most methods can be a <strong>nullable</strong> value.
* See the usage method for more information.
*/
OPTIONAL,
/** The choice is an equivalence empty value,
* the default behavior is described on the used method.
*/
DEFAULT;
;
}
| apache-2.0 |
bradhandy/osworkflow-intellij-plugin | src/main/java/net/jackofalltrades/workflow/model/xml/SingleCondition.java | 586 | package net.jackofalltrades.workflow.model.xml;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.GenericAttributeValue;
import com.intellij.util.xml.Required;
/**
* Defines the structure of the "condition" element.
*
* @author bhandy
*/
public interface SingleCondition extends DomElement, Condition, ArgumentHolder, PsiClassRestrictable, WorkflowElement {
GenericAttributeValue<String> getId();
@Required
GenericAttributeValue<String> getType();
GenericAttributeValue<Boolean> getNegate();
GenericAttributeValue<String> getName();
}
| apache-2.0 |
nihaooo/ZhinengGuanjia | app/src/main/java/explame/com/imooctestone/entity/GirdData.java | 463 | package explame.com.imooctestone.entity;
/*
* 项目名: ImoocTestOne
* 包名: explame.com.imooctestone.entity
* 时间 2017/5/8.
* 创建者: qzhuorui
* 描述: 妹子的实体类
*/
public class GirdData {
//地址
private String imgUrl;
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}
| apache-2.0 |
googleads/google-ads-java | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/common/TargetRoasSimulationPointListOrBuilder.java | 1837 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/common/simulation.proto
package com.google.ads.googleads.v10.common;
public interface TargetRoasSimulationPointListOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.common.TargetRoasSimulationPointList)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Projected metrics for a series of target ROAS amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.TargetRoasSimulationPoint points = 1;</code>
*/
java.util.List<com.google.ads.googleads.v10.common.TargetRoasSimulationPoint>
getPointsList();
/**
* <pre>
* Projected metrics for a series of target ROAS amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.TargetRoasSimulationPoint points = 1;</code>
*/
com.google.ads.googleads.v10.common.TargetRoasSimulationPoint getPoints(int index);
/**
* <pre>
* Projected metrics for a series of target ROAS amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.TargetRoasSimulationPoint points = 1;</code>
*/
int getPointsCount();
/**
* <pre>
* Projected metrics for a series of target ROAS amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.TargetRoasSimulationPoint points = 1;</code>
*/
java.util.List<? extends com.google.ads.googleads.v10.common.TargetRoasSimulationPointOrBuilder>
getPointsOrBuilderList();
/**
* <pre>
* Projected metrics for a series of target ROAS amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.TargetRoasSimulationPoint points = 1;</code>
*/
com.google.ads.googleads.v10.common.TargetRoasSimulationPointOrBuilder getPointsOrBuilder(
int index);
}
| apache-2.0 |
alphamu/PrayTime-Android | app/src/main/java/com/alimuzaffar/ramadanalarm/fragments/OnboardingTimeFormatFragment.java | 3929 | package com.alimuzaffar.ramadanalarm.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.alimuzaffar.ramadanalarm.util.AppSettings;
import com.alimuzaffar.ramadanalarm.util.PrayTime;
import com.alimuzaffar.ramadanalarm.R;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link OnOnboardingOptionSelectedListener} interface
* to handle interaction events.
* Use the {@link OnboardingTimeFormatFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class OnboardingTimeFormatFragment extends OnboardingBaseFragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private int mParam1 = 0;
protected OnOnboardingOptionSelectedListener mListener;
TextView m12h;
TextView m24h;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @return A new instance of fragment OnboardingAsrCalculationMethod.
*/
public static OnboardingTimeFormatFragment newInstance(int param1) {
OnboardingTimeFormatFragment fragment = new OnboardingTimeFormatFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
public OnboardingTimeFormatFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getInt(ARG_PARAM1);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_onboarding_time_format, container, false);
view.findViewById(R.id.prev).setOnClickListener(this);
TextView next = (TextView) view.findViewById(R.id.next);
next.setOnClickListener(this);
next.setText(R.string.button_done);
TextView title = (TextView) view.findViewById(R.id.card_title);
title.setText(R.string.time_title);
m12h = (TextView) view.findViewById(R.id.twelve);
m24h = (TextView) view.findViewById(R.id.twenty_four);
m12h.setOnClickListener(this);
m24h.setOnClickListener(this);
int method = AppSettings.getInstance(getActivity()).getTimeFormatFor(mParam1);
if (method == PrayTime.TIME_12) {
m12h.setSelected(true);
} else {
m24h.setSelected(true);
}
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnOnboardingOptionSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnOnboardingOptionSelectedListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onClick(View v) {
AppSettings settings = AppSettings.getInstance(getActivity());
if (v.getId() == R.id.next) {
mListener.onOptionSelected();
} else if (v.getId() == R.id.prev) {
getActivity().onBackPressed();
} else if (v.getId() == m12h.getId()) {
m12h.setSelected(true);
m24h.setSelected(false);
settings.setTimeFormatFor(mParam1, PrayTime.TIME_12);
mListener.onOptionSelected();
} else if (v.getId() == m24h.getId()) {
m12h.setSelected(false);
m24h.setSelected(true);
settings.setTimeFormatFor(mParam1, PrayTime.TIME_24);
mListener.onOptionSelected();
}
}
}
| apache-2.0 |
KAMP-Research/KAMP | bundles/Toometa/toometa.relations.edit/src/relations/provider/ConflictObjectItemProvider.java | 4541 | /**
*/
package relations.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import relations.RelationsPackage;
/**
* This is the item provider adapter for a {@link relations.ConflictObject} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class ConflictObjectItemProvider
extends ItemProviderAdapter
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ConflictObjectItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addConflictsWithPropertyDescriptor(object);
addHasConflictsPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Conflicts With feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addConflictsWithPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_ConflictObject_conflictsWith_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_ConflictObject_conflictsWith_feature", "_UI_ConflictObject_type"),
RelationsPackage.Literals.CONFLICT_OBJECT__CONFLICTS_WITH,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Has Conflicts feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addHasConflictsPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_ConflictObject_hasConflicts_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_ConflictObject_hasConflicts_feature", "_UI_ConflictObject_type"),
RelationsPackage.Literals.CONFLICT_OBJECT__HAS_CONFLICTS,
true,
false,
true,
null,
null,
null));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
return getString("_UI_ConflictObject_type");
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return RelationsEditPlugin.INSTANCE;
}
}
| apache-2.0 |
Qi4j/qi4j-sdk | libraries/sql-generator/src/main/java/org/apache/polygene/library/sql/generator/implementation/transformation/DefinitionProcessing.java | 20873 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package org.apache.polygene.library.sql.generator.implementation.transformation;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.polygene.library.sql.generator.grammar.common.SQLConstants;
import org.apache.polygene.library.sql.generator.grammar.definition.schema.SchemaDefinition;
import org.apache.polygene.library.sql.generator.grammar.definition.schema.SchemaElement;
import org.apache.polygene.library.sql.generator.grammar.definition.table.AutoGenerationPolicy;
import org.apache.polygene.library.sql.generator.grammar.definition.table.CheckConstraint;
import org.apache.polygene.library.sql.generator.grammar.definition.table.ColumnDefinition;
import org.apache.polygene.library.sql.generator.grammar.definition.table.ConstraintCharacteristics;
import org.apache.polygene.library.sql.generator.grammar.definition.table.ForeignKeyConstraint;
import org.apache.polygene.library.sql.generator.grammar.definition.table.LikeClause;
import org.apache.polygene.library.sql.generator.grammar.definition.table.MatchType;
import org.apache.polygene.library.sql.generator.grammar.definition.table.ReferentialAction;
import org.apache.polygene.library.sql.generator.grammar.definition.table.TableCommitAction;
import org.apache.polygene.library.sql.generator.grammar.definition.table.TableConstraintDefinition;
import org.apache.polygene.library.sql.generator.grammar.definition.table.TableDefinition;
import org.apache.polygene.library.sql.generator.grammar.definition.table.TableElement;
import org.apache.polygene.library.sql.generator.grammar.definition.table.TableElementList;
import org.apache.polygene.library.sql.generator.grammar.definition.table.TableScope;
import org.apache.polygene.library.sql.generator.grammar.definition.table.UniqueConstraint;
import org.apache.polygene.library.sql.generator.grammar.definition.table.UniqueSpecification;
import org.apache.polygene.library.sql.generator.grammar.definition.view.RegularViewSpecification;
import org.apache.polygene.library.sql.generator.grammar.definition.view.ViewCheckOption;
import org.apache.polygene.library.sql.generator.grammar.definition.view.ViewDefinition;
import org.apache.polygene.library.sql.generator.implementation.transformation.spi.SQLProcessorAggregator;
/**
*
*/
public class DefinitionProcessing
{
public static class SchemaDefinitionProcessor extends AbstractProcessor<SchemaDefinition>
{
public SchemaDefinitionProcessor()
{
super( SchemaDefinition.class );
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, SchemaDefinition object, StringBuilder builder )
{
builder.append( SQLConstants.CREATE ).append( SQLConstants.TOKEN_SEPARATOR ).append( "SCHEMA " )
.append( object.getSchemaName() );
String charset = object.getSchemaCharset();
if( charset != null )
{
builder.append( " DEFAULT CHARSET " ).append( object.getSchemaCharset() );
}
builder.append( SQLConstants.NEWLINE );
}
protected void processSchemaElements( SQLProcessorAggregator aggregator, SchemaDefinition object,
StringBuilder builder )
{
for( SchemaElement el : object.getSchemaElements() )
{
aggregator.process( el.asTypeable(), builder );
builder.append( SQLConstants.NEWLINE );
}
}
}
public static class TableDefinitionProcessor extends AbstractProcessor<TableDefinition>
{
private static final Map<TableScope, String> _defaultTableScopes;
private static final Map<TableCommitAction, String> _defaultCommitActions;
static
{
Map<TableScope, String> operations = new HashMap<TableScope, String>();
operations.put( TableScope.GLOBAL_TEMPORARY, "GLOBAL TEMPORARY" );
operations.put( TableScope.LOCAL_TEMPORARY, "LOCAL TEMPORARY" );
_defaultTableScopes = operations;
Map<TableCommitAction, String> commitActions = new HashMap<TableCommitAction, String>();
commitActions.put( TableCommitAction.ON_COMMIT_DELETE_ROWS, "DELETE ROWS" );
commitActions.put( TableCommitAction.ON_COMMIT_PRESERVE_ROWS, "PRESERVE ROWS" );
_defaultCommitActions = commitActions;
}
public static Map<TableCommitAction, String> getDefaultCommitActions()
{
return Collections.unmodifiableMap( _defaultCommitActions );
}
public static Map<TableScope, String> getDefaultTableScopes()
{
return Collections.unmodifiableMap( _defaultTableScopes );
}
private final Map<TableScope, String> _tableScopes;
private final Map<TableCommitAction, String> _commitActions;
public TableDefinitionProcessor()
{
this( _defaultTableScopes, _defaultCommitActions );
}
public TableDefinitionProcessor( Map<TableScope, String> tableScopes,
Map<TableCommitAction, String> commitActions )
{
super( TableDefinition.class );
this._tableScopes = tableScopes;
this._commitActions = commitActions;
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, TableDefinition object, StringBuilder builder )
{
builder.append( SQLConstants.CREATE );
if( object.getTableScope() != null )
{
builder.append( SQLConstants.TOKEN_SEPARATOR ).append( this._tableScopes.get( object.getTableScope() ) );
}
builder.append( SQLConstants.TOKEN_SEPARATOR ).append( "TABLE" ).append( SQLConstants.TOKEN_SEPARATOR );
aggregator.process( object.getTableName(), builder );
builder.append( SQLConstants.NEWLINE );
aggregator.process( object.getContents(), builder );
builder.append( SQLConstants.NEWLINE );
if( object.getCommitAction() != null )
{
builder.append( "ON COMMIT" ).append( SQLConstants.TOKEN_SEPARATOR )
.append( this._commitActions.get( object.getCommitAction() ) );
}
}
}
public static class TableElementListProcessor extends AbstractProcessor<TableElementList>
{
public TableElementListProcessor()
{
super( TableElementList.class );
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, TableElementList object, StringBuilder builder )
{
Iterator<TableElement> iter = object.getElementList().iterator();
builder.append( SQLConstants.OPEN_PARENTHESIS ).append( SQLConstants.NEWLINE );
while( iter.hasNext() )
{
this.processTableElement( aggregator, iter.next(), builder, iter.hasNext() );
builder.append( SQLConstants.NEWLINE );
}
builder.append( SQLConstants.CLOSE_PARENTHESIS );
}
protected void processTableElement( SQLProcessorAggregator aggregator, TableElement object, StringBuilder builder, boolean hasNext )
{
aggregator.process( object, builder );
if( hasNext )
{
builder.append( SQLConstants.COMMA );
}
}
}
public static class ColumnDefinitionProcessor extends AbstractProcessor<ColumnDefinition>
{
public ColumnDefinitionProcessor()
{
super( ColumnDefinition.class );
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, ColumnDefinition object, StringBuilder builder )
{
builder.append( object.getColumnName() ).append( SQLConstants.TOKEN_SEPARATOR );
this.processDataType( aggregator, object, builder );
if( object.getDefault() != null )
{
builder.append( SQLConstants.TOKEN_SEPARATOR ).append( "DEFAULT" )
.append( SQLConstants.TOKEN_SEPARATOR ).append( object.getDefault() );
}
this.processMayBeNull( object, builder );
if( object.getAutoGenerationPolicy() != null )
{
this.processAutoGenerationPolicy( object, builder );
}
}
protected void processMayBeNull( ColumnDefinition object, StringBuilder builder )
{
if( !object.mayBeNull() )
{
builder.append( SQLConstants.TOKEN_SEPARATOR ).append( "NOT NULL" );
}
}
protected void processDataType( SQLProcessorAggregator aggregator, ColumnDefinition object,
StringBuilder builder )
{
aggregator.process( object.getDataType(), builder );
}
protected void processAutoGenerationPolicy( ColumnDefinition object, StringBuilder builder )
{
builder.append( " GENERATED " );
if( AutoGenerationPolicy.ALWAYS.equals( object.getAutoGenerationPolicy() ) )
{
builder.append( "ALWAYS " );
}
else if( AutoGenerationPolicy.BY_DEFAULT.equals( object.getAutoGenerationPolicy() ) )
{
builder.append( "BY DEFAULT " );
}
else
{
throw new UnsupportedOperationException( "Unknown auto generation policy: "
+ object.getAutoGenerationPolicy() + "." );
}
builder.append( "AS IDENTITY" );
}
}
public static class LikeClauseProcessor extends AbstractProcessor<LikeClause>
{
public LikeClauseProcessor()
{
super( LikeClause.class );
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, LikeClause object, StringBuilder builder )
{
builder.append( "LIKE" ).append( SQLConstants.TOKEN_SEPARATOR );
aggregator.process( object.getTableName(), builder );
}
}
public static class TableConstraintDefinitionProcessor extends AbstractProcessor<TableConstraintDefinition>
{
private static final Map<ConstraintCharacteristics, String> _defaultCharacteristics;
static
{
Map<ConstraintCharacteristics, String> operations = new HashMap<ConstraintCharacteristics, String>();
operations.put( ConstraintCharacteristics.INITIALLY_DEFERRED_DEFERRABLE, "INITIALLY DEFERRED DEFERRABLE" );
operations.put( ConstraintCharacteristics.INITIALLY_IMMEDIATE_DEFERRABLE, "INITIALLY IMMEDIATE DEFERRABLE" );
operations.put( ConstraintCharacteristics.NOT_DEFERRABLE, "NOT DEFERRABLE" );
_defaultCharacteristics = operations;
}
private final Map<ConstraintCharacteristics, String> _characteristics;
public TableConstraintDefinitionProcessor()
{
this( _defaultCharacteristics );
}
public TableConstraintDefinitionProcessor( Map<ConstraintCharacteristics, String> characteristics )
{
super( TableConstraintDefinition.class );
this._characteristics = characteristics;
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, TableConstraintDefinition object,
StringBuilder builder )
{
if( object.getConstraintName() != null )
{
builder.append( "CONSTRAINT" ).append( SQLConstants.TOKEN_SEPARATOR )
.append( object.getConstraintName() ).append( SQLConstants.TOKEN_SEPARATOR );
}
aggregator.process( object.getConstraint(), builder );
if( object.getCharacteristics() != null )
{
builder.append( SQLConstants.TOKEN_SEPARATOR ).append(
this._characteristics.get( object.getCharacteristics() ) );
}
}
}
public static class CheckConstraintProcessor extends AbstractProcessor<CheckConstraint>
{
public CheckConstraintProcessor()
{
super( CheckConstraint.class );
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, CheckConstraint object, StringBuilder builder )
{
builder.append( "CHECK" ).append( SQLConstants.TOKEN_SEPARATOR ).append( SQLConstants.OPEN_PARENTHESIS );
aggregator.process( object.getCheckCondition(), builder );
builder.append( SQLConstants.CLOSE_PARENTHESIS );
}
}
public static class UniqueConstraintProcessor extends AbstractProcessor<UniqueConstraint>
{
private static final Map<UniqueSpecification, String> _defaultUniqueSpecs;
static
{
Map<UniqueSpecification, String> map = new HashMap<UniqueSpecification, String>();
map.put( UniqueSpecification.PRIMARY_KEY, "PRIMARY KEY" );
map.put( UniqueSpecification.UNIQUE, "UNIQUE" );
_defaultUniqueSpecs = map;
}
private final Map<UniqueSpecification, String> _uniqueSpecs;
public UniqueConstraintProcessor()
{
this( _defaultUniqueSpecs );
}
public UniqueConstraintProcessor( Map<UniqueSpecification, String> uniqueSpecs )
{
super( UniqueConstraint.class );
this._uniqueSpecs = uniqueSpecs;
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, UniqueConstraint object, StringBuilder builder )
{
this.processUniqueness( aggregator, object, builder );
}
protected void processUniqueness( SQLProcessorAggregator aggregator, UniqueConstraint object, StringBuilder builder )
{
builder.append( this._uniqueSpecs.get( object.getUniquenessKind() ) );
aggregator.process( object.getColumnNameList(), builder );
}
}
public static class ForeignKeyConstraintProcessor extends AbstractProcessor<ForeignKeyConstraint>
{
private static final Map<ReferentialAction, String> _defaultReferentialActions;
private static final Map<MatchType, String> _defaultMatchTypes;
static
{
Map<ReferentialAction, String> map = new HashMap<ReferentialAction, String>();
map.put( ReferentialAction.CASCADE, "CASCADE" );
map.put( ReferentialAction.NO_ACTION, "NO ACTION" );
map.put( ReferentialAction.RESTRICT, "RESTRICT" );
map.put( ReferentialAction.SET_DEFAULT, "SET DEFAULT" );
map.put( ReferentialAction.SET_NULL, "SET NULL" );
_defaultReferentialActions = map;
Map<MatchType, String> mt = new HashMap<MatchType, String>();
mt.put( MatchType.FULL, "FULL" );
mt.put( MatchType.PARTIAL, "PARTIAL" );
mt.put( MatchType.SIMPLE, "SIMPLE" );
_defaultMatchTypes = mt;
}
private final Map<ReferentialAction, String> _referentialActions;
private final Map<MatchType, String> _matchTypes;
public ForeignKeyConstraintProcessor()
{
this( _defaultReferentialActions, _defaultMatchTypes );
}
public ForeignKeyConstraintProcessor( Map<ReferentialAction, String> uniqueSpecs,
Map<MatchType, String> matchTypes )
{
super( ForeignKeyConstraint.class );
this._referentialActions = uniqueSpecs;
this._matchTypes = matchTypes;
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, ForeignKeyConstraint object, StringBuilder builder )
{
builder.append( "FOREIGN KEY" );
aggregator.process( object.getSourceColumns(), builder );
builder.append( SQLConstants.NEWLINE ).append( "REFERENCES" ).append( SQLConstants.TOKEN_SEPARATOR );
aggregator.process( object.getTargetTableName(), builder );
if( object.getTargetColumns() != null )
{
aggregator.process( object.getTargetColumns(), builder );
}
if( object.getMatchType() != null )
{
builder.append( SQLConstants.TOKEN_SEPARATOR ).append( "MATCH" ).append( SQLConstants.TOKEN_SEPARATOR )
.append( this._matchTypes.get( object.getMatchType() ) );
}
builder.append( SQLConstants.NEWLINE );
this.handleReferentialAction( "ON UPDATE", object.getOnUpdate(), builder );
builder.append( SQLConstants.TOKEN_SEPARATOR );
this.handleReferentialAction( "ON DELETE", object.getOnDelete(), builder );
}
protected void handleReferentialAction( String prefix, ReferentialAction action, StringBuilder builder )
{
if( action != null )
{
builder.append( prefix ).append( SQLConstants.TOKEN_SEPARATOR )
.append( this._referentialActions.get( action ) );
}
}
}
public static class ViewDefinitionProcessor extends AbstractProcessor<ViewDefinition>
{
private static final Map<ViewCheckOption, String> _defaultViewCheckOptions;
static
{
Map<ViewCheckOption, String> map = new HashMap<ViewCheckOption, String>();
map.put( ViewCheckOption.CASCADED, "CASCADED" );
map.put( ViewCheckOption.LOCAL, "LOCAL" );
_defaultViewCheckOptions = map;
}
private final Map<ViewCheckOption, String> _viewCheckOptions;
public ViewDefinitionProcessor()
{
this( _defaultViewCheckOptions );
}
public ViewDefinitionProcessor( Map<ViewCheckOption, String> viewCheckOptions )
{
super( ViewDefinition.class );
this._viewCheckOptions = viewCheckOptions;
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, ViewDefinition object, StringBuilder builder )
{
builder.append( SQLConstants.CREATE ).append( SQLConstants.TOKEN_SEPARATOR );
if( object.isRecursive() )
{
builder.append( "RECURSIVE" ).append( SQLConstants.TOKEN_SEPARATOR );
}
builder.append( "VIEW" ).append( SQLConstants.TOKEN_SEPARATOR );
aggregator.process( object.getViewName(), builder );
aggregator.process( object.getViewSpecification(), builder );
builder.append( "AS" ).append( SQLConstants.NEWLINE );
aggregator.process( object.getViewQuery(), builder );
if( object.getViewCheckOption() != null )
{
builder.append( SQLConstants.NEWLINE ).append( "WITH" ).append( SQLConstants.TOKEN_SEPARATOR )
.append( this._viewCheckOptions.get( object.getViewCheckOption() ) )
.append( SQLConstants.TOKEN_SEPARATOR ).append( "CHECK OPTION" );
}
}
}
public static class RegularViewSpecificationProcessor extends AbstractProcessor<RegularViewSpecification>
{
public RegularViewSpecificationProcessor()
{
super( RegularViewSpecification.class );
}
@Override
protected void doProcess( SQLProcessorAggregator aggregator, RegularViewSpecification object,
StringBuilder builder )
{
if( object.getColumns() != null )
{
aggregator.process( object.getColumns(), builder );
}
}
}
}
| apache-2.0 |
simplegeo/hadoop-pig | src/org/apache/pig/impl/logicalLayer/validators/InputOutputFileVisitor.java | 4652 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pig.impl.logicalLayer.validators;
import java.io.IOException;
import org.apache.hadoop.mapreduce.Job;
import org.apache.pig.PigException;
import org.apache.pig.ResourceSchema;
import org.apache.pig.StoreFuncInterface;
import org.apache.pig.impl.PigContext ;
import org.apache.pig.impl.logicalLayer.LOStore;
import org.apache.pig.impl.logicalLayer.LOVisitor;
import org.apache.pig.impl.logicalLayer.LogicalOperator;
import org.apache.pig.impl.logicalLayer.LogicalPlan;
import org.apache.pig.impl.plan.DepthFirstWalker;
import org.apache.pig.impl.plan.CompilationMessageCollector;
import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil;
import org.apache.pig.impl.plan.PlanValidationException;
import org.apache.pig.impl.plan.CompilationMessageCollector.MessageType;
/***
* Visitor for checking output specification
* In addition to throwing exception we also log them in msgCollector.
*
* We assume input/output files can exist only in the top level plan.
*
*/
public class InputOutputFileVisitor extends LOVisitor {
private PigContext pigCtx;
private CompilationMessageCollector msgCollector;
public InputOutputFileVisitor(LogicalPlan plan,
CompilationMessageCollector messageCollector,
PigContext pigContext) {
super(plan, new DepthFirstWalker<LogicalOperator, LogicalPlan>(plan));
pigCtx = pigContext ;
msgCollector = messageCollector ;
}
/***
* The logic here is to delegate the validation of output specification
* to output format implementation.
*/
@Override
protected void visit(LOStore store) throws PlanValidationException{
StoreFuncInterface sf = store.getStoreFunc();
String outLoc = store.getOutputFile().getFileName();
int errCode = 2116;
String validationErrStr ="Output Location Validation Failed for: " + outLoc ;
Job dummyJob;
try {
if(store.getSchema() != null){
sf.checkSchema(new ResourceSchema(store.getSchema(), store.getSortInfo()));
}
dummyJob = new Job(ConfigurationUtil.toConfiguration(pigCtx.getProperties()));
sf.setStoreLocation(outLoc, dummyJob);
} catch (IOException ioe) {
if(ioe instanceof PigException){
errCode = ((PigException)ioe).getErrorCode();
}
String exceptionMsg = ioe.getMessage();
validationErrStr += (exceptionMsg == null) ? "" : " More info to follow:\n" +exceptionMsg;
msgCollector.collect(validationErrStr, MessageType.Error) ;
throw new PlanValidationException(validationErrStr, errCode, pigCtx.getErrorSource(), ioe);
}
validationErrStr += " More info to follow:\n";
try {
sf.getOutputFormat().checkOutputSpecs(dummyJob);
} catch (IOException ioe) {
byte errSrc = pigCtx.getErrorSource();
switch(errSrc) {
case PigException.BUG:
errCode = 2002;
break;
case PigException.REMOTE_ENVIRONMENT:
errCode = 6000;
break;
case PigException.USER_ENVIRONMENT:
errCode = 4000;
break;
}
validationErrStr += ioe.getMessage();
msgCollector.collect(validationErrStr, MessageType.Error) ;
throw new PlanValidationException(validationErrStr, errCode, errSrc, ioe);
} catch (InterruptedException ie) {
validationErrStr += ie.getMessage();
msgCollector.collect(validationErrStr, MessageType.Error) ;
throw new PlanValidationException(validationErrStr, errCode, pigCtx.getErrorSource(), ie);
}
}
}
| apache-2.0 |
testify-project/testify | modules/junit4/junit4-core/src/test/java/org/testifyproject/junit4/NoConstructorTest.java | 1309 | /*
* Copyright 2016-2017 Testify Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.testifyproject.junit4;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.testifyproject.annotation.Sut;
import org.testifyproject.junit4.fixture.NoConstructorType;
/**
*
* @author saden
*/
@RunWith(UnitTest.class)
public class NoConstructorTest {
@Sut
NoConstructorType sut;
@Before
public void verifyInjections() {
assertThat(sut).isNotNull();
}
@Test
public void givenNothingClassToExecuteShouldReturnHello() {
String greeting = "Hello!";
String result = sut.execute();
assertThat(result).isEqualTo(greeting);
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/listing/FunctionTagManager.java | 2237 | /* ###
* IP: GHIDRA
*
* 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 ghidra.program.model.listing;
import java.util.List;
/**
* Interface for managing function tags. Tags are simple objects consisting of a name and an
* optional comment, which can be applied to functions.
*
* See ghidra.program.database.function.FunctionTagAdapter
* See ghidra.program.database.function.FunctionTagMappingAdapter
*/
public interface FunctionTagManager {
/**
* Returns the function tag with the given name
*
* @param name the tag name
* @return the function tag, or null if not found
*/
public FunctionTag getFunctionTag(String name);
/**
* Returns the function tag with the given database id
*
* @param id the tags database id
* @return the function tag, or null if not found
*/
public FunctionTag getFunctionTag(long id);
/**
* Returns all function tags in the database
*
* @return list of function tags
*/
public List<? extends FunctionTag> getAllFunctionTags();
/**
* Returns true if the given tag is assigned to a function
*
* @param name the tag name
* @return true if assigned to a function
*/
public boolean isTagAssigned(String name);
/**
* Creates a new function tag with the given attributes if one does
* not already exist. Otherwise, returns the existing tag.
*
* @param name the tag name
* @param comment the comment associated with the tag (optional)
* @return the new function tag
*/
public FunctionTag createFunctionTag(String name, String comment);
/**
* Returns the number of times the given tag has been applied to a function
* @param tag the tag
* @return the count
*/
public int getUseCount(FunctionTag tag);
}
| apache-2.0 |
xiongjiaji/kyle-identity | src/test/java/com/kyle/identity/IdentityApplicationTests.java | 336 | package com.kyle.identity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class IdentityApplicationTests {
@Test
public void contextLoads() {
}
}
| apache-2.0 |
menski/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/operation/AbstractPvmEventAtomicOperation.java | 1126 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.impl.pvm.runtime.operation;
import org.camunda.bpm.engine.impl.core.operation.AbstractEventAtomicOperation;
import org.camunda.bpm.engine.impl.pvm.process.ScopeImpl;
import org.camunda.bpm.engine.impl.pvm.runtime.PvmExecutionImpl;
/**
* @author Daniel Meyer
* @author Roman Smirnov
* @author Sebastian Menski
*
*/
public abstract class AbstractPvmEventAtomicOperation extends AbstractEventAtomicOperation<PvmExecutionImpl> implements PvmAtomicOperation {
protected abstract ScopeImpl getScope(PvmExecutionImpl execution);
}
| apache-2.0 |
codedy/interest | interest-web/interest-web-common/src/main/java/com/interest/web/common/utils/EncodeUtil.java | 3523 | package com.interest.web.common.utils;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.authentication.dao.ReflectionSaltSource;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
/**
* 提供加密的相关辅助功能
*/
public abstract class EncodeUtil {
/**
* Caff中所有的密码加密算法使用ShaPasswordEncoder
*/
public static ShaPasswordEncoder getPasswordEncoder() {
return new ShaPasswordEncoder();
}
/**
* 对于已有系统的历史数据,其使用用户实体的id作为加密种子,
* 升级时需要将exkey的值设置为实体的id。
*/
public static SaltSource getSaltSource() {
ReflectionSaltSource saltSource = new ReflectionSaltSource();
saltSource.setUserPropertyToUse("getExkey");
return saltSource;
}
/**
* 使用提供的加密种子进行加密密码,算法使用ShaPasswordEncoder。
* 此为单向加密,无法解密出密码明文。
*
* @param rawPassword 密码明文
* @param salt 加密种子
* @return 密码密文
*/
public static String getEncodedPassword(String rawPassword, String salt) {
ShaPasswordEncoder encoder = getPasswordEncoder();
return encoder.encodePassword(rawPassword, salt);
}
/**
* 使用对称性加密字符串,可使用相应算法解密出原字符串
*
* @param rawStr 原字符串
* @param salt 加密种子
* @return
* @throws Exception
*/
public static String getEncodedStr(String rawStr, String salt) throws Exception {
EncryptorAES encryptorAES = new EncryptorAES(salt);
return encryptorAES.encryt(rawStr);
}
/**
* 解密出通过对称性加密的字符串明文
*
* @param encodedStr 加密密文
* @param salt 加密种子
* @throws Exception
*/
public static String getDecodedStr(String encodedStr, String salt) throws Exception {
EncryptorAES encryptorAES = new EncryptorAES(salt);
return encryptorAES.decrypt(encodedStr);
}
/**
* 线上充值时使用到的md5签名
*
* @param text 信息明文
* @param charSet 字符集
*/
public static String md5(String text, String charSet) {
return DigestUtils.md5Hex(getContentBytes(text, charSet));
}
/**
* 线上充值时使用到的sha签名
*
* @param text 信息明文
* @param charSet 字符集
*/
public static String sha(String text, String charSet) {
return DigestUtils.sha256Hex(getContentBytes(text, charSet));
}
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("签名过程中出现错误, 指定的编码集不对, 您目前指定的编码集是:" + charset);
}
}
/**
* HMAC-SHA1 签名 暂用于有盾实名认证签名使用
* @author wangjuntao
* @date 2015年11月11日 上午9:13:17
* @Description:
* @param encryptKey 密钥
* @param encryptText 被签名的字符串
* @return
* @throws Exception
*/
/*public static String HmacSHA1Encrypt(String encryptKey,String encryptText)
{
return HmacUtils.hmacSha1Hex(encryptKey, encryptText);
}*/
}
| apache-2.0 |
johsonliu/coolweather | app/src/main/java/com/example/coolweather/gson/Now.java | 351 | package com.example.coolweather.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by user on 2016/12/14.
*/
public class Now {
@SerializedName("tmp")
public String temperature;
@SerializedName("cond")
public More more;
public class More{
@SerializedName("txt")
public String info;
}
}
| apache-2.0 |
angelowolf/Inmobiliaria | Inmobiliaria/src/java/Soporte/ServicioDoble.java | 1101 | /*
* 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 Soporte;
/**
*
* @author angelo
*/
public class ServicioDoble {
private String nombre1, nombre2;
private boolean nombre2Existe;
public ServicioDoble() {
}
public ServicioDoble(String nombre1, String nombre2, boolean nombre2Existe) {
this.nombre1 = nombre1;
this.nombre2 = nombre2;
this.nombre2Existe = nombre2Existe;
}
public boolean isNombre2Existe() {
return nombre2Existe;
}
public void setNombre2Existe(boolean nombre2Existe) {
this.nombre2Existe = nombre2Existe;
}
public String getNombre1() {
return nombre1;
}
public void setNombre1(String nombre1) {
this.nombre1 = nombre1;
}
public String getNombre2() {
return nombre2;
}
public void setNombre2(String nombre2) {
this.nombre2 = nombre2;
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationType.java | 11781 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.execution;
import com.intellij.compiler.options.CompileStepBeforeRun;
import com.intellij.compiler.options.CompileStepBeforeRunNoErrorCheck;
import com.intellij.execution.*;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.ConfigurationTypeUtil;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.impl.DefaultJavaProgramRunner;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessListener;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.wsl.WslDistributionManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.execution.build.DelegateBuildRunner;
import org.jetbrains.idea.maven.project.MavenGeneralSettings;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent;
import org.jetbrains.idea.maven.utils.MavenUtil;
import javax.swing.*;
import java.util.Collections;
import java.util.List;
import static icons.OpenapiIcons.RepositoryLibraryLogo;
/**
* @author Vladislav.Kaznacheev
*/
public final class MavenRunConfigurationType implements ConfigurationType {
private static final Key<Boolean> IS_DELEGATE_BUILD = new Key<>("IS_DELEGATE_BUILD");
private final ConfigurationFactory myFactory;
private static final int MAX_NAME_LENGTH = 40;
public static MavenRunConfigurationType getInstance() {
return ConfigurationTypeUtil.findConfigurationType(MavenRunConfigurationType.class);
}
/**
* reflection
*/
MavenRunConfigurationType() {
myFactory = new MavenRunConfigurationFactory(this);
}
@NotNull
@Override
public String getDisplayName() {
return RunnerBundle.message("maven.run.configuration.name");
}
@Override
public String getConfigurationTypeDescription() {
return RunnerBundle.message("maven.run.configuration.description");
}
@Override
public Icon getIcon() {
return RepositoryLibraryLogo;
}
@Override
public ConfigurationFactory[] getConfigurationFactories() {
return new ConfigurationFactory[]{myFactory};
}
@Override
public String getHelpTopic() {
return "reference.dialogs.rundebug.MavenRunConfiguration";
}
@Override
@NonNls
@NotNull
public String getId() {
return "MavenRunConfiguration";
}
public static @NlsSafe String generateName(Project project, MavenRunnerParameters runnerParameters) {
StringBuilder stringBuilder = new StringBuilder();
final String name = getMavenProjectName(project, runnerParameters);
if (!StringUtil.isEmptyOrSpaces(name)) {
stringBuilder.append(name);
}
List<String> goals = runnerParameters.getGoals();
if (!goals.isEmpty()) {
stringBuilder.append(" [");
listGoals(stringBuilder, goals);
stringBuilder.append("]");
}
return stringBuilder.toString();
}
private static void listGoals(final StringBuilder stringBuilder, final List<String> goals) {
int index = 0;
for (String goal : goals) {
if (index != 0) {
if (stringBuilder.length() + goal.length() < MAX_NAME_LENGTH) {
stringBuilder.append(",");
}
else {
stringBuilder.append("...");
break;
}
}
stringBuilder.append(goal);
index++;
}
}
@Nullable
private static String getMavenProjectName(final Project project, final MavenRunnerParameters runnerParameters) {
final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(runnerParameters.getWorkingDirPath() + "/pom.xml");
if (virtualFile != null) {
MavenProject mavenProject = MavenProjectsManager.getInstance(project).findProject(virtualFile);
if (mavenProject != null) {
if (!StringUtil.isEmptyOrSpaces(mavenProject.getMavenId().getArtifactId())) {
return mavenProject.getMavenId().getArtifactId();
}
}
}
return null;
}
public static boolean isDelegate(ExecutionEnvironment environment) {
Boolean res = IS_DELEGATE_BUILD.get(environment);
return res != null && res;
}
public static void runConfiguration(Project project,
MavenRunnerParameters params,
@Nullable ProgramRunner.Callback callback) {
runConfiguration(project, params, null, null, callback);
}
public static void runConfiguration(Project project,
@NotNull MavenRunnerParameters params,
@Nullable MavenGeneralSettings settings,
@Nullable MavenRunnerSettings runnerSettings,
@Nullable ProgramRunner.Callback callback) {
runConfiguration(project, params, settings, runnerSettings, callback, false);
}
public static void runConfiguration(Project project,
@NotNull MavenRunnerParameters params,
@Nullable MavenGeneralSettings settings,
@Nullable MavenRunnerSettings runnerSettings,
@Nullable ProgramRunner.Callback callback,
boolean isDelegateBuild) {
RunnerAndConfigurationSettings configSettings = createRunnerAndConfigurationSettings(settings,
runnerSettings,
params,
project,
generateName(project, params),
isDelegateBuild);
ProgramRunner runner = isDelegateBuild ? DelegateBuildRunner.getDelegateRunner() : DefaultJavaProgramRunner.getInstance();
Executor executor = DefaultRunExecutor.getRunExecutorInstance();
ExecutionEnvironment environment = new ExecutionEnvironment(executor, runner, configSettings, project);
environment.putUserData(IS_DELEGATE_BUILD, isDelegateBuild);
environment.setCallback(callback);
try {
runner.execute(environment);
}
catch (ExecutionException e) {
MavenUtil.showError(project, RunnerBundle.message("notification.title.failed.to.execute.maven.goal"), e);
}
}
@NotNull
public static RunnerAndConfigurationSettings createRunnerAndConfigurationSettings(@Nullable MavenGeneralSettings generalSettings,
@Nullable MavenRunnerSettings runnerSettings,
@NotNull MavenRunnerParameters params,
@NotNull Project project) {
return createRunnerAndConfigurationSettings(generalSettings, runnerSettings, params, project, generateName(project, params), false);
}
@NotNull
public static RunnerAndConfigurationSettings createRunnerAndConfigurationSettings(@Nullable MavenGeneralSettings generalSettings,
@Nullable MavenRunnerSettings runnerSettings,
@NotNull MavenRunnerParameters params,
@NotNull Project project,
@NotNull String name,
boolean isDelegate) {
MavenRunConfigurationType type = ConfigurationTypeUtil.findConfigurationType(MavenRunConfigurationType.class);
RunnerAndConfigurationSettings settings = RunManager.getInstance(project).createConfiguration(name, type.myFactory);
MavenRunConfiguration runConfiguration = (MavenRunConfiguration)settings.getConfiguration();
if (isDelegate) {
runConfiguration.setBeforeRunTasks(Collections.emptyList());
}
MavenGeneralSettings generalSettingsToRun =
generalSettings != null ? generalSettings : MavenWorkspaceSettingsComponent.getInstance(project).getSettings().generalSettings;
runConfiguration.setRunnerParameters(params);
runConfiguration.setGeneralSettings(generalSettingsToRun);
MavenRunnerSettings runnerSettingsToRun =
runnerSettings != null ? runnerSettings : new MavenRunnerSettings();
runConfiguration.setRunnerSettings(runnerSettingsToRun);
if (WslDistributionManager.isWslPath(params.getWorkingDirPath())) {
//todo: find appropriate WSL distribution
runConfiguration.setDefaultTargetName("WSL");
}
return settings;
}
public static class MavenRunConfigurationFactory extends ConfigurationFactory {
public MavenRunConfigurationFactory(ConfigurationType type) {super(type);}
@NotNull
@Override
public RunConfiguration createTemplateConfiguration(@NotNull Project project) {
return new MavenRunConfiguration(project, this, "");
}
@NotNull
@Override
public RunConfiguration createTemplateConfiguration(@NotNull Project project, @NotNull RunManager runManager) {
return new MavenRunConfiguration(project, this, "");
}
@Override
public @NotNull String getId() {
return "Maven";
}
@NotNull
@Override
public RunConfiguration createConfiguration(@Nullable String name, @NotNull RunConfiguration template) {
MavenRunConfiguration cfg = (MavenRunConfiguration)super.createConfiguration(name, template);
if (!StringUtil.isEmptyOrSpaces(cfg.getRunnerParameters().getWorkingDirPath())) return cfg;
Project project = cfg.getProject();
MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project);
List<MavenProject> projects = projectsManager.getProjects();
if (projects.size() != 1) {
return cfg;
}
VirtualFile directory = projects.get(0).getDirectoryFile();
cfg.getRunnerParameters().setWorkingDirPath(directory.getPath());
return cfg;
}
@Override
public void configureBeforeRunTaskDefaults(Key<? extends BeforeRunTask> providerID, BeforeRunTask task) {
if (providerID == CompileStepBeforeRun.ID || providerID == CompileStepBeforeRunNoErrorCheck.ID) {
task.setEnabled(false);
}
}
@Override
public boolean isEditableInDumbMode() {
return true;
}
}
}
| apache-2.0 |
mikeleishen/bacosys | frame/frame-domain/src/main/java/com/xinyou/frame/domain/biz/DOC_BIZ.java | 62244 | package com.xinyou.frame.domain.biz;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import com.xinyou.frame.domain.entities.DOC_MAIN;
import com.xinyou.frame.domain.entities.PARAM_MAIN;
import com.xinyou.frame.domain.entities.PRIVILEGE_MAIN;
import com.xinyou.frame.domain.models.DOC_DM;
import com.xinyou.frame.domain.models.PRIVILEGE_DM;
import com.xinyou.util.Config;
import com.xinyou.util.StringUtil;
public class DOC_BIZ extends StringUtil{
public void addDoc(DOC_MAIN doc, Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
switch (dataSourceType) {
case "oracle": addDoc_oracle(doc, conn);
break;
case "sqlserver": addDoc_sqlserver(doc, conn);
break;
default: addDoc_mysql(doc, conn);
break;
}
}
public DOC_DM getDocs(String doc_id, String doc_name, int page_no,
int page_size, Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
DOC_DM returnDM = new DOC_DM();
switch (dataSourceType) {
case "oracle": returnDM = getDoc_oracle(doc_id,doc_name,page_no,page_size,conn);
break;
case "sqlserver": returnDM = getDoc_sqlserver(doc_id,doc_name,page_no,page_size,conn);
break;
default: returnDM = getDoc_mysql(doc_id,doc_name,page_no,page_size,conn);
break;
}
return returnDM;
}
public void delDoc(String[] docguidArray, Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
switch (dataSourceType) {
case "oracle": delDoc_oracle(docguidArray, conn);
break;
case "sqlserver": delDoc_sqlserver(docguidArray, conn);
break;
default: delDoc_mysql(docguidArray, conn);
break;
}
}
public DOC_MAIN getDoc(String docguid, Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
DOC_MAIN returnEntity = new DOC_MAIN();
switch (dataSourceType) {
case "oracle": returnEntity = getDoc_oracle(docguid, conn);
break;
case "sqlserver": returnEntity = getDoc_sqlserver(docguid, conn);
break;
default: returnEntity = getDoc_mysql(docguid, conn);
break;
}
return returnEntity;
}
public void updateDoc(DOC_MAIN doc, Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
switch (dataSourceType) {
case "oracle": updateDoc_oracle(doc, conn);
break;
case "sqlserver": updateDoc_sqlserver(doc, conn);
break;
default: updateDoc_mysql(doc, conn);
break;
}
}
private void updateDoc_mysql(DOC_MAIN doc, Connection conn) throws Exception {
doc.setDoc_name(Decode(doc.getDoc_name()));
doc.setDoc_desc(Decode(doc.getDoc_desc()));
PreparedStatement pstmt = null;
try{
String uSQL = "update DOC_MAIN set UPDATED_DT=?, UPDATED_BY=?, DOC_NAME=?, DOC_DESC=?, DOC_PRE_TAG=?, DOC_MID_TAG_ID=?, DOC_SEQ_NO_LEN=?, DOC_STATUS_ID=? where IS_DELETED=0 and DOC_MAIN_GUID=?";
pstmt = conn.prepareStatement(uSQL);
pstmt.setLong(1, new Date().getTime());
pstmt.setString(2, doc.getUpdated_by());
pstmt.setString(3, doc.getDoc_name());
pstmt.setString(4, doc.getDoc_desc());
pstmt.setString(5, doc.getDoc_pre_tag());
pstmt.setString(6, doc.getDoc_mid_tag_id());
pstmt.setInt(7, doc.getDoc_seq_no_len());
pstmt.setString(8, doc.getDoc_status_id());
pstmt.setString(9, doc.getDoc_main_guid());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
private void updateDoc_oracle(DOC_MAIN doc, Connection conn) throws Exception {
doc.setDoc_name(Decode(doc.getDoc_name()));
doc.setDoc_desc(Decode(doc.getDoc_desc()));
PreparedStatement pstmt = null;
try{
String uSQL = "update DOC_MAIN set UPDATED_DT=?, UPDATED_BY=?, DOC_NAME=?, DOC_DESC=?, DOC_PRE_TAG=?, DOC_MID_TAG_ID=?, DOC_SEQ_NO_LEN=?, DOC_STATUS_ID=? where IS_DELETED=0 and DOC_MAIN_GUID=?";
pstmt = conn.prepareStatement(uSQL);
pstmt.setLong(1, new Date().getTime());
pstmt.setString(2, doc.getUpdated_by());
pstmt.setString(3, doc.getDoc_name());
pstmt.setString(4, doc.getDoc_desc());
pstmt.setString(5, doc.getDoc_pre_tag());
pstmt.setString(6, doc.getDoc_mid_tag_id());
pstmt.setInt(7, doc.getDoc_seq_no_len());
pstmt.setString(8, doc.getDoc_status_id());
pstmt.setString(9, doc.getDoc_main_guid());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
private void updateDoc_sqlserver(DOC_MAIN doc, Connection conn) throws Exception {
doc.setDoc_name(Decode(doc.getDoc_name()));
doc.setDoc_desc(Decode(doc.getDoc_desc()));
PreparedStatement pstmt = null;
try{
String uSQL = "update DOC_MAIN set UPDATED_DT=?, UPDATED_BY=?, DOC_NAME=?, DOC_DESC=?, DOC_PRE_TAG=?, DOC_MID_TAG_ID=?, DOC_SEQ_NO_LEN=?, DOC_STATUS_ID=? where IS_DELETED=0 and DOC_MAIN_GUID=?";
pstmt = conn.prepareStatement(uSQL);
pstmt.setLong(1, new Date().getTime());
pstmt.setString(2, doc.getUpdated_by());
pstmt.setString(3, doc.getDoc_name());
pstmt.setString(4, doc.getDoc_desc());
pstmt.setString(5, doc.getDoc_pre_tag());
pstmt.setString(6, doc.getDoc_mid_tag_id());
pstmt.setInt(7, doc.getDoc_seq_no_len());
pstmt.setString(8, doc.getDoc_status_id());
pstmt.setString(9, doc.getDoc_main_guid());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
public List<DOC_MAIN> getSlDocs(Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
List<DOC_MAIN> returnList = new ArrayList<DOC_MAIN>();
switch (dataSourceType) {
case "oracle": returnList = getSlDocs_oracle(conn);
break;
case "sqlserver": returnList = getSlDocs_sqlserver(conn);
break;
default: returnList = getSlDocs_mysql(conn);
break;
}
return returnList;
}
public void addPrivilege(PRIVILEGE_MAIN privilege, Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
switch (dataSourceType) {
case "oracle": addPrivilege_oracle(privilege, conn);
break;
case "sqlserver": addPrivilege_sqlserver(privilege, conn);
break;
default: addPrivilege_mysql(privilege, conn);
break;
}
}
public PRIVILEGE_DM getPrivileges(String privilege_id,
String privilege_name, String doc_guid, int page_no, int page_size,
Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
PRIVILEGE_DM returnDM = new PRIVILEGE_DM();
switch (dataSourceType) {
case "oracle": returnDM = getPrivileges_oracle(privilege_id,privilege_name,doc_guid,page_no,page_size,conn);
break;
case "sqlserver": returnDM = getPrivileges_sqlserver(privilege_id,privilege_name,doc_guid,page_no,page_size,conn);
break;
default: returnDM = getPrivileges_mysql(privilege_id,privilege_name,doc_guid,page_no,page_size,conn);
break;
}
return returnDM;
}
public void delPrivilege(String[] privilegeguidArray, Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
switch (dataSourceType) {
case "oracle": delPrivilege_oracle(privilegeguidArray, conn);
break;
case "sqlserver": delPrivilege_sqlserver(privilegeguidArray, conn);
break;
default: delPrivilege_mysql(privilegeguidArray, conn);
break;
}
}
public PRIVILEGE_MAIN getPrivilege(String privilegeguid, Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
PRIVILEGE_MAIN returnEntity = new PRIVILEGE_MAIN();
switch (dataSourceType) {
case "oracle": returnEntity = getPrivilege_oracle(privilegeguid, conn);
break;
case "sqlserver": returnEntity = getPrivilege_sqlserver(privilegeguid, conn);
break;
default: returnEntity = getPrivilege_mysql(privilegeguid, conn);
break;
}
return returnEntity;
}
public void updatePrivilege(PRIVILEGE_MAIN privilege, Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
switch (dataSourceType) {
case "oracle": updatePrivilege_oracle(privilege, conn);
break;
case "sqlserver": updatePrivilege_sqlserver(privilege, conn);
break;
default: updatePrivilege_mysql(privilege, conn);
break;
}
}
private void addDoc_mysql(DOC_MAIN doc, Connection conn) throws Exception {
doc.setDoc_main_id(Decode(doc.getDoc_main_id()));
doc.setDoc_name(Decode(doc.getDoc_name()));
doc.setDoc_status_id(Decode(doc.getDoc_status_id()));
doc.setDoc_pre_tag(Decode(doc.getDoc_pre_tag()));
doc.setDoc_mid_tag_id(Decode(doc.getDoc_mid_tag_id()));
doc.setDoc_desc(Decode(doc.getDoc_desc()));
PreparedStatement pstmt=null;
ResultSet rs = null;
try{
String cSQL="select 1 from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_ID=? limit 1";
pstmt = conn.prepareStatement(cSQL);
pstmt.setString(1, doc.getDoc_main_id());
rs = pstmt.executeQuery();
boolean exist = false;
if(rs.next()){
exist = true;
}
pstmt.close();
if(exist){
throw new Exception("权限代码 "+doc.getDoc_main_id()+" 已存在");
}
String iSQL = "insert into DOC_MAIN (DOC_MAIN_GUID, DOC_MAIN_ID, CREATED_DT, CREATED_BY, UPDATED_DT, UPDATED_BY, IS_DELETED, CLIENT_GUID, DOC_NAME, DOC_STATUS_ID ,DOC_PRE_TAG, DOC_MID_TAG_ID, DOC_SEQ_NO, DOC_SEQ_NO_LEN, DOC_DESC) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(iSQL);
String guidNew = UUID.randomUUID().toString();
pstmt.setString(1, guidNew);
pstmt.setString(2, doc.getDoc_main_id());
long lDate = new Date().getTime();
pstmt.setLong(3, lDate);
pstmt.setString(4, doc.getCreated_by());
pstmt.setLong(5, lDate);
pstmt.setString(6, doc.getUpdated_by());
pstmt.setInt(7, 0);
pstmt.setString(8, doc.getClient_guid());
pstmt.setString(9,doc.getDoc_name());
pstmt.setString(10, doc.getDoc_status_id());
pstmt.setString(11, doc.getDoc_pre_tag());
pstmt.setString(12, doc.getDoc_mid_tag_id());
pstmt.setInt(13, 0);
pstmt.setInt(14, doc.getDoc_seq_no_len());
pstmt.setString(15, doc.getDoc_desc());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
private DOC_DM getDoc_mysql(String doc_id, String doc_name, int page_no,
int page_size, Connection conn) throws Exception {
doc_id = Decode(doc_id);
doc_name = Decode(doc_name);
DOC_DM returnDM = new DOC_DM();
List<DOC_MAIN> returnList = new ArrayList<DOC_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select DOC_MAIN_GUID, DOC_MAIN_ID, DOC_NAME, DOC_DESC from DOC_MAIN";
String sSQLWhere = " where IS_DELETED=0";
if(doc_id!=null&&doc_id.length()>0){
sSQLWhere +=" and DOC_MAIN_ID like ?";
}
if(doc_name!=null&&doc_name.length()>0){
sSQLWhere +=" and DOC_NAME like ?";
}
pstmt = conn.prepareStatement(sSQL+sSQLWhere+" order by CREATED_DT desc limit "+ (page_no-1)*page_size + "," + page_size);
int index = 0;
if(doc_id!=null&&doc_id.length()>0){
pstmt.setString(++index, doc_id+"%");
}
if(doc_name!=null&&doc_name.length()>0){
pstmt.setString(++index, "%"+doc_name+"%");
}
rs = pstmt.executeQuery();
while(rs.next()){
DOC_MAIN entity = new DOC_MAIN();
entity.setDoc_main_guid(rs.getString(1));
entity.setDoc_main_id(rs.getString(2));
entity.setDoc_name(Encode(rs.getString(3)));
entity.setDoc_desc(Encode(rs.getString(4)));
returnList.add(entity);
}
returnDM.setDocListData(returnList);
pstmt.close();
pstmt = conn.prepareStatement("select count(*) from DOC_MAIN"+sSQLWhere);
index = 0;
if(doc_id!=null&&doc_id.length()>0){
pstmt.setString(++index, doc_id+"%");
}
if(doc_name!=null&&doc_name.length()>0){
pstmt.setString(++index, "%"+doc_name+"%");
}
rs = pstmt.executeQuery();
if(rs.next()){
returnDM.setCount(rs.getInt(1));
}else{
returnDM.setCount(0);
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnDM;
}
private void delDoc_mysql(String[] docguidArray, Connection conn) throws Exception {
PreparedStatement pstmt = null;
try{
conn.setAutoCommit(false);
String dSQL = "delete from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_GUID=?";
pstmt = conn.prepareStatement(dSQL);
for(String docguid : docguidArray){
pstmt.setString(1, docguid);
pstmt.addBatch();
}
pstmt.executeBatch();
conn.commit();
}catch(Exception e){
if(conn!=null){
conn.rollback();
}
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
if(conn!=null&&!conn.getAutoCommit()){
conn.setAutoCommit(true);
}
}
}
private DOC_MAIN getDoc_mysql(String docguid, Connection conn) throws Exception {
DOC_MAIN returnEntity = new DOC_MAIN();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select DOC_MAIN_GUID, DOC_MAIN_ID, DOC_NAME, DOC_DESC, DOC_PRE_TAG, DOC_MID_TAG_ID, DOC_SEQ_NO, DOC_SEQ_NO_LEN, DOC_STATUS_ID from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_GUID=? limit 1";
pstmt = conn.prepareStatement(sSQL);
pstmt.setString(1, docguid);
rs = pstmt.executeQuery();
if(rs.next()){
returnEntity.setDoc_main_guid(rs.getString(1));
returnEntity.setDoc_main_id(Encode(rs.getString(2)));
returnEntity.setDoc_name(Encode(rs.getString(3)));
returnEntity.setDoc_desc(Encode(rs.getString(4)));
returnEntity.setDoc_pre_tag(Encode(rs.getString(5)));
returnEntity.setDoc_mid_tag_id(Encode(rs.getString(6)));
returnEntity.setDoc_seq_no(rs.getInt(7));
returnEntity.setDoc_seq_no_len(rs.getInt(8));
returnEntity.setDoc_status_id(Encode(rs.getString(9)));
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnEntity;
}
private List<DOC_MAIN> getSlDocs_mysql(Connection conn) throws Exception {
List<DOC_MAIN> returnList = new ArrayList<DOC_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select DOC_MAIN_GUID, DOC_MAIN_ID, DOC_NAME, DOC_DESC from DOC_MAIN where IS_DELETED=0";
pstmt = conn.prepareStatement(sSQL);
rs = pstmt.executeQuery();
while(rs.next()){
DOC_MAIN entity = new DOC_MAIN();
entity.setDoc_main_guid(rs.getString(1));
entity.setDoc_main_id(rs.getString(2));
entity.setDoc_name(Encode(rs.getString(3)));
entity.setDoc_desc(Encode(rs.getString(4)));
returnList.add(entity);
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnList;
}
private void addPrivilege_mysql(PRIVILEGE_MAIN privilege, Connection conn) throws Exception {
privilege.setPrivilege_main_id(Decode(privilege.getPrivilege_main_id()));
privilege.setPrivilege_name(Decode(privilege.getPrivilege_name()));
privilege.setPrivilege_desc(Decode(privilege.getPrivilege_desc()));
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String cSQL = "select 1 from PRIVILEGE_MAIN where IS_DELETED=0 and PRIVILEGE_MAIN_ID=? limit 1";
pstmt = conn.prepareStatement(cSQL);
pstmt.setString(1, privilege.getPrivilege_main_id());
rs = pstmt.executeQuery();
boolean exist = false;
if(rs.next()){
exist = true;
}
pstmt.close();
if(exist){
throw new Exception("权限代码 "+privilege.getPrivilege_main_id()+" 已存在");
}
String iSQL = "insert into PRIVILEGE_MAIN (PRIVILEGE_MAIN_GUID, PRIVILEGE_MAIN_ID, CREATED_DT, CREATED_BY, UPDATED_DT, UPDATED_BY, IS_DELETED, CLIENT_GUID, PRIVILEGE_NAME, PRIVILEGE_DESC, DOC_GUID) values (?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(iSQL);
String guidNew = UUID.randomUUID().toString();
pstmt.setString(1, guidNew);
pstmt.setString(2, privilege.getPrivilege_main_id());
long lDate = new Date().getTime();
pstmt.setLong(3, lDate);
pstmt.setString(4, privilege.getCreated_by());
pstmt.setLong(5, lDate);
pstmt.setString(6, privilege.getUpdated_by());
pstmt.setInt(7, 0);
pstmt.setString(8, privilege.getClient_guid());
pstmt.setString(9, privilege.getPrivilege_name());
pstmt.setString(10, privilege.getPrivilege_desc());
pstmt.setString(11, privilege.getDoc_guid());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
private PRIVILEGE_DM getPrivileges_mysql(String privilege_id,
String privilege_name, String doc_guid, int page_no, int page_size,
Connection conn) throws Exception {
privilege_id = Decode(privilege_id);
privilege_name = Decode(privilege_name);
PRIVILEGE_DM returnDM = new PRIVILEGE_DM();
List<PRIVILEGE_MAIN> returnList = new ArrayList<PRIVILEGE_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select t.PRIVILEGE_MAIN_GUID, t.PRIVILEGE_MAIN_ID, t.PRIVILEGE_NAME, t.PRIVILEGE_DESC, t1.DOC_MAIN_ID, t1.DOC_NAME from PRIVILEGE_MAIN as t inner join DOC_MAIN as t1 on t1.IS_DELETED=0 and t.DOC_GUID = t1.DOC_MAIN_GUID";
String sSQLWhere = " where t.IS_DELETED=0";
if(doc_guid!=null&&doc_guid.length()!=0){
sSQLWhere +=" and t.DOC_GUID=?";
}
if(privilege_id!=null&&privilege_id.length()!=0){
sSQLWhere +=" and t.PRIVILEGE_MAIN_ID like ?";
}
if(privilege_name!=null&&privilege_name.length()>0){
sSQLWhere +=" and t.PRIVILEGE_NAME like ?";
}
pstmt = conn.prepareStatement(sSQL+sSQLWhere+" order by t.CREATED_DT desc limit "+ (page_no-1)*page_size + "," + page_size);
int index = 0;
if(doc_guid!=null&&doc_guid.length()!=0){
pstmt.setString(++index, doc_guid);
}
if(privilege_id!=null&&privilege_id.length()!=0){
pstmt.setString(++index, privilege_id+"%");
}
if(privilege_name!=null&&privilege_name.length()>0){
pstmt.setString(++index, "%"+privilege_name+"%");
}
rs = pstmt.executeQuery();
while(rs.next()){
PRIVILEGE_MAIN entity = new PRIVILEGE_MAIN();
entity.setPrivilege_main_guid(rs.getString(1));
entity.setPrivilege_main_id(Encode(rs.getString(2)));
entity.setPrivilege_name(Encode(rs.getString(3)));
entity.setPrivilege_desc(Encode(rs.getString(4)));
entity.setDoc_id(Encode(rs.getString(5)));
entity.setDoc_name(Encode(rs.getString(6)));
returnList.add(entity);
}
returnDM.setPrivilegeListData(returnList);
pstmt.close();
sSQLWhere = " where t.IS_DELETED=0";
if(doc_guid!=null&&doc_guid.length()!=0){
sSQLWhere +=" and t.DOC_GUID=?";
}
if(privilege_id!=null&&privilege_id.length()!=0){
sSQLWhere +=" and t.PRIVILEGE_MAIN_ID like ?";
}
if(privilege_name!=null&&privilege_name.length()>0){
sSQLWhere +=" and t.PRIVILEGE_NAME like ?";
}
pstmt = conn.prepareStatement("select count(*) from PRIVILEGE_MAIN t inner join DOC_MAIN t1 on t1.IS_DELETED=0 and t.DOC_GUID = t1.DOC_MAIN_GUID"+sSQLWhere);
index = 0;
if(doc_guid!=null&&doc_guid.length()!=0){
pstmt.setString(++index, doc_guid);
}
if(privilege_id!=null&&privilege_id.length()!=0){
pstmt.setString(++index, privilege_id+"%");
}
if(privilege_name!=null&&privilege_name.length()>0){
pstmt.setString(++index, "%"+privilege_name+"%");
}
rs = pstmt.executeQuery();
if(rs.next()){
returnDM.setCount(rs.getInt(1));
}else{
returnDM.setCount(0);
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnDM;
}
private void delPrivilege_mysql(String[] privilegeguidArray, Connection conn) throws Exception {
PreparedStatement pstmt = null;
try{
conn.setAutoCommit(false);
String dSQL = "delete from PRIVILEGE_MAIN where IS_DELETED=0 and PRIVILEGE_MAIN_GUID=?";
pstmt = conn.prepareStatement(dSQL);
for(String privilegeguid : privilegeguidArray){
pstmt.setString(1, privilegeguid);
pstmt.addBatch();
}
pstmt.executeBatch();
conn.commit();
}catch(Exception e){
if(conn!=null){
conn.rollback();
}
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
if(conn!=null&&!conn.getAutoCommit()){
conn.setAutoCommit(true);
}
}
}
private PRIVILEGE_MAIN getPrivilege_mysql(String privilegeguid,
Connection conn) throws Exception {
PRIVILEGE_MAIN returnEntity = new PRIVILEGE_MAIN();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select PRIVILEGE_MAIN_GUID, PRIVILEGE_MAIN_ID, PRIVILEGE_NAME, PRIVILEGE_DESC, DOC_GUID from PRIVILEGE_MAIN where IS_DELETED=0 and PRIVILEGE_MAIN_GUID=? limit 1";
pstmt = conn.prepareStatement(sSQL);
pstmt.setString(1, privilegeguid);
rs = pstmt.executeQuery();
if(rs.next()){
returnEntity.setPrivilege_main_guid(rs.getString(1));
returnEntity.setPrivilege_main_id(rs.getString(2));
returnEntity.setPrivilege_name(rs.getString(3));
returnEntity.setPrivilege_desc(rs.getString(4));
returnEntity.setDoc_guid(rs.getString(5));
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnEntity;
}
private void updatePrivilege_mysql(PRIVILEGE_MAIN privilege, Connection conn) throws Exception {
privilege.setPrivilege_name(Decode(privilege.getPrivilege_name()));
privilege.setPrivilege_desc(Decode(privilege.getPrivilege_desc()));
PreparedStatement pstmt = null;
try{
String uSQL = "update PRIVILEGE_MAIN set UPDATED_DT=?, UPDATED_BY=?, PRIVILEGE_NAME=?, PRIVILEGE_DESC=? where IS_DELETED=0 and PRIVILEGE_MAIN_GUID=?";
pstmt = conn.prepareStatement(uSQL);
pstmt.setLong(1, new Date().getTime());
pstmt.setString(2, privilege.getUpdated_by());
pstmt.setString(3, privilege.getPrivilege_name());
pstmt.setString(4, privilege.getPrivilege_desc());
pstmt.setString(5, privilege.getPrivilege_main_guid());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
private void addDoc_oracle(DOC_MAIN doc, Connection conn) throws Exception {
doc.setDoc_main_id(Decode(doc.getDoc_main_id()));
doc.setDoc_name(Decode(doc.getDoc_name()));
doc.setDoc_status_id(Decode(doc.getDoc_status_id()));
doc.setDoc_pre_tag(Decode(doc.getDoc_pre_tag()));
doc.setDoc_mid_tag_id(Decode(doc.getDoc_mid_tag_id()));
doc.setDoc_desc(Decode(doc.getDoc_desc()));
PreparedStatement pstmt=null;
ResultSet rs = null;
try{
String cSQL="select 1 from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_ID=? and ROWNUM=1";
pstmt = conn.prepareStatement(cSQL);
pstmt.setString(1, doc.getDoc_main_id());
rs = pstmt.executeQuery();
boolean exist = false;
if(rs.next()){
exist = true;
}
pstmt.close();
if(exist){
throw new Exception("权限代码 "+doc.getDoc_main_id()+" 已存在");
}
String iSQL = "insert into DOC_MAIN (DOC_MAIN_GUID, DOC_MAIN_ID, CREATED_DT, CREATED_BY, UPDATED_DT, UPDATED_BY, IS_DELETED, CLIENT_GUID, DOC_NAME, DOC_STATUS_ID ,DOC_PRE_TAG, DOC_MID_TAG_ID, DOC_SEQ_NO, DOC_SEQ_NO_LEN, DOC_DESC) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(iSQL);
String guidNew = UUID.randomUUID().toString();
pstmt.setString(1, guidNew);
pstmt.setString(2, doc.getDoc_main_id());
long lDate = new Date().getTime();
pstmt.setLong(3, lDate);
pstmt.setString(4, doc.getCreated_by());
pstmt.setLong(5, lDate);
pstmt.setString(6, doc.getUpdated_by());
pstmt.setInt(7, 0);
pstmt.setString(8, doc.getClient_guid());
pstmt.setString(9,doc.getDoc_name());
pstmt.setString(10, doc.getDoc_status_id());
pstmt.setString(11, doc.getDoc_pre_tag());
pstmt.setString(12, doc.getDoc_mid_tag_id());
pstmt.setInt(13, 0);
pstmt.setInt(14, doc.getDoc_seq_no_len());
pstmt.setString(15, doc.getDoc_desc());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
private DOC_DM getDoc_oracle(String doc_id, String doc_name, int page_no,
int page_size, Connection conn) throws Exception {
doc_id = Decode(doc_id);
doc_name = Decode(doc_name);
if(page_no<=0)page_no=1;
if(page_size<=0)page_size=10;
int iRowStart = (page_no-1)*page_size+1;
int iRowEnd = iRowStart + page_size - 1;;
DOC_DM returnDM = new DOC_DM();
List<DOC_MAIN> returnList = new ArrayList<DOC_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String subSQL = "select DOC_MAIN_GUID, DOC_MAIN_ID, DOC_NAME, DOC_DESC from DOC_MAIN";
String subSQLWhere = " where IS_DELETED=0";
if(doc_id!=null&&doc_id.length()>0){
subSQLWhere +=" and DOC_MAIN_ID like ?";
}
if(doc_name!=null&&doc_name.length()>0){
subSQLWhere +=" and DOC_NAME like ?";
}
subSQL = subSQL+subSQLWhere+" order by CREATED_DT desc";
String sSQL = "select B.* from (select A.*, ROWNUM as RN from ("+ subSQL +") A) B where B.RN>=? and B.RN <=?";
pstmt = conn.prepareStatement(sSQL);
int index = 0;
if(doc_id!=null&&doc_id.length()>0){
pstmt.setString(++index, doc_id+"%");
}
if(doc_name!=null&&doc_name.length()>0){
pstmt.setString(++index, "%"+doc_name+"%");
}
pstmt.setInt(++index, iRowStart);
pstmt.setInt(++index, iRowEnd);
rs = pstmt.executeQuery();
while(rs.next()){
DOC_MAIN entity = new DOC_MAIN();
entity.setDoc_main_guid(rs.getString(1));
entity.setDoc_main_id(rs.getString(2));
entity.setDoc_name(Encode(rs.getString(3)));
entity.setDoc_desc(Encode(rs.getString(4)));
returnList.add(entity);
}
returnDM.setDocListData(returnList);
pstmt.close();
pstmt = conn.prepareStatement("select count(*) from DOC_MAIN"+subSQLWhere);
index = 0;
if(doc_id!=null&&doc_id.length()>0){
pstmt.setString(++index, doc_id+"%");
}
if(doc_name!=null&&doc_name.length()>0){
pstmt.setString(++index, "%"+doc_name+"%");
}
rs = pstmt.executeQuery();
if(rs.next()){
returnDM.setCount(rs.getInt(1));
}else{
returnDM.setCount(0);
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnDM;
}
private void delDoc_oracle(String[] docguidArray, Connection conn) throws Exception {
PreparedStatement pstmt = null;
try{
conn.setAutoCommit(false);
String dSQL = "delete from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_GUID=?";
pstmt = conn.prepareStatement(dSQL);
for(String docguid : docguidArray){
pstmt.setString(1, docguid);
pstmt.addBatch();
}
pstmt.executeBatch();
conn.commit();
}catch(Exception e){
if(conn!=null){
conn.rollback();
}
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
if(conn!=null&&!conn.getAutoCommit()){
conn.setAutoCommit(true);
}
}
}
private DOC_MAIN getDoc_oracle(String docguid, Connection conn) throws Exception {
DOC_MAIN returnEntity = new DOC_MAIN();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select DOC_MAIN_GUID, DOC_MAIN_ID, DOC_NAME, DOC_DESC, DOC_PRE_TAG, DOC_MID_TAG_ID, DOC_SEQ_NO, DOC_SEQ_NO_LEN, DOC_STATUS_ID from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_GUID=? and ROWNUM=1";
pstmt = conn.prepareStatement(sSQL);
pstmt.setString(1, docguid);
rs = pstmt.executeQuery();
if(rs.next()){
returnEntity.setDoc_main_guid(rs.getString(1));
returnEntity.setDoc_main_id(Encode(rs.getString(2)));
returnEntity.setDoc_name(Encode(rs.getString(3)));
returnEntity.setDoc_desc(Encode(rs.getString(4)));
returnEntity.setDoc_pre_tag(Encode(rs.getString(5)));
returnEntity.setDoc_mid_tag_id(Encode(rs.getString(6)));
returnEntity.setDoc_seq_no(rs.getInt(7));
returnEntity.setDoc_seq_no_len(rs.getInt(8));
returnEntity.setDoc_status_id(Encode(rs.getString(9)));
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnEntity;
}
private List<DOC_MAIN> getSlDocs_oracle(Connection conn) throws Exception {
List<DOC_MAIN> returnList = new ArrayList<DOC_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select DOC_MAIN_GUID, DOC_MAIN_ID, DOC_NAME, DOC_DESC from DOC_MAIN where IS_DELETED=0";
pstmt = conn.prepareStatement(sSQL);
rs = pstmt.executeQuery();
while(rs.next()){
DOC_MAIN entity = new DOC_MAIN();
entity.setDoc_main_guid(rs.getString(1));
entity.setDoc_main_id(rs.getString(2));
entity.setDoc_name(Encode(rs.getString(3)));
entity.setDoc_desc(Encode(rs.getString(4)));
returnList.add(entity);
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnList;
}
private void addPrivilege_oracle(PRIVILEGE_MAIN privilege, Connection conn) throws Exception {
privilege.setPrivilege_main_id(Decode(privilege.getPrivilege_main_id()));
privilege.setPrivilege_name(Decode(privilege.getPrivilege_name()));
privilege.setPrivilege_desc(Decode(privilege.getPrivilege_desc()));
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String cSQL = "select 1 from PRIVILEGE_MAIN where IS_DELETED=0 and PRIVILEGE_MAIN_ID=? and ROWNUM=1";
pstmt = conn.prepareStatement(cSQL);
pstmt.setString(1, privilege.getPrivilege_main_id());
rs = pstmt.executeQuery();
boolean exist = false;
if(rs.next()){
exist = true;
}
pstmt.close();
if(exist){
throw new Exception("权限代码 "+privilege.getPrivilege_main_id()+" 已存在");
}
String iSQL = "insert into PRIVILEGE_MAIN (PRIVILEGE_MAIN_GUID, PRIVILEGE_MAIN_ID, CREATED_DT, CREATED_BY, UPDATED_DT, UPDATED_BY, IS_DELETED, CLIENT_GUID, PRIVILEGE_NAME, PRIVILEGE_DESC, DOC_GUID) values (?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(iSQL);
String guidNew = UUID.randomUUID().toString();
pstmt.setString(1, guidNew);
pstmt.setString(2, privilege.getPrivilege_main_id());
long lDate = new Date().getTime();
pstmt.setLong(3, lDate);
pstmt.setString(4, privilege.getCreated_by());
pstmt.setLong(5, lDate);
pstmt.setString(6, privilege.getUpdated_by());
pstmt.setInt(7, 0);
pstmt.setString(8, privilege.getClient_guid());
pstmt.setString(9, privilege.getPrivilege_name());
pstmt.setString(10, privilege.getPrivilege_desc());
pstmt.setString(11, privilege.getDoc_guid());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
private PRIVILEGE_DM getPrivileges_oracle(String privilege_id,
String privilege_name, String doc_guid, int page_no, int page_size,
Connection conn) throws Exception {
privilege_id = Decode(privilege_id);
privilege_name = Decode(privilege_name);
if(page_no<=0)page_no=1;
if(page_size<=0)page_size=10;
int iRowStart = (page_no-1)*page_size+1;
int iRowEnd = iRowStart + page_size - 1;;
PRIVILEGE_DM returnDM = new PRIVILEGE_DM();
List<PRIVILEGE_MAIN> returnList = new ArrayList<PRIVILEGE_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String subSQL = "select t.PRIVILEGE_MAIN_GUID, t.PRIVILEGE_MAIN_ID, t.PRIVILEGE_NAME, t.PRIVILEGE_DESC, t1.DOC_MAIN_ID, t1.DOC_NAME from PRIVILEGE_MAIN t inner join DOC_MAIN t1 on t1.IS_DELETED=0 and t.DOC_GUID = t1.DOC_MAIN_GUID";
String subSQLWhere = " where t.IS_DELETED=0";
if(doc_guid!=null&&doc_guid.length()!=0){
subSQLWhere +=" and t.DOC_GUID=?";
}
if(privilege_id!=null&&privilege_id.length()!=0){
subSQLWhere +=" and t.PRIVILEGE_MAIN_ID like ?";
}
if(privilege_name!=null&&privilege_name.length()>0){
subSQLWhere +=" and t.PRIVILEGE_NAME like ?";
}
subSQL = subSQL+subSQLWhere+" order by t.CREATED_DT desc";
String sSQL = "select B.* from (select A.*, ROWNUM as RN from ("+ subSQL +") A) B where B.RN>=? and B.RN <=?";
pstmt = conn.prepareStatement(sSQL);
int index = 0;
if(doc_guid!=null&&doc_guid.length()!=0){
pstmt.setString(++index, doc_guid);
}
if(privilege_id!=null&&privilege_id.length()!=0){
pstmt.setString(++index, privilege_id+"%");
}
if(privilege_name!=null&&privilege_name.length()>0){
pstmt.setString(++index, "%"+privilege_name+"%");
}
pstmt.setInt(++index, iRowStart);
pstmt.setInt(++index, iRowEnd);
rs = pstmt.executeQuery();
while(rs.next()){
PRIVILEGE_MAIN entity = new PRIVILEGE_MAIN();
entity.setPrivilege_main_guid(rs.getString(1));
entity.setPrivilege_main_id(Encode(rs.getString(2)));
entity.setPrivilege_name(Encode(rs.getString(3)));
entity.setPrivilege_desc(Encode(rs.getString(4)));
entity.setDoc_id(Encode(rs.getString(5)));
entity.setDoc_name(Encode(rs.getString(6)));
returnList.add(entity);
}
returnDM.setPrivilegeListData(returnList);
pstmt.close();
subSQLWhere = " where t.IS_DELETED=0";
if(doc_guid!=null&&doc_guid.length()!=0){
subSQLWhere +=" and t.DOC_GUID=?";
}
if(privilege_id!=null&&privilege_id.length()!=0){
subSQLWhere +=" and t.PRIVILEGE_MAIN_ID like ?";
}
if(privilege_name!=null&&privilege_name.length()>0){
subSQLWhere +=" and t.PRIVILEGE_NAME like ?";
}
pstmt = conn.prepareStatement("select count(*) from PRIVILEGE_MAIN t inner join DOC_MAIN t1 on t1.IS_DELETED=0 and t.DOC_GUID = t1.DOC_MAIN_GUID"+subSQLWhere);
index = 0;
if(doc_guid!=null&&doc_guid.length()!=0){
pstmt.setString(++index, doc_guid);
}
if(privilege_id!=null&&privilege_id.length()!=0){
pstmt.setString(++index, privilege_id+"%");
}
if(privilege_name!=null&&privilege_name.length()>0){
pstmt.setString(++index, "%"+privilege_name+"%");
}
rs = pstmt.executeQuery();
if(rs.next()){
returnDM.setCount(rs.getInt(1));
}else{
returnDM.setCount(0);
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnDM;
}
private void delPrivilege_oracle(String[] privilegeguidArray,
Connection conn) throws Exception {
PreparedStatement pstmt = null;
try{
conn.setAutoCommit(false);
String dSQL = "delete from PRIVILEGE_MAIN where IS_DELETED=0 and PRIVILEGE_MAIN_GUID=?";
pstmt = conn.prepareStatement(dSQL);
for(String privilegeguid : privilegeguidArray){
pstmt.setString(1, privilegeguid);
pstmt.addBatch();
}
pstmt.executeBatch();
conn.commit();
}catch(Exception e){
if(conn!=null){
conn.rollback();
}
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
if(conn!=null&&!conn.getAutoCommit()){
conn.setAutoCommit(true);
}
}
}
private PRIVILEGE_MAIN getPrivilege_oracle(String privilegeguid,
Connection conn) throws Exception {
PRIVILEGE_MAIN returnEntity = new PRIVILEGE_MAIN();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select PRIVILEGE_MAIN_GUID, PRIVILEGE_MAIN_ID, PRIVILEGE_NAME, PRIVILEGE_DESC, DOC_GUID from PRIVILEGE_MAIN where IS_DELETED=0 and PRIVILEGE_MAIN_GUID=? and ROWNUM=1";
pstmt = conn.prepareStatement(sSQL);
pstmt.setString(1, privilegeguid);
rs = pstmt.executeQuery();
if(rs.next()){
returnEntity.setPrivilege_main_guid(rs.getString(1));
returnEntity.setPrivilege_main_id(rs.getString(2));
returnEntity.setPrivilege_name(rs.getString(3));
returnEntity.setPrivilege_desc(rs.getString(4));
returnEntity.setDoc_guid(rs.getString(5));
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnEntity;
}
private void updatePrivilege_oracle(PRIVILEGE_MAIN privilege,
Connection conn) throws Exception {
privilege.setPrivilege_name(Decode(privilege.getPrivilege_name()));
privilege.setPrivilege_desc(Decode(privilege.getPrivilege_desc()));
PreparedStatement pstmt = null;
try{
String uSQL = "update PRIVILEGE_MAIN set UPDATED_DT=?, UPDATED_BY=?, PRIVILEGE_NAME=?, PRIVILEGE_DESC=? where IS_DELETED=0 and PRIVILEGE_MAIN_GUID=?";
pstmt = conn.prepareStatement(uSQL);
pstmt.setLong(1, new Date().getTime());
pstmt.setString(2, privilege.getUpdated_by());
pstmt.setString(3, privilege.getPrivilege_name());
pstmt.setString(4, privilege.getPrivilege_desc());
pstmt.setString(5, privilege.getPrivilege_main_guid());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
private void addDoc_sqlserver(DOC_MAIN doc, Connection conn) throws Exception {
doc.setDoc_main_id(Decode(doc.getDoc_main_id()));
doc.setDoc_name(Decode(doc.getDoc_name()));
doc.setDoc_status_id(Decode(doc.getDoc_status_id()));
doc.setDoc_pre_tag(Decode(doc.getDoc_pre_tag()));
doc.setDoc_mid_tag_id(Decode(doc.getDoc_mid_tag_id()));
doc.setDoc_desc(Decode(doc.getDoc_desc()));
PreparedStatement pstmt=null;
ResultSet rs = null;
try{
String cSQL="select top 1 1 from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_ID=?";
pstmt = conn.prepareStatement(cSQL);
pstmt.setString(1, doc.getDoc_main_id());
rs = pstmt.executeQuery();
boolean exist = false;
if(rs.next()){
exist = true;
}
pstmt.close();
if(exist){
throw new Exception("权限代码 "+doc.getDoc_main_id()+" 已存在");
}
String iSQL = "insert into DOC_MAIN (DOC_MAIN_GUID, DOC_MAIN_ID, CREATED_DT, CREATED_BY, UPDATED_DT, UPDATED_BY, IS_DELETED, CLIENT_GUID, DOC_NAME, DOC_STATUS_ID ,DOC_PRE_TAG, DOC_MID_TAG_ID, DOC_SEQ_NO, DOC_SEQ_NO_LEN, DOC_DESC) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(iSQL);
String guidNew = UUID.randomUUID().toString();
pstmt.setString(1, guidNew);
pstmt.setString(2, doc.getDoc_main_id());
long lDate = new Date().getTime();
pstmt.setLong(3, lDate);
pstmt.setString(4, doc.getCreated_by());
pstmt.setLong(5, lDate);
pstmt.setString(6, doc.getUpdated_by());
pstmt.setInt(7, 0);
pstmt.setString(8, doc.getClient_guid());
pstmt.setString(9,doc.getDoc_name());
pstmt.setString(10, doc.getDoc_status_id());
pstmt.setString(11, doc.getDoc_pre_tag());
pstmt.setString(12, doc.getDoc_mid_tag_id());
pstmt.setInt(13, 0);
pstmt.setInt(14, doc.getDoc_seq_no_len());
pstmt.setString(15, doc.getDoc_desc());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
private DOC_DM getDoc_sqlserver(String doc_id, String doc_name,
int page_no, int page_size, Connection conn) throws Exception {
doc_id = Decode(doc_id);
doc_name = Decode(doc_name);
if(page_no<=0)page_no=1;
if(page_size<=0)page_size=10;
int iRowStart = (page_no-1)*page_size+1;
int iRowEnd = iRowStart + page_size - 1;;
DOC_DM returnDM = new DOC_DM();
List<DOC_MAIN> returnList = new ArrayList<DOC_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String subSQL = "select DOC_MAIN_GUID, DOC_MAIN_ID, DOC_NAME, DOC_DESC, CREATED_DT from DOC_MAIN";
String subSQLWhere = " where IS_DELETED=0";
String subOrderby="order by CREATED_DT desc";
if(doc_id!=null&&doc_id.length()>0){
subSQLWhere +=" and DOC_MAIN_ID like ?";
}
if(doc_name!=null&&doc_name.length()>0){
subSQLWhere +=" and DOC_NAME like ?";
}
subSQL = subSQL+subSQLWhere;
String sSQL = "select B.* from (select A.*, ROW_NUMBER() over("+subOrderby+") as RN from ("+ subSQL +") A) B where B.RN>=? and B.RN <=?";
pstmt = conn.prepareStatement(sSQL);
int index = 0;
if(doc_id!=null&&doc_id.length()>0){
pstmt.setString(++index, doc_id+"%");
}
if(doc_name!=null&&doc_name.length()>0){
pstmt.setString(++index, "%"+doc_name+"%");
}
pstmt.setInt(++index, iRowStart);
pstmt.setInt(++index, iRowEnd);
rs = pstmt.executeQuery();
while(rs.next()){
DOC_MAIN entity = new DOC_MAIN();
entity.setDoc_main_guid(rs.getString(1));
entity.setDoc_main_id(rs.getString(2));
entity.setDoc_name(Encode(rs.getString(3)));
entity.setDoc_desc(Encode(rs.getString(4)));
returnList.add(entity);
}
returnDM.setDocListData(returnList);
pstmt.close();
pstmt = conn.prepareStatement("select count(DOC_MAIN_GUID) from DOC_MAIN"+subSQLWhere);
index = 0;
if(doc_id!=null&&doc_id.length()>0){
pstmt.setString(++index, doc_id+"%");
}
if(doc_name!=null&&doc_name.length()>0){
pstmt.setString(++index, "%"+doc_name+"%");
}
rs = pstmt.executeQuery();
if(rs.next()){
returnDM.setCount(rs.getInt(1));
}else{
returnDM.setCount(0);
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnDM;
}
private void delDoc_sqlserver(String[] docguidArray, Connection conn) throws Exception {
PreparedStatement pstmt = null;
try{
conn.setAutoCommit(false);
String dSQL = "delete from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_GUID=?";
pstmt = conn.prepareStatement(dSQL);
for(String docguid : docguidArray){
pstmt.setString(1, docguid);
pstmt.addBatch();
}
pstmt.executeBatch();
conn.commit();
}catch(Exception e){
if(conn!=null){
conn.rollback();
}
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
if(conn!=null&&!conn.getAutoCommit()){
conn.setAutoCommit(true);
}
}
}
private DOC_MAIN getDoc_sqlserver(String docguid, Connection conn) throws Exception {
DOC_MAIN returnEntity = new DOC_MAIN();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select top 1 DOC_MAIN_GUID, DOC_MAIN_ID, DOC_NAME, DOC_DESC, DOC_PRE_TAG, DOC_MID_TAG_ID, DOC_SEQ_NO, DOC_SEQ_NO_LEN, DOC_STATUS_ID from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_GUID=?";
pstmt = conn.prepareStatement(sSQL);
pstmt.setString(1, docguid);
rs = pstmt.executeQuery();
if(rs.next()){
returnEntity.setDoc_main_guid(rs.getString(1));
returnEntity.setDoc_main_id(Encode(rs.getString(2)));
returnEntity.setDoc_name(Encode(rs.getString(3)));
returnEntity.setDoc_desc(Encode(rs.getString(4)));
returnEntity.setDoc_pre_tag(Encode(rs.getString(5)));
returnEntity.setDoc_mid_tag_id(Encode(rs.getString(6)));
returnEntity.setDoc_seq_no(rs.getInt(7));
returnEntity.setDoc_seq_no_len(rs.getInt(8));
returnEntity.setDoc_status_id(Encode(rs.getString(9)));
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnEntity;
}
private List<DOC_MAIN> getSlDocs_sqlserver(Connection conn) throws Exception {
List<DOC_MAIN> returnList = new ArrayList<DOC_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select DOC_MAIN_GUID, DOC_MAIN_ID, DOC_NAME, DOC_DESC from DOC_MAIN where IS_DELETED=0";
pstmt = conn.prepareStatement(sSQL);
rs = pstmt.executeQuery();
while(rs.next()){
DOC_MAIN entity = new DOC_MAIN();
entity.setDoc_main_guid(rs.getString(1));
entity.setDoc_main_id(rs.getString(2));
entity.setDoc_name(Encode(rs.getString(3)));
entity.setDoc_desc(Encode(rs.getString(4)));
returnList.add(entity);
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnList;
}
private void addPrivilege_sqlserver(PRIVILEGE_MAIN privilege,
Connection conn) throws Exception {
privilege.setPrivilege_main_id(Decode(privilege.getPrivilege_main_id()));
privilege.setPrivilege_name(Decode(privilege.getPrivilege_name()));
privilege.setPrivilege_desc(Decode(privilege.getPrivilege_desc()));
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String cSQL = "select top 1 1 from PRIVILEGE_MAIN where IS_DELETED=0 and PRIVILEGE_MAIN_ID=?";
pstmt = conn.prepareStatement(cSQL);
pstmt.setString(1, privilege.getPrivilege_main_id());
rs = pstmt.executeQuery();
boolean exist = false;
if(rs.next()){
exist = true;
}
pstmt.close();
if(exist){
throw new Exception("权限代码 "+privilege.getPrivilege_main_id()+" 已存在");
}
String iSQL = "insert into PRIVILEGE_MAIN (PRIVILEGE_MAIN_GUID, PRIVILEGE_MAIN_ID, CREATED_DT, CREATED_BY, UPDATED_DT, UPDATED_BY, IS_DELETED, CLIENT_GUID, PRIVILEGE_NAME, PRIVILEGE_DESC, DOC_GUID) values (?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(iSQL);
String guidNew = UUID.randomUUID().toString();
pstmt.setString(1, guidNew);
pstmt.setString(2, privilege.getPrivilege_main_id());
long lDate = new Date().getTime();
pstmt.setLong(3, lDate);
pstmt.setString(4, privilege.getCreated_by());
pstmt.setLong(5, lDate);
pstmt.setString(6, privilege.getUpdated_by());
pstmt.setInt(7, 0);
pstmt.setString(8, privilege.getClient_guid());
pstmt.setString(9, privilege.getPrivilege_name());
pstmt.setString(10, privilege.getPrivilege_desc());
pstmt.setString(11, privilege.getDoc_guid());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
private PRIVILEGE_DM getPrivileges_sqlserver(String privilege_id,
String privilege_name, String doc_guid, int page_no, int page_size,
Connection conn) throws Exception {
privilege_id = Decode(privilege_id);
privilege_name = Decode(privilege_name);
if(page_no<=0)page_no=1;
if(page_size<=0)page_size=10;
int iRowStart = (page_no-1)*page_size+1;
int iRowEnd = iRowStart + page_size - 1;;
PRIVILEGE_DM returnDM = new PRIVILEGE_DM();
List<PRIVILEGE_MAIN> returnList = new ArrayList<PRIVILEGE_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String subSQL = "select t.PRIVILEGE_MAIN_GUID, t.PRIVILEGE_MAIN_ID, t.PRIVILEGE_NAME, t.PRIVILEGE_DESC, t1.DOC_MAIN_ID, t1.DOC_NAME, t.CREATED_DT from PRIVILEGE_MAIN t inner join DOC_MAIN t1 on t1.IS_DELETED=0 and t.DOC_GUID = t1.DOC_MAIN_GUID";
String subSQLWhere = " where t.IS_DELETED=0";
String subOrderby="order by CREATED_DT desc";
if(doc_guid!=null&&doc_guid.length()!=0){
subSQLWhere +=" and t.DOC_GUID=?";
}
if(privilege_id!=null&&privilege_id.length()!=0){
subSQLWhere +=" and t.PRIVILEGE_MAIN_ID like ?";
}
if(privilege_name!=null&&privilege_name.length()>0){
subSQLWhere +=" and t.PRIVILEGE_NAME like ?";
}
subSQL = subSQL+subSQLWhere;
String sSQL = "select B.* from (select A.*, ROW_NUMBER() over("+subOrderby+") as RN from ("+ subSQL +") A) B where B.RN>=? and B.RN <=?";
pstmt = conn.prepareStatement(sSQL);
int index = 0;
if(doc_guid!=null&&doc_guid.length()!=0){
pstmt.setString(++index, doc_guid);
}
if(privilege_id!=null&&privilege_id.length()!=0){
pstmt.setString(++index, privilege_id+"%");
}
if(privilege_name!=null&&privilege_name.length()>0){
pstmt.setString(++index, "%"+privilege_name+"%");
}
pstmt.setInt(++index, iRowStart);
pstmt.setInt(++index, iRowEnd);
rs = pstmt.executeQuery();
while(rs.next()){
PRIVILEGE_MAIN entity = new PRIVILEGE_MAIN();
entity.setPrivilege_main_guid(rs.getString(1));
entity.setPrivilege_main_id(Encode(rs.getString(2)));
entity.setPrivilege_name(Encode(rs.getString(3)));
entity.setPrivilege_desc(Encode(rs.getString(4)));
entity.setDoc_id(Encode(rs.getString(5)));
entity.setDoc_name(Encode(rs.getString(6)));
returnList.add(entity);
}
returnDM.setPrivilegeListData(returnList);
pstmt.close();
subSQLWhere = " where t.IS_DELETED=0";
if(doc_guid!=null&&doc_guid.length()!=0){
subSQLWhere +=" and t.DOC_GUID=?";
}
if(privilege_id!=null&&privilege_id.length()!=0){
subSQLWhere +=" and t.PRIVILEGE_MAIN_ID like ?";
}
if(privilege_name!=null&&privilege_name.length()>0){
subSQLWhere +=" and t.PRIVILEGE_NAME like ?";
}
pstmt = conn.prepareStatement("select count(*) from PRIVILEGE_MAIN t inner join DOC_MAIN t1 on t1.IS_DELETED=0 and t.DOC_GUID = t1.DOC_MAIN_GUID"+subSQLWhere);
index = 0;
if(doc_guid!=null&&doc_guid.length()!=0){
pstmt.setString(++index, doc_guid);
}
if(privilege_id!=null&&privilege_id.length()!=0){
pstmt.setString(++index, privilege_id+"%");
}
if(privilege_name!=null&&privilege_name.length()>0){
pstmt.setString(++index, "%"+privilege_name+"%");
}
rs = pstmt.executeQuery();
if(rs.next()){
returnDM.setCount(rs.getInt(1));
}else{
returnDM.setCount(0);
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnDM;
}
private void delPrivilege_sqlserver(String[] privilegeguidArray,
Connection conn) throws Exception {
PreparedStatement pstmt = null;
try{
conn.setAutoCommit(false);
String dSQL = "delete from PRIVILEGE_MAIN where IS_DELETED=0 and PRIVILEGE_MAIN_GUID=?";
pstmt = conn.prepareStatement(dSQL);
for(String privilegeguid : privilegeguidArray){
pstmt.setString(1, privilegeguid);
pstmt.addBatch();
}
pstmt.executeBatch();
conn.commit();
}catch(Exception e){
if(conn!=null){
conn.rollback();
}
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
if(conn!=null&&!conn.getAutoCommit()){
conn.setAutoCommit(true);
}
}
}
private PRIVILEGE_MAIN getPrivilege_sqlserver(String privilegeguid,
Connection conn) throws Exception {
PRIVILEGE_MAIN returnEntity = new PRIVILEGE_MAIN();
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
String sSQL = "select top 1 PRIVILEGE_MAIN_GUID, PRIVILEGE_MAIN_ID, PRIVILEGE_NAME, PRIVILEGE_DESC, DOC_GUID from PRIVILEGE_MAIN where IS_DELETED=0 and PRIVILEGE_MAIN_GUID=?";
pstmt = conn.prepareStatement(sSQL);
pstmt.setString(1, privilegeguid);
rs = pstmt.executeQuery();
if(rs.next()){
returnEntity.setPrivilege_main_guid(rs.getString(1));
returnEntity.setPrivilege_main_id(rs.getString(2));
returnEntity.setPrivilege_name(rs.getString(3));
returnEntity.setPrivilege_desc(rs.getString(4));
returnEntity.setDoc_guid(rs.getString(5));
}
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
return returnEntity;
}
private void updatePrivilege_sqlserver(PRIVILEGE_MAIN privilege,
Connection conn) throws Exception {
privilege.setPrivilege_name(Decode(privilege.getPrivilege_name()));
privilege.setPrivilege_desc(Decode(privilege.getPrivilege_desc()));
PreparedStatement pstmt = null;
try{
String uSQL = "update PRIVILEGE_MAIN set UPDATED_DT=?, UPDATED_BY=?, PRIVILEGE_NAME=?, PRIVILEGE_DESC=? where IS_DELETED=0 and PRIVILEGE_MAIN_GUID=?";
pstmt = conn.prepareStatement(uSQL);
pstmt.setLong(1, new Date().getTime());
pstmt.setString(2, privilege.getUpdated_by());
pstmt.setString(3, privilege.getPrivilege_name());
pstmt.setString(4, privilege.getPrivilege_desc());
pstmt.setString(5, privilege.getPrivilege_main_guid());
pstmt.execute();
pstmt.close();
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed()){
pstmt.close();
}
}
}
public List<PARAM_MAIN> getSlParam(String param_type, Connection conn) throws Exception {
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
List<PARAM_MAIN> returnList = new ArrayList<PARAM_MAIN>();
switch (dataSourceType) {
case "oracle": returnList = getSlParam_oracle(param_type, conn);
break;
case "sqlserver": returnList = getSlParam_sqlserver(param_type, conn);
break;
default: returnList = getSlParam_mysql(param_type, conn);
break;
}
return returnList;
}
private List<PARAM_MAIN> getSlParam_oracle(String param_type, Connection conn) throws Exception {
List<PARAM_MAIN> returnList = new ArrayList<PARAM_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
pstmt = conn.prepareStatement("select PARAM_MAIN_GUID, PARAM_MAIN_ID, PARAM_VALUE from PARAM_MAIN where IS_DELETED=0 and PARAM_TYPE=?");
pstmt.setString(1, param_type);
rs = pstmt.executeQuery();
while(rs.next()){
PARAM_MAIN entity = new PARAM_MAIN();
entity.setParam_main_guid(rs.getString(1));
entity.setParam_main_id(Encode(rs.getString(2)));
entity.setParam_value(Encode(rs.getString(3)));
returnList.add(entity);
}
return returnList;
}
private List<PARAM_MAIN> getSlParam_mysql(String param_type, Connection conn) throws Exception {
List<PARAM_MAIN> returnList = new ArrayList<PARAM_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
pstmt = conn.prepareStatement("select PARAM_MAIN_GUID, PARAM_MAIN_ID, PARAM_VALUE from PARAM_MAIN where IS_DELETED=0 and PARAM_TYPE=?");
pstmt.setString(1, param_type);
rs = pstmt.executeQuery();
while(rs.next()){
PARAM_MAIN entity = new PARAM_MAIN();
entity.setParam_main_guid(rs.getString(1));
entity.setParam_main_id(Encode(rs.getString(2)));
entity.setParam_value(Encode(rs.getString(3)));
returnList.add(entity);
}
return returnList;
}
private List<PARAM_MAIN> getSlParam_sqlserver(String param_type, Connection conn) throws Exception {
List<PARAM_MAIN> returnList = new ArrayList<PARAM_MAIN>();
PreparedStatement pstmt = null;
ResultSet rs = null;
pstmt = conn.prepareStatement("select PARAM_MAIN_GUID, PARAM_MAIN_ID, PARAM_VALUE from PARAM_MAIN where IS_DELETED=0 and PARAM_TYPE=?");
pstmt.setString(1, param_type);
rs = pstmt.executeQuery();
while(rs.next()){
PARAM_MAIN entity = new PARAM_MAIN();
entity.setParam_main_guid(rs.getString(1));
entity.setParam_main_id(Encode(rs.getString(2)));
entity.setParam_value(Encode(rs.getString(3)));
returnList.add(entity);
}
return returnList;
}
public DOC_MAIN getDocSeqnoID(String user_guid, String doc_id, Connection conn) throws Exception {
DOC_MAIN returnEntity = new DOC_MAIN();
String dataSourceType=new Config(FrameConfig.CONFIGNAME).get("datasource@type");
switch (dataSourceType) {
case "oracle": returnEntity = getDocSeqnoID_oracle(user_guid, doc_id, conn);
break;
case "sqlserver": returnEntity = getDocSeqnoID_sqlserver(user_guid, doc_id, conn);
break;
default: returnEntity = getDocSeqnoID_mysql(user_guid, doc_id, conn);
break;
}
return returnEntity;
}
private DOC_MAIN getDocSeqnoID_oracle(String user_guid, String doc_id,
Connection conn) throws Exception {
DOC_MAIN returnEntity = new DOC_MAIN();
String docSeqnoID = "";
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
pstmt = conn.prepareStatement("select DOC_MAIN_ID, DOC_PRE_TAG, DOC_MID_TAG_ID, DOC_SEQ_NO, DOC_SEQ_NO_LEN, DOC_STATUS_ID from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_ID=? for update");
pstmt.setString(1, doc_id);
rs = pstmt.executeQuery();
DOC_MAIN entity = new DOC_MAIN();
int icount = 0;
if(rs.next()){
icount++;
entity.setDoc_main_id(rs.getString(1));
entity.setDoc_pre_tag(rs.getString(2));
entity.setDoc_mid_tag_id(rs.getString(3));
entity.setDoc_seq_no(rs.getInt(4));
entity.setDoc_seq_no_len(rs.getInt(5));
entity.setDoc_status_id(rs.getString(6));
}
pstmt.close();
if(icount==0){
throw new Exception("未知的凭证");
}
String midTag = this.getDoc_Mid_Str(entity.getDoc_mid_tag_id());
String str_seqno=entity.getDoc_seq_no()+1+"";
int seqno_len=entity.getDoc_seq_no_len();
while(str_seqno.length()<seqno_len){
str_seqno = "0"+str_seqno;
}
docSeqnoID=entity.getDoc_pre_tag() + midTag + str_seqno;
pstmt = conn.prepareStatement("update DOC_MAIN set UPDATED_DT=?, UPDATED_BY=?, DOC_SEQ_NO = ? where IS_DELETED=0 and DOC_MAIN_ID=?");
pstmt.setLong(1, new Date().getTime());
pstmt.setString(2, user_guid);
pstmt.setString(3, str_seqno);
pstmt.setString(4, doc_id);
pstmt.execute();
entity.setDoc_seqno_id(docSeqnoID);
returnEntity = entity;
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed())pstmt.close();
}
return returnEntity;
}
private DOC_MAIN getDocSeqnoID_sqlserver(String user_guid, String doc_id,
Connection conn) throws Exception {
DOC_MAIN returnEntity = new DOC_MAIN();
String docSeqnoID = "";
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
pstmt = conn.prepareStatement("SELECT DOC_MAIN_ID, DOC_PRE_TAG, DOC_MID_TAG_ID, DOC_SEQ_NO, DOC_SEQ_NO_LEN, DOC_STATUS_ID FROM DOC_MAIN WITH(UPDLOCK) WHERE IS_DELETED=0 AND DOC_MAIN_ID=?");
pstmt.setString(1, doc_id);
rs = pstmt.executeQuery();
DOC_MAIN entity = new DOC_MAIN();
int icount = 0;
if(rs.next()){
icount++;
entity.setDoc_main_id(rs.getString(1));
entity.setDoc_pre_tag(rs.getString(2));
entity.setDoc_mid_tag_id(rs.getString(3));
entity.setDoc_seq_no(rs.getInt(4));
entity.setDoc_seq_no_len(rs.getInt(5));
entity.setDoc_status_id(rs.getString(6));
}
pstmt.close();
if(icount==0){
throw new Exception("未知的凭证");
}
String midTag = this.getDoc_Mid_Str(entity.getDoc_mid_tag_id());
String str_seqno=entity.getDoc_seq_no()+1+"";
int seqno_len=entity.getDoc_seq_no_len();
while(str_seqno.length()<seqno_len){
str_seqno = "0"+str_seqno;
}
docSeqnoID=entity.getDoc_pre_tag() + midTag + str_seqno;
pstmt = conn.prepareStatement("UPDATE DOC_MAIN SET UPDATED_DT=?, UPDATED_BY=?, DOC_SEQ_NO = ? WHERE IS_DELETED=0 AND DOC_MAIN_ID=?");
pstmt.setLong(1, new Date().getTime());
pstmt.setString(2, user_guid);
pstmt.setString(3, str_seqno);
pstmt.setString(4, doc_id);
pstmt.execute();
entity.setDoc_seqno_id(docSeqnoID);
returnEntity = entity;
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed())pstmt.close();
}
return returnEntity;
}
private DOC_MAIN getDocSeqnoID_mysql(String user_guid, String doc_id,
Connection conn) throws Exception {
DOC_MAIN returnEntity = new DOC_MAIN();
String docSeqnoID = "";
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
pstmt = conn.prepareStatement("select DOC_MAIN_ID, DOC_PRE_TAG, DOC_MID_TAG_ID, DOC_SEQ_NO, DOC_SEQ_NO_LEN, DOC_STATUS_ID from DOC_MAIN where IS_DELETED=0 and DOC_MAIN_ID=? for update");
pstmt.setString(1, doc_id);
rs = pstmt.executeQuery();
DOC_MAIN entity = new DOC_MAIN();
int icount = 0;
if(rs.next()){
icount++;
entity.setDoc_main_id(rs.getString(1));
entity.setDoc_pre_tag(rs.getString(2));
entity.setDoc_mid_tag_id(rs.getString(3));
entity.setDoc_seq_no(rs.getInt(4));
entity.setDoc_seq_no_len(rs.getInt(5));
entity.setDoc_status_id(rs.getString(6));
}
pstmt.close();
if(icount==0){
throw new Exception("未知的凭证");
}
String midTag = this.getDoc_Mid_Str(entity.getDoc_mid_tag_id());
String str_seqno=entity.getDoc_seq_no()+1+"";
int seqno_len=entity.getDoc_seq_no_len();
while(str_seqno.length()<seqno_len){
str_seqno = "0"+str_seqno;
}
docSeqnoID=entity.getDoc_pre_tag() + midTag + str_seqno;
pstmt = conn.prepareStatement("update DOC_MAIN set UPDATED_DT=?, UPDATED_BY=?, DOC_SEQ_NO = ? where IS_DELETED=0 and DOC_MAIN_ID=?");
pstmt.setLong(1, new Date().getTime());
pstmt.setString(2, user_guid);
pstmt.setString(3, str_seqno);
pstmt.setString(4, doc_id);
pstmt.execute();
entity.setDoc_seqno_id(docSeqnoID);
returnEntity = entity;
}catch(Exception e){
throw e;
}finally{
if(pstmt!=null&&!pstmt.isClosed())pstmt.close();
}
return returnEntity;
}
private String getDoc_Mid_Str(String doc_mid_tag_id){
String doc_mid_str="";
if(doc_mid_tag_id!=null&&!doc_mid_tag_id.isEmpty()){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyMMdd");
String dateText = dateFormat.format(new Date());
String dateText1 = dateFormat1.format(new Date());
switch (doc_mid_tag_id) {
case "year": doc_mid_str = dateText.substring(0, 4);break;
case "year_month": doc_mid_str = dateText.substring(0, 6);break;
case "year_month_day": doc_mid_str = dateText;break;
case "2_year": doc_mid_str = dateText1.substring(0, 2);break;
case "2_year_month": doc_mid_str = dateText1.substring(0, 4);break;
case "2_year_month_day": doc_mid_str = dateText1;break;
default: doc_mid_str = "";break;
}
}
return doc_mid_str;
}
}
| apache-2.0 |
TpSr52/allure2 | allure-plugin-api/src/main/java/io/qameta/allure/context/MarkdownContext.java | 605 | package io.qameta.allure.context;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import io.qameta.allure.Context;
import java.util.function.Function;
/**
* Markdown context. Can be used to process markdown files to html.
*
* @since 2.0
*/
public class MarkdownContext implements Context<Function<String, String>> {
@Override
public Function<String, String> getValue() {
Parser parser = Parser.builder().build();
HtmlRenderer renderer = HtmlRenderer.builder().build();
return s -> renderer.render(parser.parse(s));
}
}
| apache-2.0 |
phax/ph-schematron | ph-schematron-pure/src/test/java/com/helger/schematron/pure/validation/IPSValidationHandlerTest.java | 1598 | /*
* Copyright (C) 2014-2022 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.schematron.pure.validation;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import org.junit.Test;
/**
* Test class for class {@link IPSValidationHandler}.
*
* @author Philip Helger
*/
public final class IPSValidationHandlerTest
{
@Test
public void testAnd ()
{
final IPSValidationHandler x = new LoggingPSValidationHandler ();
final IPSValidationHandler y = new LoggingPSValidationHandler ();
assertNotSame (x, y);
assertSame (x, x.and (null));
assertSame (y, y.and (null));
final IPSValidationHandler xy = x.and (y);
assertNotSame (x, xy);
assertNotSame (x, xy);
assertNull (IPSValidationHandler.and (null, null));
assertSame (x, IPSValidationHandler.and (x, null));
assertSame (x, IPSValidationHandler.and (null, x));
assertNotSame (x, IPSValidationHandler.and (x, x));
}
}
| apache-2.0 |
fromanator/cfg4j | cfg4j-git/src/test/java/org/cfg4j/source/git/TempConfigurationGitRepo.java | 4075 | /*
* Copyright 2015 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.git;
import org.cfg4j.source.files.TempConfigurationFileRepo;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
/**
* Temporary local git repository that contains configuration files.
*/
class TempConfigurationGitRepo extends TempConfigurationFileRepo {
private final Git repo;
/**
* Create temporary, local git repository. When you're done using it remove it by invoking {@link #remove()}
* method.
*
* @throws IOException when unable to create local directories
* @throws GitAPIException when unable to execute git operations
*/
TempConfigurationGitRepo(String dirName) throws IOException, GitAPIException {
super(dirName);
repo = createLocalRepo(dirPath);
}
/**
* Change active branch to {@code branch}. Create the branch if it doesn't exist.
*
* @param branch branch to activate
* @throws GitAPIException when unable to change branch.
*/
void changeBranchTo(String branch) throws GitAPIException {
boolean createBranch = true;
List<Ref> refList = repo.branchList().call();
if (anyRefMatches(refList, branch)) {
createBranch = false;
}
repo.checkout()
.setCreateBranch(createBranch)
.setName(branch)
.call();
}
/**
* Change the {@code key} property to {@code value} and store it in a {@code propFilePath} properties file. Commits
* the change.
*
* @param propFilePath relative path to the properties file in this repository
* @param key property key
* @param value property value
* @throws IOException when unable to modify properties file
* @throws GitAPIException when unable to commit changes
*/
@Override
public void changeProperty(Path propFilePath, String key, String value) throws IOException {
super.changeProperty(propFilePath, key, value);
try {
commitChanges();
} catch (GitAPIException e) {
throw new IOException(e);
}
}
/**
* Delete file from this repository. Commits changes.
*
* @param filePath relative file path to delete
* @throws GitAPIException when unable to commit changes
*/
@Override
public void deleteFile(Path filePath) throws IOException {
try {
super.deleteFile(filePath);
repo.rm()
.addFilepattern(filePath.toString())
.call();
commitChanges();
} catch (GitAPIException e) {
throw new IOException(e);
}
}
/**
* Remove this repository. Silently fails if repo already removed.
*/
@Override
public void remove() {
try {
repo.close();
super.remove();
} catch (IOException e) {
// NOP
}
}
private Git createLocalRepo(Path path) throws IOException, GitAPIException {
Files.delete(path);
return Git.init()
.setDirectory(path.toFile())
.call();
}
private void commitChanges() throws GitAPIException {
repo.add()
.addFilepattern(".")
.call();
repo.commit()
.setMessage("config change")
.call();
}
private boolean anyRefMatches(List<Ref> refList, String branch) {
for (Ref ref : refList) {
if (ref.getName().replace("refs/heads/", "").equals(branch)) {
return true;
}
}
return false;
}
}
| apache-2.0 |
dvanherbergen/robotframework-formslibrary | src/main/java/org/robotframework/formslibrary/util/Logger.java | 514 | package org.robotframework.formslibrary.util;
/**
* Very, very simple logger implementation which allows debug logging to be
* disabled.
*/
public class Logger {
public static void debug(String message) {
if (DebugUtil.isDebugEnabled()) {
System.out.println("~ " + message);
}
}
public static void info(String message) {
System.out.println(message);
}
public static void error(Throwable t) {
t.printStackTrace();
}
}
| apache-2.0 |
punkto/mightyLD37 | core/src/eu/mighty/ld37/game/components/MovementComponent.java | 272 | package eu.mighty.ld37.game.components;
import com.badlogic.ashley.core.Component;
import com.badlogic.gdx.math.Vector2;
public class MovementComponent implements Component {
public final Vector2 velocity = new Vector2();
public final Vector2 accel = new Vector2();
}
| apache-2.0 |
jabelai/Neverland | J2EE/SimpleNetGameServ/src/nio/game/server/GameLogicContext.java | 8012 | package nio.game.server;
import java.util.Collection;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.util.internal.ConcurrentHashMap;
public class GameLogicContext {
//静态单例实例
private final static GameLogicContext mGameLogicContext = new GameLogicContext();
/******************************************************
* 功能描述:静态单例模式,获取GAME游戏逻辑的实例对象
*******************************************************/
public static GameLogicContext sharedGameContext(){
return mGameLogicContext;
}
/* IO组
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
//游戏所有客户端的IO读写列表(所有玩家都在此列表里)
private final ConcurrentHashMap<Integer, Channel> mClientChannelGroup = new ConcurrentHashMap<Integer, Channel>();
// >> 如果要对客户端IO所在列表进行分段,在此定义,便于遍历
// <<
/* 逻辑组
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
//游戏所有客户端对应的游戏逻辑处理器
private final ConcurrentHashMap<Integer, GameLogicBaseBean> mClientLogicGroup = new ConcurrentHashMap<Integer, GameLogicBaseBean>();
/* 数据组
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
//游戏所有客户端对应的客户端数据
private final ConcurrentHashMap<Integer, GameLogicBaseData> mClientDataGroup = new ConcurrentHashMap<Integer, GameLogicBaseData>();
/* Common
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
//加入一个新的客户端逻辑处理器
public void AddClient(Channel nnChannel, GameLogicBaseBean nnGameBean){
int nnID = nnChannel.getId();
this.mClientLogicGroup.put(nnID, nnGameBean);
this.mClientChannelGroup.put(nnID, nnChannel);
}
//删除一个客户端逻辑处理器,并关掉IO通道
public void RemoveClient(Channel nnChannel){
int nnID = nnChannel.getId();
this.mClientLogicGroup.remove(nnID);
this.mClientChannelGroup.remove(nnID);
nnChannel.close();
}
//获得一个客户端逻辑处理器
public GameLogicBaseBean GetClient(Channel nnChannel){
return this.mClientLogicGroup.get(nnChannel.getId());
}
//获得客户端逻辑处理器总数量
public int GetClientSize(){
return this.mClientLogicGroup.size();
}
//获得所有客户端IO集合
public ConcurrentHashMap<Integer, Channel> GetClientChannelGroup(){
return this.mClientChannelGroup;
}
//获得所有客户端IO集合的个数
public int GetClientChannelGroupSize(){
return this.mClientChannelGroup.size();
}
//加一个新的客户端数据
public void AddGameData(int nnID, GameLogicBaseData data){
mClientDataGroup.put(nnID, data);
}
//删除某一个客户端的数据
public void RemoveGameData(int nnID){
mClientDataGroup.remove(nnID);
}
//获取某一个客户端的数据
public GameLogicBaseData GetGameData(int nnID){
return mClientDataGroup.get(nnID);
}
//获取客户端数据集的个数
public int GetGameDataSize(){
return mClientDataGroup.size();
}
//获取客户端总数
public int size(){
return this.mClientDataGroup.size();
}
//需要广播数据给服务器其他所有玩家
public void write(ChannelBuffer nnChannelBuffer){
Collection<Channel> values = mClientChannelGroup.values();
for (Channel nnChannel: values) {
nnChannel.write(nnChannelBuffer);
}
}
//某一个玩家需要广播数据给服务器其他所有玩家,但是不广播给自己 nnChannelID用来排除自己
public void write(ChannelBuffer nnChannelBuffer, int nnChannelID){
Collection<Channel> values = mClientChannelGroup.values();
for (Channel nnChannel: values) {
if(nnChannel.getId() != nnChannelID){
nnChannel.write(nnChannelBuffer);
}
}
}
}
| apache-2.0 |
silverbullet-dk/opentele-client-android | questionnaire-mainapp/src/dk/silverbullet/telemed/questionnaire/node/ErrorNode.java | 1622 | package dk.silverbullet.telemed.questionnaire.node;
import dk.silverbullet.telemed.questionnaire.Questionnaire;
import dk.silverbullet.telemed.questionnaire.R;
import dk.silverbullet.telemed.questionnaire.element.ButtonElement;
import dk.silverbullet.telemed.questionnaire.element.TextViewElement;
import dk.silverbullet.telemed.utils.Util;
import java.util.Map;
public class ErrorNode extends IONode {
@SuppressWarnings("unused")
private static final String TAG = Util.getTag(ErrorNode.class);
private Node nextNode;
private String error;
private TextViewElement textViewElement;
private ButtonElement button;
public ErrorNode(Questionnaire questionnaire, String nodeName) {
super(questionnaire, nodeName);
TextViewElement x = new TextViewElement(this);
x.setText(Util.getString(R.string.error_error_occured, questionnaire));
addElement(x);
textViewElement = new TextViewElement(this);
addElement(textViewElement);
button = new ButtonElement(this);
button.setText(Util.getString(R.string.default_ok, questionnaire));
addElement(button);
}
@Override
public void enter() {
textViewElement.setText("error:" + error);
button.setNextNode(nextNode);
super.enter();
}
@Override
public void leave() {
}
@Override
public void linkNodes(Map<String, Node> map) throws UnknownNodeException {
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
public void setError(String error) {
this.error = error;
}
}
| apache-2.0 |
Sp2000/colplus-backend | colplus-dao/src/test/java/life/catalogue/dao/SubjectRematcherTest.java | 4639 | package life.catalogue.dao;
import life.catalogue.api.model.EditorialDecision;
import life.catalogue.db.mapper.DecisionMapper;
import org.apache.ibatis.session.SqlSession;
import life.catalogue.api.model.RematchRequest;
import life.catalogue.api.model.Sector;
import life.catalogue.api.model.SimpleName;
import life.catalogue.api.vocab.Datasets;
import life.catalogue.api.vocab.Users;
import life.catalogue.db.MybatisTestUtils;
import life.catalogue.db.PgSetupRule;
import life.catalogue.db.mapper.SectorMapper;
import life.catalogue.db.mapper.TestDataRule;
import org.gbif.nameparser.api.Rank;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.*;
public class SubjectRematcherTest {
@ClassRule
public static PgSetupRule pg = new PgSetupRule();
@Rule
public final TestDataRule importRule = TestDataRule.apple();
@Test
public void matchDataset() {
/*
Name n1 = draftName(nm, datasetKey,"n1", "Animalia", Rank.KINGDOM);
Name n2 = draftName(nm, datasetKey,"n2", "Arthropoda", Rank.KINGDOM);
Name n3 = draftName(nm, datasetKey,"n3", "Insecta", Rank.CLASS);
Name n4 = draftName(nm, datasetKey,"n4", "Coleoptera", Rank.ORDER);
Name n5 = draftName(nm, datasetKey,"n5", "Lepidoptera", Rank.ORDER);
*/
MybatisTestUtils.populateDraftTree(importRule.getSqlSession());
final int datasetKey = 11;
int s1 = createSector(Sector.Mode.ATTACH, datasetKey,
new SimpleName(null, "Malus sylvestris", Rank.SPECIES),
new SimpleName(null, "Coleoptera", Rank.ORDER)
);
int s2 = createSector(Sector.Mode.UNION, datasetKey,
new SimpleName(null, "Larus fuscus", Rank.SPECIES),
new SimpleName(null, "Lepidoptera", Rank.ORDER)
);
int d1 = createDecision(datasetKey,
new SimpleName("xyz", "Larus fuscus", Rank.SPECIES)
);
int d2 = createDecision(datasetKey,
new SimpleName(null, "Larus fuscus", Rank.SPECIES)
);
int d3 = createDecision(datasetKey,
new SimpleName("null", "Larus", Rank.GENUS)
);
SubjectRematcher rem = new SubjectRematcher(PgSetupRule.getSqlSessionFactory(), Datasets.DRAFT_COL, Users.TESTER);
rem.matchDatasetSubjects(datasetKey);
Sector s1b;
Sector s2b;
try (SqlSession session = PgSetupRule.getSqlSessionFactory().openSession(true)) {
SectorMapper sm = session.getMapper(SectorMapper.class);
DecisionMapper dm = session.getMapper(DecisionMapper.class);
s1b = sm.get(s1);
assertEquals("root-1", s1b.getSubject().getId());
assertNull(s1b.getTarget().getId());
s2b = sm.get(s2);
assertEquals("root-2", s2b.getSubject().getId());
assertNull(s2b.getTarget().getId());
// we order decisions in reverse order when searching, so last one gets matched
EditorialDecision d1b = dm.get(d1);
assertNull(d1b.getSubject().getId());
EditorialDecision d2b = dm.get(d2);
assertEquals("root-2", d2b.getSubject().getId());
EditorialDecision d3b = dm.get(d3);
assertNull(d3b.getSubject().getId());
}
rem.match(RematchRequest.all());
try (SqlSession session = PgSetupRule.getSqlSessionFactory().openSession(true)) {
SectorMapper sm = session.getMapper(SectorMapper.class);
Sector s1c = sm.get(s1);
assertEquals("root-1", s1c.getSubject().getId());
assertEquals("t4", s1c.getTarget().getId());
Sector s2c = sm.get(s2);
assertEquals("root-2", s2c.getSubject().getId());
assertEquals("t5", s2c.getTarget().getId());
}
}
static int createSector(Sector.Mode mode, int datasetKey, SimpleName src, SimpleName target) {
try (SqlSession session = PgSetupRule.getSqlSessionFactory().openSession(true)) {
Sector sector = new Sector();
sector.setMode(mode);
sector.setDatasetKey(Datasets.DRAFT_COL);
sector.setSubjectDatasetKey(datasetKey);
sector.setSubject(src);
sector.setTarget(target);
sector.applyUser(TestDataRule.TEST_USER);
session.getMapper(SectorMapper.class).create(sector);
return sector.getKey();
}
}
static int createDecision(int datasetKey, SimpleName src) {
try (SqlSession session = PgSetupRule.getSqlSessionFactory().openSession(true)) {
EditorialDecision d = new EditorialDecision();
d.setMode(EditorialDecision.Mode.BLOCK);
d.setDatasetKey(Datasets.DRAFT_COL);
d.setSubjectDatasetKey(datasetKey);
d.setSubject(src);
d.applyUser(TestDataRule.TEST_USER);
session.getMapper(DecisionMapper.class).create(d);
return d.getKey();
}
}
} | apache-2.0 |
torrances/swtk-commons | commons-dict-wordnet-indexbyid/src/main/java/org/swtk/commons/dict/wordnet/indexbyid/instance/p0/p8/WordnetNounIndexIdInstance0854.java | 4740 | package org.swtk.commons.dict.wordnet.indexbyid.instance.p0.p8; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexIdInstance0854 { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("08540077", "{\"term\":\"center of flotation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08540077\"]}");
add("08540077", "{\"term\":\"centre of flotation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08540077\"]}");
add("08540245", "{\"term\":\"center of mass\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08540245\"]}");
add("08540245", "{\"term\":\"centre of mass\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08540245\"]}");
add("08540475", "{\"term\":\"barycenter\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08540475\"]}");
add("08540628", "{\"term\":\"centroid\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08540628\"]}");
add("08540751", "{\"term\":\"crinion\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08540751\"]}");
add("08540751", "{\"term\":\"trichion\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08540751\"]}");
add("08540894", "{\"term\":\"center\", \"synsetCount\":18, \"upperType\":\"NOUN\", \"ids\":[\"00726757\", \"00728798\", \"00729762\", \"03971750\", \"07618221\", \"09924161\", \"08433480\", \"08531106\", \"09923774\", \"09924009\", \"08498843\", \"05471109\", \"05820064\", \"05929717\", \"08538999\", \"02997001\", \"02997788\", \"08540894\"]}");
add("08540894", "{\"term\":\"centre\", \"synsetCount\":9, \"upperType\":\"NOUN\", \"ids\":[\"02997001\", \"05471109\", \"05820064\", \"05929717\", \"07618221\", \"08531106\", \"08538999\", \"08540894\", \"08961199\"]}");
add("08540894", "{\"term\":\"eye\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"03313242\", \"08540894\", \"05711254\", \"05622259\", \"05318579\"]}");
add("08540894", "{\"term\":\"heart\", \"synsetCount\":10, \"upperType\":\"NOUN\", \"ids\":[\"03512192\", \"07560035\", \"07667514\", \"13888525\", \"04632183\", \"05929717\", \"08540894\", \"04864721\", \"05396148\", \"05927857\"]}");
add("08540894", "{\"term\":\"middle\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"15291496\", \"05563106\", \"05876894\", \"08540894\"]}");
add("08541470", "{\"term\":\"center stage\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08541470\", \"13971834\"]}");
add("08541470", "{\"term\":\"centre stage\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08541470\", \"13971834\"]}");
add("08541617", "{\"term\":\"central city\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08541617\"]}");
add("08541617", "{\"term\":\"city center\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08541617\"]}");
add("08541617", "{\"term\":\"city centre\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08541617\"]}");
add("08541787", "{\"term\":\"core\", \"synsetCount\":10, \"upperType\":\"NOUN\", \"ids\":[\"03112367\", \"03112555\", \"03112720\", \"06616419\", \"08325852\", \"09279801\", \"05929717\", \"09279721\", \"08541787\", \"08259144\"]}");
add("08541929", "{\"term\":\"navel\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08541929\", \"05564228\"]}");
add("08541929", "{\"term\":\"navel point\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08541929\"]}");
add("08542097", "{\"term\":\"storm center\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08542097\", \"14002048\"]}");
add("08542097", "{\"term\":\"storm centre\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08542097\", \"14002048\"]}");
add("08542298", "{\"term\":\"city\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"08243256\", \"08558466\", \"08542298\"]}");
add("08542298", "{\"term\":\"metropolis\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"08243256\", \"08542298\"]}");
add("08542298", "{\"term\":\"urban center\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"08542298\"]}");
} private static void add(final String ID, final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(ID)) ? map.get(ID) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(ID, list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> ids() { return map.keySet(); } } | apache-2.0 |
roadboy/KafkaACL | contrib/hadoop-consumer/src/main/java/kafka/etl/KafkaETLContext.java | 10749 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kafka.etl;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import kafka.api.FetchRequest;
import kafka.api.FetchRequestBuilder;
import kafka.api.PartitionOffsetRequestInfo;
import kafka.common.TopicAndPartition;
import kafka.javaapi.FetchResponse;
import kafka.javaapi.OffsetRequest;
import kafka.javaapi.consumer.SimpleConsumer;
import kafka.javaapi.message.ByteBufferMessageSet;
import kafka.message.MessageAndOffset;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.lib.MultipleOutputs;
@SuppressWarnings({ "deprecation"})
public class KafkaETLContext {
static protected int MAX_RETRY_TIME = 1;
final static String CLIENT_BUFFER_SIZE = "client.buffer.size";
final static String CLIENT_TIMEOUT = "client.so.timeout";
final static int DEFAULT_BUFFER_SIZE = 1 * 1024 * 1024;
final static int DEFAULT_TIMEOUT = 60000; // one minute
final static KafkaETLKey DUMMY_KEY = new KafkaETLKey();
protected int _index; /*index of context*/
protected String _input = null; /*input string*/
protected KafkaETLRequest _request = null;
protected SimpleConsumer _consumer = null; /*simple consumer*/
protected long[] _offsetRange = {0, 0}; /*offset range*/
protected long _offset = Long.MAX_VALUE; /*current offset*/
protected long _count; /*current count*/
protected FetchResponse _response = null; /*fetch response*/
protected Iterator<MessageAndOffset> _messageIt = null; /*message iterator*/
protected Iterator<ByteBufferMessageSet> _respIterator = null;
protected int _retry = 0;
protected long _requestTime = 0; /*accumulative request time*/
protected long _startTime = -1;
protected int _bufferSize;
protected int _timeout;
protected Reporter _reporter;
protected MultipleOutputs _mos;
protected OutputCollector<KafkaETLKey, BytesWritable> _offsetOut = null;
protected FetchRequestBuilder builder = new FetchRequestBuilder();
public long getTotalBytes() {
return (_offsetRange[1] > _offsetRange[0])? _offsetRange[1] - _offsetRange[0] : 0;
}
public long getReadBytes() {
return _offset - _offsetRange[0];
}
public long getCount() {
return _count;
}
/**
* construct using input string
*/
@SuppressWarnings("unchecked")
public KafkaETLContext(JobConf job, Props props, Reporter reporter,
MultipleOutputs mos, int index, String input)
throws Exception {
_bufferSize = getClientBufferSize(props);
_timeout = getClientTimeout(props);
System.out.println("bufferSize=" +_bufferSize);
System.out.println("timeout=" + _timeout);
_reporter = reporter;
_mos = mos;
// read topic and current offset from input
_index= index;
_input = input;
_request = new KafkaETLRequest(input.trim());
// read data from queue
URI uri = _request.getURI();
_consumer = new SimpleConsumer(uri.getHost(), uri.getPort(), _timeout, _bufferSize, "KafkaETLContext");
// get available offset range
_offsetRange = getOffsetRange();
System.out.println("Connected to node " + uri
+ " beginning reading at offset " + _offsetRange[0]
+ " latest offset=" + _offsetRange[1]);
_offset = _offsetRange[0];
_count = 0;
_requestTime = 0;
_retry = 0;
_startTime = System.currentTimeMillis();
}
public boolean hasMore () {
return _messageIt != null && _messageIt.hasNext()
|| _response != null && _respIterator.hasNext()
|| _offset < _offsetRange[1];
}
public boolean getNext(KafkaETLKey key, BytesWritable value) throws IOException {
if ( !hasMore() ) return false;
boolean gotNext = get(key, value);
if(_response != null) {
while ( !gotNext && _respIterator.hasNext()) {
ByteBufferMessageSet msgSet = _respIterator.next();
_messageIt = msgSet.iterator();
gotNext = get(key, value);
}
}
return gotNext;
}
public boolean fetchMore () throws IOException {
if (!hasMore()) return false;
FetchRequest fetchRequest = builder
.clientId(_request.clientId())
.addFetch(_request.getTopic(), _request.getPartition(), _offset, _bufferSize)
.build();
long tempTime = System.currentTimeMillis();
_response = _consumer.fetch(fetchRequest);
if(_response != null) {
_respIterator = new ArrayList<ByteBufferMessageSet>(){{
add((ByteBufferMessageSet) _response.messageSet(_request.getTopic(), _request.getPartition()));
}}.iterator();
}
_requestTime += (System.currentTimeMillis() - tempTime);
return true;
}
@SuppressWarnings("unchecked")
public void output(String fileprefix) throws IOException {
String offsetString = _request.toString(_offset);
if (_offsetOut == null)
_offsetOut = (OutputCollector<KafkaETLKey, BytesWritable>)
_mos.getCollector("offsets", fileprefix+_index, _reporter);
_offsetOut.collect(DUMMY_KEY, new BytesWritable(offsetString.getBytes("UTF-8")));
}
public void close() throws IOException {
if (_consumer != null) _consumer.close();
String topic = _request.getTopic();
long endTime = System.currentTimeMillis();
_reporter.incrCounter(topic, "read-time(ms)", endTime - _startTime);
_reporter.incrCounter(topic, "request-time(ms)", _requestTime);
long bytesRead = _offset - _offsetRange[0];
double megaRead = bytesRead / (1024.0*1024.0);
_reporter.incrCounter(topic, "data-read(mb)", (long) megaRead);
_reporter.incrCounter(topic, "event-count", _count);
}
protected boolean get(KafkaETLKey key, BytesWritable value) throws IOException {
if (_messageIt != null && _messageIt.hasNext()) {
MessageAndOffset messageAndOffset = _messageIt.next();
ByteBuffer buf = messageAndOffset.message().buffer();
int origSize = buf.remaining();
byte[] bytes = new byte[origSize];
buf.get(bytes, buf.position(), origSize);
value.set(bytes, 0, origSize);
key.set(_index, _offset, messageAndOffset.message().checksum());
_offset = messageAndOffset.nextOffset(); //increase offset
_count ++; //increase count
return true;
}
else return false;
}
/**
* Get offset ranges
*/
protected long[] getOffsetRange() throws IOException {
/* get smallest and largest offsets*/
long[] range = new long[2];
TopicAndPartition topicAndPartition = new TopicAndPartition(_request.getTopic(), _request.getPartition());
Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo =
new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>();
requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(kafka.api.OffsetRequest.EarliestTime(), 1));
OffsetRequest request = new OffsetRequest(
requestInfo, kafka.api.OffsetRequest.CurrentVersion(), kafka.api.OffsetRequest.DefaultClientId(), null, null);
long[] startOffsets = _consumer.getOffsetsBefore(request).offsets(_request.getTopic(), _request.getPartition());
if (startOffsets.length != 1)
throw new IOException("input:" + _input + " Expect one smallest offset but get "
+ startOffsets.length);
range[0] = startOffsets[0];
requestInfo.clear();
requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(kafka.api.OffsetRequest.LatestTime(), 1));
request = new OffsetRequest(
requestInfo, kafka.api.OffsetRequest.CurrentVersion(), kafka.api.OffsetRequest.DefaultClientId(), null, null);
long[] endOffsets = _consumer.getOffsetsBefore(request).offsets(_request.getTopic(), _request.getPartition());
if (endOffsets.length != 1)
throw new IOException("input:" + _input + " Expect one latest offset but get "
+ endOffsets.length);
range[1] = endOffsets[0];
/*adjust range based on input offsets*/
if ( _request.isValidOffset()) {
long startOffset = _request.getOffset();
if (startOffset > range[0]) {
System.out.println("Update starting offset with " + startOffset);
range[0] = startOffset;
}
else {
System.out.println("WARNING: given starting offset " + startOffset
+ " is smaller than the smallest one " + range[0]
+ ". Will ignore it.");
}
}
System.out.println("Using offset range [" + range[0] + ", " + range[1] + "]");
return range;
}
public static int getClientBufferSize(Props props) throws Exception {
return props.getInt(CLIENT_BUFFER_SIZE, DEFAULT_BUFFER_SIZE);
}
public static int getClientTimeout(Props props) throws Exception {
return props.getInt(CLIENT_TIMEOUT, DEFAULT_TIMEOUT);
}
}
| apache-2.0 |
opetrovski/development | oscm-billing-unittests/javasrc-it/org/oscm/billingservice/service/CalculateBillingResultsForPaymentPreviewIntIT.java | 20358 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: Dec 5, 2012
*
*******************************************************************************/
package org.oscm.billingservice.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Currency;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import org.junit.Test;
import org.oscm.accountservice.bean.MarketingPermissionServiceBean;
import org.oscm.app.control.ApplicationServiceBaseStub;
import org.oscm.billingservice.business.calculation.revenue.RevenueCalculatorBean;
import org.oscm.billingservice.business.calculation.share.SharesCalculatorLocal;
import org.oscm.billingservice.dao.BillingDataRetrievalServiceBean;
import org.oscm.billingservice.service.model.BillingRun;
import org.oscm.dataservice.bean.DataServiceBean;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.BillingResult;
import org.oscm.domobjects.Organization;
import org.oscm.domobjects.PriceModel;
import org.oscm.domobjects.Product;
import org.oscm.domobjects.Subscription;
import org.oscm.domobjects.SupportedCurrency;
import org.oscm.domobjects.TechnicalProduct;
import org.oscm.i18nservice.bean.LocalizerServiceBean;
import org.oscm.interceptor.DateFactory;
import org.oscm.paymentservice.bean.PaymentServiceStub;
import org.oscm.serviceprovisioningservice.bean.ServiceProvisioningServiceBean;
import org.oscm.serviceprovisioningservice.bean.TagServiceBean;
import org.oscm.subscriptionservice.local.SubscriptionServiceLocal;
import org.oscm.tenantprovisioningservice.bean.TenantProvisioningServiceBean;
import org.oscm.test.EJBTestBase;
import org.oscm.test.TestDateFactory;
import org.oscm.test.data.Organizations;
import org.oscm.test.data.Products;
import org.oscm.test.data.Subscriptions;
import org.oscm.test.data.SupportedCountries;
import org.oscm.test.data.SupportedCurrencies;
import org.oscm.test.data.TechnicalProducts;
import org.oscm.test.ejb.TestContainer;
import org.oscm.test.stubs.CommunicationServiceStub;
import org.oscm.test.stubs.ConfigurationServiceStub;
import org.oscm.test.stubs.ImageResourceServiceStub;
import org.oscm.test.stubs.LdapAccessServiceStub;
import org.oscm.test.stubs.MarketplaceServiceStub;
import org.oscm.test.stubs.SessionServiceStub;
import org.oscm.test.stubs.TriggerQueueServiceStub;
import org.oscm.internal.types.enumtypes.OrganizationRoleType;
import org.oscm.internal.types.enumtypes.PricingPeriod;
import org.oscm.internal.types.enumtypes.ServiceAccessType;
/**
* Integration test for payment preview calculation.
*
* @author muenz
*
*/
public class CalculateBillingResultsForPaymentPreviewIntIT extends EJBTestBase {
private static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd hh:mm:ss";
// use big amounts
private static final Double ONE_TIME_FEE = new Double("100.00");
// use big amounts
private static final Double PRICE_PER_UNIT = new Double("1000.00");
private DataService dm;
private PriceModel priceModel;
private Product product;
private Organization supplier;
private TechnicalProduct technicalProduct;
private List<Subscription> subscriptions;
private SharesCalculatorLocal sharesCalculator;
private BillingServiceLocal service;
/**
* <ul>
* Tests the payment preview calculation with following scenario:
* <li>Cut-off day is before (lower than) invocation day</li>
* <li>The subscription starts before the calculation period -> one time fee
* already invoiced</li>
* <li>Price model of subscription is: Price per hour 1000,00 EUR, one time
* fee 100,00 EUR</li>
* </ul>
*/
@Test
public void calculateBillingResultsForPaymentPreview_CutoffDayBeforeInvocation_SubscriptionStartBeforePeriod()
throws Exception {
// given -> cutoff day before invocation day
final int cutOffDay = 3;
final long invocationTime = defineInvocationTime("2012-12-06 14:00:00");
// create subscription with start date before cutoff day calculation
// range -> one time fee already invoiced
createSubscription(calculateMillis("2012-11-15 08:00:00"), cutOffDay,
PricingPeriod.HOUR, supplier, product);
// when
BillingRun billingRun = service.generatePaymentPreviewReport(supplier
.getKey());
// then - 86 hours should be invoiced without one time fee 86 *
// PRICE_PER_HOUR
assertEquals(BigDecimal.valueOf(86000).setScale(2),
overallCosts(billingRun));
assertEquals(calculateMillis("2012-12-01 00:00:00"),
billingRun.getStart());
assertEquals(invocationTime, billingRun.getEnd());
}
/**
* <ul>
* Tests the payment preview calculation with following scenario:
* <li>Cut-off day is after (greater than) invocation day, but this test
* doesn't proof the correct</li>
* <li>The subscription starts IN the calculation period -> one time fee is
* to be calculated</li>
* <li>Price model of subscription is: Price per hour 1000,00 EUR, one time
* fee 100,00 EUR</li>
* </ul>
*
* @throws Exception
*/
@Test
public void calculateBillingResultsForPaymentPreview_CutoffDayAfterInvocationDay_SubscriptionStartInPeriod()
throws Exception {
// given
final int cutOffDay = 28;
final long invocationTime = defineInvocationTime("2012-12-06 14:00:00");
// cutoff day after invocation time - expected = 30 hours
createSubscription(calculateMillis("2012-12-05 08:00:00"), cutOffDay,
PricingPeriod.HOUR, supplier, product);
// when
BillingRun billingRun = service.generatePaymentPreviewReport(supplier
.getKey());
// then - 30 hours should be invoiced plus one time fee
// 30 * PRICE_PER_HOUR + ONE_TIME_FEE
assertEquals(BigDecimal.valueOf(30100).setScale(2),
overallCosts(billingRun));
assertEquals(calculateMillis("2012-12-01 00:00:00"),
billingRun.getStart());
assertEquals(invocationTime, billingRun.getEnd());
}
/**
* <ul>
* Tests the payment preview calculation with following scenario:
* <li>Cut-off day is after (greater than) invocation day</li>
* <li>The subscription starts BEFORE the calculation period -> no one time
* fee is to be calculated</li>
* <li>Price model of subscription is: Price per hour 1000,00 EUR, one time
* fee 100,00 EUR</li>
* </ul>
*
* @throws Exception
*/
@Test
public void calculateBillingResultsForPaymentPreview_CutoffDayAfterInvocationDay_SubscriptionStartBeforePeriod()
throws Exception {
// given
final int cutOffDay = 28;
final long invocationTime = defineInvocationTime("2012-12-06 14:00:00");
// cutoff day after invocation time - expected = 206 hours
createSubscription(calculateMillis("2012-05-05 08:00:00"), cutOffDay,
PricingPeriod.HOUR, supplier, product);
// when
BillingRun billingRun = service.generatePaymentPreviewReport(supplier
.getKey());
// then - period time of 206 hours * PRICE_PER_HOUR
assertEquals(BigDecimal.valueOf(134000).setScale(2),
overallCosts(billingRun));
assertEquals(calculateMillis("2012-12-01 00:00:00"),
billingRun.getStart());
assertEquals(invocationTime, billingRun.getEnd());
}
/**
* <ul>
* Tests the payment preview calculation with following scenario:
* <li>Cut-off day is equal invocation day</li>
* <li>The subscription starts before the calculation period -> no one time
* fee</li>
* <li>Price model of subscription is: Price per hour 1000,00 EUR, one time
* fee 100,00 EUR</li>
* </ul>
*
* @throws Exception
*/
@Test
public void calculateBillingResultsForPaymentPreview_CutoffEqualInvocationDay_SubscriptionStartBeforePeriod()
throws Exception {
// given
final int cutOffDay = 6;
final long invocationTime = defineInvocationTime("2012-12-06 14:00:00");
// cutoff day equal invocation day - expected = 14 hours
createSubscription(calculateMillis("2012-03-11 08:00:00"), cutOffDay,
PricingPeriod.HOUR, supplier, product);
// when
BillingRun billingRun = service.generatePaymentPreviewReport(supplier
.getKey());
// then - expected are just the hours = 14 hour
assertEquals(BigDecimal.valueOf(14000).setScale(2),
overallCosts(billingRun));
assertEquals(calculateMillis("2012-12-01 00:00:00"),
billingRun.getStart());
assertEquals(invocationTime, billingRun.getEnd());
}
/**
* Test two subscriptions. One is started and terminated in the calculation
* period, the other starts before calculation period. The 29th of February
* should be considered also.
*
* @throws Exception
*/
@Test
public void calculateBillingResultsForPaymentPreview_TwoSubscriptions()
throws Exception {
// given
final int cutOffDaySubscription1 = 4;
final int cutOffDaySubscription2 = 28;
final long invocationTime = defineInvocationTime("2012-03-13 14:00:00");
// 72 hours till invocation time
createSubscription(calculateMillis("2012-03-10 14:00:00"),
cutOffDaySubscription1, PricingPeriod.HOUR, supplier, product);
// 350 hour should be invoiced - because cutoff day of 28th
createSubscription(calculateMillis("2012-02-27 15:00:00"),
cutOffDaySubscription2, PricingPeriod.HOUR, supplier, product);
// when
BillingRun billingRun = service.generatePaymentPreviewReport(supplier
.getKey());
// then - expected costs -> 72100 + 86000
assertEquals(BigDecimal.valueOf(374100).setScale(2),
overallCosts(billingRun));
assertEquals(calculateMillis("2012-03-01 00:00:00"),
billingRun.getStart());
assertEquals(invocationTime, billingRun.getEnd());
}
/**
* Tests, wheter the daylight saving hour will be considered in case of
* {@link PricingPeriod#HOUR}. Between 2012-03-24 and 2012-03-25 it is
* daylight saving where one hour is added. Therefore one hour less should
* be invoiced!
*/
@Test
public void calculateBillingResultsForPaymentPreview_DaylightSavingHoursShouldBeConsidered()
throws Exception {
// given
defineInvocationTime("2012-03-26 14:00:00");
createSubscription(calculateMillis("2012-03-24 14:00:00"), 4,
PricingPeriod.HOUR, supplier, product);
// when
BillingRun billingRun = service.generatePaymentPreviewReport(supplier
.getKey());
// then - expected costs 47100 -> 48 hours - 1 hour day light saving
assertEquals(BigDecimal.valueOf(47100).setScale(2),
overallCosts(billingRun));
}
/**
*
* @param dateFormat
* @return
*/
private long calculateMillis(String dateSource) {
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(DATE_FORMAT_PATTERN);
try {
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dateSource));
c.set(Calendar.MILLISECOND, 0);
return c.getTimeInMillis();
} catch (ParseException e) {
fail("Unable to parse date.");
}
return 0;
}
/**
* Returns the defined invocation time in millis.
*
* @param year
* @param month
* @param day
* @param hour
* @return invocation time in millis.
*/
private long defineInvocationTime(String dateSource) {
final long invocationTime = calculateMillis(dateSource);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(invocationTime);
DateFactory.setInstance(new TestDateFactory(calendar.getTime()));
return invocationTime;
}
private Subscription createSubscription(final long subscriptionStart,
final int cutoffDay, PricingPeriod neededPricingPeriod,
final Organization org, final Product p) {
try {
updatePricingPeriod(neededPricingPeriod, p);
return runTX(new Callable<Subscription>() {
@Override
public Subscription call() throws Exception {
Subscription subscription = Subscriptions
.createSubscription(dm, org.getOrganizationId(),
p.getProductId(), "sub-"
+ UUID.randomUUID().toString(),
subscriptionStart, subscriptionStart,
supplier, cutoffDay);
subscriptions.add(subscription);
return subscription;
}
});
} catch (Exception e) {
fail("Failed to create subscription for test setup.");
}
return null;
}
private BigDecimal overallCosts(BillingRun billingRun) {
assertNotNull(billingRun);
BigDecimal overallCosts = BigDecimal.valueOf(0).setScale(2);
for (BillingResult br : billingRun.getBillingResultList()) {
overallCosts = overallCosts.add(br.getGrossAmount());
}
return overallCosts;
}
private void updatePricingPeriod(final PricingPeriod newPricingPeriod,
final Product p) {
// if desired pricemodel is already set, do nothing
if (newPricingPeriod.equals(p.getPriceModel().getPeriod())) {
return;
}
try {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
Product pr = Products.findProduct(dm, supplier,
p.getProductId());
assertNotNull(
"Cannot find product in order to update pricing period!",
pr);
pr.getPriceModel().setPeriod(newPricingPeriod);
return null;
}
});
product.getPriceModel().setPeriod(newPricingPeriod);
} catch (Exception e) {
fail("Unable to update pricing period!");
}
}
@Override
protected void setup(TestContainer container) throws Exception {
subscriptions = new ArrayList<Subscription>();
setupContainer(container);
dm = container.get(DataService.class);
service = container.get(BillingServiceLocal.class);
setBaseDataCreationDate();
runTX(new Callable<SupportedCurrency>() {
@Override
public SupportedCurrency call() throws Exception {
return SupportedCurrencies.findOrCreate(dm, "EUR");
}
});
supplier = runTX(new Callable<Organization>() {
@Override
public Organization call() throws Exception {
createPaymentTypes(dm);
createOrganizationRoles(dm);
SupportedCountries.createSomeSupportedCountries(dm);
Organization org = Organizations.createOrganization(dm,
OrganizationRoleType.SUPPLIER);
return org;
}
});
technicalProduct = runTX(new Callable<TechnicalProduct>() {
@Override
public TechnicalProduct call() throws Exception {
return TechnicalProducts.createTechnicalProduct(dm, supplier,
"techProduct1", false, ServiceAccessType.LOGIN);
}
});
product = runTX(new Callable<Product>() {
@SuppressWarnings("boxing")
@Override
public Product call() throws Exception {
Product p = Products.createProduct(supplier, technicalProduct,
true, "product1", null, dm);
priceModel = p.getPriceModel();
priceModel.setPeriod(PricingPeriod.HOUR);
SupportedCurrency template = new SupportedCurrency();
template.setCurrency(Currency.getInstance("EUR"));
template = (SupportedCurrency) dm
.getReferenceByBusinessKey(template);
priceModel.setCurrency(template);
priceModel.setOneTimeFee(new BigDecimal(ONE_TIME_FEE));
priceModel.setPricePerPeriod(new BigDecimal(PRICE_PER_UNIT));
return p;
}
});
}
/**
* Setup the container.
*
* @param container
* @throws Exception
*/
@SuppressWarnings("boxing")
private void setupContainer(TestContainer container) throws Exception {
container.enableInterfaceMocking(true);
container.login("1");
container.addBean(mock(TenantProvisioningServiceBean.class));
container.addBean(new DataServiceBean());
container.addBean(new ConfigurationServiceStub());
container.addBean(new PaymentServiceStub());
container.addBean(new ApplicationServiceBaseStub());
container.addBean(mock(SubscriptionServiceLocal.class));
container.addBean(new CommunicationServiceStub());
container.addBean(new SessionServiceStub());
container.addBean(new LdapAccessServiceStub());
container.addBean(new LocalizerServiceBean());
container.addBean(new ImageResourceServiceStub());
sharesCalculator = mock(SharesCalculatorLocal.class);
when(
sharesCalculator.performBrokerSharesCalculationRun(anyLong(),
anyLong())).thenReturn(Boolean.TRUE);
when(
sharesCalculator.performMarketplacesSharesCalculationRun(
anyLong(), anyLong())).thenReturn(Boolean.TRUE);
when(
sharesCalculator.performResellerSharesCalculationRun(anyLong(),
anyLong())).thenReturn(Boolean.TRUE);
when(
sharesCalculator.performSupplierSharesCalculationRun(anyLong(),
anyLong())).thenReturn(Boolean.TRUE);
container.addBean(sharesCalculator);
container.addBean(new TriggerQueueServiceStub());
container.addBean(new TagServiceBean());
container.addBean(new MarketingPermissionServiceBean());
container.addBean(new MarketplaceServiceStub());
container.addBean(new ServiceProvisioningServiceBean());
container.addBean(new BillingDataRetrievalServiceBean());
container.addBean(new RevenueCalculatorBean());
container.addBean(new BillingServiceBean());
}
protected void setBaseDataCreationDate() {
final Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2010);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
DateFactory.setInstance(new TestDateFactory(cal.getTime()));
}
}
| apache-2.0 |
ChiangC/CHIANG_PROS | HwVmall/app/src/test/java/com/fmtech/hi/hwvmalllogitic/ExampleUnitTest.java | 321 | package com.fmtech.hi.hwvmalllogitic;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
antionio/Dodge-The-Cars | dodgethecars-desktop/src/com/sturdyhelmetgames/dodgethecars/SwarmConstants.java | 807 | package com.sturdyhelmetgames.dodgethecars;
/**
* A class containing constant values for Swarm integration.
* <p/>
* <a href="http://swarmconnect.com/">http://swarmconnect.com/</a>
* <p/>
* Please create a Swarm account to get your own APP_ID and AUTH_KEY
*
* @author Antti
*
*/
public final class SwarmConstants {
public static final class App {
public static final int APP_ID = 0; // YOUR APP_ID goes here.
public static final String APP_AUTH = ""; // YOUR APP_AUTH goes here.
}
public static final class Leaderboard {
public static final int GLOBAL_ID = 0; // YOUR LEADERBOARD ID GOES HERE.
}
public static final class Achievement {
}
public static final class StoreCategory {
}
public static final class StoreItem {
}
public static final class StoreItemListing {
}
} | apache-2.0 |
jhelmer-unicon/uPortal | uportal-war/src/main/java/org/apereo/portal/events/aggr/EventAggregationContextImpl.java | 1584 | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the License at the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apereo.portal.events.aggr;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Basic context impl
*
* @author Eric Dalquist
*/
class EventAggregationContextImpl implements EventAggregationContext {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private final Map<Object, Object> attributes = new HashMap<Object, Object>();
@Override
public void setAttribute(Object key, Object value) {
final Object old = this.attributes.put(key, value);
if (old != null) {
logger.warn("Replaced existing event aggr context for key={}", key);
}
}
@Override
public <T> T getAttribute(Object key) {
return (T) attributes.get(key);
}
}
| apache-2.0 |
googleads/googleads-java-lib | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201809/mcm/LabelServiceError.java | 5437 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* LabelServiceError.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201809.mcm;
/**
* Errors for {@link LabelService}.
*/
public class LabelServiceError extends com.google.api.ads.adwords.axis.v201809.cm.ApiError implements java.io.Serializable {
private com.google.api.ads.adwords.axis.v201809.mcm.LabelServiceErrorReason reason;
public LabelServiceError() {
}
public LabelServiceError(
java.lang.String fieldPath,
com.google.api.ads.adwords.axis.v201809.cm.FieldPathElement[] fieldPathElements,
java.lang.String trigger,
java.lang.String errorString,
java.lang.String apiErrorType,
com.google.api.ads.adwords.axis.v201809.mcm.LabelServiceErrorReason reason) {
super(
fieldPath,
fieldPathElements,
trigger,
errorString,
apiErrorType);
this.reason = reason;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("apiErrorType", getApiErrorType())
.add("errorString", getErrorString())
.add("fieldPath", getFieldPath())
.add("fieldPathElements", getFieldPathElements())
.add("reason", getReason())
.add("trigger", getTrigger())
.toString();
}
/**
* Gets the reason value for this LabelServiceError.
*
* @return reason
*/
public com.google.api.ads.adwords.axis.v201809.mcm.LabelServiceErrorReason getReason() {
return reason;
}
/**
* Sets the reason value for this LabelServiceError.
*
* @param reason
*/
public void setReason(com.google.api.ads.adwords.axis.v201809.mcm.LabelServiceErrorReason reason) {
this.reason = reason;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof LabelServiceError)) return false;
LabelServiceError other = (LabelServiceError) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.reason==null && other.getReason()==null) ||
(this.reason!=null &&
this.reason.equals(other.getReason())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getReason() != null) {
_hashCode += getReason().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(LabelServiceError.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/mcm/v201809", "LabelServiceError"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("reason");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/mcm/v201809", "reason"));
elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/mcm/v201809", "LabelServiceError.Reason"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
mattyb149/pdi-script-extension-points | src/main/java/ninja/mattburgess/pentaho/di/extensionpoints/script/trans/TransformationPrepareExecutor.java | 584 | package ninja.mattburgess.pentaho.di.extensionpoints.script.trans;
import ninja.mattburgess.pentaho.di.extensionpoints.script.BaseExtensionPointExecutor;
import org.pentaho.di.core.extension.ExtensionPoint;
@ExtensionPoint(
id = "TransformationPrepareScript",
extensionPointId = "TransformationPrepareExecution",
description = "Executes script(s) when transformations are preparing for execution"
)
public class TransformationPrepareExecutor extends BaseExtensionPointExecutor {
public TransformationPrepareExecutor() {
super( "TransformationPrepareExecution" );
}
}
| apache-2.0 |
Orange-OpenSource/matos-profiles | matos-android/src/main/java/android/graphics/drawable/AnimatedRotateDrawable.java | 2700 | package android.graphics.drawable;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public class AnimatedRotateDrawable
extends Drawable implements Animatable, java.lang.Runnable, Drawable.Callback
{
// Constructors
public AnimatedRotateDrawable(){
super();
}
// Methods
public void run(){
}
public void start(){
}
public void stop(){
}
public void inflate(android.content.res.Resources arg1, @com.francetelecom.rd.stubs.annotation.CallBackRegister("xmlPullParser") org.xmlpull.v1.XmlPullParser arg2, android.util.AttributeSet arg3) throws org.xmlpull.v1.XmlPullParserException, java.io.IOException{
}
public int getChangingConfigurations(){
return 0;
}
public boolean setVisible(boolean arg1, boolean arg2){
return false;
}
public boolean isRunning(){
return false;
}
public void setAlpha(int arg1){
}
public void draw(android.graphics.Canvas arg1){
}
public void invalidateDrawable(Drawable arg1){
}
public void scheduleDrawable(Drawable arg1, @com.francetelecom.rd.stubs.annotation.CallBackRegister("java.lang.Runnable.run") java.lang.Runnable arg2, long arg3){
}
public void unscheduleDrawable(Drawable arg1, @com.francetelecom.rd.stubs.annotation.CallBackRegister("java.lang.Runnable.run") java.lang.Runnable arg2){
}
public int getOpacity(){
return 0;
}
public Drawable.ConstantState getConstantState(){
return (Drawable.ConstantState) null;
}
public int getIntrinsicWidth(){
return 0;
}
public int getIntrinsicHeight(){
return 0;
}
public void setColorFilter(android.graphics.ColorFilter arg1){
}
protected void onBoundsChange(android.graphics.Rect arg1){
}
public Drawable mutate(){
return (Drawable) null;
}
public boolean isStateful(){
return false;
}
public boolean getPadding(android.graphics.Rect arg1){
return false;
}
public Drawable getDrawable(){
return (Drawable) null;
}
public void setFramesCount(int arg1){
}
public void setFramesDuration(int arg1){
}
}
| apache-2.0 |
lastfm/musicbrainz-data | src/main/java/fm/last/musicbrainz/data/model/Track.java | 3299 | /*
* Copyright 2013 The musicbrainz-data Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fm.last.musicbrainz.data.model;
import java.util.Set;
import java.util.UUID;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
@Access(AccessType.FIELD)
@Entity
@Table(name = "track", schema = "musicbrainz")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Track {
@Id
@Column(name = "id")
private int id;
@Column(name = "gid", nullable = false, unique = true)
@Type(type = "pg-uuid")
private UUID gid;
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "track_gid_redirect", schema = "musicbrainz", joinColumns = @JoinColumn(name = "new_id"))
@Column(name = "gid")
@Type(type = "pg-uuid")
private final Set<UUID> redirectedGids = Sets.newHashSet();
@ManyToOne(targetEntity = ArtistCredit.class, fetch = FetchType.LAZY)
@JoinColumn(name = "artist_credit", nullable = true)
private ArtistCredit artistCredit;
@Column(name = "position")
private int position;
@Column(name = "number")
private String number;
@Column(name = "name")
private String name;
@ManyToOne(targetEntity = Recording.class, fetch = FetchType.LAZY)
@JoinColumn(name = "recording")
private Recording recording;
@Column(name = "length")
private Integer length;
@Column(name = "last_updated")
@Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
private DateTime lastUpdated;
public int getId() {
return id;
}
public int getPosition() {
return position;
}
public String getNumber() {
return number;
}
public String getName() {
return name;
}
public ArtistCredit getArtistCredit() {
return artistCredit;
}
public Recording getRecording() {
return recording;
}
/**
* Length in milliseconds.
*/
public Integer getLength() {
return length;
}
public DateTime getLastUpdated() {
return lastUpdated;
}
/**
* Returns an immutable set of all associated GIDs (canonical and redirected).
*/
public Set<UUID> getGids() {
return new ImmutableSet.Builder<UUID>().addAll(redirectedGids).add(gid).build();
}
}
| apache-2.0 |
tadayosi/thinkit-fuse-eip | src/test/java/com/redhat/examples/fuse/eip/RecipientListTest.java | 1105 | package com.redhat.examples.fuse.eip;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.blueprint.CamelBlueprintTestSupport;
import org.junit.Test;
public class RecipientListTest extends CamelBlueprintTestSupport {
@Override
protected String getBlueprintDescriptor() {
return "/OSGI-INF/blueprint/recipient-list-camel-context.xml";
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:aaa").to("mock:aaa");
from("direct:bbb").to("mock:bbb");
from("direct:ccc").to("mock:ccc");
}
};
}
@Test
public void recipientList() throws Exception {
getMockEndpoint("mock:aaa").expectedMessageCount(1);
getMockEndpoint("mock:bbb").expectedMessageCount(1);
getMockEndpoint("mock:ccc").expectedMessageCount(1);
template.sendBody("direct:in", "TEST");
assertMockEndpointsSatisfied();
}
}
| apache-2.0 |
Ben-Woolley/java-for-beginners | intro-to-java/src/main/java/eca/samples/codestructure/Braces.java | 604 | package eca.samples.codestructure;
public class Braces {
public static void main(String[] args) {
var sayHello = true;
if (sayHello) { // context of if-statement starts here
// sayHello is accessible here, because this block is inside main
var helloMessage = "Hello there!";
System.out.println(helloMessage);
} // context of if-statement starts here
// helloMessage is inaccessible here, we're not in the if statement's context
// System.out.println(helloMessage); // This line would not work if uncommented
}
} | apache-2.0 |
nasa/OpenSPIFe | gov.nasa.ensemble.core.model.common/src/gov/nasa/ensemble/core/model/common/util/ModelUtil.java | 1116 | /*******************************************************************************
* Copyright 2014 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package gov.nasa.ensemble.core.model.common.util;
import gov.nasa.ensemble.emf.util.EMFUtils;
/**
* @deprecated - use EMFUtils instead
*/
@Deprecated
public class ModelUtil extends EMFUtils {
// marker class (to be deprecated)
}
| apache-2.0 |
Sellegit/j2objc | runtime/src/main/java/apple/eventkit/EKSource.java | 1250 | package apple.eventkit;
import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.addressbook.*;
import apple.corelocation.*;
/**
* @since Available in iOS 5.0 and later.
*/
@Library("EventKit/EventKit.h") @Mapping("EKSource")
public class EKSource
extends EKObject
{
@Mapping("init")
public EKSource() { }
@Mapping("sourceIdentifier")
public native String getSourceIdentifier();
@Mapping("sourceType")
public native EKSourceType getSourceType();
@Mapping("title")
public native String getTitle();
/**
* @since Available in iOS 4.0 and later.
* @deprecated Deprecated in iOS 6.0.
*/
@Deprecated
@Mapping("calendars")
public native NSSet<EKCalendar> getCalendars();
/**
* @since Available in iOS 6.0 and later.
*/
@Mapping("calendarsForEntityType:")
public native NSSet<EKCalendar> getCalendars(@Representing("EKEntityType") long entityType);
}
| apache-2.0 |
netomi/sat-tracker | src/main/java/org/netomi/tracker/orekit/SatellitePropagation.java | 15556 | package org.netomi.tracker.orekit;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.netomi.tracker.orekit.VisibilityEntry.Point;
import org.orekit.bodies.BodyShape;
import org.orekit.bodies.GeodeticPoint;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.errors.OrekitException;
import org.orekit.errors.PropagationException;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.frames.TopocentricFrame;
import org.orekit.propagation.BoundedPropagator;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.analytical.tle.TLE;
import org.orekit.propagation.analytical.tle.TLEPropagator;
import org.orekit.propagation.events.ElevationDetector;
import org.orekit.propagation.sampling.OrekitFixedStepHandler;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides satellite propagation calculation.
*/
public class SatellitePropagation {
private final static Logger logger = LoggerFactory.getLogger(SatellitePropagation.class);
// Earth constants and reference frame
// equatorial radius in meter
private static final double ae = Constants.WGS84_EARTH_EQUATORIAL_RADIUS;
// flattening
private static final double f = Constants.WGS84_EARTH_FLATTENING;
/**
* Propagates a satellite in the given time interval and returns a {@link List} of {@link GeodeticPoint}
* entries along the path.
*
* @param satTLE the two-line element of the satellite
* @param startDate the starting date for the propagation
* @param duration the duration of the propagation
* @param step the step size of the propagation (in seconds)
* @return
* @throws OrekitException
*/
public static List<GeodeticPoint> propagate(final TLE satTLE, final AbsoluteDate startDate,
final double duration, final long step)
throws OrekitException {
// Propagator based on TLE propagation
Propagator prop = TLEPropagator.selectExtrapolator(satTLE);
// terrestrial frame at an arbitrary date
Frame ITRF2005 = FramesFactory.getITRF2005();
final BodyShape earth = new OneAxisEllipsoid(ae, f, ITRF2005);
// setup an arbitrary station on the surface of the earth
double longitude = Math.toRadians(45.);
double latitude = Math.toRadians(25.);
double altitude = 0.;
final GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude);
final TopocentricFrame stationFrame = new TopocentricFrame(earth, station, "ground location");
prop.propagate(startDate);
final List<GeodeticPoint> points = new LinkedList<GeodeticPoint>();
prop.setMasterMode(step, new OrekitFixedStepHandler() {
private static final long serialVersionUID = 1L;
@Override
public void init(SpacecraftState state, AbsoluteDate date) {
}
public void handleStep(SpacecraftState currentState, boolean isLast)
throws PropagationException {
try {
points.add(convertToGeodeticPoint(currentState, stationFrame, earth));
} catch (OrekitException e) {
e.printStackTrace();
}
}
});
// Propagate from the start date for the fixed duration
prop.propagate(startDate.shiftedBy(duration));
return points;
}
/**
* Calculates and returns an ephemeris for the given satellite in the specified time interval.
* The returned {@link BoundedPropagator} can be used to propagate the {@link SpacecraftState}
* of the satellite at any time within the time interval.
*
* @param satTLE the two-line element of the satellite
* @param startDate the starting date for the propagation
* @param duration the duration of the propagation
* @param step the step size of the propagation (in seconds)
* @return a {@link BoundedPropagator} used to access the ephemeris in the time interval
* @throws OrekitException
*/
public static BoundedPropagator getEphemeris(final TLE satTLE, final AbsoluteDate startDate,
final double duration, final long step)
throws OrekitException {
// Propagator based on TLE propagation
TLEPropagator prop = TLEPropagator.selectExtrapolator(satTLE);
// propagate to the starting date in slave mode
prop.propagate(startDate);
// set ephemeris mode
prop.setEphemerisMode();
prop.setInitialState(startDate);
// propagate from the start date for the fixed duration
prop.propagate(startDate.shiftedBy(duration));
return prop.getGeneratedEphemeris();
}
/**
* Calculate visibility entries for a given ground location within a defined time-span. A visibility is defined to
* be an event when the satellite is a specified elevation degree above the horizon from the viewpoint of the ground
* station.
*
* @param lat the latitude of the ground location (in degrees)
* @param lon the longitude of the ground location (in degrees)
* @param altitude the altitude of the ground location (in m)
* @param elevation the minimum elevation to start a visibility
* @param satTLE the two-line element of the satellite
* @param startDate the starting date for the calculation
* @param duration the duration of the calculation (in s)
* @return a {@link List} of {@link VisibilityEntry} objects
*/
public static List<VisibilityEntry> getVisibilities(double lat, double lon, double altitude, double elevation,
final TLE satTLE, final AbsoluteDate startDate, double duration)
throws OrekitException {
// Propagator based on TLE propagation
Propagator prop = TLEPropagator.selectExtrapolator(satTLE);
final BodyShape earth = new OneAxisEllipsoid(ae, f, FramesFactory.getITRF2005());
// Get station data
final double latitude = Math.toRadians(lat);
final double longitude = Math.toRadians(lon);
final GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude);
final TopocentricFrame stationFrame = new TopocentricFrame(earth, station, "ground location");
prop.propagate(startDate);
// Create an event collector
final EventCollector collector = new EventCollector();
// Add now the visibility detectors
// TODO: check if 3 min is ok
final double maxcheck = 60. * 3;
// the detector for the effective elevation in place
final VisibilityDetector stationVisibility = new VisibilityDetector(maxcheck, elevation, stationFrame,
collector);
prop.addEventDetector(stationVisibility);
// Propagate from the start date for the fixed duration
prop.propagate(startDate.shiftedBy(duration));
return collector.getVisibilityEntries();
}
public static void fillVisibilityEntry(double lat, double lon, double altitude,
final TLE satTLE, final VisibilityEntry entry)
throws OrekitException {
// Propagator based on TLE propagation
Propagator prop = TLEPropagator.selectExtrapolator(satTLE);
final BodyShape earth = new OneAxisEllipsoid(ae, f, FramesFactory.getITRF2005());
// Get station data
final double latitude = Math.toRadians(lat);
final double longitude = Math.toRadians(lon);
final GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude);
final TopocentricFrame stationFrame = new TopocentricFrame(earth, station, "ground location");
prop.propagate(new AbsoluteDate(entry.getStart(), TimeScalesFactory.getUTC()));
final List<Point> points = new LinkedList<Point>();
// calculate an entry every 20s
prop.setMasterMode(20, new OrekitFixedStepHandler() {
private static final long serialVersionUID = 1L;
@Override
public void init(SpacecraftState state, AbsoluteDate date) {
}
public void handleStep(SpacecraftState currentState, boolean isLast)
throws PropagationException {
try {
points.add(convertToPoint(currentState, stationFrame, earth));
} catch (OrekitException e) {
logger.error("failed to convert a satellite state to a geodetic point", e);
}
}
});
// Propagate from the start date for the fixed duration
prop.propagate(new AbsoluteDate(entry.getEnd(), TimeScalesFactory.getUTC()));
// points.add(convertToPoint(finalState, stationFrame, earth));
entry.setPoints(points);
}
/**
* Transforms a {@link SpacecraftState} into a {@link GeodeticPoint} on the surface of the
* given body.
*
* @param state the state to be transformed
* @param frame the frame associated with the surface of the body
* @param body the body
* @return the transformed {@link GeodeticPoint}
* @throws OrekitException
*/
public static GeodeticPoint convertToGeodeticPoint(final SpacecraftState state,
final TopocentricFrame frame,
final BodyShape body)
throws OrekitException {
Vector3D pos = state.getPVCoordinates(frame).getPosition();
GeodeticPoint gp = body.transform(pos, frame, state.getDate());
return gp;
}
private static Point convertToPoint(final SpacecraftState state, final TopocentricFrame stationFrame,
final BodyShape body)
throws OrekitException {
Vector3D pos = state.getPVCoordinates(stationFrame).getPosition();
GeodeticPoint gp = body.transform(pos, stationFrame, state.getDate());
double lat = Math.toDegrees(gp.getLatitude());
double lon = Math.toDegrees(gp.getLongitude());
double elevation = Math.toDegrees(stationFrame.getElevation(state.getPVCoordinates().getPosition(),
state.getFrame(), state.getDate()));
double azimuth = Math.toDegrees(stationFrame.getAzimuth(state.getPVCoordinates().getPosition(),
state.getFrame(), state.getDate()));
return new Point(state.getDate().toDate(TimeScalesFactory.getUTC()), elevation, azimuth, lat, lon);
}
/**
* Collects elevation events and creates corresponding visibility entries, taking into account zero degree and
* effective elevation.
*/
private static class EventCollector {
private List<VisibilityEntry> entries;
private TimeScale utcScale;
public EventCollector()
throws OrekitException {
entries = new ArrayList<VisibilityEntry>();
utcScale = TimeScalesFactory.getUTC();
}
/**
* Returns the captures visibility entries.
*
* @return a {@link List} of {@link VisibilityEntry} object
*/
public List<VisibilityEntry> getVisibilityEntries() {
return entries;
}
public void foundVisibility(double elevation, final AbsoluteDate startTime, final AbsoluteDate endTime) {
VisibilityEntry entry = new VisibilityEntry();
entry.setStart(startTime.toDate(utcScale));
entry.setEnd(endTime.toDate(utcScale));
entry.setElev(elevation);
entries.add(entry);
}
}
/**
* Finder for a visibility event.
*/
private static class VisibilityDetector
extends ElevationDetector {
private static final long serialVersionUID = 1L;
private transient EventCollector collector;
private AbsoluteDate startTime;
private AbsoluteDate endTime;
public VisibilityDetector(double maxCheck, double elevation, TopocentricFrame topo,
final EventCollector collector)
throws OrekitException {
super(maxCheck, elevation, topo);
this.collector = collector;
startTime = endTime = null;
}
/**
* For each finished event, create a visibility entry.
*/
public Action eventOccurred(final SpacecraftState s, final boolean increasing)
throws OrekitException {
if (increasing) {
startTime = s.getDate();
} else {
endTime = s.getDate();
if (startTime != null && endTime != null) {
if (collector != null) {
collector.foundVisibility(getElevation(), startTime, endTime);
}
startTime = endTime = null;
}
}
return Action.CONTINUE;
}
}
public static void main(String[] args)
throws Exception {
OrekitConfiguration.configureOrekit();
String line1 = "1 29601U 06052A 12082.22855714 -.00000038 00000-0 10000-3 0 6711";
String line2 = "2 29601 56.0932 58.5006 0039010 354.4184 5.5265 2.00577835 39160";
TLE tle = new TLE(line1, line2);
AbsoluteDate startDate = new AbsoluteDate(new Date(), TimeScalesFactory.getUTC());
System.out.println(startDate);
System.out.println(startDate.shiftedBy(60L * 717.93));
BoundedPropagator boundedProp = SatellitePropagation.getEphemeris(tle, startDate, 60L * 717.93, 180);
System.out.println(boundedProp.getMinDate());
System.out.println(boundedProp.getMaxDate());
AbsoluteDate endDate = boundedProp.getMaxDate();
AbsoluteDate curr = boundedProp.getMinDate();
// terrestrial frame at an arbitrary date
Frame ITRF2005 = FramesFactory.getITRF2005();
final BodyShape earth = new OneAxisEllipsoid(ae, f, ITRF2005);
// setup an arbitrary station on the surface of the earth
double longitude = Math.toRadians(45.);
double latitude = Math.toRadians(25.);
double altitude = 0.;
final GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude);
final TopocentricFrame stationFrame = new TopocentricFrame(earth, station, "ground location");
while (curr.compareTo(endDate) < 0) {
final SpacecraftState state = boundedProp.propagate(curr);
final GeodeticPoint gp = convertToGeodeticPoint(state, stationFrame, earth);
double lat = Math.toDegrees(gp.getLatitude());
double lon = Math.toDegrees(gp.getLongitude());
System.out.println("lon=" + lon + ", lat=" + lat + ", alt=" + gp.getAltitude());
curr = curr.shiftedBy(90);
}
}
}
| apache-2.0 |
k24/retrofit-promise-qiita4jv2 | core/src/test/java/com/github/k24/qiita4jv2/QiitaApiAgentUserTest.java | 5614 | package com.github.k24.qiita4jv2;
import com.github.k24.deferred.Deferred;
import com.github.k24.deferred.RxJava2DeferredFactory;
import com.github.k24.deferred.RxJava2Promise;
import com.github.k24.qiita4jv2.api.UsersApi;
import com.github.k24.qiita4jv2.model.User;
import com.github.k24.qiita4jv2.util.Success;
import com.github.k24.qiita4jv2.util.SuccessConverterFactory;
import com.github.k24.retrofit2.adapter.promise.PromiseCallAdapterFactory;
import com.github.k24.retrofit2.converter.jsonic.JsonicConverterFactory;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import org.junit.Before;
import org.junit.Test;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.mock.BehaviorDelegate;
import retrofit2.mock.MockRetrofit;
import retrofit2.mock.NetworkBehavior;
import java.io.IOException;
import java.util.List;
import static com.github.k24.deferred.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by k24 on 2017/03/06.
*/
public class QiitaApiAgentUserTest {
private MockRetrofit mockRetrofit;
private MockUsersApi mockUsersApi;
@Before
public void setUp() throws Exception {
mockRetrofit = new MockRetrofit.Builder(new Retrofit.Builder()
.baseUrl("https://qiita.com/api/v2/")
.addCallAdapterFactory(PromiseCallAdapterFactory.create(RxJava2DeferredFactory.createWithScheduler(Schedulers.io())))
.addConverterFactory(SuccessConverterFactory.create())
.addConverterFactory(JsonicConverterFactory.create())
.client(new OkHttpClient())
.build())
.build();
NetworkBehavior networkBehavior = mockRetrofit.networkBehavior();
networkBehavior.setErrorPercent(0);
networkBehavior.setFailurePercent(0);
BehaviorDelegate<UsersApi> delegate = mockRetrofit.create(UsersApi.class);
mockUsersApi = new MockUsersApi(delegate).withDefault();
}
@Test
public void stockers() throws Exception {
List<User> expected = MockUsersApi.defaultUsers();
Deferred.Promise<Response<List<User>>> actualPromise = mockUsersApi.stockers("itemId", 0, 20);
assertThat(actualPromise)
.isNotNull();
Response<List<User>> response = RxJava2Promise.maybe(actualPromise).blockingGet();
assertThat(response.body())
.isEqualTo(expected);
}
@Test
public void user() throws Exception {
User expected = MockUsersApi.defaultUsers().get(0);
Deferred.Promise<User> actualPromise = mockUsersApi.user("userId");
assertThat(actualPromise)
.isNotNull()
.verify(expected);
}
@Test
public void unfollow() throws Exception {
Success expected = Success.SUCCESS;
Deferred.Promise<Success> actualPromise = mockUsersApi.unfollow("userId");
assertThat(actualPromise)
.isNotNull()
.verify(expected);
}
private static class MockUsersApi implements UsersApi {
private final BehaviorDelegate<UsersApi> delegate;
private List<User> users;
public MockUsersApi(BehaviorDelegate<UsersApi> delegate) {
this.delegate = delegate;
}
public MockUsersApi withDefault() throws IOException {
users = defaultUsers();
return this;
}
public static List<User> defaultUsers() throws IOException {
return TestFixture.asList(TestFixture.user(), 20);
}
@Override
public Deferred.Promise<Response<List<User>>> stockers(@Path("item_id") String itemId, @Query("page") Integer page, @Query("per_page") Integer perPage) {
return list().stockers(itemId, page, perPage);
}
@Override
public Deferred.Promise<Response<List<User>>> users(@Query("page") Integer page, @Query("per_page") Integer perPage) {
return list().users(page, perPage);
}
@Override
public Deferred.Promise<User> user(@Path("user_id") String userId) {
return single().user(userId);
}
@Override
public Deferred.Promise<Response<List<User>>> followees(@Path("user_id") String userId, @Query("page") Integer page, @Query("per_page") Integer perPage) {
return list().followees(userId, page, perPage);
}
@Override
public Deferred.Promise<Response<List<User>>> followers(@Path("user_id") String userId, @Query("page") Integer page, @Query("per_page") Integer perPage) {
return list().followers(userId, page, perPage);
}
@Override
public Deferred.Promise<Success> unfollow(@Path("user_id") String userId) {
return success().unfollow(userId);
}
@Override
public Deferred.Promise<User> following(@Path("user_id") String userId) {
return single().following(userId);
}
@Override
public Deferred.Promise<Success> follow(@Path("user_id") String userId) {
return success().follow(userId);
}
//region Delegates
private UsersApi single() {
return delegate.returningResponse(users.get(0));
}
private UsersApi list() {
return delegate.returningResponse(users);
}
private UsersApi success() {
return delegate.returningResponse(Success.SUCCESS);
}
//endregion
}
}
| apache-2.0 |
wdawson/revoker | src/test/java/wdawson/samples/revoker/managers/CertificateManagerTest.java | 2591 | package wdawson.samples.revoker.managers;
import com.google.common.collect.Lists;
import java.math.BigInteger;
import java.security.cert.X509CRL;
import java.security.cert.X509CRLEntry;
import javax.security.auth.x500.X500Principal;
import org.junit.Before;
import org.junit.Test;
import wdawson.samples.revoker.representations.CRLNameFilePair;
import wdawson.samples.revoker.representations.CertificateStatus;
import wdawson.samples.revoker.representations.CertificateSummary;
import static io.dropwizard.testing.ResourceHelpers.resourceFilePath;
import static org.assertj.core.api.Assertions.assertThat;
import static wdawson.samples.revoker.representations.CertificateSummary.DATE_TIME_FORMATTER;
/**
* @author wdawson
*/
public class CertificateManagerTest {
private CertificateManager certificateManager;
private static final String CRL_NAME = "crl.pem";
@Before
public void setup() {
certificateManager = new CertificateManager(resourceFilePath("index.txt"),
Lists.newArrayList(new CRLNameFilePair(CRL_NAME, resourceFilePath("crl/crl.pem"))),
10);
}
@Test
public void crlFileCanBeParsed() throws Exception {
certificateManager.newNonRunningDataUpdater().refreshCRLs();
X509CRL crl = certificateManager.getCRL(CRL_NAME);
assertThat(crl).isNotNull();
assertThat(crl.getRevokedCertificates()).hasSize(1);
X509CRLEntry crlEntry = crl.getRevokedCertificate(new BigInteger("1002", 16));
assertThat(crlEntry).isNotNull();
assertThat(crlEntry.getRevocationDate()).isEqualTo(DATE_TIME_FORMATTER.parseDateTime("151217225905Z").toDate());
}
@Test
public void indexFileCanBeParsed() throws Exception {
certificateManager.newNonRunningDataUpdater().parseIndexFile();
CertificateSummary summary = certificateManager.getSummary(new BigInteger("1002", 16));
CertificateSummary expected = CertificateSummary.newBuilder()
.withStatus(CertificateStatus.REVOKED)
.withExpirationTime(DATE_TIME_FORMATTER.parseDateTime("161226225851Z"))
.withRevocationTime(DATE_TIME_FORMATTER.parseDateTime("151217225905Z"))
.withRevocationReason(null)
.withSerialNumber(new BigInteger("1002", 16))
.withFileName(null)
.withSubjectDN(new X500Principal("C=US, ST=California, L=San Francisco, O=test, OU=test, CN=two"))
.build();
assertThat(summary).isEqualToIgnoringGivenFields(expected, "thisUpdateTime");
}
}
| apache-2.0 |
da1z/intellij-community | plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/style/MethodRefCanBeReplacedWithLambdaFixTest.java | 3433 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig.fixes.style;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.testFramework.IdeaTestUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.IGQuickFixesTestCase;
import com.siyeh.ig.style.MethodRefCanBeReplacedWithLambdaInspection;
public class MethodRefCanBeReplacedWithLambdaFixTest extends IGQuickFixesTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
ModuleRootModificationUtil.setModuleSdk(myModule, IdeaTestUtil.getMockJdk18());
myFixture.enableInspections(new MethodRefCanBeReplacedWithLambdaInspection());
myDefaultHint = InspectionGadgetsBundle.message("method.ref.can.be.replaced.with.lambda.quickfix");
}
@Override
protected String getRelativePath() {
return "style/methodRefs2lambda";
}
public void testRedundantCast() {
doTest();
}
public void testStaticMethodRef() {
doTest();
}
public void testThisRefs() {
doTest();
}
public void testSuperRefs() {
doTest();
}
public void testExprRefs() {
doTest();
}
public void testReceiver() {
doTest();
}
public void testNewRefs() {
doTest();
}
public void testNewRefsDefaultConstructor() {
doTest();
}
public void testNewRefsInnerClass() {
doTest();
}
public void testNewRefsStaticInnerClass() {
doTest();
}
public void testNewRefsInference() {
doTest(myDefaultHint);
}
public void testNewRefsInference1() {
doTest();
}
public void testAmbiguity() {
doTest();
}
public void testSubst() {
doTest();
}
public void testTypeElementOnTheLeft() {
doTest();
}
public void testNewDefaultConstructor() {
doTest();
}
public void testArrayConstructorRef() {
doTest();
}
public void testArrayConstructorRef2Dim() {
doTest();
}
public void testArrayMethodRef() {
doTest(myDefaultHint );
}
public void testArrayConstructorRefUniqueParamName() {
doTest();
}
public void testNameConflicts() {
doTest();
}
public void testIntroduceVariableForSideEffectQualifier() {
doTest(myDefaultHint + " (side effects)");
}
public void testCollapseToExpressionLambdaWhenCast() {
doTest();
}
public void testPreserveExpressionQualifier() {
doTest();
}
public void testNoUnderscoreInLambdaParameterName() {
doTest();
}
public void testNoCastWhereCaptureArgIsExpected() {
doTest();
}
public void testSpecifyFormalParameterTypesWhenMethodReferenceWasExactAndTypeOfParameterIsUnknown() {
doTest();
}
public void testNewArrayMethodReferenceHasNoSideEffects() {
doTest();
}
public void testEnsureNoConversionIsSuggestedWhenLambdaWithoutCantBeInferredAndFormalParametersAreNotDenotable() {
assertQuickfixNotAvailable();
}
}
| apache-2.0 |
lpicanco/grails | src/commons/org/codehaus/groovy/grails/support/ClassEditor.java | 1705 | /*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.support;
import java.beans.PropertyEditorSupport;
import org.springframework.util.ClassUtils;
/**
*
*
* @author Steven Devijver
* @since Aug 8, 2005
*/
public class ClassEditor extends PropertyEditorSupport {
private ClassLoader classLoader = null;
public ClassEditor() {
super();
}
public ClassEditor(Object arg0) {
super(arg0);
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public String getAsText() {
return ((Class)getValue()).getName();
}
public void setAsText(String className) throws IllegalArgumentException {
try {
Class clazz = ClassUtils.resolvePrimitiveClassName(className);
if (clazz != null) {
setValue(clazz);
}
else {
setValue(this.classLoader.loadClass(className));
}
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Could not load class [" + className + "]!");
}
}
}
| apache-2.0 |
xixifeng/fastquery | src/test/java/org/fastquery/test/Script2ClassTest.java | 3798 | /*
* Copyright (c) 2016-2088, fastquery.org and/or its affiliates. All rights reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information, please see http://www.fastquery.org/.
*
*/
package org.fastquery.test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.lang.reflect.Method;
import org.fastquery.asm.Script2Class;
import org.fastquery.core.Param;
import org.fastquery.util.QueryContextUtil;
import org.fastquery.where.Set;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author mei.sir@aliyun.cn
*/
public class Script2ClassTest
{
@Set("AA")
@Set(value = "BB", ignoreScript = ":age.intValue() >18 && :name!=null && :name.contains(\"Rex\")")
@Set("CC")
public void todo(@Param("age") Integer age, @Param("name") String name)
{
}
private static String processParam(String script, Method method) throws Exception
{
Method m = Script2Class.class.getDeclaredMethod("processParam", String.class, Method.class);
m.setAccessible(true);
return (String) m.invoke(null, script, method);
}
// 测试Script2Class中的私有静态方法(processParam).
@Test
public void processParam() throws Exception
{
Method method = Script2ClassTest.class.getMethod("todo", Integer.class, String.class);
String script = ":age.intValue() > 18 && :name!=null && :name.contains(\"Rex\")";
String code = processParam(script, method);
assertThat(code, equalTo("((java.lang.Integer)this.getParameter(\"age\")).intValue() > 18 && ((java.lang.String)this.getParameter(\"name\"))!=null && ((java.lang.String)this.getParameter(\"name\")).contains(\"Rex\")"));
}
@BeforeClass
public static void before() throws Exception
{
Script2Class.generate(Script2ClassTest.class);
QueryContextUtil.startQueryContext();
}
@AfterClass
public static void after() throws Exception
{
QueryContextUtil.clearQueryContext();
}
@Test
public void script1() throws Exception
{
// 给上下文 设置 method 和 参数
Method method = Script2ClassTest.class.getMethod("todo", Integer.class, String.class);
QueryContextUtil.setCurrentMethod(method);
QueryContextUtil.setCurrentArgs(17, "RexLeifeng");
boolean b = Script2Class.getJudge(1).ignore();
assertThat(b, is(false));
QueryContextUtil.setCurrentArgs(18, "RexLeifeng");
b = Script2Class.getJudge(1).ignore();
assertThat(b, is(false));
QueryContextUtil.setCurrentArgs(19, "RexLeifeng");
b = Script2Class.getJudge(1).ignore();
assertThat(b, is(true));
QueryContextUtil.setCurrentArgs(19, "Leifeng");
b = Script2Class.getJudge(1).ignore();
assertThat(b, is(false));
QueryContextUtil.setCurrentArgs(19, null);
b = Script2Class.getJudge(1).ignore();
assertThat(b, is(false));
}
}
| apache-2.0 |
SciGaP/DEPRECATED-Cipres-Airavata-POC | saminda/cipres-airavata/cipres-portal/portal2/src/main/java/org/ngbw/web/model/impl/tool/neighborValidator.java | 3166 | package org.ngbw.web.model.impl.tool;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.ngbw.sdk.api.tool.ParameterValidator;
import org.ngbw.sdk.common.util.BaseValidator;
import org.ngbw.sdk.database.TaskInputSourceDocument;
public class neighborValidator implements ParameterValidator
{
private Set<String> requiredParameters;
private Set<String> requiredInput;
public neighborValidator() {
requiredParameters = new HashSet<String>();
requiredInput = new HashSet<String>();
requiredParameters.add("distance_method_");
}
public Map<String, String> validateParameters(Map<String, String> parameters) {
Map<String, String> errors = new HashMap<String, String>();
Set<String> missingRequired = validateRequiredParameters(parameters);
for (String missing : missingRequired) {
errors.put(missing, "You must enter a value for \"" + missing + "\"");
}
for (String param : parameters.keySet()) {
String error = validate(param, parameters.get(param));
if (error != null)
errors.put(param, error);
}
return errors;
}
public Map<String, String> validateInput(Map<String, List<TaskInputSourceDocument>> input) {
Map<String, String> errors = new HashMap<String, String>();
Set<String> missingRequired = validateRequiredInput(input);
for (String missing : missingRequired) {
errors.put(missing, "You must enter a value for \"" + missing + "\"");
}
for (String param : input.keySet()) {
String error = validate(param, input.get(param));
if (error != null)
errors.put(param, error);
}
return errors;
}
public String validate(String parameter, Object value) {
if (parameter.equals("distance_method_")) {
if (BaseValidator.validateString(value) == false)
return "You must enter a value for \"" + parameter + "\"";
return null;
}
if (parameter.equals("jumble_seed_")) {
if (BaseValidator.validateInteger(value) == false)
return "\"" + parameter + "\" must be an integer.";
return null;
}
if (parameter.equals("datasets_nb_")) {
if (BaseValidator.validateInteger(value) == false)
return "\"" + parameter + "\" must be an integer.";
return null;
}
if (parameter.equals("multiple_seed_")) {
if (BaseValidator.validateInteger(value) == false)
return "\"" + parameter + "\" must be an integer.";
return null;
}
if (parameter.equals("outgroup_")) {
if (BaseValidator.validateInteger(value) == false)
return "\"" + parameter + "\" must be an integer.";
return null;
}
return null;
}
private Set<String> validateRequiredParameters(Map<String, String> parameters) {
Set<String> required = new HashSet<String>(requiredParameters.size());
required.addAll(requiredParameters);
for (String parameter : parameters.keySet()) {
if (required.contains(parameter))
required.remove(parameter);
}
return required;
}
private Set<String> validateRequiredInput(Map<String, List<TaskInputSourceDocument>> input) {
Set<String> required = new HashSet<String>(requiredInput.size());
required.addAll(requiredInput);
for (String parameter : input.keySet()) {
if (required.contains(parameter))
required.remove(parameter);
}
return required;
}
} | apache-2.0 |
ZieIony/Carbon | carbon/src/main/java/carbon/widget/OnFocusLostListener.java | 89 | package carbon.widget;
public interface OnFocusLostListener {
void onFocusLost();
}
| apache-2.0 |
mufaddalq/cloudstack-datera-driver | core/src/com/cloud/agent/api/ClusterSyncCommand.java | 1349 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.agent.api;
public class ClusterSyncCommand extends Command implements CronCommand {
int _interval;
long _clusterId;
public ClusterSyncCommand() {
}
public ClusterSyncCommand(int interval, long clusterId){
_interval = interval;
_clusterId = clusterId;
}
@Override
public int getInterval() {
return _interval;
}
public long getClusterId() {
return _clusterId;
}
@Override
public boolean executeInSequence() {
return false;
}
}
| apache-2.0 |
lventu/ytd2 | src/zsk/UTF8.java | 10050 | package zsk;
import java.util.HashMap;
import java.util.Map;
public abstract class UTF8 {
protected static HashMap<String, String> charmap;
public static String changeHTMLtoUTF8(String stringtochange) {
String ssource = stringtochange; // to avoid javac warning about parameter assignment
UTF8.charmap = new HashMap<String, String>();
// fill hasmap
charmap.put(" "," ");
charmap.put(" "," ");
charmap.put(" "," ");
charmap.put("!","!");
charmap.put(""","\"");
charmap.put(""","\"");
charmap.put("#","#");
charmap.put("$","$");
charmap.put("%","%");
charmap.put("&","&");
charmap.put("'","'");
charmap.put("(","(");
charmap.put(")",")");
charmap.put("*","*");
charmap.put("+","+");
charmap.put(",",",");
charmap.put("-","-");
charmap.put(".",".");
charmap.put("/","/");
charmap.put("0","0");
charmap.put("1","1");
charmap.put("2","2");
charmap.put("3","3");
charmap.put("4","4");
charmap.put("5","5");
charmap.put("6","6");
charmap.put("7","7");
charmap.put("8","8");
charmap.put("9","9");
charmap.put(":",":");
charmap.put(";",";");
charmap.put("<","<");
charmap.put("<","<");
charmap.put("=","=");
charmap.put(">",">");
charmap.put(">",">");
charmap.put("?","?");
charmap.put("@","@");
charmap.put("A","A");
charmap.put("B","B");
charmap.put("C","C");
charmap.put("D","D");
charmap.put("E","E");
charmap.put("F","F");
charmap.put("G","G");
charmap.put("H","H");
charmap.put("I","I");
charmap.put("J","J");
charmap.put("K","K");
charmap.put("L","L");
charmap.put("M","M");
charmap.put("N","N");
charmap.put("O","O");
charmap.put("P","P");
charmap.put("Q","Q");
charmap.put("R","R");
charmap.put("S","S");
charmap.put("T","T");
charmap.put("U","U");
charmap.put("V","V");
charmap.put("W","W");
charmap.put("X","X");
charmap.put("Y","Y");
charmap.put("Z","Z");
charmap.put("[","[");
charmap.put("\","\\");
charmap.put("]","]");
charmap.put("^","^");
charmap.put("_","_");
charmap.put("`","`");
charmap.put("a","a");
charmap.put("b","b");
charmap.put("c","c");
charmap.put("d","d");
charmap.put("e","e");
charmap.put("f","f");
charmap.put("g","g");
charmap.put("h","h");
charmap.put("i","i");
charmap.put("j","j");
charmap.put("k","k");
charmap.put("l","l");
charmap.put("m","m");
charmap.put("n","n");
charmap.put("o","o");
charmap.put("p","p");
charmap.put("q","q");
charmap.put("r","r");
charmap.put("s","s");
charmap.put("t","t");
charmap.put("u","u");
charmap.put("v","v");
charmap.put("w","w");
charmap.put("x","x");
charmap.put("y","y");
charmap.put("z","z");
charmap.put("{","{");
charmap.put("|","|");
charmap.put("}","}");
charmap.put("~","~");
charmap.put("¡","¡");
charmap.put("¡","¡");
charmap.put("¢","¢");
charmap.put("¢","¢");
charmap.put("£","£");
charmap.put("£","£");
charmap.put("¤","¤");
charmap.put("¤","¤");
charmap.put("¥","¥");
charmap.put("¥","¥");
charmap.put("¦","¦");
charmap.put("¦","¦");
charmap.put("§","§");
charmap.put("§","§");
charmap.put("¨","¨");
charmap.put("¨","¨");
charmap.put("©","©");
charmap.put("©","©");
charmap.put("ª","ª");
charmap.put("ª","ª");
charmap.put("«","«");
charmap.put("«","«");
charmap.put("¬","¬");
charmap.put("¬","¬");
charmap.put("­","");
charmap.put("­","");
charmap.put("®","®");
charmap.put("®","®");
charmap.put("¯","¯");
charmap.put("¯","¯");
charmap.put("°","°");
charmap.put("°","°");
charmap.put("±","±");
charmap.put("±","±");
charmap.put("²","²");
charmap.put("²","²");
charmap.put("³","³");
charmap.put("³","³");
charmap.put("´","´");
charmap.put("´","´");
charmap.put("µ","µ");
charmap.put("µ","µ");
charmap.put("¶","¶");
charmap.put("¶","¶");
charmap.put("·","·");
charmap.put("·","·");
charmap.put("¸","¸");
charmap.put("¸","¸");
charmap.put("¹","¹");
charmap.put("¹","¹");
charmap.put("º","º");
charmap.put("º","º");
charmap.put("»","»");
charmap.put("»","»");
charmap.put("¼","¼");
charmap.put("¼","¼");
charmap.put("½","½");
charmap.put("½","½");
charmap.put("¾","¾");
charmap.put("¾","¾");
charmap.put("¿","¿");
charmap.put("¿","¿");
charmap.put("À","À");
charmap.put("À","À");
charmap.put("Á","Á");
charmap.put("Á","Á");
charmap.put("Â","Â");
charmap.put("Â","Â");
charmap.put("Ã","Ã");
charmap.put("Ã","Ã");
charmap.put("Ä","Ä");
charmap.put("Ä","Ä");
charmap.put("Å","Å");
charmap.put("Å","Å");
charmap.put("Æ","Æ");
charmap.put("Æ","Æ");
charmap.put("Ç","Ç");
charmap.put("Ç","Ç");
charmap.put("È","È");
charmap.put("È","È");
charmap.put("É","É");
charmap.put("É","É");
charmap.put("Ê","Ê");
charmap.put("Ê","Ê");
charmap.put("Ë","Ë");
charmap.put("Ë","Ë");
charmap.put("Ì","Ì");
charmap.put("Ì","Ì");
charmap.put("Í","Í");
charmap.put("Í","Í");
charmap.put("Î","Î");
charmap.put("Î","Î");
charmap.put("Ï","Ï");
charmap.put("Ï","Ï");
charmap.put("Ð","Ð");
charmap.put("Ð","Ð");
charmap.put("Ñ","Ñ");
charmap.put("Ñ","Ñ");
charmap.put("Ò","Ò");
charmap.put("Ò","Ò");
charmap.put("Ó","Ó");
charmap.put("Ó","Ó");
charmap.put("Ô","Ô");
charmap.put("Ô","Ô");
charmap.put("Õ","Õ");
charmap.put("Õ","Õ");
charmap.put("Ö","Ö");
charmap.put("Ö","Ö");
charmap.put("×","×");
charmap.put("×","×");
charmap.put("Ø","Ø");
charmap.put("Ø","Ø");
charmap.put("Ù","Ù");
charmap.put("Ù","Ù");
charmap.put("Ú","Ú");
charmap.put("Ú","Ú");
charmap.put("Û","Û");
charmap.put("Û","Û");
charmap.put("Ü","Ü");
charmap.put("Ü","Ü");
charmap.put("Ý","Ý");
charmap.put("Ý","Ý");
charmap.put("Þ","Þ");
charmap.put("Þ","Þ");
charmap.put("ß","ß");
charmap.put("ß","ß");
charmap.put("à","à");
charmap.put("à","à");
charmap.put("á","á");
charmap.put("á","á");
charmap.put("â","â");
charmap.put("â","â");
charmap.put("ã","ã");
charmap.put("ã","ã");
charmap.put("ä","ä");
charmap.put("ä","ä");
charmap.put("å","å");
charmap.put("å","å");
charmap.put("æ","æ");
charmap.put("æ","æ");
charmap.put("ç","ç");
charmap.put("ç","ç");
charmap.put("è","è");
charmap.put("è","è");
charmap.put("é","é");
charmap.put("é","é");
charmap.put("ê","ê");
charmap.put("ê","ê");
charmap.put("ë","ë");
charmap.put("ë","ë");
charmap.put("ì","ì");
charmap.put("ì","ì");
charmap.put("í","í");
charmap.put("í","í");
charmap.put("î","î");
charmap.put("î","î");
charmap.put("ï","ï");
charmap.put("ï","ï");
charmap.put("ð","ð");
charmap.put("ð","ð");
charmap.put("ñ","ñ");
charmap.put("ñ","ñ");
charmap.put("ò","ò");
charmap.put("ò","ò");
charmap.put("ó","ó");
charmap.put("ó","ó");
charmap.put("ô","ô");
charmap.put("ô","ô");
charmap.put("õ","õ");
charmap.put("õ","õ");
charmap.put("ö","ö");
charmap.put("ö","ö");
charmap.put("÷","÷");
charmap.put("÷","÷");
charmap.put("ø","ø");
charmap.put("ø","ø");
charmap.put("ù","ù");
charmap.put("ù","ù");
charmap.put("ú","ú");
charmap.put("ú","ú");
charmap.put("û","û");
charmap.put("û","û");
charmap.put("ü","ü");
charmap.put("ü","ü");
charmap.put("ý","ý");
charmap.put("ý","ý");
charmap.put("þ","þ");
charmap.put("þ","þ");
charmap.put("ÿ","ÿ");
charmap.put("ÿ","ÿ");
charmap.put("Œ","Œ");
charmap.put("œ","œ");
charmap.put("Š","Š");
charmap.put("š","š");
charmap.put("Ÿ","Ÿ");
charmap.put("ƒ","ƒ");
charmap.put("–","–");
charmap.put("—","—");
charmap.put("‘","‘");
charmap.put("’","’");
charmap.put("‚","‚");
charmap.put("“","“");
charmap.put("”","”");
charmap.put("„","„");
charmap.put("†","†");
charmap.put("‡","‡");
charmap.put("•","•");
charmap.put("…","…");
charmap.put("‰","‰");
charmap.put("€","€");
charmap.put("€","€");
charmap.put("™","™");
// replace all occurrences of all keys to their value
for (Map.Entry<String, String> entry : charmap.entrySet()) {
ssource = ssource.replaceAll(entry.getKey(), entry.getValue());
}
return(ssource);
}; // UTF8
} // class UTF8
| apache-2.0 |
xloye/tddl5 | tddl-executor/src/main/java/com/taobao/tddl/executor/rowset/AbstractRowSet.java | 5953 | package com.taobao.tddl.executor.rowset;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import com.taobao.tddl.executor.cursor.ICursorMeta;
import com.taobao.tddl.optimizer.config.table.ColumnMeta;
import com.taobao.tddl.optimizer.core.datatype.DataType;
/**
* @author mengshi.sunmengshi 2013-12-3 上午11:06:04
* @since 5.0.0
*/
public abstract class AbstractRowSet implements IRowSet {
private final ICursorMeta iCursorMeta;
public AbstractRowSet(ICursorMeta iCursorMeta){
super();
this.iCursorMeta = iCursorMeta;
}
@Override
public ICursorMeta getParentCursorMeta() {
return iCursorMeta;
}
@Override
public Integer getInteger(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.IntegerType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setInteger(int index, Integer value) {
setObject(index, value);
}
@Override
public Long getLong(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.LongType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setLong(int index, Long value) {
setObject(index, value);
}
@Override
public String getString(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.StringType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setString(int index, String str) {
setObject(index, str);
}
@Override
public Boolean getBoolean(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.BooleanType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setBoolean(int index, Boolean bool) {
setObject(index, bool);
}
@Override
public Short getShort(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.ShortType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setShort(int index, Short shortval) {
setObject(index, shortval);
}
@Override
public Float getFloat(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.FloatType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setFloat(int index, Float fl) {
setObject(index, fl);
}
@Override
public Double getDouble(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.DoubleType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setDouble(int index, Double doub) {
setObject(index, doub);
}
@Override
public byte[] getBytes(int index) {
// ColumnMeta cm = iCursorMeta.getColumnMeta(index);
iCursorMeta.getColumnMeta(index);
Object o = this.getObject(index);
if (o == null) {
return null;
}
String str = DataType.StringType.convertFrom(o);
return str.getBytes();
}
@Override
public void setBytes(int index, byte[] bytes) {
setObject(index, bytes);
}
@Override
public Date getDate(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.DateType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setDate(int index, Date date) {
setObject(index, date);
}
@Override
public Timestamp getTimestamp(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.TimestampType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setTimestamp(int index, Timestamp timestamp) {
setObject(index, timestamp);
}
@Override
public Time getTime(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.TimeType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setTime(int index, Time time) {
setObject(index, time);
}
@Override
public BigDecimal getBigDecimal(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.BigDecimalType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setBigDecimal(int index, BigDecimal bigDecimal) {
setObject(index, bigDecimal);
}
@Override
public List<byte[]> getBytes() {
List<byte[]> res = new ArrayList<byte[]>();
for (int i = 0; i < getParentCursorMeta().getColumns().size(); i++) {
res.add(this.getBytes(i));
}
return res;
}
@Override
public Byte getByte(int index) {
ColumnMeta cm = iCursorMeta.getColumnMeta(index);
return DataType.ByteType.convertFrom(cm.getDataType().getResultGetter().get(this, index));
}
@Override
public void setByte(int index, Byte b) {
setObject(index, b);
}
@Override
public List<Object> getValues() {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
List<Object> values = this.getValues();
for (ColumnMeta cm : this.getParentCursorMeta().getColumns()) {
int index = this.getParentCursorMeta().getIndex(cm.getTableName(), cm.getName(), cm.getAlias());
sb.append(cm.getName() + ":" + values.get(index) + " ");
}
return sb.toString();
}
}
| apache-2.0 |
willr3/activemq-artemis | artemis-server/src/main/java/org/apache/activemq/artemis/core/postoffice/PostOffice.java | 5499 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.core.postoffice;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.server.ActiveMQComponent;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.core.server.RoutingContext;
import org.apache.activemq.artemis.core.server.RoutingType;
import org.apache.activemq.artemis.core.server.ServerMessage;
import org.apache.activemq.artemis.core.server.impl.AddressInfo;
import org.apache.activemq.artemis.core.transaction.Transaction;
/**
* A PostOffice instance maintains a mapping of a String address to a Queue. Multiple Queue instances can be bound
* with the same String address.
*
* Given a message and an address a PostOffice instance will route that message to all the Queue instances that are
* registered with that address.
*
* Addresses can be any String instance.
*
* A Queue instance can only be bound against a single address in the post office.
*/
public interface PostOffice extends ActiveMQComponent {
/**
* @param addressInfo
* @return true if the address was added, false if it wasn't added
*/
boolean addAddressInfo(AddressInfo addressInfo);
AddressInfo removeAddressInfo(SimpleString address) throws Exception;
AddressInfo getAddressInfo(SimpleString address);
AddressInfo updateAddressInfo(SimpleString addressName, Collection<RoutingType> routingTypes) throws Exception;
QueueBinding updateQueue(SimpleString name,
RoutingType routingType,
Integer maxConsumers,
Boolean purgeOnNoConsumers) throws Exception;
List<Queue> listQueuesForAddress(SimpleString address) throws Exception;
void addBinding(Binding binding) throws Exception;
Binding removeBinding(SimpleString uniqueName, Transaction tx, boolean deleteData) throws Exception;
/**
* It will lookup the Binding without creating an item on the Queue if non-existent
*
* @param address
* @throws Exception
*/
Bindings lookupBindingsForAddress(SimpleString address) throws Exception;
/**
* Differently to lookupBindings, this will always create a new element on the Queue if non-existent
*
* @param address
* @throws Exception
*/
Bindings getBindingsForAddress(SimpleString address) throws Exception;
Binding getBinding(SimpleString uniqueName);
Bindings getMatchingBindings(SimpleString address) throws Exception;
Map<SimpleString, Binding> getAllBindings();
SimpleString getMatchingQueue(SimpleString address, RoutingType routingType) throws Exception;
SimpleString getMatchingQueue(SimpleString address, SimpleString queueName, RoutingType routingType) throws Exception;
RoutingStatus route(ServerMessage message, boolean direct) throws Exception;
RoutingStatus route(ServerMessage message,
Transaction tx,
boolean direct) throws Exception;
RoutingStatus route(ServerMessage message,
Transaction tx,
boolean direct,
boolean rejectDuplicates) throws Exception;
RoutingStatus route(ServerMessage message,
RoutingContext context,
boolean direct) throws Exception;
RoutingStatus route(ServerMessage message,
RoutingContext context,
boolean direct,
boolean rejectDuplicates) throws Exception;
MessageReference reroute(ServerMessage message, Queue queue, Transaction tx) throws Exception;
Pair<RoutingContext, ServerMessage> redistribute(ServerMessage message,
final Queue originatingQueue,
Transaction tx) throws Exception;
void processRoute(final ServerMessage message, final RoutingContext context, final boolean direct) throws Exception;
DuplicateIDCache getDuplicateIDCache(SimpleString address);
void sendQueueInfoToQueue(SimpleString queueName, SimpleString address) throws Exception;
Object getNotificationLock();
// we can't start expiry scanner until the system is load otherwise we may get weird races - https://issues.jboss.org/browse/HORNETQ-1142
void startExpiryScanner();
boolean isAddressBound(final SimpleString address) throws Exception;
Set<SimpleString> getAddresses();
}
| apache-2.0 |
Edwin-Ran/es_source_read | src/main/java/org/elasticsearch/action/search/type/TransportSearchQueryAndFetchAction.java | 4863 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.search.type;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.search.ReduceSearchPhaseException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.search.action.SearchServiceListener;
import org.elasticsearch.search.action.SearchServiceTransportAction;
import org.elasticsearch.search.controller.SearchPhaseController;
import org.elasticsearch.search.fetch.QueryFetchSearchResult;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.search.internal.ShardSearchTransportRequest;
import org.elasticsearch.threadpool.ThreadPool;
import static org.elasticsearch.action.search.type.TransportSearchHelper.buildScrollId;
/**
*
*/
public class TransportSearchQueryAndFetchAction extends TransportSearchTypeAction {
@Inject
public TransportSearchQueryAndFetchAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController, ActionFilters actionFilters) {
super(settings, threadPool, clusterService, searchService, searchPhaseController, actionFilters);
}
@Override
protected void doExecute(SearchRequest searchRequest, ActionListener<SearchResponse> listener) {
new AsyncAction(searchRequest, listener).start();
}
private class AsyncAction extends BaseAsyncAction<QueryFetchSearchResult> {
private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
super(request, listener);
}
@Override
protected String firstPhaseName() {
return "query_fetch";
}
@Override
protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchTransportRequest request, SearchServiceListener<QueryFetchSearchResult> listener) {
searchService.sendExecuteFetch(node, request, listener);
}
@Override
protected void moveToSecondPhase() throws Exception {
try {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
try {
boolean useScroll = !useSlowScroll && request.scroll() != null;
sortedShardList = searchPhaseController.sortDocs(useScroll, firstResults);
final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, firstResults, firstResults);
String scrollId = null;
if (request.scroll() != null) {
scrollId = buildScrollId(request.searchType(), firstResults, null);
}
listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successfulOps.get(), buildTookInMillis(), buildShardFailures()));
} catch (Throwable e) {
ReduceSearchPhaseException failure = new ReduceSearchPhaseException("merge", "", e, buildShardFailures());
if (logger.isDebugEnabled()) {
logger.debug("failed to reduce search", failure);
}
listener.onFailure(failure);
}
}
});
} catch (EsRejectedExecutionException ex) {
listener.onFailure(ex);
}
}
}
}
| apache-2.0 |
vtomanov/BTCDB | com/tomanov/TempBalanceProvider.java | 989 | package com.tomanov;
/**
* USE OF THIS SOFTWARE IS GOVERNED BY THE TERMS AND CONDITIONS
* OF THE LICENSE STATEMENT AND LIMITED WARRANTY FURNISHED WITH
* THE PRODUCT.
* <p/>
* IN PARTICULAR, YOU WILL INDEMNIFY AND HOLD ITS AUTHOR, ITS
* RELATED ENTITIES AND ITS SUPPLIERS, HARMLESS FROM AND AGAINST ANY
* CLAIMS OR LIABILITIES ARISING OUT OF THE USE, REPRODUCTION, OR
* DISTRIBUTION OF YOUR PROGRAMS, INCLUDING ANY CLAIMS OR LIABILITIES
* ARISING OUT OF OR RESULTING FROM THE USE, MODIFICATION, OR
* DISTRIBUTION OF PROGRAMS OR FILES CREATED FROM, BASED ON, AND/OR
* DERIVED FROM THIS SOURCE CODE FILE.
*/
interface TempBalanceProvider
{
void write(byte[] bytes) throws Exception;
void read(byte[] bytes) throws Exception;
long readLong() throws Exception;
void seek(long position) throws Exception;
void closeWriter() throws Exception;
void closeReader() throws Exception;
long length() throws Exception;
}
| apache-2.0 |
wubin001/todo | app/src/main/java/com/nico/todo/ui/mall/MallContract.java | 298 | package com.nico.todo.ui.mall;
import com.nico.todo.base.BasePresenter;
import com.nico.todo.base.BaseView;
/**
* Created by wubin on 2016/8/8.
*/
public interface MallContract {
interface View extends BaseView<Presenter> {
}
interface Presenter extends BasePresenter{
}
}
| apache-2.0 |
VHAINNOVATIONS/Telepathology | Source/Java/BaseWebFacade/main/src/java/gov/va/med/imaging/exchange/business/taglib/artifactsource/ArtifactSourceTagUtility.java | 1232 | /**
*
*/
package gov.va.med.imaging.exchange.business.taglib.artifactsource;
import gov.va.med.imaging.artifactsource.ArtifactSource;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
/**
* @author vhaiswbeckec
*
*/
public class ArtifactSourceTagUtility
{
/**
*
* @param subject
* @return
*/
protected static AbstractArtifactSourceTag getParentArtifactSourceTag(Tag subject)
{
return (AbstractArtifactSourceTag)TagSupport.findAncestorWithClass(subject, AbstractArtifactSourceTag.class);
}
/**
*
* @return
* @throws JspException
*/
protected static ArtifactSource getArtifactSource(Tag subject)
throws JspException
{
AbstractArtifactSourceTag artifactSourceTag = ArtifactSourceTagUtility.getParentArtifactSourceTag(subject);
if(artifactSourceTag == null)
throw new JspException("An ArtifactSourceProperty tag does not have an ancestor ArtifactSource tag.");
ArtifactSource artifactSource = artifactSourceTag.getArtifactSource();
if(artifactSource == null)
throw new JspException("An ArtifactSourceProperty tag was unable to get the ArtifactSource from its parent tag.");
return artifactSource;
}
}
| apache-2.0 |
hopestar720/aioweb | src/com/xhsoft/framework/common/page/Page.java | 1754 | /*
* $RCSfile: Page,v $$
* $Revision: 1.0 $
* $Date: 2012-12-28 $
*
* Copyright (C) 2011 GyTech, Inc. All rights reserved.
*
* This software is the proprietary information of GyTech, Inc.
* Use is subject to license terms.
*/
package com.xhsoft.framework.common.page;
import java.util.List;
/**
* <p>Title:Page</p>
* <p>Description:分布</p>
* <p>Copyright:Copyright (C) 2011</p>
* @author wenzhi
* @date 2011-12-28
*/
public class Page<T>
{
public static final String PAGE_NO="qm.pn";
public static final String PAGE_LIMIT="qm.limit";
/** 一页显示的记录数*/
private int limit = 10;
/** 记录总数*/
private int totalRows;
/** 当前页码*/
private int pageNo;
/** 总页数*/
private int totalPages;
/** 结果集存放List*/
private List<T> resultList;
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public List<T> getResultList() {
return resultList;
}
public void setResultList(List<T> resultList) {
this.resultList = resultList;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
/** 计算总页数*/
public int getTotalPages() {
return totalPages;
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public int getOffset() {
return (pageNo - 1) * limit;
}
/**
* <p>Description:getEndIndex</p>
* @return int
* @author wenzhi
* @version 1.0
*/
public int getEndIndex()
{
if (getOffset() + limit > totalRows) {
return totalRows;
} else {
return getOffset() + limit;
}
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
}
| apache-2.0 |
Gilandel/utils-commons | src/main/java/fr/landel/utils/commons/StringUtils.java | 48107 | /*
* #%L
* utils-commons
* %%
* Copyright (C) 2016 - 2018 Gilles Landel
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package fr.landel.utils.commons;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import java.util.function.Function;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.tuple.Pair;
/**
* Utility class to manage strings.
*
* @since Nov 27, 2015
* @author Gilles Landel
*
*/
public final class StringUtils extends StringFormatUtils {
/**
* The comma separator to join (for readability)
*/
public static final String SEPARATOR_COMMA = ", ";
/**
* The semicolon separator to join (for readability)
*/
public static final String SEPARATOR_SEMICOLON = "; ";
/**
* The equal separator to join (for readability)
*/
public static final String SEPARATOR_EQUAL = " = ";
private static final String BRACE_OPEN = "{";
private static final String BRACE_CLOSE = "}";
private static final String DOLLAR_BRACE_OPEN = "${";
private static final String BRACE_OPEN_EXCLUDE = "{{";
private static final String BRACE_CLOSE_EXCLUDE = "}}";
private static final String DOLLAR_BRACE_OPEN_EXCLUDE = "${{";
private static final String BRACES = "{}";
private static final String BRACE_OPEN_TMP = "[#STR_UT_TMP#[";
private static final String BRACE_CLOSE_TMP = "]#STR_UT_TMP#]";
private static final String TEMP_REPLACEMENT = "___ST_REPLACEMENT___";
public static final Pair<String, String> INCLUDE_CURLY_BRACES = Pair.of(BRACE_OPEN, BRACE_CLOSE);
public static final Pair<String, String> EXCLUDE_CURLY_BRACES = Pair.of(BRACE_OPEN_EXCLUDE, BRACE_CLOSE_EXCLUDE);
public static final Pair<String, String> INCLUDE_DOLLAR_CURLY_BRACES = Pair.of(DOLLAR_BRACE_OPEN, BRACE_CLOSE);
public static final Pair<String, String> EXCLUDE_DOLLAR_CURLY_BRACES = Pair.of(DOLLAR_BRACE_OPEN_EXCLUDE, BRACE_CLOSE_EXCLUDE);
private static final int ENSURE_CAPACITY = 16;
private static final int BUFFER_CAPACITY = 64;
private static final char[] NULL_CHARS = {'n', 'u', 'l', 'l'};
private static final Function<String, String> PARAM_NULL = p -> "Parameter '".concat(p).concat("' cannot be null");
private static final String ERROR_SEQUENCE = PARAM_NULL.apply("sequence");
private static final String ERROR_OBJECTS = PARAM_NULL.apply("objects");
private static final String ERROR_PREFIX = PARAM_NULL.apply("prefix");
private static final String ERROR_SUFFIX = PARAM_NULL.apply("suffix");
/**
* Hidden constructor.
*/
private StringUtils() {
throw new UnsupportedOperationException();
}
/**
* Get the char sequence if not empty and null otherwise.
*
* @param cs
* The CharSequence to check, may be null
* @param <C>
* Type of the char sequence
* @return a char sequence or null
*/
public static <C extends CharSequence> C nullIfEmpty(final C cs) {
if (isNotEmpty(cs)) {
return cs;
}
return null;
}
/**
* Get the char sequence if not null and not empty and the default one
* otherwise.
*
* @param cs
* The CharSequence to check, may be null
* @param defaultCS
* The default char sequence
* @param <C>
* Type of the char sequence
* @return a char sequence
*/
public static <C extends CharSequence> C defaultIfEmpty(final C cs, final C defaultCS) {
if (isNotEmpty(cs)) {
return cs;
}
return defaultCS;
}
/**
* Get the char sequence if not null and the default one otherwise.
*
* @param cs
* The CharSequence to check, may be null
* @param defaultCS
* The default char sequence
* @param <C>
* Type of the char sequence
* @return a char sequence
*/
public static <C extends CharSequence> C defaultIfNull(final C cs, final C defaultCS) {
if (cs != null) {
return cs;
}
return defaultCS;
}
/**
* Get the toString if not null and the default one otherwise.
*
* @param obj
* The object to check, may be null
* @param defaultStr
* The default string
* @return a string
*/
public static String toStringOrDefaultIfNull(final Object obj, final String defaultStr) {
if (obj != null) {
return obj.toString();
}
return defaultStr;
}
/**
* Get the string part between the separator at the index position. The
* index starts from the left at 0, or at -1 from the right. If the index is
* over the number of split parts, the method returns an empty string.
*
* <pre>
* StringUtils.substring("test1::test2:test3::test4", "::", 0) => "test1"
* StringUtils.substring("test1::test2:test3::test4", "::", 1) => "test2:test3"
* StringUtils.substring("test1::test2:test3::test4", "::", 2) => "test4"
* StringUtils.substring("test1::test2:test3::test4", "::", -1) => "test4"
* StringUtils.substring("test1::test2:test3::test4", "::", -2) => "test2:test3"
* StringUtils.substring("test1::test2:test3::test4", "::", -3) => "test1"
* StringUtils.substring("test1::test2:test3::test4", "::", 100) => ""
* StringUtils.substring("test1::test2:test3::test4", "::", -100) => ""
* </pre>
*
* @param str
* The input string
* @param separator
* The string separator
* @param index
* The index position
* @return The sub-string
*/
public static String substring(final String str, final String separator, final int index) {
if (index > -1) {
return substring(str, separator, index, index + 1);
} else {
return substring(str, separator, index, index - 1);
}
}
/**
* Get the string part between the separator at the index position. The
* index starts from the left at 0, or at -1 from the right. If the from
* index is over the number of split parts, the method returns an empty
* string (the to index isn't checked).
*
* <pre>
* StringUtils.substring("test1::test2:test3::test4", "::", 0, 1); // => "test1""
* StringUtils.substring("test1::test2:test3::test4", "::", 1, 2); // => "test2:test3""
* StringUtils.substring("test1::test2:test3::test4", "::", 1, 3); // => "test2:test3::test4""
* StringUtils.substring("test1::test2:test3::test4", "::", 1, 100); // => "test2:test3::test4""
* StringUtils.substring("test1::test2:test3::test4", "::", -1, -2); // => "test4"
* StringUtils.substring("test1::test2:test3::test4", "::", -2, -3); // => "test2:test3"
* StringUtils.substring("test1::test2:test3::test4", "::", 0, -2); // => "test1"
* StringUtils.substring("test1::test2:test3::test4", "::", -3, 0); / => IllegalArgumentException, from=1, to=0
* StringUtils.substring("test1::test2:test3::test4", "::", 0, 0); // => IllegalArgumentException, from=to
* StringUtils.substring("test1::test2:test3::test4", "::", 0, -3); // => IllegalArgumentException, from=0, to=0
* </pre>
*
* @param str
* The input string
* @param separator
* The string separator
* @param from
* The from index position (inclusive)
* @param to
* The to index position (exclusive)
* @return The sub-string
*/
public static String substring(final String str, final String separator, final int from, final int to) {
if (isNotEmpty(str)) {
if (from == to) {
throw new IllegalArgumentException("The 'from' index is equal to 'to' index");
}
final List<String> strs = splitAsList(str, separator);
final int size = strs.size();
if (from >= size || (from < 0 && Math.abs(from) - 1 >= size)) {
return "";
} else {
final StringBuilder stringBuilder = new StringBuilder();
int end;
int start;
if (from > -1) {
start = from;
if (to > -1) {
end = to;
} else if (size + to > start) {
end = size + to;
} else {
throw new IllegalArgumentException("The 'to' index is invalid");
}
} else if (to > -1) {
start = size + from + 1;
end = to;
} else if (to < from) {
if (size + to + 1 < 0) {
start = 0;
} else {
start = size + to + 1;
}
end = size + from + 1;
} else {
throw new IllegalArgumentException("The 'to' index is invalid");
}
if (start >= end) {
throw new IllegalArgumentException("The 'from' and 'to' indexes are invalid");
}
for (int i = start; i < end && i < size; i++) {
stringBuilder.append(strs.get(i));
if (i < end - 1 && i < size - 1) {
stringBuilder.append(separator);
}
}
return stringBuilder.toString();
}
}
return str;
}
private static List<String> splitAsList(final String str, final String separator) {
int pos = 0;
int pPos = 0;
final int separatorLength = separator.length();
final List<String> strs = new ArrayList<>();
while ((pos = str.indexOf(separator, pPos)) > -1) {
strs.add(str.substring(pPos, pos));
pPos = pos + separatorLength;
}
strs.add(str.substring(pPos, str.length()));
return strs;
}
/**
* Replace the part of a string between two bounds
*
* <pre>
* StringUtils.replace("I'll go to the beach this afternoon.", "theater", 15, 20)
* // => "I'll go to the theater this afternoon."
* </pre>
*
* @param string
* The input string
* @param replacement
* The replacement string
* @param start
* The start position (exclusive)
* @param end
* The end position (inclusive)
* @return The new string
* @throws IllegalArgumentException
* If input string is null or empty. If replacement string is
* null. If the start is lower than 0. If the start is lower
* than the end. If the end is greater than the string length.
*/
public static String replace(final String string, final String replacement, final int start, final int end) {
if (isEmpty(string)) {
throw new IllegalArgumentException("The input string cannot be empty");
} else if (replacement == null) {
throw new IllegalArgumentException("The replacement string cannot be null");
} else if (start < 0) {
throw new IllegalArgumentException("The start parameter must be greated than or equal to 0");
} else if (end > string.length()) {
throw new IllegalArgumentException("The end parameter must be lower than or equal to the length of string");
} else if (start >= end) {
throw new IllegalArgumentException("The start parameter must be lower than the end");
}
String part1 = "";
if (start > 0) {
part1 = string.substring(0, start);
}
String part2 = "";
if (end < string.length()) {
part2 = string.substring(end);
}
return part1 + replacement + part2;
}
/**
* Converts the char sequence in char array. For {@link String}, you should
* use {@link String#toCharArray()}.
*
* @param sequence
* the input sequence
* @return the array
*/
public static char[] toChars(final CharSequence sequence) {
Objects.requireNonNull(sequence, ERROR_SEQUENCE);
final int length = sequence.length();
char[] chars = new char[length];
for (int i = 0; i < length; i++) {
chars[i] = sequence.charAt(i);
}
return chars;
}
/**
* Replaces single quotes by double quotes.
*
* @param str
* The input {@link String}
* @return the new sequence
*/
public static String replaceQuotes(final String str) {
return replaceChars(str, '\'', '\"');
}
/**
* <p>
* Joins the elements of the provided iterable into a single String
* containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. A {@code null} separator
* is the same as an empty String (""). The formatter if provided should
* support {@code null} value. By default the formatter used the function
* {@link String#valueOf}.
* </p>
*
* <pre>
* StringUtils.join(null, *, *) = null
* StringUtils.join([], *, *) = ""
* StringUtils.join([null], *, null) = "null"
* StringUtils.join(["a", "b", "c"], "--", null) = "a--b--c"
* StringUtils.join(["a", "b", "c"], null, StringUtils::upperCase) = "ABC"
* StringUtils.join(["a", "b", "c"], "", StringUtils::upperCase) = "ABC"
* StringUtils.join([null, "", "a"], ",", StringUtils::upperCase) = ",,A"
* </pre>
*
* @param iterable
* the {@link Iterable} providing the values to join together,
* may be null
* @param separator
* the separator character to use, null treated as ""
* @param formatter
* the formatter to stringify each element, null treated as
* {@link String#valueOf}
* @param <T>
* the type of iterable element
* @return the joined String, {@code null} if null array input.
*/
public static <T> String join(final Iterable<T> iterable, final String separator, final Function<T, String> formatter) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator, formatter);
}
/**
* <p>
* Joins the elements of the provided iterator into a single String
* containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. A {@code null} separator
* is the same as an empty String (""). The formatter if provided should
* support {@code null} value. By default the formatter used the function
* {@link String#valueOf}.
* </p>
*
* <pre>
* StringUtils.join(null, *, *) = null
* StringUtils.join([], *, *) = ""
* StringUtils.join([null], *, null) = "null"
* StringUtils.join(["a", "b", "c"], "--", null) = "a--b--c"
* StringUtils.join(["a", "b", "c"], null, StringUtils::upperCase) = "ABC"
* StringUtils.join(["a", "b", "c"], "", StringUtils::upperCase) = "ABC"
* StringUtils.join([null, "", "a"], ",", StringUtils::upperCase) = ",,A"
* </pre>
*
* @param iterator
* the {@link Iterator} providing the values to join together,
* may be null
* @param separator
* the separator character to use, null treated as ""
* @param formatter
* the formatter to stringify each element, null treated as
* {@link String#valueOf}
* @param <T>
* the type of iterator element
* @return the joined String, {@code null} if null array input.
*/
public static <T> String join(final Iterator<T> iterator, final String separator, final Function<T, String> formatter) {
if (iterator == null) {
return null;
}
final String sep = ObjectUtils.defaultIfNull(separator, EMPTY);
final Function<T, String> frmt = ObjectUtils.defaultIfNull(formatter, String::valueOf);
final StringBuilder buf = new StringBuilder();
while (iterator.hasNext()) {
if (buf.length() > 0) {
buf.append(sep);
}
buf.append(frmt.apply(iterator.next()));
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing
* the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. A {@code null} separator
* is the same as an empty String (""). The formatter if provided should
* support {@code null} value. By default the formatter used the function
* {@link String#valueOf}.
* </p>
*
* <pre>
* StringUtils.join(null, *, *) = null
* StringUtils.join([], *, *) = ""
* StringUtils.join([null], *, null) = "null"
* StringUtils.join(["a", "b", "c"], "--", null) = "a--b--c"
* StringUtils.join(["a", "b", "c"], null, StringUtils::upperCase) = "ABC"
* StringUtils.join(["a", "b", "c"], "", StringUtils::upperCase) = "ABC"
* StringUtils.join([null, "", "a"], ",", StringUtils::upperCase) = ",,A"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use, null treated as ""
* @param formatter
* the formatter to stringify each element, null treated as
* {@link String#valueOf}
* @param <T>
* the type of array element
* @return the joined String, {@code null} if null array input.
*/
public static <T> String join(final T[] array, final String separator, final Function<T, String> formatter) {
return join(array, separator, 0, array == null ? 0 : array.length, formatter);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing
* the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. A {@code null} separator
* is the same as an empty String (""). The formatter if provided should
* support {@code null} value. By default the formatter used the function
* {@link String#valueOf}.
* </p>
*
* <pre>
* StringUtils.join(null, *, *, *, *) = null
* StringUtils.join([], *, *, *, *) = ""
* StringUtils.join([null], *, *, *, null) = "null"
* StringUtils.join(["a", "b", "c"], "--", 0, 3, null) = "a--b--c"
* StringUtils.join(["a", "b", "c"], "--", 1, 3, null) = "b--c"
* StringUtils.join(["a", "b", "c"], "--", 2, 3, StringUtils::upperCase) = "C"
* StringUtils.join(["a", "b", "c"], "--", 2, 2, StringUtils::upperCase) = ""
* StringUtils.join(["a", "b", "c"], null, 0, 3, StringUtils::upperCase) = "ABC"
* StringUtils.join(["a", "b", "c"], "", 0, 3, StringUtils::upperCase) = "ABC"
* StringUtils.join([null, "", "a"], ",", 0, 3, StringUtils::upperCase) = "null,,A"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use, null treated as ""
* @param startIndex
* the first index to start joining from.
* @param endIndex
* the index to stop joining from (exclusive).
* @param formatter
* the formatter to stringify each element, null treated as
* {@link String#valueOf}
* @param <T>
* the type of array element
* @return the joined String, {@code null} if null array input; or the empty
* string if {@code endIndex - startIndex <= 0}. The number of
* joined entries is given by {@code endIndex - startIndex}
* @throws ArrayIndexOutOfBoundsException
* if<br>
* {@code startIndex < 0} or <br>
* {@code startIndex >= array.length()} or <br>
* {@code endIndex < 0} or <br>
* {@code endIndex > array.length()}
*/
public static <T> String join(final T[] array, final String separator, final int startIndex, final int endIndex,
final Function<T, String> formatter) {
if (array == null) {
return null;
}
final String sep = ObjectUtils.defaultIfNull(separator, EMPTY);
final Function<T, String> frmt = ObjectUtils.defaultIfNull(formatter, String::valueOf);
// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) +
// len(separator))
// (Assuming that all Strings are roughly equally long)
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = new StringBuilder(noOfItems * ENSURE_CAPACITY);
for (int i = startIndex; i < endIndex; ++i) {
if (i > startIndex) {
buf.append(sep);
}
if (array[i] != null) {
buf.append(frmt.apply(array[i]));
}
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided map into a single String containing
* the provided list of elements. On each map entry, the formatter is
* applied.
* </p>
*
* <p>
* No delimiter is added before or after the list. A {@code null} separator
* is the same as an empty String (""). If no formatter is specified, the
* format used is the following "key = value". Null key or value within the
* map are represented by the word "null".
* </p>
*
* <pre>
* StringUtils.join(null, ",", null) = null
* StringUtils.join(Collections.emptyMap(), ",", null) = ""
* StringUtils.join(Collections.singletonMap("key", "value"), ",", null) = "key = value"
* StringUtils.join(Collections.singletonMap("key", "value"), ",", e -> e.getKey()) = "key"
* StringUtils.join(MapUtils2.newHashMap(Pair.of("k1", 1), Pair.of("k2", 2)), ", ", null) = "k1 = 1, k2 = 2"
* </pre>
*
* @param map
* the map of entries to join together, may be null
* @param separator
* the separator character to use, null treated as ""
* @param formatter
* the formatter to stringify each entry, null treated as
* {@code "key = value"}
* @param <K>
* the type of each key
* @param <V>
* the type of each value
* @return the joined String, {@code null} if null map input
*/
public static <K, V> String join(final Map<K, V> map, final String separator, final Function<Entry<K, V>, String> formatter) {
if (map == null) {
return null;
}
final String sep = ObjectUtils.defaultIfNull(separator, EMPTY);
final Function<Entry<K, V>, String> frmt = ObjectUtils.defaultIfNull(formatter,
e -> new StringBuilder().append(e.getKey()).append(SEPARATOR_EQUAL).append(e.getValue()).toString());
final StringBuilder buf = new StringBuilder(map.size() * ENSURE_CAPACITY);
for (Entry<K, V> entry : map.entrySet()) {
if (buf.length() > 0) {
buf.append(sep);
}
buf.append(frmt.apply(entry));
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing
* the provided list of elements. Each element is separated by a comma
* followed by a space.
* </p>
*
* <p>
* No delimiter is added before or after the list. A {@code null} separator
* is the same as an empty String (""). Null objects or empty strings within
* the array are represented by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a"]) = "a"
* StringUtils.join(["a", "b", "c"]) = "a, b, c"
* </pre>
*
* @param elements
* the array of values to join together, may be null
* @param <T>
* the type of each element
* @return the joined String, {@code null} if null array input
*/
@SafeVarargs
public static <T> String joinComma(final T... elements) {
return join(elements, SEPARATOR_COMMA);
}
/**
* <p>
* Joins the elements of the provided {@code Iterable} into a single String
* containing the provided elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. The comma followed by a
* space is used as separator (", ").
* </p>
*
* <p>
* See the examples here: {@link #join(Iterable, String)}.
* </p>
*
* @param iterable
* the {@link Iterable} providing the values to join together,
* may be null
* @param <T>
* the type of each element
* @return the joined String, {@code null} if null iterator input
*/
public static <T> String joinComma(final Iterable<T> iterable) {
if (iterable == null) {
return null;
}
return joinComma(iterable.iterator());
}
/**
* <p>
* Joins the elements of the provided {@code Iterator} into a single String
* containing the provided elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. The comma followed by a
* space is used as separator (", ").
* </p>
*
* <p>
* See the examples here: {@link #join(Iterator, String)}.
* </p>
*
* @param iterator
* the {@link Iterator} providing the values to join together,
* may be null
* @param <T>
* the type of each element
* @return the joined String, {@code null} if null iterator input
*/
public static <T> String joinComma(final Iterator<T> iterator) {
return join(iterator, SEPARATOR_COMMA);
}
/**
* Injects all arguments in the specified char sequence. The arguments are
* injected by replacement of the braces. If no index is specified between
* braces, an internal index is created and the index is automatically
* incremented. The index starts from 0. To exclude braces, just double them
* (like {{0}} will return {0}). If number greater than arguments number are
* specified, they are ignored.
*
* <p>
* precondition: {@code charSequence} cannot be {@code null}
* </p>
*
* <pre>
* StringUtils.inject("", "test"); // => ""
*
* StringUtils.inject("I'll go to the {} this {}", "beach", "afternoon");
* // => "I'll go to the beach this afternoon"
*
* StringUtils.inject("I'll go to the {1} this {0}", "afternoon", "beach");
* // => "I'll go to the beach this afternoon"
*
* StringUtils.inject("I'll go to the {1} this {}", "afternoon", "beach");
* // => "I'll go to the beach this afternoon"
*
* StringUtils.inject("I'll go to {} {3} {} {2}", "the", "this", "afternoon", "beach");
* // => "I'll go to the beach this afternoon"
*
* StringUtils.inject("I'll go to {{}}{3} {} {2}{{0}} {4} {text}", "the", "this", "afternoon", "beach");
* // => "I'll go to {}beach the afternoon{0} {4} {text}"
* </pre>
*
* @param charSequence
* the input char sequence
* @param arguments
* the arguments to inject
* @param <T>
* the arguments type
* @return the result with replacements
*/
@SafeVarargs
public static <T> String inject(final CharSequence charSequence, final T... arguments) {
if (charSequence == null) {
throw new IllegalArgumentException("The input char sequence cannot be null");
} else if (isEmpty(charSequence) || arguments == null || arguments.length == 0) {
return charSequence.toString();
}
final StringBuilder output = new StringBuilder(charSequence);
// if no brace, just returns the string
if (output.indexOf(BRACE_OPEN) < 0) {
return output.toString();
}
// replace the excluded braces by a temporary string
replaceBrace(output, BRACE_OPEN_EXCLUDE, BRACE_OPEN_TMP);
replaceBrace(output, BRACE_CLOSE_EXCLUDE, BRACE_CLOSE_TMP);
// replace the braces without index by the arguments
int i = 0;
int index = 0;
while ((index = output.indexOf(BRACES, index)) > -1 && i < arguments.length) {
output.replace(index, index + BRACES.length(), String.valueOf(arguments[i++]));
index += BRACES.length();
}
// replace braces with index by the arguments
int len;
String param;
for (i = 0; i < arguments.length; ++i) {
index = 0;
param = new StringBuilder(BRACE_OPEN).append(i).append(BRACE_CLOSE).toString();
len = param.length();
while ((index = output.indexOf(param, index)) > -1) {
output.replace(index, index + len, String.valueOf(arguments[i]));
index += len;
}
}
// replace the temporary brace by the simple brace
replaceBrace(output, BRACE_OPEN_TMP, BRACE_OPEN);
replaceBrace(output, BRACE_CLOSE_TMP, BRACE_CLOSE);
return output.toString();
}
/**
* Injects all arguments in the specified char sequence. The arguments are
* injected by replacement of keys between braces. To exclude keys, just
* double braces (like {{key}} will return {key}). If some keys aren't
* found, they are ignored.
*
* <p>
* precondition: {@code charSequence} cannot be {@code null}
* </p>
*
* <pre>
* StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "", Pair.of("key", "test"));
* // => ""
*
* StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "I'll go to the {where} this {when}", Pair.of("where", "beach"),
* Pair.of("when", "afternoon"));
* // => "I'll go to the beach this afternoon"
*
* StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "I'll go to {key}{{key}}{key}", Pair.of("key", "beach"));
* // => "I'll go to beach{key}beach"
* </pre>
*
* @param include
* the characters that surround the property key to replace
* @param exclude
* the characters that surround the property key to exclude of
* replacement
* @param charSequence
* the input char sequence
* @param arguments
* the pairs to inject
* @param <T>
* the type arguments
* @return the result with replacements
*/
@SafeVarargs
public static <T extends Map.Entry<String, Object>> String injectKeys(final Pair<String, String> include,
final Pair<String, String> exclude, final CharSequence charSequence, final T... arguments) {
checkParamsInjectKeys(include, exclude, charSequence);
if (isEmpty(charSequence) || arguments == null || arguments.length == 0) {
return charSequence.toString();
}
final StringBuilder output = new StringBuilder(charSequence);
// if no brace, just returns the string
if (output.indexOf(include.getLeft()) < 0) {
return output.toString();
}
for (T argument : arguments) {
if (argument != null) {
int index = 0;
final String key = new StringBuilder(include.getLeft()).append(argument.getKey()).append(include.getRight()).toString();
final String keyExclude = new StringBuilder(exclude.getLeft()).append(argument.getKey()).append(exclude.getRight())
.toString();
// replace the excluded braces by a temporary string
while ((index = output.indexOf(keyExclude, index)) > -1) {
output.replace(index, index + keyExclude.length(), TEMP_REPLACEMENT);
}
// replace the key by the argument
index = 0;
while ((index = output.indexOf(key, index)) > -1) {
output.replace(index, index + key.length(), String.valueOf(argument.getValue()));
}
// replace the temporary string by the excluded braces
index = 0;
while ((index = output.indexOf(TEMP_REPLACEMENT, index)) > -1) {
output.replace(index, index + TEMP_REPLACEMENT.length(), key);
}
}
}
return output.toString();
}
private static <T extends Map.Entry<String, Object>> void checkParamsInjectKeys(final Pair<String, String> include,
final Pair<String, String> exclude, final CharSequence charSequence) {
if (charSequence == null) {
throw new IllegalArgumentException("The input char sequence cannot be null");
} else if (ObjectUtils.anyNull(include, exclude)) {
throw new IllegalArgumentException("The include and exclude parameters cannot be null");
} else if (ObjectUtils.anyNull(include.getLeft(), include.getRight(), exclude.getLeft(), exclude.getRight())) {
throw new IllegalArgumentException("The include and exclude values cannot be null");
} else if (exclude.getLeft().equals(include.getLeft()) || exclude.getRight().equals(include.getRight())) {
throw new IllegalArgumentException("The exclude values cannot be equal to include operators");
} else if (!exclude.getLeft().contains(include.getLeft()) || !exclude.getRight().contains(include.getRight())) {
throw new IllegalArgumentException("The exclude values must contain include operators");
}
}
/**
* Injects all arguments in the specified char sequence. The arguments are
* injected by replacement of keys between braces. To exclude keys, just
* double braces (like {{key}} will return {key}). If some keys aren't
* found, they are ignored.
*
* <p>
* precondition: {@code charSequence} cannot be {@code null}
* </p>
*
* <pre>
* StringUtils.injectKeys("", Pair.of("key", "test")); // => ""
*
* StringUtils.injectKeys("I'll go to the {where} this {when}", Pair.of("where", "beach"), Pair.of("when", "afternoon"));
* // => "I'll go to the beach this afternoon"
*
* StringUtils.injectKeys("I'll go to {key}{{key}}{key}", Pair.of("key", "beach"));
* // => "I'll go to beach{key}beach"
* </pre>
*
* @param charSequence
* the input char sequence
* @param arguments
* the pairs to inject
* @param <T>
* the type arguments
* @return the result with replacements
*/
@SafeVarargs
public static <T extends Map.Entry<String, Object>> String injectKeys(final CharSequence charSequence, final T... arguments) {
return injectKeys(INCLUDE_CURLY_BRACES, EXCLUDE_CURLY_BRACES, charSequence, arguments);
}
/**
* Injects all arguments in the specified char sequence. The arguments are
* injected by replacement of keys between braces. To exclude keys, just
* double braces (like {{key}} will return {key}). If some keys aren't
* found, they are ignored.
*
* <p>
* precondition: {@code charSequence} cannot be {@code null}
* </p>
*
* <pre>
* StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "", Collections.singletonMap("key", "test"));
* // => ""
*
* StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "I'll go to the ${where} this {when}",
* MapUtils2.newHashMap(Pair.of("where", "beach"), Pair.of("when", "afternoon")));
* // => "I'll go to the beach this afternoon"
*
* StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "I'll go to ${key}${{key}}${key}",
* Collections.singletonMap("key", "beach"));
* // => "I'll go to beach${key}beach"
* </pre>
*
* @param include
* the characters that surround the property key to replace
* @param exclude
* the characters that surround the property key to exclude of
* replacement
* @param charSequence
* the input char sequence
* @param arguments
* the map of pairs to inject
* @return the result with replacements
*/
public static String injectKeys(final Pair<String, String> include, final Pair<String, String> exclude, final CharSequence charSequence,
final Map<String, Object> arguments) {
if (charSequence == null) {
throw new IllegalArgumentException("The input char sequence cannot be null");
} else if (isEmpty(charSequence) || MapUtils.isEmpty(arguments)) {
return charSequence.toString();
}
return injectKeys(include, exclude, charSequence, arguments.entrySet().toArray(CastUtils.cast(new Map.Entry[arguments.size()])));
}
/**
* Injects all arguments in the specified char sequence. The arguments are
* injected by replacement of keys between braces. To exclude keys, just
* double braces (like {{key}} will return {key}). If some keys aren't
* found, they are ignored.
*
* <p>
* precondition: {@code charSequence} cannot be {@code null}
* </p>
*
* <pre>
* StringUtils.injectKeys("", Collections.singletonMap("key", "test"));
* // => ""
*
* StringUtils.injectKeys("I'll go to the {where} this {when}",
* MapUtils2.newHashMap(Pair.of("where", "beach"), Pair.of("when", "afternoon")));
* // => "I'll go to the beach this afternoon"
*
* StringUtils.injectKeys("I'll go to {key}{{key}}{key}", Collections.singletonMap("key", "beach"));
* // => "I'll go to beach{key}beach"
* </pre>
*
* @param charSequence
* the input char sequence
* @param arguments
* the map of pairs to inject
* @return the result with replacements
*/
public static String injectKeys(final CharSequence charSequence, final Map<String, Object> arguments) {
return injectKeys(INCLUDE_CURLY_BRACES, EXCLUDE_CURLY_BRACES, charSequence, arguments);
}
/**
* Injects all arguments in the specified char sequence. The arguments are
* injected by replacement of keys between braces. To exclude keys, just
* double braces (like {{key}} will return {key}). If some keys aren't
* found, they are ignored.
*
* <p>
* precondition: {@code charSequence} cannot be {@code null}
* </p>
*
* <pre>
* Properties properties = new Properties();
* properties.setProperty("where", "beach");
* properties.setProperty("when", "afternoon");
*
* StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "", properties);
* // => ""
*
* StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "I'll go to the ${where} this ${when}", properties);
* // => "I'll go to the beach this afternoon"
*
* StringUtils.injectKeys(Pair.of("${", "}"), Pair.of("${{", "}}"), "I'll go to ${where}${{where}}${where}", properties);
* // => "I'll go to beach${where}beach"
* </pre>
*
* @param include
* the characters that surround the property key to replace
* @param exclude
* the characters that surround the property key to exclude of
* replacement
* @param charSequence
* the input char sequence
* @param properties
* the properties to inject
* @return the result with replacements
*/
public static String injectKeys(final Pair<String, String> include, final Pair<String, String> exclude, final CharSequence charSequence,
final Properties properties) {
if (charSequence == null) {
throw new IllegalArgumentException("The input char sequence cannot be null");
} else if (isEmpty(charSequence) || properties == null || properties.isEmpty()) {
return charSequence.toString();
}
return injectKeys(include, exclude, charSequence, properties.entrySet().toArray(CastUtils.cast(new Map.Entry[properties.size()])));
}
/**
* Injects all arguments in the specified char sequence. The arguments are
* injected by replacement of keys between braces. To exclude keys, just
* double braces (like {{key}} will return {key}). If some keys aren't
* found, they are ignored.
*
* <p>
* precondition: {@code charSequence} cannot be {@code null}
* </p>
*
* <pre>
* Properties properties = new Properties();
* properties.setProperty("where", "beach");
* properties.setProperty("when", "afternoon");
*
* StringUtils.injectKeys("", properties);
* // => ""
*
* StringUtils.injectKeys("I'll go to the {where} this {when}", properties);
* // => "I'll go to the beach this afternoon"
*
* StringUtils.injectKeys("I'll go to {where}{{where}}{where}", properties);
* // => "I'll go to beach{where}beach"
* </pre>
*
* @param charSequence
* the input char sequence
* @param properties
* the properties to inject
* @return the result with replacements
*/
public static String injectKeys(final CharSequence charSequence, final Properties properties) {
return injectKeys(INCLUDE_CURLY_BRACES, EXCLUDE_CURLY_BRACES, charSequence, properties);
}
private static void replaceBrace(final StringBuilder output, final String text, final String replacement) {
int index = 0;
while ((index = output.indexOf(text, index)) > -1) {
output.replace(index, index + text.length(), replacement);
index += replacement.length();
}
}
/**
* Concatenate objects. If one object is {@code null}, it's replaced by the
* word 'null', otherwise calls toString method for each object.
*
* @param objects
* the objects to concatenate
* @return the concatenated String (may be empty if objects array is empty)
* @throws NullPointerException
* if {@code objects} array is {@code null}
*/
public static String concat(final Object... objects) {
Objects.requireNonNull(objects, ERROR_OBJECTS);
if (objects.length > 0) {
char[] buf = new char[BUFFER_CAPACITY];
int pos = 0;
for (Object object : objects) {
char[] chars;
if (object != null) {
chars = object.toString().toCharArray();
} else {
chars = NULL_CHARS;
}
if (pos + chars.length > buf.length) {
char[] newBuf = new char[buf.length + chars.length + ENSURE_CAPACITY];
System.arraycopy(buf, 0, newBuf, 0, buf.length);
buf = newBuf;
}
System.arraycopy(chars, 0, buf, pos, chars.length);
pos += chars.length;
}
return new String(buf, 0, pos);
} else {
return StringUtils.EMPTY;
}
}
/**
* Try to prefix the sequence
*
* @param sequence
* the sequence to prefix
* @param prefix
* the prefix
* @return the prefixed sequence
* @throws NullPointerException
* if {@code sequence} or {@code prefix} are {@code null}
*/
public static String prefixIfNotStartsWith(final CharSequence sequence, final CharSequence prefix) {
Objects.requireNonNull(sequence, ERROR_SEQUENCE);
Objects.requireNonNull(prefix, ERROR_PREFIX);
int lSequence = sequence.length();
int lPrefix = prefix.length();
if (lPrefix == 0 || (lSequence >= lPrefix && sequence.subSequence(0, lPrefix).equals(prefix))) {
return sequence.toString();
}
return prefix.toString().concat(sequence.toString());
}
/**
* Try to suffix the sequence
*
* @param sequence
* the sequence to suffix
* @param suffix
* the suffix
* @return the suffixed sequence
* @throws NullPointerException
* if {@code sequence} or {@code suffix} are {@code null}
*/
public static String suffixIfNotEndsWith(final CharSequence sequence, final CharSequence suffix) {
Objects.requireNonNull(sequence, ERROR_SEQUENCE);
Objects.requireNonNull(suffix, ERROR_SUFFIX);
int lSequence = sequence.length();
int lSuffix = suffix.length();
if (lSuffix == 0 || (lSequence >= lSuffix && sequence.subSequence(lSequence - lSuffix, lSequence).equals(suffix))) {
return sequence.toString();
}
return sequence.toString().concat(suffix.toString());
}
}
| apache-2.0 |
Muhamedali/plpgsql-java-model | model/src/main/java/org/postgresql/java/model/NullsSort.java | 199 | package org.postgresql.java.model;
import org.postgresql.java.model.annotations.Replace;
public enum NullsSort {
@Replace("NULLS FIRST") NULLS_FIRST,
@Replace("NULLS LAST") NULLS_LAST,
}
| apache-2.0 |
lcg0124/bootdo | bootdo/src/main/java/com/bootdo/system/config/BDSessionListener.java | 676 | package com.bootdo.system.config;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
public class BDSessionListener implements SessionListener {
private final AtomicInteger sessionCount = new AtomicInteger(0);
@Override
public void onStart(Session session) {
sessionCount.incrementAndGet();
}
@Override
public void onStop(Session session) {
sessionCount.decrementAndGet();
}
@Override
public void onExpiration(Session session) {
sessionCount.decrementAndGet();
}
public int getSessionCount() {
return sessionCount.get();
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-memorydb/src/main/java/com/amazonaws/services/memorydb/model/transform/CopySnapshotResultJsonUnmarshaller.java | 2789 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.memorydb.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.memorydb.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* CopySnapshotResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CopySnapshotResultJsonUnmarshaller implements Unmarshaller<CopySnapshotResult, JsonUnmarshallerContext> {
public CopySnapshotResult unmarshall(JsonUnmarshallerContext context) throws Exception {
CopySnapshotResult copySnapshotResult = new CopySnapshotResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return copySnapshotResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Snapshot", targetDepth)) {
context.nextToken();
copySnapshotResult.setSnapshot(SnapshotJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return copySnapshotResult;
}
private static CopySnapshotResultJsonUnmarshaller instance;
public static CopySnapshotResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CopySnapshotResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
quarkusio/quarkus | integration-tests/elytron-undertow/src/test/java/io/quarkus/it/undertow/elytron/BaseAuthRestTest.java | 1287 | package io.quarkus.it.undertow.elytron;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
@QuarkusTest
class BaseAuthRestTest extends HttpsSetup {
@Test
@RepeatedTest(100)
void testPost() {
// This is a regression test in that we had a problem where the Vert.x request was not paused
// before the authentication filters ran and the post message was thrown away by Vert.x because
// RESTEasy hadn't registered its request handlers yet.
given()
.header("Authorization", "Basic am9objpqb2hu")
.body("Bill")
.contentType(ContentType.TEXT)
.when()
.post("/foo/mapped/rest")
.then()
.statusCode(200)
.body(is("post success"));
}
@Test
void testGet() {
given()
.header("Authorization", "Basic am9objpqb2hu")
.when()
.get("/foo/mapped/rest")
.then()
.statusCode(200)
.body(is("get success"));
}
}
| apache-2.0 |
evgfast/java_abc | addressbook-tests-homework/src/test/java/com/hw/addressbook/appmanager/AddressBookEntryHelper.java | 8177 | package com.hw.addressbook.appmanager;
import com.hw.addressbook.model.AddressBookEntry;
import com.hw.addressbook.model.Contacts;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.*;
/**
* Created by evg on 18.09.16.
*/
public class AddressBookEntryHelper extends HelperBase{
private Contacts contactsCache = null;
public AddressBookEntryHelper(WebDriver wd) {
super(wd);
}
public void submitAddressBookEntryForm() {
click(By.xpath("//input[@type=\"submit\"][1]"));
}
/*
addressBookEntry is object of contact
creation is flag, if you will want create new contact should be equals TRUE
*/
public void fillAddressBookEntryForm(AddressBookEntry addressBookEntry, boolean creation) {
type(By.name("firstname"), addressBookEntry.getFirstname());
type(By.name("middlename"), addressBookEntry.getMiddlename());
type(By.name("lastname"), addressBookEntry.getLastname());
// type(By.name("nickname"), addressBookEntry.getNickname());
// type(By.name("company"), addressBookEntry.getCompany());
type(By.name("address"), addressBookEntry.getAddress());
type(By.name("home"), addressBookEntry.getPhoneHome());
type(By.name("mobile"), addressBookEntry.getMobile());
type(By.name("work"), addressBookEntry.getPhoneWork());
type(By.name("email"), addressBookEntry.getEmail());
attach(By.name("photo"), addressBookEntry.getPhoto() );
if(creation){
new Select(wd.findElement(By.name("new_group"))).selectByIndex(1);
} else{
Assert.assertFalse(isElementPresent(By.name("new_group")));
}
}
public void initAddressBookEntryCreation() {
click(By.linkText("add new"));
}
public void initUserDeletion(){
click(By.xpath("//input[@value=\"Delete\"]"));
wd.switchTo().alert().accept();
}
public void initFirstUserModification(int index){
wd.findElement(By.xpath("//tr[@name=\"entry\"][1]//img[@alt=\"Edit\"]")).click();
}
public void updateUser(){
click(By.xpath("//input[@value=\"Update\"][1]"));
}
public void backHomePage() {
click(By.linkText("home"));
}
public void create(AddressBookEntry contact) {
initAddressBookEntryCreation();
fillAddressBookEntryForm(contact, true);
submitAddressBookEntryForm();
contactsCache = null;
backHomePage();
}
public boolean isThereAContact() {
return isElementPresent(By.xpath("//tr[@name][1]//input"));
}
public int count() {
return wd.findElements(By.name("selected[]")).size();
}
private void selectContactEditById(int id) {
wd.findElement(By.cssSelector("a[href='edit.php?id=" + id +"']")).click();
}
private void selectContactCheckBoxById(int id) {
wd.findElement(By.cssSelector("input[value='" + id +"']")).click();
}
private void selectDetailsById(int id) {
wd.findElement(By.cssSelector("a[href='view.php?id=" + id +"']")).click();
}
public Contacts all() {
if(contactsCache != null){
return new Contacts(contactsCache);
}
contactsCache = new Contacts();
List<WebElement> elements = wd.findElements(By.cssSelector("tr[class]"));
for(WebElement element : elements){
String last_name = element.findElement(By.cssSelector("td:nth-child(2)")).getText();
String first_name = element.findElement(By.cssSelector("td:nth-child(3)")).getText();
String address = element.findElement(By.cssSelector("td:nth-child(4)")).getText();
String allEmails = element.findElement(By.cssSelector("td:nth-child(5)")).getText();
String allPhones = element.findElement(By.cssSelector("td:nth-child(6)")).getText();
int id = Integer.parseInt(element.findElement(By.cssSelector("td:nth-child(1) input")).getAttribute("value"));
contactsCache.add(new AddressBookEntry().withId(id)
.withFirstname(first_name)
.withLastname(last_name)
.withAllPhones(allPhones)
.withAllEmails(allEmails)
.withAllPostAddress(address)
);
}
return new Contacts(contactsCache);
}
public void modify(AddressBookEntry user_mod) {
selectContactEditById(user_mod.getId());
fillAddressBookEntryForm(user_mod, false);
updateUser();
contactsCache = null;
backHomePage();
}
public void delete(AddressBookEntry contact) {
selectContactCheckBoxById(contact.getId());
initUserDeletion();
contactsCache = null;
backHomePage();
}
public AddressBookEntry infoFromEditForm(AddressBookEntry contact) {
selectContactEditById(contact.getId());
String firstname = wd.findElement(By.name("firstname")).getAttribute("value");
String lastname = wd.findElement(By.name("lastname")).getAttribute("value");
String home = wd.findElement(By.name("home")).getAttribute("value");
String mobile = wd.findElement(By.name("mobile")).getAttribute("value");
String work = wd.findElement(By.name("work")).getAttribute("value");
String address = wd.findElement(By.name("address")).getText();
String email = wd.findElement(By.name("email")).getAttribute("value");
String email2 = wd.findElement(By.name("email2")).getAttribute("value");
String email3 = wd.findElement(By.name("email3")).getAttribute("value");
wd.navigate().back();
return new AddressBookEntry().withId(contact.getId()).withFirstname(firstname).withLastname(lastname)
.withPhoneHome(home).withMobile(mobile).withWorkPhone(work)
.withEmail(email).withEmail2(email2).withEmail3(email3)
.withAddress(address);
}
public AddressBookEntry infoFromDetails(AddressBookEntry contact){
selectDetailsById(contact.getId());
String[] fio = wd.findElement(By.xpath(".//*[@id='content']/b")).getText().split(" ");
String firstname = "";
String lastname = "";
if(fio.length == 3) {
firstname = fio[0];
lastname = fio[2];
}
String allDetails = wd.findElement(By.xpath(".//*[@id='content']")).getText();
List<WebElement> allEmails = wd.findElements(By.cssSelector("a[href^=\"mailto\"]"));
List<String> list_email = new ArrayList<String>();
for (WebElement e : allEmails) {
list_email.add(e.getText());
}
if(allEmails.size() == 2){
list_email.add("");
} else if(allEmails.size() == 1){
list_email.add("");
list_email.add("");
}
String mobile = getPhone(allDetails, "M");
String work = getPhone(allDetails, "W");
String home = getPhone(allDetails, "H");
String email = list_email.get(0);
String email2 = list_email.get(1);
String email3 = list_email.get(2);
wd.navigate().back();
return new AddressBookEntry().withId(contact.getId()).withFirstname(firstname).withLastname(lastname)
.withPhoneHome(home).withMobile(mobile).withWorkPhone(work)
.withEmail(email).withEmail2(email2).withEmail3(email3);
}
// txt - this is all text,
// typePhone - set symbol H(home) or M(mobile) or W(work)
/*
H: 222266
M: 88888
W: 99999
*/
private String getPhone(String txt, String typePhone){
String pattern = "(" + typePhone + "):\\s\\d+";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(txt);
try {
m.find();
return txt.substring(m.start() + 3, m.end());
}catch (IllegalStateException i){
return "";
}
}
}
| apache-2.0 |
lpandzic/assertj-core | src/test/java/org/assertj/core/api/localdate/LocalDateAssertBaseTest.java | 1441 | /**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2014 the original author or authors.
*/
package org.assertj.core.api.localdate;
import static org.junit.Assume.assumeTrue;
import java.time.LocalDate;
import org.assertj.core.api.AbstractLocalDateAssert;
import org.assertj.core.api.BaseTest;
import org.junit.experimental.theories.DataPoint;
/**
*
* Base test class for {@link AbstractLocalDateAssert} tests.
*
*/
public class LocalDateAssertBaseTest extends BaseTest {
@DataPoint
public static LocalDate localDate1 = LocalDate.now().minusDays(10);
@DataPoint
public static LocalDate localDate2 = LocalDate.now();
@DataPoint
public static LocalDate localDate3 = LocalDate.now().plusDays(10);
protected static void testAssumptions(LocalDate reference, LocalDate dateBefore, LocalDate dateAfter) {
assumeTrue(dateBefore.isBefore(reference));
assumeTrue(dateAfter.isAfter(reference));
}
} | apache-2.0 |
obidea/semantika | src/main/java/com/obidea/semantika/mapping/base/sql/SqlIsNotNull.java | 1307 | /*
* Copyright (c) 2013-2015 Josef Hardi <josef.hardi@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.obidea.semantika.mapping.base.sql;
import com.obidea.semantika.database.sql.base.ISqlExpression;
import com.obidea.semantika.database.sql.base.ISqlExpressionVisitor;
import com.obidea.semantika.datatype.DataType;
public class SqlIsNotNull extends SqlUnaryFunction
{
private static final long serialVersionUID = 629451L;
public SqlIsNotNull(ISqlExpression expression)
{
super("NOT_NULL", DataType.BOOLEAN, expression); //$NON-NLS-1$
}
@Override
public String getStringExpression()
{
return "IS NOT NULL"; //$NON-NLS-1$
}
@Override
public void accept(ISqlExpressionVisitor visitor)
{
visitor.visit(this);
}
}
| apache-2.0 |