repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
MaryArs/java_pdt | addressbook-web-tests/src/test/java/ru/stqa/pdt/addressbook/appmanager/BaseHelper.java | 1179 | package ru.stqa.pdt.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.File;
public class BaseHelper {
protected WebDriver wd;
public BaseHelper(WebDriver wd){
this.wd = wd;
}
protected void click(By locator) {
wd.findElement(locator).click();
}
protected void type(By locator, String text){
click(locator);
if (text != null) {
String existingText = wd.findElement(locator).getAttribute("value");
if (! text.equals(existingText)){
wd.findElement(locator).clear();
wd.findElement(locator).sendKeys(text);
}
}
}
protected void attach(By locator, File file){
if (file != null) {
wd.findElement(locator).sendKeys(file.getAbsolutePath());
}
}
protected boolean selectedElement() {
return wd.findElement(By.id("1")).isSelected();
}
protected boolean isElementPresent(By locator) {
try {
wd.findElement(locator);
return true;
} catch (NoSuchElementException ex) {
return false;
}
}
}
| apache-2.0 |
JohnDoll/Toyota | src/main/java/apps/toyota/mainNavigation/MainNavigation.java | 4792 | package apps.toyota.mainNavigation;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.FindBy;
import org.testng.Assert;
import com.orasi.core.interfaces.Button;
import com.orasi.core.interfaces.Element;
import com.orasi.core.interfaces.Textbox;
import com.orasi.core.interfaces.impl.internal.ElementFactory;
import com.orasi.utils.PageLoaded;
import com.orasi.utils.TestReporter;
/**
* @summary Contains the methods & objects for the Toyota.com Main Navigation Bar
* @version Created 09/10/2014
* @author Waightstill W. Avery
*/
public class MainNavigation {
// ******************************
// *** Main Navigation Fields ***
// ******************************
String initialZipCode = "";
String modifiedZipCode = "";
// ********************************
// *** Main Navigation Elements ***
// ********************************
//Your Location button
@FindBy(xpath = "//*[@id=\"tcom-main-nav\"]/ul/li[3]/button")
private Button btnYourLocation;
//ZIP Code Popup
@FindBy(xpath = "//*[@id=\"tcom-nav-zip-flyout\"]/div")
private Element eleZipCodePopup;
//ZIP Code textbox
@FindBy(xpath = "//*[@id=\"tcom-nav-zip-flyout\"]/div/div/div[2]/div/input")
private Textbox txtZipCode;
//Actual ZIP Code Value element
@FindBy(xpath = "//*[@id=\"tcom-main-nav\"]/ul/li[3]/button/span/span")
private Element eleZipCode;
// *********************
// ** Build page area **
// *********************
private WebDriver driver;
/**
*
* @summary Constructor to initialize the page
* @version Created 09/10/2014
* @author Waightstill W Avery
* @param driver
* @throws NA
* @return NA
*
*/
public MainNavigation(WebDriver driver){
this.driver = driver;
ElementFactory.initElements(driver, this);
}
public boolean pageLoaded() {
return new PageLoaded().isPageHTMLLoaded(this.getClass(), driver, btnYourLocation);
}
public boolean pageLoaded(Element element) {
return new PageLoaded().isPageHTMLLoaded(this.getClass(), driver, element);
}
public MainNavigation initialize() {
return ElementFactory.initElements(driver, this.getClass());
}
// ***********************************************
// *** HomePage Interactions ***
// ***********************************************
/**
* @summary: clicks on the locations link to allow a new zipcode to be entered
* @author: Waightstill W Avery
* @param: NA
* @return: NA
*/
private void clickYourLocation(){
//Attempt to use the Selenium 'click'
btnYourLocation.click();
if(!pageLoaded(eleZipCodePopup)){
//If the zipcode popup does not load, then try a JavaScript 'click'
initialize();
btnYourLocation.jsClick(driver);
Assert.assertEquals(pageLoaded(eleZipCodePopup), true, "The zip code popup was not displayed.");
}
}
/**
* @summary: if the zipcode is different than that found in the UI, this method will click the location icon, enter the new zipcode and verify the change is reflected in the UI
* @author: Waightstill W Avery
* @param: zipCode - String, value to be entered as the new zipcode to use
* @return: NA
*/
public void changeZipCodes(String zipCode){
pageLoaded(txtZipCode);
//Capture the zipcode that currently exists in the UI
this.initialZipCode = captureCurrentZipCode();
TestReporter.log("Initial zip code: ["+initialZipCode+"].");
//Determine if the existing zipcode in the UI is the same as the zipcode to be used in the test
if(!initialZipCode.equalsIgnoreCase(zipCode)){
//If the zipcode is different, enter the zipcode to be used for the test
clickYourLocation();
txtZipCode.safeSet(zipCode);
initialize();
pageLoaded();
//Capture the newly modified zipcode from the UI
this.modifiedZipCode = captureCurrentZipCode();
TestReporter.log("Modified zip code: ["+modifiedZipCode+"].");
//Ensure the expected and actual zipcdes match
verifyZipCodeValue(zipCode);
}
}
/**
* @summary: verifies that the expected and actual zipcodes are equal
* @author: Waightstill W Avery
* @param: expectedZipCode - String, value of the zipcode that is expected to be reflected in the UI
* @return: NA
*/
private void verifyZipCodeValue(String expectedZipCode){
Assert.assertEquals(captureCurrentZipCode(), expectedZipCode, "The actual zipcode ["+captureCurrentZipCode()+"] did not match the expected zip code ["+expectedZipCode+"].");
}
/**
* @summary: captures the zipcode that is currently displayed in the UI
* @author: Waightstill W Avery
* @param: NA
* @return: NA
*/
private String captureCurrentZipCode(){
pageLoaded(eleZipCode);
return eleZipCode.getText().trim();
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/GetInventorySchemaRequest.java | 13491 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.simplesystemsmanagement.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetInventorySchema" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetInventorySchemaRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The type of inventory item to return.
* </p>
*/
private String typeName;
/**
* <p>
* The token for the next set of items to return. (You received this token from a previous call.)
* </p>
*/
private String nextToken;
/**
* <p>
* The maximum number of items to return for this call. The call also returns a token that you can specify in a
* subsequent call to get the next set of results.
* </p>
*/
private Integer maxResults;
/**
* <p>
* Returns inventory schemas that support aggregation. For example, this call returns the
* <code>AWS:InstanceInformation</code> type, because it supports aggregation based on the <code>PlatformName</code>, <code>PlatformType</code>, and <code>PlatformVersion</code> attributes.
* </p>
*/
private Boolean aggregator;
/**
* <p>
* Returns the sub-type schema for a specified inventory type.
* </p>
*/
private Boolean subType;
/**
* <p>
* The type of inventory item to return.
* </p>
*
* @param typeName
* The type of inventory item to return.
*/
public void setTypeName(String typeName) {
this.typeName = typeName;
}
/**
* <p>
* The type of inventory item to return.
* </p>
*
* @return The type of inventory item to return.
*/
public String getTypeName() {
return this.typeName;
}
/**
* <p>
* The type of inventory item to return.
* </p>
*
* @param typeName
* The type of inventory item to return.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetInventorySchemaRequest withTypeName(String typeName) {
setTypeName(typeName);
return this;
}
/**
* <p>
* The token for the next set of items to return. (You received this token from a previous call.)
* </p>
*
* @param nextToken
* The token for the next set of items to return. (You received this token from a previous call.)
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The token for the next set of items to return. (You received this token from a previous call.)
* </p>
*
* @return The token for the next set of items to return. (You received this token from a previous call.)
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The token for the next set of items to return. (You received this token from a previous call.)
* </p>
*
* @param nextToken
* The token for the next set of items to return. (You received this token from a previous call.)
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetInventorySchemaRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* <p>
* The maximum number of items to return for this call. The call also returns a token that you can specify in a
* subsequent call to get the next set of results.
* </p>
*
* @param maxResults
* The maximum number of items to return for this call. The call also returns a token that you can specify in
* a subsequent call to get the next set of results.
*/
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
/**
* <p>
* The maximum number of items to return for this call. The call also returns a token that you can specify in a
* subsequent call to get the next set of results.
* </p>
*
* @return The maximum number of items to return for this call. The call also returns a token that you can specify
* in a subsequent call to get the next set of results.
*/
public Integer getMaxResults() {
return this.maxResults;
}
/**
* <p>
* The maximum number of items to return for this call. The call also returns a token that you can specify in a
* subsequent call to get the next set of results.
* </p>
*
* @param maxResults
* The maximum number of items to return for this call. The call also returns a token that you can specify in
* a subsequent call to get the next set of results.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetInventorySchemaRequest withMaxResults(Integer maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* <p>
* Returns inventory schemas that support aggregation. For example, this call returns the
* <code>AWS:InstanceInformation</code> type, because it supports aggregation based on the <code>PlatformName</code>, <code>PlatformType</code>, and <code>PlatformVersion</code> attributes.
* </p>
*
* @param aggregator
* Returns inventory schemas that support aggregation. For example, this call returns the
* <code>AWS:InstanceInformation</code> type, because it supports aggregation based on the
* <code>PlatformName</code>, <code>PlatformType</code>, and <code>PlatformVersion</code> attributes.
*/
public void setAggregator(Boolean aggregator) {
this.aggregator = aggregator;
}
/**
* <p>
* Returns inventory schemas that support aggregation. For example, this call returns the
* <code>AWS:InstanceInformation</code> type, because it supports aggregation based on the <code>PlatformName</code>, <code>PlatformType</code>, and <code>PlatformVersion</code> attributes.
* </p>
*
* @return Returns inventory schemas that support aggregation. For example, this call returns the
* <code>AWS:InstanceInformation</code> type, because it supports aggregation based on the
* <code>PlatformName</code>, <code>PlatformType</code>, and <code>PlatformVersion</code> attributes.
*/
public Boolean getAggregator() {
return this.aggregator;
}
/**
* <p>
* Returns inventory schemas that support aggregation. For example, this call returns the
* <code>AWS:InstanceInformation</code> type, because it supports aggregation based on the <code>PlatformName</code>, <code>PlatformType</code>, and <code>PlatformVersion</code> attributes.
* </p>
*
* @param aggregator
* Returns inventory schemas that support aggregation. For example, this call returns the
* <code>AWS:InstanceInformation</code> type, because it supports aggregation based on the
* <code>PlatformName</code>, <code>PlatformType</code>, and <code>PlatformVersion</code> attributes.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetInventorySchemaRequest withAggregator(Boolean aggregator) {
setAggregator(aggregator);
return this;
}
/**
* <p>
* Returns inventory schemas that support aggregation. For example, this call returns the
* <code>AWS:InstanceInformation</code> type, because it supports aggregation based on the <code>PlatformName</code>, <code>PlatformType</code>, and <code>PlatformVersion</code> attributes.
* </p>
*
* @return Returns inventory schemas that support aggregation. For example, this call returns the
* <code>AWS:InstanceInformation</code> type, because it supports aggregation based on the
* <code>PlatformName</code>, <code>PlatformType</code>, and <code>PlatformVersion</code> attributes.
*/
public Boolean isAggregator() {
return this.aggregator;
}
/**
* <p>
* Returns the sub-type schema for a specified inventory type.
* </p>
*
* @param subType
* Returns the sub-type schema for a specified inventory type.
*/
public void setSubType(Boolean subType) {
this.subType = subType;
}
/**
* <p>
* Returns the sub-type schema for a specified inventory type.
* </p>
*
* @return Returns the sub-type schema for a specified inventory type.
*/
public Boolean getSubType() {
return this.subType;
}
/**
* <p>
* Returns the sub-type schema for a specified inventory type.
* </p>
*
* @param subType
* Returns the sub-type schema for a specified inventory type.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetInventorySchemaRequest withSubType(Boolean subType) {
setSubType(subType);
return this;
}
/**
* <p>
* Returns the sub-type schema for a specified inventory type.
* </p>
*
* @return Returns the sub-type schema for a specified inventory type.
*/
public Boolean isSubType() {
return this.subType;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTypeName() != null)
sb.append("TypeName: ").append(getTypeName()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults()).append(",");
if (getAggregator() != null)
sb.append("Aggregator: ").append(getAggregator()).append(",");
if (getSubType() != null)
sb.append("SubType: ").append(getSubType());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetInventorySchemaRequest == false)
return false;
GetInventorySchemaRequest other = (GetInventorySchemaRequest) obj;
if (other.getTypeName() == null ^ this.getTypeName() == null)
return false;
if (other.getTypeName() != null && other.getTypeName().equals(this.getTypeName()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
if (other.getAggregator() == null ^ this.getAggregator() == null)
return false;
if (other.getAggregator() != null && other.getAggregator().equals(this.getAggregator()) == false)
return false;
if (other.getSubType() == null ^ this.getSubType() == null)
return false;
if (other.getSubType() != null && other.getSubType().equals(this.getSubType()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getTypeName() == null) ? 0 : getTypeName().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
hashCode = prime * hashCode + ((getAggregator() == null) ? 0 : getAggregator().hashCode());
hashCode = prime * hashCode + ((getSubType() == null) ? 0 : getSubType().hashCode());
return hashCode;
}
@Override
public GetInventorySchemaRequest clone() {
return (GetInventorySchemaRequest) super.clone();
}
}
| apache-2.0 |
lgoldstein/communitychest | chest/3rd-party/spring/core/src/test/java/net/community/chest/spring/test/resources/TestResourcesAnchorContext.java | 2153 | /*
*
*/
package net.community.chest.spring.test.resources;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Serves as anchor to the resource files
* @author Lyor G.
* @since Jul 20, 2010 9:28:10 AM
*/
public class TestResourcesAnchorContext extends ClassPathXmlApplicationContext {
public TestResourcesAnchorContext (String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException
{
super(configLocations, refresh, parent);
}
public TestResourcesAnchorContext (String[] configLocations, ApplicationContext parent)
throws BeansException
{
this(configLocations, true, parent);
}
public TestResourcesAnchorContext (String[] configLocations, boolean refresh)
throws BeansException
{
this(configLocations, refresh, null);
}
public TestResourcesAnchorContext (String... configLocations)
throws BeansException
{
this(configLocations, true);
}
public TestResourcesAnchorContext (String configLocation)
throws BeansException
{
this(new String[] {configLocation}, true);
}
public TestResourcesAnchorContext (String[] paths, Class<?> clazz, ApplicationContext parent)
throws BeansException
{
super(paths, clazz, parent);
}
public TestResourcesAnchorContext (String[] paths, Class<?> clazz)
throws BeansException
{
this(paths, clazz, null);
}
public TestResourcesAnchorContext (String path, Class<?> clazz)
throws BeansException
{
this(new String[] {path}, clazz);
}
public static final String DEFAULT_CONTEXT_FILE="application-testContext.xml";
public TestResourcesAnchorContext ()
{
this(DEFAULT_CONTEXT_FILE, TestResourcesAnchorContext.class);
}
public TestResourcesAnchorContext (ApplicationContext parent)
{
this(new String[] { DEFAULT_CONTEXT_FILE }, TestResourcesAnchorContext.class, parent);
}
}
| apache-2.0 |
patrickfav/dice | src/main/java/at/favre/tools/dice/service/anuquantum/AnuQuantumService.java | 1052 | /*
* Copyright 2017 Patrick Favre-Bulle
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package at.favre.tools.dice.service.anuquantum;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.HeaderMap;
import retrofit2.http.Headers;
import retrofit2.http.Query;
import java.util.Map;
public interface AnuQuantumService {
@Headers({"DNT: 1"})
@GET("/API/jsonI.php?length=1&type=hex16")
Call<AnuQuantumResponse> getRandom(@HeaderMap Map<String, String> headers, @Query("size") int byteLength);
}
| apache-2.0 |
EuropeanCustomsGateway/ReferenceData | referencedata-DS-ejb/src/main/java/org/ecg/refdata/datasource/entities/correlation/CorrelationItem.java | 2921 | package org.ecg.refdata.datasource.entities.correlation;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.ecg.refdata.datasource.entities.commons.ReferenceDataAbstractDataTypeEntity;
import org.ecg.refdata.datasource.entities.commons.ReferenceDataPeriodicValidityAbstractItem;
import org.ecg.refdata.query.DictionaryItem;
import org.ecg.refdata.query.model.impl.CorrelationImpl;
/**
* Class represents entity bean of JPA. Correlation table - unified structure
* used for defining possible combination of two codes from any reference data
* lists (e.g. requested and previous procedures).
*
*/
@Entity()
@Table(name = "ref_corelation_it")
@DiscriminatorValue(value = "CorrelationItem")
@PrimaryKeyJoinColumn(name = "ref_item_mapping_id")
public class CorrelationItem extends ReferenceDataPeriodicValidityAbstractItem {
private static final long serialVersionUID = -488692363285140782L;
/**
* @serial Code1 field
*/
@Column(name = "code1", unique = false, nullable = true, length = 20)
private String code1;
/**
* @serial Code2 field
*/
@Column(name = "code2", unique = false, nullable = true, length = 20)
private String code2;
/**
* @serial Code3 field
*/
@Column(name = "code3", unique = false, nullable = true, length = 20)
private String code3;
/**
* @serial Code3 field
*/
@Column(name = "code4", unique = false, nullable = true, length = 20)
private String code4;
/**
* For hibernate only
*/
CorrelationItem() {
super();
}
/**
* Creates CorrelationItem Item for a given
* ReferenceDataAbstractDataTypeEntity
*
* @param referenceDataTypeEntity ReferenceDataAbstractDataTypeEntity to
* which created item will belong
*/
public CorrelationItem(
ReferenceDataAbstractDataTypeEntity referenceDataTypeEntity) {
super(referenceDataTypeEntity);
}
public String getCode1() {
return code1;
}
public String getCode2() {
return code2;
}
public String getCode3() {
return code3;
}
public String getCode4() {
return code4;
}
public void setCode1(String code1) {
this.code1 = code1;
}
public void setCode2(String code2) {
this.code2 = code2;
}
public void setCode3(String code3) {
this.code3 = code3;
}
public void setCode4(String code4) {
this.code4 = code4;
}
@Override
public DictionaryItem getDictionaryItem(String locale) {
// Locale in this type of element aren't used
CorrelationImpl correlationImpl = new CorrelationImpl(this.code1, this.code2, this.code3, this.code3);
return correlationImpl;
}
}
| apache-2.0 |
opennetworkinglab/spring-open | src/main/java/net/onrc/onos/core/topology/web/serializers/TopologySerializer.java | 2217 | package net.onrc.onos.core.topology.web.serializers;
import java.io.IOException;
import net.onrc.onos.core.topology.Host;
import net.onrc.onos.core.topology.Link;
import net.onrc.onos.core.topology.Switch;
import net.onrc.onos.core.topology.MutableTopology;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.std.SerializerBase;
/**
* JSON serializer for Topology objects.
*/
public class TopologySerializer extends SerializerBase<MutableTopology> {
/**
* Default constructor.
*/
public TopologySerializer() {
super(MutableTopology.class);
}
/**
* Serializes a Topology object in JSON. The resulting JSON contains the
* switches, links and ports provided by the Topology object.
*
* @param mutableTopology the Topology that is being converted to JSON
* @param jsonGenerator generator to place the serialized JSON into
* @param serializerProvider unused but required for method override
* @throws IOException if the JSON serialization process fails
*/
@Override
public void serialize(MutableTopology mutableTopology,
JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException {
// Start the object
jsonGenerator.writeStartObject();
// Output the switches array
jsonGenerator.writeArrayFieldStart("switches");
for (final Switch swtch : mutableTopology.getSwitches()) {
jsonGenerator.writeObject(swtch);
}
jsonGenerator.writeEndArray();
// Output the links array
jsonGenerator.writeArrayFieldStart("links");
for (final Link link : mutableTopology.getLinks()) {
jsonGenerator.writeObject(link);
}
jsonGenerator.writeEndArray();
// Output the hosts array
jsonGenerator.writeArrayFieldStart("hosts");
for (final Host host : mutableTopology.getHosts()) {
jsonGenerator.writeObject(host);
}
jsonGenerator.writeEndArray();
// All done
jsonGenerator.writeEndObject();
}
}
| apache-2.0 |
kuangrewawa/onos | core/api/src/main/java/org/onosproject/net/DefaultNetwork.java | 4388 | /*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.net;
import static com.google.common.base.MoreObjects.toStringHelper;
import org.onosproject.net.provider.ProviderId;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
/**
* Default infrastructure network model implementation.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class DefaultNetwork extends AbstractElement implements Network {
private final NetworkId uuid;
private final String name;
private final Boolean adminStateUp;
private final String status;
private final Boolean shared;
private final String tenantID;
private final Boolean routerExternal;
private final String providerNetworkType;
private final String providerPhysicalNetwork;
private final String providerSegmentationID;
private final JsonNode subnets;
// For serialization
private DefaultNetwork() {
this.uuid = null;
this.name = null;
this.adminStateUp = null;
this.status = null;
this.shared = null;
this.tenantID = null;
this.routerExternal = null;
this.providerNetworkType = null;
this.providerPhysicalNetwork = null;
this.providerSegmentationID = null;
this.subnets = null;
}
/**
* Creates a network element attributed to the specified provider.
*
* @param providerId identity of the provider
*/
public DefaultNetwork(ProviderId providerId, NetworkId id, String name,
Boolean adminStateUp, String status, Boolean shared,
String tenantID, Boolean routerExternal, String providerNetworkType,
String providerPhysicalNetwork, String providerSegmentationID,
JsonNode subnets, Annotations... annotations) {
super(providerId, id, annotations);
this.uuid = id;
this.name = name;
this.adminStateUp = adminStateUp;
this.status = status;
this.shared = shared;
this.tenantID = tenantID;
this.routerExternal = routerExternal;
this.providerNetworkType = providerNetworkType;
this.providerPhysicalNetwork = providerPhysicalNetwork;
this.providerSegmentationID = providerSegmentationID;
this.subnets = subnets;
}
@Override
public String toString() {
return toStringHelper(this).add("id", uuid).add("name", name)
.add("adminStateUp", adminStateUp).add("status", status)
.add("shared", shared).add("tenantID", tenantID)
.add("routerExternal", routerExternal)
.add("providerNetworkType", providerNetworkType)
.add("providerPhysicalNetwork", providerPhysicalNetwork)
.add("providerSegmentationID", providerSegmentationID)
.toString();
}
@Override
public NetworkId id() {
return uuid;
}
@Override
public String name() {
return name;
}
@Override
public Boolean adminStateUp() {
return adminStateUp;
}
@Override
public String status() {
return status;
}
@Override
public Boolean shared() {
return shared;
}
@Override
public String tenantID() {
return tenantID;
}
@Override
public Boolean routerExternal() {
return routerExternal;
}
@Override
public String providerNetworkType() {
return providerNetworkType;
}
@Override
public String providerPhysicalNetwork() {
return providerPhysicalNetwork;
}
@Override
public String providerSegmentationID() {
return providerSegmentationID;
}
@Override
public JsonNode subnets() {
return subnets;
}
}
| apache-2.0 |
nextreports/nextreports-designer | src/ro/nextreports/designer/property/ImageChooser.java | 2269 | /*
* 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 ro.nextreports.designer.property;
import java.awt.Component;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import ro.nextreports.designer.Globals;
import ro.nextreports.designer.util.FileUtil;
import ro.nextreports.designer.util.I18NSupport;
import ro.nextreports.designer.util.ImagePreviewPanel;
import ro.nextreports.designer.util.file.ImageFilter;
public class ImageChooser {
public static String showDialog(Component parent, String title, String initialImage) {
JFileChooser fc = new JFileChooser();
ImagePreviewPanel previewPane = new ImagePreviewPanel();
fc.setAccessory(previewPane);
fc.addPropertyChangeListener(previewPane);
fc.setDialogTitle(I18NSupport.getString("image.title"));
fc.setAcceptAllFileFilterUsed(false);
fc.addChoosableFileFilter(new ImageFilter());
int returnVal = fc.showOpenDialog(Globals.getMainFrame());
if (returnVal == JFileChooser.APPROVE_OPTION) {
final File f = fc.getSelectedFile();
if (f != null) {
try {
FileUtil.copyToDir(f, new File(Globals.getCurrentReportAbsolutePath()).getParentFile(), true);
} catch (IOException e) {
e.printStackTrace();
}
return f.getName();
}
}
return null;
}
}
| apache-2.0 |
yurloc/drools | drools-core/src/main/java/org/drools/reteoo/ObjectSinkPropagator.java | 2071 | /*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.reteoo;
import java.io.Externalizable;
import org.drools.common.BaseNode;
import org.drools.common.InternalFactHandle;
import org.drools.common.InternalWorkingMemory;
import org.drools.common.RuleBasePartitionId;
import org.drools.spi.PropagationContext;
public interface ObjectSinkPropagator
extends
Externalizable {
public RuleBasePartitionId getPartitionId();
public void propagateAssertObject(InternalFactHandle factHandle,
PropagationContext context,
InternalWorkingMemory workingMemory);
public BaseNode getMatchingNode(BaseNode candidate);
public ObjectSink[] getSinks();
public int size();
public void propagateModifyObject(InternalFactHandle factHandle,
ModifyPreviousTuples modifyPreviousTuples,
PropagationContext context,
InternalWorkingMemory workingMemory);
public void byPassModifyToBetaNode (final InternalFactHandle factHandle,
final ModifyPreviousTuples modifyPreviousTuples,
final PropagationContext context,
final InternalWorkingMemory workingMemory);
public void doLinkRiaNode(InternalWorkingMemory wm);
public void doUnlinkRiaNode(InternalWorkingMemory wm);
}
| apache-2.0 |
nikita36078/J2ME-Loader | dexlib/src/main/java/com/android/dx/util/ByteArray.java | 9831 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.dx.util;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Wrapper for a {@code byte[]}, which provides read-only access and
* can "reveal" a partial slice of the underlying array.
*
* <b>Note:</b> Multibyte accessors all use big-endian order.
*/
public final class ByteArray {
/** {@code non-null;} underlying array */
private final byte[] bytes;
/** {@code >= 0}; start index of the slice (inclusive) */
private final int start;
/** {@code >= 0, <= bytes.length}; size computed as
* {@code end - start} (in the constructor) */
private final int size;
/**
* Constructs an instance.
*
* @param bytes {@code non-null;} the underlying array
* @param start {@code >= 0;} start index of the slice (inclusive)
* @param end {@code >= start, <= bytes.length;} end index of
* the slice (exclusive)
*/
public ByteArray(byte[] bytes, int start, int end) {
if (bytes == null) {
throw new NullPointerException("bytes == null");
}
if (start < 0) {
throw new IllegalArgumentException("start < 0");
}
if (end < start) {
throw new IllegalArgumentException("end < start");
}
if (end > bytes.length) {
throw new IllegalArgumentException("end > bytes.length");
}
this.bytes = bytes;
this.start = start;
this.size = end - start;
}
/**
* Constructs an instance from an entire {@code byte[]}.
*
* @param bytes {@code non-null;} the underlying array
*/
public ByteArray(byte[] bytes) {
this(bytes, 0, bytes.length);
}
/**
* Gets the size of the array, in bytes.
*
* @return {@code >= 0;} the size
*/
public int size() {
return size;
}
/**
* Returns a slice (that is, a sub-array) of this instance.
*
* @param start {@code >= 0;} start index of the slice (inclusive)
* @param end {@code >= start, <= size();} end index of
* the slice (exclusive)
* @return {@code non-null;} the slice
*/
public ByteArray slice(int start, int end) {
checkOffsets(start, end);
return new ByteArray(bytes, start + this.start, end + this.start);
}
/**
* Gets the {@code signed byte} value at a particular offset.
*
* @param off {@code >= 0, < size();} offset to fetch
* @return {@code signed byte} at that offset
*/
public int getByte(int off) {
checkOffsets(off, off + 1);
return getByte0(off);
}
/**
* Gets the {@code signed short} value at a particular offset.
*
* @param off {@code >= 0, < (size() - 1);} offset to fetch
* @return {@code signed short} at that offset
*/
public int getShort(int off) {
checkOffsets(off, off + 2);
return (getByte0(off) << 8) | getUnsignedByte0(off + 1);
}
/**
* Gets the {@code signed int} value at a particular offset.
*
* @param off {@code >= 0, < (size() - 3);} offset to fetch
* @return {@code signed int} at that offset
*/
public int getInt(int off) {
checkOffsets(off, off + 4);
return (getByte0(off) << 24) |
(getUnsignedByte0(off + 1) << 16) |
(getUnsignedByte0(off + 2) << 8) |
getUnsignedByte0(off + 3);
}
/**
* Gets the {@code signed long} value at a particular offset.
*
* @param off {@code >= 0, < (size() - 7);} offset to fetch
* @return {@code signed int} at that offset
*/
public long getLong(int off) {
checkOffsets(off, off + 8);
int part1 = (getByte0(off) << 24) |
(getUnsignedByte0(off + 1) << 16) |
(getUnsignedByte0(off + 2) << 8) |
getUnsignedByte0(off + 3);
int part2 = (getByte0(off + 4) << 24) |
(getUnsignedByte0(off + 5) << 16) |
(getUnsignedByte0(off + 6) << 8) |
getUnsignedByte0(off + 7);
return (part2 & 0xffffffffL) | ((long) part1) << 32;
}
/**
* Gets the {@code unsigned byte} value at a particular offset.
*
* @param off {@code >= 0, < size();} offset to fetch
* @return {@code unsigned byte} at that offset
*/
public int getUnsignedByte(int off) {
checkOffsets(off, off + 1);
return getUnsignedByte0(off);
}
/**
* Gets the {@code unsigned short} value at a particular offset.
*
* @param off {@code >= 0, < (size() - 1);} offset to fetch
* @return {@code unsigned short} at that offset
*/
public int getUnsignedShort(int off) {
checkOffsets(off, off + 2);
return (getUnsignedByte0(off) << 8) | getUnsignedByte0(off + 1);
}
/**
* Copies the contents of this instance into the given raw
* {@code byte[]} at the given offset. The given array must be
* large enough.
*
* @param out {@code non-null;} array to hold the output
* @param offset {@code non-null;} index into {@code out} for the first
* byte of output
*/
public void getBytes(byte[] out, int offset) {
if ((out.length - offset) < size) {
throw new IndexOutOfBoundsException("(out.length - offset) < " +
"size()");
}
System.arraycopy(bytes, start, out, offset, size);
}
/**
* Checks a range of offsets for validity, throwing if invalid.
*
* @param s start offset (inclusive)
* @param e end offset (exclusive)
*/
private void checkOffsets(int s, int e) {
if ((s < 0) || (e < s) || (e > size)) {
throw new IllegalArgumentException("bad range: " + s + ".." + e +
"; actual size " + size);
}
}
/**
* Gets the {@code signed byte} value at the given offset,
* without doing any argument checking.
*
* @param off offset to fetch
* @return byte at that offset
*/
private int getByte0(int off) {
return bytes[start + off];
}
/**
* Gets the {@code unsigned byte} value at the given offset,
* without doing any argument checking.
*
* @param off offset to fetch
* @return byte at that offset
*/
private int getUnsignedByte0(int off) {
return bytes[start + off] & 0xff;
}
/**
* Gets a {@code DataInputStream} that reads from this instance,
* with the cursor starting at the beginning of this instance's data.
* <b>Note:</b> The returned instance may be cast to {@link GetCursor}
* if needed.
*
* @return {@code non-null;} an appropriately-constructed
* {@code DataInputStream} instance
*/
public MyDataInputStream makeDataInputStream() {
return new MyDataInputStream(makeInputStream());
}
/**
* Gets a {@code InputStream} that reads from this instance,
* with the cursor starting at the beginning of this instance's data.
* <b>Note:</b> The returned instance may be cast to {@link GetCursor}
* if needed.
*
* @return {@code non-null;} an appropriately-constructed
* {@code InputStream} instancex
*/
public MyInputStream makeInputStream() {
return new MyInputStream();
}
/**
* Helper class for {@link #makeInputStream}, which implements the
* stream functionality.
*/
public class MyInputStream extends InputStream {
/** 0..size; the cursor */
private int cursor;
/** 0..size; the mark */
private int mark;
public MyInputStream() {
cursor = 0;
mark = 0;
}
@Override
public int read() throws IOException {
if (cursor >= size) {
return -1;
}
int result = getUnsignedByte0(cursor);
cursor++;
return result;
}
@Override
public int read(byte[] arr, int offset, int length) {
if ((offset + length) > arr.length) {
length = arr.length - offset;
}
int maxLength = size - cursor;
if (length > maxLength) {
length = maxLength;
}
System.arraycopy(bytes, cursor + start, arr, offset, length);
cursor += length;
return length;
}
@Override
public int available() {
return size - cursor;
}
@Override
public void mark(int reserve) {
mark = cursor;
}
@Override
public void reset() {
cursor = mark;
}
@Override
public boolean markSupported() {
return true;
}
}
/**
* Helper class for {@link #makeDataInputStream}. This is used
* simply so that the cursor of a wrapped {@link MyInputStream}
* instance may be easily determined.
*/
public static class MyDataInputStream extends DataInputStream {
public MyDataInputStream(MyInputStream wrapped) {
super(wrapped);
}
}
}
| apache-2.0 |
Xpitfire/ufo | UFO.Web/WebServiceClient/src/at/fhooe/hgb/wea5/ufo/web/generated/Artist.java | 5031 |
package at.fhooe.hgb.wea5.ufo.web.generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Artist complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Artist">
* <complexContent>
* <extension base="{http://ufo.at/}DomainObject">
* <sequence>
* <element name="ArtistId" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="Name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="EMail" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Category" type="{http://ufo.at/}Category" minOccurs="0"/>
* <element name="Country" type="{http://ufo.at/}Country" minOccurs="0"/>
* <element name="Picture" type="{http://ufo.at/}BlobData" minOccurs="0"/>
* <element name="PromoVideo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Artist", propOrder = {
"artistId",
"name",
"eMail",
"category",
"country",
"picture",
"promoVideo"
})
public class Artist
extends DomainObject
{
@XmlElement(name = "ArtistId")
protected int artistId;
@XmlElement(name = "Name")
protected String name;
@XmlElement(name = "EMail")
protected String eMail;
@XmlElement(name = "Category")
protected Category category;
@XmlElement(name = "Country")
protected Country country;
@XmlElement(name = "Picture")
protected BlobData picture;
@XmlElement(name = "PromoVideo")
protected String promoVideo;
/**
* Gets the value of the artistId property.
*
*/
public int getArtistId() {
return artistId;
}
/**
* Sets the value of the artistId property.
*
*/
public void setArtistId(int value) {
this.artistId = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the eMail property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEMail() {
return eMail;
}
/**
* Sets the value of the eMail property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEMail(String value) {
this.eMail = value;
}
/**
* Gets the value of the category property.
*
* @return
* possible object is
* {@link Category }
*
*/
public Category getCategory() {
return category;
}
/**
* Sets the value of the category property.
*
* @param value
* allowed object is
* {@link Category }
*
*/
public void setCategory(Category value) {
this.category = value;
}
/**
* Gets the value of the country property.
*
* @return
* possible object is
* {@link Country }
*
*/
public Country getCountry() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link Country }
*
*/
public void setCountry(Country value) {
this.country = value;
}
/**
* Gets the value of the picture property.
*
* @return
* possible object is
* {@link BlobData }
*
*/
public BlobData getPicture() {
return picture;
}
/**
* Sets the value of the picture property.
*
* @param value
* allowed object is
* {@link BlobData }
*
*/
public void setPicture(BlobData value) {
this.picture = value;
}
/**
* Gets the value of the promoVideo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPromoVideo() {
return promoVideo;
}
/**
* Sets the value of the promoVideo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPromoVideo(String value) {
this.promoVideo = value;
}
}
| apache-2.0 |
renovatedCore/tourist-routes | src/Collections/Linear/List/UnorderedList/DoubleLinkedUnorderedList.java | 2517 | package Collections.Linear.List.UnorderedList;
import Collections.Exception.ElementNotFoundException;
import Collections.Exception.EmptyCollectionException;
import Collections.Linear.Interfaces.UnorderedListADT;
import Collections.Linear.List.DoubleLinkedList;
import Collections.Node.BilinearNode;
/**
* Created by ivo on 22-11-2015.
*/
public class DoubleLinkedUnorderedList<T> extends DoubleLinkedList<T> implements UnorderedListADT<T> {
/**
* Add a new element to the front of the list
*
* @param element anything
*/
@Override
public void addToFront(T element) {
BilinearNode<T> temp = new BilinearNode(element);
if (this.isEmpty()) {
this.rear = temp;
} else {
this.front.setPrev(temp);
temp.setNext(this.front);
}
this.front = temp;
++this.size;
}
/**
* Add a new element to the rear of the list
*
* @param element anything
*/
@Override
public void addToRear(T element) {
BilinearNode<T> temp = new BilinearNode(element);
if (this.isEmpty()) {
this.front = temp;
} else {
temp.setPrev(this.rear);
this.rear.setNext(temp);
}
this.rear = temp;
++this.size;
}
/**
* Add a new element to next of the target
*
* @param element anything
* @param target the target element
*/
@Override
public void addAfter(T element, T target) throws ElementNotFoundException {
try {
if (this.contains(target)) {
BasicIterator<T> basicIterator = (BasicIterator<T>) this.iterator();
boolean found = false;
BilinearNode<T> prev = this.front;
while (basicIterator.hasNext() && found != true) {
prev = basicIterator.getCurrent();
if (basicIterator.next().equals(target)) {
found = true;
}
}
BilinearNode<T> newNode = new BilinearNode(element);
//The target next's will be the new one next's
newNode.setNext(prev.getNext());
//The target next's will be the newNode
prev.setNext(newNode);
} else throw new ElementNotFoundException("The target doesn't exist");
} catch (EmptyCollectionException e) {
System.out.println(e.getMessage());
}
}
}
| apache-2.0 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/vpn/vpnglobal_vpnsessionpolicy_binding.java | 12298 | /*
* Copyright (c) 2008-2015 Citrix Systems, 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.citrix.netscaler.nitro.resource.config.vpn;
import com.citrix.netscaler.nitro.resource.base.*;
import com.citrix.netscaler.nitro.service.nitro_service;
import com.citrix.netscaler.nitro.service.options;
import com.citrix.netscaler.nitro.util.*;
import com.citrix.netscaler.nitro.exception.nitro_exception;
class vpnglobal_vpnsessionpolicy_binding_response extends base_response
{
public vpnglobal_vpnsessionpolicy_binding[] vpnglobal_vpnsessionpolicy_binding;
}
/**
* Binding class showing the vpnsessionpolicy that can be bound to vpnglobal.
*/
public class vpnglobal_vpnsessionpolicy_binding extends base_resource
{
private String policyname;
private Long priority;
private String[] builtin;
private Boolean secondary;
private Boolean groupextraction;
private Long __count;
/**
* <pre>
* The priority of the policy.
* </pre>
*/
public void set_priority(long priority) throws Exception {
this.priority = new Long(priority);
}
/**
* <pre>
* The priority of the policy.
* </pre>
*/
public void set_priority(Long priority) throws Exception{
this.priority = priority;
}
/**
* <pre>
* The priority of the policy.
* </pre>
*/
public Long get_priority() throws Exception {
return this.priority;
}
/**
* <pre>
* Indicates that a variable is a built-in (SYSTEM INTERNAL) type.<br> Possible values = MODIFIABLE, DELETABLE, IMMUTABLE
* </pre>
*/
public void set_builtin(String[] builtin) throws Exception{
this.builtin = builtin;
}
/**
* <pre>
* Indicates that a variable is a built-in (SYSTEM INTERNAL) type.<br> Possible values = MODIFIABLE, DELETABLE, IMMUTABLE
* </pre>
*/
public String[] get_builtin() throws Exception {
return this.builtin;
}
/**
* <pre>
* The name of the policy.
* </pre>
*/
public void set_policyname(String policyname) throws Exception{
this.policyname = policyname;
}
/**
* <pre>
* The name of the policy.
* </pre>
*/
public String get_policyname() throws Exception {
return this.policyname;
}
/**
* <pre>
* Bind the authentication policy as the secondary policy to use in a two-factor configuration. A user must then authenticate not only to a primary authentication server but also to a secondary authentication server. User groups are aggregated across both authentication servers. The user name must be exactly the same on both authentication servers, but the authentication servers can require different passwords.
* </pre>
*/
public void set_secondary(boolean secondary) throws Exception {
this.secondary = new Boolean(secondary);
}
/**
* <pre>
* Bind the authentication policy as the secondary policy to use in a two-factor configuration. A user must then authenticate not only to a primary authentication server but also to a secondary authentication server. User groups are aggregated across both authentication servers. The user name must be exactly the same on both authentication servers, but the authentication servers can require different passwords.
* </pre>
*/
public void set_secondary(Boolean secondary) throws Exception{
this.secondary = secondary;
}
/**
* <pre>
* Bind the authentication policy as the secondary policy to use in a two-factor configuration. A user must then authenticate not only to a primary authentication server but also to a secondary authentication server. User groups are aggregated across both authentication servers. The user name must be exactly the same on both authentication servers, but the authentication servers can require different passwords.
* </pre>
*/
public Boolean get_secondary() throws Exception {
return this.secondary;
}
/**
* <pre>
* Bind the Authentication policy to a tertiary chain which will be used only for group extraction. The user will not authenticate against this server, and this will only be called it primary and/or secondary authentication has succeeded.
* </pre>
*/
public void set_groupextraction(boolean groupextraction) throws Exception {
this.groupextraction = new Boolean(groupextraction);
}
/**
* <pre>
* Bind the Authentication policy to a tertiary chain which will be used only for group extraction. The user will not authenticate against this server, and this will only be called it primary and/or secondary authentication has succeeded.
* </pre>
*/
public void set_groupextraction(Boolean groupextraction) throws Exception{
this.groupextraction = groupextraction;
}
/**
* <pre>
* Bind the Authentication policy to a tertiary chain which will be used only for group extraction. The user will not authenticate against this server, and this will only be called it primary and/or secondary authentication has succeeded.
* </pre>
*/
public Boolean get_groupextraction() throws Exception {
return this.groupextraction;
}
/**
* <pre>
* converts nitro response into object and returns the object array in case of get request.
* </pre>
*/
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{
vpnglobal_vpnsessionpolicy_binding_response result = (vpnglobal_vpnsessionpolicy_binding_response) service.get_payload_formatter().string_to_resource(vpnglobal_vpnsessionpolicy_binding_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
return result.vpnglobal_vpnsessionpolicy_binding;
}
/**
* <pre>
* Returns the value of object identifier argument
* </pre>
*/
protected String get_object_name() {
return null;
}
public static base_response add(nitro_service client, vpnglobal_vpnsessionpolicy_binding resource) throws Exception {
vpnglobal_vpnsessionpolicy_binding updateresource = new vpnglobal_vpnsessionpolicy_binding();
updateresource.policyname = resource.policyname;
updateresource.priority = resource.priority;
updateresource.secondary = resource.secondary;
updateresource.groupextraction = resource.groupextraction;
return updateresource.update_resource(client);
}
public static base_responses add(nitro_service client, vpnglobal_vpnsessionpolicy_binding resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
vpnglobal_vpnsessionpolicy_binding updateresources[] = new vpnglobal_vpnsessionpolicy_binding[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] = new vpnglobal_vpnsessionpolicy_binding();
updateresources[i].policyname = resources[i].policyname;
updateresources[i].priority = resources[i].priority;
updateresources[i].secondary = resources[i].secondary;
updateresources[i].groupextraction = resources[i].groupextraction;
}
result = update_bulk_request(client, updateresources);
}
return result;
}
public static base_response delete(nitro_service client, vpnglobal_vpnsessionpolicy_binding resource) throws Exception {
vpnglobal_vpnsessionpolicy_binding deleteresource = new vpnglobal_vpnsessionpolicy_binding();
deleteresource.policyname = resource.policyname;
deleteresource.secondary = resource.secondary;
deleteresource.groupextraction = resource.groupextraction;
return deleteresource.delete_resource(client);
}
public static base_responses delete(nitro_service client, vpnglobal_vpnsessionpolicy_binding resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
vpnglobal_vpnsessionpolicy_binding deleteresources[] = new vpnglobal_vpnsessionpolicy_binding[resources.length];
for (int i=0;i<resources.length;i++){
deleteresources[i] = new vpnglobal_vpnsessionpolicy_binding();
deleteresources[i].policyname = resources[i].policyname;
deleteresources[i].secondary = resources[i].secondary;
deleteresources[i].groupextraction = resources[i].groupextraction;
}
result = delete_bulk_request(client, deleteresources);
}
return result;
}
/**
* Use this API to fetch a vpnglobal_vpnsessionpolicy_binding resources.
*/
public static vpnglobal_vpnsessionpolicy_binding[] get(nitro_service service) throws Exception{
vpnglobal_vpnsessionpolicy_binding obj = new vpnglobal_vpnsessionpolicy_binding();
vpnglobal_vpnsessionpolicy_binding response[] = (vpnglobal_vpnsessionpolicy_binding[]) obj.get_resources(service);
return response;
}
/**
* Use this API to fetch filtered set of vpnglobal_vpnsessionpolicy_binding resources.
* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
*/
public static vpnglobal_vpnsessionpolicy_binding[] get_filtered(nitro_service service, String filter) throws Exception{
vpnglobal_vpnsessionpolicy_binding obj = new vpnglobal_vpnsessionpolicy_binding();
options option = new options();
option.set_filter(filter);
vpnglobal_vpnsessionpolicy_binding[] response = (vpnglobal_vpnsessionpolicy_binding[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to fetch filtered set of vpnglobal_vpnsessionpolicy_binding resources.
* set the filter parameter values in filtervalue object.
*/
public static vpnglobal_vpnsessionpolicy_binding[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{
vpnglobal_vpnsessionpolicy_binding obj = new vpnglobal_vpnsessionpolicy_binding();
options option = new options();
option.set_filter(filter);
vpnglobal_vpnsessionpolicy_binding[] response = (vpnglobal_vpnsessionpolicy_binding[]) obj.getfiltered(service, option);
return response;
}
/**
* Use this API to count vpnglobal_vpnsessionpolicy_binding resources configued on NetScaler.
*/
public static long count(nitro_service service) throws Exception{
vpnglobal_vpnsessionpolicy_binding obj = new vpnglobal_vpnsessionpolicy_binding();
options option = new options();
option.set_count(true);
vpnglobal_vpnsessionpolicy_binding response[] = (vpnglobal_vpnsessionpolicy_binding[]) obj.get_resources(service,option);
if (response != null) {
return response[0].__count;
}
return 0;
}
/**
* Use this API to count the filtered set of vpnglobal_vpnsessionpolicy_binding resources.
* filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
*/
public static long count_filtered(nitro_service service, String filter) throws Exception{
vpnglobal_vpnsessionpolicy_binding obj = new vpnglobal_vpnsessionpolicy_binding();
options option = new options();
option.set_count(true);
option.set_filter(filter);
vpnglobal_vpnsessionpolicy_binding[] response = (vpnglobal_vpnsessionpolicy_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
}
/**
* Use this API to count the filtered set of vpnglobal_vpnsessionpolicy_binding resources.
* set the filter parameter values in filtervalue object.
*/
public static long count_filtered(nitro_service service, filtervalue[] filter) throws Exception{
vpnglobal_vpnsessionpolicy_binding obj = new vpnglobal_vpnsessionpolicy_binding();
options option = new options();
option.set_count(true);
option.set_filter(filter);
vpnglobal_vpnsessionpolicy_binding[] response = (vpnglobal_vpnsessionpolicy_binding[]) obj.getfiltered(service, option);
if (response != null) {
return response[0].__count;
}
return 0;
}
public static class builtinEnum {
public static final String MODIFIABLE = "MODIFIABLE";
public static final String DELETABLE = "DELETABLE";
public static final String IMMUTABLE = "IMMUTABLE";
}
} | apache-2.0 |
anjlab/eclipse-tapestry5-plugin | com.anjlab.eclipse.tapestry5/src/com/anjlab/eclipse/tapestry5/TapestryContextScope.java | 710 | package com.anjlab.eclipse.tapestry5;
import org.eclipse.ui.IWorkbenchWindow;
public class TapestryContextScope
{
public final IWorkbenchWindow window;
public final TapestryProject project;
public final TapestryContext context;
public final TapestryComponentSpecification specification;
public TapestryContextScope(IWorkbenchWindow window,
TapestryProject project,
TapestryContext context,
TapestryComponentSpecification specification)
{
this.window = window;
this.project = project;
this.context = context;
this.specification = specification;
}
} | apache-2.0 |
new-x/study | chessboard/src/main/java/ru/job4j/Exceptions/ImposibleMoveException.java | 219 | package ru.job4j.Exceptions;
/**
* Created by aleks on 02.08.2017.
*/
public class ImposibleMoveException extends RuntimeException {
public ImposibleMoveException(String message){
super(message);
}
}
| apache-2.0 |
514840279/danyuan-application | src/main/java/org/danyuan/application/crawler/param/po/SysCrawlerRulerColumInfo.java | 7348 | package org.danyuan.application.crawler.param.po;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import org.danyuan.application.common.base.BaseEntity;
/**
* @文件名 SysCrawlerRulerColumInfo.java
* @包名 org.danyuan.application.crawler.param.po
* @描述 sys_crawler_ruler_colum_info的实体类
* @时间 2020年04月25日 08:00:23
* @author test
* @版本 V1.0
*/
@Entity
@Table(name = "sys_crawler_ruler_colum_info")
@NamedQuery(name = "SysCrawlerRulerColumInfo.findAll", query = "SELECT s FROM SysCrawlerRulerColumInfo s")
public class SysCrawlerRulerColumInfo extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
// 列名称
@Column(name = "colum_name")
private String columName;
// 规则id
@Column(name = "ruler_uuid")
private String rulerUuid;
// 拼接或替换的字符串
@Column(name = "param")
private String param;
//
@Column(name = "end",precision=10)
private Integer end;
// 2整型脚标
@Column(name = "spl2",precision=10)
private Integer spl2;
// split 1字符串
@Column(name = "spl1")
private String spl1;
//
@Column(name = "start",precision=10)
private Integer start;
// 取内容规则
@Column(name = "ruler")
private String ruler;
//
@Column(name = "param_new")
private String paramNew;
// 取一个 整型
@Column(name = "arr",precision=10)
private Integer arr;
// 上一层
@Column(name = "parent_uuid")
private String parentUuid;
// apand 方式 字符
@Column(name = "app1")
private String app1;
// 处理方式
@Column(name = "type")
private String type;
//
@Column(name = "md5flag")
private String md5flag;
// apand 字符
@Column(name = "app2")
private String app2;
/**
* 构造方法:
* 描 述: 默认构造函数
* 参 数:
* 作 者 : test
* @throws
*/
public SysCrawlerRulerColumInfo() {
super();
}
/**
* 方法名 : getColumName
* 功 能 : 返回变量 columName 列名称 的值
*
* @return: String
*/
public String getColumName() {
return columName;
}
/**
* 方法名 : setColumName
* 功 能 : 设置变量 columName 列名称 的值
*/
public void setColumName( String columName) {
this.columName = columName;
}
/**
* 方法名 : getRulerUuid
* 功 能 : 返回变量 rulerUuid 规则id 的值
*
* @return: String
*/
public String getRulerUuid() {
return rulerUuid;
}
/**
* 方法名 : setRulerUuid
* 功 能 : 设置变量 rulerUuid 规则id 的值
*/
public void setRulerUuid( String rulerUuid) {
this.rulerUuid = rulerUuid;
}
/**
* 方法名 : getParam
* 功 能 : 返回变量 param 拼接或替换的字符串 的值
*
* @return: String
*/
public String getParam() {
return param;
}
/**
* 方法名 : setParam
* 功 能 : 设置变量 param 拼接或替换的字符串 的值
*/
public void setParam( String param) {
this.param = param;
}
/**
* 方法名 : getEnd
* 功 能 : 返回变量 end 的值
*
* @return: String
*/
public Integer getEnd() {
return end;
}
/**
* 方法名 : setEnd
* 功 能 : 设置变量 end 的值
*/
public void setEnd( Integer end) {
this.end = end;
}
/**
* 方法名 : getSpl2
* 功 能 : 返回变量 spl2 2整型脚标 的值
*
* @return: String
*/
public Integer getSpl2() {
return spl2;
}
/**
* 方法名 : setSpl2
* 功 能 : 设置变量 spl2 2整型脚标 的值
*/
public void setSpl2( Integer spl2) {
this.spl2 = spl2;
}
/**
* 方法名 : getSpl1
* 功 能 : 返回变量 spl1 split 1字符串 的值
*
* @return: String
*/
public String getSpl1() {
return spl1;
}
/**
* 方法名 : setSpl1
* 功 能 : 设置变量 spl1 split 1字符串 的值
*/
public void setSpl1( String spl1) {
this.spl1 = spl1;
}
/**
* 方法名 : getStart
* 功 能 : 返回变量 start 的值
*
* @return: String
*/
public Integer getStart() {
return start;
}
/**
* 方法名 : setStart
* 功 能 : 设置变量 start 的值
*/
public void setStart( Integer start) {
this.start = start;
}
/**
* 方法名 : getRuler
* 功 能 : 返回变量 ruler 取内容规则 的值
*
* @return: String
*/
public String getRuler() {
return ruler;
}
/**
* 方法名 : setRuler
* 功 能 : 设置变量 ruler 取内容规则 的值
*/
public void setRuler( String ruler) {
this.ruler = ruler;
}
/**
* 方法名 : getParamNew
* 功 能 : 返回变量 paramNew 的值
*
* @return: String
*/
public String getParamNew() {
return paramNew;
}
/**
* 方法名 : setParamNew
* 功 能 : 设置变量 paramNew 的值
*/
public void setParamNew( String paramNew) {
this.paramNew = paramNew;
}
/**
* 方法名 : getArr
* 功 能 : 返回变量 arr 取一个 整型 的值
*
* @return: String
*/
public Integer getArr() {
return arr;
}
/**
* 方法名 : setArr
* 功 能 : 设置变量 arr 取一个 整型 的值
*/
public void setArr( Integer arr) {
this.arr = arr;
}
/**
* 方法名 : getParentUuid
* 功 能 : 返回变量 parentUuid 上一层 的值
*
* @return: String
*/
public String getParentUuid() {
return parentUuid;
}
/**
* 方法名 : setParentUuid
* 功 能 : 设置变量 parentUuid 上一层 的值
*/
public void setParentUuid( String parentUuid) {
this.parentUuid = parentUuid;
}
/**
* 方法名 : getApp1
* 功 能 : 返回变量 app1 apand 方式 字符 的值
*
* @return: String
*/
public String getApp1() {
return app1;
}
/**
* 方法名 : setApp1
* 功 能 : 设置变量 app1 apand 方式 字符 的值
*/
public void setApp1( String app1) {
this.app1 = app1;
}
/**
* 方法名 : getType
* 功 能 : 返回变量 type 处理方式 的值
*
* @return: String
*/
public String getType() {
return type;
}
/**
* 方法名 : setType
* 功 能 : 设置变量 type 处理方式 的值
*/
public void setType( String type) {
this.type = type;
}
/**
* 方法名 : getMd5flag
* 功 能 : 返回变量 md5flag 的值
*
* @return: String
*/
public String getMd5flag() {
return md5flag;
}
/**
* 方法名 : setMd5flag
* 功 能 : 设置变量 md5flag 的值
*/
public void setMd5flag( String md5flag) {
this.md5flag = md5flag;
}
/**
* 方法名 : getApp2
* 功 能 : 返回变量 app2 apand 字符 的值
*
* @return: String
*/
public String getApp2() {
return app2;
}
/**
* 方法名 : setApp2
* 功 能 : 设置变量 app2 apand 字符 的值
*/
public void setApp2( String app2) {
this.app2 = app2;
}
}
| apache-2.0 |
lijunyandev/MeetMusic | app/src/main/java/com/lijunyan/blackmusic/adapter/FolderAdapter.java | 3811 | package com.lijunyan.blackmusic.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.lijunyan.blackmusic.R;
import com.lijunyan.blackmusic.database.DBManager;
import com.lijunyan.blackmusic.entity.FolderInfo;
import java.util.List;
/**
* Created by lijunyan on 2017/3/11.
*/
public class FolderAdapter extends RecyclerView.Adapter<FolderAdapter.ViewHolder> {
private static final String TAG = FolderAdapter.class.getName();
private List<FolderInfo> folderInfoList;
private Context context;
private DBManager dbManager;
private FolderAdapter.OnItemClickListener onItemClickListener;
public FolderAdapter(Context context, List<FolderInfo> folderInfoList) {
this.context = context;
this.folderInfoList = folderInfoList;
this.dbManager = DBManager.getInstance(context);
}
static class ViewHolder extends RecyclerView.ViewHolder {
View swipeContent;
LinearLayout contentLl;
ImageView folderIv;
TextView folderName;
TextView count;
// Button deleteBtn;
public ViewHolder(View itemView) {
super(itemView);
this.swipeContent = (View) itemView.findViewById(R.id.model_swipemenu_layout);
this.contentLl = (LinearLayout) itemView.findViewById(R.id.model_music_item_ll);
this.folderIv = (ImageView) itemView.findViewById(R.id.model_head_iv);
this.folderName = (TextView) itemView.findViewById(R.id.model_item_name);
this.count = (TextView) itemView.findViewById(R.id.model_music_count);
// this.deleteBtn = (Button) itemView.findViewById(R.id.model_swip_delete_menu_btn);
}
}
@Override
public FolderAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.local_model_rv_item, parent, false);
FolderAdapter.ViewHolder viewHolder = new FolderAdapter.ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(final FolderAdapter.ViewHolder holder, final int position) {
Log.d("aaaa", "onBindViewHolder: position = " + position);
FolderInfo folder = folderInfoList.get(position);
holder.folderIv.setImageResource(R.drawable.folder);
holder.folderName.setText(folder.getName());
holder.count.setText("" + folder.getCount()+"首"+folder.getPath());
holder.contentLl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickListener.onContentClick(holder.contentLl, position);
}
});
// holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// onItemClickListener.onDeleteMenuClick(holder.swipeContent, position);
// }
// });
}
@Override
public int getItemCount() {
return folderInfoList.size();
}
public void update(List<FolderInfo> folderInfoList) {
this.folderInfoList.clear();
this.folderInfoList.addAll(folderInfoList);
notifyDataSetChanged();
}
public interface OnItemClickListener {
void onDeleteMenuClick(View content, int position);
void onContentClick(View content, int position);
}
public void setOnItemClickListener(FolderAdapter.OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
}
| apache-2.0 |
BUPTAnderson/apache-hive-2.1.1-src | ql/src/java/org/apache/hadoop/hive/ql/optimizer/RedundantDynamicPruningConditionsRemoval.java | 9232 | /**
* 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.hive.ql.optimizer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.calcite.util.Pair;
import org.apache.hadoop.hive.ql.exec.FilterOperator;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
import org.apache.hadoop.hive.ql.lib.DefaultGraphWalker;
import org.apache.hadoop.hive.ql.lib.DefaultRuleDispatcher;
import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.lib.GraphWalker;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.lib.NodeProcessor;
import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx;
import org.apache.hadoop.hive.ql.lib.Rule;
import org.apache.hadoop.hive.ql.lib.RuleRegExp;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.parse.ParseContext;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDescUtils;
import org.apache.hadoop.hive.ql.plan.ExprNodeDynamicListDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.plan.FilterDesc;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBaseCompare;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFIn;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
/**
* Takes a Filter operator on top of a TableScan and removes dynamic pruning conditions
* if static partition pruning has been triggered already.
*
* This transformation is executed when CBO is on and hence we can guarantee that the filtering
* conditions on the partition columns will be immediately on top of the TableScan operator.
*
*/
public class RedundantDynamicPruningConditionsRemoval extends Transform {
private static final Logger LOG = LoggerFactory.getLogger(RedundantDynamicPruningConditionsRemoval.class);
/**
* Transform the query tree.
*
* @param pctx the current parse context
*/
@Override
public ParseContext transform(ParseContext pctx) throws SemanticException {
Map<Rule, NodeProcessor> opRules = new LinkedHashMap<Rule, NodeProcessor>();
opRules.put(new RuleRegExp("R1", TableScanOperator.getOperatorName() + "%" +
FilterOperator.getOperatorName() + "%"), new FilterTransformer());
Dispatcher disp = new DefaultRuleDispatcher(null, opRules, null);
GraphWalker ogw = new DefaultGraphWalker(disp);
List<Node> topNodes = new ArrayList<Node>();
topNodes.addAll(pctx.getTopOps().values());
ogw.startWalking(topNodes, null);
return pctx;
}
private class FilterTransformer implements NodeProcessor {
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx, Object... nodeOutputs)
throws SemanticException {
FilterOperator filter = (FilterOperator) nd;
FilterDesc desc = filter.getConf();
TableScanOperator ts = (TableScanOperator) stack.get(stack.size() - 2);
// collect
CollectContext removalContext = new CollectContext();
collect(desc.getPredicate(), removalContext);
CollectContext tsRemovalContext = new CollectContext();
collect(ts.getConf().getFilterExpr(), tsRemovalContext);
for (Pair<ExprNodeDesc,ExprNodeDesc> pair : removalContext.dynamicListNodes) {
ExprNodeDesc child = pair.left;
ExprNodeDesc columnDesc = child.getChildren().get(0);
assert child.getChildren().get(1) instanceof ExprNodeDynamicListDesc;
ExprNodeDesc parent = pair.right;
String column = ExprNodeDescUtils.extractColName(columnDesc);
if (column != null) {
Table table = ts.getConf().getTableMetadata();
boolean generate = false;
if (table != null && table.isPartitionKey(column)) {
generate = true;
for (ExprNodeDesc filterColumnDesc : removalContext.comparatorNodes) {
if (columnDesc.isSame(filterColumnDesc)) {
generate = false;
break;
}
}
}
if (!generate) {
// We can safely remove the condition by replacing it with "true"
ExprNodeDesc constNode = new ExprNodeConstantDesc(TypeInfoFactory.booleanTypeInfo, Boolean.TRUE);
if (parent == null) {
desc.setPredicate(constNode);
} else {
int i = parent.getChildren().indexOf(child);
parent.getChildren().remove(i);
parent.getChildren().add(i, constNode);
}
// We remove it from the TS too if it was pushed
for (Pair<ExprNodeDesc,ExprNodeDesc> tsPair : tsRemovalContext.dynamicListNodes) {
ExprNodeDesc tsChild = tsPair.left;
ExprNodeDesc tsParent = tsPair.right;
if (tsChild.isSame(child)) {
if (tsParent == null) {
ts.getConf().setFilterExpr(null);
} else {
int i = tsParent.getChildren().indexOf(tsChild);
if (i != -1) {
tsParent.getChildren().remove(i);
tsParent.getChildren().add(i, constNode);
}
}
break;
}
}
if (LOG.isInfoEnabled()) {
LOG.info("Dynamic pruning condition removed: " + child);
}
}
}
}
return false;
}
}
private static void collect(ExprNodeDesc pred, CollectContext listContext) {
collect(null, pred, listContext);
}
private static void collect(ExprNodeDesc parent, ExprNodeDesc child, CollectContext listContext) {
if (child instanceof ExprNodeGenericFuncDesc &&
((ExprNodeGenericFuncDesc)child).getGenericUDF() instanceof GenericUDFIn) {
if (child.getChildren().get(1) instanceof ExprNodeDynamicListDesc) {
listContext.dynamicListNodes.add(new Pair<ExprNodeDesc,ExprNodeDesc>(child, parent));
}
return;
}
if (child instanceof ExprNodeGenericFuncDesc &&
((ExprNodeGenericFuncDesc)child).getGenericUDF() instanceof GenericUDFBaseCompare &&
child.getChildren().size() == 2) {
ExprNodeDesc leftCol = child.getChildren().get(0);
ExprNodeDesc rightCol = child.getChildren().get(1);
ExprNodeColumnDesc leftColDesc = ExprNodeDescUtils.getColumnExpr(leftCol);
if (leftColDesc != null) {
boolean rightConstant = false;
if (rightCol instanceof ExprNodeConstantDesc) {
rightConstant = true;
} else if (rightCol instanceof ExprNodeGenericFuncDesc) {
ExprNodeDesc foldedExpr = ConstantPropagateProcFactory.foldExpr((ExprNodeGenericFuncDesc)rightCol);
rightConstant = foldedExpr != null;
}
if (rightConstant) {
listContext.comparatorNodes.add(leftColDesc);
}
} else {
ExprNodeColumnDesc rightColDesc = ExprNodeDescUtils.getColumnExpr(rightCol);
if (rightColDesc != null) {
boolean leftConstant = false;
if (leftCol instanceof ExprNodeConstantDesc) {
leftConstant = true;
} else if (leftCol instanceof ExprNodeGenericFuncDesc) {
ExprNodeDesc foldedExpr = ConstantPropagateProcFactory.foldExpr((ExprNodeGenericFuncDesc)leftCol);
leftConstant = foldedExpr != null;
}
if (leftConstant) {
listContext.comparatorNodes.add(rightColDesc);
}
}
}
return;
}
if (FunctionRegistry.isOpAnd(child)) {
for (ExprNodeDesc newChild : child.getChildren()) {
collect(child, newChild, listContext);
}
}
}
private class CollectContext implements NodeProcessorCtx {
private final List<Pair<ExprNodeDesc,ExprNodeDesc>> dynamicListNodes;
private final List<ExprNodeDesc> comparatorNodes;
public CollectContext() {
this.dynamicListNodes = Lists.<Pair<ExprNodeDesc,ExprNodeDesc>>newArrayList();
this.comparatorNodes = Lists.<ExprNodeDesc>newArrayList();
}
}
}
| apache-2.0 |
Blazebit/blaze-data | src/test/java/com/blazebit/data/importer/DataImporterTest.java | 3019 | /*
* Copyright 2011 Blazebit
*/
package com.blazebit.data.importer;
import java.io.File;
import org.junit.After;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.blazebit.data.cfg.Configuration;
import com.blazebit.data.importer.provider.CsvDataProvider;
import com.blazebit.data.importer.storage.JPADataStorage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
/**
*
* @author Christian Beikov
*/
public class DataImporterTest {
private static final Logger log = Logger.getLogger(DataImporterTest.class.getName());
private DataImporter importer;
private EntityManagerFactory fact;
private EntityManager session;
private DataStorage storage;
private boolean commit = false;
// @Before
public void setUp() {
fact = Persistence.createEntityManagerFactory("BlazebitTest");
session = fact.createEntityManager();
File configFile = new File(new File("").getAbsolutePath(), "src/main/resources/dataConfig.xml");
File dataDir = new File(new File("").getAbsolutePath(), "src/main/resources/com/blazebit/web/cms/core/model/data/");
storage = new JPADataStorage(session);
importer = new Configuration(configFile).buildImporter(storage);
try {
if (dataDir.isDirectory()) {
for (File f : dataDir.listFiles()) {
if (f.getName().endsWith(".csv")) {
importer.add(new CsvDataProvider(f));
}
}
}
} catch (Exception ex) {
log.log(Level.SEVERE, ex.getMessage(), ex);
throw new RuntimeException(ex);
}
}
// @After
public void tearDown() {
if (fact != null) {
fact.close();
}
}
/**
* Test of getObjects method, of class GenericObjectGenerator.
*/
// @Test
public void testGetObjects() {
EntityTransaction tx = null;
try {
tx = session.getTransaction();
tx.begin();
importer.generateObjects();
storage.flush();
if (commit) {
tx.commit();
} else {
tx.rollback();
}
log.info("Successfully generated objects!");
} catch (Throwable t) {
log.log(Level.SEVERE, t.getMessage(), t);
fail(t.getMessage());
if (tx != null) {
tx.rollback();
}
} finally {
if (session != null) {
session.close();
}
}
}
public static void main(String[] args) {
DataImporterTest test = new DataImporterTest();
test.commit = true;
test.setUp();
test.testGetObjects();
test.tearDown();
}
}
| apache-2.0 |
spencergibb/halfpipe | halfpipe-properties/src/main/java/halfpipe/properties/StringToDynaPropConverter.java | 2815 | package halfpipe.properties;
import com.google.common.base.Throwables;
import org.springframework.core.ResolvableType;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Set;
/**
* User: spencergibb
* Date: 12/12/13
* Time: 5:38 PM
*/
public class StringToDynaPropConverter implements ConditionalGenericConverter {
private Field resolvableType;
private ConversionService conversionService;
public StringToDynaPropConverter(ConversionService conversionService) {
System.out.println("converter");
this.conversionService = conversionService;
try {
//FIXME: avoid reflection?
resolvableType = TypeDescriptor.class.getDeclaredField("resolvableType");
} catch (NoSuchFieldException e) {
Throwables.propagate(e);
}
resolvableType.setAccessible(true);
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(String.class, DynaProp.class));
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
try {
TypeDescriptor generic = getGenericType(getResolvableType(targetType));
return this.conversionService.canConvert(sourceType, generic);
} catch (Exception e) {
e.printStackTrace(); //TODO: implement catch
}
return false;
}
private TypeDescriptor getGenericType(ResolvableType targetType) throws NoSuchFieldException, IllegalAccessException {
ResolvableType generic = targetType.getGeneric(0);
return TypeDescriptor.valueOf(generic.getRawClass());
}
private ResolvableType getResolvableType(TypeDescriptor targetType) throws IllegalAccessException {
return (ResolvableType) resolvableType.get(targetType);
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
try {
ResolvableType tgtResolvableType = getResolvableType(targetType);
TypeDescriptor typeDescriptor = getGenericType(tgtResolvableType);
//TODO: discover propName
String propName = "hello.defaultMessage";
//TODO: discover defaultValue
Object defaultValue = conversionService.convert(source, sourceType, typeDescriptor);
return new DynamicProp(propName, defaultValue);
} catch (Exception e) {
Throwables.propagate(e);
}
return null;
}
}
| apache-2.0 |
vjanmey/EpicMudfia | com/planet_ink/coffee_mud/Races/Robin.java | 2589 | package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2014 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Robin extends Bird
{
@Override public String ID(){ return "Robin"; }
@Override public String name(){ return "Robin"; }
@Override public String racialCategory(){return "Avian";}
// an ey ea he ne ar ha to le fo no gi mo wa ta wi
private static final int[] parts={0 ,2 ,2 ,1 ,1 ,0 ,0 ,1 ,2 ,2 ,1 ,0 ,1 ,1 ,1 ,2 };
@Override public int[] bodyMask(){return parts;}
protected static Vector<RawMaterial> resources=new Vector<RawMaterial>();
@Override
public List<RawMaterial> myResources()
{
synchronized(resources)
{
if(resources.size()==0)
{
resources.addElement(makeResource
("a pair of "+name().toLowerCase()+" feet",RawMaterial.RESOURCE_BONE));
resources.addElement(makeResource
("some "+name().toLowerCase()+" feathers",RawMaterial.RESOURCE_FEATHERS));
resources.addElement(makeResource
("some "+name().toLowerCase()+" meat",RawMaterial.RESOURCE_POULTRY));
resources.addElement(makeResource
("some "+name().toLowerCase()+" blood",RawMaterial.RESOURCE_BLOOD));
resources.addElement(makeResource
("a pile of "+name().toLowerCase()+" bones",RawMaterial.RESOURCE_BONE));
}
}
return resources;
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | examples/adwords_axis/src/main/java/adwords/axis/v201506/basicoperations/GetCampaigns.java | 3383 | // Copyright 2015 Google Inc. 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 adwords.axis.v201506.basicoperations;
import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.utils.v201506.SelectorBuilder;
import com.google.api.ads.adwords.axis.v201506.cm.Campaign;
import com.google.api.ads.adwords.axis.v201506.cm.CampaignPage;
import com.google.api.ads.adwords.axis.v201506.cm.CampaignServiceInterface;
import com.google.api.ads.adwords.axis.v201506.cm.Selector;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.adwords.lib.selectorfields.v201506.cm.CampaignField;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;
/**
* This example gets all campaigns. To add a campaign, run AddCampaign.java.
*
* <p>Credentials and properties in {@code fromFile()} are pulled from the
* "ads.properties" file. See README for more info.
*/
public class GetCampaigns {
private static final int PAGE_SIZE = 100;
public static void main(String[] args) throws Exception {
// Generate a refreshable OAuth2 credential.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.ADWORDS)
.fromFile()
.build()
.generateCredential();
// Construct an AdWordsSession.
AdWordsSession session = new AdWordsSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
AdWordsServices adWordsServices = new AdWordsServices();
runExample(adWordsServices, session);
}
public static void runExample(
AdWordsServices adWordsServices, AdWordsSession session) throws Exception {
// Get the CampaignService.
CampaignServiceInterface campaignService =
adWordsServices.get(session, CampaignServiceInterface.class);
int offset = 0;
// Create selector.
SelectorBuilder builder = new SelectorBuilder();
Selector selector = builder
.fields(CampaignField.Id, CampaignField.Name)
.orderAscBy(CampaignField.Name)
.offset(offset)
.limit(PAGE_SIZE)
.build();
CampaignPage page = null;
do {
// Get all campaigns.
page = campaignService.get(selector);
// Display campaigns.
if (page.getEntries() != null) {
for (Campaign campaign : page.getEntries()) {
System.out.printf("Campaign with name '%s' and ID %d was found.%n", campaign.getName(),
campaign.getId());
}
} else {
System.out.println("No campaigns were found.");
}
offset += PAGE_SIZE;
selector = builder.increaseOffsetBy(PAGE_SIZE).build();
} while (offset < page.getTotalNumEntries());
}
}
| apache-2.0 |
lmira1/EK-PDT-18 | EK-addressbook-java-tests/src/com/example/tests/TestFolderCreation.java | 1715 | package com.example.tests;
import java.util.List;
import org.testng.annotations.Test;
import com.example.fw.Folders;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
public class TestFolderCreation extends TestBase {
@Test
public void testFolderCreation(){
String folder = "newfolder";
Folders oldFolders = app.getFolderHelper().getFolders();
app.getFolderHelper().createFolder(folder);
Folders newFolders = app.getFolderHelper().getFolders();
assertThat(newFolders, equalTo(oldFolders.withAdded(folder)));
}
@Test
public void testVariousFoldersCreation(){
String folder1 = "newfolder1";
String folder2 = "newfolder2";
Folders oldFolders = app.getFolderHelper().getFolders();
assertThat(app.getFolderHelper().createFolder(folder1), is(nullValue()));
Folders newFolders = app.getFolderHelper().getFolders();
assertThat(newFolders, equalTo(oldFolders.withAdded(folder1)));
assertThat(app.getFolderHelper().createFolder(folder2), is(nullValue()));
Folders newFolders2 = app.getFolderHelper().getFolders();
assertThat(newFolders2, equalTo(newFolders.withAdded(folder2)));
}
@Test
public void testFoldersWithSameNameCreation(){
String folder = "newfolder3";
Folders oldFolders = app.getFolderHelper().getFolders();
assertThat(app.getFolderHelper().createFolder(folder), is(nullValue()));
Folders newFolders = app.getFolderHelper().getFolders();
assertThat(newFolders, equalTo(oldFolders.withAdded(folder)));
assertThat(app.getFolderHelper().createFolder(folder), containsString("Duplicated folder name"));
Folders newFolders2 = app.getFolderHelper().getFolders();
assertThat(newFolders2, equalTo(newFolders));
}
}
| apache-2.0 |
51wakeup/wakeup-qcloud-sdk | src/main/java/com/wakeup/qcloud/listener/UrlParamDO.java | 1416 | package com.wakeup.qcloud.listener;
import com.alibaba.fastjson.annotation.JSONField;
import com.wakeup.qcloud.constant.OptPlatform;
import com.wakeup.qcloud.domain.BaseDO;
/**
* @since 2017年2月24日
* @author kalman03
*/
public class UrlParamDO extends BaseDO {
private static final long serialVersionUID = -7817364903524183026L;
@JSONField(name = "SdkAppid")
private String sdkAppid;
@JSONField(name = "CallbackCommand")
private String callbackCommond;
@JSONField(name = "contenttype")
private String contentType;
@JSONField(name = "ClientIP")
private String clientIp;
/**
* {@link OptPlatform}
*/
@JSONField(name = "OptPlatform")
private String optPlatform;
public String getSdkAppid() {
return sdkAppid;
}
public void setSdkAppid(String sdkAppid) {
this.sdkAppid = sdkAppid;
}
public String getCallbackCommond() {
return callbackCommond;
}
public void setCallbackCommond(String callbackCommond) {
this.callbackCommond = callbackCommond;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public String getOptPlatform() {
return optPlatform;
}
public void setOptPlatform(String optPlatform) {
this.optPlatform = optPlatform;
}
}
| apache-2.0 |
spring-projects/spring-security | core/src/main/java/org/springframework/security/converter/RsaKeyConverters.java | 7627 | /*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.converter;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert;
/**
* Used for creating {@link java.security.Key} converter instances
*
* @author Josh Cummings
* @author Shazin Sadakath
* @since 5.2
*/
public final class RsaKeyConverters {
private static final String DASHES = "-----";
private static final String PKCS8_PEM_HEADER = DASHES + "BEGIN PRIVATE KEY" + DASHES;
private static final String PKCS8_PEM_FOOTER = DASHES + "END PRIVATE KEY" + DASHES;
private static final String X509_PEM_HEADER = DASHES + "BEGIN PUBLIC KEY" + DASHES;
private static final String X509_PEM_FOOTER = DASHES + "END PUBLIC KEY" + DASHES;
private static final String X509_CERT_HEADER = DASHES + "BEGIN CERTIFICATE" + DASHES;
private static final String X509_CERT_FOOTER = DASHES + "END CERTIFICATE" + DASHES;
private RsaKeyConverters() {
}
/**
* Construct a {@link Converter} for converting a PEM-encoded PKCS#8 RSA Private Key
* into a {@link RSAPrivateKey}.
*
* Note that keys are often formatted in PKCS#1 and this can easily be identified by
* the header. If the key file begins with "-----BEGIN RSA PRIVATE KEY-----", then it
* is PKCS#1. If it is PKCS#8 formatted, then it begins with "-----BEGIN PRIVATE
* KEY-----".
*
* This converter does not close the {@link InputStream} in order to avoid making
* non-portable assumptions about the streams' origin and further use.
* @return A {@link Converter} that can read a PEM-encoded PKCS#8 RSA Private Key and
* return a {@link RSAPrivateKey}.
*/
public static Converter<InputStream, RSAPrivateKey> pkcs8() {
KeyFactory keyFactory = rsaFactory();
return (source) -> {
List<String> lines = readAllLines(source);
Assert.isTrue(!lines.isEmpty() && lines.get(0).startsWith(PKCS8_PEM_HEADER),
"Key is not in PEM-encoded PKCS#8 format, please check that the header begins with "
+ PKCS8_PEM_HEADER);
StringBuilder base64Encoded = new StringBuilder();
for (String line : lines) {
if (RsaKeyConverters.isNotPkcs8Wrapper(line)) {
base64Encoded.append(line);
}
}
byte[] pkcs8 = Base64.getDecoder().decode(base64Encoded.toString());
try {
return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8));
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
};
}
/**
* Construct a {@link Converter} for converting a PEM-encoded X.509 RSA Public Key or
* X.509 Certificate into a {@link RSAPublicKey}.
*
* This converter does not close the {@link InputStream} in order to avoid making
* non-portable assumptions about the streams' origin and further use.
* @return A {@link Converter} that can read a PEM-encoded X.509 RSA Public Key and
* return a {@link RSAPublicKey}.
*/
public static Converter<InputStream, RSAPublicKey> x509() {
X509PemDecoder pemDecoder = new X509PemDecoder(rsaFactory());
X509CertificateDecoder certDecoder = new X509CertificateDecoder(x509CertificateFactory());
return (source) -> {
List<String> lines = readAllLines(source);
Assert.notEmpty(lines, "Input stream is empty");
String encodingHint = lines.get(0);
Converter<List<String>, RSAPublicKey> decoder = encodingHint.startsWith(X509_PEM_HEADER) ? pemDecoder
: encodingHint.startsWith(X509_CERT_HEADER) ? certDecoder : null;
Assert.notNull(decoder,
"Key is not in PEM-encoded X.509 format or a valid X.509 certificate, please check that the header begins with "
+ X509_PEM_HEADER + " or " + X509_CERT_HEADER);
return decoder.convert(lines);
};
}
private static CertificateFactory x509CertificateFactory() {
try {
return CertificateFactory.getInstance("X.509");
}
catch (CertificateException ex) {
throw new IllegalArgumentException(ex);
}
}
private static List<String> readAllLines(InputStream source) {
BufferedReader reader = new BufferedReader(new InputStreamReader(source));
return reader.lines().collect(Collectors.toList());
}
private static KeyFactory rsaFactory() {
try {
return KeyFactory.getInstance("RSA");
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException(ex);
}
}
private static boolean isNotPkcs8Wrapper(String line) {
return !PKCS8_PEM_HEADER.equals(line) && !PKCS8_PEM_FOOTER.equals(line);
}
private static class X509PemDecoder implements Converter<List<String>, RSAPublicKey> {
private final KeyFactory keyFactory;
X509PemDecoder(KeyFactory keyFactory) {
this.keyFactory = keyFactory;
}
@Override
@NonNull
public RSAPublicKey convert(List<String> lines) {
StringBuilder base64Encoded = new StringBuilder();
for (String line : lines) {
if (isNotX509PemWrapper(line)) {
base64Encoded.append(line);
}
}
byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString());
try {
return (RSAPublicKey) this.keyFactory.generatePublic(new X509EncodedKeySpec(x509));
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
private boolean isNotX509PemWrapper(String line) {
return !X509_PEM_HEADER.equals(line) && !X509_PEM_FOOTER.equals(line);
}
}
private static class X509CertificateDecoder implements Converter<List<String>, RSAPublicKey> {
private final CertificateFactory certificateFactory;
X509CertificateDecoder(CertificateFactory certificateFactory) {
this.certificateFactory = certificateFactory;
}
@Override
@NonNull
public RSAPublicKey convert(List<String> lines) {
StringBuilder base64Encoded = new StringBuilder();
for (String line : lines) {
if (isNotX509CertificateWrapper(line)) {
base64Encoded.append(line);
}
}
byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString());
try (InputStream x509CertStream = new ByteArrayInputStream(x509)) {
X509Certificate certificate = (X509Certificate) this.certificateFactory
.generateCertificate(x509CertStream);
return (RSAPublicKey) certificate.getPublicKey();
}
catch (CertificateException | IOException ex) {
throw new IllegalArgumentException(ex);
}
}
private boolean isNotX509CertificateWrapper(String line) {
return !X509_CERT_HEADER.equals(line) && !X509_CERT_FOOTER.equals(line);
}
}
}
| apache-2.0 |
eaglelzy/myglide | library/src/main/java/com/lizy/myglide/manager/ActivityFragmentLifecycle.java | 1391 | package com.lizy.myglide.manager;
import com.lizy.myglide.util.Util;
import java.util.Collections;
import java.util.Set;
import java.util.WeakHashMap;
/**
* Created by lizy on 16-5-1.
*/
public class ActivityFragmentLifecycle implements Lifecycle {
private final Set<LifecycleListener> listeners =
Collections.newSetFromMap(new WeakHashMap<LifecycleListener, Boolean>());
private boolean isStart;
private boolean isDestroy;
@Override
public void addListener(LifecycleListener listener) {
listeners.add(listener);
if (isDestroy) {
listener.onDestroy();
} else if (isStart) {
listener.onStart();
} else {
listener.onStop();
}
}
@Override
public void removeListener(LifecycleListener listener) {
listeners.remove(listener);
}
public void onStart() {
isStart = true;
for (LifecycleListener listener : Util.getSnapshot(listeners)) {
listener.onStart();
}
}
public void onStop() {
isStart = false;
for (LifecycleListener listener : Util.getSnapshot(listeners)) {
listener.onStop();
}
}
public void onDestroy() {
isDestroy = true;
for (LifecycleListener listener : Util.getSnapshot(listeners)) {
listener.onDestroy();
}
}
}
| apache-2.0 |
kaffee-public/producto-computing | entities/java/producto/computing/CpuSocket.java | 102 |
package producto.computing;
/**
* .
* @author ahorvath
*/
public class CpuSocket {
}
| apache-2.0 |
jasonzhang2022/flexims | security/src/main/java/com/flexdms/flexims/accesscontrol/QueryAuthorizer.java | 3188 | package com.flexdms.flexims.accesscontrol;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import com.flexdms.flexims.accesscontrol.action.QueryAction;
import com.flexdms.flexims.accesscontrol.action.ReadAction;
import com.flexdms.flexims.jpa.eclipselink.FleximsDynamicEntityImpl;
import com.flexdms.flexims.jpa.event.InstanceAction.InstanceActionType;
import com.flexdms.flexims.query.TypedQuery;
import com.flexdms.flexims.report.rs.ReportActionContext;
import com.flexdms.flexims.report.rs.helper.FxReportWrapper;
import com.flexdms.flexims.users.FxRole;
import com.flexdms.flexims.users.RoleUtils;
@RequestScoped
public class QueryAuthorizer {
@Inject
RoleContext roleContext;
@Inject
PermissionChecker permissionChecker;
public void assertQueryExecution(@Observes ReportActionContext actionContext) {
for (FxRole role : roleContext.getRoles()) {
if (role.isAdminRole()) {
return;
}
if (role.isIncludedBy(RoleUtils.getAdminRole())) {
return;
}
}
FleximsDynamicEntityImpl fxReportOrQuery = actionContext.getFxReport();
Action action = ACLHelper.getActionByName(QueryAction.NAME);
FleximsDynamicEntityImpl reportEntity = null;
FleximsDynamicEntityImpl queryEntity = null;
FleximsDynamicEntityImpl queryPermissionEntity = null;
if (fxReportOrQuery.getClass().getSimpleName().equals(FxReportWrapper.TYPE_NAME)) {
reportEntity = fxReportOrQuery;
queryEntity = reportEntity.get(FxReportWrapper.PROP_NAME_PROP_QUERY);
if (reportEntity.getId() == 0) {
queryPermissionEntity = queryEntity;
} else {
queryPermissionEntity = reportEntity;
}
} else {
queryEntity = fxReportOrQuery;
queryPermissionEntity = queryEntity;
}
// check query permission defined in query instance.
for (FxRole role : roleContext.getRoles()) {
PermissionResult pr = permissionChecker.checkInternalPermission(action, role, queryPermissionEntity.getClass().getSimpleName(),
queryPermissionEntity, true);
if (pr == PermissionResult.Allow) {
return;
}
if (pr == PermissionResult.Deny) {
throw new AuthorizedException(InstanceActionType.Query, queryPermissionEntity);
}
}
// we not reach a decision yet, check the read permission on type
action = ACLHelper.getActionByName(ReadAction.NAME);
String targetType = queryEntity.get(TypedQuery.PROP_NAME_TYPE);
for (FxRole role : roleContext.getRoles()) {
PermissionResult pr = permissionChecker.checkInternalPermission(action, role, targetType, null, false);
if (pr == PermissionResult.Allow) {
return;
}
if (pr == PermissionResult.Deny) {
throw new AuthorizedException(InstanceActionType.Query, queryPermissionEntity);
}
}
// configured
PermissionResult pr = permissionChecker.getConfigedPermissionResult(action);
if (pr == PermissionResult.Allow) {
return;
}
if (pr == PermissionResult.Deny) {
throw new AuthorizedException(InstanceActionType.Query, queryPermissionEntity);
}
// default.
if (!permissionChecker.defaultActionPermission(action)) {
throw new AuthorizedException(InstanceActionType.Query, queryPermissionEntity);
}
}
}
| apache-2.0 |
fvdaak/aika | src/test/java/org/aika/network/SuspensionTest.java | 3934 | /*
* 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.aika.network;
import org.aika.*;
import org.aika.corpus.Document;
import org.junit.Assert;
import org.junit.Test;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import static org.aika.corpus.Range.Operator.EQUALS;
/**
*
* @author Lukas Molzberger
*/
public class SuspensionTest {
@Test
public void testSuspendInputNeuron() {
Model m = new Model(new DummySuspensionHook(), 1);
Neuron n = m.createNeuron("A");
n.get().node.suspend();
n.suspend();
int id = n.id;
// Reactivate
n = m.lookupNeuron(id);
Document doc = m.createDocument("Bla");
n.addInput(doc, 0, 1);
}
@Test
public void testSuspendAndNeuron() {
Model m = new Model(new DummySuspensionHook(), 1);
Neuron inA = m.createNeuron("A");
Neuron inB = m.createNeuron("B");
int idA = inA.id;
int idB = inB.id;
Neuron nC = m.initNeuron(m.createNeuron("C"),
5.0,
new Input()
.setNeuron(inA)
.setWeight(10.0f)
.setBiasDelta(0.9)
.setRelativeRid(0)
.setRecurrent(false)
.setStartRangeMatch(EQUALS)
.setStartRangeOutput(true),
new Input()
.setNeuron(inB)
.setWeight(10.0f)
.setBiasDelta(0.9)
.setRelativeRid(null)
.setRecurrent(false)
.setEndRangeMatch(EQUALS)
.setEndRangeOutput(true)
);
Neuron outD = m.initNeuron(m.createNeuron("D"),
5.0,
new Input()
.setNeuron(nC)
.setWeight(10.0f)
.setBiasDelta(0.9)
.setRecurrent(false)
.setRangeMatch(Input.RangeRelation.EQUALS)
.setRangeOutput(true)
);
m.suspendAll();
Assert.assertTrue(outD.isSuspended());
// Reactivate
Document doc = m.createDocument("Bla");
inA = m.lookupNeuron(idA);
inA.addInput(doc, 0, 1, 0);
inB = m.lookupNeuron(idB);
inB.addInput(doc, 1, 2, 1);
doc.process();
System.out.println(doc.neuronActivationsToString(true));
Assert.assertFalse(outD.getFinalActivations(doc).isEmpty());
}
public static class DummySuspensionHook implements SuspensionHook {
public AtomicInteger currentId = new AtomicInteger(0);
Map<Integer, byte[]> storage = new TreeMap<>();
@Override
public int getNewId() {
return currentId.addAndGet(1);
}
@Override
public void store(int id, byte[] data) {
storage.put(id, data);
}
@Override
public byte[] retrieve(int id) {
return storage.get(id);
}
}
}
| apache-2.0 |
palantir/atlasdb | atlasdb-commons/src/main/java/com/palantir/util/AssertUtils.java | 6598 | /*
* (c) Copyright 2018 Palantir Technologies Inc. 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 com.palantir.util;
import com.palantir.logsafe.Arg;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.exceptions.SafeRuntimeException;
import com.palantir.logsafe.logger.SafeLogger;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("BadAssert") // explicitly using asserts for test-only
public class AssertUtils {
/**
* Previously, failed asserts logged to this log.
* However, this led to the problem that the logger would always be com.palantir.util.AssertUtils,
* which is extremely annoying to try to filter based on your logging properties.
* (Should it go into the server error log, or maybe the upgrade log, or the import log file?
* Can't tell, cause it's all AssertUtils!)
* <p>
* Until we get all downstream projects off of using defaultLog however,
* this will stay, just deprecated.
*/
@Deprecated
@SuppressWarnings("PreferSafeLogger") // API exposures accept arbitrary Objects which may not be Args
private static final Logger log = LoggerFactory.getLogger(AssertUtils.class);
public static <T> boolean nonNullItems(Collection<T> c) {
for (T t : c) {
if (t == null) {
return false;
}
}
return true;
}
public static <T> boolean assertListElementsUnique(List<T> l) {
Set<T> set = new HashSet<>(l);
assert set.size() == l.size();
return true;
}
public static boolean isAssertEnabled() {
boolean ret = false;
assert (ret = true) == true;
return ret;
}
public static void assertAndLog(Logger log, boolean cheapTest, String msg) {
if (!cheapTest) {
assertAndLogWithException(log, false, msg, getDebuggingException());
}
}
public static void assertAndLog(SafeLogger log, boolean cheapTest, String msg) {
if (!cheapTest) {
assertAndLogWithException(log, false, msg, getDebuggingException());
}
}
public static void assertAndLog(SafeLogger log, boolean cheapTest, String msg, Arg<?>... args) {
if (!cheapTest) {
assertAndLogWithException(log, false, msg, getDebuggingException(), args);
}
}
/**
* @deprecated Use {@link #assertAndLog(Logger, boolean, String)} instead.
* This will make sure log events go to your logger instead of a hard-to-filter default.
* (com.palantir.util.AssertUtils)
*/
@Deprecated
public static void assertAndLog(boolean cheapTest, String msg) {
assertAndLog(log, cheapTest, msg);
}
public static Exception getDebuggingException() {
return new SafeRuntimeException(
"This stack trace is not from a thrown exception. It's provided just for debugging this error.");
}
public static void assertAndLog(Logger log, boolean cheapTest, String format, Object... args) {
if (!cheapTest) {
assertAndLogWithException(log, false, format, getDebuggingException(), args);
}
}
/**
* @deprecated Use {@link #assertAndLog(Logger, boolean, String, Object...)} instead.
* This will make sure log events go to your logger instead of a hard-to-filter default.
* (com.palantir.util.AssertUtils)
*/
@Deprecated
public static void assertAndLog(boolean cheapTest, String format, Object... args) {
assertAndLog(log, cheapTest, format, args);
}
public static void assertAndLogWithException(Logger log, boolean cheapTest, String msg, Throwable t) {
if (!cheapTest) {
assertAndLogWithException(log, cheapTest, msg, t, new Object[] {});
}
}
public static void assertAndLogWithException(SafeLogger log, boolean cheapTest, String msg, Throwable t) {
if (!cheapTest) {
log.error("An error occurred", SafeArg.of("message", msg), t);
assert false : msg;
}
}
public static void assertAndLogWithException(
SafeLogger log, boolean cheapTest, String msg, Throwable t, Arg<?>... args) {
if (!cheapTest) {
log.error(
"An error occurred",
Stream.concat(Stream.of(SafeArg.of("message", msg)), Arrays.stream(args))
.collect(Collectors.toList()),
t);
assert false : msg;
}
}
/**
* @deprecated Use {@link #assertAndLogWithException(Logger, boolean, String, Throwable)} instead.
* This will make sure log events go to your logger instead of a hard-to-filter default.
* (com.palantir.util.AssertUtils)
*/
@Deprecated
public static void assertAndLogWithException(boolean cheapTest, String msg, Throwable t) {
assertAndLogWithException(log, cheapTest, msg, t);
}
public static void assertAndLogWithException(
Logger log, boolean cheapTest, String format, Throwable t, Object... args) {
if (!cheapTest) {
Object[] newArgs = Arrays.copyOf(args, args.length + 2);
newArgs[args.length] = SafeArg.of("format", format);
newArgs[args.length + 1] = t;
log.error("Assertion with exception!", newArgs);
assert false : format;
}
}
/**
* @deprecated Use {@link #assertAndLogWithException(Logger, boolean, String, Throwable, Object...)} instead.
* This will make sure log events go to your logger instead of a hard-to-filter default.
* (com.palantir.util.AssertUtils)
*/
@Deprecated
public static void assertAndLogWithException(boolean cheapTest, String format, Throwable t, Object... args) {
assertAndLogWithException(log, cheapTest, format, t, args);
}
}
| apache-2.0 |
melkonyan/Android-Week-View | library/src/main/java/com/alamkanak/weekview/TimeInterpreter.java | 232 | package com.alamkanak.weekview;
import java.util.Calendar;
/**
* Creates string from hour that is displayed in the left column of the {@link WeekView}
*/
public interface TimeInterpreter {
String interpretTime(int hour);
}
| apache-2.0 |
nafae/developer | examples/adwords_axis/src/main/java/adwords/axis/v201402/adwordsforvideo/UpdateBidByFormat.java | 4483 | // Copyright 2014 Google Inc. 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 adwords.axis.v201402.adwordsforvideo;
import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.v201402.cm.Money;
import com.google.api.ads.adwords.axis.v201402.cm.Operator;
import com.google.api.ads.adwords.axis.v201402.video.BidsByFormat;
import com.google.api.ads.adwords.axis.v201402.video.TargetingGroup;
import com.google.api.ads.adwords.axis.v201402.video.TargetingGroupOperation;
import com.google.api.ads.adwords.axis.v201402.video.TargetingGroupReturnValue;
import com.google.api.ads.adwords.axis.v201402.video.VideoAdDisplayFormat;
import com.google.api.ads.adwords.axis.v201402.video.VideoAdDisplayFormat_VideoBidMapEntry;
import com.google.api.ads.adwords.axis.v201402.video.VideoBid;
import com.google.api.ads.adwords.axis.v201402.video.VideoTargetingGroupServiceInterface;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.client.auth.oauth2.Credential;
/**
* This example illustrates how to update bids by video ad format.
*
* Note: AdWords for Video API is a Beta feature.
*
* Credentials and properties in {@code fromFile()} are pulled from the
* "ads.properties" file. See README for more info.
*
* Tags: VideoTargetingGroupService.mutate
*
* Category: adx-exclude
*
* @author Ray Tsang
*/
public class UpdateBidByFormat {
public static void main(String[] args) throws Exception {
// Generate a refreshable OAuth2 credential similar to a ClientLogin token
// and can be used in place of a service account.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.ADWORDS)
.fromFile()
.build()
.generateCredential();
// Construct an AdWordsSession.
AdWordsSession session = new AdWordsSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
Long campaignId = Long.valueOf("INSERT_CAMPAIGN_ID_HERE");
Long targetingGroupId = Long.valueOf("INSERT_TARGETING_GROUP_ID_HERE");
AdWordsServices adWordsServices = new AdWordsServices();
runExample(adWordsServices, session, campaignId, targetingGroupId);
}
public static void runExample(
AdWordsServices adWordsServices, AdWordsSession session,
Long campaignId, Long targetingGroupId) throws Exception {
// Get the VideoTargetingGroupService.
VideoTargetingGroupServiceInterface videoTargetingGroupService =
adWordsServices.get(session, VideoTargetingGroupServiceInterface.class);
TargetingGroup targetingGroup = new TargetingGroup();
targetingGroup.setId(targetingGroupId);
targetingGroup.setCampaignId(campaignId);
Money amount = new Money();
amount.setMicroAmount(200000L);
VideoBid videoBid = new VideoBid();
videoBid.setAmount(amount);
VideoAdDisplayFormat_VideoBidMapEntry trueViewBid =
new VideoAdDisplayFormat_VideoBidMapEntry();
trueViewBid.setKey(VideoAdDisplayFormat.TRUE_VIEW_IN_DISPLAY);
trueViewBid.setValue(videoBid);
targetingGroup.setBidsByFormat(
new BidsByFormat(new VideoAdDisplayFormat_VideoBidMapEntry[] {trueViewBid}));
TargetingGroupOperation operation = new TargetingGroupOperation();
operation.setOperator(Operator.SET);
operation.setOperand(targetingGroup);
TargetingGroupReturnValue result =
videoTargetingGroupService.mutate(new TargetingGroupOperation[] {operation});
for (TargetingGroup targetingGroupResult : result.getValue()) {
System.out.printf("Targeting group with campaign id %d, "
+ "and targeting group id %d was updated.%n",
targetingGroupResult.getCampaignId(),
targetingGroupResult.getId());
}
}
}
| apache-2.0 |
Sailboats/ACMS | src/com/caoligai/acms/dao/CourseDao.java | 1052 | package com.caoligai.acms.dao;
import java.util.ArrayList;
import java.util.List;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.caoligai.acms.avobject.Course;
/**
* @ClassName: CourseDao
* @Description: Course ±í Dao Àà
* @author Noodle caoligai520402@gmail.com
* @date 2016Äê3ÔÂ9ÈÕ ÏÂÎç8:50:40
*
*/
public class CourseDao {
/**
* »ñÈ¡ËùÓпγÌ
*
* @return
*/
public static List<Course> getAllCourse() {
List<Course> data = null;
AVQuery<Course> query = AVObject.getQuery(Course.class);
try {
data = query.find();
} catch (AVException e) {
e.printStackTrace();
}
return data;
}
public static List<Course> getAllCourseByTeacherId(String teacherId) {
List<Course> data = null;
AVQuery<Course> query = AVObject.getQuery(Course.class).whereEqualTo(
"teacherId", teacherId);
try {
data = query.find();
} catch (AVException e) {
e.printStackTrace();
}
return data;
}
}
| apache-2.0 |
gfis/flodskim | src/main/java/org/teherba/flodskim/Main.java | 8948 | /* Read and Process (Floppy) Disk Image Formats
@(#) $Id: Main.java 820 2011-11-07 21:59:07Z gfis $
2013-11-05, Georg Fischer: copied from Main
*/
/*
* Copyright 2013 Dr. Georg Fischer <punctum at punctum dot kom>
*
* 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.teherba.flodskim;
import org.teherba.flodskim.buffer.BaseBuffer;
import org.teherba.flodskim.buffer.BufferFactory;
import org.teherba.flodskim.system.BaseSystem;
import org.teherba.flodskim.system.DirectoryEntry;
import org.teherba.flodskim.system.SystemFactory;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
/** Spells a number (or some other enumerable word) in some language.
* This class is the commandline interface to <em>BaseSpeller</em>.
* @author Dr. Georg Fischer
*/
final public class Main {
public final static String CVSID = "@(#) $Id: Main.java 820 2011-11-07 21:59:07Z gfis $";
/** log4j logger (category) */
public Logger log;
/** Newline string (CR/LF or LF only) */
private String nl;
/** code for output format */
private int mode;
/** code for HTML output format */
public static final int MODE_HTML = 0;
/** code for emphasized HTML output format */
public static final int MODE_HTML_EM = 1;
/** code for plain text output format */
public static final int MODE_PLAIN = 2;
/** code for tab separated values, for Excel and other spreadsheet processors */
public static final int MODE_TSV = 3;
/** code for XML output format */
public static final int MODE_XML = 4;
/** Sets the output format
* @param format code for the output format, corresponding to the value of commandline option "-m"
*/
public void setMode(int format) {
mode = format;
} // setMode
/** Gets the output format
* @return format code for the output format, corresponding to the value of commandline option "-m"
*/
public int getMode() {
return mode;
} // getMode
/** No-args Constructor
*/
public Main() {
log = LogManager.getLogger(Main.class.getName());
nl = System.getProperty("line.separator");
setMode(MODE_PLAIN);
} // Constructor()
/** Convenience overlay method with a single string argument instead
* of an array of strings.
* @param commandLine all parameters of the commandline in one string
*/
public void process(String commandLine) {
process(commandLine.split("\\s+"));
} // process(String)
/** Evaluates the arguments of the command line, and processes them.
* @param args Arguments; if missing, print the usage string
*/
public void process(String args[]) {
BufferFactory bufferFactory = new BufferFactory();
BaseBuffer container = null;
SystemFactory systemFactory = new SystemFactory();
BaseSystem fileSystem = null;
try {
int iarg = 0; // index for command line arguments
if (iarg >= args.length) { // usage
System.out.println("Usage:\tjava org.teherba.flodskim.Main parameters actions");
System.out.println("Parameters are:");
System.out.println(" -buffer code container format is code (default: dsk)");
System.out.println(" -system code filesystem is code (default: base)");
System.out.println(" -inform num amount of diagnostic output");
System.out.println("Actions on buffers are:");
System.out.println(" -block xnum dump block xnum");
System.out.println(" -dump xoffs xlen hexadecimal dump");
System.out.println(" -read filename read a disk image file");
System.out.println("Actions on file systems are:");
System.out.println(" -dir print a directory listing");
System.out.println(" -copy path copy all files into path");
} else { // >= 1 argument
String bufferCode = "dsk";
String systemCode = "base";
String fileName = null;
String targetPath = ".";
int informLevel = 0; // amount of diagnostic information
// get all option codes
while (iarg < args.length && args[iarg].startsWith("-")) {
String option = args[iarg ++];
if (false) {
} else if (option.startsWith("-block" )) {
String tblock = args[iarg ++];
int blockNo = 0;
try {
blockNo = Integer.parseInt(tblock, 16); // hex
} catch (Exception exc) {
log.error("Main.process: numeric exception, blockNo=" + tblock);
}
byte[] block = fileSystem.getBlock(blockNo);
fileSystem.dump(block, 0, block.length);
} else if (option.startsWith("-buffer" )) {
bufferCode = args[iarg ++];
container = bufferFactory.getInstance(bufferCode);
} else if (option.startsWith("-copy" )) {
targetPath = args[iarg ++];
fileSystem.copyFiles(targetPath);
} else if (option.startsWith("-dir" )) {
fileSystem.printDirectory();
} else if (option.startsWith("-dump" )) {
String toffs = args[iarg ++];
String tlen = args[iarg ++];
int offset = 0;
int length = 0x100;
try {
offset = Integer.parseInt(toffs, 16);
length = Integer.parseInt(tlen , 16);
} catch (Exception exc) {
log.error("Main.process: numeric exception, offset=" + toffs + ", length=" + tlen);
}
if (container == null) {
container = bufferFactory.getInstance(bufferCode);
}
container.dump(offset, length);
} else if (option.startsWith("-inform" )) {
String tlevel = args[iarg ++];
try {
informLevel = Integer.parseInt(tlevel, 10);
} catch (Exception exc) {
log.error("Main.process: numeric exception, level=" + tlevel);
}
} else if (option.startsWith("-read" )) {
fileName = args[iarg ++];
if (container == null) {
container = bufferFactory.getInstance(bufferCode);
}
container.openFile(0, fileName);
container.openFile(1, null);
container.readContainer(informLevel);
} else if (option.startsWith("-system" )) {
systemCode = args[iarg ++];
fileSystem = systemFactory.getInstance(systemCode);
if (container == null) {
container = bufferFactory.getInstance(bufferCode);
}
fileSystem.setContainer(container);
} else {
System.err.println("invalid option \"" + option + "\"");
}
} // while options
container.closeAll();
} // args.length >= 1
} catch (Exception exc) {
log.error(exc.getMessage(), exc);
} // try
} // process
/** Commandline interface for number spelling.
* @param args elements of the commandline separated by whitespace
*/
public static void main(String args[]) {
Main command = new Main();
command.process(args);
} // main
} // Main
| apache-2.0 |
AvinashRoyalc/Tomato-Curry | app/src/main/java/com/tomato/curry/RecyclerItemClickListener.java | 1455 | package com.tomato.curry;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
} | apache-2.0 |
Juanah/Android-BollerTuneZApp | obj/Debug/android/src/bollertunez/ActivityRegLoginTest.java | 1176 | package bollertunez;
public class ActivityRegLoginTest
extends android.app.Activity
implements
mono.android.IGCUserPeer
{
static final String __md_methods;
static {
__md_methods =
"n_onCreate:(Landroid/os/Bundle;)V:GetOnCreate_Landroid_os_Bundle_Handler\n" +
"";
mono.android.Runtime.register ("BollerTuneZ.ActivityRegLoginTest, BollerTuneZ, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ActivityRegLoginTest.class, __md_methods);
}
public ActivityRegLoginTest () throws java.lang.Throwable
{
super ();
if (getClass () == ActivityRegLoginTest.class)
mono.android.TypeManager.Activate ("BollerTuneZ.ActivityRegLoginTest, BollerTuneZ, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "", this, new java.lang.Object[] { });
}
public void onCreate (android.os.Bundle p0)
{
n_onCreate (p0);
}
private native void n_onCreate (android.os.Bundle p0);
java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
| apache-2.0 |
jdillon/gshell | gshell-commands/gshell-file/src/main/java/com/planet57/gshell/commands/file/DeleteDirectoryAction.java | 1623 | /*
* Copyright (c) 2009-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.planet57.gshell.commands.file;
import java.io.File;
import javax.annotation.Nonnull;
import com.planet57.gshell.command.Command;
import com.planet57.gshell.command.CommandContext;
import com.planet57.gshell.util.io.FileAssert;
import com.planet57.gshell.util.cli2.Argument;
import com.planet57.gshell.util.io.FileSystemAccess;
import com.planet57.gshell.util.jline.Complete;
/**
* Remove a directory.
*
* @since 2.0
*/
@Command(name = "rmdir", description = "Remove a directory")
public class DeleteDirectoryAction
extends FileCommandActionSupport
{
@Argument(required = true, description = "The path of the directory remove", token = "PATH")
@Complete("directory-name")
private String path;
@Override
public Object execute(@Nonnull final CommandContext context) throws Exception {
FileSystemAccess fs = getFileSystem();
File file = fs.resolveFile(path);
new FileAssert(file).exists().isDirectory();
fs.deleteDirectory(file);
return null;
}
}
| apache-2.0 |
SingingTree/hapi-fhir | hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/packages/NpmR4Test.java | 37532 | package ca.uhn.fhir.jpa.packages;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster;
import ca.uhn.fhir.interceptor.api.IInterceptorService;
import ca.uhn.fhir.jpa.api.config.DaoConfig;
import ca.uhn.fhir.jpa.dao.data.INpmPackageDao;
import ca.uhn.fhir.jpa.dao.data.INpmPackageVersionDao;
import ca.uhn.fhir.jpa.dao.data.INpmPackageVersionResourceDao;
import ca.uhn.fhir.jpa.dao.r4.BaseJpaR4Test;
import ca.uhn.fhir.jpa.model.entity.NpmPackageEntity;
import ca.uhn.fhir.jpa.model.entity.NpmPackageVersionEntity;
import ca.uhn.fhir.jpa.model.entity.NpmPackageVersionResourceEntity;
import ca.uhn.fhir.jpa.model.util.JpaConstants;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.server.IBundleProvider;
import ca.uhn.fhir.rest.param.ReferenceParam;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.param.UriParam;
import ca.uhn.fhir.rest.server.IRestfulServerDefaults;
import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.interceptor.partition.RequestTenantPartitionInterceptor;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.test.utilities.JettyUtil;
import ca.uhn.fhir.test.utilities.ProxyUtil;
import ca.uhn.fhir.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.r4.model.Enumerations;
import org.hl7.fhir.r4.model.ImplementationGuide;
import org.hl7.fhir.r4.model.Organization;
import org.hl7.fhir.r4.model.PractitionerRole;
import org.hl7.fhir.r4.model.Reference;
import org.hl7.fhir.r4.model.SearchParameter;
import org.hl7.fhir.r4.model.StructureDefinition;
import org.hl7.fhir.utilities.npm.NpmPackage;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class NpmR4Test extends BaseJpaR4Test {
private static final Logger ourLog = LoggerFactory.getLogger(NpmR4Test.class);
@Autowired
public IPackageInstallerSvc igInstaller;
@Autowired
private IHapiPackageCacheManager myPackageCacheManager;
@Autowired
private NpmJpaValidationSupport myNpmJpaValidationSupport;
private Server myServer;
@Autowired
private INpmPackageDao myPackageDao;
@Autowired
private INpmPackageVersionDao myPackageVersionDao;
@Autowired
private INpmPackageVersionResourceDao myPackageVersionResourceDao;
private FakeNpmServlet myFakeNpmServlet;
@Autowired
private IInterceptorService myInterceptorService;
@Autowired
private RequestTenantPartitionInterceptor myRequestTenantPartitionInterceptor;
@BeforeEach
public void before() throws Exception {
JpaPackageCache jpaPackageCache = ProxyUtil.getSingletonTarget(myPackageCacheManager, JpaPackageCache.class);
myServer = new Server(0);
ServletHandler proxyHandler = new ServletHandler();
myFakeNpmServlet = new FakeNpmServlet();
ServletHolder servletHolder = new ServletHolder(myFakeNpmServlet);
proxyHandler.addServletWithMapping(servletHolder, "/*");
myServer.setHandler(proxyHandler);
myServer.start();
int port = JettyUtil.getPortForStartedServer(myServer);
jpaPackageCache.getPackageServers().clear();
jpaPackageCache.addPackageServer("http://localhost:" + port);
myFakeNpmServlet.myResponses.clear();
}
@AfterEach
public void after() throws Exception {
JettyUtil.closeServer(myServer);
myDaoConfig.setAllowExternalReferences(new DaoConfig().isAllowExternalReferences());
myPartitionSettings.setPartitioningEnabled(false);
myInterceptorService.unregisterInterceptor(myRequestTenantPartitionInterceptor);
}
@Disabled("This test is super slow so don't run by default")
@Test
public void testInstallUsCore() {
JpaPackageCache jpaPackageCache = ProxyUtil.getSingletonTarget(myPackageCacheManager, JpaPackageCache.class);
jpaPackageCache.getPackageServers().clear();
jpaPackageCache.addPackageServer("https://packages.fhir.org");
PackageInstallationSpec spec = new PackageInstallationSpec()
.setName("hl7.fhir.us.core")
.setVersion("3.1.0")
.setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL)
.setFetchDependencies(true);
igInstaller.install(spec);
runInTransaction(()->{
SearchParameterMap map = SearchParameterMap.newSynchronous(SearchParameter.SP_BASE, new TokenParam("NamingSystem"));
IBundleProvider outcome = mySearchParameterDao.search(map);
List<IBaseResource> resources = outcome.getResources(0, outcome.sizeOrThrowNpe());
for (int i = 0; i < resources.size(); i++) {
ourLog.info("**************************************************************************");
ourLog.info("**************************************************************************");
ourLog.info("Res " + i);
ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(resources.get(i)));
}
});
igInstaller.install(spec);
}
@Test
public void testCacheDstu3Package() throws Exception {
byte[] bytes = loadClasspathBytes("/packages/nictiz.fhir.nl.stu3.questionnaires-1.0.2.tgz");
myFakeNpmServlet.myResponses.put("/nictiz.fhir.nl.stu3.questionnaires/1.0.2", bytes);
PackageInstallationSpec spec = new PackageInstallationSpec().setName("nictiz.fhir.nl.stu3.questionnaires").setVersion("1.0.2").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
igInstaller.install(spec);
// Be sure no further communication with the server
JettyUtil.closeServer(myServer);
// Make sure we can fetch the package by ID and Version
NpmPackage pkg = myPackageCacheManager.loadPackage("nictiz.fhir.nl.stu3.questionnaires", "1.0.2");
assertEquals("Nictiz NL package of FHIR STU3 conformance resources for MedMij information standard Questionnaires. Includes dependency on Zib2017 and SDC.\\n\\nHCIMs: https://zibs.nl/wiki/HCIM_Release_2017(EN)", pkg.description());
// Make sure we can fetch the package by ID
pkg = myPackageCacheManager.loadPackage("nictiz.fhir.nl.stu3.questionnaires", null);
assertEquals("1.0.2", pkg.version());
assertEquals("Nictiz NL package of FHIR STU3 conformance resources for MedMij information standard Questionnaires. Includes dependency on Zib2017 and SDC.\\n\\nHCIMs: https://zibs.nl/wiki/HCIM_Release_2017(EN)", pkg.description());
// Fetch resource by URL
FhirContext fhirContext = FhirContext.forCached(FhirVersionEnum.DSTU3);
runInTransaction(() -> {
IBaseResource asset = myPackageCacheManager.loadPackageAssetByUrl(FhirVersionEnum.DSTU3, "http://nictiz.nl/fhir/StructureDefinition/vl-QuestionnaireResponse");
assertThat(fhirContext.newJsonParser().encodeResourceToString(asset), containsString("\"url\":\"http://nictiz.nl/fhir/StructureDefinition/vl-QuestionnaireResponse\",\"version\":\"1.0.1\""));
});
// Fetch resource by URL with version
runInTransaction(() -> {
IBaseResource asset = myPackageCacheManager.loadPackageAssetByUrl(FhirVersionEnum.DSTU3, "http://nictiz.nl/fhir/StructureDefinition/vl-QuestionnaireResponse|1.0.1");
assertThat(fhirContext.newJsonParser().encodeResourceToString(asset), containsString("\"url\":\"http://nictiz.nl/fhir/StructureDefinition/vl-QuestionnaireResponse\",\"version\":\"1.0.1\""));
});
// This was saved but is the wrong version of FHIR for this server
assertNull(myNpmJpaValidationSupport.fetchStructureDefinition("http://fhir.de/StructureDefinition/condition-de-basis/0.2"));
}
@Test
public void testInstallR4Package() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
byte[] bytes = loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.12.0.tgz");
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.12.0", bytes);
PackageInstallationSpec spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.12.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL);
PackageInstallOutcomeJson outcome = igInstaller.install(spec);
assertEquals(1, outcome.getResourcesInstalled().get("CodeSystem"));
// Be sure no further communication with the server
JettyUtil.closeServer(myServer);
// Make sure we can fetch the package by ID and Version
NpmPackage pkg = myPackageCacheManager.loadPackage("hl7.fhir.uv.shorthand", "0.12.0");
assertEquals("Describes FHIR Shorthand (FSH), a domain-specific language (DSL) for defining the content of FHIR Implementation Guides (IG). (built Wed, Apr 1, 2020 17:24+0000+00:00)", pkg.description());
// Make sure we can fetch the package by ID
pkg = myPackageCacheManager.loadPackage("hl7.fhir.uv.shorthand", null);
assertEquals("0.12.0", pkg.version());
assertEquals("Describes FHIR Shorthand (FSH), a domain-specific language (DSL) for defining the content of FHIR Implementation Guides (IG). (built Wed, Apr 1, 2020 17:24+0000+00:00)", pkg.description());
// Make sure DB rows were saved
runInTransaction(() -> {
NpmPackageEntity pkgEntity = myPackageDao.findByPackageId("hl7.fhir.uv.shorthand").orElseThrow(() -> new IllegalArgumentException());
assertEquals("hl7.fhir.uv.shorthand", pkgEntity.getPackageId());
NpmPackageVersionEntity versionEntity = myPackageVersionDao.findByPackageIdAndVersion("hl7.fhir.uv.shorthand", "0.12.0").orElseThrow(() -> new IllegalArgumentException());
assertEquals("hl7.fhir.uv.shorthand", versionEntity.getPackageId());
assertEquals("0.12.0", versionEntity.getVersionId());
assertEquals(3001, versionEntity.getPackageSizeBytes());
assertEquals(true, versionEntity.isCurrentVersion());
assertEquals("hl7.fhir.uv.shorthand", versionEntity.getPackageId());
assertEquals("4.0.1", versionEntity.getFhirVersionId());
assertEquals(FhirVersionEnum.R4, versionEntity.getFhirVersion());
NpmPackageVersionResourceEntity resource = myPackageVersionResourceDao.findCurrentVersionByCanonicalUrl(Pageable.unpaged(), FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ImplementationGuide/hl7.fhir.uv.shorthand").getContent().get(0);
assertEquals("http://hl7.org/fhir/uv/shorthand/ImplementationGuide/hl7.fhir.uv.shorthand", resource.getCanonicalUrl());
assertEquals("0.12.0", resource.getCanonicalVersion());
assertEquals("ImplementationGuide-hl7.fhir.uv.shorthand.json", resource.getFilename());
assertEquals("4.0.1", resource.getFhirVersionId());
assertEquals(FhirVersionEnum.R4, resource.getFhirVersion());
assertEquals(6155, resource.getResSizeBytes());
});
// Fetch resource by URL
runInTransaction(() -> {
IBaseResource asset = myPackageCacheManager.loadPackageAssetByUrl(FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ImplementationGuide/hl7.fhir.uv.shorthand");
assertThat(myFhirCtx.newJsonParser().encodeResourceToString(asset), containsString("\"url\":\"http://hl7.org/fhir/uv/shorthand/ImplementationGuide/hl7.fhir.uv.shorthand\",\"version\":\"0.12.0\""));
});
// Fetch resource by URL with version
runInTransaction(() -> {
IBaseResource asset = myPackageCacheManager.loadPackageAssetByUrl(FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ImplementationGuide/hl7.fhir.uv.shorthand|0.12.0");
assertThat(myFhirCtx.newJsonParser().encodeResourceToString(asset), containsString("\"url\":\"http://hl7.org/fhir/uv/shorthand/ImplementationGuide/hl7.fhir.uv.shorthand\",\"version\":\"0.12.0\""));
});
// Search for the installed resource
runInTransaction(() -> {
SearchParameterMap map = SearchParameterMap.newSynchronous();
map.add(StructureDefinition.SP_URL, new UriParam("http://hl7.org/fhir/uv/shorthand/CodeSystem/shorthand-code-system"));
IBundleProvider result = myCodeSystemDao.search(map);
assertEquals(1, result.sizeOrThrowNpe());
});
}
@Test
public void testInstallR4Package_NonConformanceResources() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
byte[] bytes = loadClasspathBytes("/packages/test-organizations-package.tgz");
myFakeNpmServlet.myResponses.put("/test-organizations/1.0.0", bytes);
List<String> resourceList = new ArrayList<>();
resourceList.add("Organization");
PackageInstallationSpec spec = new PackageInstallationSpec().setName("test-organizations").setVersion("1.0.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL);
spec.setInstallResourceTypes(resourceList);
PackageInstallOutcomeJson outcome = igInstaller.install(spec);
assertEquals(3, outcome.getResourcesInstalled().get("Organization"));
// Be sure no further communication with the server
JettyUtil.closeServer(myServer);
// Search for the installed resources
runInTransaction(() -> {
SearchParameterMap map = SearchParameterMap.newSynchronous();
map.add(Organization.SP_IDENTIFIER, new TokenParam("https://github.com/synthetichealth/synthea", "organization1"));
IBundleProvider result = myOrganizationDao.search(map);
assertEquals(1, result.sizeOrThrowNpe());
map = SearchParameterMap.newSynchronous();
map.add(Organization.SP_IDENTIFIER, new TokenParam("https://github.com/synthetichealth/synthea", "organization2"));
result = myOrganizationDao.search(map);
assertEquals(1, result.sizeOrThrowNpe());
map = SearchParameterMap.newSynchronous();
map.add(Organization.SP_IDENTIFIER, new TokenParam("https://github.com/synthetichealth/synthea", "organization3"));
result = myOrganizationDao.search(map);
assertEquals(1, result.sizeOrThrowNpe());
});
}
@Test
public void testInstallR4Package_NonConformanceResources_Partitioned() throws Exception {
myPartitionSettings.setPartitioningEnabled(true);
myInterceptorService.registerInterceptor(myRequestTenantPartitionInterceptor);
myDaoConfig.setAllowExternalReferences(true);
byte[] bytes = loadClasspathBytes("/packages/test-organizations-package.tgz");
myFakeNpmServlet.myResponses.put("/test-organizations/1.0.0", bytes);
List<String> resourceList = new ArrayList<>();
resourceList.add("Organization");
PackageInstallationSpec spec = new PackageInstallationSpec().setName("test-organizations").setVersion("1.0.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL);
spec.setInstallResourceTypes(resourceList);
PackageInstallOutcomeJson outcome = igInstaller.install(spec);
assertEquals(3, outcome.getResourcesInstalled().get("Organization"));
// Be sure no further communication with the server
JettyUtil.closeServer(myServer);
// Search for the installed resources
mySrd = mock(ServletRequestDetails.class);
when(mySrd.getTenantId()).thenReturn(JpaConstants.DEFAULT_PARTITION_NAME);
when(mySrd.getServer()).thenReturn(mock(RestfulServer.class));
when(mySrd.getInterceptorBroadcaster()).thenReturn(mock(IInterceptorBroadcaster.class));
runInTransaction(() -> {
SearchParameterMap map = SearchParameterMap.newSynchronous();
map.add(Organization.SP_IDENTIFIER, new TokenParam("https://github.com/synthetichealth/synthea", "organization1"));
IBundleProvider result = myOrganizationDao.search(map, mySrd);
assertEquals(1, result.sizeOrThrowNpe());
map = SearchParameterMap.newSynchronous();
map.add(Organization.SP_IDENTIFIER, new TokenParam("https://github.com/synthetichealth/synthea", "organization2"));
result = myOrganizationDao.search(map, mySrd);
assertEquals(1, result.sizeOrThrowNpe());
map = SearchParameterMap.newSynchronous();
map.add(Organization.SP_IDENTIFIER, new TokenParam("https://github.com/synthetichealth/synthea", "organization3"));
result = myOrganizationDao.search(map, mySrd);
assertEquals(1, result.sizeOrThrowNpe());
});
}
@Test
public void testInstallR4Package_NoIdentifierNoUrl() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
byte[] bytes = loadClasspathBytes("/packages/test-missing-identifier-package.tgz");
myFakeNpmServlet.myResponses.put("/test-organizations/1.0.0", bytes);
List<String> resourceList = new ArrayList<>();
resourceList.add("Organization");
PackageInstallationSpec spec = new PackageInstallationSpec().setName("test-organizations").setVersion("1.0.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL);
spec.setInstallResourceTypes(resourceList);
try {
PackageInstallOutcomeJson outcome = igInstaller.install(spec);
fail();
} catch (ImplementationGuideInstallationException theE) {
assertThat(theE.getMessage(), containsString("Resources in a package must have a url or identifier to be loaded by the package installer."));
}
}
@Test
public void testInstallR4Package_DraftResourcesNotInstalled() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
byte[] bytes = loadClasspathBytes("/packages/test-draft-sample.tgz");
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.11.1", bytes);
PackageInstallationSpec spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.11.1").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL);
PackageInstallOutcomeJson outcome = igInstaller.install(spec);
assertEquals(0, outcome.getResourcesInstalled().size(), outcome.getResourcesInstalled().toString());
}
@Test
public void testInstallR4Package_Twice() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
byte[] bytes = loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.12.0.tgz");
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.12.0", bytes);
PackageInstallOutcomeJson outcome;
PackageInstallationSpec spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.12.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL);
outcome = igInstaller.install(spec);
assertEquals(1, outcome.getResourcesInstalled().get("CodeSystem"));
igInstaller.install(spec);
outcome = igInstaller.install(spec);
assertEquals(null, outcome.getResourcesInstalled().get("CodeSystem"));
// Ensure that we loaded the contents
IBundleProvider searchResult = myCodeSystemDao.search(SearchParameterMap.newSynchronous("url", new UriParam("http://hl7.org/fhir/uv/shorthand/CodeSystem/shorthand-code-system")));
assertEquals(1, searchResult.sizeOrThrowNpe());
}
@Test
public void testInstallR4PackageWithNoDescription() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
byte[] bytes = loadClasspathBytes("/packages/UK.Core.r4-1.1.0.tgz");
myFakeNpmServlet.myResponses.put("/UK.Core.r4/1.1.0", bytes);
PackageInstallationSpec spec = new PackageInstallationSpec().setName("UK.Core.r4").setVersion("1.1.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL);
igInstaller.install(spec);
// Be sure no further communication with the server
JettyUtil.closeServer(myServer);
// Make sure we can fetch the package by ID and Version
NpmPackage pkg = myPackageCacheManager.loadPackage("UK.Core.r4", "1.1.0");
assertEquals(null, pkg.description());
assertEquals("UK.Core.r4", pkg.name());
}
@Test
public void testLoadPackageMetadata() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.12.0", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.12.0.tgz"));
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.11.1", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.11.1.tgz"));
PackageInstallationSpec spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.12.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
igInstaller.install(spec);
spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.11.1").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
igInstaller.install(spec);
runInTransaction(() -> {
NpmPackageMetadataJson metadata = myPackageCacheManager.loadPackageMetadata("hl7.fhir.uv.shorthand");
try {
ourLog.info(JsonUtil.serialize(metadata));
assertEquals("0.12.0", metadata.getDistTags().getLatest());
assertThat(metadata.getVersions().keySet(), contains("0.12.0", "0.11.1"));
NpmPackageMetadataJson.Version version0120 = metadata.getVersions().get("0.12.0");
assertEquals(3001, version0120.getBytes());
} catch (IOException e) {
throw new InternalErrorException(e);
}
});
}
@Test
public void testLoadPackageUsingImpreciseId() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.12.0", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.12.0.tgz"));
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.11.1", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.11.1.tgz"));
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.11.0", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.11.0.tgz"));
PackageInstallationSpec spec;
spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.12.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
PackageInstallOutcomeJson outcome = igInstaller.install(spec);
ourLog.info("Install messages:\n * {}", outcome.getMessage().stream().collect(Collectors.joining("\n * ")));
assertThat(outcome.getMessage(), hasItem("Marking package hl7.fhir.uv.shorthand#0.12.0 as current version"));
assertThat(outcome.getMessage(), hasItem("Indexing CodeSystem Resource[package/CodeSystem-shorthand-code-system.json] with URL: http://hl7.org/fhir/uv/shorthand/CodeSystem/shorthand-code-system|0.12.0"));
spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.11.1").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
outcome = igInstaller.install(spec);
ourLog.info("Install messages:\n * {}", outcome.getMessage().stream().collect(Collectors.joining("\n * ")));
assertThat(outcome.getMessage(), not(hasItem("Marking package hl7.fhir.uv.shorthand#0.11.1 as current version")));
spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.11.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
igInstaller.install(spec);
NpmPackage pkg;
pkg = myPackageCacheManager.loadPackage("hl7.fhir.uv.shorthand", "0.11.x");
assertEquals("0.11.1", pkg.version());
pkg = myPackageCacheManager.loadPackage("hl7.fhir.uv.shorthand", "0.12.x");
assertEquals("0.12.0", pkg.version());
}
@Test
public void testInstallNewerPackageUpdatesLatestVersionFlag() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
byte[] contents0111 = loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.11.1.tgz");
byte[] contents0120 = loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.12.0.tgz");
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.11.1", contents0111);
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.12.0", contents0120);
// Install older version
PackageInstallationSpec spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.11.1").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
igInstaller.install(spec);
// Older version is current
runInTransaction(() -> {
NpmPackageVersionEntity versionEntity = myPackageVersionDao.findByPackageIdAndVersion("hl7.fhir.uv.shorthand", "0.11.1").orElseThrow(() -> new IllegalArgumentException());
assertEquals(true, versionEntity.isCurrentVersion());
});
// Fetching a resource should return the older version
runInTransaction(() -> {
ImplementationGuide ig = (ImplementationGuide) myPackageCacheManager.loadPackageAssetByUrl(FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ImplementationGuide/hl7.fhir.uv.shorthand");
assertEquals("0.11.1", ig.getVersion());
});
// Now install newer version
spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.12.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
igInstaller.install(spec);
// Newer version is current
runInTransaction(() -> {
NpmPackageVersionEntity versionEntity = myPackageVersionDao.findByPackageIdAndVersion("hl7.fhir.uv.shorthand", "0.11.1").orElseThrow(() -> new IllegalArgumentException());
assertEquals(false, versionEntity.isCurrentVersion());
versionEntity = myPackageVersionDao.findByPackageIdAndVersion("hl7.fhir.uv.shorthand", "0.12.0").orElseThrow(() -> new IllegalArgumentException());
assertEquals(true, versionEntity.isCurrentVersion());
});
// Fetching a resource should return the newer version
runInTransaction(() -> {
ImplementationGuide ig = (ImplementationGuide) myPackageCacheManager.loadPackageAssetByUrl(FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ImplementationGuide/hl7.fhir.uv.shorthand");
assertEquals("0.12.0", ig.getVersion());
});
}
@Test
public void testInstallOlderPackageDoesntUpdateLatestVersionFlag() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.12.0", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.12.0.tgz"));
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.11.1", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.11.1.tgz"));
// Install newer version
PackageInstallationSpec spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.12.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
igInstaller.install(spec);
runInTransaction(() -> {
NpmPackageVersionEntity versionEntity = myPackageVersionDao.findByPackageIdAndVersion("hl7.fhir.uv.shorthand", "0.12.0").orElseThrow(() -> new IllegalArgumentException());
assertEquals(true, versionEntity.isCurrentVersion());
});
// Fetching a resource should return the older version
runInTransaction(() -> {
ImplementationGuide ig = (ImplementationGuide) myPackageCacheManager.loadPackageAssetByUrl(FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ImplementationGuide/hl7.fhir.uv.shorthand");
assertEquals("0.12.0", ig.getVersion());
});
// Install older version
spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.11.1").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
igInstaller.install(spec);
// Newer version is still current
runInTransaction(() -> {
NpmPackageVersionEntity versionEntity = myPackageVersionDao.findByPackageIdAndVersion("hl7.fhir.uv.shorthand", "0.11.1").orElseThrow(() -> new IllegalArgumentException());
assertEquals(false, versionEntity.isCurrentVersion());
versionEntity = myPackageVersionDao.findByPackageIdAndVersion("hl7.fhir.uv.shorthand", "0.12.0").orElseThrow(() -> new IllegalArgumentException());
assertEquals(true, versionEntity.isCurrentVersion());
});
// Fetching a resource should return the newer version
runInTransaction(() -> {
ImplementationGuide ig = (ImplementationGuide) myPackageCacheManager.loadPackageAssetByUrl(FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ImplementationGuide/hl7.fhir.uv.shorthand");
assertEquals("0.12.0", ig.getVersion());
});
}
@Test
public void testInstallAlreadyExistingIsIgnored() throws Exception {
myDaoConfig.setAllowExternalReferences(true);
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.12.0", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.12.0.tgz"));
// Install
PackageInstallationSpec spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.12.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
igInstaller.install(spec);
runInTransaction(() -> {
NpmPackageVersionEntity versionEntity = myPackageVersionDao.findByPackageIdAndVersion("hl7.fhir.uv.shorthand", "0.12.0").orElseThrow(() -> new IllegalArgumentException());
assertEquals(true, versionEntity.isCurrentVersion());
});
// Install same again
spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.12.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY);
igInstaller.install(spec);
runInTransaction(() -> {
NpmPackageVersionEntity versionEntity = myPackageVersionDao.findByPackageIdAndVersion("hl7.fhir.uv.shorthand", "0.12.0").orElseThrow(() -> new IllegalArgumentException());
assertEquals(true, versionEntity.isCurrentVersion());
});
}
@Test
public void testInstallPkgContainingSearchParameter() throws IOException {
myDaoConfig.setAllowExternalReferences(true);
byte[] contents0111 = loadClasspathBytes("/packages/test-exchange-sample.tgz");
myFakeNpmServlet.myResponses.put("/test-exchange.fhir.us.com/2.1.1", contents0111);
contents0111 = loadClasspathBytes("/packages/test-exchange-sample-2.tgz");
myFakeNpmServlet.myResponses.put("/test-exchange.fhir.us.com/2.1.2", contents0111);
// Install older version
PackageInstallationSpec spec = new PackageInstallationSpec().setName("test-exchange.fhir.us.com").setVersion("2.1.1").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL);
igInstaller.install(spec);
IBundleProvider spSearch = mySearchParameterDao.search(SearchParameterMap.newSynchronous("code", new TokenParam("network-id")));
assertEquals(1, spSearch.sizeOrThrowNpe());
SearchParameter sp = (SearchParameter) spSearch.getResources(0, 1).get(0);
assertEquals("network-id", sp.getCode());
assertEquals("2.1", sp.getVersion());
assertEquals(Enumerations.PublicationStatus.ACTIVE, sp.getStatus());
Organization org = new Organization();
org.setName("Hello");
IIdType orgId = myOrganizationDao.create(org).getId().toUnqualifiedVersionless();
PractitionerRole pr = new PractitionerRole();
pr.addExtension().setUrl("http://test-exchange.com/fhir/us/providerdataexchange/StructureDefinition/networkreference").setValue(new Reference(orgId));
myPractitionerRoleDao.create(pr);
SearchParameterMap map = SearchParameterMap.newSynchronous("network-id", new ReferenceParam(orgId.getValue()));
spSearch = myPractitionerRoleDao.search(map);
assertEquals(1, spSearch.sizeOrThrowNpe());
// Install newer version
spec = new PackageInstallationSpec().setName("test-exchange.fhir.us.com").setVersion("2.1.2").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL);
igInstaller.install(spec);
spSearch = mySearchParameterDao.search(SearchParameterMap.newSynchronous("code", new TokenParam("network-id")));
assertEquals(1, spSearch.sizeOrThrowNpe());
sp = (SearchParameter) spSearch.getResources(0, 1).get(0);
assertEquals("network-id", sp.getCode());
assertEquals(Enumerations.PublicationStatus.ACTIVE, sp.getStatus());
assertEquals("2.2", sp.getVersion());
}
@Test
public void testLoadContents() throws IOException {
byte[] contents0111 = loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.11.1.tgz");
byte[] contents0120 = loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.12.0.tgz");
PackageInstallationSpec spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.11.1").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY).setPackageContents(contents0111);
igInstaller.install(spec);
spec = new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.12.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY).setPackageContents(contents0120);
igInstaller.install(spec);
assertArrayEquals(contents0111, myPackageCacheManager.loadPackageContents("hl7.fhir.uv.shorthand", "0.11.1").getBytes());
assertArrayEquals(contents0120, myPackageCacheManager.loadPackageContents("hl7.fhir.uv.shorthand", "0.12.0").getBytes());
assertArrayEquals(contents0120, myPackageCacheManager.loadPackageContents("hl7.fhir.uv.shorthand", "latest").getBytes());
assertEquals("0.11.1", myPackageCacheManager.loadPackageContents("hl7.fhir.uv.shorthand", "0.11.1").getVersion());
assertEquals("0.12.0", myPackageCacheManager.loadPackageContents("hl7.fhir.uv.shorthand", "0.12.0").getVersion());
assertEquals("0.12.0", myPackageCacheManager.loadPackageContents("hl7.fhir.uv.shorthand", "latest").getVersion());
assertEquals(null, myPackageCacheManager.loadPackageContents("hl7.fhir.uv.shorthand", "1.2.3"));
assertEquals(null, myPackageCacheManager.loadPackageContents("foo", "1.2.3"));
}
@Test
public void testDeletePackage() throws IOException {
myDaoConfig.setAllowExternalReferences(true);
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.12.0", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.12.0.tgz"));
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.11.1", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.11.1.tgz"));
myFakeNpmServlet.myResponses.put("/hl7.fhir.uv.shorthand/0.11.0", loadClasspathBytes("/packages/hl7.fhir.uv.shorthand-0.11.0.tgz"));
igInstaller.install(new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.12.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY));
igInstaller.install(new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.11.1").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY));
igInstaller.install(new PackageInstallationSpec().setName("hl7.fhir.uv.shorthand").setVersion("0.11.0").setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_ONLY));
runInTransaction(() -> {
Slice<NpmPackageVersionResourceEntity> versions = myPackageVersionResourceDao.findCurrentVersionByCanonicalUrl(Pageable.unpaged(), FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ValueSet/shorthand-instance-tags");
assertEquals(1, versions.getNumberOfElements());
NpmPackageVersionResourceEntity resource = versions.getContent().get(0);
assertEquals("0.12.0", resource.getCanonicalVersion());
});
myPackageCacheManager.uninstallPackage("hl7.fhir.uv.shorthand", "0.12.0");
runInTransaction(() -> {
Slice<NpmPackageVersionResourceEntity> versions = myPackageVersionResourceDao.findCurrentVersionByCanonicalUrl(Pageable.unpaged(), FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ValueSet/shorthand-instance-tags");
assertEquals(1, versions.getNumberOfElements());
NpmPackageVersionResourceEntity resource = versions.getContent().get(0);
assertEquals("0.11.1", resource.getCanonicalVersion());
});
myPackageCacheManager.uninstallPackage("hl7.fhir.uv.shorthand", "0.11.0");
runInTransaction(() -> {
Slice<NpmPackageVersionResourceEntity> versions = myPackageVersionResourceDao.findCurrentVersionByCanonicalUrl(Pageable.unpaged(), FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ValueSet/shorthand-instance-tags");
assertEquals(1, versions.getNumberOfElements());
NpmPackageVersionResourceEntity resource = versions.getContent().get(0);
assertEquals("0.11.1", resource.getCanonicalVersion());
});
myPackageCacheManager.uninstallPackage("hl7.fhir.uv.shorthand", "0.11.1");
runInTransaction(() -> {
Slice<NpmPackageVersionResourceEntity> versions = myPackageVersionResourceDao.findCurrentVersionByCanonicalUrl(Pageable.unpaged(), FhirVersionEnum.R4, "http://hl7.org/fhir/uv/shorthand/ValueSet/shorthand-instance-tags");
assertEquals(0, versions.getNumberOfElements());
});
}
static class FakeNpmServlet extends HttpServlet {
private final Map<String, byte[]> myResponses = new HashMap<>();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String requestUrl = req.getRequestURI();
if (myResponses.containsKey(requestUrl)) {
ourLog.info("Responding to request: {}", requestUrl);
resp.setStatus(200);
if (StringUtils.countMatches(requestUrl, "/") == 1) {
resp.setHeader(Constants.HEADER_CONTENT_TYPE, Constants.CT_JSON);
}else {
resp.setHeader(Constants.HEADER_CONTENT_TYPE, "application/gzip");
}
resp.getOutputStream().write(myResponses.get(requestUrl));
resp.getOutputStream().close();
} else {
ourLog.warn("Unknown request: {}", requestUrl);
resp.sendError(404);
}
}
public Map<String, byte[]> getResponses() {
return myResponses;
}
}
}
| apache-2.0 |
bstopp/acs-aem-commons | bundle/src/main/java/com/adobe/acs/commons/indesign/dynamicdeckdynamo/workflow/processes/impl/DynamicDeckBackTrackProcess.java | 14865 | /*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2020 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.indesign.dynamicdeckdynamo.workflow.processes.impl;
import com.adobe.acs.commons.indesign.dynamicdeckdynamo.constants.DynamicDeckDynamoConstants;
import com.adobe.acs.commons.indesign.dynamicdeckdynamo.exception.DynamicDeckDynamoException;
import com.adobe.acs.commons.indesign.dynamicdeckdynamo.utils.DynamicDeckUtils;
import com.adobe.aemds.guide.themes.GuideThemeConstants;
import com.adobe.granite.workflow.WorkflowException;
import com.adobe.granite.workflow.WorkflowSession;
import com.adobe.granite.workflow.exec.WorkItem;
import com.adobe.granite.workflow.exec.WorkflowProcess;
import com.adobe.granite.workflow.metadata.MetaDataMap;
import com.day.cq.dam.api.DamConstants;
import com.day.cq.dam.commons.util.DamUtil;
import com.day.cq.wcm.api.NameConstants;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.jackrabbit.core.fs.FileSystem;
import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.jcr.Session;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* This process tracks back the properties which are changed in the generated deck and updates its respective properties in all the assets.
*/
@Component(service = WorkflowProcess.class, property = {"process.label=Dynamic Deck Dynamo Write Back Process"})
public class DynamicDeckBackTrackProcess implements WorkflowProcess {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDeckBackTrackProcess.class);
@Override
public void execute(WorkItem workItem, WorkflowSession workflowSession, MetaDataMap metaDataMap) throws WorkflowException {
ResourceResolver resourceResolver;
try {
resourceResolver = workflowSession.adaptTo(ResourceResolver.class);
Session jcrSession = workflowSession.adaptTo(Session.class);
if (null == jcrSession) {
LOGGER.error("JCR Session is null");
return;
}
DynamicDeckUtils.updateUserData(jcrSession);
DynamicDeckUtils.updateUserData(resourceResolver.adaptTo(Session.class));
Resource assetResource = DynamicDeckUtils.getAssetResourceFromPayload(workItem, resourceResolver);
if (null == assetResource) {
LOGGER.error("Asset resource from payload is null");
return;
}
if (isFileEligibleToProcess(assetResource)) {
InputStream xmlInputStream = DynamicDeckUtils.getInddXmlRenditionInputStream(assetResource);
if (null == xmlInputStream) {
LOGGER.debug("File xml input stream is null, hence skipping the parsing process.");
return;
}
parseXML(xmlInputStream, resourceResolver);
} else {
LOGGER.info("File is not eligible to be parsed, hence skipping the parsing process.");
}
} catch (DynamicDeckDynamoException e) {
LOGGER.error("Back track: Error while parsing asset xml", e);
throw new WorkflowException("Error while performing back track operation", e);
}
}
private void parseXML(InputStream xmlInputStream, ResourceResolver resourceResolver) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
DocumentBuilder dBuilder = dbf.newDocumentBuilder();
Document doc = dBuilder.parse(xmlInputStream);
if (doc.hasChildNodes()) {
final String assetPath = StringUtils.EMPTY;
readNode(doc.getChildNodes(), assetPath, resourceResolver);
}
} catch (ParserConfigurationException | SAXException | IOException | DOMException | TransformerFactoryConfigurationError | DynamicDeckDynamoException e) {
LOGGER.error("Error while processing the xml template ", e);
}
}
private void readNode(NodeList nodeList, String assetPath, ResourceResolver resourceResolver) throws DOMException, DynamicDeckDynamoException {
for (int count = 0; count < nodeList.getLength(); count++) {
Node tempNode = nodeList.item(count);
// make sure it's element node.
if (tempNode.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
if (tempNode.hasAttributes()) {
// get attributes names and values
NamedNodeMap nodeMap = tempNode.getAttributes();
Node sectionType = nodeMap != null ? nodeMap.getNamedItem(DynamicDeckDynamoConstants.XML_ATTR_SECTION_TYPE) : null;
if (sectionType != null) {
assetPath = getAssetPath(nodeMap, assetPath);
if (StringUtils.isNotBlank(assetPath)) {
retrieveFieldValues(assetPath, tempNode, resourceResolver);
}
}
}
if (tempNode.hasChildNodes()) {
// loop again if has child nodes
readNode(tempNode.getChildNodes(), assetPath, resourceResolver);
}
}
DynamicDeckUtils.commit(resourceResolver);
}
private void retrieveFieldValues(String assetPath, Node sectionNode, ResourceResolver resourceResolver) throws DynamicDeckDynamoException {
NodeList childNodes = sectionNode.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
if (childNode.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
if (childNode.hasAttributes()) {
// get attributes names and values
NamedNodeMap nodeMap = childNode.getAttributes();
Node fieldTypeAttr = nodeMap != null ? nodeMap.getNamedItem(DynamicDeckDynamoConstants.XML_ATTR_FIELD_TYPE) : null;
Node dataSyncAttr = nodeMap != null ? nodeMap.getNamedItem(DynamicDeckDynamoConstants.XML_ATTR_DATA_SYNC) : null;
Node isArrayAttr = nodeMap != null ? nodeMap.getNamedItem(DynamicDeckDynamoConstants.XML_ATTR_IS_ARRAY) : null;
Boolean isArray = isArrayAttr != null && "true".equals(isArrayAttr.getNodeValue());
if (fieldTypeAttr != null && dataSyncAttr != null && "true".equals(dataSyncAttr.getNodeValue())) {
Resource assetResource = resourceResolver.getResource(assetPath);
ModifiableValueMap mValueMap = null;
if (assetResource != null) {
mValueMap = assetResource.adaptTo(ModifiableValueMap.class);
}
if (mValueMap != null) {
String fieldType = fieldTypeAttr.getNodeValue();
switch (fieldType) {
case "image":
handleImageType(assetResource, childNode, resourceResolver, isArray);
break;
case "text":
handleTextType(assetResource, childNode, isArray);
break;
default:
}
}
}
}
}
}
private void handleTextType(Resource assetResource, Node childNode, Boolean isArray) {
Node propertyPathNode = childNode.getAttributes().getNamedItem(DynamicDeckDynamoConstants.XML_ATTR_PROPERTY_PATH);
if (propertyPathNode != null) {
String propertyPath = getAssetPropertyPath(propertyPathNode.getNodeValue(), assetResource.getValueMap());
String textValue = childNode.getTextContent();
setNewPropertyValue(isArray, propertyPath, assetResource, textValue);
}
}
private void setNewPropertyValue(Boolean isArray, String propertyPath, Resource assetResource, String nodeContentValue) {
String nodePath = StringUtils.substringBeforeLast(propertyPath, "/");
ModifiableValueMap properties;
if (StringUtils.isNotBlank(nodePath)) {
Resource childResource = assetResource.getChild(nodePath);
properties = childResource.adaptTo(ModifiableValueMap.class);
propertyPath = StringUtils.substringAfterLast(propertyPath, "/");
} else {
properties = assetResource.adaptTo(ModifiableValueMap.class);
}
if (isArray) {
String index = StringUtils.substringBetween(propertyPath, "[", "]");
propertyPath = StringUtils.substringBeforeLast(propertyPath, "[");
int indexVal = Integer.parseInt(index);
String[] values = properties.get(propertyPath, String[].class);
if (indexVal >= values.length) {
values = Arrays.copyOf(values, indexVal + 1);
}
values[indexVal] = nodeContentValue;
properties.put(propertyPath, values);
} else {
properties.put(propertyPath, nodeContentValue);
}
}
private void handleImageType(Resource assetResource, Node childNode, ResourceResolver resourceResolver, Boolean isArray) throws DynamicDeckDynamoException {
Node propertyPathNode = childNode.getAttributes().getNamedItem(DynamicDeckDynamoConstants.XML_ATTR_PROPERTY_PATH);
if (propertyPathNode != null) {
String propertyPath = getAssetPropertyPath(propertyPathNode.getNodeValue(), assetResource.getValueMap());
Node hrefNode = childNode.getAttributes().getNamedItem(DavConstants.XML_HREF);
try {
if (hrefNode != null) {
String hrefValue = hrefNode.getNodeValue();
if (StringUtils.contains(hrefValue, "INDD-SERVER-DOCUMENTS/")) {
return;
}
String completeHrefValue = null;
if (hrefValue.contains(GuideThemeConstants.CONTENT_DAM_ROOT)) {
String hrefEncodedValue = StringUtils.substringAfter(
URLDecoder.decode(hrefValue, StandardCharsets.UTF_8.toString()), GuideThemeConstants.CONTENT_DAM_ROOT);
completeHrefValue = GuideThemeConstants.CONTENT_DAM_ROOT + hrefEncodedValue;
}
if (null == completeHrefValue) {
LOGGER.error("Back track root path is not correct {}", hrefValue);
return;
}
Resource imageResource = resourceResolver.getResource(completeHrefValue);
if (DamUtil.isAsset(imageResource)) {
setNewPropertyValue(isArray, propertyPath, assetResource, completeHrefValue);
} else {
LOGGER.error("ERROR: DATA SYNC : Invalid asset embedded. Asset not found in repository {}", hrefValue);
}
}
} catch (UnsupportedEncodingException e) {
throw new DynamicDeckDynamoException("Exception while handling the image type.", e);
}
}
}
private String getAssetPropertyPath(String nodeValue, ValueMap properties) {
String propertyPath = nodeValue;
if (!properties.containsKey(nodeValue)) {
propertyPath = "jcr:content/metadata/" + propertyPath;
}
return propertyPath;
}
private String getAssetPath(NamedNodeMap nodeMap, String assetPath) {
Node assetPathNode = nodeMap.getNamedItem(DynamicDeckDynamoConstants.XML_ATTR_ASSETPATH);
if (assetPathNode != null) {
return assetPathNode.getNodeValue();
}
return assetPath;
}
private boolean isFileEligibleToProcess(Resource assetResource) {
Resource metadataResource = assetResource.getResourceResolver()
.getResource(assetResource.getPath() + FileSystem.SEPARATOR + NameConstants.NN_CONTENT
+ FileSystem.SEPARATOR + DamConstants.METADATA_FOLDER);
if (null == metadataResource) {
LOGGER.error("Metadata resource is null, hence returning false");
return false;
}
ValueMap metadataValueMap = metadataResource.getValueMap();
Resource jcrContentResource = assetResource.getResourceResolver()
.getResource(assetResource.getPath() + FileSystem.SEPARATOR + NameConstants.NN_CONTENT);
if (null == jcrContentResource) {
LOGGER.error("JCR Content resource is null, hence returning false");
return false;
}
ValueMap jcrContentValueMap = jcrContentResource.getValueMap();
String assetMimeType = metadataValueMap.get(DamConstants.DC_FORMAT, String.class);
String assetTemplateType = jcrContentValueMap.get(DynamicDeckDynamoConstants.PN_INDD_TEMPLATE_TYPE, String.class);
String[] eligibleAssetMimeType = {DynamicDeckDynamoConstants.INDESIGN_MIME_TYPE};
return StringUtils.isNotEmpty(assetMimeType) && ArrayUtils.contains(eligibleAssetMimeType, assetMimeType)
&& StringUtils.isNotBlank(assetTemplateType) && assetTemplateType.equals(DynamicDeckDynamoConstants.DECK_TYPE);
}
}
| apache-2.0 |
lausd-teacher/schoolTools | src/net/videmantay/roster/seatingchart/ClassTimeMain.java | 541 | package net.videmantay.roster.seatingchart;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
public class ClassTimeMain extends Composite {
private static ClassTimeMainUiBinder uiBinder = GWT.create(ClassTimeMainUiBinder.class);
interface ClassTimeMainUiBinder extends UiBinder<Widget, ClassTimeMain> {
}
public ClassTimeMain() {
initWidget(uiBinder.createAndBindUi(this));
}
}
| apache-2.0 |
archos-sa/aos-MediaLib | src/com/uwetrottmann/trakt/v2/entities/Crew.java | 452 | package com.uwetrottmann.trakt.v2.entities;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Crew {
public List<CrewMember> writing;
public List<CrewMember> production;
public List<CrewMember> directing;
@SerializedName("costume & make-up")
public List<CrewMember> costumeAndMakeUp;
public List<CrewMember> art;
public List<CrewMember> sound;
public List<CrewMember> camera;
}
| apache-2.0 |
AiziChen/QMusicPlayer | app/src/main/java/service/MusicPlayerService.java | 4625 | package service;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import java.io.IOException;
import quanye.qmuiscplayer.R;
import quanye.qmuiscplayer.activity.MainActivity;
/**
* @author 陈权业
* 播放音乐的Service,可后台
*/
public class MusicPlayerService extends Service {
private final static String MUSIC_PATH = "quanye.qmusicplayer.MusicPlayerService.music_filepath";
private final static String CTRL_BCR = "quanye.qmusicplayer.MusicPlayerService.ControlBroadcastReceiver";
private final static String UPDATE_CMD = "update_command";
private MediaPlayer player;
/**
* 发送音乐路径通知广播
* @param context context
* @param path 音乐路径
*/
public static void sendBroadcast(Context context, String path, String cmd) {
Intent intent = new Intent(CTRL_BCR);
intent.putExtra(MUSIC_PATH, path);
intent.putExtra(UPDATE_CMD, cmd);
context.sendBroadcast(intent);
}
/**
* 控制广播接收器
*/
public class ControlBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String musicPath = intent.getStringExtra(MUSIC_PATH);
String cmd = intent.getStringExtra(UPDATE_CMD);
switch (cmd) {
case MainActivity.RESUME:
if (player != null && !player.isPlaying()) {
resume();
}
break;
case MainActivity.START:
playmusic(musicPath);
break;
case MainActivity.STATE_PAUSED:
pause();
break;
case MainActivity.STATE_STOPED:
stop();
break;
case MainActivity.NEXT:
// 发送广播让MainActivity类处理
break;
}
MainActivity.sendBroadcast(MusicPlayerService.this, cmd);
}
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// show hello toast
Toast.makeText(this, "Enjoy!", Toast.LENGTH_SHORT).show();
// init system Meidaplayer
player = new MediaPlayer();
// 播放完成当前歌曲后,继续播下一曲
player.setOnCompletionListener((MediaPlayer mp) -> {
MainActivity.sendBroadcast(MusicPlayerService.this, MainActivity.NEXT);
});
// register broadcastreceiver
IntentFilter filter = new IntentFilter();
filter.addAction(CTRL_BCR);
registerReceiver(new ControlBroadcastReceiver(), filter);
return super.onStartCommand(intent, flags, startId);
}
/**
* 开始播放音乐
* @param path 音乐文件路径
*/
private void playmusic(String path) {
// 若列表没有音乐,则不启动播放
if (path.equals(MainActivity.NO_MUSIC)) {
return;
}
// 重置音乐
player.reset();
try {
player.setDataSource(path);
player.prepare();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, getString(R.string.can_not_played_music), Toast.LENGTH_SHORT).show();
}
// 开始播放
player.start();
// 给activity发送“已经正在播放”状态的广播
MainActivity.sendBroadcast(MusicPlayerService.this, MainActivity.STATE_PLAYING);
}
/**
* 暂停播放
*/
private void pause() {
player.pause();
// 给activity发送“已经停止播放”状态的广播
MainActivity.sendBroadcast(MusicPlayerService.this, MainActivity.STATE_PAUSED);
}
/**
* 继续播放
*/
private void resume() {
player.start();
}
/**
* 停止播放
*/
private void stop() {
player.stop();
}
@Override
public void onDestroy() {
super.onDestroy();
player.release();
player = null;
}
}
| apache-2.0 |
ewertondias/vigas-web | web/src/main/java/com/vigas/web/controller/DashboardController.java | 522 | package com.vigas.web.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller()
@RequestMapping(value = "")
public class DashboardController {
@Value("${endpoint.services}")
private String endpoint;
@RequestMapping(value = "", method = RequestMethod.GET)
public String index() {
return "dashboard/index";
}
}
| apache-2.0 |
gengGjy/ChinaMobile | ChinaMobile/cmplayer/src/main/java/com/chinamobile/cmplayer/MeasureHelper.java | 10541 | /*
* Copyright (C) 2015 Zhang Rui <bbcallen@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.chinamobile.cmplayer;
import android.view.View;
import java.lang.ref.WeakReference;
public final class MeasureHelper {
private WeakReference<View> mWeakView;
private int mVideoWidth;
private int mVideoHeight;
private int mVideoSarNum;
private int mVideoSarDen;
private int mVideoRotationDegree;
private int mMeasuredWidth;
private int mMeasuredHeight;
private int mCurrentAspectRatio = IRenderView.AR_ASPECT_FIT_PARENT;
public MeasureHelper(View view) {
mWeakView = new WeakReference<View>(view);
}
public View getView() {
if (mWeakView == null)
return null;
return mWeakView.get();
}
public void setVideoSize(int videoWidth, int videoHeight) {
mVideoWidth = videoWidth;
mVideoHeight = videoHeight;
}
public void setVideoSampleAspectRatio(int videoSarNum, int videoSarDen) {
mVideoSarNum = videoSarNum;
mVideoSarDen = videoSarDen;
}
public void setVideoRotation(int videoRotationDegree) {
mVideoRotationDegree = videoRotationDegree;
}
/**
* Must be called by View.onMeasure(int, int)
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
public void doMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//Log.i("@@@@", "onMeasure(" + MeasureSpec.toString(widthMeasureSpec) + ", "
// + MeasureSpec.toString(heightMeasureSpec) + ")");
if (mVideoRotationDegree == 90 || mVideoRotationDegree == 270) {
int tempSpec = widthMeasureSpec;
widthMeasureSpec = heightMeasureSpec;
heightMeasureSpec = tempSpec;
}
int width = View.getDefaultSize(mVideoWidth, widthMeasureSpec);
int height = View.getDefaultSize(mVideoHeight, heightMeasureSpec);
if (mCurrentAspectRatio == IRenderView.AR_MATCH_PARENT) {
width = widthMeasureSpec;
height = heightMeasureSpec;
} else if (mVideoWidth > 0 && mVideoHeight > 0) {
int widthSpecMode = View.MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = View.MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = View.MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = View.MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == View.MeasureSpec.AT_MOST && heightSpecMode == View.MeasureSpec.AT_MOST) {
float specAspectRatio = (float) widthSpecSize / (float) heightSpecSize;
float displayAspectRatio;
switch (mCurrentAspectRatio) {
case IRenderView.AR_16_9_FIT_PARENT:
displayAspectRatio = 16.0f / 9.0f;
if (mVideoRotationDegree == 90 || mVideoRotationDegree == 270)
displayAspectRatio = 1.0f / displayAspectRatio;
break;
case IRenderView.AR_4_3_FIT_PARENT:
displayAspectRatio = 4.0f / 3.0f;
if (mVideoRotationDegree == 90 || mVideoRotationDegree == 270)
displayAspectRatio = 1.0f / displayAspectRatio;
break;
case IRenderView.AR_ASPECT_FIT_PARENT:
case IRenderView.AR_ASPECT_FILL_PARENT:
case IRenderView.AR_ASPECT_WRAP_CONTENT:
default:
displayAspectRatio = (float) mVideoWidth / (float) mVideoHeight;
if (mVideoSarNum > 0 && mVideoSarDen > 0)
displayAspectRatio = displayAspectRatio * mVideoSarNum / mVideoSarDen;
break;
}
boolean shouldBeWider = displayAspectRatio > specAspectRatio;
switch (mCurrentAspectRatio) {
case IRenderView.AR_ASPECT_FIT_PARENT:
case IRenderView.AR_16_9_FIT_PARENT:
case IRenderView.AR_4_3_FIT_PARENT:
if (shouldBeWider) {
// too wide, fix width
width = widthSpecSize;
height = (int) (width / displayAspectRatio);
} else {
// too high, fix height
height = heightSpecSize;
width = (int) (height * displayAspectRatio);
}
break;
case IRenderView.AR_ASPECT_FILL_PARENT:
if (shouldBeWider) {
// not high enough, fix height
height = heightSpecSize;
width = (int) (height * displayAspectRatio);
} else {
// not wide enough, fix width
width = widthSpecSize;
height = (int) (width / displayAspectRatio);
}
break;
case IRenderView.AR_ASPECT_WRAP_CONTENT:
default:
if (shouldBeWider) {
// too wide, fix width
width = Math.min(mVideoWidth, widthSpecSize);
height = (int) (width / displayAspectRatio);
} else {
// too high, fix height
height = Math.min(mVideoHeight, heightSpecSize);
width = (int) (height * displayAspectRatio);
}
break;
}
} else if (widthSpecMode == View.MeasureSpec.EXACTLY && heightSpecMode == View.MeasureSpec.EXACTLY) {
// the size is fixed
width = widthSpecSize;
height = heightSpecSize;
// for compatibility, we adjust size based on aspect ratio
if (mVideoWidth * height < width * mVideoHeight) {
//Log.i("@@@", "image too wide, correcting");
width = height * mVideoWidth / mVideoHeight;
} else if (mVideoWidth * height > width * mVideoHeight) {
//Log.i("@@@", "image too tall, correcting");
height = width * mVideoHeight / mVideoWidth;
}
} else if (widthSpecMode == View.MeasureSpec.EXACTLY) {
// only the width is fixed, adjust the height to match aspect ratio if possible
width = widthSpecSize;
height = width * mVideoHeight / mVideoWidth;
if (heightSpecMode == View.MeasureSpec.AT_MOST && height > heightSpecSize) {
// couldn't match aspect ratio within the constraints
height = heightSpecSize;
}
} else if (heightSpecMode == View.MeasureSpec.EXACTLY) {
// only the height is fixed, adjust the width to match aspect ratio if possible
height = heightSpecSize;
width = height * mVideoWidth / mVideoHeight;
if (widthSpecMode == View.MeasureSpec.AT_MOST && width > widthSpecSize) {
// couldn't match aspect ratio within the constraints
width = widthSpecSize;
}
} else {
// neither the width nor the height are fixed, try to use actual video size
width = mVideoWidth;
height = mVideoHeight;
if (heightSpecMode == View.MeasureSpec.AT_MOST && height > heightSpecSize) {
// too tall, decrease both width and height
height = heightSpecSize;
width = height * mVideoWidth / mVideoHeight;
}
if (widthSpecMode == View.MeasureSpec.AT_MOST && width > widthSpecSize) {
// too wide, decrease both width and height
width = widthSpecSize;
height = width * mVideoHeight / mVideoWidth;
}
}
} else {
// no size yet, just adopt the given spec sizes
}
mMeasuredWidth = width;
mMeasuredHeight = height;
}
public int getMeasuredWidth() {
return mMeasuredWidth;
}
public int getMeasuredHeight() {
return mMeasuredHeight;
}
public void setAspectRatio(int aspectRatio) {
mCurrentAspectRatio = aspectRatio;
}
// @NonNull
// public static String getAspectRatioText(Context context, int aspectRatio) {
// String text;
// switch (aspectRatio) {
// case IRenderView.AR_ASPECT_FIT_PARENT:
// text = context.getString(R.string.VideoView_ar_aspect_fit_parent);
// break;
// case IRenderView.AR_ASPECT_FILL_PARENT:
// text = context.getString(R.string.VideoView_ar_aspect_fill_parent);
// break;
// case IRenderView.AR_ASPECT_WRAP_CONTENT:
// text = context.getString(R.string.VideoView_ar_aspect_wrap_content);
// break;
// case IRenderView.AR_MATCH_PARENT:
// text = context.getString(R.string.VideoView_ar_match_parent);
// break;
// case IRenderView.AR_16_9_FIT_PARENT:
// text = context.getString(R.string.VideoView_ar_16_9_fit_parent);
// break;
// case IRenderView.AR_4_3_FIT_PARENT:
// text = context.getString(R.string.VideoView_ar_4_3_fit_parent);
// break;
// default:
// text = context.getString(R.string.N_A);
// break;
// }
// return text;
// }
}
| apache-2.0 |
ukyovirgden/spring-social-twitter | spring-social-twitter/src/main/java/org/springframework/social/twitter/api/impl/Coordinates.java | 1536 | package org.springframework.social.twitter.api.impl;
import org.springframework.social.twitter.api.TwitterObject;
/**
* Created by Oyku Gencay (oyku at gencay.net) on 12.08.2014.
*
*/
public class Coordinates extends TwitterObject{
private String type;
private Double longitude;
private Double latitude;
public Coordinates() {
}
public Coordinates(String type, Double longitude, Double latitude) {
this.type = type;
this.longitude = longitude;
this.latitude = latitude;
}
public String getType() {
return type;
}
public Double getLongitude() {
return longitude;
}
public Double getLatitude() {
return latitude;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coordinates that = (Coordinates) o;
if (latitude != null ? !latitude.equals(that.latitude) : that.latitude != null) return false;
if (longitude != null ? !longitude.equals(that.longitude) : that.longitude != null) return false;
if (type != null ? !type.equals(that.type) : that.type != null) return false;
return true;
}
@Override
public int hashCode() {
int result = type != null ? type.hashCode() : 0;
result = 31 * result + (longitude != null ? longitude.hashCode() : 0);
result = 31 * result + (latitude != null ? latitude.hashCode() : 0);
return result;
}
}
| apache-2.0 |
Shredder121/gh-event-api | src/main/java/com/github/shredder121/gh_event_api/handler/issues/IssuesEndpointController.java | 1727 | /*
* Copyright 2017 Shredder121.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.shredder121.gh_event_api.handler.issues;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.shredder121.gh_event_api.handler.AbstractEndpointController;
/**
* Endpoint controller for {@code issues} events.
*
* This controller is bound to {@link IssuesHandler}
* and will only be enabled when there are any on the component scan path.
*
* @author Shredder121
*/
@RestController
@RequestMapping(headers = "X-GitHub-Event=issues")
@ConditionalOnBean(IssuesHandler.class)
class IssuesEndpointController extends AbstractEndpointController<IssuesHandler, IssuesPayload> {
@Autowired
IssuesEndpointController(Collection<? extends IssuesHandler> beans) {
super(beans);
}
@Override
protected Runnable runnableHandler(IssuesHandler handler, IssuesPayload payload) {
return () -> handler.handle(payload);
}
}
| apache-2.0 |
jon-stumpf/traccar | test/org/traccar/protocol/Jt600ProtocolDecoderTest.java | 5584 | package org.traccar.protocol;
import org.traccar.ProtocolTest;
import org.junit.Test;
public class Jt600ProtocolDecoderTest extends ProtocolTest {
@Test
public void testDecode() throws Exception {
Jt600ProtocolDecoder decoder = new Jt600ProtocolDecoder(new Jt600Protocol());
verifyPositions(decoder, binary(
"24408111888821001B09060908045322564025113242329F0598000001003F0000002D00AB"));
verifyPositions(decoder, binary(
"2475609213701711002701010000020200000000000000000e00000000000f000000000020c164cd7b00d516000f0f0f02"));
verifyPositions(decoder, binary(
"24657060730131001b13111710361906538525079524797f000000000000000003f300036c"));
verifyPositions(decoder, binary(
"24624090196121001b19071703493631277203074235752f295800005308010000768b0822"));
verifyPositions(decoder, binary(
"24624090196123019519071703412131285623074214252f10560000130801000076850819071703420631282832074215165f172c0000030801000076850919071703422131282792074216635f222e0000130801000076850919071703423631282808074218261f212a0000130801000076860819071703435131283678074222928f08350000930801000076860919071703440631283003074223174f19500000930801000076870819071703445131279872074224584f07380000930801000076870819071703453631280643074227091f1b220000530801000076880919071703455131281043074228216f0a260000530801000076880819071703460631281229074228988f0c260000530801000076880819071703462131281551074229954f1f220000530801000076880919071703463631281289074230503f114e0000530801000076880819071703465131281186074230884f094f0000530801000076880819071703470631280308074231240f17500000530801000076880619071703472131280358074231636f0b1d0000530801000076890821"));
verifyPositions(decoder, binary(
"2475604055531611002311111600311326144436028210791d016c0000001f070000000020c03c4f6d07d80ccf"));
verifyPositions(decoder, binary(
"2475201509260111002313101503464722331560113555309F00000000002D0500CB206800F064109326381A03"));
verifyPositions(decoder, binary(
"2475605035891613002328091601152806086750106533350c00000000000a000000000000e1ff4f97007f1607"));
verifyPosition(decoder, buffer(
"(3301210003,U01,040812,185302,T,22.564025,N,113.242329,E,5.21,152,9,32%,00000000000011,10133,5173,22,100,1)"));
verifyPosition(decoder, buffer(
"(3301210003,U02,040812,185302,T,22.564025,N,113.242329,E,5,152,9,32%,00000000000011,10133,5173,22,100,1)"));
verifyPosition(decoder, buffer(
"(3301210003,U03,040812,185302,T,22.564025,N,113.242329,E,5,152,9,32%,00000000000011,10133,5173,22,100,1)"));
verifyNull(decoder, buffer(
"(3301210003,U04)"));
verifyPosition(decoder, buffer(
"(3301210003,U06,1,040812,185302,T,22.564025,N,113.242329,E,5,152,9,32%,0000000000011,10133,5173,22,100,1,300,100,10)"));
verifyPosition(decoder, buffer(
"(3460311327,U01,220916,135251,T,9.552607,N,13.658292,W,0.31,0,9,0%,00001001000000,11012,10,27,0,0,33)"));
verifyPosition(decoder, buffer(
"(3460311327,U01,010100,000024,F,0.000000,N,0.000000,E,0.00,0,0,100%,00000001000000,263,1,18,0,0,33)"));
verifyNull(decoder, buffer(
"(3460311327,@JT)"));
verifyPosition(decoder, buffer(
"(3460311327,U06,11,220916,135643,T,9.552553,N,13.658265,W,0.61,0,9,100%,00000001000000,11012,10,30,0,0,126,0,30)"));
verifyPosition(decoder, buffer(
"(3460311327,U06,10,220916,140619,T,9.552495,N,13.658227,W,0.43,0,7,0%,00101001000000,11012,10,0,0,0,126,0,30)"));
verifyPositions(decoder, binary(
"24311021600111001B16021105591022329862114046227B0598095080012327951435161F"),
position("2011-02-16 05:59:10.000", true, 22.54977, -114.07705));
verifyPositions(decoder, binary(
"24312082002911001B171012052831243810120255336425001907190003FD2B91044D1FA0"));
verifyPositions(decoder, binary(
"24312082002911001B1710120533052438099702553358450004061E0003EE000000000C00"));
verifyPositions(decoder, binary(
"24608111888821001B09060908045322564025113242329F0598000001003F0000002D00AB"));
verifyPosition(decoder, buffer(
"(3110312099,W01,11404.6204,E,2232.9961,N,A,040511,063736,4,7,100,4,17,1,1,company)"),
position("2011-05-04 06:37:36.000", true, 22.54994, 114.07701));
verifyPosition(decoder, buffer(
"(3120820029,W01,02553.3555,E,2438.0997,S,A,171012,053339,0,8,20,6,31,5,20,20)"));
verifyPosition(decoder, buffer(
"(3330104377,U01,010100,010228,F,00.000000,N,000.000000,E,0,0,0,0%,00001000000000,741,14,22,0,206)"));
verifyNull(decoder, buffer(
"(6221107674,2,U09,129,2,A,280513113036,E,02711.0500,S,1721.0876,A,030613171243,E,02756.7618,S,2300.0325,3491,538200,14400,1)"));
verifyPosition(decoder, buffer(
"(3301210003,U02,040812,185302,T,00.000000,N,000.000000,E,0,0,0,0%,00000000000011,741,51,22,0,1,05)"));
verifyPosition(decoder, buffer(
"(3301210003,U06,4,250916,133207,T,7.011013,N,25.060708,W,27.61,102,10,0%,00101011000000,0,1,0,448,0,126,1,30)"));
verifyPosition(decoder, buffer(
"(3551001012,U01,010100,000032,F,0.000000,N,0.000000,E,0.00,0,0,10%,00000000010000,15748,7923,23,0,0,3E)"));
}
}
| apache-2.0 |
zhishan332/mana | src/main/java/com/wq/util/SystemUtil.java | 547 | package com.wq.util;
import javax.swing.filechooser.FileSystemView;
/**
* Created with IntelliJ IDEA.
* User: wangq
* Date: 13-5-20
* Time: 下午2:54
* To change this template use File | Settings | File Templates.
*/
public class SystemUtil {
/**
* 返回一个与系统无关的用户路径
*
* @return
*/
public static String getDefaultUserFile() {
FileSystemView fsv = FileSystemView.getFileSystemView(); //注意了,这里重要的一句
return fsv.getHomeDirectory().getPath();
}
}
| apache-2.0 |
rorogarcete/jbpm-console-ng | jbpm-console-ng-process-runtime/jbpm-console-ng-process-runtime-client/src/main/java/org/jbpm/console/ng/pr/client/editors/definition/details/multi/basic/BasicProcessDefDetailsMultiPresenter.java | 4059 | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.jbpm.console.ng.pr.client.editors.definition.details.multi.basic;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import org.jbpm.console.ng.pr.client.editors.definition.details.multi.BaseProcessDefDetailsMultiPresenter;
import org.uberfire.client.annotations.DefaultPosition;
import org.uberfire.client.annotations.WorkbenchMenu;
import org.uberfire.client.annotations.WorkbenchPartView;
import org.uberfire.client.annotations.WorkbenchScreen;
import org.uberfire.client.mvp.UberView;
import org.uberfire.workbench.model.Position;
import org.uberfire.workbench.model.menu.MenuFactory;
import org.uberfire.workbench.model.menu.MenuItem;
import org.uberfire.workbench.model.menu.Menus;
import org.uberfire.workbench.model.menu.impl.BaseMenuCustom;
import com.google.gwt.user.client.ui.IsWidget;
@Dependent
@WorkbenchScreen(identifier = "Basic Process Details Multi", preferredWidth = 500)
public class BasicProcessDefDetailsMultiPresenter extends BaseProcessDefDetailsMultiPresenter {
public interface BasicProcessDefDetailsMultiView extends
BaseProcessDefDetailsMultiPresenter.BaseProcessDefDetailsMultiView {
}
@Inject
BasicProcessDefDetailsMultiView view;
@DefaultPosition
public Position getPosition() {
return super.getDefaultPosition();
}
@WorkbenchPartView
public UberView<BaseProcessDefDetailsMultiPresenter> getView() {
return view;
}
@Override
protected void setDefaultTab() {
view.getTabPanel().selectTab( 0 );
}
@WorkbenchMenu
public Menus buildMenu() {
return MenuFactory
.newTopLevelCustomMenu( new MenuFactory.CustomMenuBuilder() {
@Override
public void push( MenuFactory.CustomMenuBuilder element ) {
}
@Override
public MenuItem build() {
return new BaseMenuCustom<IsWidget>() {
@Override
public IsWidget build() {
return view.getNewInstanceButton();
}
};
}
} ).endMenu()
.newTopLevelCustomMenu( new MenuFactory.CustomMenuBuilder() {
@Override
public void push( MenuFactory.CustomMenuBuilder element ) {
}
@Override
public MenuItem build() {
return new BaseMenuCustom<IsWidget>() {
@Override
public IsWidget build() {
return view.getRefreshButton();
}
};
}
} ).endMenu()
.newTopLevelCustomMenu( new MenuFactory.CustomMenuBuilder() {
@Override
public void push( MenuFactory.CustomMenuBuilder element ) {
}
@Override
public MenuItem build() {
return new BaseMenuCustom<IsWidget>() {
@Override
public IsWidget build() {
return view.getCloseButton();
}
};
}
} ).endMenu().build();
}
}
| apache-2.0 |
yynil/elasticsearch | core/src/test/java/org/elasticsearch/search/aggregations/BaseAggregationTestCase.java | 16783 | /*
* 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.search.aggregations;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.inject.AbstractModule;
import org.elasticsearch.common.inject.Injector;
import org.elasticsearch.common.inject.ModulesBuilder;
import org.elasticsearch.common.inject.multibindings.Multibinder;
import org.elasticsearch.common.inject.util.Providers;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.SettingsModule;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.EnvironmentModule;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.AbstractQueryTestCase;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.indices.IndicesModule;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptContextRegistry;
import org.elasticsearch.script.ScriptEngineRegistry;
import org.elasticsearch.script.ScriptEngineService;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptSettings;
import org.elasticsearch.search.SearchModule;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.IndexSettingsModule;
import org.elasticsearch.test.InternalSettingsPlugin;
import org.elasticsearch.test.VersionUtils;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.ThreadPoolModule;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.elasticsearch.cluster.service.ClusterServiceUtils.createClusterService;
import static org.elasticsearch.cluster.service.ClusterServiceUtils.setState;
import static org.hamcrest.Matchers.equalTo;
public abstract class BaseAggregationTestCase<AB extends AggregatorBuilder<AB>> extends ESTestCase {
protected static final String STRING_FIELD_NAME = "mapped_string";
protected static final String INT_FIELD_NAME = "mapped_int";
protected static final String DOUBLE_FIELD_NAME = "mapped_double";
protected static final String BOOLEAN_FIELD_NAME = "mapped_boolean";
protected static final String DATE_FIELD_NAME = "mapped_date";
protected static final String OBJECT_FIELD_NAME = "mapped_object";
protected static final String[] mappedFieldNames = new String[]{STRING_FIELD_NAME, INT_FIELD_NAME,
DOUBLE_FIELD_NAME, BOOLEAN_FIELD_NAME, DATE_FIELD_NAME, OBJECT_FIELD_NAME};
private static Injector injector;
private static Index index;
private static String[] currentTypes;
protected static String[] getCurrentTypes() {
return currentTypes;
}
private static NamedWriteableRegistry namedWriteableRegistry;
protected static AggregatorParsers aggParsers;
protected static IndicesQueriesRegistry queriesRegistry;
protected static ParseFieldMatcher parseFieldMatcher;
protected abstract AB createTestAggregatorBuilder();
/**
* Setup for the whole base test class.
*/
@BeforeClass
public static void init() throws IOException {
// we have to prefer CURRENT since with the range of versions we support it's rather unlikely to get the current actually.
Version version = randomBoolean() ? Version.CURRENT
: VersionUtils.randomVersionBetween(random(), Version.V_2_0_0_beta1, Version.CURRENT);
Settings settings = Settings.builder()
.put("node.name", AbstractQueryTestCase.class.toString())
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
.put(ScriptService.SCRIPT_AUTO_RELOAD_ENABLED_SETTING.getKey(), false)
.build();
namedWriteableRegistry = new NamedWriteableRegistry();
index = new Index(randomAsciiOfLengthBetween(1, 10), "_na_");
Settings indexSettings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, version).build();
final ThreadPool threadPool = new ThreadPool(settings);
final ClusterService clusterService = createClusterService(threadPool);
setState(clusterService, new ClusterState.Builder(clusterService.state()).metaData(new MetaData.Builder()
.put(new IndexMetaData.Builder(index.getName()).settings(indexSettings).numberOfShards(1).numberOfReplicas(0))));
SettingsModule settingsModule = new SettingsModule(settings);
settingsModule.registerSetting(InternalSettingsPlugin.VERSION_CREATED);
ScriptModule scriptModule = new ScriptModule() {
@Override
protected void configure() {
Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
// no file watching, so we don't need a
// ResourceWatcherService
.put(ScriptService.SCRIPT_AUTO_RELOAD_ENABLED_SETTING.getKey(), false).build();
MockScriptEngine mockScriptEngine = new MockScriptEngine();
Multibinder<ScriptEngineService> multibinder = Multibinder.newSetBinder(binder(), ScriptEngineService.class);
multibinder.addBinding().toInstance(mockScriptEngine);
Set<ScriptEngineService> engines = new HashSet<>();
engines.add(mockScriptEngine);
List<ScriptContext.Plugin> customContexts = new ArrayList<>();
ScriptEngineRegistry scriptEngineRegistry = new ScriptEngineRegistry(Collections
.singletonList(new ScriptEngineRegistry.ScriptEngineRegistration(MockScriptEngine.class, MockScriptEngine.TYPES)));
bind(ScriptEngineRegistry.class).toInstance(scriptEngineRegistry);
ScriptContextRegistry scriptContextRegistry = new ScriptContextRegistry(customContexts);
bind(ScriptContextRegistry.class).toInstance(scriptContextRegistry);
ScriptSettings scriptSettings = new ScriptSettings(scriptEngineRegistry, scriptContextRegistry);
bind(ScriptSettings.class).toInstance(scriptSettings);
try {
ScriptService scriptService = new ScriptService(settings, new Environment(settings), engines, null,
scriptEngineRegistry, scriptContextRegistry, scriptSettings);
bind(ScriptService.class).toInstance(scriptService);
} catch (IOException e) {
throw new IllegalStateException("error while binding ScriptService", e);
}
}
};
scriptModule.prepareSettings(settingsModule);
injector = new ModulesBuilder().add(
new EnvironmentModule(new Environment(settings)),
settingsModule,
new ThreadPoolModule(threadPool),
scriptModule,
new IndicesModule() {
@Override
protected void configure() {
bindMapperExtension();
}
}, new SearchModule(settings, namedWriteableRegistry) {
@Override
protected void configureSearch() {
// Skip me
}
},
new IndexSettingsModule(index, settings),
new AbstractModule() {
@Override
protected void configure() {
bind(ClusterService.class).toProvider(Providers.of(clusterService));
bind(CircuitBreakerService.class).to(NoneCircuitBreakerService.class);
bind(NamedWriteableRegistry.class).toInstance(namedWriteableRegistry);
}
}
).createInjector();
aggParsers = injector.getInstance(AggregatorParsers.class);
//create some random type with some default field, those types will stick around for all of the subclasses
currentTypes = new String[randomIntBetween(0, 5)];
for (int i = 0; i < currentTypes.length; i++) {
String type = randomAsciiOfLengthBetween(1, 10);
currentTypes[i] = type;
}
queriesRegistry = injector.getInstance(IndicesQueriesRegistry.class);
parseFieldMatcher = ParseFieldMatcher.STRICT;
}
@AfterClass
public static void afterClass() throws Exception {
injector.getInstance(ClusterService.class).close();
terminate(injector.getInstance(ThreadPool.class));
injector = null;
index = null;
aggParsers = null;
currentTypes = null;
namedWriteableRegistry = null;
}
/**
* Generic test that creates new AggregatorFactory from the test
* AggregatorFactory and checks both for equality and asserts equality on
* the two queries.
*/
public void testFromXContent() throws IOException {
AB testAgg = createTestAggregatorBuilder();
AggregatorFactories.Builder factoriesBuilder = AggregatorFactories.builder().addAggregator(testAgg);
XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
if (randomBoolean()) {
builder.prettyPrint();
}
factoriesBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS);
XContentBuilder shuffled = shuffleXContent(builder, Collections.emptySet());
XContentParser parser = XContentFactory.xContent(shuffled.bytes()).createParser(shuffled.bytes());
QueryParseContext parseContext = new QueryParseContext(queriesRegistry);
parseContext.reset(parser);
parseContext.parseFieldMatcher(parseFieldMatcher);
assertSame(XContentParser.Token.START_OBJECT, parser.nextToken());
assertSame(XContentParser.Token.FIELD_NAME, parser.nextToken());
assertEquals(testAgg.name, parser.currentName());
assertSame(XContentParser.Token.START_OBJECT, parser.nextToken());
assertSame(XContentParser.Token.FIELD_NAME, parser.nextToken());
assertEquals(testAgg.type.name(), parser.currentName());
assertSame(XContentParser.Token.START_OBJECT, parser.nextToken());
AggregatorBuilder<?> newAgg = aggParsers.parser(testAgg.getType(), ParseFieldMatcher.STRICT).parse(testAgg.name, parseContext);
assertSame(XContentParser.Token.END_OBJECT, parser.currentToken());
assertSame(XContentParser.Token.END_OBJECT, parser.nextToken());
assertSame(XContentParser.Token.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken());
assertNotNull(newAgg);
assertNotSame(newAgg, testAgg);
assertEquals(testAgg, newAgg);
assertEquals(testAgg.hashCode(), newAgg.hashCode());
}
/**
* Test serialization and deserialization of the test AggregatorFactory.
*/
public void testSerialization() throws IOException {
AB testAgg = createTestAggregatorBuilder();
try (BytesStreamOutput output = new BytesStreamOutput()) {
output.writeAggregatorBuilder(testAgg);
try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
AggregatorBuilder deserialized = in.readAggregatorBuilder();
assertEquals(testAgg, deserialized);
assertEquals(testAgg.hashCode(), deserialized.hashCode());
assertNotSame(testAgg, deserialized);
}
}
}
public void testEqualsAndHashcode() throws IOException {
AB firstAgg = createTestAggregatorBuilder();
assertFalse("aggregation is equal to null", firstAgg.equals(null));
assertFalse("aggregation is equal to incompatible type", firstAgg.equals(""));
assertTrue("aggregation is not equal to self", firstAgg.equals(firstAgg));
assertThat("same aggregation's hashcode returns different values if called multiple times", firstAgg.hashCode(),
equalTo(firstAgg.hashCode()));
AB secondQuery = copyAggregation(firstAgg);
assertTrue("aggregation is not equal to self", secondQuery.equals(secondQuery));
assertTrue("aggregation is not equal to its copy", firstAgg.equals(secondQuery));
assertTrue("equals is not symmetric", secondQuery.equals(firstAgg));
assertThat("aggregation copy's hashcode is different from original hashcode", secondQuery.hashCode(), equalTo(firstAgg.hashCode()));
AB thirdQuery = copyAggregation(secondQuery);
assertTrue("aggregation is not equal to self", thirdQuery.equals(thirdQuery));
assertTrue("aggregation is not equal to its copy", secondQuery.equals(thirdQuery));
assertThat("aggregation copy's hashcode is different from original hashcode", secondQuery.hashCode(),
equalTo(thirdQuery.hashCode()));
assertTrue("equals is not transitive", firstAgg.equals(thirdQuery));
assertThat("aggregation copy's hashcode is different from original hashcode", firstAgg.hashCode(), equalTo(thirdQuery.hashCode()));
assertTrue("equals is not symmetric", thirdQuery.equals(secondQuery));
assertTrue("equals is not symmetric", thirdQuery.equals(firstAgg));
}
// we use the streaming infra to create a copy of the query provided as
// argument
private AB copyAggregation(AB agg) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
agg.writeTo(output);
try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
@SuppressWarnings("unchecked")
AB secondAgg = (AB) namedWriteableRegistry.getReader(AggregatorBuilder.class, agg.getWriteableName()).read(in);
return secondAgg;
}
}
}
protected String[] getRandomTypes() {
String[] types;
if (currentTypes.length > 0 && randomBoolean()) {
int numberOfQueryTypes = randomIntBetween(1, currentTypes.length);
types = new String[numberOfQueryTypes];
for (int i = 0; i < numberOfQueryTypes; i++) {
types[i] = randomFrom(currentTypes);
}
} else {
if (randomBoolean()) {
types = new String[]{MetaData.ALL};
} else {
types = new String[0];
}
}
return types;
}
public String randomNumericField() {
int randomInt = randomInt(3);
switch (randomInt) {
case 0:
return DATE_FIELD_NAME;
case 1:
return DOUBLE_FIELD_NAME;
case 2:
default:
return INT_FIELD_NAME;
}
}
}
| apache-2.0 |
NickOdessa/java_qa | addressbook-web-tests/src/test/java/com/qa/java/addressbook/tests/ContactAddToGroupTest.java | 1854 | package com.qa.java.addressbook.tests;
import com.qa.java.addressbook.model.ContactData;
import com.qa.java.addressbook.model.Contacts;
import com.qa.java.addressbook.model.GroupData;
import com.qa.java.addressbook.model.Groups;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Created by user on 02.02.2017.
*/
public class ContactAddToGroupTest extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
if (app.db().contacts().size() == 0) { //проверяем есть ли контакт, если нет, то создаем его
app.contact().create(new ContactData()
.withFirstname("Nick22")
.withLastname("Petrov1")
.withNickname("Nick12")
.withCompany("Own Company")
.withAddress("Odessa, Ukraine")
.withMobilePhone("+380487777777")
.withEmail("nick_test@mailinator.com"), true);
}
if (app.db().groups().size() == 0){
app.goTo().groupPage();
app.group().create(new GroupData().withName("Test 123"));
}
}
@Test
public void testContactAddToGroup(){
app.goTo().returnToHomePage();
Contacts before = app.db().contacts();
Groups groups = app.db().groups();
ContactData selectedAContact = before.iterator().next();
GroupData group = groups.iterator().next();
Groups beforeGroups = app.db().getIdGroupsToContact(selectedAContact.getId());
app.contact().selectContact(selectedAContact);
app.goTo().returnToHomePage();
app.contact().selectContactAdded1();
Groups afterGroups=app.db().getIdGroupsToContact(selectedAContact.getId());
assertThat(afterGroups, equalTo(beforeGroups.withAdded(group)));
}
}
| apache-2.0 |
mcekovic/tennis-crystal-ball | tennis-stats/src/main/java/org/strangeforest/tcb/stats/model/records/details/SeasonRankingPctDiffRecordDetail.java | 719 | package org.strangeforest.tcb.stats.model.records.details;
import com.fasterxml.jackson.annotation.*;
import static java.lang.String.*;
public class SeasonRankingPctDiffRecordDetail extends BaseSeasonRankingDiffRecordDetail<String> {
public SeasonRankingPctDiffRecordDetail(
@JsonProperty("value") double value,
@JsonProperty("player_id2") int playerId2,
@JsonProperty("name2") String name2,
@JsonProperty("country_id2") String countryId2,
@JsonProperty("active2") Boolean active2,
@JsonProperty("value1") int value1,
@JsonProperty("value2") int value2,
@JsonProperty("season") int season
) {
super(format("%1$.1f%%", value), playerId2, name2, countryId2, active2, value1, value2, season);
}
}
| apache-2.0 |
sogou-biztech/compass | aggregation/src/main/java/com/sogou/bizdev/compass/aggregation/datasource/Shard.java | 1310 | package com.sogou.bizdev.compass.aggregation.datasource;
import java.util.LinkedList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.util.CollectionUtils;
import com.sogou.bizdev.compass.core.router.TableContext;
/**
* 分表信息,保存了主从数据源、目标物理数据源、分库分表信息(TableContext)
* @author yk
* @since 1.0.0
*/
public class Shard
{
private DataSource targetDataSource;
private TableContext tableContext;
private List<Object> routeKeys=null;
public Shard(DataSource targetDataSource, TableContext tableContext)
{
this.targetDataSource = targetDataSource;
this.tableContext = tableContext;
}
public DataSource getTargetDataSource() {
return targetDataSource;
}
public void setTargetDataSource(DataSource targetDataSource) {
this.targetDataSource = targetDataSource;
}
public TableContext getTableContext() {
return tableContext;
}
public void setTableContext(TableContext tableContext) {
this.tableContext = tableContext;
}
public List<Object> getRouteKeys() {
return routeKeys;
}
public void addRouteKey(Object routeKey)
{
if(CollectionUtils.isEmpty(this.routeKeys))
{
this.routeKeys=new LinkedList<Object>();
}
this.routeKeys.add(routeKey);
}
}
| apache-2.0 |
OpenGamma/Strata | modules/product/src/test/java/com/opengamma/strata/product/deposit/ResolvedTermDepositTradeTest.java | 2803 | /*
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.product.deposit;
import static com.opengamma.strata.basics.currency.Currency.GBP;
import static com.opengamma.strata.basics.date.DayCounts.ACT_365F;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static com.opengamma.strata.collect.TestHelper.date;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import com.opengamma.strata.product.TradeInfo;
/**
* Test {@link ResolvedTermDepositTrade}.
*/
public class ResolvedTermDepositTradeTest {
private static final LocalDate START_DATE = LocalDate.of(2015, 1, 19);
private static final LocalDate END_DATE = LocalDate.of(2015, 7, 20);
private static final double YEAR_FRACTION = ACT_365F.yearFraction(START_DATE, END_DATE);
private static final double PRINCIPAL = 100000000d;
private static final double RATE = 0.0250;
private static final ResolvedTermDeposit DEPOSIT = ResolvedTermDeposit.builder()
.currency(GBP)
.notional(PRINCIPAL)
.startDate(START_DATE)
.endDate(END_DATE)
.yearFraction(YEAR_FRACTION)
.rate(RATE)
.build();
private static final TradeInfo TRADE_INFO = TradeInfo.of(date(2014, 6, 30));
//-------------------------------------------------------------------------
@Test
public void test_of() {
ResolvedTermDepositTrade test = ResolvedTermDepositTrade.of(TRADE_INFO, DEPOSIT);
assertThat(test.getProduct()).isEqualTo(DEPOSIT);
assertThat(test.getInfo()).isEqualTo(TRADE_INFO);
}
@Test
public void test_builder() {
ResolvedTermDepositTrade test = ResolvedTermDepositTrade.builder()
.product(DEPOSIT)
.info(TRADE_INFO)
.build();
assertThat(test.getProduct()).isEqualTo(DEPOSIT);
assertThat(test.getInfo()).isEqualTo(TRADE_INFO);
}
//-------------------------------------------------------------------------
@Test
public void coverage() {
ResolvedTermDepositTrade test1 = ResolvedTermDepositTrade.builder()
.product(DEPOSIT)
.info(TRADE_INFO)
.build();
coverImmutableBean(test1);
ResolvedTermDepositTrade test2 = ResolvedTermDepositTrade.builder()
.product(DEPOSIT)
.build();
coverBeanEquals(test1, test2);
}
@Test
public void test_serialization() {
ResolvedTermDepositTrade test = ResolvedTermDepositTrade.builder()
.product(DEPOSIT)
.info(TRADE_INFO)
.build();
assertSerialization(test);
}
}
| apache-2.0 |
li24361/mybatis-generator-core | src/main/java/org/mybatis/generator/internal/rules/Rules.java | 9143 | /**
* Copyright 2006-2015 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.mybatis.generator.internal.rules;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
/**
* This interface centralizes all the rules related to code generation -
* including the methods and objects to create, and certain attributes related
* to those objects.
*
* @author Jeff Butler
*/
public interface Rules {
/**
* Implements the rule for generating the insert SQL Map element and DAO
* method. If the insert statement is allowed, then generate the element and
* method.
*
* @return true if the element and method should be generated
*/
boolean generateInsert();
/**
* Implements the rule for generating the insert selective SQL Map element
* and DAO method. If the insert statement is allowed, then generate the
* element and method.
*
* @return true if the element and method should be generated
*/
boolean generateInsertSelective();
/**
* Calculates the class that contains all fields. This class is used as the
* insert statement parameter, as well as the returned value from the select
* by primary key method. The actual class depends on how the domain model
* is generated.
*
* @return the type of the class that holds all fields
*/
FullyQualifiedJavaType calculateAllFieldsClass();
/**
* Implements the rule for generating the update by primary key without
* BLOBs SQL Map element and DAO method. If the table has a primary key as
* well as other non-BLOB fields, and the updateByPrimaryKey statement is
* allowed, then generate the element and method.
*
* @return true if the element and method should be generated
*/
boolean generateUpdateByPrimaryKeyWithoutBLOBs();
/**
* Implements the rule for generating the update by primary key with BLOBs
* SQL Map element and DAO method. If the table has a primary key as well as
* other BLOB fields, and the updateByPrimaryKey statement is allowed, then
* generate the element and method.
*
* @return true if the element and method should be generated
*/
boolean generateUpdateByPrimaryKeyWithBLOBs();
/**
* Implements the rule for generating the update by primary key selective
* SQL Map element and DAO method. If the table has a primary key as well as
* other fields, and the updateByPrimaryKey statement is allowed, then
* generate the element and method.
*
* @return true if the element and method should be generated
*/
boolean generateUpdateByPrimaryKeySelective();
/**
* Implements the rule for generating the delete by primary key SQL Map
* element and DAO method. If the table has a primary key, and the
* deleteByPrimaryKey statement is allowed, then generate the element and
* method.
*
* @return true if the element and method should be generated
*/
boolean generateDeleteByPrimaryKey();
/**
* Implements the rule for generating the delete by example SQL Map element
* and DAO method. If the deleteByExample statement is allowed, then
* generate the element and method.
*
* @return true if the element and method should be generated
*/
boolean generateDeleteByExample();
/**
* Implements the rule for generating the result map without BLOBs. If
* either select method is allowed, then generate the result map.
*
* @return true if the result map should be generated
*/
boolean generateBaseResultMap();
/**
* Implements the rule for generating the result map with BLOBs. If the
* table has BLOB columns, and either select method is allowed, then
* generate the result map.
*
* @return true if the result map should be generated
*/
boolean generateResultMapWithBLOBs();
/**
* Implements the rule for generating the SQL example where clause element.
*
* In iBATIS2, generate the element if the selectByExample, deleteByExample,
* updateByExample, or countByExample statements are allowed.
*
* In MyBatis3, generate the element if the selectByExample,
* deleteByExample, or countByExample statements are allowed.
*
* @return true if the SQL where clause element should be generated
*/
boolean generateSQLExampleWhereClause();
/**
* Implements the rule for generating the SQL example where clause element
* specifically for use in the update by example methods.
*
* In iBATIS2, do not generate the element.
*
* In MyBatis, generate the element if the updateByExample statements are
* allowed.
*
* @return true if the SQL where clause element should be generated
*/
boolean generateMyBatis3UpdateByExampleWhereClause();
/**
* Implements the rule for generating the SQL base column list element.
* Generate the element if any of the select methods are enabled.
*
* @return true if the SQL base column list element should be generated
*/
boolean generateBaseColumnList();
/**
* Implements the rule for generating the SQL blob column list element.
* Generate the element if any of the select methods are enabled, and the
* table contains BLOB columns.
*
* @return true if the SQL blob column list element should be generated
*/
boolean generateBlobColumnList();
/**
* Implements the rule for generating the select by primary key SQL Map
* element and DAO method. If the table has a primary key as well as other
* fields, and the selectByPrimaryKey statement is allowed, then generate
* the element and method.
*
* @return true if the element and method should be generated
*/
boolean generateSelectByPrimaryKey();
/**
* Implements the rule for generating the select by example without BLOBs
* SQL Map element and DAO method. If the selectByExample statement is
* allowed, then generate the element and method.
*
* @return true if the element and method should be generated
*/
boolean generateSelectByExampleWithoutBLOBs();
/**
* Implements the rule for generating the select by example with BLOBs SQL
* Map element and DAO method. If the table has BLOB fields and the
* selectByExample statement is allowed, then generate the element and
* method.
*
* @return true if the element and method should be generated
*/
boolean generateSelectByExampleWithBLOBs();
/**
* Implements the rule for generating an example class. The class should be
* generated if the selectByExample or deleteByExample or countByExample
* methods are allowed.
*
* @return true if the example class should be generated
*/
boolean generateExampleClass();
boolean generateCountByExample();
boolean generateUpdateByExampleSelective();
boolean generateUpdateByExampleWithoutBLOBs();
boolean generateUpdateByExampleWithBLOBs();
/**
* Implements the rule for determining whether to generate a primary key
* class. If you return false from this method, and the table has primary
* key columns, then the primary key columns will be added to the base
* class.
*
* @return true if a separate primary key class should be generated
*/
boolean generatePrimaryKeyClass();
/**
* Implements the rule for generating a base record.
*
* @return true if the class should be generated
*/
boolean generateBaseRecordClass();
/**
* Implements the rule for generating a record with BLOBs. If you return
* false from this method, and the table had BLOB columns, then the BLOB
* columns will be added to the base class.
*
* @return true if the record with BLOBs class should be generated
*/
boolean generateRecordWithBLOBsClass();
/**
* Implements the rule for generating a Java client. This rule is
* only active when a javaClientGenerator configuration has been
* specified, but the table is designated as "modelOnly". Do not
* generate the client if the table is designated as modelOnly.
*
* @return true if the Java client should be generated
*/
boolean generateJavaClient();
IntrospectedTable getIntrospectedTable();
}
| apache-2.0 |
thomasfischl/kylang | com.github.thomasfischl.kylang/test/com/github/thomasfischl/kylang/runtime/ScriptedKeywordTest.java | 533 | package com.github.thomasfischl.kylang.runtime;
import java.io.InputStreamReader;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import org.junit.Test;
public class ScriptedKeywordTest {
@Test
public void scriptKeywordTest() throws ScriptException {
KyLangScriptEngineFactory factory = new KyLangScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
engine.eval(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("scriptKeywordTest.kytest")));
}
}
| apache-2.0 |
jathusanT/pebble_colors | colors/src/main/java/com/jathusan/pebble/colors/RGBObject.java | 983 | package com.jathusan.pebble.colors;
public class RGBObject {
private boolean isAbsolute;
private int rValue;
private int gValue;
private int bValue;
private boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
public boolean isAbsolute() {
return isAbsolute;
}
public void setAbsolute(boolean isAbsolute) {
this.isAbsolute = isAbsolute;
}
public int getRValue() {
return rValue;
}
public void setRValue(int rValue) {
this.rValue = rValue;
}
public int getGValue() {
return gValue;
}
public void setGValue(int gValue) {
this.gValue = gValue;
}
public int getBValue() {
return bValue;
}
public void setBValue(int bValue) {
this.bValue = bValue;
}
}
| apache-2.0 |
menglingchong/SmartBeijing | src/com/heima/smartbeijing/domain/PhotosBean.java | 303 | package com.heima.smartbeijing.domain;
import java.util.ArrayList;
public class PhotosBean {
public PhotosData data;
public class PhotosData{
public ArrayList<PhotoNews> news;
}
public class PhotoNews{
public int id;
public String title;
public String listimage;
}
}
| apache-2.0 |
TNG/ArchUnit | archunit/src/test/java/com/tngtech/archunit/core/importer/testexamples/simpleimport/AnnotationToImport.java | 406 | package com.tngtech.archunit.core.importer.testexamples.simpleimport;
import java.util.List;
@SuppressWarnings("unused")
public @interface AnnotationToImport {
String someStringMethod() default "DEFAULT";
Class<?> someTypeMethod() default List.class;
EnumToImport someEnumMethod() default EnumToImport.SECOND;
AnnotationParameter someAnnotationMethod() default @AnnotationParameter;
}
| apache-2.0 |
xiaohu846627/hello-world | ArchitectTutorial/src/main/java/com/example/thread/queue/MyObject.java | 741 | package com.example.thread.queue;
public class MyObject {
public synchronized void method1() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void method2() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
final MyObject myObject = new MyObject();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
myObject.method1();
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
myObject.method2();
}
}, "t2");
t1.start();
synchronized (t2) {
}
t2.start();
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/transform/UpdateTrustRequestMarshaller.java | 2306 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.directory.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.directory.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateTrustRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateTrustRequestMarshaller {
private static final MarshallingInfo<String> TRUSTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("TrustId").build();
private static final MarshallingInfo<String> SELECTIVEAUTH_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SelectiveAuth").build();
private static final UpdateTrustRequestMarshaller instance = new UpdateTrustRequestMarshaller();
public static UpdateTrustRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(UpdateTrustRequest updateTrustRequest, ProtocolMarshaller protocolMarshaller) {
if (updateTrustRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateTrustRequest.getTrustId(), TRUSTID_BINDING);
protocolMarshaller.marshall(updateTrustRequest.getSelectiveAuth(), SELECTIVEAUTH_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
joschi/JadConfig | src/test/java/com/github/joschi/jadconfig/converters/ByteConverterTest.java | 1955 | package com.github.joschi.jadconfig.converters;
import com.github.joschi.jadconfig.ParameterException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Unit tests for {@link ByteConverter}
*
* @author jschalanda
*/
public class ByteConverterTest {
private ByteConverter converter;
@Before
public void setUp() {
converter = new ByteConverter();
}
@Test
public void testConvertFrom() {
Assert.assertEquals(Byte.valueOf((byte) 0), converter.convertFrom("0"));
Assert.assertEquals(Byte.valueOf((byte) 1), converter.convertFrom("1"));
Assert.assertEquals(Byte.valueOf((byte) -1), converter.convertFrom("-1"));
Assert.assertEquals(Byte.MIN_VALUE, converter.convertFrom("-128").byteValue());
Assert.assertEquals(Byte.MAX_VALUE, converter.convertFrom("127").byteValue());
}
@Test(expected = ParameterException.class)
public void testConvertFromTooBig() {
converter.convertFrom("128");
}
@Test(expected = ParameterException.class)
public void testConvertFromTooSmall() {
converter.convertFrom("-129");
}
@Test(expected = ParameterException.class)
public void testConvertFromNull() {
converter.convertFrom(null);
}
@Test(expected = ParameterException.class)
public void testConvertInvalid() {
converter.convertFrom("Not a number");
}
@Test
public void testConvertTo() {
Assert.assertEquals("0", converter.convertTo((byte) 0));
Assert.assertEquals("1", converter.convertTo((byte) 1));
Assert.assertEquals("-1", converter.convertTo((byte) -1));
Assert.assertEquals("-128", converter.convertTo(Byte.MIN_VALUE));
Assert.assertEquals("127", converter.convertTo(Byte.MAX_VALUE));
}
@Test(expected = ParameterException.class)
public void testConvertToNull() {
converter.convertTo(null);
}
}
| apache-2.0 |
wentch/redkale | src/org/redkale/net/http/RestCookie.java | 992 | /*
* 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 org.redkale.net.http;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 只能注解于RestService类的方法的String参数或参数内的String字段
* <p>
* 详情见: https://redkale.org
*
* @author zhangjx
*/
@Inherited
@Documented
@Target({PARAMETER, FIELD})
@Retention(RUNTIME)
public @interface RestCookie {
/**
* cookie名
*
* @return String
*/
String name();
/**
* 转换数字byte/short/int/long时所用的进制数, 默认10进制
*
* @return int
*/
int radix() default 10;
/**
* 备注描述
*
* @return String
*/
String comment() default "";
}
| apache-2.0 |
rostam/gradoop | gradoop-flink/src/main/java/org/gradoop/flink/model/impl/operators/sampling/statistics/functions/AddSumDegreesToGraphHeadCrossFunction.java | 1952 | /*
* Copyright © 2014 - 2019 Leipzig University (Database Research Group)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradoop.flink.model.impl.operators.sampling.statistics.functions;
import org.apache.flink.api.common.functions.CrossFunction;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.common.model.impl.pojo.GraphHead;
import org.gradoop.flink.model.impl.tuples.WithCount;
/**
* Writes the sum of vertex degrees as property to the graphHead.
*/
public class AddSumDegreesToGraphHeadCrossFunction
implements CrossFunction<WithCount<GradoopId>, GraphHead, GraphHead> {
/**
* The used property key for the sum of vertex degrees
*/
private final String propertyKey;
/**
* Constructor
*
* @param propertyKey The used property key for the sum of vertex degrees
*/
public AddSumDegreesToGraphHeadCrossFunction(String propertyKey) {
this.propertyKey = propertyKey;
}
/**
* Writes the sum of vertex degrees as property to the graphHead
*
* @param gradoopIdWithCount The {@code WithCount}-Object containing the sum-value
* @param graphHead The graphHead the sum-value is written to
* @return The graphHead with the sum-value as property
*/
@Override
public GraphHead cross(WithCount<GradoopId> gradoopIdWithCount, GraphHead graphHead) {
graphHead.setProperty(propertyKey, gradoopIdWithCount.getCount());
return graphHead;
}
}
| apache-2.0 |
dbflute-test/dbflute-test-dbms-db2 | src/main/java/org/docksidestage/db2/dbflute/exbhv/MemberFollowingBhv.java | 362 | package org.docksidestage.db2.dbflute.exbhv;
import org.docksidestage.db2.dbflute.bsbhv.BsMemberFollowingBhv;
/**
* The behavior of MEMBER_FOLLOWING.
* <p>
* You can implement your original methods here.
* This class remains when re-generating.
* </p>
* @author DBFlute(AutoGenerator)
*/
public class MemberFollowingBhv extends BsMemberFollowingBhv {
}
| apache-2.0 |
tinosteinort/beanrepository | src/main/java/com/github/tinosteinort/beanrepository/ConstructorWithBeansAnd5Parameters.java | 289 | package com.github.tinosteinort.beanrepository;
@FunctionalInterface
public interface ConstructorWithBeansAnd5Parameters<B, PARAM_1, PARAM_2, PARAM_3, PARAM_4, PARAM_5> {
B create(BeanAccessor beans, PARAM_1 param1, PARAM_2 param2, PARAM_3 param3, PARAM_4 param4, PARAM_5 param5);
}
| apache-2.0 |
zeatul/learn | java-example/src/main/java/com/hawk/utility/App.java | 2802 | package com.hawk.utility;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.concurrent.CompletionService;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.sun.jndi.toolkit.ctx.AtomicContext;
/**
* Hello world!
*
*/
public class App {
private AtomicInteger atomicInteger;
private AtomicBoolean atomicBoolean;
private AtomicReference<Object> atomicReference;
private AtomicLong atomicLong;
private AtomicIntegerArray atomicIntegerArray;
private AtomicLongArray atomicLongArray;
private AtomicReferenceArray<Object> atomicReferenceArray;
private AtomicReferenceFieldUpdater<Object, Object> update = AtomicReferenceFieldUpdater.newUpdater(Object.class, Object.class, "");
public void x() {
// atomicInteger.compareAndSet(expect, update)
// update.compareAndSet(obj, expect, update);
Object.class.getFields();// 返回该类及其父类的公有字段
Object.class.getDeclaredFields(); // 返回该类的所有字段,不包括父类的。
// represented by this Class object. This includes public, protected,
// default (package) access, and private fields, but excludes inherited
// fields.
}
public static void main(String[] args) throws Exception{
String s = "你好";
byte[] b = s.getBytes("utf-8");
System.out.println("b1=" + b.length);
b = Arrays.copyOf(b, b.length - 2);
System.out.println("b2=" + b.length);
s = new String(b, "utf-8");
System.out.println(s);
System.out.println("b3=" + s.getBytes("utf-8").length);
}
// System.out.println( "Hello World!" );
//
//// ReentrantLock lock = new ReentrantLock();
////
//// lock.tryLock();
//// lock.newCondition();
//// lock.unlock();
//// Thread.sleep(1000*60);
//
// class Super {
//
// }
//
// class Sub extends Super{
//
// }
//
// System.out.println(Super.class.isAssignableFrom(Sub.class));
//
// NoClassDefFoundError x;
//
// ExecutorService s = Executors.newCachedThreadPool();
// s.inv
//
// CompletionService<Long> completionService = new
// ExecutorCompletionService<Long>(s);
// completionService.take();
}
| apache-2.0 |
googleapis/java-datacatalog | proto-google-cloud-datacatalog-v1/src/main/java/com/google/cloud/datacatalog/v1/SerializedPolicyTag.java | 48480 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/datacatalog/v1/policytagmanagerserialization.proto
package com.google.cloud.datacatalog.v1;
/**
*
*
* <pre>
* A nested protocol buffer that represents a policy tag and all its
* descendants.
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1.SerializedPolicyTag}
*/
public final class SerializedPolicyTag extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datacatalog.v1.SerializedPolicyTag)
SerializedPolicyTagOrBuilder {
private static final long serialVersionUID = 0L;
// Use SerializedPolicyTag.newBuilder() to construct.
private SerializedPolicyTag(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SerializedPolicyTag() {
policyTag_ = "";
displayName_ = "";
description_ = "";
childPolicyTags_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SerializedPolicyTag();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private SerializedPolicyTag(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
policyTag_ = s;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
displayName_ = s;
break;
}
case 26:
{
java.lang.String s = input.readStringRequireUtf8();
description_ = s;
break;
}
case 34:
{
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
childPolicyTags_ =
new java.util.ArrayList<com.google.cloud.datacatalog.v1.SerializedPolicyTag>();
mutable_bitField0_ |= 0x00000001;
}
childPolicyTags_.add(
input.readMessage(
com.google.cloud.datacatalog.v1.SerializedPolicyTag.parser(),
extensionRegistry));
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
childPolicyTags_ = java.util.Collections.unmodifiableList(childPolicyTags_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1.PolicyTagManagerSerializationProto
.internal_static_google_cloud_datacatalog_v1_SerializedPolicyTag_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1.PolicyTagManagerSerializationProto
.internal_static_google_cloud_datacatalog_v1_SerializedPolicyTag_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1.SerializedPolicyTag.class,
com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder.class);
}
public static final int POLICY_TAG_FIELD_NUMBER = 1;
private volatile java.lang.Object policyTag_;
/**
*
*
* <pre>
* Resource name of the policy tag.
* This field is ignored when calling `ImportTaxonomies`.
* </pre>
*
* <code>string policy_tag = 1;</code>
*
* @return The policyTag.
*/
@java.lang.Override
public java.lang.String getPolicyTag() {
java.lang.Object ref = policyTag_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
policyTag_ = s;
return s;
}
}
/**
*
*
* <pre>
* Resource name of the policy tag.
* This field is ignored when calling `ImportTaxonomies`.
* </pre>
*
* <code>string policy_tag = 1;</code>
*
* @return The bytes for policyTag.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPolicyTagBytes() {
java.lang.Object ref = policyTag_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
policyTag_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DISPLAY_NAME_FIELD_NUMBER = 2;
private volatile java.lang.Object displayName_;
/**
*
*
* <pre>
* Required. Display name of the policy tag. At most 200 bytes when encoded
* in UTF-8.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The displayName.
*/
@java.lang.Override
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
displayName_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Display name of the policy tag. At most 200 bytes when encoded
* in UTF-8.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for displayName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DESCRIPTION_FIELD_NUMBER = 3;
private volatile java.lang.Object description_;
/**
*
*
* <pre>
* Description of the serialized policy tag. At most
* 2000 bytes when encoded in UTF-8. If not set, defaults to an
* empty description.
* </pre>
*
* <code>string description = 3;</code>
*
* @return The description.
*/
@java.lang.Override
public java.lang.String getDescription() {
java.lang.Object ref = description_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
description_ = s;
return s;
}
}
/**
*
*
* <pre>
* Description of the serialized policy tag. At most
* 2000 bytes when encoded in UTF-8. If not set, defaults to an
* empty description.
* </pre>
*
* <code>string description = 3;</code>
*
* @return The bytes for description.
*/
@java.lang.Override
public com.google.protobuf.ByteString getDescriptionBytes() {
java.lang.Object ref = description_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
description_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CHILD_POLICY_TAGS_FIELD_NUMBER = 4;
private java.util.List<com.google.cloud.datacatalog.v1.SerializedPolicyTag> childPolicyTags_;
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.datacatalog.v1.SerializedPolicyTag>
getChildPolicyTagsList() {
return childPolicyTags_;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.datacatalog.v1.SerializedPolicyTagOrBuilder>
getChildPolicyTagsOrBuilderList() {
return childPolicyTags_;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
@java.lang.Override
public int getChildPolicyTagsCount() {
return childPolicyTags_.size();
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1.SerializedPolicyTag getChildPolicyTags(int index) {
return childPolicyTags_.get(index);
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1.SerializedPolicyTagOrBuilder getChildPolicyTagsOrBuilder(
int index) {
return childPolicyTags_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(policyTag_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, policyTag_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, displayName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(description_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, description_);
}
for (int i = 0; i < childPolicyTags_.size(); i++) {
output.writeMessage(4, childPolicyTags_.get(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(policyTag_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, policyTag_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, displayName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(description_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, description_);
}
for (int i = 0; i < childPolicyTags_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, childPolicyTags_.get(i));
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.datacatalog.v1.SerializedPolicyTag)) {
return super.equals(obj);
}
com.google.cloud.datacatalog.v1.SerializedPolicyTag other =
(com.google.cloud.datacatalog.v1.SerializedPolicyTag) obj;
if (!getPolicyTag().equals(other.getPolicyTag())) return false;
if (!getDisplayName().equals(other.getDisplayName())) return false;
if (!getDescription().equals(other.getDescription())) return false;
if (!getChildPolicyTagsList().equals(other.getChildPolicyTagsList())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + POLICY_TAG_FIELD_NUMBER;
hash = (53 * hash) + getPolicyTag().hashCode();
hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER;
hash = (53 * hash) + getDisplayName().hashCode();
hash = (37 * hash) + DESCRIPTION_FIELD_NUMBER;
hash = (53 * hash) + getDescription().hashCode();
if (getChildPolicyTagsCount() > 0) {
hash = (37 * hash) + CHILD_POLICY_TAGS_FIELD_NUMBER;
hash = (53 * hash) + getChildPolicyTagsList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.datacatalog.v1.SerializedPolicyTag prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A nested protocol buffer that represents a policy tag and all its
* descendants.
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1.SerializedPolicyTag}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datacatalog.v1.SerializedPolicyTag)
com.google.cloud.datacatalog.v1.SerializedPolicyTagOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1.PolicyTagManagerSerializationProto
.internal_static_google_cloud_datacatalog_v1_SerializedPolicyTag_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1.PolicyTagManagerSerializationProto
.internal_static_google_cloud_datacatalog_v1_SerializedPolicyTag_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1.SerializedPolicyTag.class,
com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder.class);
}
// Construct using com.google.cloud.datacatalog.v1.SerializedPolicyTag.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getChildPolicyTagsFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
policyTag_ = "";
displayName_ = "";
description_ = "";
if (childPolicyTagsBuilder_ == null) {
childPolicyTags_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
childPolicyTagsBuilder_.clear();
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datacatalog.v1.PolicyTagManagerSerializationProto
.internal_static_google_cloud_datacatalog_v1_SerializedPolicyTag_descriptor;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.SerializedPolicyTag getDefaultInstanceForType() {
return com.google.cloud.datacatalog.v1.SerializedPolicyTag.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.SerializedPolicyTag build() {
com.google.cloud.datacatalog.v1.SerializedPolicyTag result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.SerializedPolicyTag buildPartial() {
com.google.cloud.datacatalog.v1.SerializedPolicyTag result =
new com.google.cloud.datacatalog.v1.SerializedPolicyTag(this);
int from_bitField0_ = bitField0_;
result.policyTag_ = policyTag_;
result.displayName_ = displayName_;
result.description_ = description_;
if (childPolicyTagsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
childPolicyTags_ = java.util.Collections.unmodifiableList(childPolicyTags_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.childPolicyTags_ = childPolicyTags_;
} else {
result.childPolicyTags_ = childPolicyTagsBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.datacatalog.v1.SerializedPolicyTag) {
return mergeFrom((com.google.cloud.datacatalog.v1.SerializedPolicyTag) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datacatalog.v1.SerializedPolicyTag other) {
if (other == com.google.cloud.datacatalog.v1.SerializedPolicyTag.getDefaultInstance())
return this;
if (!other.getPolicyTag().isEmpty()) {
policyTag_ = other.policyTag_;
onChanged();
}
if (!other.getDisplayName().isEmpty()) {
displayName_ = other.displayName_;
onChanged();
}
if (!other.getDescription().isEmpty()) {
description_ = other.description_;
onChanged();
}
if (childPolicyTagsBuilder_ == null) {
if (!other.childPolicyTags_.isEmpty()) {
if (childPolicyTags_.isEmpty()) {
childPolicyTags_ = other.childPolicyTags_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureChildPolicyTagsIsMutable();
childPolicyTags_.addAll(other.childPolicyTags_);
}
onChanged();
}
} else {
if (!other.childPolicyTags_.isEmpty()) {
if (childPolicyTagsBuilder_.isEmpty()) {
childPolicyTagsBuilder_.dispose();
childPolicyTagsBuilder_ = null;
childPolicyTags_ = other.childPolicyTags_;
bitField0_ = (bitField0_ & ~0x00000001);
childPolicyTagsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getChildPolicyTagsFieldBuilder()
: null;
} else {
childPolicyTagsBuilder_.addAllMessages(other.childPolicyTags_);
}
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.datacatalog.v1.SerializedPolicyTag parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.datacatalog.v1.SerializedPolicyTag) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object policyTag_ = "";
/**
*
*
* <pre>
* Resource name of the policy tag.
* This field is ignored when calling `ImportTaxonomies`.
* </pre>
*
* <code>string policy_tag = 1;</code>
*
* @return The policyTag.
*/
public java.lang.String getPolicyTag() {
java.lang.Object ref = policyTag_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
policyTag_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Resource name of the policy tag.
* This field is ignored when calling `ImportTaxonomies`.
* </pre>
*
* <code>string policy_tag = 1;</code>
*
* @return The bytes for policyTag.
*/
public com.google.protobuf.ByteString getPolicyTagBytes() {
java.lang.Object ref = policyTag_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
policyTag_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Resource name of the policy tag.
* This field is ignored when calling `ImportTaxonomies`.
* </pre>
*
* <code>string policy_tag = 1;</code>
*
* @param value The policyTag to set.
* @return This builder for chaining.
*/
public Builder setPolicyTag(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
policyTag_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Resource name of the policy tag.
* This field is ignored when calling `ImportTaxonomies`.
* </pre>
*
* <code>string policy_tag = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearPolicyTag() {
policyTag_ = getDefaultInstance().getPolicyTag();
onChanged();
return this;
}
/**
*
*
* <pre>
* Resource name of the policy tag.
* This field is ignored when calling `ImportTaxonomies`.
* </pre>
*
* <code>string policy_tag = 1;</code>
*
* @param value The bytes for policyTag to set.
* @return This builder for chaining.
*/
public Builder setPolicyTagBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
policyTag_ = value;
onChanged();
return this;
}
private java.lang.Object displayName_ = "";
/**
*
*
* <pre>
* Required. Display name of the policy tag. At most 200 bytes when encoded
* in UTF-8.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The displayName.
*/
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
displayName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Display name of the policy tag. At most 200 bytes when encoded
* in UTF-8.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for displayName.
*/
public com.google.protobuf.ByteString getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Display name of the policy tag. At most 200 bytes when encoded
* in UTF-8.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The displayName to set.
* @return This builder for chaining.
*/
public Builder setDisplayName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
displayName_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Display name of the policy tag. At most 200 bytes when encoded
* in UTF-8.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearDisplayName() {
displayName_ = getDefaultInstance().getDisplayName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Display name of the policy tag. At most 200 bytes when encoded
* in UTF-8.
* </pre>
*
* <code>string display_name = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for displayName to set.
* @return This builder for chaining.
*/
public Builder setDisplayNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
displayName_ = value;
onChanged();
return this;
}
private java.lang.Object description_ = "";
/**
*
*
* <pre>
* Description of the serialized policy tag. At most
* 2000 bytes when encoded in UTF-8. If not set, defaults to an
* empty description.
* </pre>
*
* <code>string description = 3;</code>
*
* @return The description.
*/
public java.lang.String getDescription() {
java.lang.Object ref = description_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
description_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Description of the serialized policy tag. At most
* 2000 bytes when encoded in UTF-8. If not set, defaults to an
* empty description.
* </pre>
*
* <code>string description = 3;</code>
*
* @return The bytes for description.
*/
public com.google.protobuf.ByteString getDescriptionBytes() {
java.lang.Object ref = description_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
description_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Description of the serialized policy tag. At most
* 2000 bytes when encoded in UTF-8. If not set, defaults to an
* empty description.
* </pre>
*
* <code>string description = 3;</code>
*
* @param value The description to set.
* @return This builder for chaining.
*/
public Builder setDescription(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
description_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Description of the serialized policy tag. At most
* 2000 bytes when encoded in UTF-8. If not set, defaults to an
* empty description.
* </pre>
*
* <code>string description = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearDescription() {
description_ = getDefaultInstance().getDescription();
onChanged();
return this;
}
/**
*
*
* <pre>
* Description of the serialized policy tag. At most
* 2000 bytes when encoded in UTF-8. If not set, defaults to an
* empty description.
* </pre>
*
* <code>string description = 3;</code>
*
* @param value The bytes for description to set.
* @return This builder for chaining.
*/
public Builder setDescriptionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
description_ = value;
onChanged();
return this;
}
private java.util.List<com.google.cloud.datacatalog.v1.SerializedPolicyTag> childPolicyTags_ =
java.util.Collections.emptyList();
private void ensureChildPolicyTagsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
childPolicyTags_ =
new java.util.ArrayList<com.google.cloud.datacatalog.v1.SerializedPolicyTag>(
childPolicyTags_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1.SerializedPolicyTag,
com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder,
com.google.cloud.datacatalog.v1.SerializedPolicyTagOrBuilder>
childPolicyTagsBuilder_;
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public java.util.List<com.google.cloud.datacatalog.v1.SerializedPolicyTag>
getChildPolicyTagsList() {
if (childPolicyTagsBuilder_ == null) {
return java.util.Collections.unmodifiableList(childPolicyTags_);
} else {
return childPolicyTagsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public int getChildPolicyTagsCount() {
if (childPolicyTagsBuilder_ == null) {
return childPolicyTags_.size();
} else {
return childPolicyTagsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public com.google.cloud.datacatalog.v1.SerializedPolicyTag getChildPolicyTags(int index) {
if (childPolicyTagsBuilder_ == null) {
return childPolicyTags_.get(index);
} else {
return childPolicyTagsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public Builder setChildPolicyTags(
int index, com.google.cloud.datacatalog.v1.SerializedPolicyTag value) {
if (childPolicyTagsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChildPolicyTagsIsMutable();
childPolicyTags_.set(index, value);
onChanged();
} else {
childPolicyTagsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public Builder setChildPolicyTags(
int index, com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder builderForValue) {
if (childPolicyTagsBuilder_ == null) {
ensureChildPolicyTagsIsMutable();
childPolicyTags_.set(index, builderForValue.build());
onChanged();
} else {
childPolicyTagsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public Builder addChildPolicyTags(com.google.cloud.datacatalog.v1.SerializedPolicyTag value) {
if (childPolicyTagsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChildPolicyTagsIsMutable();
childPolicyTags_.add(value);
onChanged();
} else {
childPolicyTagsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public Builder addChildPolicyTags(
int index, com.google.cloud.datacatalog.v1.SerializedPolicyTag value) {
if (childPolicyTagsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChildPolicyTagsIsMutable();
childPolicyTags_.add(index, value);
onChanged();
} else {
childPolicyTagsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public Builder addChildPolicyTags(
com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder builderForValue) {
if (childPolicyTagsBuilder_ == null) {
ensureChildPolicyTagsIsMutable();
childPolicyTags_.add(builderForValue.build());
onChanged();
} else {
childPolicyTagsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public Builder addChildPolicyTags(
int index, com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder builderForValue) {
if (childPolicyTagsBuilder_ == null) {
ensureChildPolicyTagsIsMutable();
childPolicyTags_.add(index, builderForValue.build());
onChanged();
} else {
childPolicyTagsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public Builder addAllChildPolicyTags(
java.lang.Iterable<? extends com.google.cloud.datacatalog.v1.SerializedPolicyTag> values) {
if (childPolicyTagsBuilder_ == null) {
ensureChildPolicyTagsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, childPolicyTags_);
onChanged();
} else {
childPolicyTagsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public Builder clearChildPolicyTags() {
if (childPolicyTagsBuilder_ == null) {
childPolicyTags_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
childPolicyTagsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public Builder removeChildPolicyTags(int index) {
if (childPolicyTagsBuilder_ == null) {
ensureChildPolicyTagsIsMutable();
childPolicyTags_.remove(index);
onChanged();
} else {
childPolicyTagsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder getChildPolicyTagsBuilder(
int index) {
return getChildPolicyTagsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public com.google.cloud.datacatalog.v1.SerializedPolicyTagOrBuilder getChildPolicyTagsOrBuilder(
int index) {
if (childPolicyTagsBuilder_ == null) {
return childPolicyTags_.get(index);
} else {
return childPolicyTagsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public java.util.List<? extends com.google.cloud.datacatalog.v1.SerializedPolicyTagOrBuilder>
getChildPolicyTagsOrBuilderList() {
if (childPolicyTagsBuilder_ != null) {
return childPolicyTagsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(childPolicyTags_);
}
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder addChildPolicyTagsBuilder() {
return getChildPolicyTagsFieldBuilder()
.addBuilder(com.google.cloud.datacatalog.v1.SerializedPolicyTag.getDefaultInstance());
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder addChildPolicyTagsBuilder(
int index) {
return getChildPolicyTagsFieldBuilder()
.addBuilder(
index, com.google.cloud.datacatalog.v1.SerializedPolicyTag.getDefaultInstance());
}
/**
*
*
* <pre>
* Children of the policy tag, if any.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.SerializedPolicyTag child_policy_tags = 4;</code>
*/
public java.util.List<com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder>
getChildPolicyTagsBuilderList() {
return getChildPolicyTagsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1.SerializedPolicyTag,
com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder,
com.google.cloud.datacatalog.v1.SerializedPolicyTagOrBuilder>
getChildPolicyTagsFieldBuilder() {
if (childPolicyTagsBuilder_ == null) {
childPolicyTagsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1.SerializedPolicyTag,
com.google.cloud.datacatalog.v1.SerializedPolicyTag.Builder,
com.google.cloud.datacatalog.v1.SerializedPolicyTagOrBuilder>(
childPolicyTags_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
childPolicyTags_ = null;
}
return childPolicyTagsBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.datacatalog.v1.SerializedPolicyTag)
}
// @@protoc_insertion_point(class_scope:google.cloud.datacatalog.v1.SerializedPolicyTag)
private static final com.google.cloud.datacatalog.v1.SerializedPolicyTag DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datacatalog.v1.SerializedPolicyTag();
}
public static com.google.cloud.datacatalog.v1.SerializedPolicyTag getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SerializedPolicyTag> PARSER =
new com.google.protobuf.AbstractParser<SerializedPolicyTag>() {
@java.lang.Override
public SerializedPolicyTag parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new SerializedPolicyTag(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<SerializedPolicyTag> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SerializedPolicyTag> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.SerializedPolicyTag getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
iLabrys/iLabrysOSGi | es.itecban.deployment.model.plan.report/src/es/itecban/deployment/model/deployment/plan/report/marshaller/ObjectMarshaller.java | 2412 | /*******************************************************************************
* Copyright 2014 Indra
*
* 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 es.itecban.deployment.model.deployment.plan.report.marshaller;
import java.io.IOException;
import java.net.URL;
import org.eclipse.emf.common.util.URI;
import es.itecban.deployment.model.deployment.plan.report.DocumentRoot;
import es.itecban.deployment.model.deployment.plan.report.ExecutionReportType;
import es.itecban.deployment.model.deployment.plan.report.ReportFactory;
import es.itecban.deployment.model.deployment.plan.report.util.ReportResourceImpl;
import es.itecban.deployment.model.deployment.plan.report.util.ReportXMLProcessor;
public class ObjectMarshaller {
public ExecutionReportType unmarshallExecutionReport(String xmlExecutionReport) throws Exception {
// Create the object representation
if (xmlExecutionReport == null)
throw new IOException("a valid URL to an XML serialized execution report must be provided");
ReportXMLProcessor proc = new ReportXMLProcessor();
org.eclipse.emf.ecore.resource.Resource res = proc.load(new URL(xmlExecutionReport).openStream(), null);
DocumentRoot documentRoot = (DocumentRoot) res.getContents().get(0);
ExecutionReportType er = documentRoot.getExecutionReport();
return er;
}
public String getXMLExecutionReport(ExecutionReportType report) throws Exception {
ReportXMLProcessor proc = new ReportXMLProcessor();
ReportResourceImpl reportResource = new ReportResourceImpl(URI.createURI(""));
DocumentRoot documentRoot = ReportFactory.eINSTANCE.createDocumentRoot();
documentRoot.setExecutionReport(report);
reportResource.getContents().add(documentRoot);
return proc.saveToString(reportResource, null);
}
}
| apache-2.0 |
xiaohu846627/hello-world | ArchitectTutorial/src/main/java/com/example/design/pattern/masterworker/Main.java | 781 | package com.example.design.pattern.masterworker;
import java.util.Random;
import com.example.util.TimeUtil;
public class Main {
public static void main(String[] args) {
Master master = new Master(new Worker(), 50);
Random random = new Random();
for (int i = 0; i < 100; i++) {
Task task = new Task();
task.setId(i);
task.setName("任务" + i);
task.setPrice(random.nextInt(1000));
master.submit(task);
}
master.execute();
long start = System.currentTimeMillis();
while (true) {
if(master.isComplete()){
Long result = master.getResult();
System.out.println(result);
break;
}
}
System.out.println(TimeUtil.formatFriendly(System.currentTimeMillis()-start));
}
}
| apache-2.0 |
romanzenka/swift | swift/config-ui/src/main/java/edu/mayo/mprc/swift/configuration/client/view/DaemonWrapper.java | 6704 | package edu.mayo.mprc.swift.configuration.client.view;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.*;
import edu.mayo.mprc.swift.configuration.client.model.*;
import java.util.*;
public final class DaemonWrapper extends SimplePanel {
private final DaemonModel daemonModel;
private final ListBox newModulePicker;
private Button newModuleButton;
private final AvailableModules availableModules;
private Map<ResourceModel, ModuleConfigUis> uis = new HashMap<ResourceModel, ModuleConfigUis>();
private DaemonView daemonConfigUI;
private Context context;
private static class InfoComparator implements Comparator<AvailableModules.Info> {
@Override
public int compare(AvailableModules.Info o1, AvailableModules.Info o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
}
private class ModuleConfigUis {
private ModuleConfigUis(final ModuleWrapper moduleWrapper, final RunnerView runner) {
ui = moduleWrapper;
this.runner = runner;
}
public ModuleWrapper ui;
public RunnerView runner;
}
public DaemonWrapper(final DaemonModel daemonModel, final Context context) {
this.context = context;
addStyleName("module-wrapper");
final FlowPanel panel = new FlowPanel();
panel.addStyleName("module");
final Label label = new Label("Daemon");
label.addStyleName("module-label");
panel.add(label);
final HTML desc = new HTML("A daemon is a process that a provides portion of Swift functionality. " +
"<ul><li>A daemon consists of multiple modules.</li>" +
"<li>Communication between daemons is done using a message broker, " +
"shared filesystem and for the UI and main searcher, also using a database. All these means of communication are available and configurable as modules.</li>" +
"<li>Typically, you would like to have one daemon per physical machine, but that is not a requirement</li>" +
"</ul>" +
"<p>The properties below are mostly used for simplifying the configuration process. The only mandatory fields are daemon name and host name, in case you want to run multiple daemons, you must also set up the shared file space.</p>");
desc.addStyleName("module-description");
panel.add(desc);
this.daemonModel = daemonModel;
availableModules = context.getApplicationModel().getAvailableModules();
this.daemonModel.addListener(new MyDaemonModelListener());
newModulePicker = new ListBox(false);
final Collection<AvailableModules.Info> moduleInfos = availableModules.getModuleInfos();
final List<AvailableModules.Info> moduleInfoList = new ArrayList<AvailableModules.Info>(moduleInfos);
Collections.sort(moduleInfoList, new InfoComparator());
for (final AvailableModules.Info info : moduleInfoList) {
// if (info.isModule()) {
newModulePicker.addItem(info.getName(), info.getType());
// }
}
newModuleButton = new Button("Add new module");
newModuleButton.addStyleName("btn");
newModuleButton.addStyleName("new-module-button");
newModuleButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
final int index = newModulePicker.getSelectedIndex();
final String type = newModulePicker.getValue(index);
DaemonWrapper.this.daemonModel.addNewResource(type, null, context);
}
});
daemonConfigUI = new DaemonView();
daemonConfigUI.initializeUi(this.daemonModel, this.context);
panel.add(daemonConfigUI.getWidget());
final Panel moduleAdding = new HorizontalPanel();
moduleAdding.add(newModulePicker);
moduleAdding.add(newModuleButton);
panel.add(moduleAdding);
final ArrayList<ResourceModel> resources = new ArrayList<ResourceModel>(this.daemonModel.getChildren());
for (final ResourceModel resource : resources) {
addUiForResource(resource);
}
setWidget(panel);
}
public ModuleWrapper getUiForResource(final ResourceModel resourceModel) {
final DaemonWrapper.ModuleConfigUis configUis = uis.get(resourceModel);
return configUis == null ? null : configUis.ui;
}
public RunnerView getRunnerUiForModule(final ModuleModel moduleModel) {
return uis.get(moduleModel).runner;
}
private class MyDaemonModelListener implements ResourceModelListener {
@Override
public void initialized(final ResourceModel model) {
}
@Override
public void nameChanged(final ResourceModel model) {
}
@Override
public void childAdded(final ResourceModel child, final ResourceModel addedTo) {
addUiForResource(child);
}
@Override
public void childRemoved(final ResourceModel child, final ResourceModel removedFrom) {
removeUiForResource(child);
}
@Override
public void propertyChanged(final ResourceModel model, final String propertyName, final String newValue) {
if (model instanceof DaemonModel) {
daemonConfigUI.loadUI((DaemonModel) model);
} else {
throw new RuntimeException("Programmer error: type mismatch");
}
}
}
/**
* The model is already in the list. Just add the ui.
*/
private void addUiForResource(final ResourceModel resource) {
final ModuleWrapper ui = createNewModuleConfigUI(resource);
ui.getModule().loadUI(resource.getProperties());
RunnerView runner = null;
if (resource instanceof ModuleModel) {
runner = createNewRunnerUi(((ModuleModel) resource).getRunner());
}
final ModuleConfigUis t = new ModuleConfigUis(ui, runner);
uis.put(resource, t);
}
private ModuleWrapper createNewModuleConfigUI(final ResourceModel module) {
final String type = module.getType();
final ModuleView ui = null;
if ("database".equals(type)) {
// Special case. Database UI is currently not supported by UiBuilder, so it is created manually
final GwtUiBuilder builder = new GwtUiBuilder(context, module);
final DatabaseView databaseView = new DatabaseView(builder, module);
return new ModuleWrapper(availableModules.getModuleNameForType(type), databaseView, availableModules.getDescriptionForType(type));
} else {
final GwtUiBuilder builder = new GwtUiBuilder(context, module);
builder.start();
module.getReplayer().replay(builder);
return new ModuleWrapper(availableModules.getModuleNameForType(type), builder.end(), availableModules.getDescriptionForType(type));
}
}
private RunnerView createNewRunnerUi(final ResourceModel model) {
final RunnerView runner = new RunnerView(context, model);
runner.setStyleName("runner-wrapper");
return runner;
}
private void removeUiForResource(final ResourceModel module) {
for (final Map.Entry<ResourceModel, ModuleConfigUis> ui : uis.entrySet()) {
if (ui.getKey().equals(module)) {
uis.remove(ui.getKey());
break;
}
}
}
}
| apache-2.0 |
lucaswerkmeister/ceylon-model | src/com/redhat/ceylon/model/typechecker/model/NothingType.java | 1635 | package com.redhat.ceylon.model.typechecker.model;
import java.util.List;
/**
* The bottom type Nothing.
*
* @author Gavin King
*
*/
public class NothingType extends TypeDeclaration {
public NothingType(Unit unit) {
this.unit = unit;
}
@Override
public void addMember(Declaration declaration) {
throw new UnsupportedOperationException();
}
@Override
void collectSupertypeDeclarations(
List<TypeDeclaration> results) {
throw new UnsupportedOperationException();
}
@Override
public String getName() {
return "Nothing";
}
@Override
public Scope getContainer() {
return unit.getAnythingDeclaration().getContainer();
}
@Override
public String getQualifiedNameString() {
return "ceylon.language::Nothing";
}
@Override
public String toString() {
return "type Nothing";
}
@Override
public boolean isShared() {
return true;
}
@Override
public DeclarationKind getDeclarationKind() {
return DeclarationKind.TYPE;
}
@Override
public boolean inherits(TypeDeclaration dec) {
return true;
}
@Override
public boolean equals(Object object) {
return object instanceof NothingType;
}
@Override
protected int hashCodeForCache() {
return 17987123;
}
@Override
protected boolean equalsForCache(Object o) {
return equals(o);
}
@Override
protected boolean needsSatisfiedTypes() {
return false;
}
}
| apache-2.0 |
sckm/CreateIntentGeneratorPlugin | src/typegenerators/PrimitiveArrayGeneratorFactory.java | 1800 | /*
* Copyright (C) 2015 Seesaa Inc.
* Copyright (C) 2013 Michał Charmas (http://blog.charmas.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 typegenerators;
import com.intellij.psi.PsiType;
import java.util.HashMap;
import typegenerators.generators.PrimitiveArrayGenerator;
public class PrimitiveArrayGeneratorFactory implements TypeGeneratorFactory {
private final HashMap<String, TypeGenerator> handledTypes;
public PrimitiveArrayGeneratorFactory() {
handledTypes = new HashMap<String, TypeGenerator>();
handledTypes.put("boolean[]", new PrimitiveArrayGenerator("Boolean"));
handledTypes.put("byte[]", new PrimitiveArrayGenerator("Byte"));
handledTypes.put("char[]", new PrimitiveArrayGenerator("Char"));
handledTypes.put("double[]", new PrimitiveArrayGenerator("Double"));
handledTypes.put("float[]", new PrimitiveArrayGenerator("Float"));
handledTypes.put("short[]", new PrimitiveArrayGenerator("Short"));
handledTypes.put("int[]", new PrimitiveArrayGenerator("Int"));
handledTypes.put("long[]", new PrimitiveArrayGenerator("Long"));
}
@Override
public TypeGenerator getGenerator(PsiType psiType) {
return handledTypes.get(psiType.getCanonicalText());
}
}
| apache-2.0 |
otsecbsol/linkbinder | linkbinder-core/src/test/java/jp/co/opentone/bsol/linkbinder/dao/impl/DistTemplateTestBase.java | 22849 | /*
* Copyright 2016 OPEN TONE Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.co.opentone.bsol.linkbinder.dao.impl;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang.time.DateUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import jp.co.opentone.bsol.framework.test.util.AssertMapComparer;
import jp.co.opentone.bsol.linkbinder.dao.DaoFinder;
import jp.co.opentone.bsol.linkbinder.dto.DistTemplateGroup;
import jp.co.opentone.bsol.linkbinder.dto.DistTemplateHeader;
import jp.co.opentone.bsol.linkbinder.dto.code.DistributionType;
import junit.framework.Assert;
/**
* Daoテストクラスの基底クラスです.
* @author opentone
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:scope.xml",
"classpath:applicationContextTest.xml",
"classpath:daoContextTest.xml"
})
@Transactional
@Rollback
//public abstract class DistTemplateTestBase extends AbstractDaoTestCase {
public abstract class DistTemplateTestBase {
/**
* Loggerインスタンス.
*/
// CHECKSTYLE:OFF
protected Logger log = LoggerFactory.getLogger(getClass());
// CHECKSTYLE:ON
/**
* テストユーティリティDao.
*/
@Autowired
// CHECKSTYLE:OFF
protected DistTemplateDaoTestUtil distTestUtilDaoImpl;
// CHECKSTYLE:ON
/**
* 日付を比較する際の変換書式.
*/
protected static final String FORMAT_DATE = AssertMapComparer.FORMAT_DATE;
/**
* 時刻を比較する際の変換書式.
*/
protected static final String FORMAT_TIME = AssertMapComparer.FORMAT_TIME;
/**
* Dao取得クラス.
*/
@Resource
// CHECKSTYLE:OFF
protected DaoFinder daoFinder;
// CHECKSTYLE:ON
/**
* 各テストクラス実行前の初期処理.
* @throws Exception
* Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
/**
* 各テストクラス実行後の終了処理.
* @throws Exception 例外
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
/**
* 各テストメソッド実行前の初期処理.
* @throws Exception
* Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* 各テストメソッド実行後の終了処理.
* @throws Exception 例外
*/
@After
public void tearDown() throws Exception {
}
/**
* 日付書式の文字列を返します.
* @param date 日付
* @return 日付書式の文字列. 引数がnullの場合はnullを返します.
*/
public String formatDate(Date date) {
String result = null;
if (null != date) {
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE);
result = sdf.format(date);
}
return result;
}
/**
* 文字列を日付に変換します.
* @param value 日付文字列
* @return 変換した日付. 変換不可の場合はnullを返します.
*/
public Date parseDate(String value) {
Date result = null;
// CHECKSTYLE:OFF
try {
result = DateUtils.parseDate(value, new String[] {FORMAT_DATE});
} catch (ParseException pe) {
// 変換不可の場合はnullを返します.
}
// CHECKSTYLE:ON
return result;
}
/**
* 時刻書式の文字列を返します.
* @param timestamp 時刻
* @return 日付書式の文字列. 引数がnullの場合はnullを返します.
*/
public String formatTimestamp(Date timestamp) {
String result = null;
if (null != timestamp) {
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_TIME);
result = sdf.format(timestamp);
}
return result;
}
/**
* 文字列を時刻に変換します.
* @param value 時刻文字列
* @return 変換した時刻. 変換不可の場合はnullを返します.
*/
public Date parseTimestamp(String value) {
Date result = null;
// CHECKSTYLE:OFF
try {
result = DateUtils.parseDate(value, new String[] {FORMAT_TIME});
} catch (ParseException pe) {
// 変換不可の場合はnullを返します.
}
// CHECKSTYLE:ON
return result;
}
/**
* McMasterを比較します.
* @param expected 期待値
* @param actual 比較値
* @param fields 比較対象とするフィールド名配列
*/
protected void assertEquals(Object expected, Object actual, String[] fields) {
Assert.assertNotNull(expected);
Assert.assertNotNull(actual);
Assert.assertNotNull(fields);
for (String field : fields) {
try {
String methodName
= String.format("get%s%s",
field.substring(0, 1).toUpperCase(), field.substring(1));
Method expMethod = expected.getClass().getMethod(methodName, (Class[]) null);
Object expObj = expMethod.invoke(expected, (Object[]) null);
Method actMethod = actual.getClass().getMethod(methodName, (Class[]) null);
Object actObj = actMethod.invoke(actual, (Object[]) null);
Assert.assertEquals(expObj, actObj);
} catch (Exception e) {
Assert.fail(e.toString());
}
}
}
/**
* テストデータを作成する.
*/
protected void createDistHeaderTestData() {
// 既存の参照用テストデータ以外を削除
distTestUtilDaoImpl.delete("distTemplateGroup.testClearTable");
distTestUtilDaoImpl.delete("distTemplateHeader.testClearTable");
for (String[] data : TEST_DATAS) {
DistTemplateHeaderDaoImplTest impl = new DistTemplateHeaderDaoImplTest();
// CHECKSTYLE:OFF
DistTemplateHeader header
= impl.createDistTemplateHeader(Long.parseLong(data[0]),
data[1],
data[2],
data[3],
data[7],
data[8],
1L,
Long.parseLong(data[9]));
// CHECKSTYLE:ON
distTestUtilDaoImpl.insert("distTemplateHeader.testCreate", header);
}
}
/**
* insertやupdateテスト用のDistTemplateHeaderを1件作成します.
* @param id DistTemplateGroupのid
* @param projectId projectId
* @param templateCd templateCd
* @param name name
* @param createdBy DistTemplateGroupのcreated_by
* @param updatedBy DistTemplateGroupのupdated_by
* @param versionNo versionNo
* @return DistTemplateGroup
*/
protected DistTemplateHeader createDistTemplateHeader(long id,
String projectId,
String templateCd,
String name,
String createdBy,
String updatedBy,
Long versionNo) {
return createDistTemplateHeader(id,
projectId,
templateCd,
name,
createdBy,
updatedBy,
versionNo,
0L);
}
/**
* insertやupdateテスト用のDistTemplateHeaderを1件作成します.
* @param id DistTemplateGroupのid
* @param projectId projectId
* @param templateCd templateCd
* @param name name
* @param createdBy DistTemplateGroupのcreated_by
* @param updatedBy DistTemplateGroupのupdated_by
* @param versionNo versionNo
* @param deleteNo deleteNo
* @return DistTemplateGroup
*/
protected DistTemplateHeader createDistTemplateHeader(long id,
String projectId,
String templateCd,
String name,
String createdBy,
String updatedBy,
Long versionNo,
Long deleteNo) {
DistTemplateHeader distTemplateHeader = new DistTemplateHeader();
distTemplateHeader.setId(id);
distTemplateHeader.setProjectId(projectId);
distTemplateHeader.setEmpNo("00000");
distTemplateHeader.setTemplateCd(templateCd);
distTemplateHeader.setName(name);
distTemplateHeader.setCreatedBy(createdBy);
String createdAt = "2010/04/23 45:54:32";
distTemplateHeader.setCreatedAt(parseTimestamp(createdAt));
distTemplateHeader.setUpdatedBy(updatedBy);
String updateAt = "2010/02/15 12:34:56";
distTemplateHeader.setUpdatedAt(parseTimestamp(updateAt));
distTemplateHeader.setVersionNo(versionNo);
distTemplateHeader.setDeleteNo(deleteNo);
return distTemplateHeader;
}
/**
* insertやupdateテスト用のDistTemplateGroupを1件作成します.
* @param id DistTemplateGroupのid
* @param headerId DistTemplateGroupのdist_template_header_id
* @param distributionType DistTemplateGroupのdistribution_type
* @param orderNo DistTemplateGroupのorder_no
* @param groupId DistTemplateGroupのgroup_id
* @param createdBy DistTemplateGroupのcreated_by
* @param updatedBy DistTemplateGroupのupdated_by
* @return DistTemplateGroup
*/
protected DistTemplateGroup createDistTemplateGroup(long id,
long headerId,
String distributionType,
long orderNo,
long groupId,
String createdBy,
String updatedBy) {
DistTemplateGroup distTemplateGroup = new DistTemplateGroup();
distTemplateGroup.setId(id);
distTemplateGroup.setGroupName("test");
distTemplateGroup.setDistTemplateHeaderId(headerId);
Map<String, DistributionType> typeMap = new HashMap<String, DistributionType>();
typeMap.put("TO", DistributionType.TO);
typeMap.put("CC", DistributionType.CC);
distTemplateGroup.setDistributionType(typeMap.get(distributionType));
distTemplateGroup.setOrderNo(orderNo);
distTemplateGroup.setGroupId(groupId);
distTemplateGroup.setCreatedBy(createdBy);
String createDate = "2012/03/14 05:43:21";
distTemplateGroup.setCreatedAt(parseTimestamp(createDate));
distTemplateGroup.setUpdatedBy(updatedBy);
distTemplateGroup.setUpdatedAt(distTemplateGroup.getCreatedAt());
return distTemplateGroup;
}
/**
* 検索系処理で使用するテストデータ.
*/
// CHECKSTYLE:OFF
protected static final String[][] TEST_DATAS = {
// id, project_id, template_cd, name, option1, option2, option3, created_by, updated_by, delete_no
// ただし、option1-3は現状は不要な列です.
{ "1000000001", "0-1111-0", "1", "Distribution Header-1", "", "", "", "ZZA01", "ZZA16", "0" },
{ "1000000002", "0-1111-1", "2", "Distribution Header-2", "B", "B", "B", "ZZA02", "ZZA17", "0" },
{ "1000000003", "0-1111-2", "3", "Distribution Header-3", "D", "D", "D", "ZZA03", "ZZA18", "0" },
{ "1000000004", "0-1111-3", "4", "Distribution Header-4", "C", "C", "C", "ZZA04", "ZZA01", "0" },
{ "1000000005", "0-1111-4", "5", "Distribution Header-5", "", "", "", "ZZA05", "ZZA02", "0" },
{ "1000000006", "0-1111-5", "6", "Distribution Header-6", "F", "F", "F", "ZZA06", "ZZA03", "0" },
{ "1000000007", "0-1111-0", "1", "Distribution Header-7", "", "", "", "ZZA07", "ZZA04", "1" },
{ "1000000008", "0-1111-0", "2", "Distribution Header-8", "H", "H", "H", "ZZA08", "ZZA05", "0" },
{ "1000000009", "0-1111-0", "3", "Distribution Header-9", "Z", "Z", "Z", "ZZA09", "ZZA06", "0" },
{ "1000000010", "0-1111-0", "4", "Apple Header-1", "W", "W", "W", "ZZA11", "ZZA07", "1" },
{ "1000000011", "0-1111-0", "5", "Apple Header-2", "WW", "WW", "WW", "ZZA12", "ZZA08", "0" },
{ "1000000012", "0-1111-0", "6", "Apple Header-3", "YYY", "YYY", "YYY", "ZZA13", "ZZA09", "0" },
{ "1000000013", "0-1111-0", "7", "Apple Header-4", "1", "1", "1", "ZZA14", "ZZA11", "0" },
{ "1000000014", "0-1111-0", "8", "Orange Header-1", "A", "A", "A", "ZZA15", "ZZA12", "0" },
{ "1000000015", "0-1111-0", "9", "Orange Header-2", "3", "3", "3", "ZZA16", "ZZA13", "1" },
{ "1000000016", "0-1111-0", "10", "Orange Header-3", "5", "5", "5", "ZZA17", "ZZA14", "0" },
{ "1000000017", "0-1111-0", "11", "Orange Header-4", "", "", "", "ZZA18", "ZZA15", "1" },
{ "1000000021", "0-1111-1", "1", "Orange Header-5", "8", "8", "8", "ZZA04", "ZZA16", "0" },
{ "1000000022", "0-1111-1", "2", "Apple Header-12", "9", "9", "9", "ZZA04", "ZZA17", "1" },
{ "1000000023", "0-1111-1", "3", "Apple Header-13", "0", "0", "0", "ZZA04", "ZZA18", "0" },
{ "1000000024", "0-1111-1", "4", "Apple Header-14", "A", "A", "A", "ZZA04", "ZZA16", "0" },
{ "1000000025", "0-1111-1", "5", "Apple Header-15", "6", "6", "6", "ZZA04", "ZZA17", "0" },
{ "1000000026", "0-2222-1", "1", "Dist Header-201", "J", "J", "J", "ZZA01", "ZZA08", "0" },
{ "1000000027", "0-2222-1", "2", "Dist Header-202", "J", "J", "J", "ZZA02", "ZZA09", "0" },
{ "1000000028", "0-2222-1", "3", "Dist Header-203", "J", "J", "J", "ZZA03", "ZZA11", "0" },
{ "1000000029", "0-2222-1", "4", "Dist Header-204", "J", "J", "J", "ZZA04", "ZZA12", "0" },
{ "1000000030", "0-2222-1", "5", "Dist Header-205", "D", "D", "D", "ZZA05", "ZZA12", "0" },
{ "1000000031", "0-2222-1", "6", "Dist Header-206", "S", "S", "S", "ZZA06", "ZZA18", "0" },
{ "1000000032", "0-2222-1", "7", "Dist Header-207", "A", "A", "A", "ZZA06", "ZZA16", "0" },
{ "1000000033", "0-2222-1", "8", "Dist Header-208", "1", "1", "1", "ZZA06", "ZZA17", "0" },
{ "1000000034", "0-2222-1", "9", "Dist Header-209", "9", "9", "9", "ZZA06", "ZZA12", "0" },
{ "1000000035", "0-2222-1", "10", "Dist Header-210", "5", "5", "5", "ZZA06", "ZZA18", "0" },
{ "1000000036", "0-2222-2", "1", "Dist Header-211", "3", "3", "3", "ZZA06", "ZZA16", "0" },
{ "1000000037", "0-2222-2", "2", "Dist Header-212", "2", "2", "2", "ZZA06", "ZZA17", "0" },
{ "1000000038", "0-2222-2", "3", "Dist Header-213", "3", "3", "3", "ZZA06", "ZZA18", "0" },
{ "1000000039", "0-2222-2", "4", "Dist Header-214", "1", "1", "1", "ZZA06", "ZZA16", "0" },
{ "1000000040", "0-2222-2", "5", "Dist Header-215", "4", "4", "4", "ZZA06", "ZZA17", "0" },
{ "1000000041", "0-2222-2", "6", "Dist Header-216", "3", "3", "3", "ZZA06", "ZZA18", "0" },
{ "1000000042", "0-2222-2", "7", "Dist Header-217", "6", "6", "6", "ZZA06", "ZZA16", "0" },
{ "1000000043", "0-2222-2", "8", "Dist Header-218", "Y", "Y", "Y", "ZZA06", "ZZA17", "0" },
{ "1000000044", "0-2222-2", "9", "Dist Header-219", "P", "P", "P", "ZZA06", "ZZA12", "0" },
{ "1000000045", "0-2222-3", "1", "testFindDistTemplateList01-Name01", "a", "a", "a", "ZZA05", "ZZA07", "0" },
{ "1000000046", "0-2222-3", "2", "testFindDistTemplateList01-Name02", "b", "b", "b", "ZZA05", "ZZA07", "0" },
{ "1000000047", "0-2222-3", "3", "testFindDistTemplateList01-Name03", "c", "c", "c", "ZZA05", "ZZA07", "0" },
{ "1000000048", "0-2222-3", "4", "testFindDistTemplateList01-Name04", "d", "d", "d", "ZZA05", "ZZA07", "0" },
{ "1000000049", "0-2222-3", "5", "testFindDistTemplateList01-Name05", "e", "e", "e", "ZZA05", "ZZA07", "0" },
{ "1000000050", "0-2222-3", "6", "testFindDistTemplateList01-Name06", "f", "f", "f", "ZZA05", "ZZA07", "0" },
{ "1000000051", "0-2222-3", "7", "testFindDistTemplateList01-Name07", "g", "g", "g", "ZZA05", "ZZA07", "0" },
{ "1000000052", "0-2222-3", "8", "testFindDistTemplateList01-Name08", "h", "h", "h", "ZZA05", "ZZA07", "0" },
{ "1000000053", "0-2222-3", "9", "testFindDistTemplateList01-Name09", "i", "i", "i", "ZZA05", "ZZA07", "0" },
{ "1000000054", "0-2222-3", "10", "testFindDistTemplateList01-Name10", "j", "j", "j", "ZZA05", "ZZA07", "0" },
{ "1000000055", "0-2222-3", "11", "testFindDistTemplateList01-Name11", "k", "k", "k", "ZZA05", "ZZA07", "0" },
{ "1000000056", "0-2222-3", "12", "testFindDistTemplateList01-Name12", "l", "l", "l", "ZZA05", "ZZA07", "0" },
{ "1000000057", "0-2222-3", "13", "testFindDistTemplateList01-Name13", "m", "m", "m", "ZZA05", "ZZA07", "0" },
{ "1000000058", "0-2222-3", "14", "testFindDistTemplateList01-Name14", "n", "n", "n", "ZZA05", "ZZA07", "0" },
{ "1000000059", "0-2222-3", "15", "testFindDistTemplateList01-Name15", "o", "o", "o", "ZZA05", "ZZA07", "0" },
{ "1000000060", "0-2222-3", "16", "testFindDistTemplateList01-Name16", "p", "p", "p", "ZZA05", "ZZA07", "0" },
{ "1000000061", "0-2222-3", "17", "testFindDistTemplateList01-Name17", "q", "q", "q", "ZZA05", "ZZA07", "0" },
{ "1000000062", "0-2222-3", "18", "testFindDistTemplateList01-Name18", "r", "r", "r", "ZZA05", "ZZA07", "0" },
{ "1000000063", "0-2222-3", "19", "testFindDistTemplateList01-Name19", "s", "s", "s", "ZZA05", "ZZA07", "0" },
{ "1000000064", "0-2222-3", "20", "testFindDistTemplateList01-Name20", "t", "t", "t", "ZZA05", "ZZA07", "0" },
{ "1000000065", "0-2222-3", "21", "testFindDistTemplateList01-Name21", "u", "u", "u", "ZZA05", "ZZA07", "0" },
{ "1000000066", "0-2222-4", "1", "testUpdate02-Name01", "1", "1", "1", "ZZA08", "ZZA09", "0" },
{ "1000000067", "0-2222-4", "2", "testUpdate02-Name02", "2", "2", "2", "ZZA08", "ZZA09", "0" },
{ "1000000068", "0-2222-4", "3", "testUpdate02-Name03", "3", "3", "3", "ZZA08", "ZZA09", "0" },
{ "1000000069", "0-2222-4", "4", "testUpdate02-Name04", "4", "4", "4", "ZZA08", "ZZA09", "0" },
{ "1000000070", "0-2222-4", "5", "testUpdate02-Name05", "5", "5", "5", "ZZA08", "ZZA09", "0" },
{ "1000000071", "0-2222-4", "6", "testUpdate02-Name06", "6", "6", "6", "ZZA08", "ZZA09", "0" },
{ "1000000072", "0-1111-0", "12", "Dist Header Name -01", "9", "9", "9", "ZZA04", "ZZA11", "0" },
{ "1000000073", "0-1111-0", "13", "Dist Header Name -02", "8", "8", "8", "ZZA04", "ZZA11", "0" },
{ "1000000074", "0-1111-0", "14", "Dist Header Name -03", "7", "7", "7", "ZZA04", "ZZA11", "0" },
{ "1000000075", "0-1111-0", "15", "Dist Header Name -04", "6", "6", "6", "ZZA04", "ZZA11", "0" },
{ "1000000076", "0-1111-0", "16", "Dist Header Name -05", "5", "5", "5", "ZZA04", "ZZA11", "0" },
{ "1000000077", "0-1111-0", "17", "Dist Header Name -06", "4", "4", "4", "ZZA04", "ZZA11", "0" },
{ "1000000078", "0-1111-0", "18", "Dist Header Name -07", "3", "3", "3", "ZZA04", "ZZA11", "0" },
{ "1000000079", "0-1111-0", "19", "Dist Header Name -08", "2", "2", "2", "ZZA04", "ZZA11", "0" },
{ "1000000080", "0-1111-0", "20", "Dist Header Name -09", "1", "1", "1", "ZZA04", "ZZA11", "0" },
{ "1000000081", "0-1111-0", "21", "Dist Header Name -10", "a", "a", "a", "ZZA04", "ZZA11", "0" },
{ "1000000082", "0-1111-0", "22", "Dist Header Name -11", "b", "b", "b", "ZZA04", "ZZA11", "0" },
{ "1000000083", "0-1111-0", "23", "Dist Header Name -12", "c", "c", "c", "ZZA04", "ZZA11", "0" },
{ "1000000084", "0-1111-0", "24", "Dist Header Name -13", "d", "d", "d", "ZZA04", "ZZA11", "0" },
{ "1000000085", "0-1111-0", "25", "Dist Header Name -14", "e", "e", "e", "ZZA04", "ZZA11", "0" },
{ "1000000086", "0-1111-0", "26", "Dist Header Name -15", "f", "f", "f", "ZZA04", "ZZA11", "0" },
{ "1000000087", "0-1111-0", "27", "Dist Header Name -16", "g", "g", "g", "ZZA04", "ZZA11", "0" },
{ "1000000088", "0-1111-0", "28", "Dist Header Name -17", "h", "h", "h", "ZZA04", "ZZA11", "0" },
{ "1000000089", "0-1111-0", "29", "Dist Header Name -18", "i", "i", "i", "ZZA04", "ZZA11", "0" },
{ "1000000090", "0-1111-0", "30", "Dist Header Name -19", "j", "j", "j", "ZZA04", "ZZA11", "0" },
{ "1000000091", "0-1111-0", "31", "Dist Header Name -20", "k", "k", "k", "ZZA04", "ZZA11", "0" },
{ "1000000092", "0-1111-0", "32", "Dist Header Name -21", "l", "l", "l", "ZZA04", "ZZA11", "0" },
};
// CHECKSTYLE:ON
}
| apache-2.0 |
eumji025/leetcode-program | src/com/eumji/longestcommonprofix/Solution.java | 1072 | package com.eumji.longestcommonprofix;
/**
*
* Write a function to find the longest common prefix string amongst an array of strings.
*
* 在一个数组中 找到最大的公共前缀字符串
*
* @email eumji025@gmail.com
* @author:EumJi
* @date: 2017/8/30
* @time: 16:59
*/
public class Solution {
//假设第一个为公共前缀,然后依次和后面的字符串进行对比,如果相同就进行下一个字符串对比,不同就长度减1 直到遍历结束
public String longestCommonPrefix(String[] strs) {
if ( strs == null || strs.length == 0){
return "";
}
else if (strs.length == 1){
return strs[0];
}
String common = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(common)!= 0) {
common = common.substring(0, common.length() - 1);
}
}
return common;
}
public static void main(String[] args) {
new Solution().longestCommonPrefix(new String[]{"a", "b"});
}
}
| apache-2.0 |
Yiiinsh/x-pipe | redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/controller/consoleportal/HealthCheckController.java | 2606 | package com.ctrip.xpipe.redis.console.controller.consoleportal;
import com.ctrip.xpipe.endpoint.HostPort;
import com.ctrip.xpipe.redis.console.config.ConsoleConfig;
import com.ctrip.xpipe.redis.console.controller.AbstractConsoleController;
import com.ctrip.xpipe.redis.console.health.delay.DelayService;
import com.ctrip.xpipe.redis.console.health.ping.PingService;
import com.ctrip.xpipe.redis.console.model.ClusterTbl;
import com.ctrip.xpipe.redis.console.service.ClusterService;
import com.google.common.collect.ImmutableMap;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* @author shyin
* <p>
* Jan 5, 2017
*/
@RestController
@RequestMapping(AbstractConsoleController.CONSOLE_PREFIX)
public class HealthCheckController extends AbstractConsoleController {
@Autowired
private PingService pingService;
@Autowired
private DelayService delayService;
@Autowired
private ConsoleConfig config;
@Autowired
private ClusterService clusterService;
@RequestMapping(value = "/redis/health/{redisIp}/{redisPort}", method = RequestMethod.GET)
public Map<String, Boolean> isRedisHealth(@PathVariable String redisIp, @PathVariable int redisPort) {
return ImmutableMap.of("isHealth", pingService.isRedisAlive(new HostPort(redisIp, redisPort)));
}
@RequestMapping(value = "/redis/delay/{redisIp}/{redisPort}", method = RequestMethod.GET)
public Map<String, Long> getReplDelayMillis(@PathVariable String redisIp, @PathVariable int redisPort) {
return ImmutableMap.of("delay", delayService.getDelay(new HostPort(redisIp, redisPort)));
}
@RequestMapping(value = "/redis/health/hickwall/" + CLUSTER_NAME_PATH_VARIABLE + "/" + SHARD_NAME_PATH_VARIABLE + "/{redisIp}/{redisPort}", method = RequestMethod.GET)
public Map<String, String> getHickwallAddress(@PathVariable String clusterName, @PathVariable String shardName, @PathVariable String redisIp, @PathVariable int redisPort) {
String addr = config.getHickwallAddress();
if (Strings.isEmpty(addr)) {
return ImmutableMap.of("addr", "");
}
return ImmutableMap.of("addr", String.format("%s.%s.%s.%s.%s*", addr, clusterName, shardName, redisIp, redisPort));
}
}
| apache-2.0 |
Amplifino/nestor | com.amplifino.nestor.jdbc.pools/src/com/amplifino/nestor/jdbc/wrappers/PreparedStatementWrapper.java | 9648 | package com.amplifino.nestor.jdbc.wrappers;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLType;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
public class PreparedStatementWrapper extends StatementWrapper implements PreparedStatement {
private final PreparedStatement statement;
protected PreparedStatementWrapper(PreparedStatement statement) {
super(statement);
this.statement = statement;
}
protected PreparedStatementWrapper(PreparedStatement statement, SqlConsumer<Statement> onClose) {
super(statement, onClose);
this.statement = statement;
}
@Override
public void addBatch() throws SQLException {
statement.addBatch();
}
@Override
public void clearParameters() throws SQLException {
statement.clearParameters();
}
@Override
public boolean execute() throws SQLException {
return statement.execute();
}
@Override
public long executeLargeUpdate() throws SQLException {
return statement.executeLargeUpdate();
}
@Override
public ResultSet executeQuery() throws SQLException {
return statement.executeQuery();
}
@Override
public int executeUpdate() throws SQLException {
return statement.executeUpdate();
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
return statement.getMetaData();
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
return statement.getParameterMetaData();
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
statement.setArray(parameterIndex, x);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
statement.setAsciiStream(parameterIndex, x);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
statement.setAsciiStream(parameterIndex, x, length);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
statement.setAsciiStream(parameterIndex, x, length);
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
statement.setBigDecimal(parameterIndex, x);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
statement.setBinaryStream(parameterIndex, x);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
statement.setBinaryStream(parameterIndex, x, length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
statement.setBinaryStream(parameterIndex, x, length);
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
statement.setBlob(parameterIndex, x);
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
statement.setBlob(parameterIndex, inputStream);
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
statement.setBlob(parameterIndex, inputStream, length);
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
statement.setBoolean(parameterIndex, x);
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
statement.setByte(parameterIndex, x);
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
statement.setBytes(parameterIndex, x);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
statement.setCharacterStream(parameterIndex, reader);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
statement.setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
statement.setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
statement.setClob(parameterIndex, x);
}
@Override
public void setClob(int parameterIndex, Reader reader) throws SQLException {
statement.setClob(parameterIndex, reader);
}
@Override
public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
statement.setClob(parameterIndex, reader, length);
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
statement.setDate(parameterIndex, x);
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
statement.setDate(parameterIndex, x, cal);
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
statement.setDouble(parameterIndex, x);
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
statement.setFloat(parameterIndex, x);
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
statement.setInt(parameterIndex, x);
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
statement.setLong(parameterIndex, x);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
statement.setNCharacterStream(parameterIndex, value);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
statement.setNCharacterStream(parameterIndex, value, length);
}
@Override
public void setNClob(int parameterIndex, NClob value) throws SQLException {
statement.setNClob(parameterIndex, value);
}
@Override
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
statement.setNClob(parameterIndex, reader);
}
@Override
public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
statement.setNClob(parameterIndex, reader, length);
}
@Override
public void setNString(int parameterIndex, String value) throws SQLException {
statement.setNString(parameterIndex, value);
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
statement.setNull(parameterIndex, sqlType);
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
statement.setNull(parameterIndex, sqlType, typeName);
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
statement.setObject(parameterIndex, x);
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
statement.setObject(parameterIndex, x, targetSqlType);
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
statement.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
}
@Override
public void setObject(int parameterIndex, Object x, SQLType sqlType) throws SQLException {
statement.setObject(parameterIndex, x, sqlType);
}
@Override
public void setObject(int parameterIndex, Object x, SQLType sqlType, int scaleOrLength) throws SQLException {
statement.setObject(parameterIndex, x, sqlType, scaleOrLength);
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
statement.setRef(parameterIndex, x);
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
statement.setRowId(parameterIndex, x);
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
statement.setSQLXML(parameterIndex, xmlObject);
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
statement.setShort(parameterIndex, x);
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
statement.setString(parameterIndex, x);
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
statement.setTime(parameterIndex, x);
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
statement.setTime(parameterIndex, x, cal);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
statement.setTimestamp(parameterIndex, x);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
statement.setTimestamp(parameterIndex, x, cal);
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
statement.setURL(parameterIndex, x);
}
@Override
@Deprecated
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
statement.setUnicodeStream(parameterIndex, x, length);
}
}
| apache-2.0 |
pkcool/bmsuite | bmsuite-framework/src/main/java/com/enginemobi/core/common/SearchCriteria.java | 445 | package com.enginemobi.core.common;
import java.util.ArrayList;
import java.util.List;
public interface SearchCriteria extends List<Criterion>
{
public static class Builder
{
public static SearchCriteria create()
{
return new SearchCriteriaImpl();
}
private static class SearchCriteriaImpl extends ArrayList<Criterion>
implements SearchCriteria
{
}
}
}
| apache-2.0 |
hungcuongbsm/spdv | core/src/test/java/com/vnpt/spdv/service/impl/LookupManagerImplTest.java | 1040 | package com.vnpt.spdv.service.impl;
import com.vnpt.spdv.Constants;
import com.vnpt.spdv.dao.LookupDao;
import com.vnpt.spdv.model.LabelValue;
import com.vnpt.spdv.model.Role;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given;
public class LookupManagerImplTest extends BaseManagerMockTestCase {
@Mock
private LookupDao lookupDao;
@InjectMocks
private LookupManagerImpl mgr = new LookupManagerImpl();
@Test
public void testGetAllRoles() {
log.debug("entered 'testGetAllRoles' method");
//given
Role role = new Role(Constants.ADMIN_ROLE);
final List<Role> testData = new ArrayList<Role>();
testData.add(role);
given(lookupDao.getRoles()).willReturn(testData);
//when
List<LabelValue> roles = mgr.getAllRoles();
//then
assertTrue(roles.size() > 0);
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-batch/src/main/java/com/amazonaws/services/batch/model/transform/CreateJobQueueResultJsonUnmarshaller.java | 3065 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.batch.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.batch.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* CreateJobQueueResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateJobQueueResultJsonUnmarshaller implements Unmarshaller<CreateJobQueueResult, JsonUnmarshallerContext> {
public CreateJobQueueResult unmarshall(JsonUnmarshallerContext context) throws Exception {
CreateJobQueueResult createJobQueueResult = new CreateJobQueueResult();
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 createJobQueueResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("jobQueueName", targetDepth)) {
context.nextToken();
createJobQueueResult.setJobQueueName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("jobQueueArn", targetDepth)) {
context.nextToken();
createJobQueueResult.setJobQueueArn(context.getUnmarshaller(String.class).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 createJobQueueResult;
}
private static CreateJobQueueResultJsonUnmarshaller instance;
public static CreateJobQueueResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CreateJobQueueResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
wyukawa/presto | presto-tpch/src/main/java/io/prestosql/plugin/tpch/TpchTableHandle.java | 2774 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.plugin.tpch;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.prestosql.spi.connector.ColumnHandle;
import io.prestosql.spi.connector.ConnectorTableHandle;
import io.prestosql.spi.predicate.TupleDomain;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
public class TpchTableHandle
implements ConnectorTableHandle
{
private final String tableName;
private final double scaleFactor;
private final TupleDomain<ColumnHandle> constraint;
public TpchTableHandle(String tableName, double scaleFactor)
{
this(tableName, scaleFactor, TupleDomain.all());
}
@JsonCreator
public TpchTableHandle(
@JsonProperty("tableName") String tableName,
@JsonProperty("scaleFactor") double scaleFactor,
@JsonProperty("constraint") TupleDomain<ColumnHandle> constraint)
{
this.tableName = requireNonNull(tableName, "tableName is null");
checkArgument(scaleFactor > 0, "Scale factor must be larger than 0");
this.scaleFactor = scaleFactor;
this.constraint = requireNonNull(constraint, "constraint is null");
}
@JsonProperty
public String getTableName()
{
return tableName;
}
@JsonProperty
public double getScaleFactor()
{
return scaleFactor;
}
@JsonProperty
public TupleDomain<ColumnHandle> getConstraint()
{
return constraint;
}
@Override
public String toString()
{
return tableName + ":sf" + scaleFactor;
}
@Override
public int hashCode()
{
return Objects.hash(tableName, scaleFactor);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
TpchTableHandle other = (TpchTableHandle) obj;
return Objects.equals(this.tableName, other.tableName) &&
Objects.equals(this.scaleFactor, other.scaleFactor);
}
}
| apache-2.0 |
link-intersystems/maven | maven-plugins/svntools-maven-plugin/src/main/java/com/link_intersystems/maven/plugin/tools/svn/RichSvnRepository.java | 3746 | package com.link_intersystems.maven.plugin.tools.svn;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.settings.Server;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
import org.tmatesoft.svn.core.wc.admin.SVNAdminClient;
import com.link_intersystems.maven.plugin.system.GoalParameterException;
import com.link_intersystems.maven.plugin.system.MavenContext;
public class RichSvnRepository {
private static final String SVN_REPO_SPEC_PART_DIVIDER = "::";
private SvnRepository svnRepository;
private MavenContext mavenContext;
private SVNAdminClient adminClient;
private SVNRepository svnKitRepository;
RichSvnRepository(MavenContext mavenContext, SvnRepository svnRepository) {
this.mavenContext = mavenContext;
this.svnRepository = svnRepository;
}
public SVNAdminClient getAdminClient() {
if (adminClient == null) {
String authenticationId = svnRepository.getAuthenticationId();
if (!StringUtils.isBlank(authenticationId)) {
}
Server serverSettings = mavenContext
.getServerSettings(authenticationId);
String username = serverSettings.getUsername();
String password = serverSettings.getPassword();
DefaultSVNOptions defaultSVNOptions = new DefaultSVNOptions();
SVNClientManager clientManager = SVNClientManager.newInstance(
defaultSVNOptions, username, password);
adminClient = clientManager.getAdminClient();
}
return adminClient;
}
public SVNRepository getSVNRepository() throws SVNException {
if (svnKitRepository == null) {
SVNURL url = SVNURL.parseURIEncoded(svnRepository.getUrl());
SVNRepository svnKitRepository = SVNRepositoryFactory.create(url,
null);
applyAuthenticationIfAny(svnKitRepository);
this.svnKitRepository = svnKitRepository;
}
return svnKitRepository;
}
private void applyAuthenticationIfAny(SVNRepository svnKitRepository) {
String authenticationId = svnRepository.getAuthenticationId();
ISVNAuthenticationManager authManager = null;
if (StringUtils.isNotBlank(authenticationId)) {
Server serverSettings = mavenContext
.getServerSettings(authenticationId);
String username = serverSettings.getUsername();
String password = serverSettings.getPassword();
authManager = SVNWCUtil.createDefaultAuthenticationManager(
username, password);
svnKitRepository.setAuthenticationManager(authManager);
}
}
public void checkAvailability() {
try {
SVNRepository svnRepository = getSVNRepository();
svnRepository.testConnection();
} catch (SVNException e) {
String url = svnRepository.getUrl();
if (StringUtils.isBlank(url)) {
throw new GoalParameterException(
"Repository definitions must have a valid url: " + url,
e);
}
throw new GoalParameterException(
"Repository "
+ toString()
+ " can not be accessed. Does it exist? In case "
+ "of an file url you should consider to create the repository "
+ "via the svnadmin tool: svnadmin create <REPOSITORY_NAME>",
e);
}
}
@Override
public String toString() {
StringBuilder toString = new StringBuilder();
toString.append(svnRepository.getAuthenticationId());
toString.append(SVN_REPO_SPEC_PART_DIVIDER);
toString.append(svnRepository.getUrl());
return toString.toString();
}
}
| apache-2.0 |
caelum/vraptor-scala-mydvds | src/test/integration/br/com/caelum/vraptor/mydvds/pages/HomePage.java | 1314 | /***
* Copyright (c) 2009 Caelum - www.caelum.com.br/opensource
* 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 br.com.caelum.vraptor.mydvds.pages;
import br.com.caelum.seleniumdsl.Browser;
import br.com.caelum.seleniumdsl.Form;
public class HomePage {
private final Browser browser;
private Form form;
public HomePage(Browser browser) {
this.browser = browser;
}
public HomePage fillRegisterDvdForm() {
form = browser.currentPage().form("dvdRegister");
return this;
}
public HomePage withTitle(String title) {
form.field("dvd.title").type(title);
return this;
}
public HomePage withDescription(String description) {
form.field("dvd.description").type(description);
return this;
}
public void andSend() {
form.navigate("send");
}
}
| apache-2.0 |
cowthan/JavaAyo | src/com/cowthan/pattern1/proxy/ordinary/IGameProxy.java | 476 | package com.cowthan.pattern1.proxy.ordinary;
/**
* 代理的个性:
* ——代理的个性才是代理存在的价值
* ——代理的个性就是代理干了真实对象不能干的事
*
* 游戏代练的接口,就是收钱,这个例子不太恰当,因为基本上代理的意义是对
* 对象功能的扩展,而不是仅仅完成了对象能做的事情之后去跟对象要钱
* @author qiaoliang
*
*/
public interface IGameProxy {
void count();
}
| apache-2.0 |
patrickfav/uber-adb-tools | src/test/java/at/favre/tools/uberadb/AdbLocationFinderImplTest.java | 465 | package at.favre.tools.uberadb;
import org.junit.Test;
import static org.junit.Assert.fail;
public class AdbLocationFinderImplTest {
@Test
public void testLocation() {
AdbLocationFinderImpl locationFinder = new AdbLocationFinderImpl();
try {
locationFinder.find(
new MockAdbCmdProvider(false),
null
);
fail();
} catch (Exception e) {
}
}
}
| apache-2.0 |
summax/HYGBlog | src/main/java/com/hyg/controller/LoginController.java | 813 | package com.hyg.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class LoginController
{
@RequestMapping("/login")
public String Login(HttpServletRequest request , HttpServletResponse response) {
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
if(userName != "" && userPassword != ""){
request.setAttribute("name",userName);
request.setAttribute("password",userPassword);
return "register/register";
}
return "login/login";
}
}
| apache-2.0 |
daedric/buck | src/com/facebook/buck/android/HasInstallableApk.java | 1668 | /*
* Copyright 2012-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.android;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.ExopackageInfo;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import org.immutables.value.Value;
import java.util.Optional;
/**
* Build rule that generates an APK that can be installed with the install command.
*
* @see com.facebook.buck.cli.InstallCommand
*/
public interface HasInstallableApk extends BuildRule {
ApkInfo getApkInfo();
@Value.Immutable
@BuckStyleImmutable
abstract class AbstractApkInfo {
/**
* @return the path to the AndroidManifest.xml. Note that this file might be a symlink,
* and might not exist at all before this rule has been built.
*/
public abstract SourcePath getManifestPath();
/**
* @return The APK at this path is the final one that points to an APK that a user should
* install.
*/
public abstract SourcePath getApkPath();
public abstract Optional<ExopackageInfo> getExopackageInfo();
}
}
| apache-2.0 |
jituo666/CrazyPic | src/com/xjt/crazypic/edit/controller/ParameterSaturation.java | 574 | package com.xjt.crazypic.edit.controller;
public class ParameterSaturation extends BasicParameterInt {
public static String sParameterType = "ParameterSaturation";
float[] mHSVO = new float[4];
public ParameterSaturation(int id, int value) {
super(id, value, 0, 100);
}
@Override
public String getParameterType() {
return sParameterType;
}
public void setColor(float[] hsvo) {
mHSVO = hsvo;
}
public float[] getColor() {
mHSVO[3] = getValue() / (float) getMaximum();
return mHSVO;
}
}
| apache-2.0 |
baoyongan/java-examples | java-eg-thread/src/main/java/com/baoyongan/java/eg/thread/concurrent/ExchangerTest.java | 3041 | package com.baoyongan.java.eg.thread.concurrent;
import java.util.Random;
import java.util.concurrent.Exchanger;
public class ExchangerTest {
public static void main(String[] args) {
FillAndEmpty fae=new FillAndEmpty();
fae.start();
}
}
class FillAndEmpty {
Exchanger<String> exchanger = new Exchanger<String>();
String initialEmpty = new String("");
String initialFull = new String("");
int length=4;
char[] codes={'A','B','C','D','E','a','b','c','d','e'};
class FillingLoop implements Runnable {
Random random=new Random();
public void run() {
String currentBuffer = initialEmpty;
try {
while (currentBuffer != null) {
currentBuffer=addToBuffer(currentBuffer);
if (isFull(currentBuffer)){
System.out.println("交换前EmptyBuffer:"+currentBuffer.hashCode()+"内容:"+currentBuffer);
currentBuffer = exchanger.exchange(currentBuffer);
System.out.println("交换后EmptyBuffer:"+currentBuffer.hashCode()+"内容:"+currentBuffer);
}
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
private boolean isFull(String currentBuffer) {
if(currentBuffer.length()==length){
return true;
}
return false;
}
private String addToBuffer(String currentBuffer) {
int i = random.nextInt(8);
char ch=codes[i];
currentBuffer=currentBuffer+ch;
System.out.println("添加后的内容"+currentBuffer);
return currentBuffer;
}
}
class EmptyingLoop implements Runnable {
Random r=new Random();
public void run() {
String currentBuffer = initialFull;
try {
while (currentBuffer != null) {
currentBuffer=takeFromBuffer(currentBuffer);
if (isEmpty(currentBuffer)) {
System.out.println("交换前FullBuffer:" + currentBuffer.hashCode() + "内容:" + currentBuffer);
currentBuffer = exchanger.exchange(currentBuffer);
System.out.println("交换后FullBuffer:" + currentBuffer.hashCode() + "内容:" + currentBuffer);
}
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
private boolean isEmpty(String currentBuffer) {
return currentBuffer.isEmpty();
}
private String takeFromBuffer(String currentBuffer) {
System.out.println("取出的内容:"+currentBuffer);
currentBuffer="";
return currentBuffer;
}
}
void start() {
new Thread(new FillingLoop()).start();
new Thread(new EmptyingLoop()).start();
}
}
| apache-2.0 |
ahus1/bdd-examples | jgiven-mockito-spring/src/test/java/de/ahus1/bdd/calculator/adapter/inmemory/CalculatorInMemoryRepository.java | 279 | package de.ahus1.bdd.calculator.adapter.inmemory;
import de.ahus1.bdd.calculator.domain.Calculator;
import de.ahus1.bdd.calculator.domain.CalculatorRepository;
public class CalculatorInMemoryRepository extends InMemoryRepository<Calculator> implements CalculatorRepository {
}
| apache-2.0 |
Romkje/pft_java_34 | addressbook/src/test/java/ua/pft/addressbook/tests/ContactCreationTests.java | 1109 | package ua.pft.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import ua.pft.addressbook.model.ContactData;
import java.util.Comparator;
import java.util.List;
public class ContactCreationTests extends TestBase {
@Test
public void testContactCreation() throws InterruptedException {
app.getNavigationHelper().gotoHomePage();
List<ContactData> before = app.getContactHelper().getContactList();
app.getNavigationHelper().gotoContactPageCreation();
ContactData contactData = new ContactData("test_first_name", "test_last_name", "test1");
app.getContactHelper().fillContactCreationForm(contactData, true);
app.getContactHelper().submitContactCreation();
app.getNavigationHelper().gotoHomePage();
List<ContactData> after = app.getContactHelper().getContactList();
before.add(contactData);
Comparator<? super ContactData> byId = (c1, c2) -> Integer.compare(c1.getId(), c2.getId());
before.sort(byId);
after.sort(byId);
Assert.assertEquals(after, before);
}
}
| apache-2.0 |
ctripcorp/x-pipe | redis/redis-checker/src/main/java/com/ctrip/xpipe/redis/checker/healthcheck/actions/redisinfo/InfoActionController.java | 385 | package com.ctrip.xpipe.redis.checker.healthcheck.actions.redisinfo;
import com.ctrip.xpipe.redis.checker.healthcheck.HealthCheckActionController;
import com.ctrip.xpipe.redis.checker.healthcheck.RedisHealthCheckInstance;
/**
* @author Slight
* <p>
* Jun 01, 2021 4:24 PM
*/
public interface InfoActionController extends HealthCheckActionController<RedisHealthCheckInstance> {
}
| apache-2.0 |
MathRandomNext/Android | Meetup/app/src/main/java/com/telerikacademy/meetup/ui/adapter/PlacesAutocompleteLimitAdapter.java | 699 | package com.telerikacademy.meetup.ui.adapter;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.widget.ArrayAdapter;
import java.util.List;
public class PlacesAutocompleteLimitAdapter<T> extends ArrayAdapter<T> {
private static final int LIMIT = 5;
public PlacesAutocompleteLimitAdapter(@NonNull Context context,
@LayoutRes int resource,
@NonNull List<T> objects) {
super(context, resource, objects);
}
@Override
public int getCount() {
return Math.min(LIMIT, super.getCount());
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201602/CustomFieldErrorReason.java | 1289 |
package com.google.api.ads.dfp.jaxws.v201602;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CustomFieldError.Reason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="CustomFieldError.Reason">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="INVALID_CUSTOM_FIELD_FOR_OPTION"/>
* <enumeration value="UNKNOWN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CustomFieldError.Reason")
@XmlEnum
public enum CustomFieldErrorReason {
/**
*
* An attempt was made to create a {@link CustomFieldOption} for
* a {@link CustomField} that does not have {@link CustomFieldDataType#DROPDOWN}.
*
*
*/
INVALID_CUSTOM_FIELD_FOR_OPTION,
/**
*
* The value returned if the actual value is not exposed by the requested API version.
*
*
*/
UNKNOWN;
public String value() {
return name();
}
public static CustomFieldErrorReason fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-mechanicalturkrequester/src/main/java/com/amazonaws/services/mturk/model/DeleteWorkerBlockRequest.java | 5216 | /*
* Copyright 2012-2017 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.mturk.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mturk-requester-2017-01-17/DeleteWorkerBlock" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteWorkerBlockRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The ID of the Worker to unblock.
* </p>
*/
private String workerId;
/**
* <p>
* A message that explains the reason for unblocking the Worker. The Worker does not see this message.
* </p>
*/
private String reason;
/**
* <p>
* The ID of the Worker to unblock.
* </p>
*
* @param workerId
* The ID of the Worker to unblock.
*/
public void setWorkerId(String workerId) {
this.workerId = workerId;
}
/**
* <p>
* The ID of the Worker to unblock.
* </p>
*
* @return The ID of the Worker to unblock.
*/
public String getWorkerId() {
return this.workerId;
}
/**
* <p>
* The ID of the Worker to unblock.
* </p>
*
* @param workerId
* The ID of the Worker to unblock.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeleteWorkerBlockRequest withWorkerId(String workerId) {
setWorkerId(workerId);
return this;
}
/**
* <p>
* A message that explains the reason for unblocking the Worker. The Worker does not see this message.
* </p>
*
* @param reason
* A message that explains the reason for unblocking the Worker. The Worker does not see this message.
*/
public void setReason(String reason) {
this.reason = reason;
}
/**
* <p>
* A message that explains the reason for unblocking the Worker. The Worker does not see this message.
* </p>
*
* @return A message that explains the reason for unblocking the Worker. The Worker does not see this message.
*/
public String getReason() {
return this.reason;
}
/**
* <p>
* A message that explains the reason for unblocking the Worker. The Worker does not see this message.
* </p>
*
* @param reason
* A message that explains the reason for unblocking the Worker. The Worker does not see this message.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeleteWorkerBlockRequest withReason(String reason) {
setReason(reason);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getWorkerId() != null)
sb.append("WorkerId: ").append(getWorkerId()).append(",");
if (getReason() != null)
sb.append("Reason: ").append(getReason());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeleteWorkerBlockRequest == false)
return false;
DeleteWorkerBlockRequest other = (DeleteWorkerBlockRequest) obj;
if (other.getWorkerId() == null ^ this.getWorkerId() == null)
return false;
if (other.getWorkerId() != null && other.getWorkerId().equals(this.getWorkerId()) == false)
return false;
if (other.getReason() == null ^ this.getReason() == null)
return false;
if (other.getReason() != null && other.getReason().equals(this.getReason()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getWorkerId() == null) ? 0 : getWorkerId().hashCode());
hashCode = prime * hashCode + ((getReason() == null) ? 0 : getReason().hashCode());
return hashCode;
}
@Override
public DeleteWorkerBlockRequest clone() {
return (DeleteWorkerBlockRequest) super.clone();
}
}
| apache-2.0 |
TatyanaAlex/tfukova | sql_jdbc/src/main/java/ru.job4j/jdbc/StoreSql.java | 2831 | package ru.job4j.jdbc;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StoreSql implements AutoCloseable {
private final Config config;
private Connection connect;
public StoreSql(Config config, Connection connection) {
this.config = config;
this.connect = connection;
}
// генерирует n записей в бд
public void generate(int size) {
// SQL statement for creating a new table
String sql = "CREATE TABLE IF NOT EXISTS entry (id integer PRIMARY KEY);";
String sqlInsertRows = "INSERT INTO entry (id) VALUES (?)";
try {
Statement stmt = connect.createStatement();
// create a new table
stmt.execute(sql);
connect.commit();
deleteIfNotEmpty("entry");
PreparedStatement pstm = connect.prepareStatement(sqlInsertRows);
for (int i = 0; i < size; i++) {
pstm.setInt(1, i);
pstm.addBatch();
}
pstm.executeBatch();
connect.commit();
} catch (SQLException e) {
System.out.println(e.getMessage());
try {
if (connect != null) {
connect.rollback();
}
} catch (SQLException e2) {
System.out.println(e2.getMessage());
}
}
}
public List<Entry> load() {
List<Entry> resultList = new ArrayList<>();
String sql = "SELECT * FROM entry";
try (Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
connect.commit();
while (rs.next()) {
resultList.add(new Entry(rs.getInt("id")));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
try {
if (connect != null) {
connect.rollback();
}
} catch (SQLException e2) {
System.out.println(e2.getMessage());
}
}
return resultList;
}
private void deleteIfNotEmpty(String tableName) {
String sql = "DELETE * FROM " + tableName;
try {
Statement stmt = connect.createStatement();
stmt.execute(sql);
connect.commit();
} catch (SQLException e) {
e.printStackTrace();
try {
if (connect != null) {
connect.rollback();
}
} catch (SQLException e2) {
System.out.println(e2.getMessage());
}
}
}
@Override
public void close() throws Exception {
if (connect != null) {
connect.close();
}
}
}
| apache-2.0 |
vespa-engine/vespa | clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/WaitCondition.java | 9055 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core.testutils;
import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vespa.clustercontroller.core.AnnotatedClusterState;
import com.yahoo.vespa.clustercontroller.core.ClusterStateBundle;
import com.yahoo.vespa.clustercontroller.core.DummyVdsNode;
import com.yahoo.vespa.clustercontroller.core.FleetController;
import com.yahoo.vespa.clustercontroller.core.listeners.SystemStateListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Haakon Humberset
*/
public interface WaitCondition {
/** Return null if met, why not if it is not met. */
String isConditionMet();
abstract class StateWait implements WaitCondition {
private final Object monitor;
protected ClusterState currentState;
ClusterState convergedState;
private final SystemStateListener listener = new SystemStateListener() {
@Override
public void handleNewPublishedState(ClusterStateBundle state) {
synchronized (monitor) {
currentState = state.getBaselineClusterState();
monitor.notifyAll();
}
}
@Override
public void handleStateConvergedInCluster(ClusterStateBundle states) {
synchronized (monitor) {
currentState = convergedState = states.getBaselineClusterState();
monitor.notifyAll();
}
}
};
protected StateWait(FleetController fc, Object monitor) {
this.monitor = monitor;
synchronized (this.monitor) {
fc.addSystemStateListener(listener);
}
}
ClusterState getCurrentState() {
synchronized (monitor) {
return currentState;
}
}
}
class RegexStateMatcher extends StateWait {
private final Pattern pattern;
private Collection<DummyVdsNode> nodesToCheck;
private ClusterState lastCheckedState;
private boolean checkAllSpaces = false;
private Set<String> checkSpaceSubset = Collections.emptySet();
RegexStateMatcher(String regex, FleetController fc, Object monitor) {
super(fc, monitor);
pattern = Pattern.compile(regex);
}
RegexStateMatcher includeNotifyingNodes(Collection<DummyVdsNode> nodes) {
nodesToCheck = nodes;
return this;
}
RegexStateMatcher checkAllSpaces(boolean checkAllSpaces) {
this.checkAllSpaces = checkAllSpaces;
return this;
}
RegexStateMatcher checkSpaceSubset(Set<String> spaces) {
this.checkSpaceSubset = spaces;
return this;
}
private static List<ClusterState> statesInBundle(ClusterStateBundle bundle) {
List<ClusterState> states = new ArrayList<>(3);
states.add(bundle.getBaselineClusterState());
bundle.getDerivedBucketSpaceStates().forEach((space, state) -> states.add(state.getClusterState()));
return states;
}
@Override
public String isConditionMet() {
if (convergedState != null) {
lastCheckedState = convergedState;
Matcher m = pattern.matcher(lastCheckedState.toString());
if (m.matches() || !checkSpaceSubset.isEmpty()) {
if (nodesToCheck != null) {
for (DummyVdsNode node : nodesToCheck) {
if (node.getClusterState() == null) {
return "Node " + node + " has not received a cluster state yet";
}
// TODO refactor, simplify
boolean match;
if (checkAllSpaces) {
match = statesInBundle(node.getClusterStateBundle()).stream()
.allMatch(state -> pattern.matcher(withoutTimestamps(state.toString())).matches());
} else if (!checkSpaceSubset.isEmpty()) {
match = checkSpaceSubset.stream().allMatch(space -> {
String state = node.getClusterStateBundle().getDerivedBucketSpaceStates()
.getOrDefault(space, AnnotatedClusterState.emptyState()).getClusterState().toString();
return pattern.matcher(withoutTimestamps(state)).matches();
});
} else {
match = pattern.matcher(withoutTimestamps(node.getClusterState().toString())).matches();
}
if (!match) {
return "Node " + node + " state mismatch.\n wanted: " + pattern + "\n is: " + node.getClusterStateBundle().toString();
}
if (node.getStateCommunicationVersion() > 0) {
if (!node.hasPendingGetNodeStateRequest()) {
return "Node " + node + " has not received another get node state request yet";
}
}
}
}
return null;
}
return "Cluster state mismatch";
}
return "No cluster state defined yet";
}
/** Returns the given state string with timestamps removed */
private String withoutTimestamps(String state) {
String[] parts = state.split(" ");
StringBuilder b = new StringBuilder();
for (String part : parts) {
if ( ! part.contains(".t"))
b.append(part).append(" ");
}
if (b.length() > 0)
b.setLength(b.length() - 1);
return b.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("RegexStateMatcher(\n wanted: '").append(pattern.pattern())
.append("'\n last checked: '").append(lastCheckedState).append("'")
.append("'\n current: '").append(currentState).append(")");
return sb.toString();
}
}
class InitProgressPassedMatcher extends StateWait {
private final Node node;
private final double minProgress;
InitProgressPassedMatcher(Node n, double minProgress, FleetController fc, Object monitor) {
super(fc, monitor);
this.node = n;
this.minProgress = minProgress;
}
@Override
public String isConditionMet() {
if (currentState == null) {
return "No cluster state defined yet";
}
double currentProgress = currentState.getNodeState(node).getInitProgress();
if (currentProgress < minProgress) {
return "Current progress of node " + node + " at " + currentProgress + " is less than wanted progress of " + minProgress;
}
return null;
}
@Override
public String toString() {
return "InitProgressPassedMatcher(" + node + ", " + minProgress + ")";
}
}
class MinUsedBitsMatcher extends StateWait {
private final int bitCount;
private final int nodeCount;
MinUsedBitsMatcher(int bitCount, int nodeCount, FleetController fc, Object monitor) {
super(fc, monitor);
this.bitCount = bitCount;
this.nodeCount = nodeCount;
}
@Override
public String isConditionMet() {
if (currentState == null) {
return "No cluster state defined yet";
}
int nodebitcount = 0;
for (NodeType type : NodeType.getTypes()) {
int nodeCount = currentState.getNodeCount(type);
for (int i=0; i<nodeCount; ++i) {
if (currentState.getNodeState(new Node(type, i)).getMinUsedBits() == bitCount) {
++nodebitcount;
}
}
}
if (nodebitcount == nodeCount) return null;
return "Currently, " + nodebitcount + " and not " + nodeCount + " nodes have " + bitCount + " min bits used set";
}
@Override
public String toString() { return "MinUsedBitsMatcher(" + bitCount + ", " + nodeCount + ")"; }
}
}
| apache-2.0 |
googleapis/java-compute | proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/AddressesScopedListOrBuilder.java | 3206 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
package com.google.cloud.compute.v1;
public interface AddressesScopedListOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.AddressesScopedList)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* [Output Only] A list of addresses contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Address addresses = 337673122;</code>
*/
java.util.List<com.google.cloud.compute.v1.Address> getAddressesList();
/**
*
*
* <pre>
* [Output Only] A list of addresses contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Address addresses = 337673122;</code>
*/
com.google.cloud.compute.v1.Address getAddresses(int index);
/**
*
*
* <pre>
* [Output Only] A list of addresses contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Address addresses = 337673122;</code>
*/
int getAddressesCount();
/**
*
*
* <pre>
* [Output Only] A list of addresses contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Address addresses = 337673122;</code>
*/
java.util.List<? extends com.google.cloud.compute.v1.AddressOrBuilder>
getAddressesOrBuilderList();
/**
*
*
* <pre>
* [Output Only] A list of addresses contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.Address addresses = 337673122;</code>
*/
com.google.cloud.compute.v1.AddressOrBuilder getAddressesOrBuilder(int index);
/**
*
*
* <pre>
* [Output Only] Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return Whether the warning field is set.
*/
boolean hasWarning();
/**
*
*
* <pre>
* [Output Only] Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return The warning.
*/
com.google.cloud.compute.v1.Warning getWarning();
/**
*
*
* <pre>
* [Output Only] Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
com.google.cloud.compute.v1.WarningOrBuilder getWarningOrBuilder();
}
| apache-2.0 |
lukas-krecan/smock | samples/cxf-client-test/src/test/java/net/javacrumbs/calc/CalcTest.java | 5023 | /**
* Copyright 2009-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.javacrumbs.calc;
import static net.javacrumbs.smock.common.SmockCommon.resource;
import static net.javacrumbs.smock.common.client.CommonSmockClient.message;
import static net.javacrumbs.smock.common.client.CommonSmockClient.withMessage;
import static net.javacrumbs.smock.http.client.connection.SmockClient.createServer;
import static org.junit.Assert.assertEquals;
import static org.springframework.ws.test.client.RequestMatchers.anything;
import static org.springframework.ws.test.client.RequestMatchers.validPayload;
import java.io.IOException;
import javax.xml.ws.soap.SOAPFaultException;
import net.javacrumbs.smock.extended.client.connection.MockWebServiceServer;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:client-config.xml"})
public class CalcTest {
@Autowired
private CalcService calc;
private MockWebServiceServer mockServer;
public CalcTest(){
mockServer = createServer();
}
@After
public void tearDown()
{
mockServer.verify();
}
@Test
public void testSimple()
{
mockServer.expect(anything()).andRespond(withMessage("response1.xml"));
long result = calc.plus(1, 2);
assertEquals(3, result);
}
@Test
public void testVerifyRequest()
{
mockServer.expect(message("request1.xml")).andRespond(withMessage("response1.xml"));
long result = calc.plus(1, 2);
assertEquals(3, result);
}
@Test
public void testSchema() throws IOException
{
mockServer.expect(validPayload(resource("xsd/calc.xsd"))).andExpect(message("request1.xml")).andRespond(withMessage("response1.xml"));
long result = calc.plus(1, 2);
assertEquals(3, result);
}
@Test
public void testIgnore() throws IOException
{
mockServer.expect(validPayload(resource("xsd/calc.xsd"))).andExpect(message("request-ignore.xml")).andRespond(withMessage("response2.xml"));
long result = calc.plus(2, 3);
assertEquals(5, result);
}
@Test
public void testMultiple() throws IOException
{
mockServer.expect(validPayload(resource("xsd/calc.xsd"))).andExpect(message("request-ignore.xml")).andRespond(withMessage("response2.xml"));
mockServer.expect(validPayload(resource("xsd/calc.xsd"))).andExpect(message("request-ignore.xml")).andRespond(withMessage("response3.xml"));
assertEquals(5, calc.plus(2, 3));
assertEquals(8, calc.plus(3, 5));
}
@Test
public void testStrange()
{
mockServer.expect(message("request-ignore.xml")).andRespond(withMessage("response1.xml"));
mockServer.expect(message("request-ignore.xml")).andRespond(withMessage("response2.xml"));
mockServer.expect(message("request-ignore.xml")).andRespond(withMessage("response1.xml"));
assertEquals(3, calc.plus(1, 2));
assertEquals(5, calc.plus(2, 3));
assertEquals(3, calc.plus(1, 2));
}
@Test
public void testTemplate() throws IOException
{
mockServer.expect(validPayload(resource("xsd/calc.xsd"))).andExpect(message("request-ignore.xml")).andRespond(withMessage("response-template.xml"));
long result = calc.plus(2, 3);
assertEquals(5, result);
}
@Test
public void testMultipleTemplate() throws IOException
{
mockServer.expect(validPayload(resource("xsd/calc.xsd"))).andExpect(message("request-ignore.xml")).andRespond(withMessage("response-template.xml"));
mockServer.expect(validPayload(resource("xsd/calc.xsd"))).andExpect(message("request-ignore.xml")).andRespond(withMessage("response-template.xml"));
assertEquals(5, calc.plus(2, 3));
assertEquals(8, calc.plus(3, 5));
}
@Test
public void testContext() throws IOException
{
mockServer.expect(validPayload(resource("xsd/calc.xsd")))
.andExpect(message("request-context-xslt.xml").withParameter("a",1).withParameter("b", 4))
.andRespond(withMessage("response-template.xml"));
long result = calc.plus(1, 4);
assertEquals(5, result);
}
@Test(expected=SOAPFaultException.class)
public void testException() throws IOException
{
mockServer.expect(validPayload(resource("xsd/calc.xsd"))).andExpect(message("request-ignore.xml")).andRespond(withMessage("fault.xml"));
calc.plus(2, 3);
}
}
| apache-2.0 |