repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
Joybeanx/yogg | src/main/java/com/joybean/yogg/statemachine/action/VisitHomePageAction.java | 1385 | package com.joybean.yogg.statemachine.action;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.joybean.yogg.report.record.RecordStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.statemachine.StateContext;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import static com.joybean.yogg.statemachine.StateMachineConfig.Constants.*;
/**
* @author joybean
*/
@Component
public class VisitHomePageAction extends AbstractAction {
private final static Logger LOGGER = LoggerFactory
.getLogger(VisitHomePageAction.class);
@Override
protected void doExecute(StateContext<String, String> context) throws Exception {
String url = getVariable(STATE_MACHINE_INPUT_WEBSITE, context);
Assert.hasText(url, "Url must not be null");
WebClient webClient = getVariable(STATE_MACHINE_VARIABLE_WEB_CLIENT, context);
Page page;
try {
page = webClient.getPage(url);
} catch (Exception e) {
LOGGER.error("Unable to access {}", url, e);
sendFailureEvent(RecordStatus.HOME_PAGE_NOT_LOADED, e, context);
return;
}
putVariable(STATE_MACHINE_VARIABLE_CURRENT_PAGE, page, context);
sendEvent("HOME_PAGE_LOADED", context);
}
}
| apache-2.0 |
mike10004/appengine-imaging | gaecompat-awt-imaging/src/common/com/gaecompat/repackaged/com/google/common/io/package-info.java | 1839 | /*
* Copyright (C) 2007 The Guava 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.
*/
/**
* This package contains utility methods and classes for working with Java I/O,
* for example input streams, output streams, readers, writers, and files.
*
* <p>Many of the methods are based on the
* {@link com.gaecompat.repackaged.com.google.common.io.InputSupplier} and
* {@link com.gaecompat.repackaged.com.google.common.io.OutputSupplier} interfaces. They are used as
* factories for I/O objects that might throw {@link java.io.IOException} when
* being created. The advantage of using a factory is that the helper methods in
* this package can take care of closing the resource properly, even if an
* exception is thrown. The {@link com.gaecompat.repackaged.com.google.common.io.ByteStreams},
* {@link com.gaecompat.repackaged.com.google.common.io.CharStreams}, and
* {@link com.gaecompat.repackaged.com.google.common.io.Files} classes all have static helper methods to
* create new factories and to work with them.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* @author Chris Nokleberg
*/
@ParametersAreNonnullByDefault
package com.gaecompat.repackaged.com.google.common.io;
import javax.annotation.ParametersAreNonnullByDefault;
| apache-2.0 |
akarshan96/pslab-android | app/src/main/java/org/fossasia/pslab/activity/ControlActivity.java | 2664 | package org.fossasia.pslab.activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import org.fossasia.pslab.communication.ScienceLab;
import org.fossasia.pslab.fragment.ControlFragmentAdvanced;
import org.fossasia.pslab.fragment.ControlFragmentMain;
import org.fossasia.pslab.fragment.ControlFragmentRead;
import org.fossasia.pslab.others.ScienceLabCommon;
import org.fossasia.pslab.R;
import butterknife.ButterKnife;
/**
* Created by viveksb007 on 10/5/17.
*/
public class ControlActivity extends AppCompatActivity {
private ScienceLab scienceLab;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control);
scienceLab = ScienceLabCommon.scienceLab;
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener
(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = ControlFragmentMain.newInstance();
break;
case R.id.action_item2:
selectedFragment = ControlFragmentRead.newInstance();
break;
case R.id.action_item3:
selectedFragment = ControlFragmentAdvanced.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout_control, selectedFragment);
transaction.commit();
return true;
}
});
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout_control, ControlFragmentMain.newInstance());
transaction.commit();
}
}
| apache-2.0 |
everttigchelaar/camel-svn | components/camel-spring-integration/src/main/java/org/apache/camel/component/spring/integration/SpringIntegrationEndpoint.java | 3140 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.spring.integration;
import org.apache.camel.CamelContext;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.spring.SpringCamelContext;
import org.springframework.integration.MessageChannel;
/**
* Defines the <a href="http://camel.apache.org/springIntergration.html">Spring Integration Endpoint</a>
*
* @version
*/
public class SpringIntegrationEndpoint extends DefaultEndpoint {
private String inputChannel;
private String outputChannel;
private String defaultChannel;
private MessageChannel messageChannel;
private boolean inOut;
public SpringIntegrationEndpoint(String uri, String channel, SpringIntegrationComponent component) {
super(uri, component);
this.defaultChannel = channel;
}
public SpringIntegrationEndpoint(String uri, MessageChannel channel, CamelContext context) {
super(uri, context);
this.messageChannel = channel;
}
public SpringIntegrationEndpoint(String endpointUri, MessageChannel messageChannel) {
super(endpointUri);
this.messageChannel = messageChannel;
}
public Producer createProducer() throws Exception {
return new SpringIntegrationProducer((SpringCamelContext) getCamelContext(), this);
}
public Consumer createConsumer(Processor processor) throws Exception {
return new SpringIntegrationConsumer(this, processor);
}
public void setInputChannel(String input) {
inputChannel = input;
}
public String getInputChannel() {
return inputChannel;
}
public void setOutputChannel(String output) {
outputChannel = output;
}
public String getOutputChannel() {
return outputChannel;
}
public String getDefaultChannel() {
return defaultChannel;
}
public MessageChannel getMessageChannel() {
return messageChannel;
}
public boolean isSingleton() {
return false;
}
public void setInOut(boolean inOut) {
this.inOut = inOut;
}
public boolean isInOut() {
return this.inOut;
}
}
| apache-2.0 |
leizhu/pugerduty_wechat | src/main/java/pivotal/cf/cloudops/restclient/HttpRestClient.java | 3908 | package pivotal.cf.cloudops.restclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
/**
* Created by pivotal on 8/6/15.
*/
public class HttpRestClient {
private static final Logger logger = Logger.getLogger(HttpRestClient.class);
Map<String,String> headerMap;
public HttpRestClient() {
this.headerMap = null;
}
public HttpRestClient(Map<String,String> headerMap) {
this.headerMap = headerMap;
}
public String sendGET(String getURL) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(getURL);
if(headerMap != null) {
Iterator iterator = headerMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String,String> obj = (Map.Entry) iterator.next();
httpGet.addHeader(obj.getKey(), obj.getValue());
}
}
logger.info("Request: " + httpGet.getURI());
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
logger.info("GET Response Status:: "
+ httpResponse.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
// print result
logger.info("Response:" + response.toString());
httpClient.close();
return response.toString();
}
public void sendPOST(String postURL) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(postURL);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("userName", "Pankaj Kumar"));
HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
httpPost.setEntity(postParams);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
logger.info("POST Response Status:: "
+ httpResponse.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
// print result
logger.info(response.toString());
httpClient.close();
}
public static void main(String[] args) throws IOException {
// String GET_URL = "https://pivotalwechat.pagerduty.com/api/v1/incidents?since=2015-08-06T00:00+08&until=2015-08-07T00:00+08&status=triggered&fields=incident_number,status,html_url";
// Map<String,String> headerMap = new HashMap<String, String>();
// headerMap.put("Authorization","Token token=yAD3WLwgJYSp1wjV872b");
// headerMap.put("Content-type","application/json");
// HttpRestClient httpRestClient = new HttpRestClient(headerMap);
// System.out.println(httpRestClient.sendGET(GET_URL));
}
}
| apache-2.0 |
consulo/consulo-android | tools-base/sdk-common/src/main/java/com/android/ide/common/signing/KeystoreHelper.java | 8847 | /*
* Copyright (C) 2012 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.ide.common.signing;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.prefs.AndroidLocation;
import com.android.prefs.AndroidLocation.AndroidLocationException;
import com.android.utils.GrabProcessOutput;
import com.android.utils.GrabProcessOutput.IProcessOutput;
import com.android.utils.GrabProcessOutput.Wait;
import com.android.utils.ILogger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.KeyStore;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
/**
* A Helper to create and read keystore/keys.
*/
public final class KeystoreHelper {
// Certificate CN value. This is a hard-coded value for the debug key.
// Android Market checks against this value in order to refuse applications signed with
// debug keys.
private static final String CERTIFICATE_DESC = "CN=Android Debug,O=Android,C=US";
/**
* Returns the location of the default debug keystore.
*
* @return The location of the default debug keystore.
* @throws AndroidLocationException if the location cannot be computed
*/
@NonNull
public static String defaultDebugKeystoreLocation() throws AndroidLocationException {
//this is guaranteed to either return a non null value (terminated with a platform
// specific separator), or throw.
String folder = AndroidLocation.getFolder();
return folder + "debug.keystore";
}
/**
* Creates a new debug store with the location, keyalias, and passwords specified in the
* config.
*
* @param signingConfig The signing config
* @param logger a logger object to receive the log of the creation.
* @throws KeytoolException
*/
public static boolean createDebugStore(@Nullable String storeType, @NonNull File storeFile,
@NonNull String storePassword, @NonNull String keyPassword,
@NonNull String keyAlias,
@NonNull ILogger logger) throws KeytoolException {
return createNewStore(storeType, storeFile, storePassword, keyPassword, keyAlias,
CERTIFICATE_DESC, 30 /* validity*/, logger);
}
/**
* Creates a new store
*
* @param signingConfig the Signing Configuration
* @param description description
* @param validityYears
* @param logger
* @throws KeytoolException
*/
private static boolean createNewStore(
@Nullable String storeType,
@NonNull File storeFile,
@NonNull String storePassword,
@NonNull String keyPassword,
@NonNull String keyAlias,
@NonNull String description,
int validityYears,
@NonNull final ILogger logger)
throws KeytoolException {
// get the executable name of keytool depending on the platform.
String os = System.getProperty("os.name");
String keytoolCommand;
if (os.startsWith("Windows")) {
keytoolCommand = "keytool.exe";
} else {
keytoolCommand = "keytool";
}
String javaHome = System.getProperty("java.home");
if (javaHome != null && javaHome.length() > 0) {
keytoolCommand = javaHome + File.separator + "bin" + File.separator + keytoolCommand;
}
// create the command line to call key tool to build the key with no user input.
ArrayList<String> commandList = new ArrayList<String>();
commandList.add(keytoolCommand);
commandList.add("-genkey");
commandList.add("-alias");
commandList.add(keyAlias);
commandList.add("-keyalg");
commandList.add("RSA");
commandList.add("-dname");
commandList.add(description);
commandList.add("-validity");
commandList.add(Integer.toString(validityYears * 365));
commandList.add("-keypass");
commandList.add(keyPassword);
commandList.add("-keystore");
commandList.add(storeFile.getAbsolutePath());
commandList.add("-storepass");
commandList.add(storePassword);
if (storeType != null) {
commandList.add("-storetype");
commandList.add(storeType);
}
String[] commandArray = commandList.toArray(new String[commandList.size()]);
// launch the command line process
int result = 0;
try {
Process process = Runtime.getRuntime().exec(commandArray);
result = GrabProcessOutput.grabProcessOutput(
process,
Wait.WAIT_FOR_READERS,
new IProcessOutput() {
@Override
public void out(@Nullable String line) {
if (line != null) {
logger.info(line);
}
}
@Override
public void err(@Nullable String line) {
if (line != null) {
logger.error(null /*throwable*/, line);
}
}
});
} catch (Exception e) {
// create the command line as one string for debugging purposes
StringBuilder builder = new StringBuilder();
boolean firstArg = true;
for (String arg : commandArray) {
boolean hasSpace = arg.indexOf(' ') != -1;
if (firstArg) {
firstArg = false;
} else {
builder.append(' ');
}
if (hasSpace) {
builder.append('"');
}
builder.append(arg);
if (hasSpace) {
builder.append('"');
}
}
throw new KeytoolException("Failed to create key: " + e.getMessage(),
javaHome, builder.toString());
}
return result == 0;
}
/**
* Returns the CertificateInfo for the given signing configuration.
*
* Returns null if the key could not be found. If the passwords are wrong,
* it throws an exception
*
* @param signingConfig the signing configuration
* @return the certificate info if it could be loaded.
* @throws KeytoolException
* @throws FileNotFoundException
*/
public static CertificateInfo getCertificateInfo(@Nullable String storeType, @NonNull File storeFile,
@NonNull String storePassword, @NonNull String keyPassword,
@NonNull String keyAlias)
throws KeytoolException, FileNotFoundException {
try {
KeyStore keyStore = KeyStore.getInstance(storeType != null ?
storeType : KeyStore.getDefaultType());
FileInputStream fis = new FileInputStream(storeFile);
//noinspection ConstantConditions
keyStore.load(fis, storePassword.toCharArray());
fis.close();
//noinspection ConstantConditions
char[] keyPasswordArray = keyPassword.toCharArray();
PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(
keyAlias, new KeyStore.PasswordProtection(keyPasswordArray));
if (entry != null) {
return new CertificateInfo(entry.getPrivateKey(),
(X509Certificate) entry.getCertificate());
}
} catch (FileNotFoundException e) {
throw e;
} catch (Exception e) {
throw new KeytoolException(
String.format("Failed to read key %1$s from store \"%2$s\": %3$s",
keyAlias, storeFile, e.getMessage()),
e);
}
return null;
}
}
| apache-2.0 |
FAU-Inf2/AuDoscore | tests/show_replace_error/junit/SecretTest.java | 720 | import static org.junit.Assert.assertEquals;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import tester.annotations.Points;
import tester.annotations.Replace;
import tester.annotations.SecretClass;
@SecretClass
public class SecretTest {
// instead of explicitly coding the following rules here,
// your test class can also just extend the class JUnitWithPoints
@Rule
public final PointsLogger pointsLogger = new PointsLogger();
@ClassRule
public final static PointsSummary pointsSummary = new PointsSummary();
@Test(timeout=200)
@Points(exID = "GA4.6a", bonus = 47)
@Replace({"ToTest.toTest"})
public void test() {
assertEquals("Should return 42", 42, ToTest.toTest());
}
}
| apache-2.0 |
wiesed/machine-learning | src/main/java/com/bm/classify/textclassification/DictionaryJson.java | 1713 | package com.bm.classify.textclassification;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Beschreibung:.
* 23.11.16, Time: 13:40.
*
* @author wiese.daniel <br>
* copyright (C) 2016, SWM Services GmbH
*/
public class DictionaryJson {
private int anzahlDokumente;
private List<String> terms;
private List<Integer> termsDf;
private List<List<Integer>> termsCdf = new ArrayList<List<Integer>>();
private Map<String, Integer> termsMapPosition = new HashMap<String, Integer>();
public DictionaryJson() {
}
public DictionaryJson(int anzahlDokumente, List<String> terms, List<Integer> termsDf,
List<List<Integer>> termsCdf, Map<String, Integer> termsMapPosition) {
this.anzahlDokumente = anzahlDokumente;
this.terms = terms;
this.termsDf = termsDf;
this.termsCdf = termsCdf;
this.termsMapPosition = termsMapPosition;
}
public int getAnzahlDokumente() {
return anzahlDokumente;
}
public void setAnzahlDokumente(int anzahlDokumente) {
this.anzahlDokumente = anzahlDokumente;
}
public List<String> getTerms() {
return terms;
}
public void setTerms(List<String> terms) {
this.terms = terms;
}
public List<Integer> getTermsDf() {
return termsDf;
}
public void setTermsDf(List<Integer> termsDf) {
this.termsDf = termsDf;
}
public List<List<Integer>> getTermsCdf() {
return termsCdf;
}
public void setTermsCdf(List<List<Integer>> termsCdf) {
this.termsCdf = termsCdf;
}
public Map<String, Integer> getTermsMapPosition() {
return termsMapPosition;
}
public void setTermsMapPosition(Map<String, Integer> termsMapPosition) {
this.termsMapPosition = termsMapPosition;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/EffectivePatchMarshaller.java | 2302 | /*
* 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.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* EffectivePatchMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class EffectivePatchMarshaller {
private static final MarshallingInfo<StructuredPojo> PATCH_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Patch").build();
private static final MarshallingInfo<StructuredPojo> PATCHSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PatchStatus").build();
private static final EffectivePatchMarshaller instance = new EffectivePatchMarshaller();
public static EffectivePatchMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(EffectivePatch effectivePatch, ProtocolMarshaller protocolMarshaller) {
if (effectivePatch == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(effectivePatch.getPatch(), PATCH_BINDING);
protocolMarshaller.marshall(effectivePatch.getPatchStatus(), PATCHSTATUS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-applicationinsights/src/main/java/com/amazonaws/services/applicationinsights/model/LogFilter.java | 1767 | /*
* 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.applicationinsights.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum LogFilter {
ERROR("ERROR"),
WARN("WARN"),
INFO("INFO");
private String value;
private LogFilter(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return LogFilter corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static LogFilter fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (LogFilter enumEntry : LogFilter.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
| apache-2.0 |
Mygraduate/Supervisor_Java | src/main/java/com/graduate/system/evaluate/dao/EvaluateDao.java | 515 | package com.graduate.system.evaluate.dao;
import com.graduate.common.BaseDao;
import com.graduate.common.BaseService;
import com.graduate.system.evaluate.model.Evaluate;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by konglinghai on 2017/3/19.
*/
@Repository
public interface EvaluateDao extends BaseDao<Evaluate> {
List<Evaluate> findEvaluateByArrageId(Long arrageId);
}
| apache-2.0 |
android-art-intel/marshmallow | art-extension/opttests/src/OptimizationTests/regression/test1150_1/Main.java | 3099 | /*
* Copyright (C) 2015 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by Dalvik Fuzzer tool (3.5.001). Mon Mar 23 00:43:32 2015
package OptimizationTests.regression.test1150_1;
import OptimizationTests.regression.shared.*;
public class Main extends FuzzerUtils {
public static final int N = 100;
public static double dFld=-121.14612;
public static void main(String[] strArr) {
byte by=41;
long l=-55817L, l1=-10L, l2=23L, lArr[]=new long[N], lArr1[]=new long[N];
boolean b=false;
float f=-110.360F, f1=0.855F;
int i=3, i1=-13, i2=-53613, i3=-8, i4=211, iArr[][]=new int[N][N], iArr1[]=new int[N];
init(lArr, -3249646889L);
init(iArr, 11);
init(lArr1, 5055935020556592655L);
init(iArr1, 11);
for (i = 87; i > 3; --i) {
i1 = (int)(203L + (--i1));
i2 = 1;
do {
if (b) {
if (b) break;
lArr[i2] >>>= (((-62048 >>> (i >> 14)) - 5872) * i1);
l += iArr[i2 + 1][i + 1];
iArr[i][i + 1] *= (i2 * (i1--));
} else {
iArr[i2][i2] = ((i1--) + (-(iArr[i + 1][i]++)));
}
dFld *= (((++dFld) - (-i2)) * (--i1));
for (i3 = 4; i3 < 91; i3++) {
lArr1[i3 - 1] = (long)(f--);
dFld += (((--i1) + (i1--)) - f);
f += (i3 - i1);
i1 = (i2 + ((-i2) - (i1 + i3)));
}
i1 = (int)(((i + i) - (l - f)) + ((i1 + l) >> i1));
i1 += (int)((long)((i4 + dFld) - (l << by)) >>> (long)((i4 - 6) - 1.494F));
l -= l;
i4 = (int)167L;
i1 ^= (iArr1[i - 1]--);
for (f1 = 2; f1 < 63; ++f1) {
if (b) continue;
i4 = (int)(((l1 + i) - (l--)) % ((long)Float.intBitsToFloat(-(i4++)) | 1));
i1 += (int)(((f1 * l2) + i1) - f1);
dFld = ((i2 + (i4 * 0.23F)) - ((f + dFld) + i3));
}
} while (++i2 < 94);
}
System.out.println("i i1 i2 = " + i + "," + i1 + "," + i2);
System.out.println("b l i3 = " + (b ? 1 : 0) + "," + l + "," + i3);
System.out.println("f i4 by = " + Float.floatToIntBits(f) + "," + i4 + "," + by);
System.out.println("f1 l1 l2 = " + Float.floatToIntBits(f1) + "," + l1 + "," + l2);
System.out.println("lArr iArr lArr1 = " + checkSum(lArr) + "," + checkSum(iArr) + "," + checkSum(lArr1));
System.out.println("iArr1 = " + checkSum(iArr1));
System.out.println("dFld = " + Double.doubleToLongBits(dFld));
}
}
| apache-2.0 |
moley/leguan | leguan-languages/leguan-language-java/src/test/java/org/leguan/refactoring/detector/MethodInvocationByTypeDetectorTest.java | 3312 | package org.leguan.refactoring.detector;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.leguan.language.java.FullQualifiedName;
import org.leguan.language.java.JavaProject;
import org.leguan.language.java.delegates.jdt.JavaTypeJdt;
import org.leguan.refactoring.AbstractJavaRefactoringTest;
import java.io.IOException;
import java.util.Collection;
import java.util.Properties;
public class MethodInvocationByTypeDetectorTest extends AbstractJavaRefactoringTest {
private JavaProject javaProject;
@Before
public void before () throws IOException {
javaProject = getJavaProject("testprojectJava");
}
@Test
public void toStringMethod () {
MethodInvocationByTypeDetector invocationByTypeDetector = new MethodInvocationByTypeDetector(Properties.class.getName(), "variable");
Assert.assertEquals ("class org.leguan.refactoring.detector.MethodInvocationByTypeDetector:java.util.Properties.null with variable variable", invocationByTypeDetector.toString());
invocationByTypeDetector = new MethodInvocationByTypeDetector(Properties.class.getName());
Assert.assertEquals ("class org.leguan.refactoring.detector.MethodInvocationByTypeDetector:java.util.Properties.null with variable null", invocationByTypeDetector.toString());
}
@Test
public void findMethodInvocations () {
JavaTypeJdt javaType = (JavaTypeJdt) javaProject.getJavaTypeContainer().findType(new FullQualifiedName("org.leguan.testproject.language.java.ClassWithInvocation"));
CompilationUnit cu = javaType.getCompilationUnit();
Assert.assertNotNull(cu);
MethodInvocationByTypeDetector invocationByTypeDetector = new MethodInvocationByTypeDetector(Properties.class.getName());
Assert.assertEquals (4, invocationByTypeDetector.getInvocations(cu).size()); //3x inMethodDeclaration, 1x inMethodDeclaration2
}
@Test
public void findMethodInvocationsByVariableName () {
String variablename = "inMethodDeclaration";
JavaTypeJdt javaType = (JavaTypeJdt) javaProject.getJavaTypeContainer().findType(new FullQualifiedName("org.leguan.testproject.language.java.ClassWithInvocation"));
CompilationUnit cu = javaType.getCompilationUnit();
Assert.assertNotNull(cu);
MethodInvocationByTypeDetector invocationByTypeDetector = new MethodInvocationByTypeDetector(Properties.class.getName(), variablename);
Collection<MethodInvocation> invocations = invocationByTypeDetector.getInvocations(cu);
Assert.assertEquals ("Invalid number of invocations found: " + invocations, 3, invocations.size());//getProperty, setProperty and hashCode
}
@Test
public void findMethodInvocationsByVariableNameInvalid () {
String variablename = "variableNameInvalid";
JavaTypeJdt javaType = (JavaTypeJdt) javaProject.getJavaTypeContainer().findType(new FullQualifiedName("org.leguan.testproject.language.java.ClassWithInvocation"));
CompilationUnit cu = javaType.getCompilationUnit();
Assert.assertNotNull(cu);
MethodInvocationByTypeDetector invocationByTypeDetector = new MethodInvocationByTypeDetector(Properties.class.getName(), variablename);
Assert.assertEquals (0, invocationByTypeDetector.getInvocations(cu).size());
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-kinesisanalyticsv2/src/main/java/com/amazonaws/services/kinesisanalyticsv2/model/transform/AddApplicationCloudWatchLoggingOptionRequestMarshaller.java | 3438 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kinesisanalyticsv2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.kinesisanalyticsv2.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* AddApplicationCloudWatchLoggingOptionRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AddApplicationCloudWatchLoggingOptionRequestMarshaller {
private static final MarshallingInfo<String> APPLICATIONNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ApplicationName").build();
private static final MarshallingInfo<Long> CURRENTAPPLICATIONVERSIONID_BINDING = MarshallingInfo.builder(MarshallingType.LONG)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CurrentApplicationVersionId").build();
private static final MarshallingInfo<StructuredPojo> CLOUDWATCHLOGGINGOPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CloudWatchLoggingOption").build();
private static final MarshallingInfo<String> CONDITIONALTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ConditionalToken").build();
private static final AddApplicationCloudWatchLoggingOptionRequestMarshaller instance = new AddApplicationCloudWatchLoggingOptionRequestMarshaller();
public static AddApplicationCloudWatchLoggingOptionRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(AddApplicationCloudWatchLoggingOptionRequest addApplicationCloudWatchLoggingOptionRequest, ProtocolMarshaller protocolMarshaller) {
if (addApplicationCloudWatchLoggingOptionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(addApplicationCloudWatchLoggingOptionRequest.getApplicationName(), APPLICATIONNAME_BINDING);
protocolMarshaller.marshall(addApplicationCloudWatchLoggingOptionRequest.getCurrentApplicationVersionId(), CURRENTAPPLICATIONVERSIONID_BINDING);
protocolMarshaller.marshall(addApplicationCloudWatchLoggingOptionRequest.getCloudWatchLoggingOption(), CLOUDWATCHLOGGINGOPTION_BINDING);
protocolMarshaller.marshall(addApplicationCloudWatchLoggingOptionRequest.getConditionalToken(), CONDITIONALTOKEN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
falko/camunda-bpm-platform | engine/src/test/java/org/camunda/bpm/engine/test/api/multitenancy/MultiTenancyExecutionPropagationTest.java | 18444 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.test.api.multitenancy;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.engine.externaltask.ExternalTask;
import org.camunda.bpm.engine.externaltask.LockedExternalTask;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.camunda.bpm.engine.management.JobDefinition;
import org.camunda.bpm.engine.repository.CaseDefinition;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.CaseExecution;
import org.camunda.bpm.engine.runtime.EventSubscription;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.Incident;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.runtime.VariableInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.model.bpmn.Bpmn;
public class MultiTenancyExecutionPropagationTest extends PluggableProcessEngineTestCase {
protected static final String CMMN_FILE = "org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn";
protected static final String SET_VARIABLE_CMMN_FILE = "org/camunda/bpm/engine/test/api/multitenancy/HumanTaskSetVariableExecutionListener.cmmn";
protected static final String PROCESS_DEFINITION_KEY = "testProcess";
protected static final String TENANT_ID = "tenant1";
public void testPropagateTenantIdToProcessDefinition() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY).done());
ProcessDefinition processDefinition = repositoryService
.createProcessDefinitionQuery()
.singleResult();
assertNotNull(processDefinition);
// inherit the tenant id from deployment
assertEquals(TENANT_ID, processDefinition.getTenantId());
}
public void testPropagateTenantIdToProcessInstance() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.userTask()
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().singleResult();
assertThat(processInstance, is(notNullValue()));
// inherit the tenant id from process definition
assertThat(processInstance.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToConcurrentExecution() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.parallelGateway("fork")
.userTask()
.parallelGateway("join")
.endEvent()
.moveToNode("fork")
.userTask()
.connectTo("join")
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
List<Execution> executions = runtimeService.createExecutionQuery().list();
assertThat(executions.size(), is(3));
assertThat(executions.get(0).getTenantId(), is(TENANT_ID));
// inherit the tenant id from process instance
assertThat(executions.get(1).getTenantId(), is(TENANT_ID));
assertThat(executions.get(2).getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToEmbeddedSubprocess() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.subProcess()
.embeddedSubProcess()
.startEvent()
.userTask()
.endEvent()
.subProcessDone()
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
List<Execution> executions = runtimeService.createExecutionQuery().list();
assertThat(executions.size(), is(2));
assertThat(executions.get(0).getTenantId(), is(TENANT_ID));
// inherit the tenant id from parent execution (e.g. process instance)
assertThat(executions.get(1).getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToTask() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.userTask()
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
Task task = taskService.createTaskQuery().singleResult();
assertThat(task, is(notNullValue()));
// inherit the tenant id from execution
assertThat(task.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToVariableInstanceOnStartProcessInstance() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.userTask()
.endEvent()
.done());
VariableMap variables = Variables.putValue("var", "test");
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
runtimeService.startProcessInstanceById(processDefinition.getId(), variables);
VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().singleResult();
assertThat(variableInstance, is(notNullValue()));
// inherit the tenant id from process instance
assertThat(variableInstance.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToVariableInstanceFromExecution() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.serviceTask()
.camundaClass(SetVariableTask.class.getName())
.camundaAsyncAfter()
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().singleResult();
assertThat(variableInstance, is(notNullValue()));
// inherit the tenant id from execution
assertThat(variableInstance.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToVariableInstanceFromTask() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.userTask()
.camundaAsyncAfter()
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
VariableMap variables = Variables.createVariables().putValue("var", "test");
Task task = taskService.createTaskQuery().singleResult();
taskService.setVariablesLocal(task.getId(), variables);
VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().singleResult();
assertThat(variableInstance, is(notNullValue()));
// inherit the tenant id from task
assertThat(variableInstance.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToStartMessageEventSubscription() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.message("start")
.endEvent()
.done());
// the event subscription of the message start is created on deployment
EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery().singleResult();
assertThat(eventSubscription, is(notNullValue()));
// inherit the tenant id from process definition
assertThat(eventSubscription.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToStartSignalEventSubscription() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.signal("start")
.endEvent()
.done());
// the event subscription of the signal start event is created on deployment
EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery().singleResult();
assertThat(eventSubscription, is(notNullValue()));
// inherit the tenant id from process definition
assertThat(eventSubscription.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToIntermediateMessageEventSubscription() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.intermediateCatchEvent()
.message("start")
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery().singleResult();
assertThat(eventSubscription, is(notNullValue()));
// inherit the tenant id from process instance
assertThat(eventSubscription.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToIntermediateSignalEventSubscription() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.intermediateCatchEvent()
.signal("start")
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery().singleResult();
assertThat(eventSubscription, is(notNullValue()));
// inherit the tenant id from process instance
assertThat(eventSubscription.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToCompensationEventSubscription() {
deploymentForTenant(TENANT_ID, "org/camunda/bpm/engine/test/api/multitenancy/compensationBoundaryEvent.bpmn");
startProcessInstance(PROCESS_DEFINITION_KEY);
// the event subscription is created after execute the activity with the attached compensation boundary event
EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery().singleResult();
assertThat(eventSubscription, is(notNullValue()));
// inherit the tenant id from process instance
assertThat(eventSubscription.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToStartTimerJobDefinition() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.timerWithDuration("PT1M")
.endEvent()
.done());
// the job definition is created on deployment
JobDefinition jobDefinition = managementService.createJobDefinitionQuery().singleResult();
assertThat(jobDefinition, is(notNullValue()));
// inherit the tenant id from process definition
assertThat(jobDefinition.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToIntermediateTimerJob() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.intermediateCatchEvent()
.timerWithDuration("PT1M")
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
// the job is created when the timer event is reached
Job job = managementService.createJobQuery().singleResult();
assertThat(job, is(notNullValue()));
// inherit the tenant id from job definition
assertThat(job.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToAsyncJob() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.userTask()
.camundaAsyncBefore()
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
// the job is created when the asynchronous activity is reached
Job job = managementService.createJobQuery().singleResult();
assertThat(job, is(notNullValue()));
// inherit the tenant id from job definition
assertThat(job.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToFailedJobIncident() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.serviceTask()
.camundaExpression("${failing}")
.camundaAsyncBefore()
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
executeAvailableJobs();
Incident incident = runtimeService.createIncidentQuery().singleResult();
assertThat(incident, is(notNullValue()));
// inherit the tenant id from execution
assertThat(incident.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToFailedStartTimerIncident() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.timerWithDuration("PT1M")
.serviceTask()
.camundaExpression("${failing}")
.endEvent()
.done());
executeAvailableJobs();
Incident incident = runtimeService.createIncidentQuery().singleResult();
assertThat(incident, is(notNullValue()));
// inherit the tenant id from job
assertThat(incident.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToFailedExternalTaskIncident() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.serviceTask()
.camundaType("external")
.camundaTopic("test")
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
// fetch the external task and mark it as failed which create an incident
List<LockedExternalTask> tasks = externalTaskService.fetchAndLock(1, "test-worker").topic("test", 1000).execute();
externalTaskService.handleFailure(tasks.get(0).getId(), "test-worker", "expected", 0, 0);
Incident incident = runtimeService.createIncidentQuery().singleResult();
assertThat(incident, is(notNullValue()));
// inherit the tenant id from execution
assertThat(incident.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToExternalTask() {
deploymentForTenant(TENANT_ID, Bpmn.createExecutableProcess(PROCESS_DEFINITION_KEY)
.startEvent()
.serviceTask()
.camundaType("external")
.camundaTopic("test")
.endEvent()
.done());
startProcessInstance(PROCESS_DEFINITION_KEY);
ExternalTask externalTask = externalTaskService.createExternalTaskQuery().singleResult();
assertThat(externalTask, is(notNullValue()));
// inherit the tenant id from execution
assertThat(externalTask.getTenantId(), is(TENANT_ID));
List<LockedExternalTask> externalTasks = externalTaskService.fetchAndLock(1, "test").topic("test", 1000).execute();
assertThat(externalTasks.size(), is(1));
assertThat(externalTasks.get(0).getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToVariableInstanceOnCreateCaseInstance() {
deploymentForTenant(TENANT_ID, CMMN_FILE);
VariableMap variables = Variables.putValue("var", "test");
CaseDefinition caseDefinition = repositoryService.createCaseDefinitionQuery().singleResult();
caseService.createCaseInstanceById(caseDefinition.getId(), variables);
VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().singleResult();
assertThat(variableInstance, is(notNullValue()));
// inherit the tenant id from case instance
assertThat(variableInstance.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToVariableInstanceFromCaseExecution() {
deploymentForTenant(TENANT_ID, SET_VARIABLE_CMMN_FILE);
createCaseInstance();
VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().singleResult();
assertThat(variableInstance, is(notNullValue()));
// inherit the tenant id from case execution
assertThat(variableInstance.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToVariableInstanceFromHumanTask() {
deploymentForTenant(TENANT_ID, CMMN_FILE);
createCaseInstance();
VariableMap variables = Variables.createVariables().putValue("var", "test");
CaseExecution caseExecution = caseService.createCaseExecutionQuery().activityId("PI_HumanTask_1").singleResult();
caseService.setVariables(caseExecution.getId(), variables);
VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().singleResult();
assertThat(variableInstance, is(notNullValue()));
// inherit the tenant id from human task
assertThat(variableInstance.getTenantId(), is(TENANT_ID));
}
public void testPropagateTenantIdToTaskOnCreateCaseInstance() {
deploymentForTenant(TENANT_ID, CMMN_FILE);
CaseDefinition caseDefinition = repositoryService.createCaseDefinitionQuery().singleResult();
caseService.createCaseInstanceById(caseDefinition.getId());
Task task = taskService.createTaskQuery().taskName("A HumanTask").singleResult();
assertThat(task, is(notNullValue()));
// inherit the tenant id from case instance
assertThat(task.getTenantId(), is(TENANT_ID));
}
public static class SetVariableTask implements JavaDelegate {
@Override
public void execute(DelegateExecution execution) throws Exception {
execution.setVariable("var", "test");
}
}
protected void startProcessInstance(String processDefinitionKey) {
ProcessDefinition processDefinition = repositoryService
.createProcessDefinitionQuery()
.processDefinitionKey(processDefinitionKey)
.latestVersion()
.singleResult();
runtimeService.startProcessInstanceById(processDefinition.getId());
}
protected void createCaseInstance() {
CaseDefinition caseDefinition = repositoryService.createCaseDefinitionQuery().singleResult();
caseService.createCaseInstanceById(caseDefinition.getId());
}
}
| apache-2.0 |
daschl/netty | codec-http2/src/main/java/io/netty/handler/codec/http2/AbstractHttp2ConnectionHandler.java | 42715 | /*
* Copyright 2014 The Netty Project
*
* The Netty Project 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 io.netty.handler.codec.http2;
import static io.netty.handler.codec.http2.Http2CodecUtil.CONNECTION_STREAM_ID;
import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT;
import static io.netty.handler.codec.http2.Http2CodecUtil.HTTP_UPGRADE_STREAM_ID;
import static io.netty.handler.codec.http2.Http2CodecUtil.connectionPrefaceBuf;
import static io.netty.handler.codec.http2.Http2CodecUtil.toByteBuf;
import static io.netty.handler.codec.http2.Http2CodecUtil.toHttp2Exception;
import static io.netty.handler.codec.http2.Http2Error.NO_ERROR;
import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
import static io.netty.handler.codec.http2.Http2Error.STREAM_CLOSED;
import static io.netty.handler.codec.http2.Http2Exception.protocolError;
import static io.netty.handler.codec.http2.Http2Stream.State.HALF_CLOSED_LOCAL;
import static io.netty.handler.codec.http2.Http2Stream.State.HALF_CLOSED_REMOTE;
import static io.netty.handler.codec.http2.Http2Stream.State.OPEN;
import static io.netty.handler.codec.http2.Http2Stream.State.RESERVED_LOCAL;
import static io.netty.handler.codec.http2.Http2Stream.State.RESERVED_REMOTE;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Abstract base class for a handler of HTTP/2 frames. Handles reading and writing of HTTP/2 frames
* as well as management of connection state and flow control for both inbound and outbound data
* frames.
* <p>
* Subclasses need to implement the methods defined by the {@link Http2FrameObserver} interface for
* receiving inbound frames. Outbound frames are sent via one of the {@code writeXXX} methods.
* <p>
* It should be noted that the connection preface is sent upon either activation or addition of this
* handler to the pipeline. Subclasses overriding {@link #channelActive} or {@link #handlerAdded}
* must call this class to write the preface to the remote endpoint.
*/
public abstract class AbstractHttp2ConnectionHandler extends ByteToMessageDecoder implements
Http2FrameObserver {
private final Http2FrameObserver internalFrameObserver = new FrameReadObserver();
private final Http2FrameReader frameReader;
private final Http2FrameWriter frameWriter;
private final Http2Connection connection;
private final Http2InboundFlowController inboundFlow;
private final Http2OutboundFlowController outboundFlow;
// We prefer ArrayDeque to LinkedList because later will produce more GC.
// This initial capacity is plenty for SETTINGS traffic.
private final ArrayDeque<Http2Settings> outstandingLocalSettingsQueue = new ArrayDeque<Http2Settings>(4);
private ByteBuf clientPrefaceString;
private boolean prefaceSent;
private boolean prefaceReceived;
private ChannelHandlerContext ctx;
private ChannelFutureListener closeListener;
protected AbstractHttp2ConnectionHandler(boolean server) {
this(server, false);
}
protected AbstractHttp2ConnectionHandler(boolean server, boolean allowCompression) {
this(new DefaultHttp2Connection(server, allowCompression));
}
protected AbstractHttp2ConnectionHandler(Http2Connection connection) {
this(connection, new DefaultHttp2FrameReader(), new DefaultHttp2FrameWriter(),
new DefaultHttp2InboundFlowController(), new DefaultHttp2OutboundFlowController());
}
protected AbstractHttp2ConnectionHandler(Http2Connection connection,
Http2FrameReader frameReader, Http2FrameWriter frameWriter,
Http2InboundFlowController inboundFlow, Http2OutboundFlowController outboundFlow) {
if (connection == null) {
throw new NullPointerException("connection");
}
if (frameReader == null) {
throw new NullPointerException("frameReader");
}
if (frameWriter == null) {
throw new NullPointerException("frameWriter");
}
if (inboundFlow == null) {
throw new NullPointerException("inboundFlow");
}
if (outboundFlow == null) {
throw new NullPointerException("outboundFlow");
}
this.connection = connection;
this.frameReader = frameReader;
this.frameWriter = frameWriter;
this.inboundFlow = inboundFlow;
this.outboundFlow = outboundFlow;
// Set the expected client preface string. Only servers should receive this.
clientPrefaceString = connection.isServer()? connectionPrefaceBuf() : null;
}
/**
* Handles the client-side (cleartext) upgrade from HTTP to HTTP/2. Reserves local stream 1 for
* the HTTP/2 response.
*/
public final void onHttpClientUpgrade() throws Http2Exception {
if (connection.isServer()) {
throw protocolError("Client-side HTTP upgrade requested for a server");
}
if (prefaceSent || prefaceReceived) {
throw protocolError("HTTP upgrade must occur before HTTP/2 preface is sent or received");
}
// Create a local stream used for the HTTP cleartext upgrade.
createLocalStream(HTTP_UPGRADE_STREAM_ID, true, CONNECTION_STREAM_ID,
DEFAULT_PRIORITY_WEIGHT, false);
}
/**
* Handles the server-side (cleartext) upgrade from HTTP to HTTP/2.
*
* @param settings the settings for the remote endpoint.
*/
public final void onHttpServerUpgrade(Http2Settings settings)
throws Http2Exception {
if (!connection.isServer()) {
throw protocolError("Server-side HTTP upgrade requested for a client");
}
if (prefaceSent || prefaceReceived) {
throw protocolError("HTTP upgrade must occur before HTTP/2 preface is sent or received");
}
// Apply the settings but no ACK is necessary.
applyRemoteSettings(settings);
// Create a stream in the half-closed state.
createRemoteStream(HTTP_UPGRADE_STREAM_ID, true, CONNECTION_STREAM_ID,
DEFAULT_PRIORITY_WEIGHT, false);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// The channel just became active - send the connection preface to the remote
// endpoint.
sendPreface(ctx);
super.channelActive(ctx);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
// This handler was just added to the context. In case it was handled after
// the connection became active, send the connection preface now.
this.ctx = ctx;
sendPreface(ctx);
}
@Override
protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
// Free any resources associated with this handler.
freeResources();
}
protected final ChannelHandlerContext ctx() {
return ctx;
}
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
// Avoid NotYetConnectedException
if (!ctx.channel().isActive()) {
ctx.close(promise);
return;
}
sendGoAway(ctx, promise, null);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
ChannelFuture future = ctx.newSucceededFuture();
for (Http2Stream stream : connection.activeStreams().toArray(new Http2Stream[0])) {
close(stream, ctx, future);
}
super.channelInactive(ctx);
}
/**
* Handles {@link Http2Exception} objects that were thrown from other handlers. Ignores all
* other exceptions.
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause instanceof Http2Exception) {
processHttp2Exception(ctx, (Http2Exception) cause);
}
super.exceptionCaught(ctx, cause);
}
/**
* Gets the local settings for this endpoint of the HTTP/2 connection.
*/
public final Http2Settings settings() {
Http2Settings settings = new Http2Settings();
settings.allowCompressedData(connection.local().allowCompressedData());
settings.initialWindowSize(inboundFlow.initialInboundWindowSize());
settings.maxConcurrentStreams(connection.remote().maxStreams());
settings.maxHeaderTableSize(frameReader.maxHeaderTableSize());
if (!connection.isServer()) {
// Only set the pushEnabled flag if this is a client endpoint.
settings.pushEnabled(connection.local().allowPushTo());
}
return settings;
}
/**
* Gets the next stream ID that can be created by the local endpoint.
*/
protected int nextStreamId() {
return connection.local().nextStreamId();
}
protected ChannelFuture writeData(final ChannelHandlerContext ctx,
final ChannelPromise promise, int streamId, final ByteBuf data, int padding,
boolean endStream, boolean endSegment, boolean compressed) {
try {
if (connection.isGoAway()) {
throw protocolError("Sending data after connection going away.");
}
if (!connection.remote().allowCompressedData() && compressed) {
throw protocolError("compression is disallowed for remote endpoint.");
}
Http2Stream stream = connection.requireStream(streamId);
stream.verifyState(PROTOCOL_ERROR, OPEN, HALF_CLOSED_REMOTE);
// Hand control of the frame to the flow controller.
outboundFlow.sendFlowControlled(streamId, data, padding, endStream, endSegment,
compressed, new FlowControlWriter(ctx, data, promise));
return promise;
} catch (Http2Exception e) {
return promise.setFailure(e);
}
}
protected ChannelFuture writeHeaders(ChannelHandlerContext ctx, ChannelPromise promise,
int streamId, Http2Headers headers, int padding, boolean endStream, boolean endSegment) {
return writeHeaders(ctx, promise, streamId, headers, 0, DEFAULT_PRIORITY_WEIGHT, false,
padding, endStream, endSegment);
}
protected ChannelFuture writeHeaders(ChannelHandlerContext ctx, ChannelPromise promise,
int streamId, Http2Headers headers, int streamDependency, short weight,
boolean exclusive, int padding, boolean endStream, boolean endSegment) {
try {
if (connection.isGoAway()) {
throw protocolError("Sending headers after connection going away.");
}
Http2Stream stream = connection.stream(streamId);
if (stream == null) {
// Create a new locally-initiated stream.
stream = createLocalStream(streamId, endStream, streamDependency, weight, exclusive);
} else {
// An existing stream...
if (stream.state() == RESERVED_LOCAL) {
// Sending headers on a reserved push stream ... open it for push to the remote
// endpoint.
stream.openForPush();
// Allow outbound traffic only.
if (!endStream) {
outboundFlow.addStream(streamId, streamDependency, weight, exclusive);
}
} else {
// The stream already exists, make sure it's in an allowed state.
stream.verifyState(PROTOCOL_ERROR, OPEN, HALF_CLOSED_REMOTE);
// Update the priority for this stream only if we'll be sending more data.
if (!endStream) {
outboundFlow.updateStream(stream.id(), streamDependency, weight, exclusive);
}
}
// If the headers are the end of the stream, close it now.
if (endStream) {
closeLocalSide(stream, ctx, promise);
}
}
return frameWriter.writeHeaders(ctx, promise, streamId, headers, streamDependency,
weight, exclusive, padding, endStream, endSegment);
} catch (Http2Exception e) {
return promise.setFailure(e);
}
}
protected ChannelFuture writePriority(ChannelHandlerContext ctx, ChannelPromise promise,
int streamId, int streamDependency, short weight, boolean exclusive) {
try {
if (connection.isGoAway()) {
throw protocolError("Sending priority after connection going away.");
}
// Update the priority on this stream.
outboundFlow.updateStream(streamId, streamDependency, weight, exclusive);
return frameWriter.writePriority(ctx, promise, streamId, streamDependency, weight,
exclusive);
} catch (Http2Exception e) {
return promise.setFailure(e);
}
}
protected ChannelFuture writeRstStream(ChannelHandlerContext ctx, ChannelPromise promise,
int streamId, long errorCode) {
Http2Stream stream = connection.stream(streamId);
if (stream == null) {
// The stream may already have been closed ... ignore.
promise.setSuccess();
return promise;
}
close(stream, ctx, promise);
return frameWriter.writeRstStream(ctx, promise, streamId, errorCode);
}
protected ChannelFuture writeSettings(ChannelHandlerContext ctx, ChannelPromise promise,
Http2Settings settings) {
outstandingLocalSettingsQueue.add(settings);
try {
if (connection.isGoAway()) {
throw protocolError("Sending settings after connection going away.");
}
if (settings.hasPushEnabled() && connection.isServer()) {
throw protocolError("Server sending SETTINGS frame with ENABLE_PUSH specified");
}
return frameWriter.writeSettings(ctx, promise, settings);
} catch (Http2Exception e) {
return promise.setFailure(e);
}
}
protected ChannelFuture writePing(ChannelHandlerContext ctx, ChannelPromise promise,
ByteBuf data) {
try {
if (connection.isGoAway()) {
throw protocolError("Sending ping after connection going away.");
}
// Just pass the frame through.
return frameWriter.writePing(ctx, promise, false, data);
} catch (Http2Exception e) {
return promise.setFailure(e);
}
}
protected ChannelFuture writePushPromise(ChannelHandlerContext ctx, ChannelPromise promise,
int streamId, int promisedStreamId, Http2Headers headers, int padding) {
try {
if (connection.isGoAway()) {
throw protocolError("Sending push promise after connection going away.");
}
// Reserve the promised stream.
Http2Stream stream = connection.requireStream(streamId);
connection.local().reservePushStream(promisedStreamId, stream);
// Write the frame.
return frameWriter.writePushPromise(ctx, promise, streamId, promisedStreamId, headers,
padding);
} catch (Http2Exception e) {
return promise.setFailure(e);
}
}
protected ChannelFuture writeAltSvc(ChannelHandlerContext ctx, ChannelPromise promise,
int streamId, long maxAge, int port, ByteBuf protocolId, String host, String origin) {
if (!connection.isServer()) {
return promise.setFailure(protocolError("Client sending ALT_SVC frame"));
}
return frameWriter.writeAltSvc(ctx, promise, streamId, maxAge, port, protocolId, host,
origin);
}
@Override
protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
throws Exception {
try {
// Read the remaining of the client preface string if we haven't already.
// If this is a client endpoint, always returns true.
if (!readClientPrefaceString(ctx, in)) {
// Still processing the client preface.
return;
}
frameReader.readFrame(ctx, in, internalFrameObserver);
} catch (Http2Exception e) {
processHttp2Exception(ctx, e);
}
}
/**
* Decodes the client connection preface string from the input buffer.
*
* @return {@code true} if processing of the client preface string is complete. Since client
* preface strings can only be received by servers, returns true immediately for client
* endpoints.
*/
private boolean readClientPrefaceString(ChannelHandlerContext ctx, ByteBuf in) {
if (clientPrefaceString == null) {
return true;
}
int prefaceRemaining = clientPrefaceString.readableBytes();
int bytesRead = Math.min(in.readableBytes(), prefaceRemaining);
// Read the portion of the input up to the length of the preface, if reached.
ByteBuf sourceSlice = in.readSlice(bytesRead);
// Read the same number of bytes from the preface buffer.
ByteBuf prefaceSlice = clientPrefaceString.readSlice(bytesRead);
// If the input so far doesn't match the preface, break the connection.
if (bytesRead == 0 || !prefaceSlice.equals(sourceSlice)) {
ctx.close();
return false;
}
if (!clientPrefaceString.isReadable()) {
// Entire preface has been read.
clientPrefaceString.release();
clientPrefaceString = null;
return true;
}
return false;
}
/**
* Processes the given exception. Depending on the type of exception, delegates to either
* {@link #processConnectionError} or {@link #processStreamError}.
*/
private void processHttp2Exception(ChannelHandlerContext ctx, Http2Exception e) {
if (e instanceof Http2StreamException) {
processStreamError(ctx, (Http2StreamException) e);
} else {
processConnectionError(ctx, e);
}
}
private void processConnectionError(ChannelHandlerContext ctx, Http2Exception cause) {
sendGoAway(ctx, ctx.newPromise(), cause);
}
private void processStreamError(ChannelHandlerContext ctx, Http2StreamException cause) {
// Close the stream if it was open.
int streamId = cause.streamId();
Http2Stream stream = connection.stream(streamId);
if (stream != null) {
close(stream, ctx, null);
}
// Send the Rst frame to the remote endpoint.
frameWriter.writeRstStream(ctx, ctx.newPromise(), streamId, cause.error().code());
}
private void sendGoAway(ChannelHandlerContext ctx, ChannelPromise promise,
Http2Exception cause) {
ChannelFuture future = null;
ChannelPromise closePromise = promise;
if (!connection.isGoAway()) {
connection.goAwaySent();
int errorCode = cause != null ? cause.error().code() : NO_ERROR.code();
ByteBuf debugData = toByteBuf(ctx, cause);
future = frameWriter.writeGoAway(ctx, promise, connection.remote().lastStreamCreated(),
errorCode, debugData);
closePromise = null;
}
closeListener = getOrCreateCloseListener(ctx, closePromise);
// If there are no active streams, close immediately after the send is complete.
// Otherwise wait until all streams are inactive.
if (cause != null || connection.numActiveStreams() == 0) {
if (future == null) {
future = ctx.newSucceededFuture();
}
future.addListener(closeListener);
}
}
private ChannelFutureListener getOrCreateCloseListener(final ChannelHandlerContext ctx,
ChannelPromise promise) {
final ChannelPromise closePromise = promise == null? ctx.newPromise() : promise;
if (closeListener == null) {
// If no promise was provided, create a new one.
closeListener = new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
ctx.close(closePromise);
freeResources();
}
};
} else {
closePromise.setSuccess();
}
return closeListener;
}
private void freeResources() {
frameReader.close();
frameWriter.close();
if (clientPrefaceString != null) {
clientPrefaceString.release();
clientPrefaceString = null;
}
}
private void closeLocalSide(Http2Stream stream, ChannelHandlerContext ctx, ChannelFuture future) {
switch (stream.state()) {
case HALF_CLOSED_LOCAL:
case OPEN:
stream.closeLocalSide();
outboundFlow.removeStream(stream.id());
break;
default:
close(stream, ctx, future);
break;
}
}
private void closeRemoteSide(Http2Stream stream, ChannelHandlerContext ctx, ChannelFuture future) {
switch (stream.state()) {
case HALF_CLOSED_REMOTE:
case OPEN:
stream.closeRemoteSide();
inboundFlow.removeStream(stream.id());
break;
default:
close(stream, ctx, future);
break;
}
}
private void close(Http2Stream stream, ChannelHandlerContext ctx, ChannelFuture future) {
stream.close();
// Notify the flow controllers.
inboundFlow.removeStream(stream.id());
outboundFlow.removeStream(stream.id());
// If this connection is closing and there are no longer any
// active streams, close after the current operation completes.
if (closeListener != null && connection.numActiveStreams() == 0) {
future.addListener(closeListener);
}
}
/**
* Verifies that the HTTP/2 connection preface has been received from the remote endpoint.
*/
private void verifyPrefaceReceived() throws Http2Exception {
if (!prefaceReceived) {
throw protocolError("Received non-SETTINGS as first frame.");
}
}
/**
* Sends the HTTP/2 connection preface upon establishment of the connection, if not already sent.
*/
private void sendPreface(final ChannelHandlerContext ctx) throws Http2Exception {
if (prefaceSent || !ctx.channel().isActive()) {
return;
}
prefaceSent = true;
if (!connection.isServer()) {
// Clients must send the preface string as the first bytes on the connection.
ctx.write(connectionPrefaceBuf()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}
// Both client and server must send their initial settings.
Http2Settings settings = settings();
outstandingLocalSettingsQueue.add(settings);
frameWriter.writeSettings(ctx, ctx.newPromise(), settings).addListener(
ChannelFutureListener.CLOSE_ON_FAILURE);
}
/**
* Applies settings sent from the local endpoint.
*/
private void applyLocalSettings(Http2Settings settings) throws Http2Exception {
if (settings.hasPushEnabled()) {
if (connection.isServer()) {
throw protocolError("Server sending SETTINGS frame with ENABLE_PUSH specified");
}
connection.local().allowPushTo(settings.pushEnabled());
}
if (settings.hasAllowCompressedData()) {
connection.local().allowCompressedData(settings.allowCompressedData());
}
if (settings.hasMaxConcurrentStreams()) {
connection.remote().maxStreams(settings.maxConcurrentStreams());
}
if (settings.hasMaxHeaderTableSize()) {
frameReader.maxHeaderTableSize(settings.maxHeaderTableSize());
}
if (settings.hasInitialWindowSize()) {
inboundFlow.initialInboundWindowSize(settings.initialWindowSize());
}
}
/**
* Applies settings received from the remote endpoint.
*/
private void applyRemoteSettings(Http2Settings settings) throws Http2Exception {
if (settings.hasPushEnabled()) {
if (!connection.isServer()) {
throw protocolError("Client received SETTINGS frame with ENABLE_PUSH specified");
}
connection.remote().allowPushTo(settings.pushEnabled());
}
if (settings.hasAllowCompressedData()) {
connection.remote().allowCompressedData(settings.allowCompressedData());
}
if (settings.hasMaxConcurrentStreams()) {
connection.local().maxStreams(settings.maxConcurrentStreams());
}
if (settings.hasMaxHeaderTableSize()) {
frameWriter.maxHeaderTableSize(settings.maxHeaderTableSize());
}
if (settings.hasInitialWindowSize()) {
outboundFlow.initialOutboundWindowSize(settings.initialWindowSize());
}
}
/**
* Creates a new stream initiated by the local endpoint.
*/
private Http2Stream createLocalStream(int streamId, boolean halfClosed, int streamDependency,
short weight, boolean exclusive) throws Http2Exception {
Http2Stream stream = connection.local().createStream(streamId, halfClosed);
inboundFlow.addStream(streamId);
if (!halfClosed) {
outboundFlow.addStream(streamId, streamDependency, weight, exclusive);
}
return stream;
}
/**
* Creates a new stream initiated by the remote endpoint.
*/
private Http2Stream createRemoteStream(int streamId, boolean halfClosed, int streamDependency,
short weight, boolean exclusive) throws Http2Exception {
Http2Stream stream = connection.remote().createStream(streamId, halfClosed);
outboundFlow.addStream(streamId, streamDependency, weight, exclusive);
if (!halfClosed) {
inboundFlow.addStream(streamId);
}
return stream;
}
/**
* Handles all inbound frames from the network.
*/
private final class FrameReadObserver implements Http2FrameObserver {
@Override
public void onDataRead(final ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
boolean endOfStream, boolean endOfSegment, boolean compressed) throws Http2Exception {
verifyPrefaceReceived();
if (!connection.local().allowCompressedData() && compressed) {
throw protocolError("compression is disallowed.");
}
// Check if we received a data frame for a stream which is half-closed
Http2Stream stream = connection.requireStream(streamId);
stream.verifyState(STREAM_CLOSED, OPEN, HALF_CLOSED_LOCAL);
// Apply flow control.
inboundFlow.applyInboundFlowControl(streamId, data, padding, endOfStream, endOfSegment,
compressed, new Http2InboundFlowController.FrameWriter() {
@Override
public void writeFrame(int streamId, int windowSizeIncrement)
throws Http2Exception {
frameWriter.writeWindowUpdate(ctx, ctx.newPromise(), streamId,
windowSizeIncrement);
}
});
if (isInboundStreamAfterGoAway(streamId)) {
return;
}
if (endOfStream) {
closeRemoteSide(stream, ctx, ctx.newSucceededFuture());
}
AbstractHttp2ConnectionHandler.this.onDataRead(ctx, streamId, data, padding, endOfStream,
endOfSegment, compressed);
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
int padding, boolean endStream, boolean endSegment) throws Http2Exception {
onHeadersRead(ctx, streamId, headers, 0, DEFAULT_PRIORITY_WEIGHT, false, padding,
endStream, endSegment);
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
int streamDependency, short weight, boolean exclusive, int padding,
boolean endStream, boolean endSegment) throws Http2Exception {
verifyPrefaceReceived();
if (isInboundStreamAfterGoAway(streamId)) {
return;
}
Http2Stream stream = connection.stream(streamId);
if (stream == null) {
createRemoteStream(streamId, endStream, streamDependency, weight, exclusive);
} else {
if (stream.state() == RESERVED_REMOTE) {
// Received headers for a reserved push stream ... open it for push to the
// local endpoint.
stream.verifyState(PROTOCOL_ERROR, RESERVED_REMOTE);
stream.openForPush();
// Allow inbound traffic only.
if (!endStream) {
inboundFlow.addStream(streamId);
}
} else {
// Receiving headers on an existing stream. Make sure the stream is in an
// allowed
// state.
stream.verifyState(PROTOCOL_ERROR, OPEN, HALF_CLOSED_LOCAL);
// Update the outbound priority if outbound traffic is allowed.
if (stream.state() == OPEN) {
outboundFlow.updateStream(streamId, streamDependency, weight, exclusive);
}
}
// If the headers completes this stream, close it.
if (endStream) {
closeRemoteSide(stream, ctx, ctx.newSucceededFuture());
}
}
AbstractHttp2ConnectionHandler.this.onHeadersRead(ctx, streamId, headers, streamDependency,
weight, exclusive, padding, endStream, endSegment);
}
@Override
public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency,
short weight, boolean exclusive) throws Http2Exception {
verifyPrefaceReceived();
if (isInboundStreamAfterGoAway(streamId)) {
// Ignore frames for any stream created after we sent a go-away.
return;
}
// Set the priority for this stream on the flow controller.
outboundFlow.updateStream(streamId, streamDependency, weight, exclusive);
AbstractHttp2ConnectionHandler.this.onPriorityRead(ctx, streamId, streamDependency,
weight, exclusive);
}
@Override
public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode)
throws Http2Exception {
verifyPrefaceReceived();
if (isInboundStreamAfterGoAway(streamId)) {
// Ignore frames for any stream created after we sent a go-away.
return;
}
Http2Stream stream = connection.stream(streamId);
if (stream == null) {
// RstStream frames must be ignored for closed streams.
return;
}
close(stream, ctx, ctx.newSucceededFuture());
AbstractHttp2ConnectionHandler.this.onRstStreamRead(ctx, streamId, errorCode);
}
@Override
public void onSettingsAckRead(ChannelHandlerContext ctx) throws Http2Exception {
verifyPrefaceReceived();
// Apply oldest outstanding local settings here. This is a synchronization point
// between endpoints.
Http2Settings settings = outstandingLocalSettingsQueue.poll();
if (settings != null) {
applyLocalSettings(settings);
}
AbstractHttp2ConnectionHandler.this.onSettingsAckRead(ctx);
}
@Override
public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings)
throws Http2Exception {
applyRemoteSettings(settings);
// Acknowledge receipt of the settings.
frameWriter.writeSettingsAck(ctx, ctx.newPromise());
// We've received at least one non-ack settings frame from the remote endpoint.
prefaceReceived = true;
AbstractHttp2ConnectionHandler.this.onSettingsRead(ctx, settings);
}
@Override
public void onPingRead(ChannelHandlerContext ctx, ByteBuf data) throws Http2Exception {
verifyPrefaceReceived();
// Send an ack back to the remote client.
frameWriter.writePing(ctx, ctx.newPromise(), true, data);
AbstractHttp2ConnectionHandler.this.onPingRead(ctx, data);
}
@Override
public void onPingAckRead(ChannelHandlerContext ctx, ByteBuf data) throws Http2Exception {
verifyPrefaceReceived();
AbstractHttp2ConnectionHandler.this.onPingAckRead(ctx, data);
}
@Override
public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId,
int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception {
verifyPrefaceReceived();
if (isInboundStreamAfterGoAway(streamId)) {
// Ignore frames for any stream created after we sent a go-away.
return;
}
// Reserve the push stream based with a priority based on the current stream's priority.
Http2Stream parentStream = connection.requireStream(streamId);
connection.remote().reservePushStream(promisedStreamId, parentStream);
AbstractHttp2ConnectionHandler.this.onPushPromiseRead(ctx, streamId, promisedStreamId,
headers, padding);
}
@Override
public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)
throws Http2Exception {
// Don't allow any more connections to be created.
connection.goAwayReceived();
AbstractHttp2ConnectionHandler.this.onGoAwayRead(ctx, lastStreamId, errorCode, debugData);
}
@Override
public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId,
int windowSizeIncrement) throws Http2Exception {
verifyPrefaceReceived();
if (isInboundStreamAfterGoAway(streamId)) {
// Ignore frames for any stream created after we sent a go-away.
return;
}
if (streamId > 0) {
Http2Stream stream = connection.stream(streamId);
if (stream == null) {
// Window Update frames must be ignored for closed streams.
return;
}
stream.verifyState(PROTOCOL_ERROR, OPEN, HALF_CLOSED_REMOTE);
}
// Update the outbound flow controller.
outboundFlow.updateOutboundWindowSize(streamId, windowSizeIncrement);
AbstractHttp2ConnectionHandler.this.onWindowUpdateRead(ctx, streamId, windowSizeIncrement);
}
@Override
public void onAltSvcRead(ChannelHandlerContext ctx, int streamId, long maxAge, int port,
ByteBuf protocolId, String host, String origin) throws Http2Exception {
if (connection.isServer()) {
throw protocolError("Server received ALT_SVC frame");
}
AbstractHttp2ConnectionHandler.this.onAltSvcRead(ctx, streamId, maxAge, port,
protocolId, host, origin);
}
@Override
public void onBlockedRead(ChannelHandlerContext ctx, int streamId) throws Http2Exception {
verifyPrefaceReceived();
if (isInboundStreamAfterGoAway(streamId)) {
// Ignore frames for any stream created after we sent a go-away.
return;
}
if (streamId > 0) {
Http2Stream stream = connection.stream(streamId);
if (stream == null) {
// Window Update frames must be ignored for closed streams.
return;
}
stream.verifyState(PROTOCOL_ERROR, OPEN, HALF_CLOSED_REMOTE);
}
// Update the outbound flow controller.
outboundFlow.setBlocked(streamId);
AbstractHttp2ConnectionHandler.this.onBlockedRead(ctx, streamId);
}
/**
* Determines whether or not the stream was created after we sent a go-away frame. Frames
* from streams created after we sent a go-away should be ignored. Frames for the connection
* stream ID (i.e. 0) will always be allowed.
*/
private boolean isInboundStreamAfterGoAway(int streamId) {
return connection.isGoAwaySent() && connection.remote().lastStreamCreated() <= streamId;
}
}
/**
* Controls the write for a single outbound DATA frame. This writer is passed to the outbound flow
* controller, which may break the frame into chunks as dictated by the flow control window. If
* the write of any chunk fails, the original promise fails as well. Success occurs after the last
* chunk is written successfully.
*/
private final class FlowControlWriter implements Http2OutboundFlowController.FrameWriter {
private final ChannelHandlerContext ctx;
private final ChannelPromise promise;
private final List<ChannelPromise> promises;
private int remaining;
FlowControlWriter(ChannelHandlerContext ctx, ByteBuf data, ChannelPromise promise) {
this.ctx = ctx;
this.promise = promise;
promises = new ArrayList<ChannelPromise>(
Arrays.asList(promise));
remaining = data.readableBytes();
}
@Override
public void writeFrame(int streamId, ByteBuf data, int padding,
boolean endStream, boolean endSegment, boolean compressed) {
if (promise.isDone()) {
// Most likely the write already failed. Just release the
// buffer.
data.release();
return;
}
remaining -= data.readableBytes();
// The flow controller may split the write into chunks. Use a new
// promise for intermediate writes.
final ChannelPromise chunkPromise =
remaining == 0 ? promise : ctx.newPromise();
// The original promise is already in the list, so don't add again.
if (chunkPromise != promise) {
promises.add(chunkPromise);
}
// TODO: consider adding a flush() method to this interface. The
// frameWriter flushes on each write which isn't optimal
// for the case of the outbound flow controller, which sends a batch
// of frames when the flow control window changes. We should let
// the flow controller manually flush after all writes are.
// complete.
// Write the frame.
ChannelFuture future =
frameWriter.writeData(ctx, chunkPromise, streamId, data,
padding, endStream, endSegment, compressed);
// Close the connection on write failures that leave the outbound
// flow
// control window in a corrupt state.
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future)
throws Exception {
if (!future.isSuccess()) {
// If any of the chunk writes fail, also fail the
// original
// future that was returned to the caller.
failAllPromises(future.cause());
processHttp2Exception(ctx,
toHttp2Exception(future.cause()));
}
}
});
// Close the local side of the stream if this is the last frame
if (endStream) {
Http2Stream stream = connection.stream(streamId);
closeLocalSide(stream, ctx, ctx.newPromise());
}
}
@Override
public void setFailure(Throwable cause) {
failAllPromises(cause);
}
/**
* Called when the write for any chunk fails. Fails all promises including
* the one returned to the caller.
*/
private void failAllPromises(Throwable cause) {
for (ChannelPromise chunkPromise : promises) {
if (!chunkPromise.isDone()) {
chunkPromise.setFailure(cause);
}
}
}
}
}
| apache-2.0 |
Blazebit/blaze-weblink | rest/model/src/main/java/com/blazebit/weblink/rest/model/BulkWeblinkRepresentation.java | 981 | package com.blazebit.weblink.rest.model;
import java.util.Calendar;
import java.util.Map;
import java.util.Set;
import com.blazebit.weblink.rest.model.config.ConfigurationTypeConfigElementRepresentation;
public class BulkWeblinkRepresentation extends WeblinkRepresentation {
private static final long serialVersionUID = 1L;
private String weblinkKey;
public BulkWeblinkRepresentation() {
super();
}
public BulkWeblinkRepresentation(String targetUri, Calendar expirationTime, String securityGroupName, String dispatcherType, Set<ConfigurationTypeConfigElementRepresentation> dispatcherConfiguration, Map<String, String> tags, Calendar creationDate, String weblinkKey) {
super(targetUri, expirationTime, securityGroupName, dispatcherType, dispatcherConfiguration, tags, creationDate);
this.weblinkKey = weblinkKey;
}
public String getWeblinkKey() {
return weblinkKey;
}
public void setWeblinkKey(String weblinkKey) {
this.weblinkKey = weblinkKey;
}
}
| apache-2.0 |
TTroia/CommunityManager | src/com/hdc/dao/BaseDao.java | 671 | package com.hdc.dao;
import java.util.List;
import java.util.Map;
import com.hdc.page.Page;
public interface BaseDao {
public int insert(Object obj);
public int update(Object obj);
public int updateByMap(String tableName, Map<String,Object> updateMap,Map<String,Object> wherMap);
public int delete(Object obj );
public int deleteAll(Object obj);
public Object getObjectById(Object obj);
public List getObjectList(Object obj,Page page);
public List getObjectListByOrderByPro(Object obj,Page page,String orderBy);
//降序
public List getObjectListByOrderByPro(Object obj,Page page,String orderBy,String desc);
}
| apache-2.0 |
alanbuttars/commons-java | commons-cli/src/main/java/com/alanbuttars/commons/cli/evaluator/evaluation/EvaluationEnum.java | 994 | /*
* Copyright (C) Alan Buttars
*
* 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.alanbuttars.commons.cli.evaluator.evaluation;
import com.alanbuttars.commons.cli.evaluator.CommandLineEvaluator;
/**
* Enumerated types used by {@link CommandLineEvaluator} to identify either conclusively or non-conclusively that a
* {@link Process} is successful or non-successful.
*
* @author Alan Buttars
*
*/
enum EvaluationEnum {
SUCCESS, //
FAILURE, //
NON_CONCLUSIVE;
}
| apache-2.0 |
googleads/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202111/ApiVersionError.java | 2259 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.admanager.jaxws.v202111;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Errors related to the usage of API versions.
*
*
* <p>Java class for ApiVersionError complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ApiVersionError">
* <complexContent>
* <extension base="{https://www.google.com/apis/ads/publisher/v202111}ApiError">
* <sequence>
* <element name="reason" type="{https://www.google.com/apis/ads/publisher/v202111}ApiVersionError.Reason" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ApiVersionError", propOrder = {
"reason"
})
public class ApiVersionError
extends ApiError
{
@XmlSchemaType(name = "string")
protected ApiVersionErrorReason reason;
/**
* Gets the value of the reason property.
*
* @return
* possible object is
* {@link ApiVersionErrorReason }
*
*/
public ApiVersionErrorReason getReason() {
return reason;
}
/**
* Sets the value of the reason property.
*
* @param value
* allowed object is
* {@link ApiVersionErrorReason }
*
*/
public void setReason(ApiVersionErrorReason value) {
this.reason = value;
}
}
| apache-2.0 |
pkdevbox/gerrit | gerrit-server/src/test/java/com/google/gerrit/server/mail/AddressTest.java | 4465 | // Copyright (C) 2009 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.google.gerrit.server.mail;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class AddressTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testParse_NameEmail1() {
final Address a = Address.parse("A U Thor <author@example.com>");
assertThat(a.name).isEqualTo("A U Thor");
assertThat(a.email).isEqualTo("author@example.com");
}
@Test
public void testParse_NameEmail2() {
final Address a = Address.parse("A <a@b>");
assertThat(a.name).isEqualTo("A");
assertThat(a.email).isEqualTo("a@b");
}
@Test
public void testParse_NameEmail3() {
final Address a = Address.parse("<a@b>");
assertThat(a.name).isNull();
assertThat(a.email).isEqualTo("a@b");
}
@Test
public void testParse_NameEmail4() {
final Address a = Address.parse("A U Thor<author@example.com>");
assertThat(a.name).isEqualTo("A U Thor");
assertThat(a.email).isEqualTo("author@example.com");
}
@Test
public void testParse_NameEmail5() {
final Address a = Address.parse("A U Thor <author@example.com>");
assertThat(a.name).isEqualTo("A U Thor");
assertThat(a.email).isEqualTo("author@example.com");
}
@Test
public void testParse_Email1() {
final Address a = Address.parse("author@example.com");
assertThat(a.name).isNull();
assertThat(a.email).isEqualTo("author@example.com");
}
@Test
public void testParse_Email2() {
final Address a = Address.parse("a@b");
assertThat(a.name).isNull();
assertThat(a.email).isEqualTo("a@b");
}
@Test
public void testParse_NewTLD() {
Address a = Address.parse("A U Thor <author@example.systems>");
assertThat(a.name).isEqualTo("A U Thor");
assertThat(a.email).isEqualTo("author@example.systems");
}
@Test
public void testParseInvalid() {
assertInvalid("");
assertInvalid("a");
assertInvalid("a<");
assertInvalid("<a");
assertInvalid("<a>");
assertInvalid("a<a>");
assertInvalid("a <a>");
assertInvalid("a");
assertInvalid("a<@");
assertInvalid("<a@");
assertInvalid("<a@>");
assertInvalid("a<a@>");
assertInvalid("a <a@>");
assertInvalid("a <@a>");
}
private void assertInvalid(final String in) {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Invalid email address: " + in);
Address.parse(in);
}
@Test
public void testToHeaderString_NameEmail1() {
assertThat(format("A", "a@a")).isEqualTo("A <a@a>");
}
@Test
public void testToHeaderString_NameEmail2() {
assertThat(format("A B", "a@a")).isEqualTo("A B <a@a>");
}
@Test
public void testToHeaderString_NameEmail3() {
assertThat(format("A B. C", "a@a")).isEqualTo("\"A B. C\" <a@a>");
}
@Test
public void testToHeaderString_NameEmail4() {
assertThat(format("A B, C", "a@a")).isEqualTo("\"A B, C\" <a@a>");
}
@Test
public void testToHeaderString_NameEmail5() {
assertThat(format("A \" C", "a@a")).isEqualTo("\"A \\\" C\" <a@a>");
}
@Test
public void testToHeaderString_NameEmail6() {
assertThat(format("A \u20ac B", "a@a"))
.isEqualTo("=?UTF-8?Q?A_=E2=82=AC_B?= <a@a>");
}
@Test
public void testToHeaderString_NameEmail7() {
assertThat(format("A \u20ac B (Code Review)", "a@a"))
.isEqualTo("=?UTF-8?Q?A_=E2=82=AC_B_=28Code_Review=29?= <a@a>");
}
@Test
public void testToHeaderString_Email1() {
assertThat(format(null, "a@a")).isEqualTo("a@a");
}
@Test
public void testToHeaderString_Email2() {
assertThat(format(null, "a,b@a")).isEqualTo("<a,b@a>");
}
private static String format(final String name, final String email) {
return new Address(name, email).toHeaderString();
}
}
| apache-2.0 |
aosp-mirror/platform_frameworks_support | samples/SupportDesignDemos/src/main/java/com/example/android/support/design/widget/CustomSnackbarUsage.java | 2696 | /*
* Copyright (C) 2016 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.example.android.support.design.widget;
import android.os.Bundle;
import android.support.design.widget.BaseTransientBottomBar;
import android.view.LayoutInflater;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.example.android.support.design.R;
/**
* This demonstrates custom usage of the snackbar
*/
public class CustomSnackbarUsage extends AppCompatActivity {
private CoordinatorLayout mContentView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_snackbar_with_fab);
mContentView = findViewById(R.id.content_view);
}
/** Shows a custom snackbar with no action. */
public void show(View view) {
final LayoutInflater inflater = LayoutInflater.from(mContentView.getContext());
final CustomSnackbarMainContent content =
(CustomSnackbarMainContent) inflater.inflate(
R.layout.custom_snackbar_include, mContentView, false);
final BaseTransientBottomBar.ContentViewCallback contentViewCallback =
new BaseTransientBottomBar.ContentViewCallback() {
@Override
public void animateContentIn(int delay, int duration) {
content.setAlpha(0f);
content.animate().alpha(1f).setDuration(duration)
.setStartDelay(delay).start();
}
@Override
public void animateContentOut(int delay, int duration) {
content.setAlpha(1f);
content.animate().alpha(0f).setDuration(duration)
.setStartDelay(delay).start();
}
};
new CustomSnackbar(mContentView, content, contentViewCallback).setTitle("Custom title")
.setSubtitle("Custom subtitle").show();
}
}
| apache-2.0 |
KRMAssociatesInc/eHMP | ehmp/product/production/hmp-main/src/test/java/gov/va/cpe/vpr/AllergyTests.java | 8425 | package gov.va.cpe.vpr;
import static org.junit.Assert.*;
import gov.va.cpe.vpr.termeng.TermLoadException;
import gov.va.cpe.vpr.termeng.jlv.JLVHddDao;
import gov.va.cpe.vpr.termeng.jlv.JLVHddDao.MappingType;
import gov.va.cpe.vpr.termeng.jlv.JLVDodAllergiesMap;
import gov.va.cpe.vpr.termeng.jlv.JLVMappedCode;
import gov.va.hmp.util.NullChecker;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class AllergyTests {
private static final String SYSTEM_DOD_CHCS_IEN = "DOD_ALLERGY_IEN";
private static final String DOD_DISPLAY_TEXT_GENERATED = "SomeText2";
private static final String DOD_CHCS_IEN_GENERATED = "4321";
private static final String UMLS_DISPLAY_TEXT_GENERATED = "SomeText";
private static final String UMLS_CUI_CODE_GENERATED = "C111";
Allergy testSubject = null;
JLVHddDao mockHDDDao = null;
@Before
public void setUp() throws Exception {
mockHDDDao = mock(JLVHddDao.class);
testSubject = new Allergy() {
private static final long serialVersionUID = -4226027408358664542L;
@Override
protected JLVHddDao getHDDDao() throws TermLoadException {
return mockHDDDao;
}
};
}
@Test
public void testSummary() {
Allergy a = new Allergy();
AllergyProduct product = new AllergyProduct();
product.setData("name","BBQ SAUCE");
a.addToProducts(product);
assertEquals("BBQ SAUCE", a.getSummary());
}
@Test
public void testKind() {
Allergy a = new Allergy();
assertEquals("Allergy/Adverse Reaction", a.getKind());
}
//-----------------------------------------------------------------------------------------------
// The following tests were created to test the getCodes method.
//-----------------------------------------------------------------------------------------------
/**
* This method creates the UMLS CUI Code.
*
* @return This returns the UNLS CUI code that was created.
*/
private JdsCode createUMLSCuiCode() {
JdsCode oCode = new JdsCode();
oCode.setSystem(JLVDodAllergiesMap.CODE_SYSTEM_UMLS_CUI);
oCode.setCode(UMLS_CUI_CODE_GENERATED);
oCode.setDisplay(UMLS_DISPLAY_TEXT_GENERATED);
return oCode;
}
/**
* This method creates the UMLS CUI Code.
*
* @return This returns the UNLS CUI code that was created.
*/
private JdsCode createChcsIenCode() {
JdsCode oCode = new JdsCode();
oCode.setSystem(SYSTEM_DOD_CHCS_IEN);
oCode.setCode(DOD_CHCS_IEN_GENERATED);
oCode.setDisplay(DOD_DISPLAY_TEXT_GENERATED);
return oCode;
}
/**
* This method creates the UMLS CUI Code.
*
* @return This returns the UNLS CUI code that was created.
*/
private JLVMappedCode createMappedUMLSCuiCode() {
JLVMappedCode oCode = new JLVMappedCode();
oCode.setCodeSystem(JLVDodAllergiesMap.CODE_SYSTEM_UMLS_CUI);
oCode.setCode(UMLS_CUI_CODE_GENERATED);
oCode.setDisplayText(UMLS_DISPLAY_TEXT_GENERATED);
return oCode;
}
/**
* This method verifies that the code array existed and was the correct size.
*
* @param oaCode The array to verified.
* @param iSize The size the array should be.
*/
private void verifyCodeArray(List<JdsCode> oaCode, int iSize) {
assertNotNull("The returned set should not have been null.", oaCode);
assertEquals("The codes array size was not correct.", iSize, oaCode.size());
}
/**
* Verifies that the UMLS CUI code is correct.
*
* @param oCode The UMLS CUI Code information.
*/
private void verifyUMLSCuiCode(JdsCode oCode) {
assertEquals("The code system was incorrect.", JLVDodAllergiesMap.CODE_SYSTEM_UMLS_CUI, oCode.getSystem());
assertEquals("The code was incorrect.", UMLS_CUI_CODE_GENERATED, oCode.getCode());
assertEquals("The display was incorrect.", UMLS_DISPLAY_TEXT_GENERATED, oCode.getDisplay());
}
/**
* Test case where the UMLS CUI code is already in the codes array.
*/
@Test
public void testGetCodesAlreadyContainsUMLSCuiCode () {
try {
List<JdsCode> oaCode = new ArrayList<JdsCode>();
JdsCode oCode = createUMLSCuiCode();
oaCode.add(oCode);
testSubject.setCodes(oaCode);
List<JdsCode> oaReturnedCodes = testSubject.getCodes();
verifyCodeArray(oaReturnedCodes, 1);
verifyUMLSCuiCode(oaReturnedCodes.get(0));
verify(mockHDDDao, times(0)).getMappedCode(any(MappingType.class), any(String.class));
}
catch (Exception e) {
String sErrorMessage = "An unexpected exception occurred. Error: " + e.getMessage();
System.out.println(sErrorMessage);
e.printStackTrace();
fail(sErrorMessage);
}
}
/**
* Test VA Allergy case where the UMLS CUI code is not in the codes array
*/
@Test
public void testVAAllergyGetCodesUMLSCuiNotInCodes () {
try {
when(mockHDDDao.getMappedCode(eq(MappingType.AllergyVUIDtoUMLSCui), any(String.class))).thenReturn(createMappedUMLSCuiCode());
AllergyProduct oProduct = new AllergyProduct();
oProduct.setData("vuid","urn:va:vuid:12345");
testSubject.addToProducts(oProduct);
List<JdsCode> oaReturnedCodes = testSubject.getCodes();
verifyCodeArray(oaReturnedCodes, 1);
verifyUMLSCuiCode(oaReturnedCodes.get(0));
verify(mockHDDDao, times(1)).getMappedCode(eq(MappingType.AllergyVUIDtoUMLSCui), any(String.class));
}
catch (Exception e) {
String sErrorMessage = "An unexpected exception occurred. Error: " + e.getMessage();
System.out.println(sErrorMessage);
e.printStackTrace();
fail(sErrorMessage);
}
}
/**
* Test DoD Allergy case where the UMLS CUI code is not in the codes array
*/
@Test
public void testDoDAllergyGetCodesUMLSCuiNotInCodes () {
try {
when(mockHDDDao.getMappedCode(eq(MappingType.AllergyCHCSIenToUMLSCui), any(String.class))).thenReturn(createMappedUMLSCuiCode());
List<JdsCode> oaCode = new ArrayList<JdsCode>();
JdsCode oCode = createChcsIenCode();
oaCode.add(oCode);
testSubject.setCodes(oaCode);
List<JdsCode> oaReturnedCodes = testSubject.getCodes();
verifyCodeArray(oaReturnedCodes, 2);
for (JdsCode oReturnedCode : oaReturnedCodes) {
if (oReturnedCode.getSystem().equals(JLVDodAllergiesMap.CODE_SYSTEM_UMLS_CUI)) {
verifyUMLSCuiCode(oReturnedCode);
}
}
verify(mockHDDDao, times(1)).getMappedCode(eq(MappingType.AllergyCHCSIenToUMLSCui), any(String.class));
}
catch (Exception e) {
String sErrorMessage = "An unexpected exception occurred. Error: " + e.getMessage();
System.out.println(sErrorMessage);
e.printStackTrace();
fail(sErrorMessage);
}
}
/**
* Test Where it is not DoD or VA allergy. (This should insert nothing at this point.)
*/
@Test
public void testNotDoDOrVAAllergy () {
try {
when(mockHDDDao.getMappedCode(any(MappingType.class), any(String.class))).thenReturn(createMappedUMLSCuiCode());
List<JdsCode> oaReturnedCodes = testSubject.getCodes();
assertTrue("The returned result should have been nullish.", NullChecker.isNullish(oaReturnedCodes));
verify(mockHDDDao, times(0)).getMappedCode(any(MappingType.class), any(String.class));
}
catch (Exception e) {
String sErrorMessage = "An unexpected exception occurred. Error: " + e.getMessage();
System.out.println(sErrorMessage);
e.printStackTrace();
fail(sErrorMessage);
}
}
/**
* Test VA Allergy case where there was no mapping returnd by HDDDao.
*/
@Test
public void testVAAllergyNoMappingFound () {
try {
when(mockHDDDao.getMappedCode(eq(MappingType.AllergyVUIDtoUMLSCui), any(String.class))).thenReturn(null);
AllergyProduct oProduct = new AllergyProduct();
oProduct.setData("vuid","12345");
testSubject.addToProducts(oProduct);
List<JdsCode> oaReturnedCodes = testSubject.getCodes();
assertTrue("The returned value should have been nullish.", NullChecker.isNullish(oaReturnedCodes));
verify(mockHDDDao, times(1)).getMappedCode(eq(MappingType.AllergyVUIDtoUMLSCui), any(String.class));
}
catch (Exception e) {
String sErrorMessage = "An unexpected exception occurred. Error: " + e.getMessage();
System.out.println(sErrorMessage);
e.printStackTrace();
fail(sErrorMessage);
}
}
}
| apache-2.0 |
krestenkrab/hotruby | modules/vm-shared/src/com/trifork/hotruby/compiler/CompiledMethod2.java | 674 | package com.trifork.hotruby.compiler;
import com.trifork.hotruby.objects.IRubyObject;
import com.trifork.hotruby.runtime.RubyBlock;
public abstract class CompiledMethod2 extends CompiledMethod {
@Override
public IRubyObject call(IRubyObject receiver, RubyBlock block) {
throw wrongArgs(receiver, 0);
}
@Override
public IRubyObject call(IRubyObject receiver, IRubyObject arg,
RubyBlock block) {
throw wrongArgs(receiver, 1);
}
@Override
public IRubyObject call(IRubyObject receiver, IRubyObject[] args,
RubyBlock block) {
if (args.length == 2) {
return call(receiver, args[0], args[1], block);
}
throw wrongArgs(receiver, args.length);
}
}
| apache-2.0 |
lewismc/oodt | pushpull/src/main/java/org/apache/oodt/cas/pushpull/expressions/Method.java | 11221 | /*
* 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.oodt.cas.pushpull.expressions;
import org.apache.oodt.cas.pushpull.exceptions.MethodException;
import java.util.LinkedList;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author bfoster
* @version $Revision$
*
* <p>
* Describe your class here
* </p>.
*/
public class Method {
private static Logger LOG = Logger.getLogger(Method.class.getName());
private String name;
private String infix;
private LinkedList<Variable> args;
private LinkedList<String> argNames;
private LinkedList<Integer> argTypes;
public final int INT = 0;
public final int STRING = 1;
public Method(String name) {
this.name = name;
args = new LinkedList<Variable>();
argNames = new LinkedList<String>();
argTypes = new LinkedList<Integer>();
}
public void addArgSignature(String name, int type) {
argNames.add(name);
argTypes.add(type);
}
public boolean addArg(String name, String value) {
int nextLoc = args.size();
if (nextLoc >= 0) {
switch (argTypes.get(nextLoc)) {
case INT:
addArg(new Variable(null, Integer.valueOf(value)));
break;
case STRING:
addArg(new Variable(null, value));
break;
default:
return false;
}
return true;
} else {
return false;
}
}
public void addArg(Variable v) {
args.addLast(v);
}
public void setBehavoir(String infix) {
this.infix = infix;
}
private LinkedList<ValidInput> convert(String infix) throws MethodException {
try {
LinkedList<ValidInput> output = new LinkedList<ValidInput>();
Stack<ValidInput> stack = new Stack<ValidInput>();
char[] infixArray = infix.toCharArray();
for (int i = 0; i < infixArray.length; i++) {
char c = infixArray[i];
// System.out.println("Next C = " + c);
switch (c) {
case '$':
StringBuilder variable = new StringBuilder("");
boolean globalVar = false;
// skip $ by incr i and if true then variable is a global
// variable and skip '{' by incr i again
if (infixArray[++i] == '{') {
globalVar = true;
i++;
}
for (; i < infixArray.length; i++) {
char ch = infixArray[i];
// System.out.println("ch = " + ch);
if ((ch <= 'Z' && ch >= 'A')
|| (ch <= 'z' && ch >= 'a')
|| (ch <= '9' && ch >= '0') || ch == '_') {
variable.append(ch);
} else {
break;
}
}
if (globalVar) {
try {
output.addLast(GlobalVariables.ConcurrentHashMap.get(variable
.toString()));
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage());
}
} else {
i--;
output.addLast(args.get(argNames.indexOf(variable
.toString())));
}
break;
case '#':
StringBuilder variableIntString = new StringBuilder("");
int k = i + 1;
for (; k < infixArray.length; k++) {
char ch = infixArray[k];
if (ch <= '9' && ch >= '0') {
variableIntString.append(ch);
} else {
break;
}
}
output.addLast(new Variable(null, Integer.valueOf(
variableIntString.toString())));
i = k - 1;
break;
case '"':
StringBuilder variableString = new StringBuilder("");
int l = i + 1;
for (; l < infixArray.length; l++) {
char ch = infixArray[l];
if (ch == '"') {
break;
} else {
variableString.append(ch);
}
}
output
.addLast(new Variable(null, variableString
.toString()));
i = l;
break;
case '+':
case '-':
case '/':
case '*':
while (!stack.empty()
&& hasHigherPrecedence(stack.peek().toString()
.charAt(0), c)) {
output.addLast(stack.pop());
}
stack.push(new Operator(c + ""));
break;
case ')':
while (!stack.empty()) {
ValidInput vi = stack.pop();
if (vi.toString().charAt(0) == '(') {
break;
}
output.addLast(vi);
}
break;
case '(':
stack.push(new Punctuation(c + ""));
break;
}
}
while (!stack.empty()) {
output.addLast(stack.pop());
}
return output;
} catch (Exception e) {
throw new MethodException("Failed to convert infix to postfix : "
+ e.getMessage());
}
}
public Object execute() throws MethodException {
try {
Stack<ValidInput> stack = new Stack<ValidInput>();
LinkedList<ValidInput> postfix = convert(infix);
for (ValidInput vi : postfix) {
if (vi instanceof Variable) {
stack.push(vi);
} else if (vi instanceof Operator) {
ValidInput first = stack.pop();
ValidInput second = stack.pop();
switch (vi.toString().charAt(0)) {
case '+':
if (((Variable) first).isString()
|| ((Variable) second).isString()) {
String value = second.toString() + first.toString();
stack.push(new Variable(null, value));
} else if (((Variable) first).isInteger()
&& ((Variable) second).isInteger()) {
Integer value = (Integer) second
.getValue()
+ (Integer) first.getValue();
stack.push(new Variable(null, value));
} else {
throw new MethodException(
"Invalid Concatination/Addition types. . .must be String or Integer");
}
break;
case '-':
if (((Variable) first).isInteger()
&& ((Variable) second).isInteger()) {
Integer value = (Integer) second
.getValue()
- (Integer) first.getValue();
stack.push(new Variable(null, value));
} else {
throw new MethodException(
"Invalid Subtraction types. . .must be Integer");
}
break;
case '*':
if (((Variable) first).isInteger()
&& ((Variable) second).isInteger()) {
Integer value = (Integer) second
.getValue()
* (Integer) first.getValue();
stack.push(new Variable(null, value));
} else {
throw new MethodException(
"Invalid Multiplication types. . .must be Integer");
}
break;
case '/':
if (((Variable) first).isInteger()
&& ((Variable) second).isInteger()
&& (Integer) first.getValue() > 0) {
Integer value = (Integer) second
.getValue()
/ (Integer) first.getValue();
stack.push(new Variable(null, value));
} else {
throw new MethodException(
"Invalid Division types. . .must be Integer and denominator must be greater than 0");
}
break;
}
}
}
return stack.pop().getValue();
} catch (Exception e) {
throw new MethodException("Failed to execute method " + name
+ " : " + e.getMessage());
}
}
// does first have higher precedence than second
private boolean hasHigherPrecedence(char first, char second) {
switch (first) {
case '+':
case '-':
switch (second) {
case '+':
case '-':
return true;
}
return false;
case '*':
case '/':
return true;
}
return false;
}
public String getName() {
return name;
}
}
| apache-2.0 |
nivanov/ignite | modules/indexing/src/test/java/org/apache/ignite/internal/processors/cache/CacheIndexStreamerTest.java | 5451 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.spi.swapspace.inmemory.GridTestSwapSpaceSpi;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMemoryMode.OFFHEAP_TIERED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
/**
*
*/
public class CacheIndexStreamerTest extends GridCommonAbstractTest {
/** */
private final TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(ipFinder);
cfg.setSwapSpaceSpi(new GridTestSwapSpaceSpi());
return cfg;
}
/**
* @throws Exception If failed.
*/
public void testStreamerAtomic() throws Exception {
checkStreamer(ATOMIC);
}
/**
* @throws Exception If failed.
*/
public void testStreamerTx() throws Exception {
checkStreamer(TRANSACTIONAL);
}
/**
* @param atomicityMode Cache atomicity mode.
* @throws Exception If failed.
*/
public void checkStreamer(CacheAtomicityMode atomicityMode) throws Exception {
final Ignite ignite = startGrid(0);
final IgniteCache<Integer, String> cache = ignite.createCache(cacheConfiguration(atomicityMode));
final AtomicBoolean stop = new AtomicBoolean();
final int KEYS = 10_000;
try {
IgniteInternalFuture streamerFut = GridTestUtils.runAsync(new Callable() {
@Override public Void call() throws Exception {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
while (!stop.get()) {
try (IgniteDataStreamer<Integer, String> streamer = ignite.dataStreamer(null)) {
for (int i = 0; i < 1; i++)
streamer.addData(rnd.nextInt(KEYS), String.valueOf(i));
}
}
return null;
}
}, "streamer-thread");
IgniteInternalFuture updateFut = GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {
@Override public Void call() throws Exception {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
while (!stop.get()) {
for (int i = 0; i < 100; i++) {
Integer key = rnd.nextInt(KEYS);
cache.put(key, String.valueOf(key));
cache.remove(key);
}
}
return null;
}
}, 1, "update-thread");
U.sleep(30_000);
stop.set(true);
streamerFut.get();
updateFut.get();
}
finally {
stop.set(true);
stopAllGrids();
}
}
/**
* @param atomicityMode Cache atomicity mode.
* @return Cache configuration.
*/
private CacheConfiguration cacheConfiguration(CacheAtomicityMode atomicityMode) {
CacheConfiguration ccfg = new CacheConfiguration();
ccfg.setAtomicityMode(atomicityMode);
ccfg.setWriteSynchronizationMode(FULL_SYNC);
ccfg.setMemoryMode(OFFHEAP_TIERED);
ccfg.setOffHeapMaxMemory(0);
ccfg.setBackups(1);
ccfg.setIndexedTypes(Integer.class, String.class);
return ccfg;
}
}
| apache-2.0 |
toddharrison/BriarCraft | src/main/java/com/goodformentertainment/canary/playerstate/PlayerStateConfiguration.java | 2509 | package com.goodformentertainment.canary.playerstate;
import java.util.ArrayList;
import java.util.List;
import com.goodformentertainment.canary.playerstate.api.IWorldStateManager;
import com.goodformentertainment.canary.playerstate.api.SaveState;
import net.canarymod.api.world.World;
import net.canarymod.config.Configuration;
import net.canarymod.plugin.Plugin;
import net.visualillusionsent.utils.PropertiesFile;
public class PlayerStateConfiguration {
private final PropertiesFile cfg;
public PlayerStateConfiguration(final Plugin plugin) {
cfg = Configuration.getPluginConfig(plugin, "PlayerState");
}
public boolean exactSpawn() {
return cfg.getBoolean("exactSpawn");
}
public String getDefaultState() {
return cfg.getString("state.global", IWorldStateManager.ALL_WORLDS);
}
public String getState(final World world) {
final String state;
final String key = "state.world." + world.getName();
if (cfg.containsKey(key)) {
state = cfg.getString(key);
} else {
state = getDefaultState();
}
return state;
}
public SaveState[] getSaves(final String state) {
final List<SaveState> saves = new ArrayList<SaveState>();
if (cfg.getBoolean("save." + state + "." + SaveState.ACHIEVEMENTS, false)) {
saves.add(SaveState.ACHIEVEMENTS);
}
if (cfg.getBoolean("save." + state + "." + SaveState.CONDITIONS, true)) {
saves.add(SaveState.CONDITIONS);
}
if (cfg.getBoolean("save." + state + "." + SaveState.GAMEMODE, true)) {
saves.add(SaveState.GAMEMODE);
}
if (cfg.getBoolean("save." + state + "." + SaveState.INVENTORY, true)) {
saves.add(SaveState.INVENTORY);
}
if (cfg.getBoolean("save." + state + "." + SaveState.LOCATIONS, true)) {
saves.add(SaveState.LOCATIONS);
}
if (cfg.getBoolean("save." + state + "." + SaveState.PREFIX, false)) {
saves.add(SaveState.PREFIX);
}
if (cfg.getBoolean("save." + state + "." + SaveState.STATISTICS, false)) {
saves.add(SaveState.STATISTICS);
}
return saves.toArray(new SaveState[saves.size()]);
}
public String getLoggingLevel() {
String level = null;
final String key = "log.level";
if (cfg.containsKey(key)) {
level = cfg.getString(key);
}
return level;
}
}
| apache-2.0 |
PlanetWaves/clockworkengine | trunk/jme3-core/src/main/java/com/jme3/animation/AnimControl.java | 13360 | /*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.animation;
import com.jme3.export.*;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Mesh;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.Control;
import com.jme3.util.clone.Cloner;
import com.jme3.util.clone.JmeCloneable;
import com.jme3.util.TempVars;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* <code>AnimControl</code> is a Spatial control that allows manipulation
* of skeletal animation.
*
* The control currently supports:
* 1) Animation blending/transitions
* 2) Multiple animation channels
* 3) Multiple skins
* 4) Animation event listeners
* 5) Animated model cloning
* 6) Animated model binary import/export
* 7) Hardware skinning
* 8) Attachments
* 9) Add/remove skins
*
* Planned:
* 1) Morph/Pose animation
*
* @author Kirill Vainer
*/
public final class AnimControl extends AbstractControl implements Cloneable, JmeCloneable {
/**
* Skeleton object must contain corresponding data for the targets' weight buffers.
*/
Skeleton skeleton;
/** only used for backward compatibility */
@Deprecated
private SkeletonControl skeletonControl;
/**
* List of animations
*/
HashMap<String, Animation> animationMap = new HashMap<String, Animation>();
/**
* Animation channels
*/
private transient ArrayList<AnimChannel> channels = new ArrayList<AnimChannel>();
/**
* Animation event listeners
*/
private transient ArrayList<AnimEventListener> listeners = new ArrayList<AnimEventListener>();
/**
* Creates a new animation control for the given skeleton.
* The method {@link AnimControl#setAnimations(java.util.HashMap) }
* must be called after initialization in order for this class to be useful.
*
* @param skeleton The skeleton to animate
*/
public AnimControl(Skeleton skeleton) {
this.skeleton = skeleton;
reset();
}
/**
* Serialization only. Do not use.
*/
public AnimControl() {
}
/**
* Internal use only.
*/
@Override
public Control cloneForSpatial(Spatial spatial) {
try {
AnimControl clone = (AnimControl) super.clone();
clone.spatial = spatial;
clone.channels = new ArrayList<AnimChannel>();
clone.listeners = new ArrayList<AnimEventListener>();
if (skeleton != null) {
clone.skeleton = new Skeleton(skeleton);
}
// animationMap is cloned, but only ClonableTracks will be cloned as they need a reference to a cloned spatial
for (Entry<String, Animation> animEntry : animationMap.entrySet()) {
clone.animationMap.put(animEntry.getKey(), animEntry.getValue().cloneForSpatial(spatial));
}
return clone;
} catch (CloneNotSupportedException ex) {
throw new AssertionError();
}
}
@Override
public Object jmeClone() {
AnimControl clone = (AnimControl) super.jmeClone();
clone.channels = new ArrayList<AnimChannel>();
clone.listeners = new ArrayList<AnimEventListener>();
return clone;
}
@Override
public void cloneFields( Cloner cloner, Object original ) {
super.cloneFields(cloner, original);
this.skeleton = cloner.clone(skeleton);
// Note cloneForSpatial() never actually cloned the animation map... just its reference
HashMap<String, Animation> newMap = new HashMap<>();
// animationMap is cloned, but only ClonableTracks will be cloned as they need a reference to a cloned spatial
for( Map.Entry<String, Animation> e : animationMap.entrySet() ) {
newMap.put(e.getKey(), cloner.clone(e.getValue()));
}
this.animationMap = newMap;
}
/**
* @param animations Set the animations that this <code>AnimControl</code>
* will be capable of playing. The animations should be compatible
* with the skeleton given in the constructor.
*/
public void setAnimations(HashMap<String, Animation> animations) {
animationMap = animations;
}
/**
* Retrieve an animation from the list of animations.
* @param name The name of the animation to retrieve.
* @return The animation corresponding to the given name, or null, if no
* such named animation exists.
*/
public Animation getAnim(String name) {
return animationMap.get(name);
}
/**
* Adds an animation to be available for playing to this
* <code>AnimControl</code>.
* @param anim The animation to add.
*/
public void addAnim(Animation anim) {
animationMap.put(anim.getName(), anim);
}
/**
* Remove an animation so that it is no longer available for playing.
* @param anim The animation to remove.
*/
public void removeAnim(Animation anim) {
if (!animationMap.containsKey(anim.getName())) {
throw new IllegalArgumentException("Given animation does not exist "
+ "in this AnimControl");
}
animationMap.remove(anim.getName());
}
/**
* Create a new animation channel, by default assigned to all bones
* in the skeleton.
*
* @return A new animation channel for this <code>AnimControl</code>.
*/
public AnimChannel createChannel() {
AnimChannel channel = new AnimChannel(this);
channels.add(channel);
return channel;
}
/**
* Return the animation channel at the given index.
* @param index The index, starting at 0, to retrieve the <code>AnimChannel</code>.
* @return The animation channel at the given index, or throws an exception
* if the index is out of bounds.
*
* @throws IndexOutOfBoundsException If no channel exists at the given index.
*/
public AnimChannel getChannel(int index) {
return channels.get(index);
}
/**
* @return The number of channels that are controlled by this
* <code>AnimControl</code>.
*
* @see AnimControl#createChannel()
*/
public int getNumChannels() {
return channels.size();
}
/**
* Clears all the channels that were created.
*
* @see AnimControl#createChannel()
*/
public void clearChannels() {
for (AnimChannel animChannel : channels) {
for (AnimEventListener list : listeners) {
list.onAnimCycleDone(this, animChannel, animChannel.getAnimationName());
}
}
channels.clear();
}
/**
* @return The skeleton of this <code>AnimControl</code>.
*/
public Skeleton getSkeleton() {
return skeleton;
}
/**
* Adds a new listener to receive animation related events.
* @param listener The listener to add.
*/
public void addListener(AnimEventListener listener) {
if (listeners.contains(listener)) {
throw new IllegalArgumentException("The given listener is already "
+ "registed at this AnimControl");
}
listeners.add(listener);
}
/**
* Removes the given listener from listening to events.
* @param listener
* @see AnimControl#addListener(com.jme3.animation.AnimEventListener)
*/
public void removeListener(AnimEventListener listener) {
if (!listeners.remove(listener)) {
throw new IllegalArgumentException("The given listener is not "
+ "registed at this AnimControl");
}
}
/**
* Clears all the listeners added to this <code>AnimControl</code>
*
* @see AnimControl#addListener(com.jme3.animation.AnimEventListener)
*/
public void clearListeners() {
listeners.clear();
}
void notifyAnimChange(AnimChannel channel, String name) {
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onAnimChange(this, channel, name);
}
}
void notifyAnimCycleDone(AnimChannel channel, String name) {
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).onAnimCycleDone(this, channel, name);
}
}
/**
* Internal use only.
*/
@Override
public void setSpatial(Spatial spatial) {
if (spatial == null && skeletonControl != null) {
this.spatial.removeControl(skeletonControl);
}
super.setSpatial(spatial);
//Backward compatibility.
if (spatial != null && skeletonControl != null) {
spatial.addControl(skeletonControl);
}
}
final void reset() {
if (skeleton != null) {
skeleton.resetAndUpdate();
}
}
/**
* @return The names of all animations that this <code>AnimControl</code>
* can play.
*/
public Collection<String> getAnimationNames() {
return animationMap.keySet();
}
/**
* Returns the length of the given named animation.
* @param name The name of the animation
* @return The length of time, in seconds, of the named animation.
*/
public float getAnimationLength(String name) {
Animation a = animationMap.get(name);
if (a == null) {
throw new IllegalArgumentException("The animation " + name
+ " does not exist in this AnimControl");
}
return a.getLength();
}
/**
* Internal use only.
*/
@Override
protected void controlUpdate(float tpf) {
if (skeleton != null) {
skeleton.reset(); // reset skeleton to bind pose
}
TempVars vars = TempVars.get();
for (int i = 0; i < channels.size(); i++) {
channels.get(i).update(tpf, vars);
}
vars.release();
if (skeleton != null) {
skeleton.updateWorldVectors();
}
}
/**
* Internal use only.
*/
@Override
protected void controlRender(RenderManager rm, ViewPort vp) {
}
@Override
public void write(JmeExporter ex) throws IOException {
super.write(ex);
OutputCapsule oc = ex.getCapsule(this);
oc.write(skeleton, "skeleton", null);
oc.writeStringSavableMap(animationMap, "animations", null);
}
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
InputCapsule in = im.getCapsule(this);
skeleton = (Skeleton) in.readSavable("skeleton", null);
HashMap<String, Animation> loadedAnimationMap = (HashMap<String, Animation>) in.readStringSavableMap("animations", null);
if (loadedAnimationMap != null) {
animationMap = loadedAnimationMap;
}
if (im.getFormatVersion() == 0) {
// Changed for backward compatibility with j3o files generated
// before the AnimControl/SkeletonControl split.
// If we find a target mesh array the AnimControl creates the
// SkeletonControl for old files and add it to the spatial.
// When backward compatibility won't be needed anymore this can deleted
Savable[] sav = in.readSavableArray("targets", null);
if (sav != null) {
// NOTE: allow the targets to be gathered automatically
skeletonControl = new SkeletonControl(skeleton);
spatial.addControl(skeletonControl);
}
}
}
}
| apache-2.0 |
RestExpress/HyperExpress | core/src/main/java/com/strategicgains/hyperexpress/AbstractResourceFactoryStrategy.java | 5842 | /*
Copyright 2014, Strategic Gains, 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.strategicgains.hyperexpress;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import com.strategicgains.hyperexpress.domain.Resource;
import com.strategicgains.hyperexpress.exception.ResourceException;
/**
* @author toddf
* @since Apr 11, 2014
*/
public abstract class AbstractResourceFactoryStrategy
implements ResourceFactoryStrategy
{
public static final int IGNORED_FIELD_MODIFIERS = Modifier.FINAL | Modifier.STATIC | Modifier.TRANSIENT | Modifier.VOLATILE;
private Set<Class<? extends Annotation>> inclusionAnnotations;
private Set<Class<? extends Annotation>> exclusionAnnotations;
/**
* Instead of requiring its own property/field annotations, this strategy supports the
* ability to denote which fields you want to include in your resources by utilizing
* *ANY* annotations.
* <p/>
* By default, this ResourceFactoryStrategy includes all properties, public and private,
* except static, final, volatile and transient fields.
*
* @param annotations the Field annotations that indicate which properties to copy to resources.
* @return a reference to the ResourceFactoryStrategy to facilitate method chaining.
*/
@SafeVarargs
public final AbstractResourceFactoryStrategy includeAnnotations(Class<? extends Annotation>... annotations)
{
if (annotations == null) return this;
if (inclusionAnnotations == null)
{
inclusionAnnotations = new HashSet<>();
}
inclusionAnnotations.addAll(Arrays.asList(annotations));
return this;
}
/**
* By default, AbstractResourceFactoryStrategy includes all properties from an object and copies
* them to the newly-created Resource. It does exclude, final, static, transient and volatile fields.
* <p/>
* To leverage annotations on fields to exclude from inclusion, this method allows callers to
* indicate which fields to not include in newly-created Resource instances.
*
* @param annotations the Field annotations that indicate which properties not copied to resources.
* @return a reference to the ResourceFactoryStrategy to facilitate method chaining.
*/
@SafeVarargs
public final AbstractResourceFactoryStrategy excludeAnnotations(Class<? extends Annotation>... annotations)
{
if (annotations == null) return this;
if (exclusionAnnotations == null)
{
exclusionAnnotations = new HashSet<>();
}
exclusionAnnotations.addAll(Arrays.asList(annotations));
return this;
}
/**
* Entry-point into the deep-copy functionality.
*
* @param from an Object instance, never null.
* @param to a presumably-empty Resource instance.
*/
protected void copyProperties(Object from, Resource to)
{
copyProperties0(from.getClass(), from, to);
}
/**
* Recursively-copies properties from the Object, up the inheritance hierarchy, to
* the destination Resource.
*
* @param type the Type of the object being copied. May be a super-type of the 'from' object.
* @param from the instance of Object being copied.
* @param to the destination Resource instance.
*/
private void copyProperties0(Class<?> type, Object from, Resource to)
{
if (type == null) return;
if (Resource.class.isAssignableFrom(type))
{
to.from((Resource) from);
return;
}
Field[] fields = getDeclaredFields(type);
try
{
for (Field f : fields)
{
if (isIncluded(f))
{
f.setAccessible(true);
Object value = f.get(from);
if (value != null)
{
addProperty(to, f, value);
}
}
}
}
catch (IllegalAccessException e)
{
throw new ResourceException(e);
}
copyProperties0(type.getSuperclass(), from, to);
}
/**
* Template method. Sub-classes can override to possibly handle annotations
* on the field, etc. By default, this method simply adds the property to
* the resource using the value and the given name of the field.
*
* @param to the destination resource.
* @param f the field to copy.
* @param value the value of the field.
*/
protected void addProperty(Resource to, Field f, Object value)
{
to.addProperty(f.getName(), value);
}
/**
* Answers whether the Field should be copied. By default it ignores (answers 'false' to)
* static, final, volatile and transient fields.
*
* @param f a Field of a Class.
* @return true if the field should be copied into the resource. Otherwise, false.
*/
private boolean isIncluded(Field f)
{
if ((inclusionAnnotations == null && exclusionAnnotations == null)
|| f.getAnnotations().length == 0)
{
return ((f.getModifiers() & IGNORED_FIELD_MODIFIERS) == 0);
}
for (Annotation annotation : f.getAnnotations())
{
Class<? extends Annotation> type = annotation.annotationType();
if (inclusionAnnotations != null && inclusionAnnotations.contains(type))
{
return true;
}
if (exclusionAnnotations != null && exclusionAnnotations.contains(type))
{
return false;
}
}
return ((f.getModifiers() & IGNORED_FIELD_MODIFIERS) == 0);
}
private Field[] getDeclaredFields(Class<?> type)
{
return type.getDeclaredFields();
}
}
| apache-2.0 |
GoogleCloudPlatform/native-image-support-java | native-image-samples/native-image-samples-spring/spring-cloud-gcp-trace-sample/src/main/java/com/example/ExampleController.java | 1930 | /*
* Copyright 2020-2021 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.
*/
package com.example;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Sample REST Controller to demonstrate Spring Cloud Sleuth and Stackdriver Trace.
*
* @author Ray Tsang
* @author Mike Eltsufin
*/
@RestController
public class ExampleController {
private static final Log LOGGER = LogFactory.getLog(ExampleController.class);
private final WorkService workService;
public ExampleController(WorkService workService) {
this.workService = workService;
}
/**
* Root endpoint for the application.
*/
@RequestMapping("/")
public String work(HttpServletRequest request) {
String meetUrl = request.getRequestURL().toString() + "/meet";
this.workService.visitMeetEndpoint(meetUrl);
return "finished";
}
/**
* Secondary endpoint which will receive requests triggered by visiting home.
*/
@RequestMapping("/meet")
public String meet() throws InterruptedException {
long duration = 200L + (long) (Math.random() * 500L);
Thread.sleep(duration);
LOGGER.info("meeting took " + duration + "ms");
return "meeting finished in " + duration + "ms";
}
}
| apache-2.0 |
googleapis/java-analytics-admin | proto-google-analytics-admin-v1alpha/src/main/java/com/google/analytics/admin/v1alpha/ListIosAppDataStreamsRequest.java | 31418 | /*
* 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/analytics/admin/v1alpha/analytics_admin.proto
package com.google.analytics.admin.v1alpha;
/**
*
*
* <pre>
* Request message for ListIosAppDataStreams RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest}
*/
public final class ListIosAppDataStreamsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest)
ListIosAppDataStreamsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListIosAppDataStreamsRequest.newBuilder() to construct.
private ListIosAppDataStreamsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListIosAppDataStreamsRequest() {
parent_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListIosAppDataStreamsRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ListIosAppDataStreamsRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
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();
parent_ = s;
break;
}
case 16:
{
pageSize_ = input.readInt32();
break;
}
case 26:
{
java.lang.String s = input.readStringRequireUtf8();
pageToken_ = s;
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 {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_ListIosAppDataStreamsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_ListIosAppDataStreamsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest.class,
com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
private volatile java.lang.Object parent_;
/**
*
*
* <pre>
* Required. The name of the parent property.
* For example, to list results of app streams under the property with Id
* 123: "properties/123"
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
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();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the parent property.
* For example, to list results of app streams under the property with Id
* 123: "properties/123"
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of resources to return.
* If unspecified, at most 50 resources will be returned.
* The maximum value is 200; (higher values will be coerced to the maximum)
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
private volatile java.lang.Object pageToken_;
/**
*
*
* <pre>
* A page token, received from a previous `ListIosAppDataStreams`
* call. Provide this to retrieve the subsequent page.
* When paginating, all other parameters provided to `ListIosAppDataStreams`
* must match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
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();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A page token, received from a previous `ListIosAppDataStreams`
* call. Provide this to retrieve the subsequent page.
* When paginating, all other parameters provided to `ListIosAppDataStreams`
* must match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
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(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
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(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
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.analytics.admin.v1alpha.ListIosAppDataStreamsRequest)) {
return super.equals(obj);
}
com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest other =
(com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) 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) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest 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.analytics.admin.v1alpha.ListIosAppDataStreamsRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest 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.analytics.admin.v1alpha.ListIosAppDataStreamsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest 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.analytics.admin.v1alpha.ListIosAppDataStreamsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest 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.analytics.admin.v1alpha.ListIosAppDataStreamsRequest 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>
* Request message for ListIosAppDataStreams RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest)
com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_ListIosAppDataStreamsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_ListIosAppDataStreamsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest.class,
com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest.Builder.class);
}
// Construct using com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_ListIosAppDataStreamsRequest_descriptor;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest
getDefaultInstanceForType() {
return com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest build() {
com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest buildPartial() {
com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest result =
new com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest(this);
result.parent_ = parent_;
result.pageSize_ = pageSize_;
result.pageToken_ = pageToken_;
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.analytics.admin.v1alpha.ListIosAppDataStreamsRequest) {
return mergeFrom((com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest other) {
if (other
== com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
onChanged();
}
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.analytics.admin.v1alpha.ListIosAppDataStreamsRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The name of the parent property.
* For example, to list results of app streams under the property with Id
* 123: "properties/123"
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the parent property.
* For example, to list results of app streams under the property with Id
* 123: "properties/123"
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the parent property.
* For example, to list results of app streams under the property with Id
* 123: "properties/123"
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the parent property.
* For example, to list results of app streams under the property with Id
* 123: "properties/123"
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the parent property.
* For example, to list results of app streams under the property with Id
* 123: "properties/123"
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of resources to return.
* If unspecified, at most 50 resources will be returned.
* The maximum value is 200; (higher values will be coerced to the maximum)
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of resources to return.
* If unspecified, at most 50 resources will be returned.
* The maximum value is 200; (higher values will be coerced to the maximum)
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of resources to return.
* If unspecified, at most 50 resources will be returned.
* The maximum value is 200; (higher values will be coerced to the maximum)
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A page token, received from a previous `ListIosAppDataStreams`
* call. Provide this to retrieve the subsequent page.
* When paginating, all other parameters provided to `ListIosAppDataStreams`
* must match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A page token, received from a previous `ListIosAppDataStreams`
* call. Provide this to retrieve the subsequent page.
* When paginating, all other parameters provided to `ListIosAppDataStreams`
* must match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A page token, received from a previous `ListIosAppDataStreams`
* call. Provide this to retrieve the subsequent page.
* When paginating, all other parameters provided to `ListIosAppDataStreams`
* must match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* A page token, received from a previous `ListIosAppDataStreams`
* call. Provide this to retrieve the subsequent page.
* When paginating, all other parameters provided to `ListIosAppDataStreams`
* must match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
onChanged();
return this;
}
/**
*
*
* <pre>
* A page token, received from a previous `ListIosAppDataStreams`
* call. Provide this to retrieve the subsequent page.
* When paginating, all other parameters provided to `ListIosAppDataStreams`
* must match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
onChanged();
return this;
}
@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.analytics.admin.v1alpha.ListIosAppDataStreamsRequest)
}
// @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest)
private static final com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest();
}
public static com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListIosAppDataStreamsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListIosAppDataStreamsRequest>() {
@java.lang.Override
public ListIosAppDataStreamsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ListIosAppDataStreamsRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ListIosAppDataStreamsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListIosAppDataStreamsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.ListIosAppDataStreamsRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
hernad/oo-netbeans | src/org/openoffice/extensions/projecttemplates/addon/AddOnActions.java | 14695 | /**************************************************************
*
* 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.openoffice.extensions.projecttemplates.addon;
import java.beans.PropertyVetoException;
import java.util.Iterator;
import java.util.Vector;
import org.openide.explorer.ExplorerManager;
import org.openide.nodes.Node;
import org.openoffice.extensions.projecttemplates.addon.datamodel.AddOn;
import org.openoffice.extensions.projecttemplates.addon.datamodel.Command;
import org.openoffice.extensions.projecttemplates.addon.datamodel.SeparatorElement;
import org.openoffice.extensions.projecttemplates.addon.datamodel.SubMenuElement;
import org.openoffice.extensions.projecttemplates.addon.datamodel.node.AddOnChildren;
import org.openoffice.extensions.projecttemplates.addon.datamodel.node.AddOnNode;
import org.openoffice.extensions.projecttemplates.calcaddin.LanguageHandlingDialog;
import org.openoffice.extensions.util.LogWriter;
import org.openoffice.extensions.util.datamodel.NbNodeObject;
import org.openoffice.extensions.util.datamodel.actions.BaseAction;
import org.openoffice.extensions.util.datamodel.actions.LanguageAction;
import org.openoffice.extensions.util.datamodel.properties.LocalizedOpenOfficeOrgProperty;
/**
*
* @author sg128468
*/
public class AddOnActions implements BaseAction, LanguageAction {
private ExplorerManager manager;
private ActionPanel panel;
private Vector<Command> deletedCommands;
/** Creates a new instance of AddOnActions */
public AddOnActions(ExplorerManager manager,
ActionPanel panel) {
this.manager = manager;
this.panel = panel;
this.deletedCommands = new Vector<Command>();
}
public Vector<Command> getDeletedCommands() {
return deletedCommands;
}
public void addCommandAction() {
NbNodeObject selectedObject = getSelectedObject();
Node node = manager.getRootContext();
if (node != null) {
// get the data object
NbNodeObject nodeObject = (NbNodeObject)
node.getLookup().lookup(NbNodeObject.class);
AddOn addon = (AddOn)nodeObject;
// add function
addon.addCommand(selectedObject);
// update UI
AddOnChildren children = (AddOnChildren)node.getChildren();
children.update();
panel.fireChangeEvent(); // Notify that the panel changed
selectNextNode();
}
}
public SubMenuElement addMenuAction() {
NbNodeObject selectedObject = getSelectedObject();
Node node = getNextMenuNode();
if (node != null) {
// get the data object "AddIn"
NbNodeObject nodeObject = (NbNodeObject)node.getLookup().lookup(NbNodeObject.class);
AddOn addon = (AddOn)nodeObject;
// add function
SubMenuElement subMenu = addon.addMenuElement(selectedObject);
// update UI
AddOnChildren children = (AddOnChildren)node.getChildren();
children.update();
panel.fireChangeEvent(); // Notify that the panel changed
return subMenu;
}
return null;
}
public SeparatorElement addSeparatorAction() {
NbNodeObject selectedObject = getSelectedObject();
Node node = getNextMenuNode();
if (node != null) {
// get the data object "AddIn"
NbNodeObject nodeObject = (NbNodeObject)node.getLookup().lookup(NbNodeObject.class);
AddOn addon = (AddOn)nodeObject;
// add function
SeparatorElement sep = addon.addSeparatorElement(selectedObject);
// update UI
AddOnChildren children = (AddOnChildren)node.getChildren();
children.update();
panel.fireChangeEvent(); // Notify that the panel changed
return sep;
}
return null;
}
public void deleteAction() {
NbNodeObject nodeObject = getSelectedObject();
if (nodeObject != null) {
if (nodeObject instanceof Command) {
Command f = (Command)nodeObject;
AddOn addon = (AddOn)nodeObject.getParent();
addon.removeCommand(f);
}
else if (nodeObject instanceof AddOn) {
SubMenuElement m = (SubMenuElement)nodeObject;
// keep the deleted commands in deleted vector for restoring
NbNodeObject[] subCommands = m.getAllCommands();
for (int i = 0; i < subCommands.length; i++) {
this.deletedCommands.add((Command)subCommands[i]);
}
AddOn addon = (AddOn)nodeObject.getParent();
addon.removeMenuElement(m);
}
else if (nodeObject instanceof SeparatorElement) {
SeparatorElement se = (SeparatorElement)nodeObject;
AddOn addon = (AddOn)nodeObject.getParent();
addon.removeSeparatorElement(se);
}
else {
return; // return and do not update UI unnecessarily
}
// update UI
AddOnChildren children = (AddOnChildren)
manager.getSelectedNodes()[0].getParentNode().getChildren();
children.update(); // updates nodes
panel.fireChangeEvent();
}
}
public void moveUp() {
Node[] selectedNodes = manager.getSelectedNodes();
NbNodeObject object = getSelectedObject();
if (object != null) {
NbNodeObject parent = object.getParent();
AddOn addon = (AddOn)parent;
addon.moveUp(object);
// update UI
Node parentNode = selectedNodes[0].getParentNode();
AddOnChildren children = (AddOnChildren)parentNode.getChildren();
children.update(); // updates nodes
panel.fireChangeEvent();
}
try {
manager.setSelectedNodes(selectedNodes);
} catch (PropertyVetoException ex) {
LogWriter.getLogWriter().printStackTrace(ex);
}
}
public void moveDown() {
Node[] selectedNodes = manager.getSelectedNodes();
NbNodeObject object = getSelectedObject();
if (object != null) {
NbNodeObject parent = object.getParent();
AddOn addon = (AddOn)parent;
addon.moveDown(object);
// update UI
AddOnChildren children = (AddOnChildren)
manager.getSelectedNodes()[0].getParentNode().getChildren();
children.update(); // updates nodes
panel.fireChangeEvent();
}
try {
manager.setSelectedNodes(selectedNodes);
} catch (PropertyVetoException ex) {
LogWriter.getLogWriter().printStackTrace(ex);
}
}
public void toggleVisibility() {
Node[] selected = manager.getSelectedNodes();
if (selected == null || selected.length == 0) {
return; // nothing to do
}
Node selectedNode = selected[0]; // single tree selection
Node parent = selectedNode.getParentNode();
NbNodeObject object = (NbNodeObject)selectedNode.getLookup().lookup(NbNodeObject.class);
// if not a command selected, delete the stuff!
if (object.getType() != NbNodeObject.FUNCTION_TYPE) {
this.deleteAction();
return;
}
Command f = (Command)object;
AddOn addon = (AddOn)f.getParent();
deletedCommands.add(f);
addon.removeCommand(f);
// update UI
AddOnChildren children = (AddOnChildren)parent.getChildren();
children.update(); // updates nodes
panel.fireChangeEvent();
}
public void restoreCommands() {
Node rootNode = manager.getRootContext();
AddOn addOn = (AddOn)rootNode.getLookup().lookup(NbNodeObject.class);
AddOn subMenu = null;
NbNodeObject[] subMenus = addOn.getAllSubObjects();
if (subMenus != null && subMenus.length != 0)
subMenu = (AddOn)subMenus[0];
else
subMenu = addOn;
for (Iterator<Command> it = deletedCommands.iterator(); it.hasNext(); ) {
Command com = it.next();
subMenu.insertCommand(com);
}
deletedCommands.clear();
// update UI
AddOnChildren children = (AddOnChildren)
rootNode.getChildren().getNodes()[0].getChildren();
children.update(); // updates nodes
panel.fireChangeEvent();
}
public void restoreCommand(Command com) {
Node[] selected = manager.getSelectedNodes();
Node selectedNode = null;
if (selected == null || selected.length == 0) { // all commands removed
selected = manager.getRootContext().getChildren().getNodes();
if (selected != null && selected.length > 0) { // nothing selected: take top menu
selectedNode = selected[0];
}
else { // top menu gone: must not happen!
LogWriter.getLogWriter().log(LogWriter.LEVEL_CRITICAL,
"Top Level Menu is gone from menu structure"); // NOI18N
selectedNode = manager.getRootContext(); // insert top level?
}
}
else {
selectedNode = selected[0]; // single tree selection
}
NbNodeObject object = (NbNodeObject)selectedNode.getLookup().lookup(NbNodeObject.class);
int type = object.getType();
if (type == NbNodeObject.UI_MENU_TYPE || type == NbNodeObject.ADDON_TYPE) {
AddOn addOn = (AddOn)object;
addOn.insertCommand(com);
}
else {
AddOn addOn = (AddOn)object.getParent();
selectedNode = selectedNode.getParentNode();
addOn.insertCommand(com, object);
}
deletedCommands.remove(com);
// update UI
AddOnChildren children = (AddOnChildren)selectedNode.getChildren();
children.update(); // updates nodes
panel.fireChangeEvent();
}
public void addLanguageAction() {
// get used languages
AddOnNode rootNode = (AddOnNode)manager.getRootContext();
NbNodeObject nodeObject = (NbNodeObject)rootNode.getLookup().lookup(NbNodeObject.class);
AddOn addon = (AddOn)nodeObject;
LocalizedOpenOfficeOrgProperty prop = (LocalizedOpenOfficeOrgProperty)addon.getProperty(addon.PROPERTY_DisplayName);
Integer[] indexes = prop.getUsedLanguageIndexes();
int langID = LanguageHandlingDialog.start(false, indexes); // add a language
if (langID != -1) {
addon.addLanguage(langID, null);
rootNode.triggerLanguageChange();
if (indexes.length == 0) // first language added: trigger valid() with the change event...
panel.fireChangeEvent(); // Notify that the panel changed
}
}
public void deleteLanguageAction() {
// get used languages
AddOnNode rootNode = (AddOnNode)manager.getRootContext();
// get the data object "AddIn"
NbNodeObject nodeObject = (NbNodeObject)rootNode.getLookup().lookup(NbNodeObject.class);
AddOn addon = (AddOn)nodeObject;
LocalizedOpenOfficeOrgProperty prop = (LocalizedOpenOfficeOrgProperty)addon.getProperty(addon.PROPERTY_DisplayName);
Integer[] indexes = prop.getUsedLanguageIndexes();
int langID = LanguageHandlingDialog.start(true, indexes); // delete a language
if (langID != -1) {
addon.removeLanguage(langID);
rootNode.triggerLanguageChange();
if (indexes.length == 1) // last language deleted: trigger valid() with the change event...
panel.fireChangeEvent(); // Notify that the panel changed
}
}
private NbNodeObject getSelectedObject() {
NbNodeObject object = null;
Node[] selectedNodes = manager.getSelectedNodes();
if (selectedNodes != null && selectedNodes.length > 0) {
AddOnNode addonNode = (AddOnNode)selectedNodes[0];
if(addonNode != null)
object = (NbNodeObject)addonNode.getLookup().lookup(NbNodeObject.class);
}
return object;
}
private void selectNextNode() {
Node[] selectedNodes = manager.getSelectedNodes();
if (selectedNodes != null && selectedNodes.length > 0) {
Node theNode = (Node)selectedNodes[0];
Node parentNode = theNode.getParentNode();
Node[] nodes = parentNode.getChildren().getNodes(); // the array is sorted!
boolean selectThisOne = false;
for (int i = 0; i < nodes.length; i++) {
if (selectThisOne) {
selectThisOne = false;
try {
manager.setSelectedNodes(new Node[]{nodes[i]});
} catch (PropertyVetoException ex) {
LogWriter.getLogWriter().printStackTrace(ex);
}
}
if (nodes[i].equals(theNode)) {
selectThisOne = true;
}
}
}
}
private Node getNextMenuNode() {
AddOnNode addonNode = null;
Node[] selectedNodes = manager.getSelectedNodes();
if (selectedNodes != null && selectedNodes.length > 0) {
addonNode = (AddOnNode)selectedNodes[0];
while (addonNode != null && !addonNode.isMenu()) {
addonNode = (AddOnNode)addonNode.getParentNode();
}
}
return addonNode;
}
public interface ActionPanel {
void fireChangeEvent();
}
}
| apache-2.0 |
mumabinggan/WeygoPhone | app/src/main/java/com/weygo/weygophone/base/WGResponse.java | 347 | package com.weygo.weygophone.base;
import com.weygo.common.base.JHResponse;
/**
* Created by muma on 2016/12/14.
*/
public class WGResponse extends JHResponse {
public int code;
public String message;
public boolean success() {
return code == 1;
}
public boolean reLogin() {
return code == -1;
}
}
| apache-2.0 |
OpenBEL/openbel-framework | org.openbel.framework.tools/src/main/java/org/openbel/framework/tools/xgmml/XGMMLExporter.java | 5405 | /**
* Copyright (C) 2012-2013 Selventa, Inc.
*
* This file is part of the OpenBEL Framework.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The OpenBEL Framework is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the OpenBEL Framework. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms under LGPL v3:
*
* This license does not authorize you and you are prohibited from using the
* name, trademarks, service marks, logos or similar indicia of Selventa, Inc.,
* or, in the discretion of other licensors or authors of the program, the
* name, trademarks, service marks, logos or similar indicia of such authors or
* licensors, in any marketing or advertising materials relating to your
* distribution of the program or any covered product. This restriction does
* not waive or limit your obligation to keep intact all copyright notices set
* forth in the program as delivered to you.
*
* If you distribute the program in whole or in part, or any modified version
* of the program, and you assume contractual liability to the recipient with
* respect to the program or modified version, then you will indemnify the
* authors and licensors of the program for any liabilities that these
* contractual assumptions directly impose on those licensors and authors.
*/
package org.openbel.framework.tools.xgmml;
import static org.openbel.framework.common.BELUtilities.nulls;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.List;
import org.openbel.framework.api.Kam;
import org.openbel.framework.api.Kam.KamEdge;
import org.openbel.framework.api.Kam.KamNode;
import org.openbel.framework.api.internal.KAMStoreDaoImpl.BelTerm;
import org.openbel.framework.api.KAMStore;
import org.openbel.framework.api.KAMStoreException;
import org.openbel.framework.common.InvalidArgument;
import org.openbel.framework.tools.xgmml.XGMMLObjects.Edge;
import org.openbel.framework.tools.xgmml.XGMMLObjects.Node;
/**
* XGMMLExporter leverages the KAM API to export a KAM in XGMML graph format.
*
* @see <a href="http://en.wikipedia.org/wiki/XGMML">http://en.wikipedia.org/wiki/XGMML</a>
* @author Anthony Bargnesi {@code <abargnesi@selventa.com>}
*/
public class XGMMLExporter {
/**
* Private constructor to prevent instantiation.
*/
private XGMMLExporter() {
}
/**
* Export KAM to XGMML format using the KAM API.
*
* @param kam {@link Kam} the kam to export to XGMML
* @param kAMStore {@link KAMStore} the kam store to read kam details from
* @param outputPath {@link String} the output path to write XGMML file to,
* which can be null, in which case the kam's name will be used and it will
* be written to the current directory (user.dir).
*
* @throws KAMStoreException Thrown if an error occurred retrieving the KAM
* @throws FileNotFoundException Thrown if the export file cannot be
* written to
* @throws InvalidArgument Thrown if either the kam, kamInfo, kamStore, or
* outputPath arguments were null
*/
public static void exportKam(final Kam kam, final KAMStore kAMStore,
String outputPath) throws KAMStoreException, FileNotFoundException {
if (nulls(kam, kAMStore, outputPath)) {
throw new InvalidArgument("argument(s) were null");
}
// Set up a writer to write the XGMML
PrintWriter writer = new PrintWriter(outputPath);
// Start to process the Kam
// Write xgmml <graph> element header
XGMMLUtility.writeStart(kam.getKamInfo().getName(), writer);
// We iterate over all the nodes in the Kam first
for (KamNode kamNode : kam.getNodes()) {
Node xNode = new Node();
xNode.id = kamNode.getId();
xNode.label = kamNode.getLabel();
xNode.function = kamNode.getFunctionType();
List<BelTerm> supportingTerms =
kAMStore.getSupportingTerms(kamNode);
XGMMLUtility.writeNode(xNode, supportingTerms, writer);
}
// Iterate over all the edges
for (KamEdge kamEdge : kam.getEdges()) {
Edge xEdge = new Edge();
xEdge.id = kamEdge.getId();
xEdge.rel = kamEdge.getRelationshipType();
KamNode knsrc = kamEdge.getSourceNode();
KamNode kntgt = kamEdge.getTargetNode();
xEdge.source = knsrc.getId();
xEdge.target = kntgt.getId();
Node src = new Node();
src.function = knsrc.getFunctionType();
src.label = knsrc.getLabel();
Node tgt = new Node();
tgt.function = kntgt.getFunctionType();
tgt.label = kntgt.getLabel();
XGMMLUtility.writeEdge(src, tgt, xEdge, writer);
}
// Close out the writer
XGMMLUtility.writeEnd(writer);
writer.close();
}
}
| apache-2.0 |
AssafMashiah/assafmashiah-yaml | src/test/java/org/yaml/snakeyaml/constructor/FilterClassesConstructorTest.java | 2346 | /**
* Copyright (c) 2008-2011, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.constructor;
import junit.framework.TestCase;
import org.yaml.snakeyaml.Yaml;
public class FilterClassesConstructorTest extends TestCase {
public void testGetClassForName() {
Yaml yaml = new Yaml(new FilterConstructor(true));
String input = "!!org.yaml.snakeyaml.constructor.FilterClassesConstructorTest$FilteredBean {name: Andrey, number: 543}";
try {
yaml.load(input);
fail("Filter is expected.");
} catch (Exception e) {
assertTrue(e.getMessage().contains("Filter is applied."));
}
yaml = new Yaml(new FilterConstructor(false));
FilteredBean s = (FilteredBean) yaml.load(input);
assertEquals("Andrey", s.getName());
}
class FilterConstructor extends Constructor {
private boolean filter;
public FilterConstructor(boolean f) {
filter = f;
}
@Override
protected Class<?> getClassForName(String name) throws ClassNotFoundException {
if (filter && name.startsWith("org.yaml")) {
throw new RuntimeException("Filter is applied.");
}
return super.getClassForName(name);
}
}
public static class FilteredBean {
private String name;
private int number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
}
| apache-2.0 |
carlosrojaso/nuts | app/src/main/java/com/google/cloud/backend/core/Consts.java | 2197 | /*
* Copyright (c) 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.backend.core;
/**
* A class to hold hard coded constants. Developers may modify the values based
* on their usage.
*/
public interface Consts {
/**
* Set Project ID of your Google APIs Console Project.
*/
public static final String PROJECT_ID = "feisty-lambda-522";
/**
* Set Project Number of your Google APIs Console Project.
*/
public static final String PROJECT_NUMBER = "898652117588";
/**
* Set your Web Client ID for authentication at backend.
*/
public static final String WEB_CLIENT_ID = "898652117588-ba8rjk77cp9ebiqf9n2giqprvhssirqb.apps.googleusercontent.com";
/**
* Set default user authentication enabled or disabled.
*/
public static final boolean IS_AUTH_ENABLED = false;
/**
* Auth audience for authentication on backend.
*/
public static final String AUTH_AUDIENCE = "server:client_id:" + WEB_CLIENT_ID;
/**
* Endpoint root URL
*/
public static final String ENDPOINT_ROOT_URL = "https://" + PROJECT_ID
+ ".appspot.com/_ah/api/";
/**
* A flag to switch if the app should be run with local dev server or
* production (cloud).
*/
public static final boolean LOCAL_ANDROID_RUN = false;
/**
* SharedPreferences keys for CloudBackend.
*/
public static final String PREF_KEY_CLOUD_BACKEND = "PREF_KEY_CLOUD_BACKEND";
public static final String PREF_KEY_ACCOUNT_NAME = "PREF_KEY_ACCOUNT_NAME";
/**
* Tag name for logging.
*/
public static final String TAG = "CloudBackend";
}
| apache-2.0 |
littlezhou/hadoop | hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/ScmConfigKeys.java | 14011 | /*
* 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.hdds.scm;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.ratis.proto.RaftProtos.ReplicationLevel;
import org.apache.ratis.util.TimeDuration;
import java.util.concurrent.TimeUnit;
/**
* This class contains constants for configuration keys used in SCM.
*/
@InterfaceAudience.Public
@InterfaceStability.Unstable
public final class ScmConfigKeys {
// Location of SCM DB files. For now we just support a single
// metadata dir but in future we may support multiple for redundancy or
// performance.
public static final String OZONE_SCM_DB_DIRS = "ozone.scm.db.dirs";
public static final String SCM_CONTAINER_CLIENT_STALE_THRESHOLD_KEY =
"scm.container.client.idle.threshold";
public static final String SCM_CONTAINER_CLIENT_STALE_THRESHOLD_DEFAULT =
"10s";
public static final String SCM_CONTAINER_CLIENT_MAX_SIZE_KEY =
"scm.container.client.max.size";
public static final int SCM_CONTAINER_CLIENT_MAX_SIZE_DEFAULT =
256;
public static final String SCM_CONTAINER_CLIENT_MAX_OUTSTANDING_REQUESTS =
"scm.container.client.max.outstanding.requests";
public static final int SCM_CONTAINER_CLIENT_MAX_OUTSTANDING_REQUESTS_DEFAULT
= 100;
public static final String DFS_CONTAINER_RATIS_ENABLED_KEY
= "dfs.container.ratis.enabled";
public static final boolean DFS_CONTAINER_RATIS_ENABLED_DEFAULT
= false;
public static final String DFS_CONTAINER_RATIS_RPC_TYPE_KEY
= "dfs.container.ratis.rpc.type";
public static final String DFS_CONTAINER_RATIS_RPC_TYPE_DEFAULT
= "GRPC";
public static final String DFS_CONTAINER_RATIS_NUM_WRITE_CHUNK_THREADS_KEY
= "dfs.container.ratis.num.write.chunk.threads";
public static final int DFS_CONTAINER_RATIS_NUM_WRITE_CHUNK_THREADS_DEFAULT
= 60;
public static final String DFS_CONTAINER_RATIS_REPLICATION_LEVEL_KEY
= "dfs.container.ratis.replication.level";
public static final ReplicationLevel
DFS_CONTAINER_RATIS_REPLICATION_LEVEL_DEFAULT = ReplicationLevel.MAJORITY;
public static final String DFS_CONTAINER_RATIS_NUM_CONTAINER_OP_EXECUTORS_KEY
= "dfs.container.ratis.num.container.op.executors";
public static final int DFS_CONTAINER_RATIS_NUM_CONTAINER_OP_EXECUTORS_DEFAULT
= 10;
public static final String DFS_CONTAINER_RATIS_SEGMENT_SIZE_KEY =
"dfs.container.ratis.segment.size";
public static final int DFS_CONTAINER_RATIS_SEGMENT_SIZE_DEFAULT =
16 * 1024;
public static final String DFS_CONTAINER_RATIS_SEGMENT_PREALLOCATED_SIZE_KEY =
"dfs.container.ratis.segment.preallocated.size";
public static final int
DFS_CONTAINER_RATIS_SEGMENT_PREALLOCATED_SIZE_DEFAULT = 128 * 1024 * 1024;
public static final String
DFS_CONTAINER_RATIS_STATEMACHINEDATA_SYNC_TIMEOUT =
"dfs.container.ratis.statemachinedata.sync.timeout";
public static final TimeDuration
DFS_CONTAINER_RATIS_STATEMACHINEDATA_SYNC_TIMEOUT_DEFAULT =
TimeDuration.valueOf(10, TimeUnit.SECONDS);
public static final String
DFS_CONTAINER_RATIS_STATEMACHINEDATA_SYNC_RETRIES =
"dfs.container.ratis.statemachinedata.sync.retries";
public static final int
DFS_CONTAINER_RATIS_STATEMACHINEDATA_SYNC_RETRIES_DEFAULT = -1;
public static final String DFS_CONTAINER_RATIS_LOG_QUEUE_SIZE =
"dfs.container.ratis.log.queue.size";
public static final int DFS_CONTAINER_RATIS_LOG_QUEUE_SIZE_DEFAULT = 128;
public static final String DFS_RATIS_CLIENT_REQUEST_TIMEOUT_DURATION_KEY =
"dfs.ratis.client.request.timeout.duration";
public static final TimeDuration
DFS_RATIS_CLIENT_REQUEST_TIMEOUT_DURATION_DEFAULT =
TimeDuration.valueOf(3000, TimeUnit.MILLISECONDS);
public static final String DFS_RATIS_CLIENT_REQUEST_MAX_RETRIES_KEY =
"dfs.ratis.client.request.max.retries";
public static final int DFS_RATIS_CLIENT_REQUEST_MAX_RETRIES_DEFAULT = 180;
public static final String DFS_RATIS_CLIENT_REQUEST_RETRY_INTERVAL_KEY =
"dfs.ratis.client.request.retry.interval";
public static final TimeDuration
DFS_RATIS_CLIENT_REQUEST_RETRY_INTERVAL_DEFAULT =
TimeDuration.valueOf(100, TimeUnit.MILLISECONDS);
public static final String DFS_RATIS_SERVER_RETRY_CACHE_TIMEOUT_DURATION_KEY =
"dfs.ratis.server.retry-cache.timeout.duration";
public static final TimeDuration
DFS_RATIS_SERVER_RETRY_CACHE_TIMEOUT_DURATION_DEFAULT =
TimeDuration.valueOf(600000, TimeUnit.MILLISECONDS);
public static final String DFS_RATIS_SERVER_REQUEST_TIMEOUT_DURATION_KEY =
"dfs.ratis.server.request.timeout.duration";
public static final TimeDuration
DFS_RATIS_SERVER_REQUEST_TIMEOUT_DURATION_DEFAULT =
TimeDuration.valueOf(3000, TimeUnit.MILLISECONDS);
public static final String
DFS_RATIS_LEADER_ELECTION_MINIMUM_TIMEOUT_DURATION_KEY =
"dfs.ratis.leader.election.minimum.timeout.duration";
public static final TimeDuration
DFS_RATIS_LEADER_ELECTION_MINIMUM_TIMEOUT_DURATION_DEFAULT =
TimeDuration.valueOf(1, TimeUnit.SECONDS);
public static final String DFS_RATIS_SNAPSHOT_THRESHOLD_KEY =
"dfs.ratis.snapshot.threshold";
public static final long DFS_RATIS_SNAPSHOT_THRESHOLD_DEFAULT = 10000;
public static final String DFS_RATIS_SERVER_FAILURE_DURATION_KEY =
"dfs.ratis.server.failure.duration";
public static final TimeDuration
DFS_RATIS_SERVER_FAILURE_DURATION_DEFAULT =
TimeDuration.valueOf(120, TimeUnit.SECONDS);
// TODO : this is copied from OzoneConsts, may need to move to a better place
public static final String OZONE_SCM_CHUNK_SIZE_KEY = "ozone.scm.chunk.size";
// 16 MB by default
public static final int OZONE_SCM_CHUNK_SIZE_DEFAULT = 16 * 1024 * 1024;
public static final int OZONE_SCM_CHUNK_MAX_SIZE = 32 * 1024 * 1024;
public static final String OZONE_SCM_CLIENT_PORT_KEY =
"ozone.scm.client.port";
public static final int OZONE_SCM_CLIENT_PORT_DEFAULT = 9860;
public static final String OZONE_SCM_DATANODE_PORT_KEY =
"ozone.scm.datanode.port";
public static final int OZONE_SCM_DATANODE_PORT_DEFAULT = 9861;
// OZONE_OM_PORT_DEFAULT = 9862
public static final String OZONE_SCM_BLOCK_CLIENT_PORT_KEY =
"ozone.scm.block.client.port";
public static final int OZONE_SCM_BLOCK_CLIENT_PORT_DEFAULT = 9863;
// Container service client
public static final String OZONE_SCM_CLIENT_ADDRESS_KEY =
"ozone.scm.client.address";
public static final String OZONE_SCM_CLIENT_BIND_HOST_KEY =
"ozone.scm.client.bind.host";
public static final String OZONE_SCM_CLIENT_BIND_HOST_DEFAULT =
"0.0.0.0";
// Block service client
public static final String OZONE_SCM_BLOCK_CLIENT_ADDRESS_KEY =
"ozone.scm.block.client.address";
public static final String OZONE_SCM_BLOCK_CLIENT_BIND_HOST_KEY =
"ozone.scm.block.client.bind.host";
public static final String OZONE_SCM_BLOCK_CLIENT_BIND_HOST_DEFAULT =
"0.0.0.0";
public static final String OZONE_SCM_DATANODE_ADDRESS_KEY =
"ozone.scm.datanode.address";
public static final String OZONE_SCM_DATANODE_BIND_HOST_KEY =
"ozone.scm.datanode.bind.host";
public static final String OZONE_SCM_DATANODE_BIND_HOST_DEFAULT =
"0.0.0.0";
public static final String OZONE_SCM_HTTP_ENABLED_KEY =
"ozone.scm.http.enabled";
public static final String OZONE_SCM_HTTP_BIND_HOST_KEY =
"ozone.scm.http-bind-host";
public static final String OZONE_SCM_HTTPS_BIND_HOST_KEY =
"ozone.scm.https-bind-host";
public static final String OZONE_SCM_HTTP_ADDRESS_KEY =
"ozone.scm.http-address";
public static final String OZONE_SCM_HTTPS_ADDRESS_KEY =
"ozone.scm.https-address";
public static final String OZONE_SCM_KEYTAB_FILE =
"ozone.scm.keytab.file";
public static final String OZONE_SCM_HTTP_BIND_HOST_DEFAULT = "0.0.0.0";
public static final int OZONE_SCM_HTTP_BIND_PORT_DEFAULT = 9876;
public static final int OZONE_SCM_HTTPS_BIND_PORT_DEFAULT = 9877;
public static final String HDDS_REST_HTTP_ADDRESS_KEY =
"hdds.rest.http-address";
public static final String HDDS_REST_HTTP_ADDRESS_DEFAULT = "0.0.0.0:9880";
public static final String HDDS_DATANODE_DIR_KEY = "hdds.datanode.dir";
public static final String HDDS_REST_CSRF_ENABLED_KEY =
"hdds.rest.rest-csrf.enabled";
public static final boolean HDDS_REST_CSRF_ENABLED_DEFAULT = false;
public static final String HDDS_REST_NETTY_HIGH_WATERMARK =
"hdds.rest.netty.high.watermark";
public static final int HDDS_REST_NETTY_HIGH_WATERMARK_DEFAULT = 65536;
public static final int HDDS_REST_NETTY_LOW_WATERMARK_DEFAULT = 32768;
public static final String HDDS_REST_NETTY_LOW_WATERMARK =
"hdds.rest.netty.low.watermark";
public static final String OZONE_SCM_HANDLER_COUNT_KEY =
"ozone.scm.handler.count.key";
public static final int OZONE_SCM_HANDLER_COUNT_DEFAULT = 10;
public static final String OZONE_SCM_DEADNODE_INTERVAL =
"ozone.scm.dead.node.interval";
public static final String OZONE_SCM_DEADNODE_INTERVAL_DEFAULT =
"10m";
public static final String OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL =
"ozone.scm.heartbeat.thread.interval";
public static final String OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL_DEFAULT =
"3s";
public static final String OZONE_SCM_STALENODE_INTERVAL =
"ozone.scm.stale.node.interval";
public static final String OZONE_SCM_STALENODE_INTERVAL_DEFAULT =
"90s";
public static final String OZONE_SCM_HEARTBEAT_RPC_TIMEOUT =
"ozone.scm.heartbeat.rpc-timeout";
public static final String OZONE_SCM_HEARTBEAT_RPC_TIMEOUT_DEFAULT =
"1s";
/**
* Defines how frequently we will log the missing of heartbeat to a specific
* SCM. In the default case we will write a warning message for each 10
* sequential heart beats that we miss to a specific SCM. This is to avoid
* overrunning the log with lots of HB missed Log statements.
*/
public static final String OZONE_SCM_HEARTBEAT_LOG_WARN_INTERVAL_COUNT =
"ozone.scm.heartbeat.log.warn.interval.count";
public static final int OZONE_SCM_HEARTBEAT_LOG_WARN_DEFAULT =
10;
// ozone.scm.names key is a set of DNS | DNS:PORT | IP Address | IP:PORT.
// Written as a comma separated string. e.g. scm1, scm2:8020, 7.7.7.7:7777
//
// If this key is not specified datanodes will not be able to find
// SCM. The SCM membership can be dynamic, so this key should contain
// all possible SCM names. Once the SCM leader is discovered datanodes will
// get the right list of SCMs to heartbeat to from the leader.
// While it is good for the datanodes to know the names of all SCM nodes,
// it is sufficient to actually know the name of on working SCM. That SCM
// will be able to return the information about other SCMs that are part of
// the SCM replicated Log.
//
//In case of a membership change, any one of the SCM machines will be
// able to send back a new list to the datanodes.
public static final String OZONE_SCM_NAMES = "ozone.scm.names";
public static final int OZONE_SCM_DEFAULT_PORT =
OZONE_SCM_DATANODE_PORT_DEFAULT;
// File Name and path where datanode ID is to written to.
// if this value is not set then container startup will fail.
public static final String OZONE_SCM_DATANODE_ID = "ozone.scm.datanode.id";
public static final String OZONE_SCM_DATANODE_ID_PATH_DEFAULT = "datanode.id";
public static final String OZONE_SCM_DB_CACHE_SIZE_MB =
"ozone.scm.db.cache.size.mb";
public static final int OZONE_SCM_DB_CACHE_SIZE_DEFAULT = 128;
public static final String OZONE_SCM_CONTAINER_SIZE =
"ozone.scm.container.size";
public static final String OZONE_SCM_CONTAINER_SIZE_DEFAULT = "5GB";
public static final String OZONE_SCM_CONTAINER_PLACEMENT_IMPL_KEY =
"ozone.scm.container.placement.impl";
public static final String OZONE_SCM_CONTAINER_PROVISION_BATCH_SIZE =
"ozone.scm.container.provision_batch_size";
public static final int OZONE_SCM_CONTAINER_PROVISION_BATCH_SIZE_DEFAULT = 20;
public static final String
OZONE_SCM_KEY_VALUE_CONTAINER_DELETION_CHOOSING_POLICY =
"ozone.scm.keyvalue.container.deletion-choosing.policy";
public static final String OZONE_SCM_CONTAINER_CREATION_LEASE_TIMEOUT =
"ozone.scm.container.creation.lease.timeout";
public static final String
OZONE_SCM_CONTAINER_CREATION_LEASE_TIMEOUT_DEFAULT = "60s";
public static final String OZONE_SCM_PIPELINE_DESTROY_TIMEOUT =
"ozone.scm.pipeline.destroy.timeout";
public static final String OZONE_SCM_PIPELINE_DESTROY_TIMEOUT_DEFAULT =
"300s";
public static final String OZONE_SCM_BLOCK_DELETION_MAX_RETRY =
"ozone.scm.block.deletion.max.retry";
public static final int OZONE_SCM_BLOCK_DELETION_MAX_RETRY_DEFAULT = 4096;
public static final String HDDS_SCM_WATCHER_TIMEOUT =
"hdds.scm.watcher.timeout";
public static final String HDDS_SCM_WATCHER_TIMEOUT_DEFAULT =
"10m";
/**
* Never constructed.
*/
private ScmConfigKeys() {
}
}
| apache-2.0 |
shuiliuxing/Cyclist | app/src/main/java/com/huabing/cyclist/bean/DownloadListener.java | 291 | package com.huabing.cyclist.bean;
/**
* Created by 30781 on 2017/7/14.
*/
public interface DownloadListener {
void onProgress(int progress); //进度
void onSuccess(); //成功
void onFail(); //失败
void onPause(); //暂停
void onCanceled(); //取消
}
| apache-2.0 |
vasilyvlasov/jtuples | src/main/java/com/othelle/jtuples/Product3.java | 2098 | package com.othelle.jtuples;
/*
* =============================================================================
*
* Copyright 2013, JTuples team
*
* 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.
*
* =============================================================================
*/
/*
* =============================================================================
* GENERATED CODE DO NOT EDIT
* =============================================================================
*/
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
public class Product3<T1, T2, T3> extends Product implements Tuple3<T1, T2, T3> {
private static final long serialVersionUID = -1187955276020306879L;
private T1 v1;
private T2 v2;
private T3 v3;
@JsonCreator
public Product3(@JsonProperty("_1") T1 v1, @JsonProperty("_2") T2 v2, @JsonProperty("_3") T3 v3) {
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
this.arity = 3;
}
public Object getElement(int index) {
switch (index) {
case 0:
return v1;
case 1:
return v2;
case 2:
return v3;
default:
throw new IndexOutOfBoundsException("Index is out of range: " + index);
}
}
@JsonProperty("_1")
public T1 _1() {
return v1;
}
@JsonProperty("_2")
public T2 _2() {
return v2;
}
@JsonProperty("_3")
public T3 _3() {
return v3;
}
} | apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/model/transform/GetDataRetrievalPolicyRequestMarshaller.java | 2140 | /*
* 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.glacier.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.glacier.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GetDataRetrievalPolicyRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetDataRetrievalPolicyRequestMarshaller {
private static final MarshallingInfo<String> ACCOUNTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
.marshallLocationName("accountId").defaultValueSupplier(DefaultAccountIdSupplier.getInstance()).build();
private static final GetDataRetrievalPolicyRequestMarshaller instance = new GetDataRetrievalPolicyRequestMarshaller();
public static GetDataRetrievalPolicyRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(GetDataRetrievalPolicyRequest getDataRetrievalPolicyRequest, ProtocolMarshaller protocolMarshaller) {
if (getDataRetrievalPolicyRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getDataRetrievalPolicyRequest.getAccountId(), ACCOUNTID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
usdot-jpo-ode/jpo-ode | jpo-ode-plugins/src/main/java/us/dot/its/jpo/ode/plugin/j2735/timstorage/Circle.java | 1856 | /*******************************************************************************
* Copyright 2018 572682
*
* 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 us.dot.its.jpo.ode.plugin.j2735.timstorage;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import us.dot.its.jpo.ode.plugin.asn1.Asn1Object;
@JsonPropertyOrder({ "center", "radius", "units" })
public class Circle extends Asn1Object {
private static final long serialVersionUID = 1L;
private Position center;
@JsonProperty("radius")
private String radius;
@JsonProperty("units")
private DistanceUnits units;
@JsonProperty("position")
public Position getPosition() {
return center;
}
@JsonProperty("center")
public void setPosition(Position position) {
this.center = position;
}
public String getRadius() {
return radius;
}
public void setRadius(String radius) {
this.radius = radius;
}
public Position getCenter() {
return center;
}
public void setCenter(Position center) {
this.center = center;
}
public DistanceUnits getUnits() {
return units;
}
public void setUnits(DistanceUnits units) {
this.units = units;
}
}
| apache-2.0 |
daileyet/openlibs.easywebframework | src/main/java/com/openthinks/easyweb/utils/json/package-info.java | 91 | /**
*
*/
/**
* @author minjdai
*
*/
package com.openthinks.easyweb.utils.json; | apache-2.0 |
mp911de/spinach | src/main/java/biz/paluch/spinach/impl/BaseCommandBuilder.java | 1392 | /*
* Copyright 2016 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 biz.paluch.spinach.impl;
import com.lambdaworks.redis.codec.RedisCodec;
import com.lambdaworks.redis.output.CommandOutput;
import com.lambdaworks.redis.protocol.Command;
import com.lambdaworks.redis.protocol.ProtocolKeyword;
class BaseCommandBuilder<K, V> {
protected RedisCodec<K, V> codec;
public BaseCommandBuilder(RedisCodec<K, V> codec) {
this.codec = codec;
}
protected <T> Command<K, V, T> createCommand(ProtocolKeyword type, CommandOutput<K, V, T> output) {
return createCommand(type, output, null);
}
protected <T> Command<K, V, T> createCommand(ProtocolKeyword type, CommandOutput<K, V, T> output,
DisqueCommandArgs<K, V> args) {
return new DisqueCommand<K, V, T>(type, output, args);
}
} | apache-2.0 |
ksimar/incubator-carbondata | core/src/main/java/org/apache/carbondata/core/compression/DoubleCompressor.java | 8311 | /*
* 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.carbondata.core.compression;
import java.math.BigDecimal;
import org.apache.carbondata.core.datastore.dataholder.CarbonWriteDataHolder;
import org.apache.carbondata.core.metadata.datatype.DataType;
/**
* Double compressor
*/
public class DoubleCompressor extends ValueCompressor {
@Override protected Object compressNonDecimalMaxMin(DataType convertedDataType,
CarbonWriteDataHolder dataHolder, int decimal, Object maxValue) {
int i = 0;
BigDecimal max = BigDecimal.valueOf((double)maxValue);
double[] value = dataHolder.getWritableDoubleValues();
switch (convertedDataType) {
case BYTE:
byte[] result = new byte[value.length];
for (int j = 0; j < value.length; j++) {
BigDecimal val = BigDecimal.valueOf(value[j]);
double diff = max.subtract(val).doubleValue();
result[i] = (byte) (Math.round(diff * Math.pow(10, decimal)));
i++;
}
return result;
case SHORT:
short[] shortResult = new short[value.length];
for (int j = 0; j < value.length; j++) {
BigDecimal val = BigDecimal.valueOf(value[j]);
double diff = max.subtract(val).doubleValue();
shortResult[i] = (short) (Math.round(diff * Math.pow(10, decimal)));
i++;
}
return shortResult;
case INT:
int[] intResult = new int[value.length];
for (int j = 0; j < value.length; j++) {
BigDecimal val = BigDecimal.valueOf(value[j]);
double diff = max.subtract(val).doubleValue();
intResult[i] = (int) (Math.round(diff * Math.pow(10, decimal)));
i++;
}
return intResult;
case LONG:
long[] longResult = new long[value.length];
for (int j = 0; j < value.length; j++) {
BigDecimal val = BigDecimal.valueOf(value[j]);
double diff = max.subtract(val).doubleValue();
longResult[i] = Math.round(diff * Math.pow(10, decimal));
i++;
}
return longResult;
case FLOAT:
float[] floatResult = new float[value.length];
for (int j = 0; j < value.length; j++) {
BigDecimal val = BigDecimal.valueOf(value[j]);
double diff = max.subtract(val).doubleValue();
floatResult[i] = (float) (Math.round(diff * Math.pow(10, decimal)));
i++;
}
return floatResult;
default:
double[] defaultResult = new double[value.length];
for (int j = 0; j < value.length; j++) {
BigDecimal val = BigDecimal.valueOf(value[j]);
double diff = max.subtract(val).doubleValue();
defaultResult[i] = (Math.round(diff * Math.pow(10, decimal)));
i++;
}
return defaultResult;
}
}
@Override
protected Object compressNonDecimal(DataType convertedDataType, CarbonWriteDataHolder dataHolder,
int decimal) {
int i = 0;
double[] value = dataHolder.getWritableDoubleValues();
switch (convertedDataType) {
case BYTE:
byte[] result = new byte[value.length];
for (int j = 0; j < value.length; j++) {
result[i] = (byte) (Math.round(Math.pow(10, decimal) * value[j]));
i++;
}
return result;
case SHORT:
short[] shortResult = new short[value.length];
for (int j = 0; j < value.length; j++) {
shortResult[i] = (short) (Math.round(Math.pow(10, decimal) * value[j]));
i++;
}
return shortResult;
case INT:
int[] intResult = new int[value.length];
for (int j = 0; j < value.length; j++) {
intResult[i] = (int) (Math.round(Math.pow(10, decimal) * value[j]));
i++;
}
return intResult;
case LONG:
long[] longResult = new long[value.length];
for (int j = 0; j < value.length; j++) {
longResult[i] = Math.round(Math.pow(10, decimal) * value[j]);
i++;
}
return longResult;
case FLOAT:
float[] floatResult = new float[value.length];
for (int j = 0; j < value.length; j++) {
floatResult[i] = (float) (Math.round(Math.pow(10, decimal) * value[j]));
i++;
}
return floatResult;
default:
double[] defaultResult = new double[value.length];
for (int j = 0; j < value.length; j++) {
defaultResult[i] = (double) (Math.round(Math.pow(10, decimal) * value[j]));
i++;
}
return defaultResult;
}
}
@Override
protected Object compressMaxMin(DataType convertedDataType, CarbonWriteDataHolder dataHolder,
Object max) {
double maxValue = (double) max;
double[] value = dataHolder.getWritableDoubleValues();
int i = 0;
switch (convertedDataType) {
case BYTE:
byte[] result = new byte[value.length];
for (int j = 0; j < value.length; j++) {
result[i] = (byte) (maxValue - value[j]);
i++;
}
return result;
case SHORT:
short[] shortResult = new short[value.length];
for (int j = 0; j < value.length; j++) {
shortResult[i] = (short) (maxValue - value[j]);
i++;
}
return shortResult;
case INT:
int[] intResult = new int[value.length];
for (int j = 0; j < value.length; j++) {
intResult[i] = (int) (maxValue - value[j]);
i++;
}
return intResult;
case LONG:
long[] longResult = new long[value.length];
for (int j = 0; j < value.length; j++) {
longResult[i] = (long) (maxValue - value[j]);
i++;
}
return longResult;
case FLOAT:
float[] floatResult = new float[value.length];
for (int j = 0; j < value.length; j++) {
floatResult[i] = (float) (maxValue - value[j]);
i++;
}
return floatResult;
default:
double[] defaultResult = new double[value.length];
for (int j = 0; j < value.length; j++) {
defaultResult[i] = maxValue - value[j];
i++;
}
return defaultResult;
}
}
@Override
protected Object compressAdaptive(DataType changedDataType, CarbonWriteDataHolder dataHolder) {
double[] value = dataHolder.getWritableDoubleValues();
int i = 0;
switch (changedDataType) {
case BYTE:
byte[] result = new byte[value.length];
for (int j = 0; j < value.length; j++) {
result[i] = (byte) value[j];
i++;
}
return result;
case SHORT:
short[] shortResult = new short[value.length];
for (int j = 0; j < value.length; j++) {
shortResult[i] = (short) value[j];
i++;
}
return shortResult;
case INT:
int[] intResult = new int[value.length];
for (int j = 0; j < value.length; j++) {
intResult[i] = (int) value[j];
i++;
}
return intResult;
case LONG:
long[] longResult = new long[value.length];
for (int j = 0; j < value.length; j++) {
longResult[i] = (long) value[j];
i++;
}
return longResult;
case FLOAT:
float[] floatResult = new float[value.length];
for (int j = 0; j < value.length; j++) {
floatResult[i] = (float) value[j];
i++;
}
return floatResult;
default:
return value;
}
}
}
| apache-2.0 |
googleads/google-ads-java | google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/services/ThirdPartyAppAnalyticsLinkServiceProto.java | 6605 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/services/third_party_app_analytics_link_service.proto
package com.google.ads.googleads.v8.services;
public final class ThirdPartyAppAnalyticsLinkServiceProto {
private ThirdPartyAppAnalyticsLinkServiceProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v8_services_GetThirdPartyAppAnalyticsLinkRequest_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v8_services_GetThirdPartyAppAnalyticsLinkRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v8_services_RegenerateShareableLinkIdRequest_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v8_services_RegenerateShareableLinkIdRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v8_services_RegenerateShareableLinkIdResponse_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v8_services_RegenerateShareableLinkIdResponse_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\nMgoogle/ads/googleads/v8/services/third" +
"_party_app_analytics_link_service.proto\022" +
" google.ads.googleads.v8.services\032Fgoogl" +
"e/ads/googleads/v8/resources/third_party" +
"_app_analytics_link.proto\032\034google/api/an" +
"notations.proto\032\031google/api/resource.pro" +
"to\032\027google/api/client.proto\"w\n$GetThirdP" +
"artyAppAnalyticsLinkRequest\022O\n\rresource_" +
"name\030\001 \001(\tB8\372A5\n3googleads.googleapis.co" +
"m/ThirdPartyAppAnalyticsLink\"s\n Regenera" +
"teShareableLinkIdRequest\022O\n\rresource_nam" +
"e\030\001 \001(\tB8\372A5\n3googleads.googleapis.com/T" +
"hirdPartyAppAnalyticsLink\"#\n!RegenerateS" +
"hareableLinkIdResponse2\345\004\n!ThirdPartyApp" +
"AnalyticsLinkService\022\355\001\n\035GetThirdPartyAp" +
"pAnalyticsLink\022F.google.ads.googleads.v8" +
".services.GetThirdPartyAppAnalyticsLinkR" +
"equest\032=.google.ads.googleads.v8.resourc" +
"es.ThirdPartyAppAnalyticsLink\"E\202\323\344\223\002?\022=/" +
"v8/{resource_name=customers/*/thirdParty" +
"AppAnalyticsLinks/*}\022\210\002\n\031RegenerateShare" +
"ableLinkId\022B.google.ads.googleads.v8.ser" +
"vices.RegenerateShareableLinkIdRequest\032C" +
".google.ads.googleads.v8.services.Regene" +
"rateShareableLinkIdResponse\"b\202\323\344\223\002\\\"W/v8" +
"/{resource_name=customers/*/thirdPartyAp" +
"pAnalyticsLinks/*}:regenerateShareableLi" +
"nkId:\001*\032E\312A\030googleads.googleapis.com\322A\'h" +
"ttps://www.googleapis.com/auth/adwordsB\215" +
"\002\n$com.google.ads.googleads.v8.servicesB" +
"&ThirdPartyAppAnalyticsLinkServiceProtoP" +
"\001ZHgoogle.golang.org/genproto/googleapis" +
"/ads/googleads/v8/services;services\242\002\003GA" +
"A\252\002 Google.Ads.GoogleAds.V8.Services\312\002 G" +
"oogle\\Ads\\GoogleAds\\V8\\Services\352\002$Google" +
"::Ads::GoogleAds::V8::Servicesb\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.ads.googleads.v8.resources.ThirdPartyAppAnalyticsLinkProto.getDescriptor(),
com.google.api.AnnotationsProto.getDescriptor(),
com.google.api.ResourceProto.getDescriptor(),
com.google.api.ClientProto.getDescriptor(),
});
internal_static_google_ads_googleads_v8_services_GetThirdPartyAppAnalyticsLinkRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_ads_googleads_v8_services_GetThirdPartyAppAnalyticsLinkRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v8_services_GetThirdPartyAppAnalyticsLinkRequest_descriptor,
new java.lang.String[] { "ResourceName", });
internal_static_google_ads_googleads_v8_services_RegenerateShareableLinkIdRequest_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_ads_googleads_v8_services_RegenerateShareableLinkIdRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v8_services_RegenerateShareableLinkIdRequest_descriptor,
new java.lang.String[] { "ResourceName", });
internal_static_google_ads_googleads_v8_services_RegenerateShareableLinkIdResponse_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_ads_googleads_v8_services_RegenerateShareableLinkIdResponse_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v8_services_RegenerateShareableLinkIdResponse_descriptor,
new java.lang.String[] { });
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.ClientProto.defaultHost);
registry.add(com.google.api.AnnotationsProto.http);
registry.add(com.google.api.ClientProto.oauthScopes);
registry.add(com.google.api.ResourceProto.resourceReference);
com.google.protobuf.Descriptors.FileDescriptor
.internalUpdateFileDescriptor(descriptor, registry);
com.google.ads.googleads.v8.resources.ThirdPartyAppAnalyticsLinkProto.getDescriptor();
com.google.api.AnnotationsProto.getDescriptor();
com.google.api.ResourceProto.getDescriptor();
com.google.api.ClientProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| apache-2.0 |
wz2cool/mybatis-dynamic-query | src/test/java/com/github/wz2cool/dynamic/DynamicQueryTest.java | 4341 | package com.github.wz2cool.dynamic;
import static com.github.wz2cool.dynamic.builder.DynamicQueryBuilderHelper.*;
import com.github.wz2cool.dynamic.model.Student;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* \* Created with IntelliJ IDEA.
* \* User: Frank
* \* Date: 8/10/2017
* \* Time: 10:15 AM
* \* To change this template use File | Settings | File Templates.
* \* Description:
* \
*/
public class DynamicQueryTest {
@Test
public void testAddFilter() {
FilterDescriptor filterDescriptor =
new FilterDescriptor(FilterCondition.AND, "name", FilterOperator.EQUAL, "frank");
DynamicQuery<Student> dynamicQuery = new DynamicQuery<>(Student.class);
dynamicQuery.addFilters(filterDescriptor);
assertEquals(1, dynamicQuery.getFilters().length);
}
@Test
public void testRemoveFilter() {
FilterDescriptor filterDescriptor =
new FilterDescriptor(FilterCondition.AND, "name", FilterOperator.EQUAL, "frank");
DynamicQuery<Student> dynamicQuery = new DynamicQuery<>(Student.class);
dynamicQuery.addFilters(filterDescriptor);
assertEquals(1, dynamicQuery.getFilters().length);
dynamicQuery.removeFilters(filterDescriptor);
assertEquals(0, dynamicQuery.getFilters().length);
}
@Test
public void testAddSort() {
SortDescriptor sort = new SortDescriptor("name", SortDirection.DESC);
DynamicQuery<Student> dynamicQuery = new DynamicQuery<>(Student.class);
dynamicQuery.addSorts(sort);
assertEquals(1, dynamicQuery.getSorts().length);
}
@Test
public void testRemoveSort() {
SortDescriptor sort = new SortDescriptor("name", SortDirection.DESC);
DynamicQuery<Student> dynamicQuery = new DynamicQuery<>(Student.class);
dynamicQuery.addSorts(sort);
assertEquals(1, dynamicQuery.getSorts().length);
dynamicQuery.removeSorts(sort);
assertEquals(0, dynamicQuery.getSorts().length);
}
@Test
public void testCreateQuery() {
DynamicQuery<Student> query = DynamicQuery.createQuery(Student.class);
assertEquals(0, query.getFilters().length);
}
@Test
public void testAddFilterDescriptor() {
DynamicQuery<Student> query = DynamicQuery.createQuery(Student.class)
.or(Student::getName, isEqual("frank"));
FilterDescriptor filterDescriptor = (FilterDescriptor) query.getFilters()[0];
assertEquals(FilterCondition.OR, filterDescriptor.getCondition());
assertEquals("name", filterDescriptor.getPropertyName());
assertEquals(FilterOperator.EQUAL, filterDescriptor.getOperator());
assertEquals("frank", filterDescriptor.getValue());
}
@Test
public void testLinkOperation() {
DynamicQuery<Student> query = DynamicQuery.createQuery(Student.class)
.and(Student::getName, isEqual("frank"))
.orderBy(Student::getAge, desc());
FilterDescriptor filterDescriptor = (FilterDescriptor) query.getFilters()[0];
assertEquals(FilterCondition.AND, filterDescriptor.getCondition());
assertEquals("name", filterDescriptor.getPropertyName());
assertEquals(FilterOperator.EQUAL, filterDescriptor.getOperator());
assertEquals("frank", filterDescriptor.getValue());
SortDescriptor sortDescriptor = (SortDescriptor) query.getSorts()[0];
assertEquals("age", sortDescriptor.getPropertyName());
assertEquals(SortDirection.DESC, sortDescriptor.getDirection());
}
@Test
public void testAddSelectProperty() {
DynamicQuery<Student> query = DynamicQuery.createQuery(Student.class)
.select(Student::getAge, Student::getName);
String[] selectFields = query.getSelectedProperties();
assertEquals("age", selectFields[0]);
assertEquals("name", selectFields[1]);
}
@Test
public void testAddIgnoredProperty() {
DynamicQuery<Student> query = DynamicQuery.createQuery(Student.class)
.ignore(Student::getAge, Student::getName);
String[] ignoredProperties = query.getIgnoredProperties();
assertEquals("age", ignoredProperties[0]);
assertEquals("name", ignoredProperties[1]);
}
} | apache-2.0 |
pvalsecc/camel-retry | src/main/java/ch/thus/camel/retry/RetryComponent.java | 1127 | /*
* Copyright 2016 Patrick Valsecchi
* 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 ch.thus.camel.retry;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.DefaultComponent;
/**
* Camel component for retry: URLs
*/
public class RetryComponent extends DefaultComponent {
@Override
protected Endpoint createEndpoint(java.lang.String uri, java.lang.String remaining, java.util.Map<java.lang.String, java.lang.Object> parameters) throws Exception {
Endpoint endpoint = new RetryEndpoint(uri, this);
setProperties(endpoint, parameters);
return endpoint;
}
}
| apache-2.0 |
floodlight/loxigen-artifacts | openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver15/OFOvsTcpFlagSerializerVer15.java | 5235 | // Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template const_set_serializer.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver15;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.projectfloodlight.openflow.protocol.OFOvsTcpFlag;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import java.util.EnumSet;
import java.util.Collections;
public class OFOvsTcpFlagSerializerVer15 {
public final static short OVS_TCP_FLAG_FIN_VAL = (short) 0x1;
public final static short OVS_TCP_FLAG_SYN_VAL = (short) 0x2;
public final static short OVS_TCP_FLAG_RST_VAL = (short) 0x4;
public final static short OVS_TCP_FLAG_PSH_VAL = (short) 0x8;
public final static short OVS_TCP_FLAG_ACK_VAL = (short) 0x10;
public final static short OVS_TCP_FLAG_URG_VAL = (short) 0x20;
public final static short OVS_TCP_FLAG_ECE_VAL = (short) 0x40;
public final static short OVS_TCP_FLAG_CWR_VAL = (short) 0x80;
public final static short OVS_TCP_FLAG_NS_VAL = (short) 0x100;
public static Set<OFOvsTcpFlag> readFrom(ByteBuf bb) throws OFParseError {
try {
return ofWireValue(bb.readShort());
} catch (IllegalArgumentException e) {
throw new OFParseError(e);
}
}
public static void writeTo(ByteBuf bb, Set<OFOvsTcpFlag> set) {
bb.writeShort(toWireValue(set));
}
public static void putTo(Set<OFOvsTcpFlag> set, PrimitiveSink sink) {
sink.putShort(toWireValue(set));
}
public static Set<OFOvsTcpFlag> ofWireValue(short val) {
EnumSet<OFOvsTcpFlag> set = EnumSet.noneOf(OFOvsTcpFlag.class);
if((val & OVS_TCP_FLAG_FIN_VAL) != 0)
set.add(OFOvsTcpFlag.OVS_TCP_FLAG_FIN);
if((val & OVS_TCP_FLAG_SYN_VAL) != 0)
set.add(OFOvsTcpFlag.OVS_TCP_FLAG_SYN);
if((val & OVS_TCP_FLAG_RST_VAL) != 0)
set.add(OFOvsTcpFlag.OVS_TCP_FLAG_RST);
if((val & OVS_TCP_FLAG_PSH_VAL) != 0)
set.add(OFOvsTcpFlag.OVS_TCP_FLAG_PSH);
if((val & OVS_TCP_FLAG_ACK_VAL) != 0)
set.add(OFOvsTcpFlag.OVS_TCP_FLAG_ACK);
if((val & OVS_TCP_FLAG_URG_VAL) != 0)
set.add(OFOvsTcpFlag.OVS_TCP_FLAG_URG);
if((val & OVS_TCP_FLAG_ECE_VAL) != 0)
set.add(OFOvsTcpFlag.OVS_TCP_FLAG_ECE);
if((val & OVS_TCP_FLAG_CWR_VAL) != 0)
set.add(OFOvsTcpFlag.OVS_TCP_FLAG_CWR);
if((val & OVS_TCP_FLAG_NS_VAL) != 0)
set.add(OFOvsTcpFlag.OVS_TCP_FLAG_NS);
return Collections.unmodifiableSet(set);
}
public static short toWireValue(Set<OFOvsTcpFlag> set) {
short wireValue = 0;
for(OFOvsTcpFlag e: set) {
switch(e) {
case OVS_TCP_FLAG_FIN:
wireValue |= OVS_TCP_FLAG_FIN_VAL;
break;
case OVS_TCP_FLAG_SYN:
wireValue |= OVS_TCP_FLAG_SYN_VAL;
break;
case OVS_TCP_FLAG_RST:
wireValue |= OVS_TCP_FLAG_RST_VAL;
break;
case OVS_TCP_FLAG_PSH:
wireValue |= OVS_TCP_FLAG_PSH_VAL;
break;
case OVS_TCP_FLAG_ACK:
wireValue |= OVS_TCP_FLAG_ACK_VAL;
break;
case OVS_TCP_FLAG_URG:
wireValue |= OVS_TCP_FLAG_URG_VAL;
break;
case OVS_TCP_FLAG_ECE:
wireValue |= OVS_TCP_FLAG_ECE_VAL;
break;
case OVS_TCP_FLAG_CWR:
wireValue |= OVS_TCP_FLAG_CWR_VAL;
break;
case OVS_TCP_FLAG_NS:
wireValue |= OVS_TCP_FLAG_NS_VAL;
break;
default:
throw new IllegalArgumentException("Illegal enum value for type OFOvsTcpFlag in version 1.5: " + e);
}
}
return wireValue;
}
}
| apache-2.0 |
farhanshaikh202/HitChat | src/main/java/com/farhanapps/HitChat/activities/ProfileImageViewer.java | 12580 | package com.farhanapps.HitChat.activities;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.os.AsyncTaskCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.farhanapps.HitChat.Models.ContactModel;
import com.farhanapps.HitChat.R;
import com.farhanapps.HitChat.adapters.MainChatListViewAdapter;
import com.farhanapps.HitChat.interfaces.OnMessageReceiveListener;
import com.farhanapps.HitChat.interfaces.UploadListener;
import com.farhanapps.HitChat.net.JSONParser;
import com.farhanapps.HitChat.net.UploadImageToServer;
import com.farhanapps.HitChat.services.MessageGateway;
import com.farhanapps.HitChat.utils.Constants;
import com.farhanapps.HitChat.utils.StringUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import org.hybridsquad.android.library.CropHandler;
import org.hybridsquad.android.library.CropHelper;
import org.hybridsquad.android.library.CropParams;
import org.json.JSONObject;
import java.util.prefs.Preferences;
public class ProfileImageViewer extends AppCompatActivity implements CropHandler{
ImageView imageView;
ProgressBar progressBar;
CropParams mCropParams;
String phoneNumber;
ImageLoader uil;
int type;
boolean self;
private MessageGateway messageGateway;
private Intent serviceIntent = null;
//binding
private boolean serviceBound = false;
//connect to the service
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MessageGateway.ServiceBinder binder = (MessageGateway.ServiceBinder) service;
//get service
messageGateway = binder.getService();
//Toast.makeText(getApplicationContext(), "binded", Toast.LENGTH_LONG).show();
serviceBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
finish();
}
};
//start and bind the service when the activity starts
@Override
protected void onStart() {
if (serviceIntent == null) {
serviceIntent = new Intent(this, MessageGateway.class);
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
startService(serviceIntent);
//Toast.makeText(getApplicationContext(), "svrs start", Toast.LENGTH_LONG).show();
}
Log.i("pointer", "start");
super.onStart();
}
DisplayImageOptions dip = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_image_viewer);
imageView=(ImageView)findViewById(R.id.profileImage);
progressBar=(ProgressBar)findViewById(R.id.profileImageLoading);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getIntent().getStringExtra(Constants.TAG_INTENT_USER_NAME));
type=getIntent().getIntExtra(Constants.TAG_IMAGE_TYPE, 0);
progressBar.setVisibility(View.GONE);
uil = ImageLoader.getInstance();
if (!uil.isInited()){
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.memoryCacheSize(41943040)
.diskCacheSize(104857600)
.threadPoolSize(10)
.build();
uil.init(config);
}
phoneNumber=getIntent().getStringExtra(Constants.TAG_INTENT_USER_NUMBER);
String url=getIntent().getStringExtra(Constants.TAG_INTENT_USER_IMAGE_URL);
self=phoneNumber.equals(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.TAG_MY_NUMBER, ""));
uil.displayImage(url, imageView, dip);
this.getCropParams();
mCropParams.outputFormat=Bitmap.CompressFormat.PNG.toString();
Log.i("URI",mCropParams.uri.toString());
if(type==Constants.TAG_IMAGE_TYPE_COVER){
mCropParams.aspectX=3;
mCropParams.aspectY=2;
mCropParams.outputX=500;
mCropParams.outputY=400;
}else {
mCropParams.outputX=500;
mCropParams.outputY=500;
}
}
void setNewImage(){
// MUST!! Clear Last Cached Image
CropHelper.clearCachedCropFile(mCropParams.uri);
AlertDialog.Builder builder=new AlertDialog.Builder(ProfileImageViewer.this);
builder.setItems(new String[]{"Camera", "Gallery"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
Intent intent = CropHelper.buildCaptureIntent(mCropParams.uri);
startActivityForResult(intent, CropHelper.REQUEST_CAMERA);
} else {
Intent intent = CropHelper.buildCropFromGalleryIntent(mCropParams);
startActivityForResult(intent, CropHelper.REQUEST_CROP);
}
}
});
builder.create().show();
}
@Override
protected void onDestroy() {
try {
unbindService(serviceConnection);
} catch (Exception e) {
}
if (this.getCropParams() != null)
CropHelper.clearCachedCropFile(mCropParams.uri);
super.onDestroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
CropHelper.handleResult(this, requestCode, resultCode, data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(self)
getMenuInflater().inflate(R.menu.profile_image_menu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home){
finish();
}else if(item.getItemId()==R.id.setNewImage){
setNewImage();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPhotoCropped(Uri uri) {
UploadImageToServer uploader=new UploadImageToServer();
uploader.setUploadListener(new UploadListener() {
@Override
public void onUploadStart() {
progressBar.setVisibility(View.VISIBLE);
progressBar.setMax(100);
}
@Override
public void onUploadProgress(int progress) {
progressBar.setIndeterminate(false);
progressBar.setProgress(progress);
}
@Override
public void onUploadFinish(String json) {
progressBar.setVisibility(View.GONE);
try {
if(!json.isEmpty()) {
JSONObject jsonObject = new JSONObject(json);
if(jsonObject.getString("error").equals("false")) {
String url = jsonObject.getString("url");
String thumb = jsonObject.getString("thumb");
if (self){
SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if(type==Constants.TAG_IMAGE_TYPE_PIC) {
preferences.edit().putString("picurl",url).putString("picthumb",thumb).apply();
}else {
preferences.edit().putString("coverurl",url).putString("coverthumb",thumb).apply();
}
}else{
ContactModel contactModel=messageGateway.db.getContactDetail(phoneNumber);
if (contactModel!=null) {
if(type==Constants.TAG_IMAGE_TYPE_PIC) {
contactModel.setContact_pic(StringUtils.filterAndi(url));
contactModel.setContact_pic_thumb(StringUtils.filterAndi(thumb));
}else {
contactModel.setContact_cover(StringUtils.filterAndi(url));
contactModel.setContact_cover_thumb(StringUtils.filterAndi(thumb));
}
messageGateway.db.updateContact(contactModel);
} else {
//todo for unknown number
}
}
uil.displayImage(url, imageView, dip, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String s, View view) {
progressBar.setIndeterminate(true);
progressBar.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String s, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
@Override
public void onLoadingComplete(String s, View view, Bitmap bitmap) {
progressBar.setVisibility(View.GONE);
}
@Override
public void onLoadingCancelled(String s, View view) {
progressBar.setVisibility(View.GONE);
}
});
}else Toast.makeText(getApplicationContext(),"server error",Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onUploadError(String error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();
}
});
if(type==Constants.TAG_IMAGE_TYPE_PIC){
AsyncTaskCompat.executeParallel(uploader,uri.getPath(),"pic",phoneNumber);
}
else if(type==Constants.TAG_IMAGE_TYPE_COVER){
AsyncTaskCompat.executeParallel(uploader,uri.getPath(),"cover",phoneNumber);
}
}
@Override
public void onCropCancel() {
}
@Override
public void onCropFailed(String message) {
}
@Override
public CropParams getCropParams() {
mCropParams = new CropParams();
return mCropParams;
}
@Override
public Activity getContext() {
return this;
}
}
| apache-2.0 |
yurloc/assertj-core | src/test/java/org/assertj/core/api/date/DateAssert_isInSameYearAs_Test.java | 1405 | /*
* Created on Dec 21, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Copyright @2010-2011 the original author or authors.
*/
package org.assertj.core.api.date;
import static org.mockito.Mockito.verify;
import java.util.Date;
import org.assertj.core.api.DateAssert;
/**
* Tests for <code>{@link DateAssert#isInSameYearAs(Date)}</code>.
*
* @author Joel Costigliola
*/
public class DateAssert_isInSameYearAs_Test extends AbstractDateAssertWithDateArg_Test {
@Override
protected DateAssert assertionInvocationWithDateArg() {
return assertions.isInSameYearAs(otherDate);
}
@Override
protected DateAssert assertionInvocationWithStringArg(String date) {
return assertions.isInSameYearAs(date);
}
@Override
protected void verifyAssertionInvocation(Date date) {
verify(dates).assertIsInSameYearAs(getInfo(assertions), getActual(assertions), date);
}
}
| apache-2.0 |
CenturyLinkCloud/clc-java-sdk | sdk/src/test/java/com/centurylink/cloud/sdk/server/services/dsl/domain/server/refs/ServerByDescriptionRefTest.java | 1240 | /*
* (c) 2015 CenturyLink. 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.centurylink.cloud.sdk.server.services.dsl.domain.server.refs;
import org.testng.annotations.Test;
import static com.centurylink.cloud.sdk.base.services.dsl.domain.datacenters.refs.DataCenter.US_WEST_SANTA_CLARA;
import static org.testng.Assert.assertTrue;
public class ServerByDescriptionRefTest {
@Test
public void testServerByDescSerialization() {
Server server = Server.refByDescription(US_WEST_SANTA_CLARA, "My Description");
String toStringValue = server.toString();
assertTrue(toStringValue.contains("My Description"));
assertTrue(toStringValue.contains("uc1"));
}
} | apache-2.0 |
bulenkov/Darcula | src/com/bulenkov/darcula/ui/DarculaButtonPainter.java | 2553 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bulenkov.darcula.ui;
import com.bulenkov.darcula.DarculaUIUtil;
import com.bulenkov.iconloader.util.GraphicsConfig;
import com.bulenkov.iconloader.util.Gray;
import javax.swing.border.Border;
import javax.swing.plaf.InsetsUIResource;
import javax.swing.plaf.UIResource;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaButtonPainter implements Border, UIResource {
private static final int myOffset = 4;
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
final Graphics2D g2d = (Graphics2D)g;
final Insets ins = getBorderInsets(c);
final int yOff = (ins.top + ins.bottom) / 4;
final boolean square = DarculaButtonUI.isSquare(c);
int offset = square ? 1 : getOffset();
if (c.hasFocus()) {
DarculaUIUtil.paintFocusRing(g2d, offset, yOff, width - 2 * offset, height - 2 * yOff);
} else {
final GraphicsConfig config = new GraphicsConfig(g);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
g2d.setPaint(new GradientPaint(width / 2, y + yOff + 1, Gray._80.withAlpha(90), width / 2, height - 2 * yOff, Gray._90.withAlpha(90)));
//g.drawRoundRect(x + offset + 1, y + yOff + 1, width - 2 * offset, height - 2*yOff, 5, 5);
((Graphics2D)g).setPaint(Gray._100.withAlpha(180));
g.drawRoundRect(x + offset, y + yOff, width - 2 * offset, height - 2*yOff, square ? 3 : 5, square ? 3 : 5);
config.restore();
}
}
@Override
public Insets getBorderInsets(Component c) {
if (DarculaButtonUI.isSquare(c)) {
return new InsetsUIResource(2, 0, 2, 0);
}
return new InsetsUIResource(8, 16, 8, 14);
}
protected int getOffset() {
return myOffset;
}
@Override
public boolean isBorderOpaque() {
return false;
}
}
| apache-2.0 |
mpi2/PhenotypeArchive | src/main/java/uk/ac/ebi/phenotype/data/impress/Utilities.java | 7576 | /*******************************************************************************
* Copyright 2015 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*******************************************************************************/
package uk.ac.ebi.phenotype.data.impress;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import uk.ac.ebi.phenotype.dao.DatasourceDAO;
import uk.ac.ebi.phenotype.dao.OntologyTermDAO;
import uk.ac.ebi.phenotype.pojo.*;
import java.util.*;
/**
*
* Utilities provide a set of utility methods for IMPRESS client
*
* @author Gautier Koscielny
* @see Parameter
*/
@Component
public class Utilities {
private static final Logger logger = LoggerFactory.getLogger(Utilities.class);
@Autowired
OntologyTermDAO ontologyTermDAO;
@Autowired
DatasourceDAO datasourceDAO;
private Integer efoDbId=null;
private final Set<String> expectedDpc = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("9.5", "12.5", "13.5", "14.5", "15.5", "18.5")));
/**
* Returns the observation type based on the parameter, when the parameter
* has a valid dataType.
*
* @param parameter a valid <code>Parameter</code> instance
* @return The observation type based on the parameter, when the parameter
* has a valid data type (<code>parameter.getDatatype()</code>).
*
* <b>NOTE: if the parameter does not have a valid data type, this function
* may return incorrect results. When the parameter datatype is unknown,
* call <code>checktype(Parameter p, String value)</code> with a sample data
* value to get the correct observation type.</b>
*/
public ObservationType checkType(Parameter parameter) {
ObservationType ret=null;
try {
ret = checkType(parameter, null);
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
/**
* Returns the observation type based on the parameter and a sample
* parameter value.
*
* @param parameter a valid <code>Parameter</code> instance
* @param value a string representing parameter sample data (e.g. a floating
* point number or anything else).
* @return The observation type based on the parameter and a sample
* parameter value. If <code>value</code> is a floating point number and
* <code>parameter</code> does not have a valid data type,
* <code>value</code> is used to disambiguate the graph type: the
* observation type will be either <i>time_series</i> or
* <i>unidimensional</i>; otherwise, it will be interpreted as
* <i>categorical</i>.
*/
public ObservationType checkType(Parameter parameter, String value) {
Map<String, String> MAPPING = new HashMap<>();
MAPPING.put("M-G-P_022_001_001_001", "FLOAT");
MAPPING.put("M-G-P_022_001_001", "FLOAT");
MAPPING.put("ESLIM_006_001_035", "FLOAT");
MAPPING = Collections.unmodifiableMap(MAPPING);
ObservationType observationType = null;
Float valueToInsert = 0.0f;
String datatype = parameter.getDatatype();
if (MAPPING.containsKey(parameter.getStableId())) {
datatype = MAPPING.get(parameter.getStableId());
}
if (parameter.isMetaDataFlag()) {
observationType = ObservationType.metadata;
} else {
if (parameter.isOptionsFlag()) {
observationType = ObservationType.categorical;
} else {
if (datatype.equals("TEXT")) {
observationType = ObservationType.text;
} else if (datatype.equals("DATETIME")) {
observationType = ObservationType.datetime;
} else if (datatype.equals("BOOL")) {
observationType = ObservationType.categorical;
} else if (datatype.equals("FLOAT") || datatype.equals("INT")) {
if (parameter.isIncrementFlag()) {
observationType = ObservationType.time_series;
} else {
observationType = ObservationType.unidimensional;
}
try {
if (value != null) {
valueToInsert = Float.valueOf(value);
}
} catch (NumberFormatException ex) {
logger.debug("Invalid float value: " + value);
//TODO probably should throw an exception!
}
} else if (datatype.equals("IMAGE") || (datatype.equals("") && parameter.getName().contains("images"))) {
observationType = ObservationType.image_record;
} else if (datatype.equals("") && !parameter.isOptionsFlag() && !parameter.getName().contains("images")) {
// is that a number or a category?
try {
// check whether it's null
if (value != null && !value.equals("null")) {
valueToInsert = Float.valueOf(value);
}
if (parameter.isIncrementFlag()) {
observationType = ObservationType.time_series;
} else {
observationType = ObservationType.unidimensional;
}
} catch (NumberFormatException ex) {
observationType = ObservationType.categorical;
}
}
}
}
return observationType;
}
/**
* Always return EFO term for "embryo stage" for now
* Future enhancement (once EFO gets a term for "embryonic day 9.5") would be
* to return the actual term associated with the stage parameter
*
* @param stage the stage from impress
* @param stageUnit the stage unit applicable to stage
* @return the term associated with the correct stage
*/
public OntologyTerm getStageTerm(String stage, StageUnitType stageUnit) {
// Fail fast if the stage is not a "number"
try {
Float.parseFloat(stage);
} catch (NumberFormatException e) {
return null;
}
initializeEfoDbId();
switch (stageUnit) {
case DPC:
// Mouse gestation is 20 days
if(Float.parseFloat(stage)>21) {
return null;
}
String termName = String.format("embryonic day %s", stage);
if( ! expectedDpc.contains(stage)) {
logger.warn("Unexpected value for embryonic DCP stage: "+stage);
}
OntologyTerm term = ontologyTermDAO.getOntologyTermByName(termName);
if (term==null) {
// Term not found -- create it
term = createOntologyTerm(termName);
}
return term;
case THEILER:
return ontologyTermDAO.getOntologyTermByName(String.format("TS%s,embryo", stage));
default:
return null;
}
}
/**
* Create an EFO OntologyTerm for the passed in termName
*
* @param termName the name of the term to create
* @return the (already persisted) ontology term
*/
public OntologyTerm createOntologyTerm(String termName) {
initializeEfoDbId();
String termAcc = "NULL-" + DigestUtils.md5Hex(termName).substring(0,9).toUpperCase();
logger.info("Creating EFO term for name '%s' (Accession: %s)", termName, termAcc);
OntologyTerm term;
term = new OntologyTerm();
term.setId(new DatasourceEntityId(termAcc,efoDbId));
term.setDescription(termName);
term.setName(termName);
ontologyTermDAO.batchInsertion(Arrays.asList(term));
return term;
}
private void initializeEfoDbId() {
if(efoDbId==null) {
efoDbId = datasourceDAO.getDatasourceByShortName("EFO").getId();
}
}
}
| apache-2.0 |
MyRobotLab/myrobotlab | src/main/java/org/myrobotlab/opencv/OpenCVFilterHsv.java | 3011 | /**
*
* @author grog (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab is free software: you can redistribute it and/or modify
* it under the terms of the Apache License 2.0 as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Apache License 2.0 for more details.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.opencv;
/*
* HSV changes in OpenCV -
* https://code.ros.org/trac/opencv/ticket/328 H is only 1-180
* H <- H/2 (to fit to 0 to 255)
*
* CV_HSV2BGR_FULL uses full 0 to 255 range
*/
import static org.bytedeco.opencv.global.opencv_imgproc.CV_FONT_HERSHEY_PLAIN;
import static org.bytedeco.opencv.global.opencv_imgproc.CV_RGB2HSV;
import static org.bytedeco.opencv.global.opencv_imgproc.cvCvtColor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import org.bytedeco.opencv.opencv_core.IplImage;
import org.bytedeco.opencv.opencv_imgproc.CvFont;
import org.myrobotlab.logging.LoggerFactory;
import org.slf4j.Logger;
public class OpenCVFilterHsv extends OpenCVFilter {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(OpenCVFilterHsv.class.getCanonicalName());
transient IplImage hsv = null;
transient IplImage hue = null;
transient IplImage value = null;
transient IplImage saturation = null;
transient IplImage mask = null;
int x = 0;
int y = 0;
int clickCounter = 0;
Graphics g = null;
String lastHexValueOfPoint = "";
transient CvFont font = new CvFont(CV_FONT_HERSHEY_PLAIN);
public OpenCVFilterHsv() {
super();
}
public OpenCVFilterHsv(String name) {
super(name);
}
@Override
public void imageChanged(IplImage image) {
hsv = IplImage.createCompatible(image);
}
@Override
public IplImage process(IplImage image) {
cvCvtColor(image, hsv, CV_RGB2HSV);
return hsv;
}
public void samplePoint(Integer inX, Integer inY) {
++clickCounter;
x = inX;
y = inY;
}
@Override
public BufferedImage processDisplay(Graphics2D graphics, BufferedImage image) {
if (x != 0 && clickCounter % 2 == 0) {
int clr = image.getRGB(x, y);
lastHexValueOfPoint = Integer.toHexString(clr);
graphics.drawString(lastHexValueOfPoint, x, y);
}
return image;
}
}
| apache-2.0 |
adrygll2/literacyapp-chat | app/src/main/java/org/literacyapp/chat/model/Message.java | 953 | package org.literacyapp.chat.model;
import org.greenrobot.greendao.annotation.Convert;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.NotNull;
import org.literacyapp.chat.dao.converter.CalendarConverter;
import java.util.Calendar;
@Deprecated
public class Message {
@Id(autoincrement = true)
private Long id;
@NotNull
private String deviceId;
@NotNull
@Convert(converter = CalendarConverter.class, columnType = Long.class)
private Calendar timeSent;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public Calendar getTimeSent() {
return timeSent;
}
public void setTimeSent(Calendar timeSent) {
this.timeSent = timeSent;
}
}
| apache-2.0 |
ctripcorp/x-pipe | redis/redis-checker/src/main/java/com/ctrip/xpipe/redis/checker/resource/Resource.java | 703 | package com.ctrip.xpipe.redis.checker.resource;
/**
* @author lishanglin
* date 2021/3/8
*/
public class Resource {
public static final String REDIS_COMMAND_EXECUTOR = "redisCommandExecutor";
public static final String KEYED_NETTY_CLIENT_POOL = "keyedClientPool";
public static final String REDIS_SESSION_NETTY_CLIENT_POOL = "redisSessionClientPool";
public static final String PING_DELAY_INFO_EXECUTORS = "pingDelayInfoExecutors";
public static final String PING_DELAY_INFO_SCHEDULED = "pingDelayInfoScheduled";
public static final String HELLO_CHECK_EXECUTORS = "helloCheckExecutors";
public static final String HELLO_CHECK_SCHEDULED = "helloCheckScheduled";
}
| apache-2.0 |
aseemsbapat/test | LoginDBSQLInjection.java | 8755 |
package org.owasp.webgoat.plugin.dbsqlinjection;
import org.owasp.webgoat.plugin.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.plugin.GoatHillsFinancial.EmployeeStub;
import org.owasp.webgoat.plugin.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.plugin.GoatHillsFinancial.LessonAction;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.List;
import java.util.Vector;
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*/
public class LoginDBSQLInjection extends DefaultLessonAction
{
private LessonAction chainedAction;
public LoginDBSQLInjection(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
{
// System.out.println("Login.handleRequest()");
getLesson().setCurrentAction(s, getActionName());
List employees = getAllEmployees(s);
setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.STAFF_ATTRIBUTE_KEY, employees);
String employeeId = null;
try
{
employeeId = s.getParser().getStringParameter(DBSQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(DBSQLInjection.PASSWORD);
// Attempt authentication
boolean authenticated = login(s, employeeId, password);
if (authenticated)
{
// Execute the chained Action if authentication succeeded.
try
{
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}
else
s.setMessage("Login failed");
} catch (ParameterNotFoundException pnfe)
{
// No credentials offered, so we log them out
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE);
}
}
public String getNextPage(WebSession s)
{
String nextPage = DBSQLInjection.LOGIN_ACTION;
if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s);
return nextPage;
}
public boolean requiresAuthentication()
{
return false;
}
public boolean login(WebSession s, String userId, String password)
{
boolean authenticated = false;
try
{
String call = "{ ? = call EMPLOYEE_LOGIN(?,?) }"; // NB: "call", not "CALL"! Doh!
try
{
CallableStatement statement = WebSession.getConnection(s)
.prepareCall(call, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
statement.registerOutParameter(1, Types.INTEGER);
statement.setInt(2, Integer.parseInt(userId));
statement.setString(3, password);
statement.execute();
int rows = statement.getInt(1);
if (rows > 0)
{
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.USER_ID, userId);
authenticated = true;
if (DBSQLInjection.STAGE1.equals(getStage(s))
&& DBSQLInjection.PRIZE_EMPLOYEE_ID == Integer.parseInt(userId))
{
setStageComplete(s, DBSQLInjection.STAGE1);
}
}
else
{
if (DBSQLInjection.STAGE2.equals(getStage(s)))
{
try
{
String call2 = "{ ? = call EMPLOYEE_LOGIN_BACKUP(?,?) }";
statement = WebSession.getConnection(s).prepareCall(call2,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.registerOutParameter(1, Types.INTEGER);
statement.setInt(2, Integer.parseInt(userId));
statement.setString(3, password);
statement.execute();
rows = statement.getInt(1);
if (rows > 0) setStageComplete(s, DBSQLInjection.STAGE2);
} catch (SQLException sqle2)
{
}
}
}
} catch (SQLException sqle)
{
s.setMessage("Error logging in: " + sqle.getLocalizedMessage());
sqle.printStackTrace();
}
} catch (Exception e)
{
s.setMessage("Error logging in: " + e.getLocalizedMessage());
e.printStackTrace();
}
// System.out.println("Lesson login result: " + authenticated);
return authenticated;
}
public List getAllEmployees(WebSession s)
{
List<EmployeeStub> employees = new Vector<EmployeeStub>();
// Query the database for all roles the given employee belongs to
// Query the database for all employees "owned" by these roles
try
{
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles "
+ "where employee.userid=roles.userid";
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst();
while (answer_results.next())
{
int employeeId = answer_results.getInt("userid");
String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role");
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub);
}
} catch (SQLException sqle)
{
s.setMessage("Error getting employees");
sqle.printStackTrace();
}
} catch (Exception e)
{
s.setMessage("Error getting employees");
e.printStackTrace();
}
return employees;
}
}
| apache-2.0 |
dongyuanlongwang/coder | algorithms/algs4/src/test/java/rui/coder/algorithms/algs4/第一章_基础/c_第三节_背包_队列_栈/QueueTest.java | 3342 | package rui.coder.algorithms.algs4.第一章_基础.c_第三节_背包_队列_栈;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import rui.coder.algorithms.algs4.第一章_基础.c_第三节_背包_队列_栈.Queue;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class QueueTest {
rui.coder.algorithms.algs4.第一章_基础.c_第三节_背包_队列_栈.Queue<String> queue = new java.util.Queue<>();
@Test
void enqueue () {
for (int i = 0; i < 10; i++) {
queue.enqueue(UUID.randomUUID().toString());
}
assertSame(10,queue.size());
}
@Test
void toStringMethod(){
List<String> stringList=new ArrayList<>();
for (int i = 0; i < 3; i++) {
String random=UUID.randomUUID().toString();
stringList.add(random);
queue.enqueue(random);
}
assertEquals(stringList.toString(),queue.toString());
}
@Nested
class dequeue{
@Test
void noSuchElementException() {
NoSuchElementException noSuchElementException= assertThrows(NoSuchElementException.class,() -> queue.dequeue());
assertEquals("空队列",noSuchElementException.getMessage());
}
@Test
void dequeue() {
List<String> stringList=new ArrayList<>();
for (int i = 0; i < 10; i++) {
String random=UUID.randomUUID().toString();
stringList.add(random);
queue.enqueue(random);
}
assertSame(10,queue.size());
for (int i = 0; i < 10; i++) {
String uuid=queue.dequeue();
assertEquals(stringList.get(i),uuid);
}
}
}
@Nested
class iterator{
List<String> stringList=new ArrayList<>();
@BeforeEach
void setUp() {
for (int i = 0; i < 10; i++) {
String random=UUID.randomUUID().toString();
stringList.add(random);
queue.enqueue(random);
}
}
@Test
void remove() {
UnsupportedOperationException unsupportedOperationException=assertThrows(UnsupportedOperationException.class,()-> queue.iterator().remove());
assertEquals("不支持移除操作",unsupportedOperationException.getMessage());
}
@Test
void next() {
int i=0;
Iterator<String> iterator=queue.iterator();
while(iterator.hasNext()){
String uuid=iterator.next();
assertEquals(stringList.get(i++),uuid);
}
}
@Test
void noNext_stillUseNest() {
Iterator<String> iterator=queue.iterator();
while(iterator.hasNext()){
iterator.next();
}
NoSuchElementException noSuchElementException=assertThrows(NoSuchElementException.class,()->iterator.next());
assertEquals("迭代器已经没有下一个了",noSuchElementException.getMessage());
}
@Test
void foreach(){
int i=0;
for (String s : queue) {
assertEquals(stringList.get(i++),s);
}
}
}
} | apache-2.0 |
mbizhani/Demeter | common/src/main/java/org/devocative/demeter/vo/filter/FileStoreFVO.java | 2533 | //overwrite
package org.devocative.demeter.vo.filter;
import org.devocative.adroit.vo.RangeVO;
import org.devocative.demeter.entity.EFileStatus;
import org.devocative.demeter.entity.EFileStorage;
import org.devocative.demeter.entity.EMimeType;
import org.devocative.demeter.entity.User;
import org.devocative.demeter.iservice.persistor.Filterer;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Filterer
public class FileStoreFVO implements Serializable {
private static final long serialVersionUID = -1852367703L;
private String name;
private List<EFileStatus> status;
private List<EFileStorage> storage;
private List<EMimeType> mimeType;
private String fileId;
private String tag;
private RangeVO<Date> expiration;
private RangeVO<Date> creationDate;
private List<User> creatorUser;
private RangeVO<Date> modificationDate;
private List<User> modifierUser;
// ------------------------------
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<EFileStatus> getStatus() {
return status;
}
public void setStatus(List<EFileStatus> status) {
this.status = status;
}
public List<EFileStorage> getStorage() {
return storage;
}
public void setStorage(List<EFileStorage> storage) {
this.storage = storage;
}
public List<EMimeType> getMimeType() {
return mimeType;
}
public void setMimeType(List<EMimeType> mimeType) {
this.mimeType = mimeType;
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public RangeVO<Date> getExpiration() {
return expiration;
}
public void setExpiration(RangeVO<Date> expiration) {
this.expiration = expiration;
}
public RangeVO<Date> getCreationDate() {
return creationDate;
}
public void setCreationDate(RangeVO<Date> creationDate) {
this.creationDate = creationDate;
}
public List<User> getCreatorUser() {
return creatorUser;
}
public void setCreatorUser(List<User> creatorUser) {
this.creatorUser = creatorUser;
}
public RangeVO<Date> getModificationDate() {
return modificationDate;
}
public void setModificationDate(RangeVO<Date> modificationDate) {
this.modificationDate = modificationDate;
}
public List<User> getModifierUser() {
return modifierUser;
}
public void setModifierUser(List<User> modifierUser) {
this.modifierUser = modifierUser;
}
} | apache-2.0 |
Tataraovoleti/SpringSecurityDaoAuth | SpringSecurityDaoAuth/src/main/java/com/tata/spring/service/UserService.java | 754 | package com.tata.spring.service;
/**
*
* @author Tatarao voleti
* @date May 22, 2015
*/
import java.util.List;
import com.tata.spring.beans.UserBean;
public class UserService extends AbstractService {
@Override
public void addUser(UserBean user) {
// TODO Auto-generated method stub
}
@Override
public void updateUser(UserBean user) {
// TODO Auto-generated method stub
}
@Override
public void deleteUser(UserBean user) {
// TODO Auto-generated method stub
}
@Override
public UserBean findUser(String username) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<UserBean> listUsers() {
// TODO Auto-generated method stub
return null;
}
}
| apache-2.0 |
yurloc/assertj-core | src/test/java/org/assertj/core/api/map/MapAssert_hasSize_Test.java | 1246 | /*
* Created on Dec 21, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* Copyright @2010-2011 the original author or authors.
*/
package org.assertj.core.api.map;
import org.assertj.core.api.MapAssert;
import org.assertj.core.api.MapAssertBaseTest;
import static org.mockito.Mockito.verify;
/**
* Tests for <code>{@link MapAssert#hasSize(int)}</code>.
*
* @author Alex Ruiz
* @author Nicolas François
*/
public class MapAssert_hasSize_Test extends MapAssertBaseTest {
@Override
protected MapAssert<Object, Object> invoke_api_method() {
return assertions.hasSize(6);
}
@Override
protected void verify_internal_effects() {
verify(maps).assertHasSize(getInfo(assertions), getActual(assertions), 6);
}
}
| apache-2.0 |
Estwd/Safari-Park | main-attraction/src/main/java/com/estwd/safari/examples/servlets/lion/SafariLionServlet.java | 1361 | package com.estwd.safari.examples.servlets.lion;
import org.apache.shiro.util.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* A servlet for testing the uses of the Safari-park Lion utilities.
*
* @author Guni Y.
*/
@Path("/lion")
public class SafariLionServlet {
private static final Logger log = LoggerFactory.getLogger(SafariLionServlet.class);
public SafariLionServlet() {
log.info("Started the Safari-Lion servlet");
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public String get() {
return "This service is used to demonstrate the use of Zookeeper as a sessions-store for the Apache Shiro library";
}
@GET
@Path("/login/{username}")
@Produces(MediaType.TEXT_PLAIN)
public String login(@PathParam("username") final String username) {
return "The session ID created for this session is:" + ThreadContext.getSubject().getSession().getId();
}
@GET
@Path("/user/{sessionId}")
@Produces(MediaType.TEXT_PLAIN)
public String getUserName(@PathParam("sessionId") final String sessionId) {
return "The user that created this session is:" + ThreadContext.getSubject().getPrincipal();
}
}
| apache-2.0 |
ogregoire/imgn | imgn-module/src/main/java/io/imgn/module/Dependency.java | 56 | package io.imgn.module;
public class Dependency {
}
| apache-2.0 |
telstra/open-kilda | src-java/network-topology/network-storm-topology/src/main/java/org/openkilda/wfm/topology/network/storm/bolt/sw/command/SwitchManagedEventCommand.java | 1292 | /* Copyright 2019 Telstra Open Source
*
* 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.openkilda.wfm.topology.network.storm.bolt.sw.command;
import org.openkilda.messaging.model.SpeakerSwitchView;
import org.openkilda.wfm.topology.network.storm.bolt.sw.SwitchHandler;
public class SwitchManagedEventCommand extends SwitchCommand {
private final SpeakerSwitchView switchView;
private final String dumpId;
public SwitchManagedEventCommand(SpeakerSwitchView switchView, String dumpId) {
super(switchView.getDatapath());
this.switchView = switchView;
this.dumpId = dumpId;
}
@Override
public void apply(SwitchHandler handler) {
handler.processSwitchBecomeManaged(switchView, dumpId);
}
}
| apache-2.0 |
azusa/hatunatu | hatunatu/src/test/java/jp/fieldnotes/hatunatu/dao/dbms/H2Test.java | 3938 | /*
* Copyright 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 jp.fieldnotes.hatunatu.dao.dbms;
import jp.fieldnotes.hatunatu.dao.Dbms;
import jp.fieldnotes.hatunatu.dao.handler.BasicSelectHandler;
import jp.fieldnotes.hatunatu.dao.jdbc.QueryObject;
import jp.fieldnotes.hatunatu.dao.resultset.ObjectResultSetHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.lastaflute.di.core.LaContainer;
import org.lastaflute.di.core.SingletonLaContainer;
import org.lastaflute.di.core.factory.LaContainerFactory;
import org.lastaflute.di.core.factory.SingletonLaContainerFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import static org.junit.Assert.assertEquals;
public class H2Test {
@Before
public void before(){
LaContainer container = LaContainerFactory.create("app-h2.xml");
SingletonLaContainerFactory.setContainer(container);
}
@Test
public void testSequence() throws Exception {
// ## Arrange ##
final DataSource ds = SingletonLaContainer.getComponent(DataSource.class);
final Connection con = ds.getConnection();
final Statement stmt = con.createStatement();
stmt.executeUpdate("DROP SEQUENCE IF EXISTS H2TEST_SEQ");
stmt
.executeUpdate("CREATE SEQUENCE H2TEST_SEQ START WITH 7650 INCREMENT BY 1");
stmt.close();
final Dbms dbms = DbmsManager.getDbms(ds);
System.err.println(dbms.getClass());
assertEquals(true, dbms instanceof H2);
// ## Act ##
// ## Assert ##
final String sequenceNextValString = dbms
.getSequenceNextValString("H2TEST_SEQ");
QueryObject queryObject = new QueryObject();
queryObject.setSql(sequenceNextValString);
final BasicSelectHandler nextvalHandler = new BasicSelectHandler(
ds,
new ObjectResultSetHandler(Number.class));
{
final Number nextval = (Number) nextvalHandler.execute(queryObject);
assertEquals(7650, nextval.intValue());
}
{
final Number nextval = (Number) nextvalHandler.execute(queryObject);
assertEquals(7651, nextval.intValue());
}
{
final Number nextval = (Number) nextvalHandler.execute(queryObject);
assertEquals(7652, nextval.intValue());
}
final String identitySelectString = dbms.getIdentitySelectString();
final BasicSelectHandler identityHandler = new BasicSelectHandler(
ds,
new ObjectResultSetHandler(Number.class));
QueryObject queryObject2 = new QueryObject();
queryObject2.setSql(identitySelectString);
{
final Number currval = (Number) identityHandler.execute(queryObject2);
assertEquals(7652, currval.intValue());
}
{
final Number currval = (Number) identityHandler.execute(queryObject2);
assertEquals(7652, currval.intValue());
}
{
nextvalHandler.execute(queryObject);
final Number currval = (Number) identityHandler.execute(queryObject2);
assertEquals(7653, currval.intValue());
}
}
@After
public void after(){
SingletonLaContainerFactory.destroy();
}
}
| apache-2.0 |
google-code-export/google-api-dfp-java | examples/v201302/companyservice/GetAllCompaniesExample.java | 2609 | // Copyright 2012 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 v201302.companyservice;
import com.google.api.ads.dfp.lib.DfpService;
import com.google.api.ads.dfp.lib.DfpServiceLogger;
import com.google.api.ads.dfp.lib.DfpUser;
import com.google.api.ads.dfp.v201302.Company;
import com.google.api.ads.dfp.v201302.CompanyPage;
import com.google.api.ads.dfp.v201302.CompanyServiceInterface;
import com.google.api.ads.dfp.v201302.Statement;
/**
* This example gets all companies. To create companies, run
* CreateCompaniesExample.java.
*
* Tags: CompanyService.getCompaniesByStatement
*
* @author api.arogal@gmail.com (Adam Rogal)
*/
public class GetAllCompaniesExample {
public static void main(String[] args) {
try {
// Log SOAP XML request and response.
DfpServiceLogger.log();
// Get DfpUser from "~/dfp.properties".
DfpUser user = new DfpUser();
// Get the CompanyService.
CompanyServiceInterface companyService =
user.getService(DfpService.V201302.COMPANY_SERVICE);
// Set defaults for page and filterStatement.
CompanyPage page = new CompanyPage();
Statement filterStatement = new Statement();
int offset = 0;
do {
// Create a statement to get all companies.
filterStatement.setQuery("LIMIT 500 OFFSET " + offset);
// Get companies by statement.
page = companyService.getCompaniesByStatement(filterStatement);
if (page.getResults() != null) {
int i = page.getStartIndex();
for (Company company : page.getResults()) {
System.out.println(i + ") Company with ID \"" + company.getId()
+ "\", name \"" + company.getName()
+ "\", and type \"" + company.getType() + "\" was found.");
i++;
}
}
offset += 500;
} while (offset < page.getTotalResultSetSize());
System.out.println("Number of results found: " + page.getTotalResultSetSize());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| apache-2.0 |
dbflute-test/dbflute-test-option-compatible10x | src/main/java/org/docksidestage/compatible10x/dbflute/cbean/cq/bs/AbstractBsVendorIdentityOnlyCQ.java | 21937 | /*
* Copyright 2014-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.docksidestage.compatible10x.dbflute.cbean.cq.bs;
import java.util.*;
import org.dbflute.cbean.*;
import org.dbflute.cbean.chelper.*;
import org.dbflute.cbean.ckey.*;
import org.dbflute.cbean.coption.*;
import org.dbflute.cbean.cvalue.ConditionValue;
import org.dbflute.cbean.ordering.*;
import org.dbflute.cbean.scoping.*;
import org.dbflute.cbean.sqlclause.SqlClause;
import org.dbflute.dbmeta.DBMetaProvider;
import org.docksidestage.compatible10x.dbflute.allcommon.*;
import org.docksidestage.compatible10x.dbflute.cbean.*;
import org.docksidestage.compatible10x.dbflute.cbean.cq.*;
/**
* The abstract condition-query of VENDOR_IDENTITY_ONLY.
* @author DBFlute(AutoGenerator)
*/
public abstract class AbstractBsVendorIdentityOnlyCQ extends AbstractConditionQuery {
// ===================================================================================
// Constructor
// ===========
public AbstractBsVendorIdentityOnlyCQ(ConditionQuery referrerQuery, SqlClause sqlClause, String aliasName, int nestLevel) {
super(referrerQuery, sqlClause, aliasName, nestLevel);
}
// ===================================================================================
// DB Meta
// =======
@Override
protected DBMetaProvider xgetDBMetaProvider() {
return DBMetaInstanceHandler.getProvider();
}
public String asTableDbName() {
return "VENDOR_IDENTITY_ONLY";
}
// ===================================================================================
// Query
// =====
/**
* Equal(=). And NullIgnored, OnlyOnceRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
* @param identityOnlyId The value of identityOnlyId as equal. (basically NotNull: error as default, or no condition as option)
*/
public void setIdentityOnlyId_Equal(Long identityOnlyId) {
doSetIdentityOnlyId_Equal(identityOnlyId);
}
protected void doSetIdentityOnlyId_Equal(Long identityOnlyId) {
regIdentityOnlyId(CK_EQ, identityOnlyId);
}
/**
* NotEqual(<>). And NullIgnored, OnlyOnceRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
* @param identityOnlyId The value of identityOnlyId as notEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setIdentityOnlyId_NotEqual(Long identityOnlyId) {
doSetIdentityOnlyId_NotEqual(identityOnlyId);
}
protected void doSetIdentityOnlyId_NotEqual(Long identityOnlyId) {
regIdentityOnlyId(CK_NES, identityOnlyId);
}
/**
* GreaterThan(>). And NullIgnored, OnlyOnceRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
* @param identityOnlyId The value of identityOnlyId as greaterThan. (basically NotNull: error as default, or no condition as option)
*/
public void setIdentityOnlyId_GreaterThan(Long identityOnlyId) {
regIdentityOnlyId(CK_GT, identityOnlyId);
}
/**
* LessThan(<). And NullIgnored, OnlyOnceRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
* @param identityOnlyId The value of identityOnlyId as lessThan. (basically NotNull: error as default, or no condition as option)
*/
public void setIdentityOnlyId_LessThan(Long identityOnlyId) {
regIdentityOnlyId(CK_LT, identityOnlyId);
}
/**
* GreaterEqual(>=). And NullIgnored, OnlyOnceRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
* @param identityOnlyId The value of identityOnlyId as greaterEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setIdentityOnlyId_GreaterEqual(Long identityOnlyId) {
regIdentityOnlyId(CK_GE, identityOnlyId);
}
/**
* LessEqual(<=). And NullIgnored, OnlyOnceRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
* @param identityOnlyId The value of identityOnlyId as lessEqual. (basically NotNull: error as default, or no condition as option)
*/
public void setIdentityOnlyId_LessEqual(Long identityOnlyId) {
regIdentityOnlyId(CK_LE, identityOnlyId);
}
/**
* RangeOf with various options. (versatile) <br>
* {(default) minNumber <= column <= maxNumber} <br>
* And NullIgnored, OnlyOnceRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
* @param minNumber The min number of identityOnlyId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param maxNumber The max number of identityOnlyId. (basically NotNull: if op.allowOneSide(), null allowed)
* @param rangeOfOption The option of range-of. (NotNull)
*/
public void setIdentityOnlyId_RangeOf(Long minNumber, Long maxNumber, RangeOfOption rangeOfOption) {
regROO(minNumber, maxNumber, xgetCValueIdentityOnlyId(), "IDENTITY_ONLY_ID", rangeOfOption);
}
/**
* InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
* @param identityOnlyIdList The collection of identityOnlyId as inScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setIdentityOnlyId_InScope(Collection<Long> identityOnlyIdList) {
doSetIdentityOnlyId_InScope(identityOnlyIdList);
}
protected void doSetIdentityOnlyId_InScope(Collection<Long> identityOnlyIdList) {
regINS(CK_INS, cTL(identityOnlyIdList), xgetCValueIdentityOnlyId(), "IDENTITY_ONLY_ID");
}
/**
* NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
* @param identityOnlyIdList The collection of identityOnlyId as notInScope. (basically NotNull, NotEmpty: error as default, or no condition as option)
*/
public void setIdentityOnlyId_NotInScope(Collection<Long> identityOnlyIdList) {
doSetIdentityOnlyId_NotInScope(identityOnlyIdList);
}
protected void doSetIdentityOnlyId_NotInScope(Collection<Long> identityOnlyIdList) {
regINS(CK_NINS, cTL(identityOnlyIdList), xgetCValueIdentityOnlyId(), "IDENTITY_ONLY_ID");
}
/**
* IsNull {is null}. And OnlyOnceRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
*/
public void setIdentityOnlyId_IsNull() { regIdentityOnlyId(CK_ISN, DOBJ); }
/**
* IsNotNull {is not null}. And OnlyOnceRegistered. <br>
* IDENTITY_ONLY_ID: {PK, ID, NotNull, BIGINT(19)}
*/
public void setIdentityOnlyId_IsNotNull() { regIdentityOnlyId(CK_ISNN, DOBJ); }
protected void regIdentityOnlyId(ConditionKey ky, Object vl) { regQ(ky, vl, xgetCValueIdentityOnlyId(), "IDENTITY_ONLY_ID"); }
protected abstract ConditionValue xgetCValueIdentityOnlyId();
// ===================================================================================
// ScalarCondition
// ===============
/**
* Prepare ScalarCondition as equal. <br>
* {where FOO = (select max(BAR) from ...)}
* <pre>
* cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span>
* <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True();
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<VendorIdentityOnlyCB> scalar_Equal() {
return xcreateSLCFunction(CK_EQ, VendorIdentityOnlyCB.class);
}
/**
* Prepare ScalarCondition as equal. <br>
* {where FOO <> (select max(BAR) from ...)}
* <pre>
* cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span>
* <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True();
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<VendorIdentityOnlyCB> scalar_NotEqual() {
return xcreateSLCFunction(CK_NES, VendorIdentityOnlyCB.class);
}
/**
* Prepare ScalarCondition as greaterThan. <br>
* {where FOO > (select max(BAR) from ...)}
* <pre>
* cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span>
* <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True();
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<VendorIdentityOnlyCB> scalar_GreaterThan() {
return xcreateSLCFunction(CK_GT, VendorIdentityOnlyCB.class);
}
/**
* Prepare ScalarCondition as lessThan. <br>
* {where FOO < (select max(BAR) from ...)}
* <pre>
* cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span>
* <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True();
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<VendorIdentityOnlyCB> scalar_LessThan() {
return xcreateSLCFunction(CK_LT, VendorIdentityOnlyCB.class);
}
/**
* Prepare ScalarCondition as greaterEqual. <br>
* {where FOO >= (select max(BAR) from ...)}
* <pre>
* cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>></span> {
* <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span>
* <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True();
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<VendorIdentityOnlyCB> scalar_GreaterEqual() {
return xcreateSLCFunction(CK_GE, VendorIdentityOnlyCB.class);
}
/**
* Prepare ScalarCondition as lessEqual. <br>
* {where FOO <= (select max(BAR) from ...)}
* <pre>
* cb.query().<span style="color: #CC4747">scalar_LessEqual()</span>.max(new SubQuery<VendorIdentityOnlyCB>() {
* public void query(VendorIdentityOnlyCB subCB) {
* subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span>
* subCB.query().setBar...
* }
* });
* </pre>
* @return The object to set up a function. (NotNull)
*/
public HpSLCFunction<VendorIdentityOnlyCB> scalar_LessEqual() {
return xcreateSLCFunction(CK_LE, VendorIdentityOnlyCB.class);
}
@SuppressWarnings("unchecked")
protected <CB extends ConditionBean> void xscalarCondition(String fn, SubQuery<CB> sq, String rd, HpSLCCustomized<CB> cs, ScalarConditionOption op) {
assertObjectNotNull("subQuery", sq);
VendorIdentityOnlyCB cb = xcreateScalarConditionCB(); sq.query((CB)cb);
String pp = keepScalarCondition(cb.query()); // for saving query-value
cs.setPartitionByCBean((CB)xcreateScalarConditionPartitionByCB()); // for using partition-by
registerScalarCondition(fn, cb.query(), pp, rd, cs, op);
}
public abstract String keepScalarCondition(VendorIdentityOnlyCQ sq);
protected VendorIdentityOnlyCB xcreateScalarConditionCB() {
VendorIdentityOnlyCB cb = newMyCB(); cb.xsetupForScalarCondition(this); return cb;
}
protected VendorIdentityOnlyCB xcreateScalarConditionPartitionByCB() {
VendorIdentityOnlyCB cb = newMyCB(); cb.xsetupForScalarConditionPartitionBy(this); return cb;
}
// ===================================================================================
// MyselfDerived
// =============
public void xsmyselfDerive(String fn, SubQuery<VendorIdentityOnlyCB> sq, String al, DerivedReferrerOption op) {
assertObjectNotNull("subQuery", sq);
VendorIdentityOnlyCB cb = new VendorIdentityOnlyCB(); cb.xsetupForDerivedReferrer(this);
lockCall(() -> sq.query(cb)); String pp = keepSpecifyMyselfDerived(cb.query()); String pk = "IDENTITY_ONLY_ID";
registerSpecifyMyselfDerived(fn, cb.query(), pk, pk, pp, "myselfDerived", al, op);
}
public abstract String keepSpecifyMyselfDerived(VendorIdentityOnlyCQ sq);
/**
* Prepare for (Query)MyselfDerived (correlated sub-query).
* @return The object to set up a function for myself table. (NotNull)
*/
public HpQDRFunction<VendorIdentityOnlyCB> myselfDerived() {
return xcreateQDRFunctionMyselfDerived(VendorIdentityOnlyCB.class);
}
@SuppressWarnings("unchecked")
protected <CB extends ConditionBean> void xqderiveMyselfDerived(String fn, SubQuery<CB> sq, String rd, Object vl, DerivedReferrerOption op) {
assertObjectNotNull("subQuery", sq);
VendorIdentityOnlyCB cb = new VendorIdentityOnlyCB(); cb.xsetupForDerivedReferrer(this); sq.query((CB)cb);
String pk = "IDENTITY_ONLY_ID";
String sqpp = keepQueryMyselfDerived(cb.query()); // for saving query-value.
String prpp = keepQueryMyselfDerivedParameter(vl);
registerQueryMyselfDerived(fn, cb.query(), pk, pk, sqpp, "myselfDerived", rd, vl, prpp, op);
}
public abstract String keepQueryMyselfDerived(VendorIdentityOnlyCQ sq);
public abstract String keepQueryMyselfDerivedParameter(Object vl);
// ===================================================================================
// MyselfExists
// ============
/**
* Prepare for MyselfExists (correlated sub-query).
* @param subCBLambda The implementation of sub-query. (NotNull)
*/
public void myselfExists(SubQuery<VendorIdentityOnlyCB> subCBLambda) {
assertObjectNotNull("subCBLambda", subCBLambda);
VendorIdentityOnlyCB cb = new VendorIdentityOnlyCB(); cb.xsetupForMyselfExists(this);
lockCall(() -> subCBLambda.query(cb)); String pp = keepMyselfExists(cb.query());
registerMyselfExists(cb.query(), pp);
}
public abstract String keepMyselfExists(VendorIdentityOnlyCQ sq);
// ===================================================================================
// Manual Order
// ============
/**
* Order along manual ordering information.
* <pre>
* ManualOrderOption mop = new ManualOrderOption();
* mop.<span style="color: #CC4747">when_GreaterEqual</span>(priorityDate); <span style="color: #3F7E5E">// e.g. 2000/01/01</span>
* cb.query().addOrderBy_Birthdate_Asc().<span style="color: #CC4747">withManualOrder(mop)</span>;
* <span style="color: #3F7E5E">// order by </span>
* <span style="color: #3F7E5E">// case</span>
* <span style="color: #3F7E5E">// when BIRTHDATE >= '2000/01/01' then 0</span>
* <span style="color: #3F7E5E">// else 1</span>
* <span style="color: #3F7E5E">// end asc, ...</span>
*
* ManualOrderOption mop = new ManualOrderOption();
* mop.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Withdrawal);
* mop.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Formalized);
* mop.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Provisional);
* cb.query().addOrderBy_MemberStatusCode_Asc().<span style="color: #CC4747">withManualOrder(mop)</span>;
* <span style="color: #3F7E5E">// order by </span>
* <span style="color: #3F7E5E">// case</span>
* <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'WDL' then 0</span>
* <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'FML' then 1</span>
* <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'PRV' then 2</span>
* <span style="color: #3F7E5E">// else 3</span>
* <span style="color: #3F7E5E">// end asc, ...</span>
* </pre>
* <p>This function with Union is unsupported!</p>
* <p>The order values are bound (treated as bind parameter).</p>
* @param option The option of manual-order containing order values. (NotNull)
*/
public void withManualOrder(ManualOrderOption option) { // is user public!
xdoWithManualOrder(option);
}
// ===================================================================================
// Small Adjustment
// ================
/**
* Order along the list of manual values. #beforejava8 <br>
* This function with Union is unsupported! <br>
* The order values are bound (treated as bind parameter).
* <pre>
* MemberCB cb = new MemberCB();
* List<CDef.MemberStatus> orderValueList = new ArrayList<CDef.MemberStatus>();
* orderValueList.add(CDef.MemberStatus.Withdrawal);
* orderValueList.add(CDef.MemberStatus.Formalized);
* orderValueList.add(CDef.MemberStatus.Provisional);
* cb.query().addOrderBy_MemberStatusCode_Asc().<span style="color: #CC4747">withManualOrder(orderValueList)</span>;
* <span style="color: #3F7E5E">// order by </span>
* <span style="color: #3F7E5E">// case</span>
* <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'WDL' then 0</span>
* <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'FML' then 1</span>
* <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'PRV' then 2</span>
* <span style="color: #3F7E5E">// else 3</span>
* <span style="color: #3F7E5E">// end asc, ...</span>
* </pre>
* @param orderValueList The list of order values for manual ordering. (NotNull)
*/
public void withManualOrder(List<? extends Object> orderValueList) { // is user public!
assertObjectNotNull("withManualOrder(orderValueList)", orderValueList);
final ManualOrderOption option = new ManualOrderOption();
option.acceptOrderValueList(orderValueList);
withManualOrder(option);
}
@Override
protected void filterFromToOption(String columnDbName, FromToOption option) {
option.allowOneSide();
}
// ===================================================================================
// Very Internal
// =============
protected VendorIdentityOnlyCB newMyCB() {
return new VendorIdentityOnlyCB();
}
// very internal (for suppressing warn about 'Not Use Import')
protected String xabUDT() { return Date.class.getName(); }
protected String xabCQ() { return VendorIdentityOnlyCQ.class.getName(); }
protected String xabLSO() { return LikeSearchOption.class.getName(); }
protected String xabSLCS() { return HpSLCSetupper.class.getName(); }
protected String xabSCP() { return SubQuery.class.getName(); }
}
| apache-2.0 |
robinsteel/Sqawsh | src/acceptancetest/java/applicationdriverlayer/pageobjects/squash/S3ConsistencyHelper.java | 3566 | /**
* Copyright 2015-2016 Robin Steel
*
* 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 applicationdriverlayer.pageobjects.squash;
import java.util.HashMap;
import java.util.Map;
/**
* Acceptance test helper to determine when pages served from S3 are consistent.
*
* <p>S3 has only eventual consistency for ReadAfterUpdate. Yet tests must ensure they are
* seeing the latest 'consistent' version of any page they view - and the S3 consistency
* helper ensures they do.
* <p>A single instance of the helper is shared between all S3 page objects via
* dependency-injection (it is Optional as non-S3 page objects don't need it unless they
* ever navigate to S3 page objects). Whenever a page is mutated in S3, the page's guid
* in the helper's map must be updated. Rather than using the entire page as a 'guid', we
* read a guid embedded within each page by AWS Lambda. Then any subsequent get's of the
* page within that scenario will first load the page normally, and then call the
* isS3PageConsistent() override on the page object. If it is consistent, it will update
* the guid in the map and return true - in which case the load is complete. If it's not
* yet consistent, it will ask the webdriver to do another get _to the current url_ (rather
* than to what getUrl() returns, so e.g. any date query parameters are retained) and then
* call load(false, *) recursively on the base page object. The page object's
* isS3PageConsistent() override should make its decision as follows:
* <ul>
* <li>if there is no guid, it will assume the page is consistent only if it has no bookings (
* pages always start each scenario with no bookings).</li>
* <li>if there is a guid, then the page we're get-ing will either have changed or not, and
* if not, the guid will be the same - so we need to know if we are expecting a changed
* page or not (e.g. we could be returning to the booking page from the reservation page
* either with or without having made a new booking). This information is passed as a
* parameter to isS3PageConsistent.</li>
* </ul>
* <p>We assume the helper will be accessed by only one thread at a time (even when the
* scenario uses multiple webdrivers).
*
* @author robinsteel19@outlook.com (Robin Steel)
*/
public class S3ConsistencyHelper {
private Map<String, String> s3PageGuids;
public S3ConsistencyHelper() {
s3PageGuids = new HashMap<>();
}
/**
* Updates the guid for this page for a given key.
*
* @param key distinguishes multiple pages managed by this page object (e.g. booking pages for different dates).
* @param guid the new guid.
*
* @see SquashBasePage#getCachedWebElementAndGuidKey()
*/
public void updateGuid(String key, String guid) {
s3PageGuids.put(key, guid);
}
/**
* Returns the guid for this page for a given key.
*
* @see SquashBasePage#getCachedWebElementAndGuidKey()
*/
public String getGuid(String key) {
return s3PageGuids.get(key);
}
} | apache-2.0 |
pascalrobert/aribaweb | src/aribaweb/src/main/java/ariba/ui/aribaweb/core/AWBinding.java | 58928 | /*
Copyright 1996-2008 Ariba, 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.
$Id: //ariba/platform/ui/aribaweb/ariba/ui/aribaweb/core/AWBinding.java#48 $
*/
package ariba.ui.aribaweb.core;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import ariba.ui.aribaweb.util.AWBaseObject;
import ariba.ui.aribaweb.util.AWEncodedString;
import ariba.ui.aribaweb.util.AWFormatting;
import ariba.ui.aribaweb.util.AWGenericException;
import ariba.ui.aribaweb.util.AWMultiLocaleResourceManager;
import ariba.ui.aribaweb.util.AWResourceManagerDictionary;
import ariba.ui.aribaweb.util.AWSingleLocaleResourceManager;
import ariba.ui.aribaweb.util.AWUtil;
import ariba.util.core.Assert;
import ariba.util.core.Constants;
import ariba.util.core.Fmt;
import ariba.util.core.MapUtil;
import ariba.util.core.ResourceService;
import ariba.util.core.StringUtil;
import ariba.util.expr.AribaExprEvaluator;
import ariba.util.fieldvalue.Expression;
import ariba.util.fieldvalue.FieldPath;
import ariba.util.fieldvalue.FieldValue;
import ariba.util.fieldvalue.FieldValueAccessor;
final class AWFormattedBinding extends AWVariableBinding
{
private AWVariableBinding _binding;
private AWBinding _formatterBinding;
public void init (String bindingName, AWVariableBinding binding, AWBinding formatterBinding)
{
this.init(bindingName);
_binding = binding;
_formatterBinding = formatterBinding;
}
public boolean isSettableInComponent (Object object)
{
return _binding.isSettableInComponent(object);
}
public Object value (Object object)
{
String formattedString = null;
Object objectValue = _binding.value(object);
if (objectValue != null) {
Object formatter = _formatterBinding.value(object);
formattedString = (formatter == null) ?
AWUtil.toString(objectValue) :
AWFormatting.get(formatter).format(formatter, objectValue);
}
return formattedString;
}
public void setValue (Object value, Object object)
{
Object parsedObject = null;
String stringValue = (String)value;
if (stringValue != null) {
Object formatter = _formatterBinding.value(object);
if (formatter == null) {
parsedObject = stringValue;
}
else try {
parsedObject = AWFormatting.get(formatter).parseObject(formatter, stringValue);
}
catch (RuntimeException runtimeException) {
if (object instanceof AWComponent) {
((AWComponent)object).recordValidationError(runtimeException, this, value);
}
return;
}
}
_binding.setValue(parsedObject, object);
}
protected String bindingDescription ()
{
return StringUtil.strcat(_binding.bindingDescription(), "|", _formatterBinding.bindingDescription());
}
}
final class AWDefaultValueKeyPathBinding extends AWKeyPathBinding
{
private AWBinding _defaultBinding;
public void init (String bindingName, String fieldPathString, AWBinding defaultBinding)
{
super.init(bindingName, fieldPathString);
_defaultBinding = defaultBinding;
}
public Object value (Object object)
{
Object objectValue = super.value(object);
if (objectValue == null) {
objectValue = _defaultBinding.value(object);
}
return objectValue;
}
}
////////////////////////
// AWKeyPathBinding
////////////////////////
class AWKeyPathBinding extends AWVariableBinding
{
// ** Its thread safe to use these globals because they are immutable.
private FieldPath _fieldPath;
public void init (String bindingName, FieldPath fieldPath)
{
this.init(bindingName);
_fieldPath = fieldPath;
}
public void init (String bindingName, String fieldPathString)
{
// Becasue we cache fieldPaths, we don't use the shared pey paths
// since we get better performance from the lookup skipping
// built into FieldPath
FieldPath fieldPath = new FieldPath(fieldPathString);
this.init(bindingName, fieldPath);
}
public boolean isSettableInComponent (Object object)
{
return true;
}
public Object value (Object object)
{
Object objectValue = null;
try {
objectValue = _fieldPath.getFieldValue(object);
}
catch (AWBindingException bindingException) {
throw bindingException;
}
catch (RuntimeException exception) {
String message = formatBindingExceptionMessage(object, _fieldPath);
throw getBindingException(message, exception);
}
if (_isDebuggingEnabled && object instanceof AWComponent) {
AWComponent component = (AWComponent)object;
String awdebugMessage = Fmt.S("%s: %s <== %s (%s%s)", component.name(), bindingName(), bindingDescription(), formatClassNameForObject(objectValue), formatDescriptionForObject(objectValue));
debugString(awdebugMessage);
}
return objectValue;
}
public void setValue (Object value, Object object)
{
if (_isDebuggingEnabled && object instanceof AWComponent) {
AWComponent component = (AWComponent)object;
String awdebugMessage = Fmt.S("%s: %s ==> %s (%s%s)", component.name(), bindingName(), bindingDescription(), formatClassNameForObject(value), formatDescriptionForObject(value));
debugString(awdebugMessage);
}
try {
_fieldPath.setFieldValue(object, value);
}
catch (AWBindingException bindingException) {
throw bindingException;
}
catch (RuntimeException runtimeException) {
String message = formatBindingExceptionMessage(object, _fieldPath);
throw getBindingException(message, runtimeException);
}
}
public String fieldPath ()
{
return _fieldPath.toString();
}
public FieldPath fieldPathObject ()
{
return _fieldPath;
}
public Object fieldPathTargetInComponent (AWComponent component)
{
return component;
}
public String toString ()
{
return StringUtil.strcat(": <AWKeyPathBinding> ", bindingName(), "=\"", bindingDescription(), "\"");
}
protected String bindingDescription ()
{
return StringUtil.strcat("$", _fieldPath.toString());
}
//////////////
// Validation
//////////////
protected void validate (AWValidationContext validationContext, AWComponent component, int bindingDirection)
{
String fieldName = _fieldPath.car();
int missingBindingDirection = -1;
if (_fieldPath.cdr() != null) {
bindingDirection = FieldValue.Getter;
}
FieldValueAccessor fieldValueAccessor = null;
try {
if (bindingDirection == AWBindingApi.Both) {
fieldValueAccessor = FieldValue.get(component).getAccessor(component, fieldName, FieldValue.Setter);
if (fieldValueAccessor == null) {
missingBindingDirection = FieldValue.Setter;
}
fieldValueAccessor = FieldValue.get(component).getAccessor(component, fieldName, FieldValue.Getter);
if (fieldValueAccessor == null) {
// if we're already missing the setter, then set to both
missingBindingDirection =
(missingBindingDirection == FieldValue.Setter) ?
AWBindingApi.Both :
FieldValue.Getter;
}
}
else if (bindingDirection == AWBindingApi.Either) {
try {
fieldValueAccessor = FieldValue.get(component).getAccessor(component, fieldName, FieldValue.Getter);
}
catch (RuntimeException runtimeException) {
// ignore exceptions in getting the Getter and just try to get the Setter
}
if (fieldValueAccessor == null) {
fieldValueAccessor = FieldValue.get(component).getAccessor(component, fieldName, FieldValue.Setter);
}
if (fieldValueAccessor == null) {
missingBindingDirection = AWBindingApi.Either;
}
}
else {
Assert.that(bindingDirection == FieldValue.Getter || bindingDirection == FieldValue.Setter, "Invalid bindingDirection: " + bindingDirection);
fieldValueAccessor = FieldValue.get(component).getAccessor(component, fieldName, bindingDirection);
if (fieldValueAccessor == null) {
missingBindingDirection = bindingDirection;
}
}
} catch (RuntimeException runtimeException) {
String message = formatBindingExceptionMessage(component, _fieldPath);
if (AWBinding.ThrowValidationExceptions) {
throw getBindingException(message,runtimeException);
} else {
String exceptionString = "Exception resolving binding \"" + fieldName + "\": " + runtimeException.toString();
component.componentDefinition().addInvalidValueForBinding(
validationContext, component, bindingName(), exceptionString);
logString(StringUtil.strcat(message, "\n", exceptionString));
}
return;
}
if (fieldValueAccessor == null || missingBindingDirection != -1) {
String message = formatBindingExceptionMessage(component, _fieldPath);
String missingMethod = null;
switch (missingBindingDirection) {
case AWBindingApi.Both:
missingMethod = "both setter and getter";
break;
case FieldValue.Getter:
missingMethod = "getter";
break;
case FieldValue.Setter:
missingMethod = "setter";
break;
case AWBindingApi.Either:
missingMethod = "either setter or getter";
break;
default:
Assert.that(false, Fmt.S("Unknown binding direction %s", missingBindingDirection));
}
String exceptionString =
Fmt.S("Unable to locate %s method(s) or field named \"" + fieldName + "\"", missingMethod);
if (AWBinding.ThrowValidationExceptions) {
try {
throw new RuntimeException(exceptionString);
}
catch (RuntimeException runtimeException) {
throw getBindingException(message,runtimeException);
}
}
else {
component.componentDefinition().addInvalidValueForBinding(
validationContext, component, bindingName(), exceptionString);
logString(StringUtil.strcat(message, "\n", exceptionString));
}
}
}
}
//////////////////////////////
// AWParentKeyPathBinding
//////////////////////////////
final class AWParentKeyPathBinding extends AWVariableBinding
{
private FieldPath DummyFieldPath = new FieldPath("AWParentKeyPathBinding_DUMMY");
private String _fieldPathString;
private String _bindingKey;
private FieldPath _additionalKeyPath;
private AWBinding _defaultBinding;
private FieldPath _primaryBindingFieldPath = DummyFieldPath;
// ** Its thread safe to use these globals because they are immutable.
public void init (String bindingName, String fieldPathString, AWBinding defaultBinding)
{
this.init(bindingName);
// Because we cache fieldPaths, we don't use the shared key paths
// since we get better performance from the lookup skipping
// built into FieldPath
FieldPath fieldPath = new FieldPath(fieldPathString);
_fieldPathString = fieldPathString.intern();
_bindingKey = fieldPath.car().intern();
_additionalKeyPath = fieldPath.cdr();
_defaultBinding = defaultBinding;
}
// todo: make this name more generic (lose "InComponent")
public boolean isSettableInComponent (Object object)
{
// Only supported for AWComponent
AWComponent component = (AWComponent)object;
boolean isSettable = false;
AWBinding binding = component.bindingForName(_bindingKey, true);
if (binding != null) {
isSettable = binding.isSettableInComponent(component.parent());
}
else if (_defaultBinding != null) {
isSettable = _defaultBinding.isSettableInComponent(component);
}
return isSettable;
}
// todo: make this name more generic (lose "InComponent")
protected boolean bindingExistsInParentForSubcomponent (AWComponent component)
{
boolean bindingExists = false;
if (_defaultBinding != null) {
bindingExists = _defaultBinding.bindingExistsInParentForSubcomponent(component);
}
if (!bindingExists) {
bindingExists = primaryBinding(component.parent()) != null;
}
return bindingExists;
}
// takes care of the special case where the parent binding is just a binding and
// continues recursion of debugValue up the parent binding chain. (see AWNLSBinding).
public Object debugValue (Object object)
{
// Only supported for AWComponent
AWComponent component = (AWComponent)object;
AWBinding primaryBinding = primaryBinding(component);
if (primaryBinding == null || _additionalKeyPath != null) {
return value(component);
}
// assume we have a primary binding and no additional key path binding
return primaryBinding.debugValue(component.parent());
}
public Object value (Object object)
{
// ParentKeyPath bindings only work in for AWComponents
AWComponent component = (AWComponent)object;
Object objectValue = null;
AWBinding primaryBinding = primaryBinding(component);
if (primaryBinding == null) {
if (_defaultBinding != null) {
objectValue = _defaultBinding.value(component);
}
}
else {
objectValue = component.valueForBinding(primaryBinding);
if ((_additionalKeyPath != null) && (objectValue != null)) {
try {
objectValue = _additionalKeyPath.getFieldValue(objectValue);
}
catch (AWBindingException bindingException) {
throw bindingException;
}
catch (RuntimeException runtimeException) {
String message = formatBindingExceptionMessage(component, _additionalKeyPath);
throw getBindingException(message, runtimeException);
}
}
if (_isDebuggingEnabled) {
String awdebugMessage = Fmt.S("%s: %s <== %s (%s%s)", component.name(), bindingName(), bindingDescription(), formatClassNameForObject(objectValue), formatDescriptionForObject(objectValue));
debugString(awdebugMessage);
}
}
return objectValue;
}
public void setValue (Object objectValue, Object object)
{
// ParentKeyPath bindings only work in for AWComponents
AWComponent component = (AWComponent)object;
AWBinding primaryBinding = primaryBinding(component);
if (primaryBinding == null) {
if (_defaultBinding != null) {
_defaultBinding.setValue(objectValue, component);
}
}
else {
if (_isDebuggingEnabled) {
String awdebugMessage = Fmt.S("%s: %s ==> %s (%s%s)",
component.name(), bindingName(), bindingDescription(),
formatClassNameForObject(objectValue), formatDescriptionForObject(objectValue));
debugString(awdebugMessage);
}
if (_additionalKeyPath == null) {
component.setValueForBinding(objectValue, primaryBinding);
}
else {
Object primaryBindingValue = component.valueForBinding(primaryBinding);
if (primaryBindingValue != null) {
try {
_additionalKeyPath.setFieldValue(primaryBindingValue, objectValue);
}
catch (AWBindingException bindingException) {
throw bindingException;
}
catch (RuntimeException runtimeException) {
String message = formatBindingExceptionMessage(component, _additionalKeyPath);
throw getBindingException(message, runtimeException);
}
}
}
}
}
private AWBinding primaryBinding (AWComponent component)
{
if (_primaryBindingFieldPath == DummyFieldPath) {
_primaryBindingFieldPath = null;
if (component.useLocalPool()) {
Field bindingField = component.lookupBindingField(_bindingKey);
if (bindingField != null) {
_primaryBindingFieldPath = new FieldPath(bindingField.getName());
}
}
}
AWBinding primaryBinding = null;
if (_primaryBindingFieldPath == null) {
primaryBinding = component.bindingForName(_bindingKey, true);
}
else {
primaryBinding = (AWBinding)_primaryBindingFieldPath.getFieldValue(component);
if (primaryBinding != null) {
if (!primaryBinding.bindingExistsInParentForSubcomponent(component)) {
primaryBinding = null;
}
}
}
return primaryBinding;
}
public String toString ()
{
return StringUtil.strcat("<", getClass().getName(), "> ", bindingName(), "=\"", bindingDescription(), "\"");
}
public String fieldPath ()
{
return _fieldPathString;
}
// todo: make this name more generic (lose "InComponent")
public String effectiveKeyPathInComponent (AWComponent component)
{
String effectiveKeyPath = null;
AWBinding binding = component.bindingForName(_bindingKey, true);
if (binding != null) {
AWComponent parentComponent = component.parent();
effectiveKeyPath = binding.effectiveKeyPathInComponent(parentComponent);
if (_additionalKeyPath != null) {
effectiveKeyPath = StringUtil.strcat(effectiveKeyPath, ".", _additionalKeyPath.toString());
}
}
return effectiveKeyPath;
}
protected String bindingDescription ()
{
String bindingDescription = null;
if (_additionalKeyPath == null) {
bindingDescription = StringUtil.strcat("$^", _bindingKey);
}
else {
bindingDescription = StringUtil.strcat("$^", _bindingKey, ".", _additionalKeyPath.toString());
}
return bindingDescription;
}
}
/////////////////////////
// AWLocalizedBinding -- for the AW's preferred localization scheme
/////////////////////////
final class AWLocalizedBinding extends AWVariableBinding
{
private AWResourceManagerDictionary _localizedStringsHashtable = new AWResourceManagerDictionary();
private String _defaultString;
// need a way to optionally specify the key as part of the binding
// for example foo="$[someKey]this is a string for someKey"
private String _key;
private String _comment;
public void init (String bindingName, String keyString, String defaultString)
{
this.init(bindingName);
_defaultString = defaultString.intern();
int indexOfColon = keyString.indexOf(':');
if (indexOfColon != -1) {
_comment = keyString.substring(indexOfColon).intern();
keyString = keyString.substring(0, indexOfColon);
}
_key = keyString.intern();
}
public boolean isSettableInComponent (Object object)
{
return false;
}
public void setValue (Object value, Object object)
{
throw new AWGenericException(getClass().getName() + ": setValue() not allowed for this type of binding.");
}
public Object value (Object object)
{
// Localized bindings only work in for AWComponents
AWComponent component = (AWComponent)object;
AWSingleLocaleResourceManager resourceManager =
(AWSingleLocaleResourceManager)component.resourceManager();
AWEncodedString localizedString = (AWEncodedString)_localizedStringsHashtable.get(resourceManager);
if (localizedString == null) {
synchronized (this) {
localizedString = (AWEncodedString)_localizedStringsHashtable.get(resourceManager);
if (localizedString == null) {
Map localizedStringsHashtable = AWLocal.loadLocalizedAWLStrings(component);
if (localizedStringsHashtable != null) {
String stringForKey = (String)localizedStringsHashtable.get(_key);
if (stringForKey != null) {
localizedString = AWEncodedString.sharedEncodedString(stringForKey);
}
}
if (localizedString == null) {
String string = resourceManager.pseudoLocalizeUnKeyed(_defaultString);
if (AWLocal.IsDebuggingEnabled) {
localizedString = AWEncodedString.sharedEncodedString(addEmbeddedContextToString(_key, string, component));
}
else {
localizedString = AWEncodedString.sharedEncodedString(string);
}
}
if (!AWConcreteApplication.IsRapidTurnaroundEnabled) {
_localizedStringsHashtable.put(resourceManager, localizedString);
}
}
}
}
return localizedString;
}
private String addEmbeddedContextToString (String key, String value, AWComponent component)
{
String returnVal = StringUtil.strcat(AWUtil.getEmbeddedContextBegin(key, component.namePath()),
value,
AWUtil.getEmbeddedContextEnd());
return returnVal;
}
protected String bindingDescription ()
{
return StringUtil.strcat("$[", ((_key != null) ? _key : ""), ((_comment != null) ? ":" + _comment : ""), "]", _defaultString);
}
}
/////////////////////////
// AWNLSBinding -- for Buyer's traditional localization scheme
/////////////////////////
final class AWNLSBinding extends AWVariableBinding
{
private String _key;
public AWNLSBinding (String bindingName, String keyString)
{
this.init(bindingName);
_key = keyString.intern();
}
public boolean isSettableInComponent (Object object)
{
return false;
}
public void setValue (Object value, Object object)
{
throw new AWGenericException(getClass().getName() + ": setValue() not allowed for this type of binding.");
}
public Object value (Object object)
{
// AWNLSBinding only supported for AWComponent
AWComponent component = (AWComponent)object;
return ResourceService.getService().getLocalizedCompositeKey(_key, component.preferredLocale());
}
protected String bindingDescription ()
{
return _key;
}
public Object debugValue (Object object)
{
return _key;
}
}
/////////////////////////
// AWListBinding -- Static String list
/////////////////////////
final class AWListBinding extends AWVariableBinding
{
private List _list;
public void init (String bindingName, String keyString)
{
this.init(bindingName);
// Crazy way to use Hashtable parser to parse array...
Map map = MapUtil.map();
String mapString = StringUtil.strcat("{m=(", keyString, ");}");
ariba.util.core.MapUtil.fromSerializedString(map, mapString);
_list = (List)map.get("m");
}
public boolean isSettableInComponent (Object object)
{
return false;
}
public void setValue (Object value, Object object)
{
throw new AWGenericException(getClass().getName() + ": setValue() not allowed for this type of binding.");
}
public Object value (Object object)
{
return _list;
}
protected String bindingDescription ()
{
return ("$( list )");
}
}
/////////////////////////
// AWExpressionBinding -- AWExpr expresion
/////////////////////////
final class AWExpressionBinding extends AWVariableBinding implements AWBinding.ExpressionBinding {
private String _expressionString;
private AWBinding _substituteBinding;
private Expression _expression;
public void init (String bindingName, String keyString)
{
this.init(bindingName);
_expressionString = keyString;
}
public boolean isSettableInComponent (Object object)
{
return false;
}
protected void assertExpression ()
{
if (_substituteBinding == null && _expression == null) {
_expression = AribaExprEvaluator.instance().compile(_expressionString);
// print out expression / parse tree
/*
System.out.println("EXPR: " + _expressionString);
((AribaExprEvaluator.Expression)_expression).printExprTree();
*/
}
}
public void setValue (Object value, Object object)
{
assertExpression();
if (_substituteBinding != null) {
_substituteBinding.setValue(value, object);
} else {
((AribaExprEvaluator.Expression)_expression).evaluateSet(object, value, null);
}
}
public Object value (Object object)
{
// Assert.that(_substituteBinding != null, "Attempt to evalute AWExpressionBinding without preparing: %s=%s", bindingName(), bindingDescription());
assertExpression();
if (_substituteBinding != null) {
return _substituteBinding.value(object);
} else {
return _expression.evaluate(object, null);
}
}
protected String bindingDescription ()
{
return "${" + _expressionString + "}";
}
// ExpressionBinding support
public String expressionString ()
{
return _expressionString;
}
public void setSubstituteBinding (AWBinding binding)
{
_substituteBinding = binding;
}
}
/////////////////////////
// AWVariableBinding
/////////////////////////
abstract class AWVariableBinding extends AWBinding
{
// ** Thread Safety Considerations: the timing feature is not thread safe and should not be used with multiple threads.
public boolean isConstantValue ()
{
return false;
}
abstract public boolean isSettableInComponent (Object object);
}
/////////////////////////
// AWClassAccessorBinding
/////////////////////////
final class AWClassAccessorBinding extends AWVariableBinding
{
Class _targetClass;
FieldPath _fieldPath;
public void init (String bindingName, Class targetClass, String fieldPathString)
{
this.init(bindingName);
_targetClass = targetClass;
_fieldPath = new FieldPath(fieldPathString);
}
public boolean isSettableInComponent (Object object)
{
return true;
}
public Object value (Object object)
{
try {
return _fieldPath.getFieldValue(_targetClass);
}
catch (AWBindingException bindingException) {
throw bindingException;
}
catch (RuntimeException runtimeException) {
String message = formatBindingExceptionMessage(object, _fieldPath);
throw getBindingException(message, runtimeException);
}
}
public void setValue (Object value, Object object)
{
try {
_fieldPath.setFieldValue(_targetClass, value);
}
catch (AWBindingException bindingException) {
throw bindingException;
}
catch (RuntimeException runtimeException) {
String message = formatBindingExceptionMessage(object, _fieldPath);
throw getBindingException(message, runtimeException);
}
}
public String fieldPath ()
{
return _fieldPath.toString();
}
public FieldPath fieldPathObject ()
{
return _fieldPath;
}
// todo: make this name more generic (lose "InComponent")
public Object fieldPathTargetInComponent (AWComponent component)
{
return _targetClass;
}
protected String bindingDescription ()
{
return StringUtil.strcat(_targetClass.getName(), ".", _fieldPath.toString());
}
public String effectiveKeyPathInComponent (AWComponent component)
{
return StringUtil.strcat(_targetClass.getName(), ".", _fieldPath.toString());
}
}
/////////////////////////
// AWConstantBinding
/////////////////////////
class AWConstantBinding extends AWBinding
{
private Object _constantObject;
private AWEncodedString _encodedString = AWUtil.UndefinedEncodedString;
// todo: might want to consider creating separate bindings for boolean, string, int
private boolean _booleanValue;
// ** No thread issues here -- _constantObject is immutable.
public void init (String bindingName, Object objectValue)
{
this.init(bindingName);
if (AWBindingNames.awstandalone.equals(objectValue)) {
objectValue = AWBindingNames.awstandalone;
}
else if (AWBindingNames.intType.equals(objectValue)) {
objectValue = AWBindingNames.intType;
}
else if (AWBindingNames.booleanType.equals(objectValue)) {
objectValue = AWBindingNames.booleanType;
}
setConstantObject(objectValue);
_booleanValue = AWBinding.computeBooleanValue(objectValue);
}
protected boolean isDynamicBinding ()
{
return ((_constantObject == null) || (_constantObject == Boolean.TRUE) || (_constantObject == Boolean.FALSE));
}
public void reinit (Object value)
{
setConstantObject(value);
}
protected void setConstantObject (Object objectValue)
{
_constantObject = objectValue instanceof String ? ((String)objectValue).intern() : objectValue;
_encodedString = (_constantObject instanceof AWEncodedString) ? (AWEncodedString)_constantObject : AWUtil.UndefinedEncodedString;
}
public boolean isConstantValue ()
{
return true;
}
public boolean isSettableInComponent (Object object)
{
return false;
}
public Object value (Object object)
{
if (_isDebuggingEnabled && object instanceof AWComponent) {
AWComponent component = (AWComponent)object;
String componentName = (component == null) ? "(null component)" : component.name();
String awdebugMessage = Fmt.S("%s: %s <== constant: (%s%s)", componentName, bindingName(), formatClassNameForObject(_constantObject), formatDescriptionForObject(_constantObject));
debugString(awdebugMessage);
}
return _constantObject;
}
public AWEncodedString encodedStringValue (Object object)
{
if (_encodedString == AWUtil.UndefinedEncodedString) {
_encodedString = super.encodedStringValue(object);
}
return _encodedString;
}
public void setValue (Object value, Object object)
{
throw new AWGenericException("*** Error: attempt to set value on constant binding with value: " + _constantObject);
}
public String toString ()
{
return StringUtil.strcat("<AWConstantBinding> ", bindingName(), "=\"", bindingDescription(), "\"");
}
protected String bindingDescription ()
{
return (_constantObject == null) ? "$null" : _constantObject.toString();
}
public boolean booleanValue (Object object)
{
return _booleanValue;
}
}
/////////////////////////
// AWDynamicConstantBinding
/////////////////////////
final class AWDynamicConstantBinding extends AWConstantBinding
{
private AWBinding _binding;
// Since _binding is used nulled out after the first evaluation,
// we need another reference to the containing binding for
// semantic key generation to work.
private AWBinding _debugBinding;
public void init (String bindingName, AWBinding binding)
{
this.init(bindingName);
_binding = binding;
_debugBinding = binding;
}
public void init (String bindingName, String fieldPathString)
{
AWBinding binding = AWBinding.bindingWithNameAndKeyPath(bindingName, fieldPathString);
this.init(bindingName, binding);
}
protected boolean isDynamicBinding ()
{
return true;
}
public boolean isConstantValue ()
{
return (_binding == null);
}
public Object value (Object object)
{
if (_binding != null) {
Object constantObject = _binding.value(object);
setConstantObject(constantObject);
_binding = null;
}
return super.value(object);
}
public String effectiveKeyPathInComponent (AWComponent component)
{
return _debugBinding.effectiveKeyPathInComponent(component);
}
}
///////////////////////
// AWBooleanNotBinding
///////////////////////
final class AWBooleanNotBinding extends AWVariableBinding
{
private AWBinding _binding;
private AWBinding _defaultBinding;
public void init (String bindingName, AWBinding binding)
{
this.init(bindingName);
_binding = binding;
}
public void init (String bindingName, String fieldPathString, AWBinding defaultBinding)
{
AWBinding binding =
AWBinding.bindingWithNameAndKeyPath(bindingName, fieldPathString);
this.init(bindingName, binding);
_defaultBinding = defaultBinding;
}
protected boolean isDynamicBinding ()
{
return true;
}
public boolean isConstantValue ()
{
return false;
}
public boolean isSettableInComponent (Object object)
{
return false;
}
public Object value (Object object)
{
Object objectValue = _binding.value(object);
// if the object value is null and there is a default binding, then use it
// otherwise, evaluate the binding -- note that a null binding evaluates to false
if (objectValue == null && _defaultBinding != null) {
objectValue = _defaultBinding.value(object);
}
else {
boolean flag = _binding.booleanValue(object);
objectValue = flag ? Boolean.FALSE : Boolean.TRUE;
}
return objectValue;
}
public void setValue (Object value, Object object)
{
Assert.that(false, "unsupported usage of $! operator");
}
protected String bindingDescription ()
{
return "$!" + _binding.bindingDescription();
}
}
/**
Represents a binding between a named property and a constant or dynamic
expression in the context of the parent component.
<p>
Many binding subtypes are supported, including:
<ol>
<li>{@link AWConstantBinding}: e.g.: "10" or "A long string"
<li>{@link AWKeyPathBinding}: e.g.: "$userName" or "$project.costCenter.budget" or "$delete"</li>
<li>{@link AWExpressionBinding}: e.g. '${firstName + " " + lastName}' or '${pageWithName("Page2")}'</li>
<li>{@link AWLocalizedBinding}: e.g. "$[a002]Delete Items"</li>
</ol>
*/
abstract public class AWBinding extends AWBaseObject implements Cloneable
{
// ThrowValidationExceptions is false for now (May 8, 2002) but should be made
// true by default at some point to force the correction of these problems.
public static boolean ThrowValidationExceptions = false;
public static final AWBinding DummyBinding = new AWConstantBinding();
public static final String NullKey = "null";
public static final String TrueKey = "true";
public static final String FalseKey = "false";
protected boolean _isDebuggingEnabled = false;
private AWEncodedString _name;
// ** No thread issues here -- _bindingName is immutable and the flags don't matter.
abstract public boolean isConstantValue ();
abstract public boolean isSettableInComponent (Object object);
abstract protected String bindingDescription ();
// TODO: temporary hack way to make bindingDescription public...
public String _bindingDescription ()
{
return bindingDescription();
}
abstract public Object value (Object object);
abstract public void setValue (Object value, Object object);
public Object debugValue (Object object)
{
return value(object);
}
public void init (String bindingName)
{
this.init();
_name = AWEncodedString.sharedEncodedString(bindingName.intern());
}
protected boolean isDynamicBinding ()
{
return true;
}
public void reinit (Object value)
{
throw new AWGenericException("reinit not supported for: " + getClass().getName() + " " + this);
}
public String bindingName ()
{
return _name == null ? "-unnamed-" : _name.string();
}
public AWEncodedString name ()
{
return _name;
}
public String fieldPath ()
{
return null;
}
public FieldPath fieldPathObject ()
{
return null;
}
public Object fieldPathTargetInComponent (AWComponent component)
{
return null;
}
public String effectiveKeyPathInComponent (AWComponent component)
{
return fieldPath();
}
public void setIsDebuggingEnabled (boolean isDebuggingEnabled)
{
_isDebuggingEnabled = isDebuggingEnabled;
}
public boolean isDebuggingEnabled ()
{
return _isDebuggingEnabled;
}
protected boolean bindingExistsInParentForSubcomponent (AWComponent component)
{
return true;
}
public void setValue (int intValue, Object object)
{
Integer integerValue = Constants.getInteger(intValue);
setValue(integerValue, object);
}
public void setValue (boolean booleanValue, Object object)
{
Boolean booleanObject = booleanValue ? Boolean.TRUE : Boolean.FALSE;
setValue(booleanObject, object);
}
public String stringValue (Object object)
{
Object objectValue = value(object);
return AWUtil.toString(objectValue);
}
public AWEncodedString encodedStringValue (Object object)
{
AWEncodedString encodedString = null;
Object objectValue = value(object);
if ((objectValue != null) && !(objectValue instanceof AWEncodedString)) {
encodedString = AWEncodedString.sharedEncodedString(AWUtil.toString(objectValue));
}
else {
encodedString = (AWEncodedString)objectValue;
}
return encodedString;
}
public static boolean computeBooleanValue (Object value)
{
if (value == null) {
return false;
}
else if (value instanceof Boolean) {
return ((Boolean)value).booleanValue();
}
else if (value instanceof Integer) {
return ((Integer)value).intValue() == 0 ? false : true;
}
else {
return true;
}
}
public boolean booleanValue (Object object)
{
try {
Object value = value(object);
return AWBinding.computeBooleanValue(value);
}
catch (Exception exception) {
String message = formatBindingExceptionMessage(object, fieldPathObject());
throw getBindingException(message, exception);
}
}
public int intValue (Object object)
{
int intValue = 0;
Object value = value(object);
if (value instanceof String) {
intValue = Integer.parseInt((String)value);
}
else if (value instanceof Number) {
intValue = ((Number)value).intValue();
}
else {
String message = Fmt.S(
"%s: attempt to compute intValue for binding not bound to an String or Number."
+ "Component: %s binding: (%s=\"%s\")",
getClass().getName(), object, bindingName(), bindingDescription());
throw new AWGenericException(message);
}
return intValue;
}
public double doubleValue (Object object)
{
double doubleValue = 0;
Object value = value(object);
if (value instanceof String) {
doubleValue = Double.parseDouble((String)value);
}
else if (value instanceof Number) {
doubleValue = ((Number)value).doubleValue();
}
else {
String message = Fmt.S(
"%s: attempt to compute doubleValue for binding not bound to an String or Number."
+ "Component: %s binding: (%s=\"%s\")",
getClass().getName(), object, bindingName(), bindingDescription());
throw new AWGenericException(message);
}
return doubleValue;
}
//////////////////
// Creation
//////////////////
private static String classNameForKeyPath (String fieldPathString)
{
String targetClassName = null;
int lastDotIndex = fieldPathString.lastIndexOf('.');
if (lastDotIndex != -1) {
int penultimateDotIndex = fieldPathString.lastIndexOf('.', lastDotIndex - 1);
boolean isUpperCase = Character.isUpperCase(fieldPathString.charAt(penultimateDotIndex + 1));
if (isUpperCase) {
targetClassName = fieldPathString.substring(0, lastDotIndex);
boolean isJavaIdentifier = Character.isJavaIdentifierStart(targetClassName.charAt(0));
if (isJavaIdentifier) {
AWMultiLocaleResourceManager resourceManager = AWConcreteApplication.SharedInstance.resourceManager();
Class targetClass = resourceManager.classForName(targetClassName);
if (targetClass == null) {
targetClassName = classNameForKeyPath(targetClassName);
}
}
}
else {
String substring = fieldPathString.substring(0, lastDotIndex);
targetClassName = classNameForKeyPath(substring);
}
}
return targetClassName;
}
/**
Grammar (with the leading $ stripped):
1) keypath = localized | constant | variable ("|" formatter) | ariba_expression
2) localized = "["key"]"
3) variable = field (":" default)
4) default = "$"keypath | literal
5) formatter = "$"field
6) constant = boolean | "="field | null
7) boolean = true | false
8) field = booleanNot | "^" parent binding name | instance accessor | class accessor
9) booleanNot = "!" field
*/
public static AWBinding bindingWithNameAndKeyPath (String bindingName, String keyPathString)
{
AWBinding binding = null;
char firstChar = keyPathString.charAt(0);
if (firstChar == '[') {
int indexOfRightBrace = keyPathString.indexOf(']');
String keyString = keyPathString.substring(1, indexOfRightBrace);
binding = new AWLocalizedBinding();
((AWLocalizedBinding)binding).init(bindingName, keyString, keyPathString.substring(indexOfRightBrace + 1));
}
else if (firstChar == '(') {
int indexOfRightBrace = keyPathString.indexOf(')');
String listString = keyPathString.substring(1, indexOfRightBrace);
binding = new AWListBinding();
((AWListBinding)binding).init(bindingName, listString);
}
else if (firstChar == ':') { // Deprecated
String expressionString = keyPathString.substring(1);
binding = new AWExpressionBinding();
((AWExpressionBinding)binding).init(bindingName, expressionString);
}
else if (firstChar == '{') {
String expressionString = keyPathString.substring(1).trim();
Assert.that(expressionString.endsWith("}"), "Expression binding must end with '}'");
expressionString = expressionString.substring(0,expressionString.length()-1);
binding = new AWExpressionBinding();
((AWExpressionBinding)binding).init(bindingName, expressionString);
} else {
binding = constantBinding(bindingName, keyPathString);
}
if (binding == null) {
String variableString = keyPathString;
AWBinding formatterBinding = null;
int pipeIndex = keyPathString.indexOf('|');
if (pipeIndex != -1) {
variableString = keyPathString.substring(0, pipeIndex);
String formatterString = keyPathString.substring(pipeIndex + 1);
formatterBinding = formatterBinding(bindingName, formatterString);
}
AWVariableBinding variableBinding = variableBinding(bindingName, variableString);
if (formatterBinding != null) {
binding = new AWFormattedBinding();
((AWFormattedBinding)binding).init(bindingName, variableBinding, formatterBinding);
}
else {
binding = variableBinding;
}
}
return binding;
}
/**
See 5) from above
*/
private static AWBinding formatterBinding (String bindingName, String formatterString)
{
if (formatterString.length() < 2) {
throw new AWGenericException("invalid formatter binding: " + formatterString);
}
char firstChar = formatterString.charAt(0);
if (firstChar == '$') {
return fieldBinding(bindingName, formatterString.substring(1), null);
}
else if (firstChar == '^') {
// we allow ^ without $
return fieldBinding(bindingName, formatterString, null);
}
else {
throw new AWGenericException("invalid formatter binding: " + formatterString);
}
}
/**
See 4) from above
*/
private static AWVariableBinding variableBinding (String bindingName, String variableString)
{
int colonIndex = variableString.indexOf(':');
String fieldPathString = variableString;
AWBinding defaultBinding = null;
if (colonIndex > 0) {
fieldPathString = variableString.substring(0, colonIndex);
String defaultString = variableString.substring(colonIndex + 1);
defaultBinding = defaultBinding(bindingName, defaultString);
}
return (AWVariableBinding)fieldBinding(bindingName, fieldPathString, defaultBinding);
}
/**
See 5) from above
*/
private static AWBinding defaultBinding (String bindingName, String defaultString)
{
char firstChar = defaultString.charAt(0);
AWBinding defaultBinding = null;
if (firstChar == '$') {
return bindingWithNameAndKeyPath(bindingName, defaultString.substring(1));
}
else if (firstChar == '^') {
// we allow ^ without $
// recursion
defaultBinding = variableBinding(bindingName, defaultString);
}
else {
defaultBinding = bindingWithNameAndConstant(bindingName, defaultString);
}
return defaultBinding;
}
/**
See 6) from above
*/
private static AWBinding constantBinding (String bindingName, String constantString)
{
AWBinding constantBinding = null;
if (constantString.length() < 2) {
throw new AWGenericException("invalid constant binding: " + constantString);
}
char firstChar = constantString.charAt(0);
if (constantString.equals(TrueKey) || constantString.equals(FalseKey)) {
Boolean booleanObject = Boolean.valueOf(constantString);
constantBinding = new AWConstantBinding();
((AWConstantBinding)constantBinding).init(bindingName, booleanObject);
}
else if (constantString.equals(NullKey)) {
constantBinding = new AWConstantBinding();
((AWConstantBinding)constantBinding).init(bindingName, null);
}
else if (firstChar == '=') {
constantBinding = new AWDynamicConstantBinding();
((AWDynamicConstantBinding)constantBinding).init(bindingName, constantString.substring(1));
}
return constantBinding;
}
/**
See 8) from above
*/
public static AWBinding fieldBinding (String bindingName, String fieldPathString, AWBinding defaultBinding)
{
if (StringUtil.nullOrEmptyOrBlankString(fieldPathString)) {
throw new AWGenericException("invalid field binding: " + fieldPathString);
}
AWBinding fieldBinding = null;
char firstChar = fieldPathString.charAt(0);
if (firstChar == '!') {
fieldBinding = new AWBooleanNotBinding();
((AWBooleanNotBinding)fieldBinding).init(bindingName, fieldPathString.substring(1), defaultBinding);
}
else if (firstChar == '^') {
fieldBinding = new AWParentKeyPathBinding();
((AWParentKeyPathBinding)fieldBinding).init(bindingName, fieldPathString.substring(1), defaultBinding);
}
else {
String targetClassName = classNameForKeyPath(fieldPathString);
if (targetClassName != null) {
int targetClassNameLength = targetClassName.length();
String subsequentKeyPath = fieldPathString.substring(targetClassNameLength + 1);
Class targetClass = AWUtil.classForName(targetClassName);
fieldBinding =
bindingWithNameTargetClassAndKeyPath(bindingName, targetClass, subsequentKeyPath);
}
else if (defaultBinding == null) {
fieldBinding= new AWKeyPathBinding();
((AWKeyPathBinding)fieldBinding).init(bindingName, fieldPathString);
}
else {
fieldBinding= new AWDefaultValueKeyPathBinding();
((AWDefaultValueKeyPathBinding)fieldBinding).init(bindingName, fieldPathString, defaultBinding);
}
}
return fieldBinding;
}
public static AWBinding bindingWithNameTargetClassAndKeyPath (String bindingName, Class targetClass, String fieldPathString)
{
AWClassAccessorBinding classAccessorBinding = new AWClassAccessorBinding();
classAccessorBinding.init(bindingName, targetClass, fieldPathString);
return classAccessorBinding;
}
public static AWBinding bindingWithNameAndConstant (String bindingName, Object constantObject)
{
AWConstantBinding constantBinding = new AWConstantBinding();
constantBinding.init(bindingName, constantObject);
return constantBinding;
}
public static AWBinding bindingWithNameAndNLSKey (String bindingName, String key)
{
return new AWNLSBinding(bindingName, key);
}
protected String formatClassNameForObject (Object objectValue)
{
return (objectValue == null) ? "" : StringUtil.strcat(objectValue.getClass().getName(), ": ");
}
protected String formatDescriptionForObject (Object objectValue)
{
String formattedDescription = "null";
if (objectValue != null) {
formattedDescription = (objectValue instanceof String) ? StringUtil.strcat("\"", objectValue.toString(), "\"") : objectValue.toString();
}
return formattedDescription;
}
protected String keyValuePairDescription ()
{
return StringUtil.strcat(bindingName(), "=\"", bindingDescription(), "\"");
}
/////////////////
// Binding Dict
/////////////////
abstract public static class NameFilter
{
abstract public String translate (String orig);
}
public static AWBindingDictionary bindingsDictionary (Map bindingsHashtable, NameFilter filter)
{
// This is provided to allow users of AWIncludeComponent's awbindingsDictionary to
// convert a Map of AWBindings to an AWBindingDictionary with uniqued keys.
// (Use LinkedHashMap to keep bindings in original order)
Map uniquedHashtable = new LinkedHashMap(bindingsHashtable.size());
if (!bindingsHashtable.isEmpty()) {
Iterator bindingEnumerator = bindingsHashtable.values().iterator();
while (bindingEnumerator.hasNext()) {
AWBinding currentBinding = (AWBinding)bindingEnumerator.next();
String uniqueString = currentBinding.bindingName();
if (filter != null) uniqueString = filter.translate(uniqueString);
uniquedHashtable.put(uniqueString, currentBinding);
}
}
return new AWBindingDictionary(uniquedHashtable);
}
public static AWBindingDictionary bindingsDictionary (Map bindingsHashtable)
{
return bindingsDictionary(bindingsHashtable, null);
}
public static boolean hasDynamicBindings (Map bindingsHashtable)
{
boolean hasDynamicBindings = false;
if (!bindingsHashtable.isEmpty()) {
Iterator associationIterator = bindingsHashtable.values().iterator();
while (associationIterator.hasNext()) {
AWBinding currentBinding = (AWBinding)associationIterator.next();
if (currentBinding.isDynamicBinding()) {
hasDynamicBindings = true;
break;
}
}
}
return hasDynamicBindings;
}
protected Object clone ()
{
Object clonedObject = null;
try {
clonedObject = super.clone();
}
catch (CloneNotSupportedException cloneNotSupportedException) {
throw new AWGenericException(cloneNotSupportedException);
}
return clonedObject;
}
protected String formatBindingExceptionMessage (Object object, FieldPath fieldPath)
{
String message = null;
if (object instanceof AWComponent) {
AWComponent component = (AWComponent)object;
message = Fmt.S("The following exception occurred while evaluating fieldpath: %s, Component: %s",
toString(), component.toString());
}
else {
message = Fmt.S("The following exception occurred while evaluating fieldpath: %s\n", fieldPath);
}
return message;
}
protected void validate (AWValidationContext validationContext, AWComponent component, int bindingDirection)
{
// no-op as default
}
protected void validate (AWValidationContext validationContext, AWComponentDefinition componentDefinition)
{
// no-op as default
}
protected void validate (AWValidationContext validationContext,
AWComponent component, AWComponentDefinition componentDefinition)
{
// This must check to make sure binding name is valid as per the componentDefinition
// and that the binding is a legal binding in the component.
// For now, I'll just make sure the binding is legal in the current component.
// component is the component which contains the element that has the binding
// component definition is the definition of the element that has the binding
int bindingDirection = AWBindingApi.Either;
AWApi componentApi = componentDefinition.componentApi();
if (componentApi != null) {
AWBindingApi bindingApi = componentApi.getBindingApi(bindingName());
if (bindingApi != null) {
// catch in case they failed to specify a "direction" on their <binding> tag
try {
bindingDirection = bindingApi.direction();
} catch (RuntimeException runtimeException) {
componentDefinition.addInvalidValueForBinding(validationContext, component, "direction", "binding tag: missing or invalid 'direction' attribute");
}
}
}
// right side validations
validate(validationContext, component, bindingDirection);
validate(validationContext, componentDefinition);
}
protected final AWGenericException getBindingException (String message, Exception exception)
{
AWGenericException wrappedException = null;
if (exception instanceof AWGenericException) {
wrappedException = (AWGenericException)exception;
wrappedException.addMessage(message);
}
else {
wrappedException = new AWBindingException(message, exception);
}
return wrappedException;
}
public final class AWBindingException extends AWGenericException
{
public AWBindingException (String message, Exception exception)
{
super(message, exception);
}
}
public interface ExpressionBinding {
public String expressionString ();
public void setSubstituteBinding (AWBinding binding);
}
}
| apache-2.0 |
nablarch/nablarch-core-dataformat | src/test/java/nablarch/core/dataformat/JsonDataBuilderTest.java | 74717 | package nablarch.core.dataformat;
import nablarch.core.dataformat.convertor.JsonDataConvertorFactory;
import nablarch.core.dataformat.convertor.JsonDataConvertorSetting;
import nablarch.core.dataformat.convertor.datatype.CharacterStreamDataString;
import nablarch.core.dataformat.convertor.datatype.DataType;
import nablarch.core.dataformat.convertor.datatype.JsonString;
import nablarch.core.dataformat.convertor.value.ValueConvertor;
import nablarch.core.dataformat.convertor.value.ValueConvertorSupport;
import nablarch.core.repository.ObjectLoader;
import nablarch.core.repository.SystemRepository;
import nablarch.core.util.map.CaseInsensitiveMap;
import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.skyscreamer.jsonassert.JSONAssert;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.hamcrest.Matchers.containsString;
/**
* {@link JsonDataParser}のテストを行います。
*
* @author TIS
*/
public class JsonDataBuilderTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Rule
public ExpectedException exception = ExpectedException.none();
/** テスト対象 */
private JsonDataBuilder sut = new JsonDataBuilder();
@After
public void tearDown() throws Exception {
SystemRepository.clear();
}
@Test
public void 必須項目に値が設定されたJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key\":\"value\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 必須項目に値が設定されていないためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("Field key is required"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>();
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 任意項目に値が設定されたJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key\":\"value\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 任意項目に値が設定されていないJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>();
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
JSONAssert.assertEquals("{}", actual.toString("utf-8"), true);
}
@Test
public void 子要素の必須項目に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent OB",
"",
"[parent]",
"1 child X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent.child", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":{" +
" \"child\":\"value\"" +
" }" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 子要素の必須項目に値が設定されていないためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("parent,Field child is required"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent OB",
"",
"[parent]",
"1 child X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 必須子要素に値が設定されていないためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("Field parent is required"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent OB",
"",
"[parent]",
"1 child X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>();
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 子要素の任意項目に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent OB",
"",
"[parent]",
"1 child [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent.child", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":{" +
" \"child\":\"value\"" +
" }" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 子要素の任意項目に値が設定されていないJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent OB",
"",
"[parent]",
"1 child [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":{}" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 必須配列に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 array [1..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("array", new String[]{"value1", "value2", "value3"});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"array\":[" +
" \"value1\"," +
" \"value2\"," +
" \"value3\"" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 必須配列に値が設定されていないためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("FieldName=array:MinCount=1:MaxCount=10:Actual=0"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 array [1..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>();
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 任意配列に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 array [0..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("array", new String[]{"value1", "value2", "value3"});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"array\":[" +
" \"value1\"," +
" \"value2\"," +
" \"value3\"" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 任意配列に値が設定されていないJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 array [0..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>();
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
JSONAssert.assertEquals("{}", actual.toString("utf-8"), true);
}
@Test
public void 配列内の必須配列に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child [1..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child", new String[]{"value1", "value2", "value3"});
put("parent[1].child", new String[]{"value4", "value5", "value6"});
put("parent[2].child", new String[]{"value7", "value8", "value9"});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":[" +
" {" +
" \"child\":[" +
" \"value1\"," +
" \"value2\"," +
" \"value3\"" +
" ]" +
" }," +
" {" +
" \"child\":[" +
" \"value4\"," +
" \"value5\"," +
" \"value6\"" +
" ]" +
" }," +
" {" +
" \"child\":[" +
" \"value7\"," +
" \"value8\"," +
" \"value9\"" +
" ]" +
" }" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 配列内の必須配列に値が設定されていないためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(containsString("FieldName=child:MinCount=1:MaxCount=10:Actual=0"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child [1..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child", new String[]{});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 配列内の任意配列に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child [0..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child", new String[]{"value1", "value2", "value3"});
put("parent[1].child", new String[]{"value4", "value5", "value6"});
put("parent[2].child", new String[]{"value7", "value8", "value9"});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":[" +
" {" +
" \"child\":[" +
" \"value1\"," +
" \"value2\"," +
" \"value3\"" +
" ]" +
" }," +
" {" +
" \"child\":[" +
" \"value4\"," +
" \"value5\"," +
" \"value6\"" +
" ]" +
" }," +
" {" +
" \"child\":[" +
" \"value7\"," +
" \"value8\"," +
" \"value9\"" +
" ]" +
" }" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 配列内の任意配列に値が設定されていないJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child [0..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child", new String[]{});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
JSONAssert.assertEquals("{}", actual.toString("utf-8"), true);
}
@Test
public void 必須配列と必須項目に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key1 [1..10] X",
"2 key2 X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key1", new String[]{"value1", "value2"});
put("key2", "value3");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key1\":[" +
" \"value1\"," +
" \"value2\"" +
" ]," +
" \"key2\":\"value3\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 必須配列と必須項目に値が設定されていないためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("FieldName=key1:MinCount=1:MaxCount=10:Actual=0"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key1 [1..10] X",
"2 key2 X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key1", new String[]{});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 任意配列と任意項目に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key1 [0..10] X",
"2 key2 [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key1", new String[]{"value1", "value2"});
put("key2", "value3");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key1\":[" +
" \"value1\"," +
" \"value2\"" +
" ]," +
" \"key2\":\"value3\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 任意配列と任意項目に値が設定されていないJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key1 [0..10] X",
"2 key2 [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key1", new String[]{});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
JSONAssert.assertEquals("{}", actual.toString("utf-8"), true);
}
@Test
public void 子要素の必須配列に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent OB",
"",
"[parent]",
"1 child [1..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent.child", new String[]{"value1", "value2", "value3"});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":{" +
" \"child\":[" +
" \"value1\"," +
" \"value2\"," +
" \"value3\"" +
" ]" +
" }" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 子要素の必須配列に値が設定されていないためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("parent,FieldName=child:MinCount=1:MaxCount=10:Actual=0"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent OB",
"",
"[parent]",
"1 child [1..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent.child", new String[]{});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 子要素の任意配列に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent OB",
"",
"[parent]",
"1 child [0..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent.child", new String[]{"value1", "value2", "value3"});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":{" +
" \"child\":[" +
" \"value1\"," +
" \"value2\"," +
" \"value3\"" +
" ]" +
" }" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 子要素の任意配列に値が設定されていないJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent OB",
"",
"[parent]",
"1 child [0..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent.child", new String[]{});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":{}" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void オブジェクト配列の必須項目に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child1 X",
"2 child2 X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child1", "value1");
put("parent[1].child1", "value2");
put("parent[2].child1", "value3");
put("parent[0].child2", "value4");
put("parent[1].child2", "value5");
put("parent[2].child2", "value6");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":[" +
" {" +
" \"child1\":\"value1\"," +
" \"child2\":\"value4\"" +
" }," +
" {" +
" \"child1\":\"value2\"," +
" \"child2\":\"value5\"" +
" }," +
" {" +
" \"child1\":\"value3\"," +
" \"child2\":\"value6\"" +
" }" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Ignore("オブジェクト配列内の項目に対する必須チェックが実施されない不具合により、このテストは落ちる")
@Test
public void オブジェクト配列の必須項目に値が設定されていないためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("parent[0],Field child1 is required"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child1 X",
"2 child2 X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child2", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void オブジェクト配列の任意項目に値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child1 [0..1] X",
"2 child2 [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child1", "value1");
put("parent[1].child1", "value2");
put("parent[2].child1", "value3");
put("parent[0].child2", "value4");
put("parent[1].child2", "value5");
put("parent[2].child2", "value6");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":[" +
" {" +
" \"child1\":\"value1\"," +
" \"child2\":\"value4\"" +
" }," +
" {" +
" \"child1\":\"value2\"," +
" \"child2\":\"value5\"" +
" }," +
" {" +
" \"child1\":\"value3\"," +
" \"child2\":\"value6\"" +
" }" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void オブジェクト配列の任意項目に値が設定されていないJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child1 [0..1] X",
"2 child2 [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child2", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":[" +
" {" +
" \"child2\":\"value\"" +
" }" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void オブジェクト配列に値が設定されていないJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child1 [0..1] X",
"2 child2 [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>();
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
JSONAssert.assertEquals("{}", actual.toString("utf-8"), true);
}
@Test
public void フォーマット定義されていない項目はJSONに出力されないこと() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", "value1");
put("undefined", "value2");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key\":\"value1\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 配列の要素数が超過しているためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("FieldName=array:MinCount=1:MaxCount=3:Actual=4"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 array [1..3] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("array", new String[]{"value1", "value2", "value3", "value4"});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 項目名が重複しているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent1 OB",
"2 parent2 OB",
"3 child X",
"",
"[parent1]",
"1 child X",
"",
"[parent2]",
"1 child X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("child", "value1");
put("parent1.child", "value2");
put("parent2.child", "value3");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"child\":\"value1\"," +
" \"parent1\":{" +
" \"child\":\"value2\"" +
" }," +
" \"parent2\":{" +
" \"child\":\"value3\"" +
" }" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 各フィールドタイプを全て使用できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 type1 X",
"2 type2 N",
"3 type3 XN",
"4 type4 X9",
"5 type5 SX9",
"6 type6 BL",
"7 type7 OB",
"",
"[type7]",
"1 type1 X",
"2 type2 N",
"3 type3 XN",
"4 type4 X9",
"5 type5 SX9",
"6 type6 BL"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("type1", "value1");
put("type2", "value2");
put("type3", "value3");
put("type4", "value4");
put("type5", "value5");
put("type6", "value6");
put("type7.type1", "value1");
put("type7.type2", "value2");
put("type7.type3", "value3");
put("type7.type4", "value4");
put("type7.type5", "value5");
put("type7.type6", "value6");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"type1\":\"value1\"," +
" \"type2\":\"value2\"," +
" \"type3\":\"value3\"," +
" \"type4\":\"value4\"," +
" \"type5\":\"value5\"," +
" \"type6\":\"value6\"," +
" \"type7\":{" +
" \"type1\":\"value1\"," +
" \"type2\":\"value2\"," +
" \"type3\":\"value3\"," +
" \"type4\":\"value4\"," +
" \"type5\":\"value5\"," +
" \"type6\":\"value6\"" +
" }" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 各フィールドタイプがnullの場合に全てnullで出力されること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 type1 [0..1] X",
"2 type2 [0..1] N",
"3 type3 [0..1] XN",
"4 type4 [0..1] X9",
"5 type5 [0..1] SX9",
"6 type6 [0..1] BL",
"7 type7 [0..1] OB",
"8 type8 [0..1] OB",
"",
"[type7]",
"1 type1 [0..1] X",
"2 type2 [0..1] N",
"3 type3 [0..1] XN",
"4 type4 [0..1] X9",
"5 type5 [0..1] SX9",
"6 type6 [0..1] BL",
"",
"[type8]",
"1 type1 [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("type1", null);
put("type2", null);
put("type3", null);
put("type4", null);
put("type5", null);
put("type6", null);
put("type7.type1", null);
put("type7.type2", null);
put("type7.type3", null);
put("type7.type4", null);
put("type7.type5", null);
put("type7.type6", null);
put("type8", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"type1\":null," +
" \"type2\":null," +
" \"type3\":null," +
" \"type4\":null," +
" \"type5\":null," +
" \"type6\":null," +
" \"type7\":{" +
" \"type1\":null," +
" \"type2\":null," +
" \"type3\":null," +
" \"type4\":null," +
" \"type5\":null," +
" \"type6\":null" +
" }," +
" \"type8\":null" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void numberコンバータを使用できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 number X number"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("number", 123456);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"number\":\"123456\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void numberコンバータでnullを使用できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 number [0..1] X number"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("number", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"number\":null" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void numberコンバータで符号付き数値の場合に型変換に失敗すること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("invalid parameter format was specified."));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 number X number"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("number", -123456);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void signed_numberコンバータを使用できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 number X signed_number"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("number", -123456);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"number\":\"-123456\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void signed_numberコンバータでnullを使用できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 number [0..1] X signed_number"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("number", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"number\":null" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void signed_numberコンバータで文字列の場合にエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("invalid parameter format was specified."));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 number SX9 signed_number"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("number", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void replacementコンバータで置換されること() throws Exception {
// 寄せ字用のコンポーネント定義
SystemRepository.load(new ObjectLoader() {
@Override
public Map<String, Object> load() {
return new HashMap<String, Object>() {{
CharacterReplacementConfig config = new CharacterReplacementConfig();
config.setTypeName("type");
config.setFilePath("classpath:nablarch/core/dataformat/replacement.properties");
config.setEncoding("UTF-8");
CharacterReplacementManager characterReplacementManager = new CharacterReplacementManager();
characterReplacementManager.setConfigList(Arrays.asList(config));
characterReplacementManager.initialize();
put("characterReplacementManager", characterReplacementManager);
}};
}
});
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key X replacement(\"type\")"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", "髙﨑唖");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key\":\"高崎■\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void replacementコンバータでnullが使用できること() throws Exception {
// 寄せ字用のコンポーネント定義
SystemRepository.load(new ObjectLoader() {
@Override
public Map<String, Object> load() {
return new HashMap<String, Object>() {{
CharacterReplacementConfig config = new CharacterReplacementConfig();
config.setTypeName("type");
config.setFilePath("classpath:nablarch/core/dataformat/replacement.properties");
config.setEncoding("UTF-8");
CharacterReplacementManager characterReplacementManager = new CharacterReplacementManager();
characterReplacementManager.setConfigList(Arrays.asList(config));
characterReplacementManager.initialize();
put("characterReplacementManager", characterReplacementManager);
}};
}
});
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key [0..1] X replacement(\"type\")"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key\":null" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 独自コンバータが適用されること() throws Exception {
SystemRepository.load(new ObjectLoader() {
@Override
public Map<String, Object> load() {
return new HashMap<String, Object>() {{
JsonDataConvertorSetting setting = new JsonDataConvertorSetting();
setting.setJsonDataConvertorFactory(new JsonDataConvertorFactory() {
protected Map<String, Class<?>> getDefaultConvertorTable() {
final Map<String, Class<?>> defaultConvertorTable = new CaseInsensitiveMap<Class<?>>(
new ConcurrentHashMap<String, Class<?>>(super.getDefaultConvertorTable()));
defaultConvertorTable.put("custom", CustomValueConvertor.class);
return Collections.unmodifiableMap(defaultConvertorTable);
}
});
put("jsonDataConvertorSetting", setting);
}};
}
});
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key X custom"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key\":\"custom\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 独自フィールドタイプが適用されること() throws Exception {
SystemRepository.load(new ObjectLoader() {
@Override
public Map<String, Object> load() {
return new HashMap<String, Object>() {{
JsonDataConvertorSetting setting = new JsonDataConvertorSetting();
setting.setJsonDataConvertorFactory(new JsonDataConvertorFactory() {
protected Map<String, Class<?>> getDefaultConvertorTable() {
final Map<String, Class<?>> defaultConvertorTable = new CaseInsensitiveMap<Class<?>>(
new ConcurrentHashMap<String, Class<?>>(super.getDefaultConvertorTable()));
defaultConvertorTable.put("CM", CustomDataType.class);
return Collections.unmodifiableMap(defaultConvertorTable);
}
});
put("jsonDataConvertorSetting", setting);
}};
}
});
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key CM"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key\":\"custom\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 不正なフィールドタイプを指定した場合にエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("Invalid data type definition."));
SystemRepository.load(new ObjectLoader() {
@Override
public Map<String, Object> load() {
return new HashMap<String, Object>() {{
JsonDataConvertorSetting setting = new JsonDataConvertorSetting();
setting.setJsonDataConvertorFactory(new JsonDataConvertorFactory() {
protected Map<String, Class<?>> getDefaultConvertorTable() {
final Map<String, Class<?>> defaultConvertorTable = new CaseInsensitiveMap<Class<?>>(
new ConcurrentHashMap<String, Class<?>>(super.getDefaultConvertorTable()));
defaultConvertorTable.put("CM", InvalidDataType.class);
return Collections.unmodifiableMap(defaultConvertorTable);
}
});
put("jsonDataConvertorSetting", setting);
}};
}
});
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key CM"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 必須項目にnullが設定されているためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("key is required"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 任意項目にnullが設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key\":null" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 必須配列にnullが設定されているためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("FieldName=key:MinCount=1:MaxCount=10:Actual=0"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key [1..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 必須配列の要素にnullが設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key [1..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", new String[]{null});
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key\": [null]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 任意配列にnullが設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key [0..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key\":null" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void オブジェクトの必須項目にnullが設定されているためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("BaseKey = parent,Field child is required"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..1] OB",
"",
"[parent]",
"1 child X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent.child", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void オブジェクトの任意項目にnullが設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..1] OB",
"",
"[parent]",
"1 child [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent.child", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":{" +
" \"child\":null" +
" }" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void オブジェクトの必須配列にnullが設定されているためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("BaseKey = parent,FieldName=child:MinCount=1:MaxCount=10:Actual=0"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..1] OB",
"",
"[parent]",
"1 child [1..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent.child", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void オブジェクトの任意配列にnullが設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..1] OB",
"",
"[parent]",
"1 child [0..10] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent.child", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":{" +
" \"child\":null" +
" }" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 必須オブジェクト配列にnullが設定されているためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("FieldName=parent:MinCount=1:MaxCount=10:Actual=0"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [1..10] OB",
"",
"[parent]",
"1 child X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void 任意オブジェクト配列にnullが設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
JSONAssert.assertEquals("{}", actual.toString("utf-8"), true);
}
@Ignore("オブジェクト配列内の項目に対する必須チェックが実施されない不具合により、このテストは落ちる")
@Test
public void オブジェクト配列内の必須項目にnullが設定されているためエラーとなること() throws Exception {
exception.expect(InvalidDataFormatException.class);
exception.expectMessage(CoreMatchers.containsString("BaseKey = parent[0],Field child is required"));
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [1..10] OB",
"",
"[parent]",
"1 child X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
}
@Test
public void オブジェクト配列内の任意項目にnullが設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":[" +
" {" +
" \"child\":null" +
" }" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 子要素がオブジェクトで孫要素にのみ値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child [0..1] OB",
"",
"[child]",
"1 key [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child.key", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":[" +
" {" +
" \"child\":{" +
" \"key\":\"value\"" +
" }" +
" }" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 子要素がオブジェクトで孫要素にのみnullが設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child [0..1] OB",
"",
"[child]",
"1 key [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child.key", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":[" +
" {" +
" \"child\":{" +
" \"key\":null" +
" }" +
" }" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 子要素がオブジェクト配列で孫要素にのみ値が設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child [0..10] OB",
"",
"[child]",
"1 key [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child[0].key", "value");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":[" +
" {" +
" \"child\":[" +
" {" +
" \"key\":\"value\"" +
" }" +
" ]" +
" }" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 子要素がオブジェクト配列で孫要素にのみnullが設定されているJSONを出力できること() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 parent [0..10] OB",
"",
"[parent]",
"1 child [0..10] OB",
"",
"[child]",
"1 key [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("parent[0].child[0].key", null);
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"parent\":[" +
" {" +
" \"child\":[" +
" {" +
" \"key\":null" +
" }" +
" ]" +
" }" +
" ]" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
@Test
public void 任意項目が出力されない場合に余計なカンマがJSONに出力されないこと() throws Exception {
// フォーマット定義
LayoutDefinition definition = createLayoutDefinition(
"file-type: \"JSON\"",
"text-encoding: \"UTF-8\"",
"[root]",
"1 key1 [0..1] X",
"2 key2 [0..1] X",
"3 key3 [0..1] X"
);
// MAP
Map<String, Object> map = new HashMap<String, Object>() {{
put("key1", "value1");
put("key2", "value2");
}};
// テスト実行
ByteArrayOutputStream actual = new ByteArrayOutputStream();
sut.buildData(map, definition, actual);
// 検証
String expected = "{" +
" \"key1\":\"value1\"," +
" \"key2\":\"value2\"" +
"}";
JSONAssert.assertEquals(expected, actual.toString("utf-8"), true);
}
private LayoutDefinition createLayoutDefinition(String... records) throws Exception {
File file = folder.newFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
for (String record : records) {
writer.write(record);
writer.newLine();
}
writer.close();
LayoutDefinition definition = new LayoutFileParser(file.getPath()).parse();
DataRecordFormatter formatter = new JsonDataRecordFormatter();
formatter.setDefinition(definition);
formatter.initialize();
return definition;
}
/**
* カスタムの{@link ValueConvertor}実装クラス。
*/
public static class CustomValueConvertor extends ValueConvertorSupport {
@Override
public Object convertOnRead(Object data) {
return null;
}
@Override
public Object convertOnWrite(Object data) {
return "custom";
}
}
/**
* カスタムの{@link DataType}実装クラス。
*/
public static class CustomDataType extends JsonString {
@Override
public String convertOnWrite(Object data) {
return "custom";
}
}
public static class InvalidDataType extends CharacterStreamDataString {
}
}
| apache-2.0 |
chelu/jdal | vaadin/src/main/java/org/jdal/vaadin/UiRequestMapping.java | 1213 | /*
* Copyright 2009-2014 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.jdal.vaadin;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.UI;
/**
* Interface to define a mapping between request and Vaadin {@link UI UIs}.
*
* @author Jose Luis Martin
* @since 2.1
*/
public interface UiRequestMapping {
/**
* Get the UI that applies for a request
* @param request request to map
* @return the mapped UI
*/
UI getUi(VaadinRequest request);
/**
* Gets the UI Class taht applies for a request
* @param request the request to map
* @return the mapped UI class
*/
Class<?extends UI> getUiClass(VaadinRequest request);
}
| apache-2.0 |
dulvac/publick-sling-blog | core/src/main/java/com/nateyolles/sling/publick/services/impl/BlogServiceImpl.java | 2387 | package com.nateyolles.sling.publick.services.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.JcrConstants;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.jcr.resource.JcrResourceConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nateyolles.sling.publick.PublickConstants;
import com.nateyolles.sling.publick.services.BlogService;
@Service
@Component
public class BlogServiceImpl implements BlogService {
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(BlogServiceImpl.class);
/**
* JCR_SQL2 query to get all blog posts in order of newest first.
*/
private static final String BLOG_QUERY = String.format("SELECT * FROM [%s] AS s WHERE "
+ "ISDESCENDANTNODE([%s]) AND s.[%s] = '%s' ORDER BY [%s] desc",
JcrConstants.NT_UNSTRUCTURED,
PublickConstants.BLOG_PATH,
JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY,
PublickConstants.PAGE_TYPE_BLOG,
JcrConstants.JCR_CREATED);
public List<Resource> getPosts(SlingHttpServletRequest request) {
return getPosts(request, 0, 0);
}
public List<Resource> getPosts(SlingHttpServletRequest request, long offset, long limit) {
ArrayList<Resource> posts = new ArrayList<>();
Iterator<Resource> blogPosts = request.getResourceResolver().findResources(BLOG_QUERY, "JCR-SQL2");
long count = 0;
while (blogPosts.hasNext()) {
count++;
if (limit != 0 && posts.size() >= limit) {
break;
}
if (offset > 0 && count <= offset) {
// consume
blogPosts.next();
continue;
}
posts.add(blogPosts.next());
}
return posts;
}
public long getNumberOfPages(SlingHttpServletRequest request, int pageSize) {
long posts = getNumberOfPosts(request);
return (long)Math.ceil((double)posts / pageSize);
}
public long getNumberOfPosts(SlingHttpServletRequest request) {
return getPosts(request).size();
}
} | apache-2.0 |
bazelbuild/intellij | base/src/com/google/idea/blaze/base/run/smrunner/BlazeXmlSchema.java | 6071 | /*
* Copyright 2016 The Bazel Authors. 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.google.idea.blaze.base.run.smrunner;
import static java.util.stream.Collectors.joining;
import com.google.common.collect.Lists;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nullable;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlRootElement;
/** Used to parse the test.xml generated by the blaze/bazel testing framework. */
public class BlazeXmlSchema {
private static final JAXBContext CONTEXT;
static {
try {
CONTEXT = JAXBContext.newInstance(TestSuite.class, TestSuites.class);
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
public static TestSuite parse(InputStream input) {
try {
Object parsed = CONTEXT.createUnmarshaller().unmarshal(input);
return parsed instanceof TestSuites
? ((TestSuites) parsed).convertToTestSuite()
: (TestSuite) parsed;
} catch (JAXBException e) {
throw new RuntimeException("Failed to parse test XML", e);
}
}
// optional wrapping XML element. Some test runners don't include it.
@XmlRootElement(name = "testsuites")
static class TestSuites {
@XmlElement(name = "testsuite")
List<TestSuite> testSuites = Lists.newArrayList();
TestSuite convertToTestSuite() {
TestSuite suite = new TestSuite();
suite.testSuites.addAll(testSuites);
return suite;
}
}
/** XML output by blaze test runners. */
@XmlRootElement(name = "testsuite")
public static class TestSuite {
@XmlAttribute public String name;
@XmlAttribute public String classname;
@XmlAttribute public int tests;
@XmlAttribute public int failures;
@XmlAttribute public int errors;
@XmlAttribute public int skipped;
@XmlAttribute public int disabled;
@XmlAttribute public double time;
@XmlElement(name = "system-out")
public String sysOut;
@XmlElement(name = "system-err")
public String sysErr;
@XmlElement(name = "error", type = ErrorOrFailureOrSkipped.class)
ErrorOrFailureOrSkipped error;
@XmlElement(name = "failure", type = ErrorOrFailureOrSkipped.class)
ErrorOrFailureOrSkipped failure;
@XmlElement(name = "testsuite")
public List<TestSuite> testSuites = Lists.newArrayList();
@XmlElement(name = "testdecorator")
List<TestSuite> testDecorators = Lists.newArrayList();
@XmlElement(name = "testcase")
public List<TestCase> testCases = Lists.newArrayList();
/** Used to merge test suites from a single target, split across multiple shards */
private void addSuite(TestSuite suite) {
for (TestSuite existing : testSuites) {
if (Objects.equals(existing.name, suite.name)) {
existing.mergeWithSuite(suite);
return;
}
}
testSuites.add(suite);
}
private void mergeWithSuite(TestSuite suite) {
for (TestSuite child : suite.testSuites) {
addSuite(child);
}
testDecorators.addAll(suite.testDecorators);
testCases.addAll(suite.testCases);
tests += suite.tests;
failures += suite.failures;
errors += suite.errors;
skipped += suite.skipped;
disabled += suite.disabled;
time += suite.time;
}
}
/** Used to merge test suites from a single target, split across multiple shards */
static TestSuite mergeSuites(List<TestSuite> suites) {
TestSuite outer = new TestSuite();
for (TestSuite suite : suites) {
outer.addSuite(suite);
}
return outer;
}
/** Individual test case XML output by blaze test runners. */
public static class TestCase {
@XmlAttribute public String name;
@XmlAttribute public String classname;
@XmlAttribute public String status;
@XmlAttribute public String result;
@XmlAttribute public String time;
@XmlElement(name = "system-out")
String sysOut;
@XmlElement(name = "system-err")
String sysErr;
@XmlElement(name = "error", type = ErrorOrFailureOrSkipped.class)
public List<ErrorOrFailureOrSkipped> errors = Lists.newArrayList();
@XmlElement(name = "failure", type = ErrorOrFailureOrSkipped.class)
public List<ErrorOrFailureOrSkipped> failures = Lists.newArrayList();
@XmlElement(name = "skipped", type = ErrorOrFailureOrSkipped.class)
public ErrorOrFailureOrSkipped skipped;
}
@Nullable
static String getErrorContent(ErrorOrFailureOrSkipped err) {
if (err.content == null) {
return null;
}
return err.content.stream()
.filter(Objects::nonNull)
.map(Object::toString)
.map(String::trim)
.filter(s -> !s.isEmpty())
.collect(joining("\n"));
}
static class ErrorOrFailureOrSkipped {
// Can't use @XmlValue with @XmlElement
@XmlMixed
@XmlAnyElement(lax = true)
private List<Object> content;
@XmlAttribute String message;
@XmlAttribute String type;
@XmlElement(name = "expected", type = Values.class)
Values expected;
@XmlElement(name = "actual", type = Values.class)
Values actual;
}
static class Values {
@XmlElement(name = "value", type = String.class)
List<String> values = new ArrayList<>();
}
}
| apache-2.0 |
ecarm002/incubator-asterixdb | hyracks-fullstack/hyracks/hyracks-storage-am-btree/src/main/java/org/apache/hyracks/storage/am/btree/dataflow/BTreeSearchOperatorDescriptor.java | 6024 | /*
* 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.hyracks.storage.am.btree.dataflow;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.value.IMissingWriterFactory;
import org.apache.hyracks.api.dataflow.value.IRecordDescriptorProvider;
import org.apache.hyracks.api.dataflow.value.RecordDescriptor;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.job.IOperatorDescriptorRegistry;
import org.apache.hyracks.dataflow.std.base.AbstractSingleActivityOperatorDescriptor;
import org.apache.hyracks.storage.am.common.api.ISearchOperationCallbackFactory;
import org.apache.hyracks.storage.am.common.api.ITupleFilterFactory;
import org.apache.hyracks.storage.am.common.dataflow.IIndexDataflowHelperFactory;
public class BTreeSearchOperatorDescriptor extends AbstractSingleActivityOperatorDescriptor {
private static final long serialVersionUID = 1L;
protected final int[] lowKeyFields;
protected final int[] highKeyFields;
protected final boolean lowKeyInclusive;
protected final boolean highKeyInclusive;
private final int[] minFilterFieldIndexes;
private final int[] maxFilterFieldIndexes;
protected final IIndexDataflowHelperFactory indexHelperFactory;
protected final boolean retainInput;
protected final boolean retainMissing;
protected final IMissingWriterFactory missingWriterFactory;
protected final ISearchOperationCallbackFactory searchCallbackFactory;
protected final boolean appendIndexFilter;
protected boolean appendOpCallbackProceedResult;
protected byte[] searchCallbackProceedResultFalseValue;
protected byte[] searchCallbackProceedResultTrueValue;
protected final ITupleFilterFactory tupleFilterFactory;
protected final long outputLimit;
public BTreeSearchOperatorDescriptor(IOperatorDescriptorRegistry spec, RecordDescriptor outRecDesc,
int[] lowKeyFields, int[] highKeyFields, boolean lowKeyInclusive, boolean highKeyInclusive,
IIndexDataflowHelperFactory indexHelperFactory, boolean retainInput, boolean retainMissing,
IMissingWriterFactory missingWriterFactory, ISearchOperationCallbackFactory searchCallbackFactory,
int[] minFilterFieldIndexes, int[] maxFilterFieldIndexes, boolean appendIndexFilter) {
this(spec, outRecDesc, lowKeyFields, highKeyFields, lowKeyInclusive, highKeyInclusive, indexHelperFactory,
retainInput, retainMissing, missingWriterFactory, searchCallbackFactory, minFilterFieldIndexes,
maxFilterFieldIndexes, appendIndexFilter, null, -1, false, null, null);
}
public BTreeSearchOperatorDescriptor(IOperatorDescriptorRegistry spec, RecordDescriptor outRecDesc,
int[] lowKeyFields, int[] highKeyFields, boolean lowKeyInclusive, boolean highKeyInclusive,
IIndexDataflowHelperFactory indexHelperFactory, boolean retainInput, boolean retainMissing,
IMissingWriterFactory missingWriterFactory, ISearchOperationCallbackFactory searchCallbackFactory,
int[] minFilterFieldIndexes, int[] maxFilterFieldIndexes, boolean appendIndexFilter,
ITupleFilterFactory tupleFilterFactory, long outputLimit, boolean appendOpCallbackProceedResult,
byte[] searchCallbackProceedResultFalseValue, byte[] searchCallbackProceedResultTrueValue) {
super(spec, 1, 1);
this.indexHelperFactory = indexHelperFactory;
this.retainInput = retainInput;
this.retainMissing = retainMissing;
this.missingWriterFactory = missingWriterFactory;
this.searchCallbackFactory = searchCallbackFactory;
this.lowKeyFields = lowKeyFields;
this.highKeyFields = highKeyFields;
this.lowKeyInclusive = lowKeyInclusive;
this.highKeyInclusive = highKeyInclusive;
this.minFilterFieldIndexes = minFilterFieldIndexes;
this.maxFilterFieldIndexes = maxFilterFieldIndexes;
this.appendIndexFilter = appendIndexFilter;
this.outRecDescs[0] = outRecDesc;
this.tupleFilterFactory = tupleFilterFactory;
this.outputLimit = outputLimit;
this.appendOpCallbackProceedResult = appendOpCallbackProceedResult;
this.searchCallbackProceedResultFalseValue = searchCallbackProceedResultFalseValue;
this.searchCallbackProceedResultTrueValue = searchCallbackProceedResultTrueValue;
}
@Override
public BTreeSearchOperatorNodePushable createPushRuntime(final IHyracksTaskContext ctx,
IRecordDescriptorProvider recordDescProvider, int partition, int nPartitions) throws HyracksDataException {
return new BTreeSearchOperatorNodePushable(ctx, partition,
recordDescProvider.getInputRecordDescriptor(getActivityId(), 0), lowKeyFields, highKeyFields,
lowKeyInclusive, highKeyInclusive, minFilterFieldIndexes, maxFilterFieldIndexes, indexHelperFactory,
retainInput, retainMissing, missingWriterFactory, searchCallbackFactory, appendIndexFilter,
tupleFilterFactory, outputLimit, appendOpCallbackProceedResult, searchCallbackProceedResultFalseValue,
searchCallbackProceedResultTrueValue);
}
}
| apache-2.0 |
arnozhang/android-jungle-framework | jungle-framework/android-jungle-framework-photos/src/main/java/com/jungle/apps/photos/module/category/data/manager/NormalCategoryManager.java | 2278 | /**
* Android photos application project.
*
* Copyright 2016 Arno Zhang <zyfgood12@163.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jungle.apps.photos.module.category.data.manager;
import android.text.TextUtils;
import com.jungle.apps.photos.base.component.AppUtils;
import com.jungle.apps.photos.module.category.data.CategoryStrategy;
import com.jungle.base.app.AppCore;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class NormalCategoryManager extends CategoryManager {
public static NormalCategoryManager getInstance() {
return AppCore.getInstance().getManager(NormalCategoryManager.class);
}
private CategoryParser mNormalCategoryParser = new CategoryParser();
public MgrType getCategoryType() {
return MgrType.ForNormal;
}
@Override
protected String generateFetchUrl(
String category, String tag, int fetchIndex, int count) {
if (TextUtils.isEmpty(category)) {
category = AppUtils.getMainCategory();
}
try {
String categoryEncode = null;
String tagEncode = null;
categoryEncode = URLEncoder.encode(category, "UTF-8");
tagEncode = URLEncoder.encode(tag, "UTF-8");
return CategoryStrategy.getCategoryUrl(categoryEncode, tagEncode, fetchIndex, count);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
@Override
protected CategoryInfo createDefaultCategoryInfo(String category, String key) {
return new CategoryInfo(category, key);
}
@Override
protected CategoryParser getCategoryParser() {
return mNormalCategoryParser;
}
}
| apache-2.0 |
lfkdsk/Just-Evaluator | src/main/java/com/lfkdsk/justel/ast/operators/PlusOp.java | 1671 | /*
* Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package com.lfkdsk.justel.ast.operators;
import com.lfkdsk.justel.ast.base.AstNode;
import com.lfkdsk.justel.ast.function.OperatorExpr;
import com.lfkdsk.justel.context.JustContext;
import com.lfkdsk.justel.token.SepToken;
import com.lfkdsk.justel.token.Token;
import java.util.List;
import static com.lfkdsk.justel.utils.NumberUtils.computePlusValue;
import static com.lfkdsk.justel.utils.TypeUtils.*;
/**
* + Operator:
* eq:left + operator
*
* @author liufengkai
* Created by liufengkai on 2017/7/26.
* @see OperatorExpr
*/
public class PlusOp extends OperatorExpr {
public PlusOp(List<AstNode> children) {
super(children, Token.PLUS_OP);
}
@Override
public String funcName() {
return SepToken.PLUS_TOKEN.getText();
}
@Override
public Object eval(JustContext env) {
Object left = leftChild().eval(env);
Object right = rightChild().eval(env);
if (isString(left) || isString(right)) {
// "" + ""
return String.valueOf(left) + String.valueOf(right);
} else if (isNumber(left) && isNumber(right)) {
// id(num) + id(num)
return computePlusValue((Number) left, (Number) right);
}
return super.eval(env);
}
}
| apache-2.0 |
wyukawa/presto | presto-main/src/test/java/io/prestosql/sql/planner/iterative/rule/TestImplementExceptAsUnion.java | 3515 | /*
* 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.sql.planner.iterative.rule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.planner.iterative.rule.test.BaseRuleTest;
import io.prestosql.sql.planner.plan.AggregationNode;
import io.prestosql.sql.planner.plan.FilterNode;
import org.testng.annotations.Test;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.expression;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.node;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.project;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.union;
import static io.prestosql.sql.planner.assertions.PlanMatchPattern.values;
public class TestImplementExceptAsUnion
extends BaseRuleTest
{
@Test
public void test()
{
tester().assertThat(new ImplementExceptAsUnion())
.on(p -> {
Symbol a = p.symbol("a");
Symbol b = p.symbol("b");
Symbol c = p.symbol("c");
return p.except(
ImmutableListMultimap.<Symbol, Symbol>builder()
.put(c, a)
.put(c, b)
.build(),
ImmutableList.of(
p.values(a),
p.values(b)));
})
.matches(
project(
node(FilterNode.class,
node(AggregationNode.class,
union(
project(
ImmutableMap.of(
"leftValue", expression("a"),
"left_marker_1", expression("true"),
"left_marker_2", expression("CAST(null as boolean)")),
values("a")),
project(
ImmutableMap.of(
"rightValue", expression("b"),
"right_marker_1", expression("CAST(null as boolean)"),
"right_marker_2", expression("true")),
values("b")))))));
}
}
| apache-2.0 |
tiarebalbi/vote-no-filme | src/main/java/com/tiarebalbi/query/FilmeQuery.java | 863 | package com.tiarebalbi.query;
import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.types.expr.NumberExpression;
import com.tiarebalbi.entity.Filme;
import com.tiarebalbi.entity.QFilme;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
/**
* @author Tiarê Balbi Bonamini
*/
@Repository
public class FilmeQuery {
@PersistenceContext
private EntityManager em;
/**
* Método responsável por buscar dois filmes random
*
* @return {@link java.util.List}
*/
public List<Filme> buscarFilmeRandom(int quantidade) {
JPAQuery query = new JPAQuery(em);
QFilme entidade = QFilme.filme;
return query.from(entidade)
.orderBy(NumberExpression.random().asc()).limit(quantidade).list(entidade);
}
} | apache-2.0 |
cherryhill/collectionspace-services | services/common/src/main/java/org/collectionspace/services/common/profile/BufferedServletOutputStream.java | 1002 | package org.collectionspace.services.common.profile;
import java.io.*;
import javax.servlet.*;
public class BufferedServletOutputStream extends ServletOutputStream {
// the actual buffer
private ByteArrayOutputStream bos = new ByteArrayOutputStream( );
public String getAsString(){
byte[] buf = bos.toByteArray();
return new String(buf);
}
/**
* @return the contents of the buffer.
*/
public byte[] getBuffer( ) {
return this.bos.toByteArray( );
}
/**
* This method must be defined for custom servlet output streams.
*/
public void write(int data) {
this.bos.write(data);
}
// BufferedHttpResponseWrapper calls this method
public void reset( ) {
this.bos.reset( );
}
// BufferedHttpResponseWrapper calls this method
public void setBufferSize(int size) {
// no way to resize an existing ByteArrayOutputStream
this.bos = new ByteArrayOutputStream(size);
}
} | apache-2.0 |
drewwills/confluence-portlet | WikiPortlet/src/main/java/edu/illinois/my/wiki/portlet/http/package-info.java | 951 | /**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* Jasig 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.
*/
@DefaultAnnotation(NonNull.class)
package edu.illinois.my.wiki.portlet.http;
import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
import edu.umd.cs.findbugs.annotations.NonNull; | apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/internal/Utils.java | 10404 | /*
* Copyright (c) 2016. 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.codegen.internal;
import com.amazonaws.codegen.model.intermediate.IntermediateModel;
import com.amazonaws.codegen.model.intermediate.Metadata;
import com.amazonaws.codegen.model.intermediate.Protocol;
import com.amazonaws.codegen.model.intermediate.ShapeMarshaller;
import com.amazonaws.codegen.model.intermediate.ShapeModel;
import com.amazonaws.codegen.model.service.Input;
import com.amazonaws.codegen.model.service.Operation;
import com.amazonaws.codegen.model.service.ServiceMetadata;
import com.amazonaws.codegen.model.service.ServiceModel;
import com.amazonaws.codegen.model.service.Shape;
import com.amazonaws.codegen.model.service.XmlNamespace;
import com.amazonaws.util.StringUtils;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import static com.amazonaws.codegen.internal.Constants.LOGGER;
public class Utils {
public static boolean isScalar(Shape shape) {
// enums are treated as scalars in C2j.
return !(isListShape(shape) || isStructure(shape) || isMapShape(shape));
}
public static boolean isStructure(Shape shape) {
return shape.getType().equals("structure");
}
public static boolean isListShape(Shape shape) {
return shape.getType().equals("list");
}
public static boolean isMapShape(Shape shape) {
return shape.getType().equals("map");
}
public static boolean isEnumShape(Shape shape) {
return shape.getEnumValues() != null;
}
public static boolean isExceptionShape(Shape shape) {
return shape.isException() || shape.isFault();
}
public static String getAsyncInterfaceName(String interfaceNamePrefix) {
return interfaceNamePrefix + Constants.ASYNC_SUFFIX;
}
public static String getClientName(String clientNamePrefix) {
return clientNamePrefix + Constants.CLIENT_NAME_SUFFIX;
}
public static String unCapitialize(String name) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Name cannot be null or empty");
}
return name.length() < 2 ? StringUtils.lowerCase(name) : StringUtils.lowerCase(name.substring(0, 1))
+ name.substring(1);
}
public static String capitialize(String name) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Name cannot be null or empty");
}
return name.length() < 2 ? StringUtils.upperCase(name) : StringUtils.upperCase(name.substring(0, 1))
+ name.substring(1);
}
/**
* * @param serviceModel Service model to get prefix for.
* * @return Prefix to use when writing model files (service and intermediate).
*/
public static String getFileNamePrefix(ServiceModel serviceModel) {
return String.format("%s-%s", serviceModel.getMetadata().getEndpointPrefix(), serviceModel.getMetadata().getApiVersion());
}
/**
* Converts a directory to a Java package name.
*
* @param directoryPath Directory to convert.
* @return Package name
*/
public static String directoryToPackage(String directoryPath) {
return directoryPath.replace('/', '.');
}
public static String getDefaultEndpointWithoutHttpProtocol(String endpoint) {
if (endpoint == null) {
return null;
}
if (endpoint.startsWith("http://")) {
return endpoint.substring("http://".length());
}
if (endpoint.startsWith("https://")) {
return endpoint.substring("https://".length());
}
return endpoint;
}
public static File createDirectory(String path) {
if (isNullOrEmpty(path)) {
throw new IllegalArgumentException(
"Invalid path directory. Path directory cannot be null or empty");
}
final File dir = new File(path);
createDirectory(dir);
return dir;
}
public static void createDirectory(File dir) {
if (!(dir.exists())) {
if (!dir.mkdirs()) {
throw new RuntimeException("Not able to create directory. "
+ dir.getAbsolutePath());
}
}
}
public static File createFile(String dir, String fileName) throws IOException {
if (isNullOrEmpty(fileName)) {
throw new IllegalArgumentException(
"Invalid file name. File name cannot be null or empty");
}
createDirectory(dir);
File file = new File(dir, fileName);
if (!(file.exists())) {
if (!(file.createNewFile())) {
throw new RuntimeException("Not able to create file . "
+ file.getAbsolutePath());
}
}
return file;
}
public static boolean isNullOrEmpty(String str) {
return str == null || str.trim().isEmpty();
}
public static void closeQuietly(Closeable closeable) {
if (closeable == null)
return;
try {
closeable.close();
} catch (Exception e) {
LOGGER.debug("Not able to close the stream.");
}
}
/**
* Return an InputStream of the specified resource, failing if it can't be found.
*
* @param clzz
* @param location
* Location of resource
*/
public static InputStream getRequiredResourceAsStream(Class<?> clzz, String location) {
InputStream resourceStream = clzz.getResourceAsStream(location);
if (resourceStream == null) {
// Try with a leading "/"
if (!location.startsWith("/")) {
resourceStream = clzz.getResourceAsStream("/" + location);
}
if (resourceStream == null) {
throw new RuntimeException("Resource file was not found at location " + location);
}
}
return resourceStream;
}
/**
* Retrieve system property by name, failing if it's not found
*
* @param propertyName
* @param errorMsgIfNotFound
* @return Value of property if it exists
*/
public static String getRequiredSystemProperty(String propertyName, String errorMsgIfNotFound) {
String propertyValue = System.getProperty(propertyName);
if (propertyValue == null) {
throw new RuntimeException(errorMsgIfNotFound);
}
return propertyValue;
}
/**
* Retrieve optional system property by name, returning null if not found
*
* @param propertyName
* @return Value of property if it exists, null if it does not
*/
public static String getOptionalSystemProperty(String propertyName) {
return System.getProperty(propertyName);
}
/**
* Throws IllegalArgumentException with the specified error message if the input
* is null, otherwise return the input as is.
*/
public static <T> T assertNotNull(T argument, String msg) {
if (argument == null) throw new IllegalArgumentException(msg);
return argument;
}
/**
* Search for intermediate shape model by its c2j name.
*
* @return ShapeModel
* @throws IllegalArgumentException
* if the specified c2j name is not found in the intermediate model.
*/
public static ShapeModel findShapeModelByC2jName(IntermediateModel intermediateModel, String shapeC2jName)
throws IllegalArgumentException {
ShapeModel shapeModel = findShapeModelByC2jNameIfExists(intermediateModel, shapeC2jName);
if (shapeModel != null) {
return shapeModel;
} else {
throw new IllegalArgumentException(
shapeC2jName + " shape (c2j name) does not exist in the intermediate model.");
}
}
/**
* Search for intermediate shape model by its c2j name.
*
* @return ShapeModel or null if the shape doesn't exist (if it's primitive or container type for example)
*/
public static ShapeModel findShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName) {
for (ShapeModel shape : intermediateModel.getShapes().values()) {
if (shape.getC2jName().equals(shapeC2jName)) {
return shape;
}
}
return null;
}
/**
* Create the ShapeMarshaller to the input shape from the specified Operation.
* The input shape in the operation could be empty.
*
* @param service
* @param operation
* @return
*/
public static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation) {
if (operation == null)
throw new IllegalArgumentException(
"The operation parameter must be specified!");
ShapeMarshaller marshaller = new ShapeMarshaller()
.withAction(operation.getName())
.withVerb(operation.getHttp().getMethod())
.withRequestUri(operation.getHttp().getRequestUri());
Input input = operation.getInput();
if (input != null) {
marshaller.setLocationName(input.getLocationName());
// Pass the xmlNamespace trait from the input reference
XmlNamespace xmlNamespace = input.getXmlNamespace();
if (xmlNamespace != null) {
marshaller.setXmlNameSpaceUri(xmlNamespace.getUri());
}
}
if (!StringUtils.isNullOrEmpty(service.getTargetPrefix()) && Metadata.isNotRestProtocol(service.getProtocol())) {
marshaller.setTarget(service.getTargetPrefix() + "." + operation.getName());
}
return marshaller;
}
}
| apache-2.0 |
CRDNicolasBourbaki/pac4j | pac4j-cas/src/test/java/org/pac4j/cas/profile/TestProfileHelper.java | 1420 | /*
Copyright 2012 - 2015 pac4j organization
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.pac4j.cas.profile;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.profile.ProfileHelper;
/**
* This class tests the {@link ProfileHelper} class for the {@link CasProfile}.
*
* @author Jerome Leleu
* @since 1.4.0
*/
public final class TestProfileHelper extends org.pac4j.core.profile.TestProfileHelper {
@Override
protected Class<? extends CommonProfile> getProfileClass() {
return CasProfile.class;
}
public void testBuildProfileCasProxyProfile() {
assertNotNull(ProfileHelper.buildProfile("CasProxyProfile" + "#" + STRING_ID, EMPTY_MAP));
}
@Override
protected String getProfileType() {
return "CasProfile";
}
@Override
protected String getAttributeName() {
return "whatever";
}
}
| apache-2.0 |
xmpace/jetty-read | jetty-spdy/spdy-jetty/src/main/java/org/eclipse/jetty/spdy/SPDYClient.java | 17290 | //
// ========================================================================
// Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.spdy;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.ConnectedEndPoint;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.nio.AsyncConnection;
import org.eclipse.jetty.io.nio.SelectChannelEndPoint;
import org.eclipse.jetty.io.nio.SelectorManager;
import org.eclipse.jetty.io.nio.SslConnection;
import org.eclipse.jetty.npn.NextProtoNego;
import org.eclipse.jetty.spdy.api.Session;
import org.eclipse.jetty.spdy.api.SessionFrameListener;
import org.eclipse.jetty.spdy.generator.Generator;
import org.eclipse.jetty.spdy.parser.Parser;
import org.eclipse.jetty.util.component.AggregateLifeCycle;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class SPDYClient
{
private final Map<String, AsyncConnectionFactory> factories = new ConcurrentHashMap<>();
private final short version;
private final Factory factory;
private SocketAddress bindAddress;
private long maxIdleTime = -1;
private volatile int initialWindowSize = 65536;
protected SPDYClient(short version, Factory factory)
{
this.version = version;
this.factory = factory;
}
/**
* @return the address to bind the socket channel to
* @see #setBindAddress(SocketAddress)
*/
public SocketAddress getBindAddress()
{
return bindAddress;
}
/**
* @param bindAddress the address to bind the socket channel to
* @see #getBindAddress()
*/
public void setBindAddress(SocketAddress bindAddress)
{
this.bindAddress = bindAddress;
}
public Future<Session> connect(InetSocketAddress address, SessionFrameListener listener) throws IOException
{
if (!factory.isStarted())
throw new IllegalStateException(Factory.class.getSimpleName() + " is not started");
SocketChannel channel = SocketChannel.open();
if (bindAddress != null)
channel.bind(bindAddress);
channel.socket().setTcpNoDelay(true);
channel.configureBlocking(false);
SessionPromise result = new SessionPromise(channel, this, listener);
channel.connect(address);
factory.selector.register(channel, result);
return result;
}
public long getMaxIdleTime()
{
return maxIdleTime;
}
public void setMaxIdleTime(long maxIdleTime)
{
this.maxIdleTime = maxIdleTime;
}
public int getInitialWindowSize()
{
return initialWindowSize;
}
public void setInitialWindowSize(int initialWindowSize)
{
this.initialWindowSize = initialWindowSize;
}
protected String selectProtocol(List<String> serverProtocols)
{
if (serverProtocols == null)
return "spdy/2";
for (String serverProtocol : serverProtocols)
{
for (String protocol : factories.keySet())
{
if (serverProtocol.equals(protocol))
return protocol;
}
String protocol = factory.selectProtocol(serverProtocols);
if (protocol != null)
return protocol;
}
return null;
}
public AsyncConnectionFactory getAsyncConnectionFactory(String protocol)
{
for (Map.Entry<String, AsyncConnectionFactory> entry : factories.entrySet())
{
if (protocol.equals(entry.getKey()))
return entry.getValue();
}
for (Map.Entry<String, AsyncConnectionFactory> entry : factory.factories.entrySet())
{
if (protocol.equals(entry.getKey()))
return entry.getValue();
}
return null;
}
public void putAsyncConnectionFactory(String protocol, AsyncConnectionFactory factory)
{
factories.put(protocol, factory);
}
public AsyncConnectionFactory removeAsyncConnectionFactory(String protocol)
{
return factories.remove(protocol);
}
protected SSLEngine newSSLEngine(SslContextFactory sslContextFactory, SocketChannel channel)
{
String peerHost = channel.socket().getInetAddress().getHostAddress();
int peerPort = channel.socket().getPort();
SSLEngine engine = sslContextFactory.newSslEngine(peerHost, peerPort);
engine.setUseClientMode(true);
return engine;
}
protected FlowControlStrategy newFlowControlStrategy()
{
return FlowControlStrategyFactory.newFlowControlStrategy(version);
}
public static class Factory extends AggregateLifeCycle
{
private final Map<String, AsyncConnectionFactory> factories = new ConcurrentHashMap<>();
private final Queue<Session> sessions = new ConcurrentLinkedQueue<>();
private final ByteBufferPool bufferPool = new StandardByteBufferPool();
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final Executor threadPool;
private final SslContextFactory sslContextFactory;
private final SelectorManager selector;
public Factory()
{
this(null, null);
}
public Factory(SslContextFactory sslContextFactory)
{
this(null, sslContextFactory);
}
public Factory(Executor threadPool)
{
this(threadPool, null);
}
public Factory(Executor threadPool, SslContextFactory sslContextFactory)
{
if (threadPool == null)
threadPool = new QueuedThreadPool();
this.threadPool = threadPool;
addBean(threadPool);
this.sslContextFactory = sslContextFactory;
if (sslContextFactory != null)
addBean(sslContextFactory);
selector = new ClientSelectorManager();
addBean(selector);
factories.put("spdy/2", new ClientSPDYAsyncConnectionFactory());
}
public SPDYClient newSPDYClient(short version)
{
return new SPDYClient(version, this);
}
@Override
protected void doStop() throws Exception
{
closeConnections();
super.doStop();
}
protected String selectProtocol(List<String> serverProtocols)
{
for (String serverProtocol : serverProtocols)
{
for (String protocol : factories.keySet())
{
if (serverProtocol.equals(protocol))
return protocol;
}
}
return null;
}
private boolean sessionOpened(Session session)
{
// Add sessions only if the factory is not stopping
return isRunning() && sessions.offer(session);
}
private boolean sessionClosed(Session session)
{
// Remove sessions only if the factory is not stopping
// to avoid concurrent removes during iterations
return isRunning() && sessions.remove(session);
}
private void closeConnections()
{
for (Session session : sessions)
session.goAway();
sessions.clear();
}
protected Collection<Session> getSessions()
{
return Collections.unmodifiableCollection(sessions);
}
private class ClientSelectorManager extends SelectorManager
{
@Override
public boolean dispatch(Runnable task)
{
try
{
threadPool.execute(task);
return true;
}
catch (RejectedExecutionException x)
{
return false;
}
}
@Override
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key) throws IOException
{
SessionPromise attachment = (SessionPromise)key.attachment();
long maxIdleTime = attachment.client.getMaxIdleTime();
if (maxIdleTime < 0)
maxIdleTime = getMaxIdleTime();
SelectChannelEndPoint result = new SelectChannelEndPoint(channel, selectSet, key, (int)maxIdleTime);
AsyncConnection connection = newConnection(channel, result, attachment);
result.setConnection(connection);
return result;
}
@Override
protected void endPointOpened(SelectChannelEndPoint endpoint)
{
}
@Override
protected void endPointUpgraded(ConnectedEndPoint endpoint, Connection oldConnection)
{
}
@Override
protected void endPointClosed(SelectChannelEndPoint endpoint)
{
endpoint.getConnection().onClose();
}
@Override
public AsyncConnection newConnection(final SocketChannel channel, AsyncEndPoint endPoint, final Object attachment)
{
SessionPromise sessionPromise = (SessionPromise)attachment;
final SPDYClient client = sessionPromise.client;
try
{
if (sslContextFactory != null)
{
final SSLEngine engine = client.newSSLEngine(sslContextFactory, channel);
SslConnection sslConnection = new SslConnection(engine, endPoint)
{
@Override
public void onClose()
{
NextProtoNego.remove(engine);
super.onClose();
}
};
endPoint.setConnection(sslConnection);
final AsyncEndPoint sslEndPoint = sslConnection.getSslEndPoint();
NextProtoNego.put(engine, new NextProtoNego.ClientProvider()
{
@Override
public boolean supports()
{
return true;
}
@Override
public void unsupported()
{
// Server does not support NPN, but this is a SPDY client, so hardcode SPDY
ClientSPDYAsyncConnectionFactory connectionFactory = new ClientSPDYAsyncConnectionFactory();
AsyncConnection connection = connectionFactory.newAsyncConnection(channel, sslEndPoint, attachment);
sslEndPoint.setConnection(connection);
}
@Override
public String selectProtocol(List<String> protocols)
{
String protocol = client.selectProtocol(protocols);
if (protocol == null)
return null;
AsyncConnectionFactory connectionFactory = client.getAsyncConnectionFactory(protocol);
AsyncConnection connection = connectionFactory.newAsyncConnection(channel, sslEndPoint, attachment);
sslEndPoint.setConnection(connection);
return protocol;
}
});
AsyncConnection connection = new EmptyAsyncConnection(sslEndPoint);
sslEndPoint.setConnection(connection);
startHandshake(engine);
return sslConnection;
}
else
{
AsyncConnectionFactory connectionFactory = new ClientSPDYAsyncConnectionFactory();
AsyncConnection connection = connectionFactory.newAsyncConnection(channel, endPoint, attachment);
endPoint.setConnection(connection);
return connection;
}
}
catch (RuntimeException x)
{
sessionPromise.failed(null,x);
throw x;
}
}
private void startHandshake(SSLEngine engine)
{
try
{
engine.beginHandshake();
}
catch (SSLException x)
{
throw new RuntimeException(x);
}
}
}
}
private static class SessionPromise extends Promise<Session>
{
private final SocketChannel channel;
private final SPDYClient client;
private final SessionFrameListener listener;
private SessionPromise(SocketChannel channel, SPDYClient client, SessionFrameListener listener)
{
this.channel = channel;
this.client = client;
this.listener = listener;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning)
{
try
{
super.cancel(mayInterruptIfRunning);
channel.close();
return true;
}
catch (IOException x)
{
return true;
}
}
}
private static class ClientSPDYAsyncConnectionFactory implements AsyncConnectionFactory
{
@Override
public AsyncConnection newAsyncConnection(SocketChannel channel, AsyncEndPoint endPoint, Object attachment)
{
SessionPromise sessionPromise = (SessionPromise)attachment;
SPDYClient client = sessionPromise.client;
Factory factory = client.factory;
CompressionFactory compressionFactory = new StandardCompressionFactory();
Parser parser = new Parser(compressionFactory.newDecompressor());
Generator generator = new Generator(factory.bufferPool, compressionFactory.newCompressor());
SPDYAsyncConnection connection = new ClientSPDYAsyncConnection(endPoint, factory.bufferPool, parser, factory);
endPoint.setConnection(connection);
FlowControlStrategy flowControlStrategy = client.newFlowControlStrategy();
StandardSession session = new StandardSession(client.version, factory.bufferPool, factory.threadPool, factory.scheduler, connection, connection, 1, sessionPromise.listener, generator, flowControlStrategy);
session.setWindowSize(client.getInitialWindowSize());
parser.addListener(session);
sessionPromise.completed(session);
connection.setSession(session);
factory.sessionOpened(session);
return connection;
}
private class ClientSPDYAsyncConnection extends SPDYAsyncConnection
{
private final Factory factory;
public ClientSPDYAsyncConnection(AsyncEndPoint endPoint, ByteBufferPool bufferPool, Parser parser, Factory factory)
{
super(endPoint, bufferPool, parser);
this.factory = factory;
}
@Override
public void onClose()
{
super.onClose();
factory.sessionClosed(getSession());
}
}
}
}
| apache-2.0 |
googleapis/java-talent | proto-google-cloud-talent-v4/src/main/java/com/google/cloud/talent/v4/LocationFilterOrBuilder.java | 7836 | /*
* 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/talent/v4/filters.proto
package com.google.cloud.talent.v4;
public interface LocationFilterOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.talent.v4.LocationFilter)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The address name, such as "Mountain View" or "Bay Area".
* </pre>
*
* <code>string address = 1;</code>
*
* @return The address.
*/
java.lang.String getAddress();
/**
*
*
* <pre>
* The address name, such as "Mountain View" or "Bay Area".
* </pre>
*
* <code>string address = 1;</code>
*
* @return The bytes for address.
*/
com.google.protobuf.ByteString getAddressBytes();
/**
*
*
* <pre>
* CLDR region code of the country/region. This field may be used in two ways:
* 1) If telecommute preference is not set, this field is used address
* ambiguity of the user-input address. For example, "Liverpool" may refer to
* "Liverpool, NY, US" or "Liverpool, UK". This region code biases the
* address resolution toward a specific country or territory. If this field is
* not set, address resolution is biased toward the United States by default.
* 2) If telecommute preference is set to TELECOMMUTE_ALLOWED, the
* telecommute location filter will be limited to the region specified in this
* field. If this field is not set, the telecommute job locations will not be
* See
* https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/territory_information.html
* for details. Example: "CH" for Switzerland.
* </pre>
*
* <code>string region_code = 2;</code>
*
* @return The regionCode.
*/
java.lang.String getRegionCode();
/**
*
*
* <pre>
* CLDR region code of the country/region. This field may be used in two ways:
* 1) If telecommute preference is not set, this field is used address
* ambiguity of the user-input address. For example, "Liverpool" may refer to
* "Liverpool, NY, US" or "Liverpool, UK". This region code biases the
* address resolution toward a specific country or territory. If this field is
* not set, address resolution is biased toward the United States by default.
* 2) If telecommute preference is set to TELECOMMUTE_ALLOWED, the
* telecommute location filter will be limited to the region specified in this
* field. If this field is not set, the telecommute job locations will not be
* See
* https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/territory_information.html
* for details. Example: "CH" for Switzerland.
* </pre>
*
* <code>string region_code = 2;</code>
*
* @return The bytes for regionCode.
*/
com.google.protobuf.ByteString getRegionCodeBytes();
/**
*
*
* <pre>
* The latitude and longitude of the geographic center to search from. This
* field is ignored if `address` is provided.
* </pre>
*
* <code>.google.type.LatLng lat_lng = 3;</code>
*
* @return Whether the latLng field is set.
*/
boolean hasLatLng();
/**
*
*
* <pre>
* The latitude and longitude of the geographic center to search from. This
* field is ignored if `address` is provided.
* </pre>
*
* <code>.google.type.LatLng lat_lng = 3;</code>
*
* @return The latLng.
*/
com.google.type.LatLng getLatLng();
/**
*
*
* <pre>
* The latitude and longitude of the geographic center to search from. This
* field is ignored if `address` is provided.
* </pre>
*
* <code>.google.type.LatLng lat_lng = 3;</code>
*/
com.google.type.LatLngOrBuilder getLatLngOrBuilder();
/**
*
*
* <pre>
* The distance_in_miles is applied when the location being searched for is
* identified as a city or smaller. This field is ignored if the location
* being searched for is a state or larger.
* </pre>
*
* <code>double distance_in_miles = 4;</code>
*
* @return The distanceInMiles.
*/
double getDistanceInMiles();
/**
*
*
* <pre>
* Allows the client to return jobs without a
* set location, specifically, telecommuting jobs (telecommuting is considered
* by the service as a special location.
* [Job.posting_region][google.cloud.talent.v4.Job.posting_region] indicates if a job permits telecommuting.
* If this field is set to [TelecommutePreference.TELECOMMUTE_ALLOWED][google.cloud.talent.v4.LocationFilter.TelecommutePreference.TELECOMMUTE_ALLOWED],
* telecommuting jobs are searched, and [address][google.cloud.talent.v4.LocationFilter.address] and [lat_lng][google.cloud.talent.v4.LocationFilter.lat_lng] are
* ignored. If not set or set to
* [TelecommutePreference.TELECOMMUTE_EXCLUDED][google.cloud.talent.v4.LocationFilter.TelecommutePreference.TELECOMMUTE_EXCLUDED], telecommute job are not
* searched.
* This filter can be used by itself to search exclusively for telecommuting
* jobs, or it can be combined with another location
* filter to search for a combination of job locations,
* such as "Mountain View" or "telecommuting" jobs. However, when used in
* combination with other location filters, telecommuting jobs can be
* treated as less relevant than other jobs in the search response.
* This field is only used for job search requests.
* </pre>
*
* <code>.google.cloud.talent.v4.LocationFilter.TelecommutePreference telecommute_preference = 5;
* </code>
*
* @return The enum numeric value on the wire for telecommutePreference.
*/
int getTelecommutePreferenceValue();
/**
*
*
* <pre>
* Allows the client to return jobs without a
* set location, specifically, telecommuting jobs (telecommuting is considered
* by the service as a special location.
* [Job.posting_region][google.cloud.talent.v4.Job.posting_region] indicates if a job permits telecommuting.
* If this field is set to [TelecommutePreference.TELECOMMUTE_ALLOWED][google.cloud.talent.v4.LocationFilter.TelecommutePreference.TELECOMMUTE_ALLOWED],
* telecommuting jobs are searched, and [address][google.cloud.talent.v4.LocationFilter.address] and [lat_lng][google.cloud.talent.v4.LocationFilter.lat_lng] are
* ignored. If not set or set to
* [TelecommutePreference.TELECOMMUTE_EXCLUDED][google.cloud.talent.v4.LocationFilter.TelecommutePreference.TELECOMMUTE_EXCLUDED], telecommute job are not
* searched.
* This filter can be used by itself to search exclusively for telecommuting
* jobs, or it can be combined with another location
* filter to search for a combination of job locations,
* such as "Mountain View" or "telecommuting" jobs. However, when used in
* combination with other location filters, telecommuting jobs can be
* treated as less relevant than other jobs in the search response.
* This field is only used for job search requests.
* </pre>
*
* <code>.google.cloud.talent.v4.LocationFilter.TelecommutePreference telecommute_preference = 5;
* </code>
*
* @return The telecommutePreference.
*/
com.google.cloud.talent.v4.LocationFilter.TelecommutePreference getTelecommutePreference();
}
| apache-2.0 |
konifar/android-strings-search-plugin | src/main/java/com/konifar/stringssearch/models/PluralStringElement.java | 1268 | package main.java.com.konifar.stringssearch.models;
import java.util.LinkedList;
import java.util.List;
public final class PluralStringElement extends AbstractStringElement {
private String name;
private final LinkedList<QuantityStringElement> quantities = new LinkedList<QuantityStringElement>();
private final String parentDirName;
public PluralStringElement(String name, List<QuantityStringElement> quantities, String parentDirName) {
this.name = name;
this.parentDirName = parentDirName;
this.quantities.addAll(quantities);
}
public String getName() {
return name;
}
@Override
public String getTag() {
return "plurals";
}
@Override
public String getValue() {
if (quantities.isEmpty()) return "";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < quantities.size(); i++) {
QuantityStringElement quantity = quantities.get(i);
builder.append(quantity.getValue());
if (i < quantities.size() - 1) {
builder.append(", ");
}
}
return builder.toString();
}
@Override
public String getParentDirName() {
return parentDirName;
}
}
| apache-2.0 |
pepstock-org/Charba | src/org/pepstock/charba/client/commons/Merger.java | 15877 | /**
Copyright 2017 Andrea "Stock" Stocchero
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.pepstock.charba.client.commons;
import java.util.List;
import org.pepstock.charba.client.ChartEnvelop;
import org.pepstock.charba.client.ChartOptions;
import org.pepstock.charba.client.Defaults;
import org.pepstock.charba.client.GlobalOptions;
import org.pepstock.charba.client.GlobalScale;
import org.pepstock.charba.client.Helpers;
import org.pepstock.charba.client.IsChart;
import org.pepstock.charba.client.ScaleType;
import org.pepstock.charba.client.Type;
import org.pepstock.charba.client.configuration.AxisType;
import org.pepstock.charba.client.options.Scale;
import org.pepstock.charba.client.resources.ResourcesType;
/**
* Singleton utility to merge java script object in the another one and provide the service to get the chart options with all defaults.
*
* @author Andrea "Stock" Stocchero
*
*/
public final class Merger {
// singleton instance
private static final Merger INSTANCE = new Merger();
/**
* Name of properties of native objects to use to creates defaults for chart by its type.
*/
private enum Property implements Key
{
SCALES("scales");
// name value of property
private final String value;
/**
* Creates a property with the value to use in the native object.
*
* @param value value of property name
*/
private Property(String value) {
this.value = value;
}
/*
* (non-Javadoc)
*
* @see org.pepstock.charba.client.commons.Key#value()
*/
@Override
public String value() {
return value;
}
}
/**
* To avoid any instantiation
*/
private Merger() {
// inject Chart.js and date library if not already loaded
ResourcesType.getResources().inject();
}
/**
* Singleton method to get the instance
*
* @return merger instance
*/
public static Merger get() {
return INSTANCE;
}
/**
* Merges the chart options, built after the chart initialization on the chart configuration in order that the configuration can contain all values, also the defaults.
*
* @param options chart options configuration
* @param envelop the envelop for options as native options
*/
public void load(NativeObjectContainer options, ChartEnvelop<NativeObject> envelop) {
// checks if envelop is consistent
if (Envelop.isValid(envelop)) {
// clones native object of native chart options
// on chart configuration
mergeNativeObjects(options.getNativeObject(), envelop.getContent());
}
}
/**
* Merges chart default options (by chart.defaults[type]), default scale options (by chart.defaults.scale) and global options (by chart.defaults.global) and chart options.<br>
* The chain of priority is:<br>
* <ul>
* <li>chart options
* <li>chart default options (by chart.defaults[type])
* <li>default scale options (by chart.defaults.scale)
* <li>global options (by chart.defaults.global)
* </ul>
*
* @param chart chart instance which contains the chart options to be merged
* @param options the options as native object container to be merged
* @param envelop the envelop for options as native options
*/
public void load(IsChart chart, NativeObjectContainer options, ChartEnvelop<NativeObject> envelop) {
// checks if argument is consistent
IsChart.checkIfConsistent(chart);
// checks if envelop is consistent
if (envelop != null) {
// gets global and chart type options merged
NativeObject defaults = get(chart.getType(), Defaults.get().getOptions(chart.getType()));
// clones native object to avoid to changes the sources
NativeObject chartOptions = Helpers.get().clone(options.getNativeObject());
// merges the current chart options with the global and chart type ones
NativeObject wholeOptions = mergeNativeObjects(chartOptions, defaults);
// loads whole options in the envelop
envelop.setContent(wholeOptions);
}
}
/**
* Merges chart default options (by chart.defaults[type]), default scale options (by chart.defaults.scale) and global options (by chart.defaults.global).<br>
* The chain of priority is:<br>
* <ul>
* <li>chart default options (by chart.defaults[type])
* <li>default scale options (by chart.defaults.scale)
* <li>global options (by chart.defaults.global)
* </ul>
*
* @param type chart type
* @param envelop the envelop for options as native options
*/
public void load(Type type, ChartEnvelop<NativeObject> envelop) {
// checks if envelop is consistent
if (envelop != null) {
// gets global and chart type options merged
NativeObject defaults = get(type, Defaults.get().getOptions(type));
// loads whole options in the envelop
envelop.setContent(defaults);
}
}
/**
* Merges chart default options (by chart.defaults[type]), default scale options (by chart.defaults.scale) and global options (by chart.defaults.global).<br>
* The chain of priority is:<br>
* <ul>
* <li>chart default options (by chart.defaults[type])
* <li>default scale options (by chart.defaults.scale)
* <li>global options (by chart.defaults.global)
* </ul>
*
* @param type chart type
* @param options temporary chart options in order to get a default for the chart options
* @param envelop the envelop for options as native options
*/
public void load(Type type, ChartEnvelop<ChartOptions> options, ChartEnvelop<NativeObject> envelop) {
// checks if envelop is consistent
if (envelop != null && options != null && options.getContent() != null) {
// gets global and chart type options merged
NativeObject defaults = get(type, options.getContent());
// loads whole options in the envelop
envelop.setContent(defaults);
}
}
/**
* Merges chart default options (by chart.defaults[type]), default scale options (by chart.defaults.scale) and global options (by chart.defaults.global).<br>
* The chain of priority is:<br>
* <ul>
* <li>chart default options (by chart.defaults[type])
* <li>default scale options (by chart.defaults.scale)
* <li>global options (by chart.defaults.global)
* </ul>
*
* @param type chart type
* @param base default for the chart options instance
* @return a native object to be mapped with all defaults for that chart type.
*/
private NativeObject get(Type type, ChartOptions base) {
// checks if argument is consistent
Type.checkIfValid(type);
// gets chart.defaults.scale
GlobalScale scale = Defaults.get().getScale();
// gets chart.defaults.global
GlobalOptions global = Defaults.get().getGlobal();
// clones all native object to avoid to changes the sources
NativeObject chartOptions = Helpers.get().clone(base.getNativeObject());
NativeObject scaleOptions = Helpers.get().clone(scale.getNativeObject());
NativeObject globalOptions = Helpers.get().clone(global.getNativeObject());
// checks if the chart options has got scale (only 1)
// chart without scales don't do anything
if (!ScaleType.NONE.equals(type.scaleType())) {
// manages multi scale chart type
handleMultiScalesType(base, chartOptions, scaleOptions);
}
// merges chart options (maybe already updated by scales)
// and the global ones
return mergeNativeObjects(chartOptions, globalOptions);
}
/**
* Manages the merge of options for chart with multiple scales.
*
* @param base base chart options
* @param chartOptions default chart options
* @param scaleOptions default scale options
*/
private void handleMultiScalesType(ChartOptions base, NativeObject chartOptions, NativeObject scaleOptions) {
// checks if scales object is present
if (NativeObjectUtils.hasProperty(chartOptions, Property.SCALES.value())) {
// if here, the chart has got 2 or more scales
// gets the native object for scales
NativeObject scales = NativeObjectUtils.getObjectProperty(chartOptions, Property.SCALES.value());
// checks and apply scales
applyDefaultsOnScales(base.getScales().getAxes(), scales, scaleOptions);
}
}
/**
* Applies the defaults to all scales (X and Y) defined for a chart.
*
* @param storedScales the list of object with all defined scales
* @param scales native object with scales
* @param scaleOptions defaults scales native object
*/
private void applyDefaultsOnScales(List<Scale> storedScales, NativeObject scales, NativeObject scaleOptions) {
// scans all scales
for (Scale storedScale : storedScales) {
// gets native object of scale
NativeObject scaleObject = NativeObjectUtils.getObjectProperty(scales, storedScale.getId().value());
// create instance for axis type
AxisType type = storedScale.getType();
// checks if axis type is consistent
if (Key.isValid(type)) {
// gets default by axis type
Scale axisDefault = Defaults.get().getScale(type);
// before it applies the axis defaults by its type
NativeObject tempObject = mergeNativeObjects(scaleObject, axisDefault.getNativeObject());
// then it applies defaults scale
NativeObjectUtils.defineObjectProperty(scales, storedScale.getId().value(), mergeNativeObjects(tempObject, scaleOptions));
} else {
// then it applies defaults scale
NativeObjectUtils.defineObjectProperty(scales, storedScale.getId().value(), mergeNativeObjects(scaleObject, scaleOptions));
}
}
}
/**
* Copies <code>source</code> properties (creating a new java script object and setting the <code>source</code> one with the property argument) in the <code>target</code> only
* if not defined in target.<br>
* <code>target</code> is not cloned and will be updated with <code>source</code> properties.<br>
* The property is
*
* @param target The target object in which <code>source</code> is merged into.
* @param source Object to merge in the <code>target</code>.
* @param property property of root java script object to add
* @return the added java script object
*/
public NativeObject merge(NativeObjectContainer target, NativeObjectContainer source, String property) {
// checks if arguments are consistent
checkArgumentsConsistency(target, source, property);
return merge(target.getNativeObject(), source.getNativeObject(), property);
}
/**
* Copies <code>source</code> properties (creating a new java script object and setting the <code>source</code> one with the property argument) in the <code>target</code> only
* if not defined in target.<br>
* <code>target</code> is not cloned and will be updated with <code>source</code> properties.<br>
* The property is
*
* @param target The target object in which <code>source</code> is merged into.
* @param source Object to merge in the <code>target</code>.
* @param property property of root java script object to add
* @return the added java script object
*/
public NativeObject merge(NativeObject target, NativeObjectContainer source, String property) {
// checks if arguments are consistent
checkArgumentsConsistency(target, source, property);
return merge(target, source.getNativeObject(), property);
}
/**
* Copies <code>source</code> properties (creating a new java script object and setting the <code>source</code> one with the property argument) in the <code>target</code> only
* if not defined in target.<br>
* <code>target</code> is not cloned and will be updated with <code>source</code> properties.<br>
* The property is
*
* @param target The target object in which <code>source</code> is merged into.
* @param source Object to merge in the <code>target</code>.
* @param property property of root java script object to add
* @return the added java script object
*/
public NativeObject merge(NativeObjectContainer target, NativeObject source, String property) {
// checks if arguments are consistent
checkArgumentsConsistency(target, source, property);
return merge(target.getNativeObject(), source, property);
}
/**
* Copies <code>source</code> properties (creating a new java script object and setting the <code>source</code> one with the property argument) in the <code>target</code> only
* if not defined in target.<br>
* <code>target</code> is not cloned and will be updated with <code>source</code> properties.<br>
* The property is
*
* @param target The target object in which <code>source</code> is merged into.
* @param source Object to merge in the <code>target</code>.
* @param property property of root java script object to add
* @return the added java script object
*/
public NativeObject merge(NativeObject target, NativeObject source, String property) {
// checks if arguments are consistent
checkArgumentsConsistency(target, source, property);
return internalMerge(target, source, property);
}
/**
* Copies <code>source</code> properties (creating a new java script object and setting the <code>source</code> one with the property argument) in the <code>target</code> only
* if not defined in target.<br>
* <code>target</code> is not cloned and will be updated with <code>source</code> properties.<br>
* The property is
*
* @param target The target object in which <code>source</code> is merged into.
* @param source Object to merge in the <code>target</code>.
* @param property property of root java script object to add
* @return the added java script object
*/
private NativeObject internalMerge(NativeObject target, NativeObject source, String property) {
// creates new root object
NativeObject newObject = NativeObjectUtils.create();
// stores configuration
NativeObjectUtils.defineObjectProperty(newObject, property, source);
// invokes CHART.JS to merge
return mergeNativeObjects(target, newObject);
}
/**
* Copies <code>source</code> properties in the <code>target</code> only if not defined in target.<br>
* <code>target</code> is not cloned and will be updated with <code>source</code> properties.
*
* @param target The target object in which <code>source</code> is merged into.
* @param source Object to merge in the <code>target</code>.
* @return the merged java script object
*/
private NativeObject mergeNativeObjects(NativeObject target, NativeObject source) {
NativeObject newObject = Helpers.get().mergeIf(target, source);
return newObject == null ? NativeObjectUtils.create() : newObject;
}
/**
* Checks if arguments are not <code>null</code> or not consistent. If not consistent, throws an {@link IllegalArgumentException}.
*
* @param target The target object in which <code>source</code> is merged into.
* @param source Object to merge in the <code>target</code>.
* @param property property of root java script object to add
*/
private void checkArgumentsConsistency(Object target, Object source, String property) {
// checks if arguments are not consistent
Checker.checkAndGetIfValid(target, "Target argument");
Checker.checkAndGetIfValid(source, "Source argument");
Checker.checkAndGetIfValid(property, "Property argument");
Checker.checkIfNotEqualTo(property.trim().length(), 0, "Property argument size");
}
}
| apache-2.0 |
nagyistoce/camunda-dmn-model | src/test/java/org/camunda/bpm/model/dmn/instance/OutputDefinitionReferenceTest.java | 693 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.model.dmn.instance;
public class OutputDefinitionReferenceTest extends AbstractDmnElementReferenceTest {
}
| apache-2.0 |
adm3942soit/VehiclyManager | src/main/java/com/adonis/data/persons/Person.java | 1981 | package com.adonis.data.persons;
import com.adonis.data.Audit;
import com.adonis.data.payments.CreditCard;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
/**
* A domain object example. In a real application this would probably be a JPA
* entity or DTO.
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "persons", schema = "")
@Getter
@Setter
@NoArgsConstructor
@Cacheable(value = false)
public class Person extends Audit
{
@NotNull(message="Please enter first name")
@Column(name = "FIRST_NAME", nullable = false)
private String firstName;
@NotNull(message="Please enter last name")
@Column(name = "LAST_NAME", nullable = false)
private String lastName;
@Column(name = "NAME", nullable = false)
private String name;
@Email
@NotNull(message="Please enter email")
@Column(name = "EMAIL", unique = true, nullable = false)
private String email;
@Column(name = "LOGIN", nullable = true, unique = true)
private String login;
// @NotNull(message="Please select a password")
@Length(min=5, max=10, message="Password should be between 5 - 10 charactes")
@Column(name = "PASSWORD", nullable = true)
private String password;
@Past
@Column(name = "BIRTH_DATE", nullable = true)
private java.util.Date birthDate;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "ADDRESS")
private Address address;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "CARD")
private CreditCard card;
@Column(name = "PHONE_NUMBER", nullable = true)
private String phoneNumber;
@Column(name = "GENDER", nullable = true)
private String gender;
@Column(name = "PICTURE", nullable = true)
private String picture;
@Lob
@Column(name = "NOTES", length = 1000, nullable = true)
private String notes;
}
| apache-2.0 |
mcculls/bnd | biz.aQute.bnd/src/aQute/bnd/main/Profiles.java | 3523 | package aQute.bnd.main;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.header.Parameters;
import aQute.bnd.main.bnd.ProfileOptions;
import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Domain;
import aQute.bnd.osgi.Instruction;
import aQute.bnd.osgi.Instructions;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.resource.ResourceBuilder;
import aQute.bnd.version.Version;
import aQute.lib.getopt.Options;
import aQute.lib.io.IO;
import aQute.libg.glob.Glob;
public class Profiles extends Processor {
private final static Logger logger = LoggerFactory.getLogger(Profiles.class);
private bnd bnd;
// private ProfileOptions options;
public Profiles(bnd bnd, ProfileOptions options) {
super(bnd);
getSettings(bnd);
this.bnd = bnd;
// this.options = options;
}
public interface CreateOptions extends Options {
String[] properties();
String bsn();
Version version();
Instructions match();
String output();
Glob extension();
}
public void _create(CreateOptions options) throws Exception {
Builder b = new Builder();
bnd.addClose(b);
b.setBase(bnd.getBase());
if (options.properties() != null) {
for (String propertyFile : options.properties()) {
File pf = bnd.getFile(propertyFile);
b.addProperties(pf);
}
}
if (options.bsn() != null)
b.setProperty(Constants.BUNDLE_SYMBOLICNAME, options.bsn());
if (options.version() != null)
b.setProperty(Constants.BUNDLE_VERSION, options.version().toString());
Instructions match = options.match();
Parameters packages = new Parameters();
Parameters capabilities = new Parameters();
Collection<String> paths = new ArrayList<>(new Parameters(b.getProperty("-paths"), bnd).keySet());
if (paths.isEmpty())
paths = options._arguments();
logger.debug("input {}", paths);
ResourceBuilder pb = new ResourceBuilder();
for (String root : paths) {
File f = bnd.getFile(root);
if (!f.exists()) {
error("could not find %s", f);
} else {
Glob g = options.extension();
if (g == null)
g = new Glob("*.jar");
Collection<File> files = IO.tree(f, "*.jar");
logger.debug("will profile {}", files);
for (File file : files) {
Domain domain = Domain.domain(file);
if (domain == null) {
error("Not a bundle because no manifest %s", file);
continue;
}
String bsn = domain.getBundleSymbolicName().getKey();
if (bsn == null) {
error("Not a bundle because no manifest %s", file);
continue;
}
if (match != null) {
Instruction instr = match.finder(bsn);
if (instr == null || instr.isNegated()) {
logger.debug("skipped {} because of non matching bsn {}", file, bsn);
continue;
}
}
Parameters eps = domain.getExportPackage();
Parameters pcs = domain.getProvideCapability();
logger.debug("parse {}:\ncaps: {}\npac: {}\n", file, pcs, eps);
packages.mergeWith(eps, false);
capabilities.mergeWith(pcs, false);
}
}
}
b.setProperty(Constants.PROVIDE_CAPABILITY, capabilities.toString());
b.setProperty(Constants.EXPORT_PACKAGE, packages.toString());
logger.debug("Found {} packages and {} capabilities", packages.size(), capabilities.size());
Jar jar = b.build();
File f = b.getOutputFile(options.output());
logger.debug("Saving as {}", f);
jar.write(f);
}
}
| apache-2.0 |
bseber/fubatra-archiv | src/main/java/de/fubatra/archiv/shared/domain/UserInfoSeasonProxy.java | 887 | package de.fubatra.archiv.shared.domain;
import com.google.gwt.view.client.ProvidesKey;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
import de.fubatra.archiv.server.domain.UserInfoSeason;
import de.fubatra.archiv.server.ioc.ObjectifyEntityLocator;
@ProxyFor(value = UserInfoSeason.class, locator = ObjectifyEntityLocator.class)
public interface UserInfoSeasonProxy extends EntityProxy {
public class KeyProvider implements ProvidesKey<UserInfoSeasonProxy> {
@Override
public Object getKey(UserInfoSeasonProxy item) {
return item.getId();
}
}
Long getId();
UserInfoProxy getOwner();
void setOwner(UserInfoProxy owner);
String getSeason();
void setSeason(String season);
String getClub();
void setClub(String club);
Team getTeam();
void setTeam(Team team);
}
| apache-2.0 |
lchli/ListItemAsyncDataLoader | LoaderLibrary/app/src/main/java/com/lchli/loaderlibrary/example/phoneInfoList/PhoneInfoResponse.java | 787 | package com.lchli.loaderlibrary.example.phoneInfoList;
/**
* Created by lchli on 2016/4/24.
*/
public class PhoneInfoResponse {
public int errNum;
public String errMsg;
public PhoneInfo retData;
public static class PhoneInfo {
public String telString;
public String province;
public String carrier;
public int memorySize() {
int size = 0;
if (telString != null) {
size += telString.getBytes().length;
}
if (province != null) {
size += province.getBytes().length;
}
if (carrier != null) {
size += carrier.getBytes().length;
}
return size;
}
}
}
| apache-2.0 |
ChiangC/FMTech | GooglePlay6.0.5/app/src/main/java/com/google/android/wallet/ui/simple/SimpleFragment.java | 30220 | package com.google.android.wallet.ui.simple;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MarginLayoutParamsCompat;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.google.android.wallet.analytics.UiNode;
import com.google.android.wallet.analytics.WalletUiElement;
import com.google.android.wallet.common.address.AddressUtils;
import com.google.android.wallet.common.address.RegionCode;
import com.google.android.wallet.dependencygraph.DependencyGraphManager;
import com.google.android.wallet.dependencygraph.TriggerListener;
import com.google.android.wallet.ui.address.AddressEntryFragment;
import com.google.android.wallet.ui.common.BaseWalletUiComponentFragment;
import com.google.android.wallet.ui.common.ClickSpan.OnClickListener;
import com.google.android.wallet.ui.common.FormEditText;
import com.google.android.wallet.ui.common.FormFragment;
import com.google.android.wallet.ui.common.FormFragment.FieldData;
import com.google.android.wallet.ui.common.FormHeaderView;
import com.google.android.wallet.ui.common.InfoMessageTextView;
import com.google.android.wallet.ui.common.OnAutoAdvanceListener;
import com.google.android.wallet.ui.common.OtpFieldFragment;
import com.google.android.wallet.ui.common.RegionCodeView;
import com.google.android.wallet.ui.common.TooltipDialogFragment;
import com.google.android.wallet.ui.common.TooltipUiFieldView.OnTooltipIconClickListener;
import com.google.android.wallet.ui.common.UiFieldBuilder;
import com.google.android.wallet.ui.common.WalletUiUtils;
import com.google.android.wallet.ui.common.WebViewDialogFragment;
import com.google.android.wallet.uicomponents.R.attr;
import com.google.android.wallet.uicomponents.R.id;
import com.google.android.wallet.uicomponents.R.layout;
import com.google.commerce.payments.orchestration.proto.ui.common.FormFieldReferenceOuterClass.FormFieldReference;
import com.google.commerce.payments.orchestration.proto.ui.common.UiErrorOuterClass.FormFieldMessage;
import com.google.commerce.payments.orchestration.proto.ui.common.components.AddressFormOuterClass.AddressForm;
import com.google.commerce.payments.orchestration.proto.ui.common.components.AddressFormOuterClass.CountrySelector;
import com.google.commerce.payments.orchestration.proto.ui.common.components.FormHeaderOuterClass.FormHeader;
import com.google.commerce.payments.orchestration.proto.ui.common.components.OtpFieldOuterClass.OtpField;
import com.google.commerce.payments.orchestration.proto.ui.common.components.SimpleFormOuterClass.Field;
import com.google.commerce.payments.orchestration.proto.ui.common.components.SimpleFormOuterClass.FieldValue;
import com.google.commerce.payments.orchestration.proto.ui.common.components.SimpleFormOuterClass.SimpleForm;
import com.google.commerce.payments.orchestration.proto.ui.common.components.SimpleFormOuterClass.SimpleForm.FormField;
import com.google.commerce.payments.orchestration.proto.ui.common.components.SimpleFormOuterClass.SimpleFormValue;
import com.google.commerce.payments.orchestration.proto.ui.common.components.SimpleFormOuterClass.SimpleFormValue.FormFieldValue;
import com.google.commerce.payments.orchestration.proto.ui.common.components.SimpleFormOuterClass.SubForm;
import com.google.commerce.payments.orchestration.proto.ui.common.components.SimpleFormOuterClass.SubFormValue;
import com.google.commerce.payments.orchestration.proto.ui.common.components.legal.LegalMessageOuterClass.LegalMessage;
import com.google.commerce.payments.orchestration.proto.ui.common.generic.InfoMessageOuterClass.InfoMessage;
import com.google.commerce.payments.orchestration.proto.ui.common.generic.TooltipOuterClass.Tooltip;
import com.google.commerce.payments.orchestration.proto.ui.common.generic.UiFieldOuterClass.UiField;
import java.util.ArrayList;
import java.util.List;
public class SimpleFragment
extends FormFragment<SimpleFormOuterClass.SimpleForm>
implements ClickSpan.OnClickListener, TooltipUiFieldView.OnTooltipIconClickListener
{
final ArrayList<AddressEntryFragment> mAddressFragments = new ArrayList();
private final ArrayList<UiNode> mChildUiNodes = new ArrayList();
final ArrayList<RegionCodeView> mCountrySelectors = new ArrayList();
private int mInfoMessageLayout;
final ArrayList<InfoMessageTextView> mInfoMessages = new ArrayList();
final ArrayList<View> mLegalMessages = new ArrayList();
private int mNextViewId = 1;
final ArrayList<OtpFieldFragment> mOtpFields = new ArrayList();
final ArrayList<int[]> mRegionCodeLists = new ArrayList();
private final ArrayList<Integer> mRevealBelowTriggerChildViewIndices = new ArrayList();
private final ArrayList<Integer> mRevealBelowTriggerGrandChildViewIndices = new ArrayList();
private int mRevealBelowTriggeredCount;
LinearLayout mRootView;
final ArrayList<SimpleFormFieldData> mSimpleFormFieldDataList = new ArrayList();
private final ArrayList<ArrayList<UiNode>> mSubFormChildUiNodes = new ArrayList();
private final ArrayList<UiNode> mSubFormUiNodes = new ArrayList();
private final WalletUiElement mUiElement = new WalletUiElement(1715);
final ArrayList<View> mUiFields = new ArrayList();
private void addLeafUiNodeToUiNodeTree(UiNode paramUiNode, int paramInt)
{
if (paramInt < 0)
{
this.mChildUiNodes.add(paramUiNode);
return;
}
paramUiNode.setParentUiNode((UiNode)this.mSubFormUiNodes.get(paramInt));
((ArrayList)this.mSubFormChildUiNodes.get(paramInt)).add(paramUiNode);
}
private void createField(ViewGroup paramViewGroup, SimpleFormOuterClass.Field paramField, String paramString, int paramInt1, int paramInt2)
{
int i = this.mNextViewId;
this.mNextViewId = (i + 1);
Object localObject1;
int j;
int k;
int m;
Object localObject2;
Object localObject3;
int i1;
label180:
OnAutoAdvanceListener local2;
if (paramField.uiField != null)
{
UiFieldBuilder localUiFieldBuilder = new UiFieldBuilder(paramField.uiField, this.mThemedInflater);
localUiFieldBuilder.mActivity = getActivity();
localUiFieldBuilder.mViewId = i;
localUiFieldBuilder.mOnTooltipIconClickListener = this;
localObject1 = localUiFieldBuilder.build();
j = 1;
k = this.mUiFields.size();
m = paramField.uiField.uiReference;
localObject2 = localObject1;
localObject3 = WalletUiUtils.getInitialValue(paramField.uiField);
this.mUiFields.add(localObject1);
WalletUiUtils.addComponentToDependencyGraph(localObject1, paramField.uiField.uiReference, this.mDependencyGraphManager, this.mTriggerListener);
if (paramField.hideFieldsBelow)
{
final int n = this.mRevealBelowTriggerChildViewIndices.size();
this.mRevealBelowTriggerChildViewIndices.add(Integer.valueOf(this.mRootView.getChildCount()));
ArrayList localArrayList = this.mRevealBelowTriggerGrandChildViewIndices;
if (paramInt1 != -1) {
break label881;
}
i1 = -1;
localArrayList.add(Integer.valueOf(i1));
if (n >= this.mRevealBelowTriggeredCount)
{
local2 = new OnAutoAdvanceListener()
{
public final void onAutoAdvance(View paramAnonymousView)
{
SimpleFragment.access$100(SimpleFragment.this, n);
}
};
View localView = WalletUiUtils.getBaseUiFieldView((View)localObject1);
if (!(localView instanceof FormEditText)) {
break label890;
}
((FormEditText)localView).addOnAutoAdvanceListener(local2);
}
}
}
for (;;)
{
((View)localObject1).setTag(R.id.field_type, Integer.valueOf(j));
paramViewGroup.addView((View)localObject1);
SimpleFormFieldData localSimpleFormFieldData = new SimpleFormFieldData(m, localObject2, localObject3);
localSimpleFormFieldData.mFieldType = j;
localSimpleFormFieldData.mIdxInFieldType = k;
localSimpleFormFieldData.mFormHeaderId = paramString;
localSimpleFormFieldData.mIdxInParent = paramInt2;
this.mSimpleFormFieldDataList.add(localSimpleFormFieldData);
return;
if (paramField.addressForm != null)
{
localObject1 = new FrameLayout(this.mThemedContext);
((View)localObject1).setId(i);
AddressEntryFragment localAddressEntryFragment = (AddressEntryFragment)getChildFragmentManager().findFragmentById(i);
if (localAddressEntryFragment == null)
{
localAddressEntryFragment = AddressEntryFragment.newInstance(paramField.addressForm, this.mThemeResourceId);
getChildFragmentManager().beginTransaction().add(i, localAddressEntryFragment).commit();
}
j = 4;
k = this.mAddressFragments.size();
m = paramField.addressForm.uiReference;
localObject2 = localAddressEntryFragment;
this.mAddressFragments.add(localAddressEntryFragment);
addLeafUiNodeToUiNodeTree(localAddressEntryFragment, paramInt1);
localObject3 = null;
break;
}
if (paramField.infoMessage != null)
{
InfoMessageTextView localInfoMessageTextView = (InfoMessageTextView)this.mThemedInflater.inflate(this.mInfoMessageLayout, paramViewGroup, false);
localInfoMessageTextView.setId(i);
localInfoMessageTextView.setInfoMessage(paramField.infoMessage);
localInfoMessageTextView.setUrlClickListener(this);
k = this.mInfoMessages.size();
m = paramField.infoMessage.uiReference;
localObject2 = localInfoMessageTextView;
this.mInfoMessages.add(localInfoMessageTextView);
addLeafUiNodeToUiNodeTree(localInfoMessageTextView, paramInt1);
localObject1 = localInfoMessageTextView;
localObject3 = null;
j = 0;
break;
}
if (paramField.otpField != null)
{
localObject1 = new FrameLayout(this.mThemedContext);
((View)localObject1).setId(i);
OtpFieldFragment localOtpFieldFragment = (OtpFieldFragment)getChildFragmentManager().findFragmentById(i);
if (localOtpFieldFragment == null)
{
localOtpFieldFragment = createOtpFieldFragment(paramField.otpField);
getChildFragmentManager().beginTransaction().add(i, localOtpFieldFragment).commit();
}
localOtpFieldFragment.registerDependencyGraphComponents(this.mDependencyGraphManager, this.mTriggerListener);
j = 2;
k = this.mOtpFields.size();
m = paramField.otpField.otp.uiReference;
localObject2 = localOtpFieldFragment;
this.mOtpFields.add(localOtpFieldFragment);
addLeafUiNodeToUiNodeTree(localOtpFieldFragment, paramInt1);
localObject3 = null;
break;
}
if (paramField.countrySelector != null)
{
RegionCodeView localRegionCodeView = (RegionCodeView)this.mThemedInflater.inflate(R.layout.view_region_code, paramViewGroup, false);
localRegionCodeView.setId(i);
k = this.mCountrySelectors.size();
int[] arrayOfInt;
if (this.mRegionCodeLists.size() > k) {
arrayOfInt = (int[])this.mRegionCodeLists.get(k);
}
for (;;)
{
localRegionCodeView.setFormHeader(paramField.countrySelector.formHeader);
localRegionCodeView.setRegionCodes(arrayOfInt);
localRegionCodeView.setSelectedRegionCode$2563266(RegionCode.toRegionCode(paramField.countrySelector.initialCountryCode));
j = 3;
m = paramField.countrySelector.formHeader.uiReference;
localObject2 = localRegionCodeView;
this.mCountrySelectors.add(localRegionCodeView);
localObject1 = localRegionCodeView;
DependencyGraphManager localDependencyGraphManager = this.mDependencyGraphManager;
TriggerListener localTriggerListener = this.mTriggerListener;
WalletUiUtils.addComponentToDependencyGraph(localRegionCodeView, m, localDependencyGraphManager, localTriggerListener);
localObject3 = paramField.countrySelector.initialCountryCode;
break;
arrayOfInt = AddressUtils.scrubAndSortRegionCodes(AddressUtils.stringArrayToRegionCodeArray(paramField.countrySelector.allowedCountryCode));
this.mRegionCodeLists.add(arrayOfInt);
}
}
throw new IllegalArgumentException("Empty or unknown field in SimpleForm.");
label881:
i1 = paramViewGroup.getChildCount();
break label180;
label890:
if (j != 2) {
break label916;
}
((OtpFieldFragment)this.mOtpFields.get(k)).addOnAutoAdvanceListener(local2);
}
label916:
throw new IllegalStateException("Invalid field type for hideFieldsBelow");
}
private SimpleFormOuterClass.FieldValue getFieldValue(SimpleFormOuterClass.Field paramField, int paramInt, Bundle paramBundle)
{
SimpleFormOuterClass.FieldValue localFieldValue = new SimpleFormOuterClass.FieldValue();
SimpleFormFieldData localSimpleFormFieldData = (SimpleFormFieldData)this.mSimpleFormFieldDataList.get(paramInt);
switch (localSimpleFormFieldData.mFieldType)
{
default:
throw new IllegalStateException("Unknown field type " + localSimpleFormFieldData.mFieldType + " in SimpleForm.");
case 1:
localFieldValue.uiFieldValue = WalletUiUtils.createUiFieldValue((View)this.mUiFields.get(localSimpleFormFieldData.mIdxInFieldType), paramField.uiField);
case 0:
return localFieldValue;
case 4:
localFieldValue.addressFormValue = ((AddressEntryFragment)this.mAddressFragments.get(localSimpleFormFieldData.mIdxInFieldType)).getAddressFormValue$64352f99();
return localFieldValue;
case 2:
localFieldValue.otpFieldValue = ((OtpFieldFragment)this.mOtpFields.get(localSimpleFormFieldData.mIdxInFieldType)).getFieldValue(paramBundle);
return localFieldValue;
}
localFieldValue.countrySelectorValue = ((RegionCodeView)this.mCountrySelectors.get(localSimpleFormFieldData.mIdxInFieldType)).getFieldValue();
return localFieldValue;
}
private void hideBelow()
{
if (this.mRevealBelowTriggeredCount == this.mRevealBelowTriggerChildViewIndices.size()) {}
for (;;)
{
return;
int i = ((Integer)this.mRevealBelowTriggerChildViewIndices.get(this.mRevealBelowTriggeredCount)).intValue();
int j = ((Integer)this.mRevealBelowTriggerGrandChildViewIndices.get(this.mRevealBelowTriggeredCount)).intValue();
int k = i + 1;
int m = this.mRootView.getChildCount();
while (k < m)
{
this.mRootView.getChildAt(k).setVisibility(8);
k++;
}
if (j >= 0)
{
ViewGroup localViewGroup = (ViewGroup)this.mRootView.getChildAt(i);
int n = j + 1;
int i1 = localViewGroup.getChildCount();
while (n < i1)
{
localViewGroup.getChildAt(n).setVisibility(8);
n++;
}
}
}
}
public final boolean applyFormFieldMessage(UiErrorOuterClass.FormFieldMessage paramFormFieldMessage)
{
int i = 0;
int j = this.mSimpleFormFieldDataList.size();
while (i < j)
{
SimpleFormFieldData localSimpleFormFieldData = (SimpleFormFieldData)this.mSimpleFormFieldDataList.get(i);
if ((paramFormFieldMessage.formFieldReference.formId.equals(localSimpleFormFieldData.mFormHeaderId)) && (paramFormFieldMessage.formFieldReference.repeatedFieldIndex == localSimpleFormFieldData.mIdxInParent))
{
if (localSimpleFormFieldData.mFieldType == 1) {
WalletUiUtils.setUiFieldError((View)this.mUiFields.get(localSimpleFormFieldData.mIdxInFieldType), paramFormFieldMessage.message);
}
for (;;)
{
return true;
if (localSimpleFormFieldData.mFieldType != 2) {
break;
}
((OtpFieldFragment)this.mOtpFields.get(localSimpleFormFieldData.mIdxInFieldType)).setError(paramFormFieldMessage.message);
}
throw new IllegalArgumentException("Could not apply FormFieldMessage to fieldId: " + paramFormFieldMessage.formFieldReference.fieldId);
}
i++;
}
int k = 0;
int m = this.mAddressFragments.size();
while (k < m)
{
if (((AddressEntryFragment)this.mAddressFragments.get(k)).applyFormFieldMessage(paramFormFieldMessage)) {
return true;
}
k++;
}
return false;
}
public OtpFieldFragment createOtpFieldFragment(OtpFieldOuterClass.OtpField paramOtpField)
{
return OtpFieldFragment.newInstance(paramOtpField, this.mThemeResourceId);
}
protected final void doEnableUi()
{
if (this.mUiFields.size() + this.mAddressFragments.size() + this.mInfoMessages.size() + this.mOtpFields.size() + this.mLegalMessages.size() == 0) {}
for (;;)
{
return;
boolean bool = this.mUiEnabled;
int i = 0;
int j = this.mUiFields.size();
while (i < j)
{
((View)this.mUiFields.get(i)).setEnabled(bool);
i++;
}
int k = 0;
int m = this.mAddressFragments.size();
while (k < m)
{
((AddressEntryFragment)this.mAddressFragments.get(k)).enableUi(bool);
k++;
}
int n = 0;
int i1 = this.mInfoMessages.size();
while (n < i1)
{
((InfoMessageTextView)this.mInfoMessages.get(n)).setEnabled(bool);
n++;
}
int i2 = 0;
int i3 = this.mOtpFields.size();
while (i2 < i3)
{
((OtpFieldFragment)this.mOtpFields.get(i2)).enableUi(bool);
i2++;
}
int i4 = 0;
int i5 = this.mCountrySelectors.size();
while (i4 < i5)
{
((RegionCodeView)this.mCountrySelectors.get(i4)).setEnabled(bool);
i4++;
}
int i6 = 0;
int i7 = this.mLegalMessages.size();
while (i6 < i7)
{
((View)this.mLegalMessages.get(i6)).setEnabled(bool);
i6++;
}
}
}
public List<UiNode> getChildren()
{
return this.mChildUiNodes;
}
public final List<SimpleFormFieldData> getFieldsForValidationInOrder()
{
return this.mSimpleFormFieldDataList;
}
public final SimpleFormOuterClass.SimpleFormValue getSimpleFormValue(Bundle paramBundle)
{
SimpleFormOuterClass.SimpleFormValue localSimpleFormValue = new SimpleFormOuterClass.SimpleFormValue();
localSimpleFormValue.id = ((SimpleFormOuterClass.SimpleForm)this.mFormProto).formHeader.id;
localSimpleFormValue.dataToken = ((SimpleFormOuterClass.SimpleForm)this.mFormProto).formHeader.dataToken;
localSimpleFormValue.formFieldValue = new SimpleFormOuterClass.SimpleFormValue.FormFieldValue[((SimpleFormOuterClass.SimpleForm)this.mFormProto).formField.length];
int i = 0;
int j = ((SimpleFormOuterClass.SimpleForm)this.mFormProto).formField.length;
int k = 0;
SimpleFormOuterClass.SimpleForm.FormField localFormField;
int i1;
if (i < j)
{
localFormField = ((SimpleFormOuterClass.SimpleForm)this.mFormProto).formField[i];
localSimpleFormValue.formFieldValue[i] = new SimpleFormOuterClass.SimpleFormValue.FormFieldValue();
if (localFormField.subForm != null)
{
SimpleFormOuterClass.SubFormValue localSubFormValue = new SimpleFormOuterClass.SubFormValue();
localSubFormValue.id = localFormField.subForm.formHeader.id;
localSubFormValue.dataToken = localFormField.subForm.formHeader.dataToken;
localSubFormValue.fieldValue = new SimpleFormOuterClass.FieldValue[localFormField.subForm.field.length];
int m = 0;
int n = localFormField.subForm.field.length;
while (m < n)
{
SimpleFormOuterClass.FieldValue[] arrayOfFieldValue = localSubFormValue.fieldValue;
SimpleFormOuterClass.Field localField1 = localFormField.subForm.field[m];
int i2 = k + 1;
arrayOfFieldValue[m] = getFieldValue(localField1, k, paramBundle);
m++;
k = i2;
}
if (localFormField.subForm.legalMessage != null) {
localSubFormValue.legalDocData = localFormField.subForm.legalMessage.opaqueData;
}
localSimpleFormValue.formFieldValue[i].subFormValue = localSubFormValue;
i1 = k;
}
}
for (;;)
{
i++;
k = i1;
break;
if (localFormField.field != null)
{
SimpleFormOuterClass.SimpleFormValue.FormFieldValue localFormFieldValue = localSimpleFormValue.formFieldValue[i];
SimpleFormOuterClass.Field localField2 = localFormField.field;
i1 = k + 1;
localFormFieldValue.fieldValue = getFieldValue(localField2, k, paramBundle);
continue;
if (((SimpleFormOuterClass.SimpleForm)this.mFormProto).legalMessage != null) {
localSimpleFormValue.legalDocData = ((SimpleFormOuterClass.SimpleForm)this.mFormProto).legalMessage.opaqueData;
}
return localSimpleFormValue;
}
else
{
i1 = k;
}
}
}
public WalletUiElement getUiElement()
{
return this.mUiElement;
}
public final boolean isReadyToSubmit()
{
int i = 0;
int j = this.mAddressFragments.size();
while (i < j)
{
this.mAddressFragments.get(i);
i++;
}
return this.mRevealBelowTriggeredCount >= this.mRevealBelowTriggerChildViewIndices.size();
}
public final void onClick(View paramView, String paramString)
{
if (this.mFragmentManager.findFragmentByTag("tagWebViewDialog") != null) {
return;
}
WebViewDialogFragment.newInstance(paramString, this.mThemeResourceId).show(this.mFragmentManager, "tagWebViewDialog");
}
public final void onClick(TooltipOuterClass.Tooltip paramTooltip)
{
if (this.mFragmentManager.findFragmentByTag("tagTooltipDialog") != null) {
return;
}
TooltipDialogFragment localTooltipDialogFragment = TooltipDialogFragment.newInstance(paramTooltip, this.mThemeResourceId);
localTooltipDialogFragment.setTargetFragment(this, -1);
localTooltipDialogFragment.show(this.mFragmentManager, "tagTooltipDialog");
}
public final void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
if (paramBundle != null)
{
int j;
for (int i = 0;; i = j)
{
StringBuilder localStringBuilder = new StringBuilder("regionCodes_");
j = i + 1;
int[] arrayOfInt = paramBundle.getIntArray(i);
if (arrayOfInt == null) {
break;
}
this.mRegionCodeLists.add(arrayOfInt);
}
}
}
protected final View onCreateThemedView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
{
ContextThemeWrapper localContextThemeWrapper = this.mThemedContext;
int[] arrayOfInt = new int[4];
arrayOfInt[0] = R.attr.internalUicInfoMessageLayout;
arrayOfInt[1] = R.attr.internalUicLegalMessageLayout;
arrayOfInt[2] = R.attr.internalUicFormNonEditableTextStartMargin;
arrayOfInt[3] = R.attr.uicLegalMessageTopMargin;
TypedArray localTypedArray = localContextThemeWrapper.obtainStyledAttributes(arrayOfInt);
this.mInfoMessageLayout = localTypedArray.getResourceId(0, R.layout.view_info_message_text);
int i = localTypedArray.getResourceId(1, R.layout.view_legal_message_text);
int j = localTypedArray.getDimensionPixelSize(2, 0);
int k = localTypedArray.getDimensionPixelSize(3, 0);
localTypedArray.recycle();
this.mRootView = ((LinearLayout)paramLayoutInflater.inflate(R.layout.fragment_simple, null));
this.mNextViewId = ((FormHeaderView)this.mRootView.findViewById(R.id.header)).setFormHeader(((SimpleFormOuterClass.SimpleForm)this.mFormProto).formHeader, paramLayoutInflater, this, this, this.mChildUiNodes, this.mNextViewId);
final WalletUiElement localWalletUiElement = new WalletUiElement(1716);
int m = 0;
int n = ((SimpleFormOuterClass.SimpleForm)this.mFormProto).formField.length;
if (m < n)
{
SimpleFormOuterClass.SimpleForm.FormField localFormField = ((SimpleFormOuterClass.SimpleForm)this.mFormProto).formField[m];
if (localFormField.subForm != null)
{
final int i2 = this.mSubFormChildUiNodes.size();
this.mSubFormChildUiNodes.add(new ArrayList());
UiNode local1 = new UiNode()
{
public final List<UiNode> getChildren()
{
return (List)SimpleFragment.this.mSubFormChildUiNodes.get(i2);
}
public final UiNode getParentUiNode()
{
return SimpleFragment.this;
}
public final WalletUiElement getUiElement()
{
return localWalletUiElement;
}
public final void setParentUiNode(UiNode paramAnonymousUiNode)
{
throw new UnsupportedOperationException("Custom parents not supported for SimpleForm subforms.");
}
};
this.mChildUiNodes.add(local1);
this.mSubFormUiNodes.add(local1);
LinearLayout localLinearLayout = (LinearLayout)paramLayoutInflater.inflate(R.layout.view_subform, this.mRootView, false);
this.mNextViewId = ((FormHeaderView)localLinearLayout.findViewById(R.id.subform_header)).setFormHeader(localFormField.subForm.formHeader, paramLayoutInflater, this, local1, (List)this.mSubFormChildUiNodes.get(i2), this.mNextViewId);
int i3 = 0;
int i4 = localFormField.subForm.field.length;
while (i3 < i4)
{
createField(localLinearLayout, localFormField.subForm.field[i3], localFormField.subForm.formHeader.id, i2, i3);
i3++;
}
if (localFormField.subForm.legalMessage != null)
{
View localView2 = WalletUiUtils.createViewForLegalMessage(this.mThemedInflater, i, localFormField.subForm.legalMessage, this, this);
int i5 = this.mNextViewId;
this.mNextViewId = (i5 + 1);
localView2.setId(i5);
localLinearLayout.addView(localView2);
this.mLegalMessages.add(localView2);
((ArrayList)this.mSubFormChildUiNodes.get(i2)).add((UiNode)localView2);
ViewGroup.MarginLayoutParams localMarginLayoutParams2 = (ViewGroup.MarginLayoutParams)localView2.getLayoutParams();
MarginLayoutParamsCompat.setMarginStart(localMarginLayoutParams2, j);
localMarginLayoutParams2.topMargin = k;
localMarginLayoutParams2.bottomMargin = k;
}
this.mRootView.addView(localLinearLayout);
}
for (;;)
{
m++;
break;
if (localFormField.field == null) {
break label566;
}
createField(this.mRootView, localFormField.field, ((SimpleFormOuterClass.SimpleForm)this.mFormProto).formHeader.id, -1, m);
}
label566:
throw new IllegalArgumentException("Empty or unknown form field in SimpleForm.");
}
if (((SimpleFormOuterClass.SimpleForm)this.mFormProto).legalMessage != null)
{
View localView1 = WalletUiUtils.createViewForLegalMessage(this.mThemedInflater, i, ((SimpleFormOuterClass.SimpleForm)this.mFormProto).legalMessage, this, this);
int i1 = this.mNextViewId;
this.mNextViewId = (i1 + 1);
localView1.setId(i1);
this.mRootView.addView(localView1);
this.mLegalMessages.add(localView1);
this.mChildUiNodes.add((UiNode)localView1);
ViewGroup.MarginLayoutParams localMarginLayoutParams1 = (ViewGroup.MarginLayoutParams)localView1.getLayoutParams();
MarginLayoutParamsCompat.setMarginStart(localMarginLayoutParams1, j);
localMarginLayoutParams1.topMargin = k;
}
if (paramBundle != null) {
this.mRevealBelowTriggeredCount = paramBundle.getInt("revealBelowTriggeredCount");
}
hideBelow();
doEnableUi();
notifyFormEvent(1, Bundle.EMPTY);
return this.mRootView;
}
public final void onDestroyView()
{
this.mChildUiNodes.clear();
this.mSubFormUiNodes.clear();
this.mSubFormChildUiNodes.clear();
this.mSimpleFormFieldDataList.clear();
this.mUiFields.clear();
this.mAddressFragments.clear();
this.mInfoMessages.clear();
this.mOtpFields.clear();
this.mCountrySelectors.clear();
this.mRegionCodeLists.clear();
this.mLegalMessages.clear();
super.onDestroyView();
}
public final void onSaveInstanceState(Bundle paramBundle)
{
super.onSaveInstanceState(paramBundle);
paramBundle.putInt("revealBelowTriggeredCount", this.mRevealBelowTriggeredCount);
int i = 0;
int j = this.mRegionCodeLists.size();
while (i < j)
{
paramBundle.putIntArray("regionCodes_" + i, (int[])this.mRegionCodeLists.get(i));
i++;
}
}
static final class SimpleFormFieldData<T>
extends FormFragment.FieldData<T>
{
int mFieldType;
String mFormHeaderId;
int mIdxInFieldType;
int mIdxInParent;
public SimpleFormFieldData(int paramInt, T paramT, Object paramObject)
{
super(paramT, paramObject);
}
}
}
/* Location: F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar
* Qualified Name: com.google.android.wallet.ui.simple.SimpleFragment
* JD-Core Version: 0.7.0.1
*/ | apache-2.0 |
ljmdbc7a/leetcode-java | src/main/java/com/ikouz/algorithm/leetcode/Tree_404_SumofLeftLeaves.java | 1136 | package com.ikouz.algorithm.leetcode;
import com.ikouz.algorithm.leetcode.domain.TreeNode;
import com.ikouz.algorithm.leetcode.utils.TestUtil;
/**
* Find the sum of all left leaves in a given binary tree.
* <p>
* Example:
* <p>
* 3
* / \
* 9 20
* / \
* 15 7
* <p>
* There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
*
* @author liujiaming
* @since 2017/05/21
*/
public class Tree_404_SumofLeftLeaves {
public static int sumOfLeftLeaves(TreeNode root) {
return doSumOfLeftLeaves(root, false);
}
private static int doSumOfLeftLeaves(TreeNode root, boolean isLeft) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
if (isLeft) {
return root.val;
} else {
return 0;
}
}
return doSumOfLeftLeaves(root.left, true) + doSumOfLeftLeaves(root.right, false);
}
public static void main(String[] args) {
System.out.println(sumOfLeftLeaves(TestUtil.buildTree("[3,9,20,null,null,15,7]")));
}
}
| apache-2.0 |
jmanday/Master | IM/Practicas/Practica2/playQuestion/app/src/main/java/com/jesusgarciamanday/playquestion/OtherGamesActivity.java | 2321 | package com.jesusgarciamanday.playquestion;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
/**
* Created by jesusgarciamanday on 1/2/17.
*/
public class OtherGamesActivity extends AppCompatActivity {
private Button buttonGame1, buttonGame2, buttonGame3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_other_games);
buttonGame1 = (Button) findViewById(R.id.buttonGame1);
buttonGame2 = (Button) findViewById(R.id.buttonGame2);
buttonGame3 = (Button) findViewById(R.id.buttonGame3);
buttonGame1.setText("PAC-ON DELUXE");
buttonGame2.setText("ZOMBIE CRISIS");
buttonGame3.setText("SUPER STACK");
setGames();
}
private void setGames(){
buttonGame1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(OtherGamesActivity.this, webViewActivity.class);
Bundle b = new Bundle();
b.putString("url", "https://m.minijuegos.com/juego/pac-xon-deluxe/jugar");
intent.putExtras(b);
startActivity(intent);
}
});
buttonGame2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(OtherGamesActivity.this, webViewActivity.class);
Bundle b = new Bundle();
b.putString("url", "https://m.minijuegos.com/juego/zombie-crisis/jugar");
intent.putExtras(b);
startActivity(intent);
}
});
buttonGame3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(OtherGamesActivity.this, webViewActivity.class);
Bundle b = new Bundle();
b.putString("url", "https://m.minijuegos.com/juego/super-stack/jugar");
intent.putExtras(b);
startActivity(intent);
}
});
}
}
| apache-2.0 |
DICL/cassandra | test/unit/org/apache/cassandra/utils/EncodedStreamsTest.java | 6823 | /*
* 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.cassandra.utils;
import java.io.*;
import com.google.common.collect.Iterators;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.KSMetaData;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.RowUpdateBuilder;
import org.apache.cassandra.db.TypeSizes;
import org.apache.cassandra.db.rows.*;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.locator.SimpleStrategy;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.utils.vint.EncodedDataInputStream;
import org.apache.cassandra.utils.vint.EncodedDataOutputStream;
public class EncodedStreamsTest
{
private static final String KEYSPACE1 = "Keyspace1";
private static final String CF_STANDARD = "Standard1";
private static final String CF_COUNTER = "Counter1";
private int version = MessagingService.current_version;
@BeforeClass
public static void defineSchema() throws ConfigurationException
{
SchemaLoader.prepareServer();
SchemaLoader.createKeyspace(KEYSPACE1,
SimpleStrategy.class,
KSMetaData.optsWithRF(1),
SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD),
SchemaLoader.counterCFMD(KEYSPACE1, CF_COUNTER));
}
@Test
public void testStreams() throws IOException
{
ByteArrayOutputStream byteArrayOStream1 = new ByteArrayOutputStream();
EncodedDataOutputStream odos = new EncodedDataOutputStream(byteArrayOStream1);
ByteArrayOutputStream byteArrayOStream2 = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteArrayOStream2);
for (short i = 0; i < 10000; i++)
{
out.writeShort(i);
odos.writeShort(i);
}
out.flush();
odos.flush();
for (int i = Short.MAX_VALUE; i < ((int)Short.MAX_VALUE + 10000); i++)
{
out.writeInt(i);
odos.writeInt(i);
}
out.flush();
odos.flush();
for (long i = Integer.MAX_VALUE; i < ((long)Integer.MAX_VALUE + 10000);i++)
{
out.writeLong(i);
odos.writeLong(i);
}
out.flush();
odos.flush();
Assert.assertTrue(byteArrayOStream1.size() < byteArrayOStream2.size());
ByteArrayInputStream byteArrayIStream1 = new ByteArrayInputStream(byteArrayOStream1.toByteArray());
EncodedDataInputStream idis = new EncodedDataInputStream(new DataInputStream(byteArrayIStream1));
// assert reading Short
for (int i = 0; i < 10000; i++)
Assert.assertEquals(i, idis.readShort());
// assert reading Integer
for (int i = Short.MAX_VALUE; i < ((int)Short.MAX_VALUE + 10000); i++)
Assert.assertEquals(i, idis.readInt());
// assert reading Long
for (long i = Integer.MAX_VALUE; i < ((long)Integer.MAX_VALUE) + 1000; i++)
Assert.assertEquals(i, idis.readLong());
}
private UnfilteredRowIterator createTable()
{
CFMetaData cfm = Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_STANDARD).metadata;
RowUpdateBuilder builder = new RowUpdateBuilder(cfm, 0, "key");
builder.clustering("vijay").add(cfm.partitionColumns().iterator().next(), "try").build();
builder.clustering("to").add(cfm.partitionColumns().iterator().next(), "be_nice").build();
return builder.unfilteredIterator();
}
private UnfilteredRowIterator createCounterTable()
{
CFMetaData cfm = Keyspace.open(KEYSPACE1).getColumnFamilyStore(CF_COUNTER).metadata;
RowUpdateBuilder builder = new RowUpdateBuilder(cfm, 0, "key");
builder.clustering("vijay").add(cfm.partitionColumns().iterator().next(), 1L).build();
builder.clustering("wants").add(cfm.partitionColumns().iterator().next(), 1000000L).build();
return builder.unfilteredIterator();
}
@Test
public void testCFSerialization() throws IOException
{
ByteArrayOutputStream byteArrayOStream1 = new ByteArrayOutputStream();
EncodedDataOutputStream odos = new EncodedDataOutputStream(byteArrayOStream1);
UnfilteredRowIteratorSerializer.serializer.serialize(createTable(), odos, version, 1);
ByteArrayInputStream byteArrayIStream1 = new ByteArrayInputStream(byteArrayOStream1.toByteArray());
EncodedDataInputStream odis = new EncodedDataInputStream(new DataInputStream(byteArrayIStream1));
UnfilteredRowIterator partition = UnfilteredRowIteratorSerializer.serializer.deserialize(odis, version, SerializationHelper.Flag.LOCAL);
Assert.assertTrue(Iterators.elementsEqual(partition, createTable()));
Assert.assertEquals(byteArrayOStream1.size(), (int) UnfilteredRowIteratorSerializer.serializer.serializedSize(createTable(), version, 1, TypeSizes.VINT));
}
@Test
public void testCounterCFSerialization() throws IOException
{
ByteArrayOutputStream byteArrayOStream1 = new ByteArrayOutputStream();
EncodedDataOutputStream odos = new EncodedDataOutputStream(byteArrayOStream1);
UnfilteredRowIteratorSerializer.serializer.serialize(createCounterTable(), odos, version, 1);
ByteArrayInputStream byteArrayIStream1 = new ByteArrayInputStream(byteArrayOStream1.toByteArray());
EncodedDataInputStream odis = new EncodedDataInputStream(new DataInputStream(byteArrayIStream1));
UnfilteredRowIterator partition = UnfilteredRowIteratorSerializer.serializer.deserialize(odis, version, SerializationHelper.Flag.LOCAL);
Assert.assertTrue(Iterators.elementsEqual(partition, createCounterTable()));
Assert.assertEquals(byteArrayOStream1.size(), (int) UnfilteredRowIteratorSerializer.serializer.serializedSize(createCounterTable(), version, 1, TypeSizes.VINT));
}
}
| apache-2.0 |
chmyga/component-runtime | component-server-parent/component-server/src/main/java/org/talend/sdk/component/server/front/security/CommandSecurityProvider.java | 2501 | /**
* Copyright (C) 2006-2020 Talend Inc. - www.talend.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.talend.sdk.component.server.front.security;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
import static org.talend.sdk.component.server.front.model.ErrorDictionary.UNAUTHORIZED;
import java.io.IOException;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.talend.sdk.component.server.front.model.error.ErrorPayload;
import org.talend.sdk.component.server.service.security.event.OnCommand;
@Provider
@Dependent
public class CommandSecurityProvider implements ContainerRequestFilter {
public static final String SKIP = CommandSecurityProvider.class.getName() + ".skip";
@Context
private HttpServletRequest request;
@Context
private ResourceInfo resourceInfo;
@Inject
private Event<OnCommand> onConnectionEvent;
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
if (Boolean.TRUE.equals(request.getAttribute(SKIP))) {
return;
}
final OnCommand onCommand = new OnCommand(resourceInfo.getResourceClass(), resourceInfo.getResourceMethod());
onConnectionEvent.fire(onCommand);
if (!onCommand.isValid()) {
requestContext
.abortWith(Response
.status(Response.Status.UNAUTHORIZED)
.entity(new ErrorPayload(UNAUTHORIZED, "Invalid command credentials"))
.type(APPLICATION_JSON_TYPE)
.build());
}
}
}
| apache-2.0 |
huitseeker/deeplearning4j | deeplearning4j-core/src/test/java/org/deeplearning4j/datasets/fetchers/SvhnDataFetcherTest.java | 642 | package org.deeplearning4j.datasets.fetchers;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.assertTrue;
/**
* @author saudet
*/
public class SvhnDataFetcherTest {
@Test
public void testMnistDataFetcher() throws Exception {
SvhnDataFetcher fetch = new SvhnDataFetcher();
File path = fetch.getDataSetPath(DataSetType.TRAIN);
File path2 = fetch.getDataSetPath(DataSetType.TEST);
File path3 = fetch.getDataSetPath(DataSetType.VALIDATION);
assertTrue(path.isDirectory());
assertTrue(path2.isDirectory());
assertTrue(path3.isDirectory());
}
}
| apache-2.0 |
eSCT/oppfin | src/main/java/org/datacontract/schemas/_2004/_07/EventKeywordMarket.java | 2167 |
package org.datacontract.schemas._2004._07;
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 eventKeywordMarket complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="eventKeywordMarket">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="keyField" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="labelField" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "eventKeywordMarket", propOrder = {
"keyField",
"labelField"
})
public class EventKeywordMarket {
@XmlElement(required = true, nillable = true)
protected String keyField;
@XmlElement(required = true, nillable = true)
protected String labelField;
/**
* Gets the value of the keyField property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKeyField() {
return keyField;
}
/**
* Sets the value of the keyField property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKeyField(String value) {
this.keyField = value;
}
/**
* Gets the value of the labelField property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLabelField() {
return labelField;
}
/**
* Sets the value of the labelField property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLabelField(String value) {
this.labelField = value;
}
}
| apache-2.0 |
bernd/samsa | src/main/java/com/github/bernd/samsa/cleaner/LogCleaningAbortedException.java | 104 | package com.github.bernd.samsa.cleaner;
public class LogCleaningAbortedException extends Exception {
}
| apache-2.0 |
donsunsoft/donsun-framework | donsun-jwebsoup/src/test/java/info/donsun/app/webparser/vo/UserVo.java | 5185 | /*
* Copyright (c) 2013, ORZII and/or its affiliates. All rights reserved. Use, Copy is subject to authorized license.
*/
package info.donsun.app.webparser.vo;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
/**
*
* @author Leo.du
* @date 2013-12-12
*/
@JsonRootName("user")
public class UserVo extends BaseVo {
private static final long serialVersionUID = 1L;
@JsonProperty("username")
private String username;
@JsonProperty("password")
private String password;
@JsonProperty("salt")
private String salt;
@JsonProperty("roles")
private String roles;
@JsonProperty("name")
private String name;
@JsonProperty("email")
private String email;
@JsonProperty("credits_id")
private Long creditsId;
@JsonProperty("balance_id")
private Long balanceId;
@JsonProperty("online_id")
private Long onlineId;
@JsonProperty("grade_id")
private Long gradeId;
@JsonProperty("exp")
private Long exp;
@JsonProperty("banned")
private Boolean banned;
@JsonProperty("ban_reason")
private String banReason;
@JsonProperty("remark")
private String remark;
@JsonProperty("register_ip")
private String registerIp;
@JsonProperty("created")
private Date created;
@JsonProperty("modified")
private Date modified;
@JsonProperty("active")
private Boolean active;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return this.username;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return this.password;
}
public void setSalt(String salt) {
this.salt = salt;
}
public String getSalt() {
return this.salt;
}
public void setRoles(String roles) {
this.roles = roles;
}
public String getRoles() {
return this.roles;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return this.email;
}
public void setCreditsId(Long creditsId) {
this.creditsId = creditsId;
}
public Long getCreditsId() {
return this.creditsId;
}
public void setBalanceId(Long balanceId) {
this.balanceId = balanceId;
}
public Long getBalanceId() {
return this.balanceId;
}
public void setOnlineId(Long onlineId) {
this.onlineId = onlineId;
}
public Long getOnlineId() {
return this.onlineId;
}
public void setGradeId(Long gradeId) {
this.gradeId = gradeId;
}
public Long getGradeId() {
return this.gradeId;
}
public void setExp(Long exp) {
this.exp = exp;
}
public Long getExp() {
return this.exp;
}
public void setBanned(Boolean banned) {
this.banned = banned;
}
public Boolean getBanned() {
return this.banned;
}
public void setBanReason(String banReason) {
this.banReason = banReason;
}
public String getBanReason() {
return this.banReason;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getRemark() {
return this.remark;
}
public void setRegisterIp(String registerIp) {
this.registerIp = registerIp;
}
public String getRegisterIp() {
return this.registerIp;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getCreated() {
return this.created;
}
public void setModified(Date modified) {
this.modified = modified;
}
public Date getModified() {
return this.modified;
}
public void setActive(Boolean active) {
this.active = active;
}
public Boolean getActive() {
return this.active;
}
private UserOnlineVo userOnlineVo;
public void setUserOnlineVo(UserOnlineVo userOnlineVo){
this.userOnlineVo = userOnlineVo;
}
public UserOnlineVo getUserOnlineVo() {
return userOnlineVo;
}
private UserGradeVo userGradeVo;
public void setUserGradeVo(UserGradeVo userGradeVo){
this.userGradeVo = userGradeVo;
}
public UserGradeVo getUserGradeVo() {
return userGradeVo;
}
private UserBalanceVo userBalanceVo;
public void setUserBalanceVo(UserBalanceVo userBalanceVo){
this.userBalanceVo = userBalanceVo;
}
public UserBalanceVo getUserBalanceVo() {
return userBalanceVo;
}
private UserCreditsVo userCreditsVo;
public void setUserCreditsVo(UserCreditsVo userCreditsVo){
this.userCreditsVo = userCreditsVo;
}
public UserCreditsVo getUserCreditsVo() {
return userCreditsVo;
}
}
| apache-2.0 |