repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
brightgenerous/fx-player | src/main/java/com/brightgenerous/fxplayer/url/HttpUtilsBuilder.java | 1819 | package com.brightgenerous.fxplayer.url;
import java.nio.charset.Charset;
public class HttpUtilsBuilder {
private String userAgent;
private String contentType;
private Charset encode;
private boolean selfSigned;
private boolean syncCookie;
private HttpUtilsBuilder() {
}
public static HttpUtilsBuilder create() {
return new HttpUtilsBuilder();
}
public static HttpUtilsBuilder createDefault() {
return create().userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)").encode("UTF-8");
}
public HttpUtils build() {
return new HttpUtils(userAgent, contentType, encode, selfSigned, syncCookie);
}
public String userAgent() {
return userAgent;
}
public HttpUtilsBuilder userAgent(String userAgent) {
this.userAgent = userAgent;
return this;
}
public String contentType() {
return contentType;
}
public HttpUtilsBuilder contentType(String contentType) {
this.contentType = contentType;
return this;
}
public Charset encode() {
return encode;
}
public HttpUtilsBuilder encode(Charset encode) {
this.encode = encode;
return this;
}
public HttpUtilsBuilder encode(String encode) {
return encode(Charset.forName(encode));
}
public boolean selfSigned() {
return selfSigned;
}
public HttpUtilsBuilder selfSigned(boolean selfSigned) {
this.selfSigned = selfSigned;
return this;
}
public boolean syncCookie() {
return syncCookie;
}
public HttpUtilsBuilder syncCookie(boolean syncCookie) {
this.syncCookie = syncCookie;
return this;
}
}
| apache-2.0 |
shell88/bdd_videoannotator | java/src/test/java/stepdefinitions/ReportingTest.java | 8104 | package stepdefinitions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.contains;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.refEq;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.mockito.InOrder;
import stepdef.helper.IsSameStringArrayArray;
import stepdef.helper.TestUtils;
import stepdef.subtest.CucumberSubTestThreadWithAdapterInstance;
import com.github.shell88.bddvideoannotator.javaadapters.CucumberReportingAdapter;
import com.github.shell88.bddvideoannotator.javaadapters.ServerConnector;
import com.github.shell88.bddvideoannotator.stubjava.AnnotationService;
import com.github.shell88.bddvideoannotator.stubjava.StepResult;
import com.github.shell88.bddvideoannotator.stubjava.StringArray;
import com.github.shell88.bddvideoannotator.stubjava.StringArrayArray;
import cucumber.api.DataTable;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import gherkin.formatter.model.DataTableRow;
import java.io.File;
import java.util.List;
public class ReportingTest {
private AnnotationService mockedClient;
private CucumberReportingAdapter mockedAdapter;
private String[] expectedSteps;
private File subTestDirectory;
private int scenariosToStop = 0;
private InOrder orderedVerifier;
@Given("^i have an instance of the BDD-Adapter for Cucumber-JVM with a mocked server connection$")
public void i_have_an_instance_of_the_BDD_Adapter_for_Cucumber_JVM_with_a_mocked_server_connection()
throws Throwable {
mockedClient = mock(AnnotationService.class);
ServerConnector mockedServerConnector = mock(ServerConnector.class);
when(mockedServerConnector.startServerProcess()).thenReturn(mockedClient);
when(mockedServerConnector.getServerClient()).thenReturn(mockedClient);
mockedAdapter = new CucumberReportingAdapter(mockedServerConnector);
orderedVerifier = inOrder(mockedClient);
}
@Given("^I have a feature file:$")
public void i_have_a_feature_file(String contentFeatureFile) throws Throwable {
if (subTestDirectory == null) {
subTestDirectory = TestUtils.getNewSubTestDirectory();
}
File featureFileTemp = new File(subTestDirectory, "test.feature");
FileUtils.write(featureFileTemp, contentFeatureFile);
}
@Given("^i have a step definition file with following methods:$")
public void i_have_a_step_definition_file_with_following_methods(
String methodsString) throws Throwable {
if (subTestDirectory == null) {
subTestDirectory = TestUtils.getNewSubTestDirectory();
}
File stepDefFile = new File(subTestDirectory, "StepDef.java");
FileUtils.write(stepDefFile, "package " + subTestDirectory.getName()
+ ";\n");
FileUtils.write(stepDefFile, "import cucumber.api.java.en.*;\n", true);
FileUtils.write(stepDefFile, "import cucumber.api.java.After;\n", true);
FileUtils.write(stepDefFile, "import cucumber.api.java.Before;\n", true);
FileUtils.write(stepDefFile, "public class StepDef{\n\n", true);
FileUtils.write(stepDefFile, methodsString, true);
FileUtils.write(stepDefFile, "\n}", true);
List<String> messages = TestUtils.compileJavaFile(stepDefFile);
assertEquals(StringUtils.join(messages, "\n"), 0, messages.size());
}
@Given("^I have a feature file with a step \"(.*?)\" and a docstring \"(.*?)\"$")
public void i_have_a_feature_file_with_a_step_and_a_docstring(
String steptext, String docstring) throws Throwable {
String contentsFeatureFile = "Feature: test";
contentsFeatureFile += "\nScenario: test";
contentsFeatureFile += "\n" + steptext;
contentsFeatureFile += "\n\"\"\"\n" + docstring + "\n\"\"\"";
i_have_a_feature_file(contentsFeatureFile);
}
@Then("^the Adapter should report the step \"(.*?)\" with the docstring \"(.*?)\"$")
public void the_Adapter_should_report_the_step_with_the_docstring(String steptext,
String docstring) throws Throwable {
String verificationText = steptext + " \"\"\"" + docstring + "\"\"\"";
orderedVerifier.verify(mockedClient).addStepToBuffer(eq(verificationText),
any(StringArrayArray.class));
}
@When("^I run Cucumber-JVM$")
public void i_run_Cucumber_JVM() throws Throwable {
CucumberSubTestThreadWithAdapterInstance subTest = new CucumberSubTestThreadWithAdapterInstance(
mockedAdapter, this.subTestDirectory);
subTest.start();
subTest.join();
assertTrue(StringUtils.join(subTest.getThrownExceptions(), "\n"), subTest
.getThrownExceptions().size() == 0);
}
@Then("^the Adapter should report the feature \"([^\"]*)\"$")
public void the_Adapter_should_report_the_feature(String featureTextExpected) throws Throwable {
// Write code here that turns the phrase above into concrete actions
orderedVerifier.verify(mockedClient).setFeatureText(featureTextExpected);
}
@Then("^the Adapter should report following steps:$")
public void the_Adapter_should_report_following_steps(String stepListExpected) throws Throwable {
// Write code here that turns the phrase above into concrete actions
expectedSteps = stepListExpected.split("\n");
for (int i = 0; i < expectedSteps.length; i++) {
expectedSteps[i] = expectedSteps[i].trim();
orderedVerifier.verify(mockedClient).addStepToBuffer(eq(expectedSteps[i]),
any(StringArrayArray.class));
}
}
@Then("^the Adapter should report the scenario \"(.*?)\"$")
public void the_Adapter_should_report_the_scenario(String scenarioName)
throws Throwable {
/*
* atLeastOnce(): for ScenarioOutlines the scenario will transmitted twice
* but ignored the second time from the server (desired behaviour)
*/
verify(mockedClient, atLeastOnce()).startScenario(scenarioName);
scenariosToStop++;
verify(mockedClient, atLeast(scenariosToStop)).stopScenario();
}
@Then("^the Adapter should send the steptext \"([^\"]*)\" with the datatable:$")
public void the_Adapter_should_send_the_steptext_with_the_datatable(String expectedStepText,
DataTable expectedDataTable) throws Throwable {
StringArrayArray expectedDataArray = convertDataTable2StringArrayArray(expectedDataTable);
orderedVerifier.verify(mockedClient, atLeastOnce()).addStepToBuffer(eq(expectedStepText),
argThat(new IsSameStringArrayArray(expectedDataArray)));
}
private StringArrayArray convertDataTable2StringArrayArray(DataTable table) {
StringArrayArray datatable = new StringArrayArray();
for (DataTableRow row : table.getGherkinRows()) {
StringArray rowElement = new StringArray();
rowElement.getItem().addAll(row.getCells());
datatable.getItem().add(rowElement);
}
return datatable;
}
@Then("^the Adapter should send \"(.*?)\" for all steps to the server$")
public void the_Adapter_should_send_for_all_steps_to_the_server(
String expectedResult) throws Throwable {
verify(mockedClient, times(expectedSteps.length)).addResultToBufferStep(
refEq(StepResult.valueOf(expectedResult)));
}
@Then("^the Adapter should send the step \"(.*?)\" with Result \"(.*?)\"$")
public void the_Adapter_should_send_the_step_with_Result(String steptext,
String result) throws Throwable {
//Contains steptext, as CucumberJVM will also Add name of the StepdefinitionClass
// to the Steptext
orderedVerifier.verify(mockedClient, atLeastOnce()).addStepWithResult(
contains(steptext),
any(StringArrayArray.class),
refEq(StepResult.valueOf(result)));
}
}
| apache-2.0 |
ApolloDev/apollo | services-common/src/main/java/edu/pitt/apollo/interfaces/TranslatorServiceInterface.java | 288 | package edu.pitt.apollo.interfaces;
import edu.pitt.apollo.exception.TranslatorServiceException;
import java.math.BigInteger;
/**
*
* @author nem41
*/
public interface TranslatorServiceInterface {
public void translateRun(BigInteger runId) throws TranslatorServiceException;
}
| apache-2.0 |
arrayexpress/annotare2 | app/webapp/src/main/java/uk/ac/ebi/fg/annotare2/web/gwt/editor/client/view/EditorLogBarViewImpl.java | 2651 | /*
* Copyright 2009-2016 European Molecular Biology Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.fg.annotare2.web.gwt.editor.client.view;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import uk.ac.ebi.fg.annotare2.web.gwt.common.shared.ValidationResult;
import java.util.List;
/**
* @author Olga Melnichuk
*/
public class EditorLogBarViewImpl extends Composite implements EditorLogBarView {
private final VerticalPanel panel;
public EditorLogBarViewImpl() {
panel = new VerticalPanel();
panel.add(new Label("No validation results"));
panel.addStyleName("app-log");
initWidget(panel);
}
@Override
public void showValidationResult(ValidationResult result) {
panel.clear();
if (result.getFailures().isEmpty()) {
if (result.getErrors().isEmpty() && result.getWarnings().isEmpty()) {
panel.add(new Label("Validation has been successful"));
} else if(result.getErrors().isEmpty() && !result.getWarnings().isEmpty()) {
panel.add(new Label("Validation has been successful with " + result.getWarnings().size() + " warnings, please review:"));
addAll(result.getWarnings());
} else if(!result.getErrors().isEmpty() && result.getWarnings().isEmpty()) {
panel.add(new HTML("Validation failed with " + result.getErrors().size() + " errors, please fix:"));
addAll(result.getErrors());
} else {
panel.add(new HTML("Validation failed with " + result.getWarnings().size() + " warnings and " + result.getErrors().size() + " errors, please fix:"));
addAll(result.getWarnings());
addAll(result.getErrors());
}
} else {
addAll(result.getFailures());
}
}
private void addAll(List<String> list) {
for (String item : list) {
panel.add(new HTML(item));
}
}
}
| apache-2.0 |
spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/model/Customer680.java | 624 | package example.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer680 {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private long id;
private String firstName;
private String lastName;
protected Customer680() {}
public Customer680(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format("Customer680[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
}
}
| apache-2.0 |
iritgo/iritgo-aktera | aktera-ui/src/main/java/de/iritgo/aktera/ui/el/ExpressionLanguageContext.java | 6761 | /**
* This file is part of the Iritgo/Aktera Framework.
*
* Copyright (C) 2005-2011 Iritgo Technologies.
* Copyright (C) 2003-2005 BueroByte GbR.
*
* Iritgo 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 de.iritgo.aktera.ui.el;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.commons.beanutils.PropertyUtils;
import de.iritgo.aktera.authentication.UserEnvironment;
import de.iritgo.aktera.model.ModelRequest;
import de.iritgo.aktera.ui.UIController;
import de.iritgo.aktera.ui.UIRequest;
import de.iritgo.aktera.ui.ng.ModelRequestWrapper;
import de.iritgo.simplelife.math.NumberTools;
import de.iritgo.simplelife.string.StringTools;
public class ExpressionLanguageContext
{
/** The model requets */
protected ModelRequest request;
/** The user environment */
private UserEnvironment userEnvironment;
public void setUserEnvironment(UserEnvironment userEnvironment)
{
this.userEnvironment = userEnvironment;
}
/**
* Initialize a new ExpressionLanguageContext.
*
* @param request A ui request
*/
public ExpressionLanguageContext(UIRequest request)
{
this.request = new ModelRequestWrapper(request);
}
/**
* Initialize a new ExpressionLanguageContext.
*
* @param request A model request
*/
public ExpressionLanguageContext(ModelRequest request)
{
this.request = request;
}
/**
* Initialize a new ExpressionLanguageContext.
*/
public ExpressionLanguageContext()
{
}
/**
* Set the ui request.
*
* @param request The model request
*/
public void setRequest(UIRequest request)
{
this.request = new ModelRequestWrapper(request);
}
/**
* Set the model request.
*
* @param request The model request
*/
public void setRequest(ModelRequest request)
{
this.request = request;
}
/**
* Get the model request.
*
* @return The model request
*/
public ModelRequest getRequest()
{
return request;
}
/**
* Get the request parameters.
*
* @return The request parameters
*/
public Map getParams()
{
return request != null ? request.getParameters() : null;
}
/**
* Get a request parameter.
*
* @param name The request parameter name
* @return The parameter value
*/
public String getParam(String name)
{
return request != null ? StringTools.trim(request.getParameter(name)) : "";
}
/**
* Get a request parameter as an integer.
*
* @param name The request parameter name
* @return The parameter value as an integer
*/
public Integer getParamAsInt(String name)
{
return request != null ? NumberTools.toIntInstance(request.getParameter(name), - 1) : - 1;
}
/**
* Get a request parameter as a long.
*
* @param name The request parameter name
* @return The parameter value as a long
*/
public Long getParamAsLong(String name)
{
return request != null ? NumberTools.toLongInstance(request.getParameter(name), - 1) : - 1;
}
/**
* See {@link ExpressionLanguageContext#evalExpressionLanguageValue(Object, ModelRequest, String)}.
*/
public Object evalExpressionLanguageValue(String expression) throws IllegalArgumentException
{
return evalExpressionLanguageValue(this, request, expression);
}
/**
* Parse an expression language string and return the corresponding value.
* If the supplied argument is not an expression language string, the string
* itself is returned.If the expression connot be resolved succesfully, an
* InvalidArgumentException is thrown.
*
* The following expressions are supported:
*
* <ul>
* <li>#{variable} Retrieve a variable from the context map</li>
* <li>#{variable.property} Retrieve a property (through calling the getter)
* of a context variable</li>
* <li>#{variable.property(index)} Retrieve a property (through calling a
* getter which returns an array or a list) of a context variable</li>
* <li>#{variable.property(key)} Retrieve a property (through calling a
* getter which accepts a string parameter) of a context variable</li>
* <li>#{variable.property1.property2...} Retrieve a property (through
* calling a chain of getters as specified above) of a context variable</li>
* </ul>
*
* @param expression
* The expression language string
* @param context
* POJO containing the accessible variables
* @param properties
* Backward compatibility; Additional variable properties. TODO
* Should be replaced (see code)
* @return The expression language value
* @throws InvalidArgumentException
* in case of an error
*/
public static Object evalExpressionLanguageValue(Object context, ModelRequest request, String expression)
throws IllegalArgumentException
{
if (expression.startsWith("#{") && expression.endsWith("}"))
{
expression = expression.substring(2, expression.length() - 1);
try
{
return PropertyUtils.getNestedProperty(context, expression);
}
catch (IllegalAccessException x)
{
}
catch (InvocationTargetException x)
{
}
catch (NoSuchMethodException x)
{
}
throw new IllegalArgumentException("Error in expression '" + expression + "'. Unable"
+ " to retrieve variable or it's property");
}
// Backward compatibility: #paramName
// TODO Replace this with ${params(name)}
if (expression.startsWith("#"))
{
if (request == null)
{
throw new IllegalArgumentException("Error in expression '" + expression + "'. No"
+ " model request found in context");
}
return request.getParameterAsString(expression.substring(1));
}
return expression;
}
/**
* See {@link ExpressionLanguageContext#evalExpressionLanguageValue(Object, ModelRequest, String)}.
*/
public static Properties evalExpressionLanguageValue(Object context, ModelRequest request, Properties expressions)
{
Properties newProperties = new Properties();
for (Entry<Object, Object> expression : expressions.entrySet())
{
Object val = evalExpressionLanguageValue(context, request, expression.getValue().toString());
if (val != null)
{
newProperties.put(expression.getKey(), val);
}
}
return newProperties;
}
}
| apache-2.0 |
popwich/test_selendroid | selendroid-server/src/main/java/io/selendroid/server/model/AndroidNativeElement.java | 16268 | /*
* Copyright 2012-2013 eBay Software Foundation and selendroid committers.
*
* 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.selendroid.server.model;
import io.selendroid.ServerInstrumentation;
import io.selendroid.android.AndroidKeys;
import io.selendroid.android.AndroidWait;
import io.selendroid.android.ViewHierarchyAnalyzer;
import io.selendroid.android.internal.Dimension;
import io.selendroid.android.internal.Point;
import io.selendroid.exceptions.ElementNotVisibleException;
import io.selendroid.exceptions.NoSuchElementAttributeException;
import io.selendroid.exceptions.NoSuchElementException;
import io.selendroid.exceptions.SelendroidException;
import io.selendroid.exceptions.TimeoutException;
import io.selendroid.server.model.interactions.AndroidCoordinates;
import io.selendroid.server.model.interactions.Coordinates;
import io.selendroid.server.model.internal.AbstractNativeElementContext;
import io.selendroid.util.Function;
import io.selendroid.util.Preconditions;
import io.selendroid.util.SelendroidLogger;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Rect;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidNativeElement implements AndroidElement {
// TODO revisit
protected static final long DURATION_OF_LONG_PRESS = 750L;// (long)
// (ViewConfiguration.getLongPressTimeout()
// * 1.5f);
private View view;
private Collection<AndroidElement> children = new LinkedHashSet<AndroidElement>();
private AndroidElement parent;
private ServerInstrumentation instrumentation;
private SearchContext nativeElementSearchScope = null;
private Coordinates coordinates = null;
final Object syncObject = new Object();
private Boolean done = false;
private KnownElements ke;
static final long UI_TIMEOUT = 3000L;
public AndroidNativeElement(View view, ServerInstrumentation instrumentation, KnownElements ke) {
this.view = view;
this.instrumentation = instrumentation;
this.nativeElementSearchScope = new NativeElementSearchScope(instrumentation, ke);
this.ke = ke;
}
@Override
public AndroidElement getParent() {
return parent;
}
public boolean isDisplayed() {
return view.hasWindowFocus() && view.isEnabled() && view.isShown() && (view.getWidth() > 0)
&& (view.getHeight() > 0);
}
private void waitUntilIsDisplayed() {
AndroidWait wait = instrumentation.getAndroidWait();
try {
wait.until(new Function<Void, Boolean>() {
@Override
public Boolean apply(Void input) {
return isDisplayed();
}
});
} catch (TimeoutException exception) {
throw new ElementNotVisibleException(
"You may only do passive read with element not displayed");
}
}
protected void scrollIntoScreenIfNeeded() {
Point leftTopLocation = getLocation();
final int left = leftTopLocation.x;
final int top = leftTopLocation.y;
instrumentation.runOnUiThread(new Runnable() {
@Override
public void run() {
synchronized (syncObject) {
Rect r = new Rect(left, top, view.getWidth(), view.getHeight());
view.requestRectangleOnScreen(r);
done = true;
syncObject.notify();
}
}
});
long end = System.currentTimeMillis() + instrumentation.getAndroidWait().getTimeoutInMillis();
synchronized (syncObject) {
while (!done && System.currentTimeMillis() < end) {
try {
syncObject.wait(AndroidWait.DEFAULT_SLEEP_INTERVAL);
} catch (InterruptedException e) {
e.printStackTrace();
throw new SelendroidException(e);
}
}
}
}
@Override
public void enterText(CharSequence... keysToSend) {
final View viewview = view;
instrumentation.runOnUiThread(new Runnable() {
@Override
public void run() {
viewview.requestFocus();
}
});
click();
StringBuilder sb = new StringBuilder();
for (CharSequence keys : keysToSend) {
sb.append(keys);
}
send(sb.toString());
}
@Override
public String getText() {
if (view instanceof TextView) {
return ((TextView) view).getText().toString();
}
System.err.println("not supported elment for getting the text: "
+ view.getClass().getSimpleName());
return null;
}
@Override
public void click() {
waitUntilIsDisplayed();
scrollIntoScreenIfNeeded();
try {
// is needed for recalculation of location
Thread.sleep(300);
} catch (InterruptedException e) {}
int[] xy = new int[2];
view.getLocationOnScreen(xy);
final int viewWidth = view.getWidth();
final int viewHeight = view.getHeight();
final float x = xy[0] + (viewWidth / 2.0f);
float y = xy[1] + (viewHeight / 2.0f);
clickOnScreen(x, y);
}
private void clickOnScreen(float x, float y) {
final ServerInstrumentation inst = ServerInstrumentation.getInstance();
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis();
final MotionEvent event =
MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y, 0);
final MotionEvent event2 =
MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, x, y, 0);
try {
inst.sendPointerSync(event);
inst.sendPointerSync(event2);
try {
Thread.sleep(300);
} catch (InterruptedException ignored) {}
} catch (SecurityException e) {
SelendroidLogger.log("error while clicking element", e);
}
}
public Integer getAndroidId() {
int viewId = view.getId();
return (viewId == View.NO_ID) ? null : viewId;
}
@Override
public AndroidElement findElement(By by) throws NoSuchElementException {
return by.findElement(nativeElementSearchScope);
}
@Override
public List<AndroidElement> findElements(By by) throws NoSuchElementException {
return by.findElements(nativeElementSearchScope);
}
@Override
public Collection<AndroidElement> getChildren() {
return children;
}
public void setParent(AndroidElement parent) {
this.parent = parent;
}
public void addChild(AndroidElement child) {
this.children.add(child);
}
public String toString() {
StringBuilder string = new StringBuilder();
string.append("id: " + view.getId());
string.append("view class: " + view.getClass());
string.append("view content desc: " + view.getContentDescription());
return string.toString();
}
private static int indexOfSpecialKey(CharSequence string, int startIndex) {
for (int i = startIndex; i < string.length(); i++) {
if (AndroidKeys.hasAndroidKeyEvent(string.charAt(i))) {
return i;
}
}
return string.length();
}
protected void send(CharSequence string) {
int currentIndex = 0;
instrumentation.waitForIdleSync();
while (currentIndex < string.length()) {
char currentCharacter = string.charAt(currentIndex);
if (AndroidKeys.hasAndroidKeyEvent(currentCharacter)) {
// The next character is special and must be sent individually
instrumentation.sendKeyDownUpSync(AndroidKeys.keyCodeFor(currentCharacter));
currentIndex++;
} else {
// There is at least one "normal" character, that is a character
// represented by a plain Unicode character that can be sent
// with
// sendStringSync. So send as many such consecutive normal
// characters
// as possible in a single String.
int nextSpecialKey = indexOfSpecialKey(string, currentIndex);
instrumentation.sendStringSync(string.subSequence(currentIndex, nextSpecialKey).toString());
currentIndex = nextSpecialKey;
}
}
}
public JSONObject toJson() throws JSONException {
JSONObject object = new JSONObject();
JSONObject l10n = new JSONObject();
String l10nKey = null;
// try {
// l10nKey =
// instrumentation.getCurrentActivity().getResources().getText(view.getId()).toString();
// } catch (Resources.NotFoundException e) {
// // ignoring, can happen
// }
if (l10nKey != null) {
l10n.put("matches", 1);
l10n.put("key", l10nKey);
} else {
l10n.put("matches", 0);
}
object.put("l10n", l10n);
String label = String.valueOf(view.getContentDescription());
object.put("name", label == null ? "" : label);
String id = getNativeId();
object.put("id", id.startsWith("id/") ? id.replace("id/", "") : id);
JSONObject rect = new JSONObject();
object.put("rect", rect);
JSONObject origin = new JSONObject();
Point location = getLocation();
origin.put("x", location.x);
origin.put("y", location.y);
rect.put("origin", origin);
JSONObject size = new JSONObject();
Dimension s = getSize();
size.put("height", s.getHeight());
size.put("width", s.getWidth());
rect.put("size", size);
object.put("ref", ke.getIdOfElement(this));
object.put("type", view.getClass().getSimpleName());
String value = "";
if (view instanceof TextView) {
value = String.valueOf(((TextView) view).getText());
}
object.put("value", value);
object.put("shown", view.isShown());
if (view instanceof WebView) {
final WebView webview = (WebView) view;
final MyWebChromeClient client = new MyWebChromeClient();
String html = null;
instrumentation.runOnUiThread(new Runnable() {
public void run() {
synchronized (syncObject) {
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(client);
String script = "document.body.parentNode.innerHTML";
webview.loadUrl("javascript:alert('selendroidSource:'+" + script + ")");
}
}
});
long end = System.currentTimeMillis() + 10000;
waitForDone(end, UI_TIMEOUT, "Error while grabbing web view source code.");
object.put("source", "<html>"+ client.result+"</html>");
}
return object;
}
public class MyWebChromeClient extends WebChromeClient {
public Object result = null;
/**
* Unconventional way of adding a Javascript interface but the main reason why I took this way
* is that it is working stable compared to the webview.addJavascriptInterface way.
*/
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult jsResult) {
System.out.println("alert message: " + message);
if (message != null && message.startsWith("selendroidSource:")) {
jsResult.confirm();
synchronized (syncObject) {
result = message.replaceFirst("selendroidSource:", "");
done = true;
syncObject.notify();
}
return true;
} else {
return super.onJsAlert(view, url, message, jsResult);
}
}
}
private void waitForDone(long end, long timeout, String error) {
synchronized (syncObject) {
while (!done && System.currentTimeMillis() < end) {
try {
syncObject.wait(timeout);
} catch (InterruptedException e) {
throw new SelendroidException(error, e);
}
}
}
}
private String getNativeId() {
return ViewHierarchyAnalyzer.getNativeId(view);
}
public View getView() {
return view;
}
@Override
public void clear() {
final View viewview = view;
instrumentation.runOnUiThread(new Runnable() {
@Override
public void run() {
viewview.requestFocus();
if (viewview instanceof EditText) {
((EditText) viewview).setText("");
}
}
});
}
@Override
public void submit() {
throw new UnsupportedOperationException("Submit is not supported for native elements.");
}
@Override
public boolean isSelected() {
if (view instanceof CompoundButton) {
return ((CompoundButton) view).isChecked();
}
throw new UnsupportedOperationException(
"Is selected is only available for view class CheckBox and RadioButton.");
}
@Override
public Point getLocation() {
int[] xy = new int[2];
view.getLocationOnScreen(xy);
return new Point(xy[0], xy[1]);
}
private class NativeElementSearchScope extends AbstractNativeElementContext {
public NativeElementSearchScope(ServerInstrumentation instrumentation,
KnownElements knownElements) {
super(instrumentation, knownElements);
}
@Override
protected View getRootView() {
return view;
}
protected List<View> getTopLevelViews() {
return Arrays.asList(view);
}
}
@Override
public Coordinates getCoordinates() {
if (coordinates == null) {
coordinates = new AndroidCoordinates(String.valueOf(view.getId()), getCenterCoordinates());
}
return coordinates;
}
private Point getCenterCoordinates() {
int height = view.getHeight();
int width = view.getWidth();
Point location = getLocation();
int x = location.x + (height / 2);
int y = location.y + (width / 2);
return new Point(x, y);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((view == null) ? 0 : view.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
AndroidNativeElement other = (AndroidNativeElement) obj;
if (view == null) {
if (other.view != null) return false;
} else if (!view.equals(other.view)) return false;
return true;
}
@Override
public Dimension getSize() {
return new Dimension(view.getWidth(), view.getHeight());
}
@Override
public String getAttribute(String attribute) {
if (attribute.equalsIgnoreCase("nativeid")) {
return getNativeId();
}
String name = capitalizeFirstLetter(attribute);
Method method = getDeclaredMethod("get" + name);
if (method == null) {
method = getDeclaredMethod("is" + name);
if (method == null) {
throw new NoSuchElementAttributeException("The attribute with name '" + name
+ "' was not found.");
}
}
try {
Object result = method.invoke(view);
return String.valueOf(result);
} catch (IllegalArgumentException e) {
throw new SelendroidException(e);
} catch (IllegalAccessException e) {
throw new SelendroidException(e);
} catch (InvocationTargetException e) {
throw new SelendroidException(e);
}
}
private String capitalizeFirstLetter(String name) {
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
private Method getDeclaredMethod(String name) {
Preconditions.checkNotNull(name);
Method method = null;
try {
method = view.getClass().getMethod(name);
} catch (NoSuchMethodException e) {
// can happen
}
return method;
}
@Override
public boolean isEnabled() {
return view.isEnabled();
}
@Override
public String getTagName() {
return view.getClass().getSimpleName();
}
}
| apache-2.0 |
joarder/oltpdbsim | oltpdbsim/src/main/java/utils/Utility.java | 11121 | /*******************************************************************************
* Copyright [2014] [Joarder Kamal]
*
* 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 main.java.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;
import java.util.TreeMap;
import main.java.entry.Global;
import org.apache.commons.codec.digest.DigestUtils;
public class Utility {
private static final Random rand = new Random();
private static final ThreadLocal<Random> rng = new ThreadLocal<Random>();
public static Random random() {
Random ret = rng.get();
if(ret == null) {
ret = new Random(rand.nextLong());
rng.set(ret);
}
return ret;
}
// Returns the Base
public static int getBase(int x) {
int value = Math.abs(x);
if (value == 0)
return 1;
else
return (int) (1 + Math.floor((Math.log(value)/Math.log(10.0d))));
}
// Randomly shuffles a given Array
public static void shuffleArray(int[] array) {
int index, temp;
for (int i = array.length - 1; i > 1; i--)
{
index = Global.rand.nextInt(i-1) + 1;
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
// Collected from http://rosettacode.org/wiki/Remove_lines_from_a_file#Java
public static void deleteLinesFromFile(String filename, int startline, int numlines) {
try {
BufferedReader br=new BufferedReader(new FileReader(filename));
//String buffer to store contents of the file
StringBuffer sb=new StringBuffer("");
//Keep track of the line number
int linenumber=1;
String line;
while((line=br.readLine())!=null) {
//Store each valid line in the string buffer
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
//Write entire string buffer into the file
fw.write(sb.toString());
fw.close();
} catch (Exception e) {
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
// Returns a normalised value between a and b for the given x
public static double normalise(double min, double max, double x, double a, double b) {
return (a + (((x - min) * (b - a))/(max - min)));
}
// Used for creating 2D Matrix of size of total Partition numbers
// Used in MethodX
public static Matrix createMatrix(int M, int N) {
// Create a 2D Matrix
MatrixElement[][] mapping = new MatrixElement[M][N];
// Initialization
int id = 0;
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
if(i == j) {
mapping[i][j] = new MatrixElement(++id, i, j, -1.0d);
} else if(i == 0) {
mapping[i][j] = new MatrixElement(++id, i, j, j);
} else if(j == 0) {
mapping[i][j] = new MatrixElement(++id, i, j, i);
} else {
mapping[i][j] = new MatrixElement(++id, i, j, 0.0d);
mapping[j][i] = new MatrixElement(++id, j, i, -1.0d);
}
}
}
// Create and return the Matrix
return (new Matrix(mapping));
}
@SuppressWarnings("unused")
private static double exp(double mean) {
return -mean * Math.log(Global.rand.nextDouble());
}
public static double round(double value, int places) {
if(places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value *= factor;
long temp = Math.round(value);
return (double) temp/factor;
}
// Returns a simple hash key
public static int simpleHash(int x, int divisor) {
//Global.LOGGER.info("@debug >> x = "+x+" divisor = "+divisor);
return ((x % divisor) + 1);
}
public static int convertByteToInt(byte[] b) {
int value= 0;
for(int i = 0; i < b.length; i++)
value = (value << 8) | b[i];
return value;
}
public static long convertByteToUnsignedLong(byte[] b) {
return (ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).getLong() & 0xFFFFFFFFL);
}
//
public static String getSaltedKey(String key) {
int prefix = (++Global.global_index % Global.partitions);
Global.global_index_map.put(Integer.parseInt(key), prefix);
return (Integer.toString(prefix) + key);
}
// Returns a Java hash value
public static long javaHash(String key) {
return key.hashCode();
}
// Returns a MD5 hash value
public static long md5Hash(String key) {
byte[] value = DigestUtils.md5(key.getBytes());
return Utility.convertByteToUnsignedLong(value);
}
// Knuth's Multiplication Method
public static int intHash(int key) {
// int w = 4; // Number of bits
// int p = Global.partitions; // number of slots i.e., 16 partitions
// int m = 2^p; //
// int s = 13; // Must have 0 < s < 2^w. Let, s = 9973 (Prime number)
// int A = s/2^w; // Or, 0.5*(sqrt(5) - 1)
////
//// // h(k) = ⌊m · (k·A mod 1)⌋
// return (int) Math.floor(m*((key*A)%1));
//--------------------------------------------
// int s = (int) Math.floor((double)(key * 2^w));
// int x = k*s;
// return (x >> (w-p));
//--------------------------------------------
// int p = 20; // m = 2^20
// int w = 32;
// int A = (int) 2654435769L;
//
// return (key * A) >>> (w - p);
//--------------------------------------------
double A = 0.6180339887;
int m = 65536; //2^(Global.partitions);
return (int) Math.floor(m * ((key * A) % 1));
}
public static String getRandomAlphanumericString() {
return RandomStringGenerator.generateRandomString(50, RandomStringGenerator.Mode.ALPHANUMERIC);
}
// Returns a SHA1 hash value
public static long sha512Hash(String key) {
String value = DigestUtils.sha512Hex(key.getBytes());
BigInteger b = new BigInteger(value, 16);
return (b.longValue());
}
/* // Returns a SHA1 hash value
public static long sha1Hash(String key, boolean lookup, boolean flag) {
if(flag) {
if(lookup) {
int prefix = Global.global_index_map.get(Integer.parseInt(key));
key = (Integer.toString(prefix) + key);
} else {
key = getSaltedKey(key);
}
BigInteger bigInt = new BigInteger(key.getBytes());
key = bigInt.toString();
key = getAlphaNumericString(key);
//System.out.println(key);
}
byte[] value = DigestUtils.sha1(key.getBytes());
return Utility.convertByteToUnsignedLong(value);
}
*/
public static String getAlphaNumericString(String str) {
String out = null;
try {
byte[] b = str.getBytes("ASCII");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = md.digest(b);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hashBytes.length; i++)
hexString.append(Integer.toHexString(0xFF & hashBytes[i]));
out = hexString.toString();
} catch (Exception e) {
e.printStackTrace();
}
return out;
}
// Add padding value in the least significant bits of id
public static int rightPadding(int id, int value) {
return ((int) Math.pow(10, Math.floor(Math.log10(value)) + 1) * id + value);
}
public static String asUnsignedDecimalString(long l) {
/** the constant 2^64 */
BigInteger TWO_64 = BigInteger.ONE.shiftLeft(64);
BigInteger b = BigInteger.valueOf(l);
if(b.signum() < 0) {
b = b.add(TWO_64);
}
return b.toString();
}
public static boolean inRange(long min, long max, long x) {
return (x >= min && x <= max);
}
public static PrintWriter getPrintWriter(String dir, String file_name) {
File file = new File(dir+file_name+".txt");
PrintWriter prWriter = null;
try {
file.getParentFile().mkdirs();
file.createNewFile();
try {
prWriter = new PrintWriter(new BufferedWriter(new FileWriter(file)));
} catch(IOException e) {
Global.LOGGER.error("Failed to create a print writer !!", e);
}
} catch (IOException e) {
Global.LOGGER.error("Failed to create a file !!", e);
}
return prWriter;
}
//
public static PrintWriter getPrintWriter(String dir, File file) {
PrintWriter prWriter = null;
try {
file.getParentFile().mkdirs();
/*if(file.exists())
file.delete();*/
file.createNewFile();
try {
prWriter = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
} catch(IOException e) {
Global.LOGGER.error("Failed to create a print writer !!", e);
}
} catch (IOException e) {
Global.LOGGER.error("Failed to create a file !!", e);
}
return prWriter;
}
public static boolean isWindows() {
return (Global.OS.indexOf("win") >= 0);
}
public static boolean isUnix() {
return (Global.OS.indexOf("nix") >= 0 || Global.OS.indexOf("nux") >= 0 || Global.OS.indexOf("aix") > 0 );
}
public static boolean isOSX() {
return (Global.OS.indexOf("mac") >= 0);
}
/**
* Added from SO: http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java
*
*/
public static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
Comparator<K> valueComparator = new Comparator<K>() {
public int compare(K k1, K k2) {
int compare = map.get(k2).compareTo(map.get(k1));
if (compare == 0)
return 1;
else
return compare;
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
public static <K,V extends Comparable<? super V>> List<Entry<K, V>> sortedByValuesAsc(Map<K,V> map) {
List<Entry<K,V>> sortedEntries = new ArrayList<Entry<K,V>>(map.entrySet());
Collections.sort(sortedEntries, new Comparator<Entry<K,V>>()
{
@Override
public int compare(Entry<K,V> e1, Entry<K,V> e2) {
return e1.getValue().compareTo(e2.getValue()); // Ascending Order
}
}
);
return sortedEntries;
}
} | apache-2.0 |
Netflix/staash | staash-web/src/test/java/com/netflix/staash/test/core/StaashDeamon.java | 919 |
package com.netflix.staash.test.core;
import org.apache.cassandra.service.CassandraDaemon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class StaashDeamon extends CassandraDaemon {
private static final Logger logger = LoggerFactory.getLogger(StaashDeamon.class);
private static final StaashDeamon instance = new StaashDeamon();
public static void main(String[] args) {
System.setProperty("cassandra-foreground", "true");
System.setProperty("log4j.defaultInitOverride", "true");
System.setProperty("log4j.configuration", "log4j.properties");
instance.activate();
}
@Override
protected void setup() {
super.setup();
}
@Override
public void init(String[] arguments) throws IOException {
super.init(arguments);
}
@Override
public void start() {
super.start();
}
@Override
public void stop() {
super.stop();
}
} | apache-2.0 |
spring-cloud/spring-cloud-sleuth | tests/brave/spring-cloud-sleuth-instrumentation-messaging-tests/src/test/java/org/springframework/cloud/sleuth/instrument/messaging/issues/issue_943/HelloWorldImpl.java | 1688 | /*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.sleuth.instrument.messaging.issues.issue_943;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorldImpl {
private static final Logger LOG = LoggerFactory.getLogger(HelloWorldImpl.class);
public String invokeProcessor(String message) throws InterruptedException {
LOG.info(" input message " + message);
Thread.currentThread().sleep(500);
LOG.info(" After the Sleep " + message);
String responseMessage = message + " Persist into DB ";
return responseMessage;
}
public List<String> aggregate(List<String> requestMessage) {
LOG.info(Thread.currentThread().getName());
LOG.info(" requestMessage aggregate " + requestMessage);
return requestMessage;
}
public List<String> splitMessage(String[] splitRequest) {
LOG.info(" Inside splitMessage " + splitRequest);
List<String> splitGBSResponse = new ArrayList<String>();
splitGBSResponse = Arrays.asList(splitRequest);
return splitGBSResponse;
}
}
| apache-2.0 |
smantinc/wikiup | plugins/wmdk/src/org/wikiup/plugins/wmdk/action/ContextServletAction.java | 5203 | package org.wikiup.plugins.wmdk.action;
import java.util.Iterator;
import org.wikiup.core.Wikiup;
import org.wikiup.core.impl.Null;
import org.wikiup.core.inf.Attribute;
import org.wikiup.core.inf.BeanContainer;
import org.wikiup.core.inf.Document;
import org.wikiup.core.util.Documents;
import org.wikiup.core.util.Interfaces;
import org.wikiup.core.util.StringUtil;
import org.wikiup.core.util.ValueUtil;
import org.wikiup.servlet.ServletProcessorContext;
import org.wikiup.servlet.exception.ServiceNotImplementException;
import org.wikiup.servlet.util.ProcessorContexts;
public class ContextServletAction {
public void get(ServletProcessorContext context) {
Document resp = context.getResponseXML();
String name = context.getParameter("name");
Documents.setAttributeValue(resp, "value", context.get(name));
}
public void contexts(ServletProcessorContext context) {
String node = context.getParameter("node");
int pos = node.indexOf('@');
String uri = pos == -1 ? node : node.substring(0, pos);
String objectName = pos == -1 ? null : node.substring(pos + 1);
Document resp = context.getResponseXML();
ServletProcessorContext ctx = getRequestedContext(context, uri);
if(ctx != null)
if(objectName == null) {
Object globalContext = Wikiup.getInstance().get("wk.servlet.context");
Document rScope = ctx.getRequestContextConf();
Document sScope = ctx.getServletContextConf();
Iterable<Object> iterable = Interfaces.getModel(globalContext, Iterable.class);
if(sScope != null)
mergeContext(uri, sScope, resp);
if(rScope != null)
mergeContext(uri, rScope, resp);
if(iterable != null)
for(Object obj : iterable) {
String name = ValueUtil.toString(obj);
appendContextNode(resp, "context", uri + '@' + name, name, false);
}
} else {
ctx.doInit();
Iterator<Object> iterator = getIterator(ctx, objectName);
while(iterator != null && iterator.hasNext()) {
String name = ValueUtil.toString(iterator.next());
String p = StringUtil.connect(objectName, name, ':');
appendContextNode(resp, "item", uri + '@' + p, name, getIterator(ctx, p) == null);
}
}
}
private ServletProcessorContext getRequestedContext(ServletProcessorContext context, String uri) {
ServletProcessorContext ctx = null;
try {
ctx = new ServletProcessorContext(context, uri);
} catch(ServiceNotImplementException e) {
}
return ctx;
}
private void appendContextNode(Document resp, String nodeName, String id, String text, boolean isLeaf) {
Document doc = resp.addChild(nodeName);
Documents.setAttributeValue(doc, "text", text);
Documents.setAttributeValue(doc, "id", id);
Documents.setAttributeValue(doc, "leaf", isLeaf);
}
public void actions(ServletProcessorContext context) {
String uri = context.getParameter("uri", "/");
ServletProcessorContext ctx = getRequestedContext(context, uri);
Document resp = context.getResponseXML();
if(ctx != null) {
Document rScope = ctx.getRequestContextConf().getChild("context-action");
Document sScope = ctx.getServletContextConf().getChild("context-action");
if(sScope != null)
mergeContext(uri, sScope, resp);
if(rScope != null) {
if(!rScope.getChildren().iterator().hasNext())
mergeAction(rScope, resp.addChild("action"));
else
mergeAction(rScope, resp);
for(Document doc : resp.getChildren())
Documents.setChildValue(doc, "scope", "Request");
}
}
}
private void mergeAction(Document action, Document resp) {
for(Attribute attr : action.getAttributes())
Documents.setChildValue(resp, attr.getName(), attr.toString());
}
private Iterator<Object> getIterator(ServletProcessorContext ctx, String path) {
try {
BeanContainer mc = ProcessorContexts.getBeanContainer(ctx, path, Null.getInstance());
return mc != null ? mc.query(Iterator.class) : null;
} catch(Exception e) {
return null;
}
}
private void mergeContext(String uri, Document sScope, Document resp) {
for(Document item : sScope.getChildren("context")) {
Document node = resp.addChild("context");
String name = Documents.getAttributeValue(item, "name");
Documents.setAttributeValue(node, "text", name);
Documents.setAttributeValue(node, "id", uri + '@' + name);
Documents.setAttributeValue(node, "leaf", false);
}
}
}
| apache-2.0 |
JoelMarcey/buck | test/com/facebook/buck/core/model/actiongraph/computation/ActionGraphProviderTest.java | 18423 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.core.model.actiongraph.computation;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.actiongraph.ActionGraphAndBuilder;
import com.facebook.buck.core.model.targetgraph.FakeTargetNodeBuilder;
import com.facebook.buck.core.model.targetgraph.TargetGraph;
import com.facebook.buck.core.model.targetgraph.TargetGraphFactory;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.core.model.targetgraph.TestTargetGraphCreationResultFactory;
import com.facebook.buck.core.rulekey.RuleKey;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.transformer.impl.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.event.ActionGraphEvent;
import com.facebook.buck.event.BuckEvent;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventBusForTests;
import com.facebook.buck.event.ExperimentEvent;
import com.facebook.buck.jvm.java.JavaLibraryBuilder;
import com.facebook.buck.rules.keys.ContentAgnosticRuleKeyFactory;
import com.facebook.buck.rules.keys.RuleKeyFieldLoader;
import com.facebook.buck.rules.keys.config.TestRuleKeyConfigurationFactory;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.util.Scope;
import com.facebook.buck.util.concurrent.ExecutorPool;
import com.facebook.buck.util.concurrent.MostExecutors;
import com.facebook.buck.util.stream.RichStream;
import com.facebook.buck.util.timing.IncrementingFakeClock;
import com.facebook.buck.util.types.Pair;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.eventbus.Subscribe;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ActionGraphProviderTest {
private TargetNode<?> nodeA;
private TargetNode<?> nodeB;
private TargetGraph targetGraph1;
private TargetGraph targetGraph2;
private BuckEventBus eventBus;
private final BlockingQueue<BuckEvent> trackedEvents = new LinkedBlockingQueue<>();
private final int keySeed = 0;
@Rule public ExpectedException expectedException = ExpectedException.none();
@Rule public TemporaryPaths tmpFilePath = new TemporaryPaths();
@Before
public void setUp() {
// Creates the following target graph:
// A
// /
// B
nodeB = createTargetNode("B");
nodeA = createTargetNode("A", nodeB);
targetGraph1 = TargetGraphFactory.newInstance(nodeA, nodeB);
targetGraph2 = TargetGraphFactory.newInstance(nodeB);
eventBus =
BuckEventBusForTests.newInstance(new IncrementingFakeClock(TimeUnit.SECONDS.toNanos(1)));
trackedEvents.clear();
eventBus.register(
new Object() {
@Subscribe
public void actionGraphCacheEvent(ActionGraphEvent.Cache event) {
trackedEvents.add(event);
}
@Subscribe
public void actionGraphCacheEvent(ExperimentEvent event) {
trackedEvents.add(event);
}
});
}
@Test
public void hitOnCache() {
ActionGraphProvider cache =
new ActionGraphProviderBuilder()
.withEventBus(eventBus)
.withRuleKeyConfiguration(TestRuleKeyConfigurationFactory.createWithSeed(keySeed))
.withCheckActionGraphs()
.build();
ActionGraphAndBuilder resultRun1 =
cache.getActionGraph(TestTargetGraphCreationResultFactory.create(targetGraph1));
// The 1st time you query the ActionGraph it's a cache miss.
assertEquals(countEventsOf(ActionGraphEvent.Cache.Hit.class), 0);
assertEquals(countEventsOf(ActionGraphEvent.Cache.Miss.class), 1);
ActionGraphAndBuilder resultRun2 =
cache.getActionGraph(TestTargetGraphCreationResultFactory.create(targetGraph1));
// The 2nd time it should be a cache hit and the ActionGraphs should be exactly the same.
assertEquals(countEventsOf(ActionGraphEvent.Cache.Hit.class), 1);
assertEquals(countEventsOf(ActionGraphEvent.Cache.Miss.class), 1);
// Check all the RuleKeys are the same between the 2 ActionGraphs.
Map<BuildRule, RuleKey> resultRun1RuleKeys =
getRuleKeysFromBuildRules(
resultRun1.getActionGraph().getNodes(), resultRun1.getActionGraphBuilder());
Map<BuildRule, RuleKey> resultRun2RuleKeys =
getRuleKeysFromBuildRules(
resultRun2.getActionGraph().getNodes(), resultRun2.getActionGraphBuilder());
assertThat(resultRun1RuleKeys, equalTo(resultRun2RuleKeys));
}
@Test
public void hitOnMultiEntryCache() {
ActionGraphProvider cache =
new ActionGraphProviderBuilder()
.withMaxEntries(2)
.withEventBus(eventBus)
.withCheckActionGraphs()
.build();
// List of (graph to run, (expected hit count, expected miss count))
ArrayList<Pair<TargetGraph, Pair<Integer, Integer>>> runList = new ArrayList<>();
// First run for graph 1 should be a miss.
runList.add(new Pair<>(targetGraph1, new Pair<>(0, 1)));
// First run for graph 2 should be a miss.
runList.add(new Pair<>(targetGraph2, new Pair<>(0, 2)));
// Second run for graph 2 should be a hit.
runList.add(new Pair<>(targetGraph2, new Pair<>(1, 2)));
// Second run for graph 1 should be a hit.
runList.add(new Pair<>(targetGraph1, new Pair<>(2, 2)));
// Third run for graph 2 should be a hit again.
runList.add(new Pair<>(targetGraph2, new Pair<>(3, 2)));
runAndCheckExpectedHitMissCount(cache, runList);
}
@Test
public void testLruEvictionOrder() {
ActionGraphProvider cache =
new ActionGraphProviderBuilder()
.withMaxEntries(2)
.withEventBus(eventBus)
.withCheckActionGraphs()
.build();
// List of (graph to run, (expected hit count, expected miss count))
ArrayList<Pair<TargetGraph, Pair<Integer, Integer>>> runList = new ArrayList<>();
// First run for graph 1 should be a miss.
runList.add(new Pair<>(targetGraph1, new Pair<>(0, 1)));
// First run for graph 2 should be a miss.
runList.add(new Pair<>(targetGraph2, new Pair<>(0, 2)));
// Run graph 1 again to make it the MRU.
runList.add(new Pair<>(targetGraph1, new Pair<>(1, 2)));
// Run empty graph to evict graph 2.
runList.add(new Pair<>(TargetGraph.EMPTY, new Pair<>(1, 3)));
// Another run with graph 2 should be a miss (it should have just been evicted)
runList.add(new Pair<>(targetGraph2, new Pair<>(1, 4)));
// Now cache order should be (by LRU): EMPTY, targetGraph2
runList.add(new Pair<>(targetGraph1, new Pair<>(1, 5)));
runAndCheckExpectedHitMissCount(cache, runList);
}
private void runAndCheckExpectedHitMissCount(
ActionGraphProvider cache, List<Pair<TargetGraph, Pair<Integer, Integer>>> runList) {
for (Pair<TargetGraph, Pair<Integer, Integer>> run : runList) {
cache.getActionGraph(TestTargetGraphCreationResultFactory.create(run.getFirst()));
assertEquals(
countEventsOf(ActionGraphEvent.Cache.Hit.class), (int) run.getSecond().getFirst());
assertEquals(
countEventsOf(ActionGraphEvent.Cache.Miss.class), (int) run.getSecond().getSecond());
}
}
@Test
public void missOnCache() {
ActionGraphProvider cache =
new ActionGraphProviderBuilder()
.withEventBus(eventBus)
.withRuleKeyConfiguration(TestRuleKeyConfigurationFactory.createWithSeed(keySeed))
.withCheckActionGraphs()
.build();
ActionGraphAndBuilder resultRun1 =
cache.getActionGraph(TestTargetGraphCreationResultFactory.create(targetGraph1));
// Each time you call it for a different TargetGraph so all calls should be misses.
assertEquals(0, countEventsOf(ActionGraphEvent.Cache.Hit.class));
assertEquals(1, countEventsOf(ActionGraphEvent.Cache.Miss.class));
trackedEvents.clear();
ActionGraphAndBuilder resultRun2 =
cache.getActionGraph(
TestTargetGraphCreationResultFactory.create(
targetGraph1.getSubgraph(ImmutableSet.of(nodeB))));
assertEquals(0, countEventsOf(ActionGraphEvent.Cache.Hit.class));
assertEquals(1, countEventsOf(ActionGraphEvent.Cache.Miss.class));
assertEquals(1, countEventsOf(ActionGraphEvent.Cache.MissWithTargetGraphDifference.class));
trackedEvents.clear();
ActionGraphAndBuilder resultRun3 =
cache.getActionGraph(TestTargetGraphCreationResultFactory.create(targetGraph1));
assertEquals(0, countEventsOf(ActionGraphEvent.Cache.Hit.class));
assertEquals(1, countEventsOf(ActionGraphEvent.Cache.Miss.class));
// Run1 and Run2 should not match, but Run1 and Run3 should
Map<BuildRule, RuleKey> resultRun1RuleKeys =
getRuleKeysFromBuildRules(
resultRun1.getActionGraph().getNodes(), resultRun1.getActionGraphBuilder());
Map<BuildRule, RuleKey> resultRun2RuleKeys =
getRuleKeysFromBuildRules(
resultRun2.getActionGraph().getNodes(), resultRun2.getActionGraphBuilder());
Map<BuildRule, RuleKey> resultRun3RuleKeys =
getRuleKeysFromBuildRules(
resultRun3.getActionGraph().getNodes(), resultRun3.getActionGraphBuilder());
// Run2 is done in a subgraph and it should not have the same ActionGraph.
assertThat(resultRun1RuleKeys, Matchers.not(equalTo(resultRun2RuleKeys)));
// Run1 and Run3 should match.
assertThat(resultRun1RuleKeys, equalTo(resultRun3RuleKeys));
}
// If this breaks it probably means the ActionGraphProvider checking also breaks.
@Test
public void compareActionGraphsBasedOnRuleKeys() {
ActionGraphProvider actionGraphProvider =
new ActionGraphProviderBuilder().withEventBus(eventBus).build();
ActionGraphAndBuilder resultRun1 =
actionGraphProvider.getFreshActionGraph(
new DefaultTargetNodeToBuildRuleTransformer(),
TestTargetGraphCreationResultFactory.create(targetGraph1));
ActionGraphAndBuilder resultRun2 =
actionGraphProvider.getFreshActionGraph(
new DefaultTargetNodeToBuildRuleTransformer(),
TestTargetGraphCreationResultFactory.create(targetGraph1));
// Check all the RuleKeys are the same between the 2 ActionGraphs.
Map<BuildRule, RuleKey> resultRun1RuleKeys =
getRuleKeysFromBuildRules(
resultRun1.getActionGraph().getNodes(), resultRun1.getActionGraphBuilder());
Map<BuildRule, RuleKey> resultRun2RuleKeys =
getRuleKeysFromBuildRules(
resultRun2.getActionGraph().getNodes(), resultRun2.getActionGraphBuilder());
assertThat(resultRun1RuleKeys, equalTo(resultRun2RuleKeys));
}
@Test
public void incrementalActionGraphStateIsLogged() {
List<ExperimentEvent> experimentEvents;
for (IncrementalActionGraphMode mode :
ImmutableSet.of(IncrementalActionGraphMode.DISABLED, IncrementalActionGraphMode.ENABLED)) {
new ActionGraphProviderBuilder()
.withEventBus(eventBus)
.withRuleKeyConfiguration(TestRuleKeyConfigurationFactory.createWithSeed(keySeed))
.withIncrementalActionGraphMode(mode)
.build()
.getActionGraph(TestTargetGraphCreationResultFactory.create(targetGraph1));
experimentEvents =
RichStream.from(trackedEvents.stream())
.filter(ExperimentEvent.class)
.filter(ev -> !ev.getTag().equals("rule_analysis"))
.collect(Collectors.toList());
assertThat(
"No experiment event is logged if not in experiment mode", experimentEvents, empty());
}
trackedEvents.clear();
ImmutableMap.Builder<IncrementalActionGraphMode, Double> experimentGroups =
ImmutableMap.builder();
experimentGroups.put(IncrementalActionGraphMode.ENABLED, 0.5);
experimentGroups.put(IncrementalActionGraphMode.DISABLED, 0.5);
new ActionGraphProviderBuilder()
.withEventBus(eventBus)
.withRuleKeyConfiguration(TestRuleKeyConfigurationFactory.createWithSeed(keySeed))
.withIncrementalActionGraphExperimentGroups(experimentGroups.build())
.withIncrementalActionGraphMode(IncrementalActionGraphMode.EXPERIMENT)
.build()
.getActionGraph(TestTargetGraphCreationResultFactory.create(targetGraph1));
experimentEvents =
RichStream.from(trackedEvents.stream())
.filter(ExperimentEvent.class)
.filter(ev -> !ev.getTag().equals("rule_analysis"))
.collect(Collectors.toList());
assertThat(
"EXPERIMENT mode should log either enabled or disabled.",
experimentEvents,
contains(
allOf(
hasProperty("tag", equalTo("incremental_action_graph")),
hasProperty("variant", anyOf(equalTo("ENABLED"), equalTo("DISABLED"))))));
trackedEvents.clear();
}
@Test
public void cachedSubgraphReturnedFromNodeCacheParallel() {
ListeningExecutorService executor =
MoreExecutors.listeningDecorator(MostExecutors.newMultiThreadExecutor("threads", 1));
try (Scope ignored = executor::shutdownNow) {
ActionGraphProvider cache =
new ActionGraphProviderBuilder()
.withPoolSupplier(ImmutableMap.of(ExecutorPool.GRAPH_CPU, executor))
.withEventBus(eventBus)
.withRuleKeyConfiguration(TestRuleKeyConfigurationFactory.createWithSeed(keySeed))
.withIncrementalActionGraphMode(IncrementalActionGraphMode.ENABLED)
.build();
TargetNode<?> originalNode3 = createCacheableTargetNode("C");
TargetNode<?> originalNode2 = createCacheableTargetNode("B", originalNode3);
TargetNode<?> originalNode1 = createCacheableTargetNode("A", originalNode2);
targetGraph1 = TargetGraphFactory.newInstance(originalNode1, originalNode2, originalNode3);
ActionGraphAndBuilder originalResult =
cache.getActionGraph(TestTargetGraphCreationResultFactory.create(targetGraph1));
BuildRule originalBuildRule1 =
originalResult.getActionGraphBuilder().getRule(originalNode1.getBuildTarget());
BuildRule originalBuildRule2 =
originalResult.getActionGraphBuilder().getRule(originalNode2.getBuildTarget());
BuildRule originalBuildRule3 =
originalResult.getActionGraphBuilder().getRule(originalNode3.getBuildTarget());
TargetNode<?> newNode4 = createCacheableTargetNode("D");
TargetNode<?> newNode3 = createCacheableTargetNode("C");
TargetNode<?> newNode2 = createCacheableTargetNode("B", newNode3);
TargetNode<?> newNode1 = createCacheableTargetNode("A", newNode2, newNode4);
targetGraph2 = TargetGraphFactory.newInstance(newNode1, newNode2, newNode3, newNode4);
ActionGraphAndBuilder newResult =
cache.getActionGraph(TestTargetGraphCreationResultFactory.create(targetGraph2));
assertNotSame(
originalBuildRule1, newResult.getActionGraphBuilder().getRule(newNode1.getBuildTarget()));
assertSame(
originalBuildRule2, newResult.getActionGraphBuilder().getRule(newNode2.getBuildTarget()));
assertSame(
originalBuildRule3, newResult.getActionGraphBuilder().getRule(newNode3.getBuildTarget()));
}
}
private TargetNode<?> createCacheableTargetNode(String name, TargetNode<?>... deps) {
return FakeTargetNodeBuilder.newBuilder(BuildTargetFactory.newInstance("//foo:" + name))
.setDeps(deps)
.setProducesCacheableSubgraph(true)
.build();
}
private TargetNode<?> createTargetNode(String name, TargetNode<?>... deps) {
BuildTarget buildTarget = BuildTargetFactory.newInstance("//foo:" + name);
JavaLibraryBuilder targetNodeBuilder = JavaLibraryBuilder.createBuilder(buildTarget);
for (TargetNode<?> dep : deps) {
targetNodeBuilder.addDep(dep.getBuildTarget());
}
return targetNodeBuilder.build();
}
private int countEventsOf(Class<? extends ActionGraphEvent> trackedClass) {
int i = 0;
for (BuckEvent event : trackedEvents) {
if (trackedClass.isInstance(event)) {
i++;
}
}
return i;
}
private Map<BuildRule, RuleKey> getRuleKeysFromBuildRules(
Iterable<BuildRule> buildRules, BuildRuleResolver buildRuleResolver) {
RuleKeyFieldLoader ruleKeyFieldLoader =
new RuleKeyFieldLoader(TestRuleKeyConfigurationFactory.create());
ContentAgnosticRuleKeyFactory factory =
new ContentAgnosticRuleKeyFactory(ruleKeyFieldLoader, buildRuleResolver, Optional.empty());
HashMap<BuildRule, RuleKey> ruleKeysMap = new HashMap<>();
for (BuildRule rule : buildRules) {
ruleKeysMap.put(rule, factory.build(rule));
}
return ruleKeysMap;
}
}
| apache-2.0 |
keedio/flume-cacheable-interceptor-skeleton | src/test/java/org/apache/flume/interceptor/CacheableInterceptorTest.java | 1147 | package org.apache.flume.interceptor;
import org.apache.flume.Event;
import org.apache.flume.interceptor.service.ICacheService;
import org.springframework.context.ApplicationContext;
import org.testng.Assert;
import org.testng.annotations.Test;
public class CacheableInterceptorTest {
@Test
public void testSpringContext() {
CacheableInterceptor.Builder builder = new CacheableInterceptor.Builder();
CacheableInterceptor interceptor = (CacheableInterceptor) builder.build();
ApplicationContext context = interceptor.getContext();
Assert.assertNotNull(context);
String id = context.getId();
Assert.assertNotNull(id);
}
@Test
public void testSpringService() {
CacheableInterceptor.Builder builder = new CacheableInterceptor.Builder();
CacheableInterceptor interceptor = (CacheableInterceptor) builder.build();
interceptor.initialize();
ICacheService<Event> service = interceptor.getService();
Assert.assertNotNull(service);
String name = service.getClass().getCanonicalName();
Assert.assertNotNull(name);
}
}
| apache-2.0 |
nikGayko/Onliner | Onliner/app/src/main/java/com/example/nick/onliner/Parser/ParseArticle.java | 873 | package com.example.nick.onliner.Parser;
import android.os.AsyncTask;
import android.util.Log;
import com.example.backend.HttpClient;
public class ParseArticle extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... url) {
String html[] = new HttpClient().getHtml(url[0]).getData();
return getContent(html);
}
private String getContent(String html[]) {
String content = "";
for (int z = 0; z < html.length; z++) {
if (html[z].contains("<p>")) {
content += html[z].substring(html[z].indexOf("<p>") + 3, html[z].indexOf("</p>")) + "\n\n";
Log.d("TAG", content);
}
// TODO: 02.11.2016 this condition doesn't work
if(html[z].contains("text-align: right")) break;
}
return content;
}
}
| apache-2.0 |
dongpf/hadoop-0.19.1 | src/test/org/apache/hadoop/hdfs/TestFileAppend.java | 11168 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import junit.framework.TestCase;
import java.io.*;
import java.net.*;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileUtil.HardLink;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.FSDataset;
import org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset;
/**
* This class tests the building blocks that are needed to support HDFS appends.
*/
public class TestFileAppend extends TestCase {
static final int blockSize = 1024;
static final int numBlocks = 10;
static final int fileSize = numBlocks * blockSize + 1;
boolean simulatedStorage = false;
private long seed;
private byte[] fileContents = null;
//
// create a buffer that contains the entire test file data.
//
private void initBuffer(int size) {
seed = AppendTestUtil.nextLong();
fileContents = AppendTestUtil.randomBytes(seed, size);
}
/*
* creates a file but does not close it
*/
private FSDataOutputStream createFile(FileSystem fileSys, Path name, int repl) throws IOException {
FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096),
(short) repl, (long) blockSize);
return stm;
}
//
// writes to file but does not close it
//
private void writeFile(FSDataOutputStream stm) throws IOException {
byte[] buffer = AppendTestUtil.randomBytes(seed, fileSize);
stm.write(buffer);
}
//
// verify that the data written to the full blocks are sane
//
private void checkFile(FileSystem fileSys, Path name, int repl) throws IOException {
boolean done = false;
// wait till all full blocks are confirmed by the datanodes.
while (!done) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
done = true;
BlockLocation[] locations = fileSys.getFileBlockLocations(fileSys.getFileStatus(name), 0, fileSize);
if (locations.length < numBlocks) {
System.out.println("Number of blocks found " + locations.length);
done = false;
continue;
}
for (int idx = 0; idx < numBlocks; idx++) {
if (locations[idx].getHosts().length < repl) {
System.out.println("Block index " + idx + " not yet replciated.");
done = false;
break;
}
}
}
FSDataInputStream stm = fileSys.open(name);
byte[] expected = new byte[numBlocks * blockSize];
if (simulatedStorage) {
for (int i = 0; i < expected.length; i++) {
expected[i] = SimulatedFSDataset.DEFAULT_DATABYTE;
}
} else {
for (int i = 0; i < expected.length; i++) {
expected[i] = fileContents[i];
}
}
// do a sanity check. Read the file
byte[] actual = new byte[numBlocks * blockSize];
stm.readFully(0, actual);
checkData(actual, 0, expected, "Read 1");
}
private void checkFullFile(FileSystem fs, Path name) throws IOException {
FSDataInputStream stm = fs.open(name);
byte[] actual = new byte[fileSize];
stm.readFully(0, actual);
checkData(actual, 0, fileContents, "Read 2");
stm.close();
}
private void checkData(byte[] actual, int from, byte[] expected, String message) {
for (int idx = 0; idx < actual.length; idx++) {
assertEquals(message + " byte " + (from + idx) + " differs. expected " + expected[from + idx] + " actual "
+ actual[idx], expected[from + idx], actual[idx]);
actual[idx] = 0;
}
}
/**
* Test that copy on write for blocks works correctly
*/
public void testCopyOnWrite() throws IOException {
Configuration conf = new Configuration();
if (simulatedStorage) {
conf.setBoolean(SimulatedFSDataset.CONFIG_PROPERTY_SIMULATED, true);
}
MiniDFSCluster cluster = new MiniDFSCluster(conf, 1, true, null);
FileSystem fs = cluster.getFileSystem();
InetSocketAddress addr = new InetSocketAddress("localhost", cluster.getNameNodePort());
DFSClient client = new DFSClient(addr, conf);
try {
// create a new file, write to it and close it.
//
Path file1 = new Path("/filestatus.dat");
FSDataOutputStream stm = createFile(fs, file1, 1);
writeFile(stm);
stm.close();
// Get a handle to the datanode
DataNode[] dn = cluster.listDataNodes();
assertTrue("There should be only one datanode but found " + dn.length, dn.length == 1);
LocatedBlocks locations = client.namenode.getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
List<LocatedBlock> blocks = locations.getLocatedBlocks();
FSDataset dataset = (FSDataset) dn[0].data;
//
// Create hard links for a few of the blocks
//
for (int i = 0; i < blocks.size(); i = i + 2) {
Block b = (Block) blocks.get(i).getBlock();
FSDataset fsd = (FSDataset) dataset;
File f = fsd.getFile(b);
File link = new File(f.toString() + ".link");
System.out.println("Creating hardlink for File " + f + " to " + link);
HardLink.createHardLink(f, link);
}
//
// Detach all blocks. This should remove hardlinks (if any)
//
for (int i = 0; i < blocks.size(); i++) {
Block b = (Block) blocks.get(i).getBlock();
System.out.println("testCopyOnWrite detaching block " + b);
assertTrue("Detaching block " + b + " should have returned true", dataset.detachBlock(b, 1) == true);
}
// Since the blocks were already detached earlier, these calls
// should
// return false
//
for (int i = 0; i < blocks.size(); i++) {
Block b = (Block) blocks.get(i).getBlock();
System.out.println("testCopyOnWrite detaching block " + b);
assertTrue("Detaching block " + b + " should have returned false", dataset.detachBlock(b, 1) == false);
}
} finally {
fs.close();
cluster.shutdown();
}
}
/**
* Test a simple flush on a simple HDFS file.
*/
public void testSimpleFlush() throws IOException {
Configuration conf = new Configuration();
if (simulatedStorage) {
conf.setBoolean(SimulatedFSDataset.CONFIG_PROPERTY_SIMULATED, true);
}
initBuffer(fileSize);
MiniDFSCluster cluster = new MiniDFSCluster(conf, 1, true, null);
FileSystem fs = cluster.getFileSystem();
try {
// create a new file.
Path file1 = new Path("/simpleFlush.dat");
FSDataOutputStream stm = createFile(fs, file1, 1);
System.out.println("Created file simpleFlush.dat");
// write to file
int mid = fileSize / 2;
stm.write(fileContents, 0, mid);
stm.sync();
System.out.println("Wrote and Flushed first part of file.");
// write the remainder of the file
stm.write(fileContents, mid, fileSize - mid);
System.out.println("Written second part of file");
stm.sync();
stm.sync();
System.out.println("Wrote and Flushed second part of file.");
// verify that full blocks are sane
checkFile(fs, file1, 1);
stm.close();
System.out.println("Closed file.");
// verify that entire file is good
checkFullFile(fs, file1);
} catch (IOException e) {
System.out.println("Exception :" + e);
throw e;
} catch (Throwable e) {
System.out.println("Throwable :" + e);
e.printStackTrace();
throw new IOException("Throwable : " + e);
} finally {
fs.close();
cluster.shutdown();
}
}
/**
* Test that file data can be flushed.
*/
public void testComplexFlush() throws IOException {
Configuration conf = new Configuration();
if (simulatedStorage) {
conf.setBoolean(SimulatedFSDataset.CONFIG_PROPERTY_SIMULATED, true);
}
initBuffer(fileSize);
MiniDFSCluster cluster = new MiniDFSCluster(conf, 1, true, null);
FileSystem fs = cluster.getFileSystem();
try {
// create a new file.
Path file1 = new Path("/complexFlush.dat");
FSDataOutputStream stm = createFile(fs, file1, 1);
System.out.println("Created file complexFlush.dat");
int start = 0;
for (start = 0; (start + 29) < fileSize;) {
stm.write(fileContents, start, 29);
stm.sync();
start += 29;
}
stm.write(fileContents, start, fileSize - start);
// verify that full blocks are sane
checkFile(fs, file1, 1);
stm.close();
// verify that entire file is good
checkFullFile(fs, file1);
} catch (IOException e) {
System.out.println("Exception :" + e);
throw e;
} catch (Throwable e) {
System.out.println("Throwable :" + e);
e.printStackTrace();
throw new IOException("Throwable : " + e);
} finally {
fs.close();
cluster.shutdown();
}
}
}
| apache-2.0 |
justinsb/cloudata | cloudata-shared/src/main/java/com/cloudata/util/ByteStrings.java | 1266 | package com.cloudata.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.io.ByteSource;
import com.google.protobuf.ByteString;
public class ByteStrings {
public static ByteSource asByteSource(ByteString s) {
return new ByteStringByteSource(s);
}
public static class ByteStringByteSource extends ByteSource {
final ByteString s;
public ByteStringByteSource(ByteString s) {
this.s = s;
}
@Override
public InputStream openStream() throws IOException {
return s.newInput();
}
@Override
public InputStream openBufferedStream() throws IOException {
return openStream();
}
@Override
public long size() throws IOException {
return s.size();
}
@Override
public long copyTo(OutputStream output) throws IOException {
s.writeTo(output);
return s.size();
}
}
public static HashCode hash(HashFunction hash, ByteString data) throws IOException {
return asByteSource(data).hash(hash);
}
}
| apache-2.0 |
yuanguozheng/XiyouLibrary | src/com/JustYY/xiyoulibrary/model/SearchResultAdapter.java | 1562 | package com.JustYY.xiyoulibrary.model;
import java.util.List;
import java.util.Map;
import com.JustYY.xiyoulibrary.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SearchResultAdapter extends BaseAdapter {
private class ViewHolder {
TextView bookTitle;
}
private List<Map<String, String>> resultItems;
private Context context;
// private LayoutInflater inflater;
public SearchResultAdapter(List<Map<String, String>> resultItems,
Context context) {
this.resultItems = resultItems;
this.context = context;
}
@Override
public int getCount() {
return resultItems.size();
}
@Override
public Object getItem(int position) {
return resultItems.get(position).get("ID");
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(
R.layout.searchresult_item, null);
holder = new ViewHolder();
holder.bookTitle = (TextView) convertView
.findViewById(R.id.searchresult_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.bookTitle.setText(resultItems.get(position).get("Name"));
return convertView;
}
public void addItem(Map<String, String> it) {
resultItems.add(it);
}
}
| apache-2.0 |
ysjiang4869/WechatPet | src/main/java/com/pinebud/application/wechat/pet/handler/LogHandler.java | 812 | package com.pinebud.application.wechat.pet.handler;
import com.pinebud.application.wechat.pet.utils.JsonUtils;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author Binary Wang
*/
@Component
public class LogHandler extends AbstractHandler {
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
Map<String, Object> context, WxMpService wxMpService,
WxSessionManager sessionManager) {
this.logger.info("\n接收到请求消息,内容:{}", JsonUtils.toJson(wxMessage));
return null;
}
}
| apache-2.0 |
TANGO-Project/code-optimiser-plugin | bundles/org.jvmmonitor.ui/src/org/jvmmonitor/internal/ui/views/JvmTreeLabelProvider.java | 9589 | /*******************************************************************************
* Copyright (c) 2010 JVM Monitor project. All rights reserved.
*
* This code is distributed under the terms of the Eclipse Public License v1.0
* which is available at http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.jvmmonitor.internal.ui.views;
import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.swt.graphics.Image;
import org.jvmmonitor.core.IActiveJvm;
import org.jvmmonitor.core.IHost;
import org.jvmmonitor.core.IJvm;
import org.jvmmonitor.core.ISnapshot;
import org.jvmmonitor.core.ISnapshot.SnapshotType;
import org.jvmmonitor.core.ITerminatedJvm;
import org.jvmmonitor.ui.Activator;
import org.jvmmonitor.ui.ISharedImages;
/**
* The label provider for JVMs tree viewer.
*/
public class JvmTreeLabelProvider implements IStyledLabelProvider,
ISharedImages {
/** The local host image. */
private Image localHostImage;
/** The remote host image. */
private Image remoteHostImage;
/** The connected JVM image. */
private Image connectedJvmImage;
/** The disconnected JVM image. */
private Image disconnectedJvmImage;
/** The terminated JVM image. */
private Image terminatedJvmImage;
/** The thread dump image. */
private Image threadDumpImage;
/** The hprof dump image. */
private Image hprofDumpImage;
/** The heap dump image. */
private Image heapDumpImage;
/** The CPU dump image. */
private Image cpuDumpImage;
/*
* @see IStyledLabelProvider#getImage(Object)
*/
@Override
public Image getImage(Object element) {
// host image
if (element instanceof IHost) {
if (IHost.LOCALHOST.equals(((IHost) element).getName())) {
return getLocalHostImage();
}
return getRemoteHostImage();
}
// JVM image
if (element instanceof IActiveJvm) {
if (((IActiveJvm) element).isConnected()) {
return getConnectedJvmImage();
}
return getDisconnectedJvmImage();
} else if (element instanceof IJvm) {
return getTerminatedJvmImage();
}
// snapshot image
if (element instanceof ISnapshot) {
if (((ISnapshot) element).getType() == SnapshotType.Thread) {
return getThreadDumpImage();
} else if (((ISnapshot) element).getType() == SnapshotType.Hprof) {
return getHprofDumpImage();
} else if (((ISnapshot) element).getType() == SnapshotType.Heap) {
return getHeapDumpImage();
} else if (((ISnapshot) element).getType() == SnapshotType.Cpu) {
return getCpuDumpImage();
}
}
return null;
}
/*
* @see IStyledLabelProvider#getStyledText(Object)
*/
@Override
public StyledString getStyledText(Object element) {
StyledString text = new StyledString();
if (element instanceof IJvm) {
String prefix = ""; //$NON-NLS-1$
String mainClass = ((IJvm) element).getMainClass();
String suffix = getIdInicator((IJvm) element);
if (element instanceof ITerminatedJvm) {
prefix = "<terminated>"; //$NON-NLS-1$
}
text.append(prefix).append(mainClass).append(suffix);
text.setStyle(prefix.length() + mainClass.length(),
suffix.length(), StyledString.DECORATIONS_STYLER);
} else if (element instanceof ISnapshot) {
String fileName = ((ISnapshot) element).getFileStore().getName();
text.append(fileName);
String date = ((ISnapshot) element).getTimeStamp();
if (date != null) {
text.append(" (").append(date).append(")"); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
text.append(element.toString());
}
return text;
}
/*
* @see IBaseLabelProvider#addListener(ILabelProviderListener)
*/
@Override
public void addListener(ILabelProviderListener listener) {
// do nothing
}
/*
* @see IBaseLabelProvider#dispose()
*/
@Override
public void dispose() {
if (localHostImage != null) {
localHostImage.dispose();
}
if (remoteHostImage != null) {
remoteHostImage.dispose();
}
if (connectedJvmImage != null) {
connectedJvmImage.dispose();
}
if (disconnectedJvmImage != null) {
disconnectedJvmImage.dispose();
}
if (terminatedJvmImage != null) {
terminatedJvmImage.dispose();
}
if (threadDumpImage != null) {
threadDumpImage.dispose();
}
if (heapDumpImage != null) {
heapDumpImage.dispose();
}
if (hprofDumpImage != null) {
hprofDumpImage.dispose();
}
if (cpuDumpImage != null) {
cpuDumpImage.dispose();
}
}
/*
* @see IBaseLabelProvider#isLabelProperty(Object, String)
*/
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
/*
* @see IBaseLabelProvider#removeListener(ILabelProviderListener)
*/
@Override
public void removeListener(ILabelProviderListener listener) {
// do nothing
}
/**
* Gets the local host image.
*
* @return The image
*/
private Image getLocalHostImage() {
if (localHostImage == null || localHostImage.isDisposed()) {
localHostImage = Activator.getImageDescriptor(LOCAL_HOST_IMG_PATH)
.createImage();
}
return localHostImage;
}
/**
* Gets the remote host image.
*
* @return The image
*/
private Image getRemoteHostImage() {
if (remoteHostImage == null || remoteHostImage.isDisposed()) {
remoteHostImage = Activator
.getImageDescriptor(REMOTE_HOST_IMG_PATH).createImage();
}
return remoteHostImage;
}
/**
* Gets the connected JVM image.
*
* @return The image
*/
private Image getConnectedJvmImage() {
if (connectedJvmImage == null || connectedJvmImage.isDisposed()) {
connectedJvmImage = Activator.getImageDescriptor(
CONNECTED_JVM_IMG_PATH).createImage();
}
return connectedJvmImage;
}
/**
* Gets the disconnected JVM image.
*
* @return The image
*/
private Image getDisconnectedJvmImage() {
if (disconnectedJvmImage == null || disconnectedJvmImage.isDisposed()) {
disconnectedJvmImage = Activator.getImageDescriptor(
DISCONNECTED_JVM_IMG_PATH).createImage();
}
return disconnectedJvmImage;
}
/**
* Gets the terminated JVM image.
*
* @return The image
*/
private Image getTerminatedJvmImage() {
if (terminatedJvmImage == null || terminatedJvmImage.isDisposed()) {
terminatedJvmImage = Activator.getImageDescriptor(
TERMINATED_JVM_IMG_PATH).createImage();
}
return terminatedJvmImage;
}
/**
* Gets the thread dump image.
*
* @return The image
*/
private Image getThreadDumpImage() {
if (threadDumpImage == null || threadDumpImage.isDisposed()) {
threadDumpImage = Activator
.getImageDescriptor(THREAD_DUMP_IMG_PATH).createImage();
}
return threadDumpImage;
}
/**
* Gets the hprof dump image.
*
* @return The image
*/
private Image getHprofDumpImage() {
if (hprofDumpImage == null || hprofDumpImage.isDisposed()) {
hprofDumpImage = Activator.getImageDescriptor(HPROF_DUMP_IMG_PATH)
.createImage();
}
return hprofDumpImage;
}
/**
* Gets the heap dump image.
*
* @return The image
*/
private Image getHeapDumpImage() {
if (heapDumpImage == null || heapDumpImage.isDisposed()) {
heapDumpImage = Activator.getImageDescriptor(HEAP_DUMP_IMG_PATH)
.createImage();
}
return heapDumpImage;
}
/**
* Gets the CPU dump image.
*
* @return The image
*/
private Image getCpuDumpImage() {
if (cpuDumpImage == null || cpuDumpImage.isDisposed()) {
cpuDumpImage = Activator.getImageDescriptor(CPU_DUMP_IMG_PATH)
.createImage();
}
return cpuDumpImage;
}
/**
* Gets the ID indicator. e.g. [PID: 1234]
*
* @param jvm
* The JVM
* @return the ID
*/
private static String getIdInicator(IJvm jvm) {
int pid = jvm.getPid();
int port = jvm.getPort();
StringBuffer buffer = new StringBuffer();
if (pid != -1) {
buffer.append(" [PID: ").append(pid).append("]"); //$NON-NLS-1$ //$NON-NLS-2$
}
if (port != -1) {
buffer.append(" [Port: ").append(port).append("]"); //$NON-NLS-1$ //$NON-NLS-2$
}
return buffer.toString();
}
}
| apache-2.0 |
nayuan/properties-maven-plugin | src/main/java/com/dplugin/maven/plugins/properties/source/JdbcTemplate.java | 3175 | package com.dplugin.maven.plugins.properties.source;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 数据库表操作类 2016-07-23 22:45:46
* @author nayuan
*/
public class JdbcTemplate {
private DataSource dataSource;
public JdbcTemplate(com.dplugin.maven.plugins.properties.model.DataSource source) throws Exception {
Properties properties = new Properties();
properties.put("url", source.getUrl());
properties.put("username", source.getUsername());
properties.put("password", source.getPassword());
this.dataSource = DruidDataSourceFactory.createDataSource(properties);
}
public String getPackId(String sql, Object... args) throws SQLException {
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = dataSource.getConnection();
try{
preparedStatement = connection.prepareStatement(sql);
if(args != null && args.length > 0) {
for(int i = 0; i < args.length; i++) {
preparedStatement.setObject(i+1, args[i]);
}
}
resultSet = preparedStatement.executeQuery();
if(resultSet.next()) {
return resultSet.getString("id");
}else{
return null;
}
}finally {
if(resultSet != null) {
resultSet.close();
}
if(preparedStatement != null) {
preparedStatement.close();
}
if(connection != null) {
connection.close();
}
}
}
public List<Entry> queryForList(String sql, Object... args) throws SQLException {
List<Entry> result = new ArrayList();
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = dataSource.getConnection();
try{
preparedStatement = connection.prepareStatement(sql);
if(args != null && args.length > 0) {
for(int i = 0; i < args.length; i++) {
preparedStatement.setObject(i+1, args[i]);
}
}
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
result.add(new Entry(
resultSet.getObject("id"),
resultSet.getString("title"),
resultSet.getString("key"),
resultSet.getString("value")
));
}
}finally {
if(resultSet != null) {
resultSet.close();
}
if(preparedStatement != null) {
preparedStatement.close();
}
if(connection != null) {
connection.close();
}
}
return result;
}
}
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-clouddirectory/src/main/java/com/amazonaws/services/clouddirectory/model/TagResourceResult.java | 2231 | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.clouddirectory.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/clouddirectory-2016-05-10/TagResource" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TagResourceResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof TagResourceResult == false)
return false;
TagResourceResult other = (TagResourceResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public TagResourceResult clone() {
try {
return (TagResourceResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
lemonJun/Emmet | src/test/java/algo1/common/HuiWen.java | 1148 | package algo1.common;
public class HuiWen {
public static void main(String[] args) {
f2(123454321);
}
// 方法一
public static void f1(int n) {
if (n >= 10000 && n < 100000) {
String s = String.valueOf(n);
char[] c = s.toCharArray();
if (c[0] == c[4] && c[1] == c[3]) {
System.out.println(n + "是一个回文数。");
} else {
System.out.println(n + "不是一个回文数。");
}
} else {
System.out.println(n + "不是一个5位数!!!");
}
}
// 方法二
public static void f2(int n) {
boolean flag = true;
String s = Long.toString(n);
char[] c = s.toCharArray();
int j = c.length;
for (int i = 0; i < j / 2; i++) {
if (c[i] != c[j - i - 1]) {
flag = false;
}
}
if (flag) {
System.out.println(n + "是一个回文数。");
} else {
System.out.println(n + "不是一个回文数。");
}
}
}
| apache-2.0 |
dvamedveda/b.savelev | chapter_001/src/test/java/ru/job4j/CalculateTest.java | 500 | package ru.job4j;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
* @author b.savelev
* @version 2.0
* @since 1.8
*/
public class CalculateTest {
/**
* Test for echo method.
*/
@Test
public void whenTakeNameThenThreeEchoPlusName() {
String input = "b.savelev";
String expect = "Echo, echo, echo: b.savelev";
Calculate calc = new Calculate();
String result = calc.echo(input);
assertThat(result, is(expect));
}
} | apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-route53resolver/src/main/java/com/amazonaws/services/route53resolver/model/transform/TagResourceResultJsonUnmarshaller.java | 1595 | /*
* 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.route53resolver.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.route53resolver.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* TagResourceResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TagResourceResultJsonUnmarshaller implements Unmarshaller<TagResourceResult, JsonUnmarshallerContext> {
public TagResourceResult unmarshall(JsonUnmarshallerContext context) throws Exception {
TagResourceResult tagResourceResult = new TagResourceResult();
return tagResourceResult;
}
private static TagResourceResultJsonUnmarshaller instance;
public static TagResourceResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new TagResourceResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
opentracing-contrib/java-spring-cloud | instrument-starters/opentracing-spring-cloud-jdbc-starter/src/main/java/io/opentracing/contrib/spring/cloud/jdbc/JdbcTracingProperties.java | 1516 | /**
* Copyright 2017-2018 The OpenTracing 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 io.opentracing.contrib.spring.cloud.jdbc;
import java.util.HashSet;
import java.util.Set;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "opentracing.spring.cloud.jdbc")
public class JdbcTracingProperties {
/**
* Trace JDBC calls only if it's part of an active span.
*/
private boolean withActiveSpanOnly = false;
/**
* Set of JDBC statement calls to not trace.
*/
private Set<String> ignoreStatements = new HashSet<>();
public boolean isWithActiveSpanOnly() {
return withActiveSpanOnly;
}
public void setWithActiveSpanOnly(boolean withActiveSpanOnly) {
this.withActiveSpanOnly = withActiveSpanOnly;
}
public Set<String> getIgnoreStatements() {
return ignoreStatements;
}
public void setIgnoreStatements(Set<String> ignoreStatements) {
this.ignoreStatements = ignoreStatements;
}
}
| apache-2.0 |
nakamura5akihito/opensec-oval | src/main/java/io/opensec/oval/model/unix/XinetdState.java | 8524 | /**
* Opensec OVAL - https://nakamura5akihito.github.io/
* Copyright (C) 2015 Akihito Nakamura
*
* 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.opensec.oval.model.unix;
import io.opensec.oval.model.ComponentType;
import io.opensec.oval.model.ElementRef;
import io.opensec.oval.model.Family;
import io.opensec.oval.model.definitions.EntityStateBoolType;
import io.opensec.oval.model.definitions.EntityStateIPAddressStringType;
import io.opensec.oval.model.definitions.EntityStateIntType;
import io.opensec.oval.model.definitions.EntityStateStringType;
import io.opensec.oval.model.definitions.StateType;
import java.util.ArrayList;
import java.util.Collection;
/**
* The xinetd state defines the different information
* associated with a specific Internet service.
*
* @author Akihito Nakamura, AIST
* @see <a href="http://oval.mitre.org/language/">OVAL Language</a>
*/
public class XinetdState
extends StateType
{
//{0..1}
private EntityStateStringType protocol;
private EntityStateStringType service_name;
private EntityStateStringType flags;
private EntityStateStringType no_access;
private EntityStateIPAddressStringType only_from;
private EntityStateIntType port;
private EntityStateStringType server;
private EntityStateStringType server_arguments;
private EntityStateStringType socket_type;
private EntityStateXinetdTypeStatusType type;
private EntityStateStringType user;
private EntityStateBoolType wait;
private EntityStateBoolType disabled;
/**
* Constructor.
*/
public XinetdState()
{
this( null, 0 );
}
public XinetdState(
final String id,
final int version
)
{
this( id, version, null );
}
public XinetdState(
final String id,
final int version,
final String comment
)
{
super( id, version, comment );
// _oval_platform_type = OvalPlatformType.unix;
// _oval_component_type = OvalComponentType.xinetd;
_oval_family = Family.UNIX;
_oval_component = ComponentType.XINETD;
}
/**
*/
public void setProtocol(
final EntityStateStringType protocol
)
{
this.protocol = protocol;
}
public EntityStateStringType getProtocol()
{
return protocol;
}
/**
*/
public void setServiceName(
final EntityStateStringType service_name
)
{
this.service_name = service_name;
}
public EntityStateStringType getServiceName()
{
return service_name;
}
/**
*/
public void setFlags(
final EntityStateStringType flags
)
{
this.flags = flags;
}
public EntityStateStringType getFlags()
{
return flags;
}
/**
*/
public void setNoAccess(
final EntityStateStringType no_access
)
{
this.no_access = no_access;
}
public EntityStateStringType getNoAccess()
{
return no_access;
}
/**
*/
public void setOnlyFrom(
final EntityStateIPAddressStringType only_from
)
{
this.only_from = only_from;
}
public EntityStateIPAddressStringType getOnlyFrom()
{
return only_from;
}
/**
*/
public void setPort(
final EntityStateIntType port
)
{
this.port = port;
}
public EntityStateIntType getPort()
{
return port;
}
/**
*/
public void setServer(
final EntityStateStringType server
)
{
this.server = server;
}
public EntityStateStringType getServer()
{
return server;
}
/**
*/
public void setServerArguments(
final EntityStateStringType server_arguments
)
{
this.server_arguments = server_arguments;
}
public EntityStateStringType getServerArguments()
{
return server_arguments;
}
/**
*/
public void setSocketType(
final EntityStateStringType socket_type
)
{
this.socket_type = socket_type;
}
public EntityStateStringType getSocketType()
{
return socket_type;
}
/**
*/
public void setType(
final EntityStateXinetdTypeStatusType type
)
{
this.type = type;
}
public EntityStateXinetdTypeStatusType getType()
{
return type;
}
/**
*/
public void setUser(
final EntityStateStringType user
)
{
this.user = user;
}
public EntityStateStringType getUser()
{
return user;
}
/**
*/
public void setWait(
final EntityStateBoolType wait
)
{
this.wait = wait;
}
public EntityStateBoolType getWait()
{
return wait;
}
/**
*/
public void setDisabled(
final EntityStateBoolType disabled
)
{
this.disabled = disabled;
}
public EntityStateBoolType getDisabled()
{
return disabled;
}
//*********************************************************************
// DefinitionsElement
//*********************************************************************
@Override
public Collection<ElementRef> ovalGetElementRef()
{
Collection<ElementRef> ref_list = new ArrayList<ElementRef>();
ref_list.add( getProtocol() );
ref_list.add( getServiceName() );
ref_list.add( getFlags() );
ref_list.add( getNoAccess() );
ref_list.add( getOnlyFrom() );
ref_list.add( getPort() );
ref_list.add( getServer() );
ref_list.add( getServerArguments() );
ref_list.add( getSocketType() );
ref_list.add( getType() );
ref_list.add( getUser() );
ref_list.add( getWait() );
ref_list.add( getDisabled() );
return ref_list;
}
//**************************************************************
// java.lang.Object
//**************************************************************
@Override
public int hashCode()
{
return super.hashCode();
}
@Override
public boolean equals(
final Object obj
)
{
if (!(obj instanceof XinetdState)) {
return false;
}
return super.equals( obj );
}
@Override
public String toString()
{
return "xinetd_state[" + super.toString()
+ ", protocol=" + getProtocol()
+ ", service_name=" + getServiceName()
+ ", flags=" + getFlags()
+ ", no_access=" + getNoAccess()
+ ", only_from=" + getOnlyFrom()
+ ", port=" + getPort()
+ ", server=" + getServer()
+ ", server_arguments=" + getServerArguments()
+ ", socket_type=" + getSocketType()
+ ", type=" + getType()
+ ", user=" + getUser()
+ ", wait=" + getWait()
+ ", disabled=" + getDisabled()
+ "]";
}
}
//XinetdState
| apache-2.0 |
agwlvssainokuni/springapp | goods/src/test/java/cherry/goods/crypto/AESDeterministicCryptoTest.java | 3262 | /*
* Copyright 2014,2015 agwlvssainokuni
*
* 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 cherry.goods.crypto;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;
public class AESDeterministicCryptoTest {
@Test
public void testDefault() throws Exception {
AESDeterministicCrypto crypto = new AESDeterministicCrypto();
crypto.setSecretKeyBytes(RandomUtils.nextBytes(16));
crypto.setInitVectorBytes(RandomUtils.nextBytes(16));
for (int i = 0; i < 100; i++) {
byte[] plain = RandomUtils.nextBytes(1024);
byte[] enc = crypto.encrypt(plain);
byte[] dec = crypto.decrypt(enc);
assertThat(dec, is(plain));
}
}
@Test
public void testCBC() throws Exception {
AESDeterministicCrypto crypto = new AESDeterministicCrypto();
crypto.setAlgorithm("AES/CBC/PKCS5Padding");
crypto.setSecretKeyBytes(RandomUtils.nextBytes(16));
crypto.setInitVectorBytes(RandomUtils.nextBytes(16));
for (int i = 0; i < 100; i++) {
byte[] plain = RandomUtils.nextBytes(1024);
byte[] enc = crypto.encrypt(plain);
byte[] dec = crypto.decrypt(enc);
assertThat(dec, is(plain));
}
}
@Test
public void testECB() throws Exception {
AESDeterministicCrypto crypto = new AESDeterministicCrypto();
crypto.setAlgorithm("AES/ECB/PKCS5Padding");
crypto.setSecretKeyBytes(RandomUtils.nextBytes(16));
for (int i = 0; i < 100; i++) {
byte[] plain = RandomUtils.nextBytes(1024);
byte[] enc = crypto.encrypt(plain);
byte[] dec = crypto.decrypt(enc);
assertThat(dec, is(plain));
}
}
@Test
public void testUsingKeyCrypto() throws Exception {
byte[] key = RandomUtils.nextBytes(16);
byte[] iv = RandomUtils.nextBytes(16);
AESDeterministicCrypto crypto0 = new AESDeterministicCrypto();
crypto0.setSecretKeyBytes(key);
crypto0.setInitVectorBytes(iv);
AESDeterministicCrypto keyCrypto = new AESDeterministicCrypto();
keyCrypto.setSecretKeyBytes(RandomUtils.nextBytes(16));
keyCrypto.setInitVectorBytes(RandomUtils.nextBytes(16));
AESDeterministicCrypto crypto1 = new AESDeterministicCrypto();
crypto1.setKeyCrypto(keyCrypto);
crypto1.setSecretKeyBytes(keyCrypto.encrypt(key));
crypto1.setInitVectorBytes(keyCrypto.encrypt(iv));
for (int i = 0; i < 100; i++) {
byte[] plain = RandomUtils.nextBytes(1024);
byte[] enc0 = crypto0.encrypt(plain);
byte[] enc1 = crypto1.encrypt(plain);
assertThat(enc1, is(enc0));
byte[] dec0 = crypto0.decrypt(enc0);
byte[] dec1 = crypto1.decrypt(enc1);
assertThat(dec0, is(plain));
assertThat(dec1, is(plain));
}
}
}
| apache-2.0 |
IAops/flyway | flyway-core/src/test/java/org/flywaydb/core/internal/dbsupport/saphana/SapHanaSqlStatementBuilderSmallTest.java | 2645 | /*
* Copyright 2010-2017 Boxfuse GmbH
*
* 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.flywaydb.core.internal.dbsupport.saphana;
import org.flywaydb.core.internal.util.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Test for PostgreSQLSqlStatementBuilder.
*/
public class SapHanaSqlStatementBuilderSmallTest {
/**
* Class under test.
*/
private SapHanaSqlStatementBuilder statementBuilder = new SapHanaSqlStatementBuilder();
@Test
public void unicodeString() {
String sqlScriptSource = "SELECT 'Bria n' \"character string 1\", '100' \"character string 2\", N'abc' \"unicode string\" FROM DUMMY;\n";
String[] lines = StringUtils.tokenizeToStringArray(sqlScriptSource, "\n");
for (String line : lines) {
statementBuilder.addLine(line);
}
assertTrue(statementBuilder.isTerminated());
}
@Test
public void binaryString() {
String sqlScriptSource = "SELECT X'00abcd' \"binary string 1\", x'dcba00' \"binary string 2\" FROM DUMMY;";
String[] lines = StringUtils.tokenizeToStringArray(sqlScriptSource, "\n");
for (String line : lines) {
statementBuilder.addLine(line);
}
assertTrue(statementBuilder.isTerminated());
}
@Test
public void binaryStringNot() {
String sqlScriptSource = "SELECT '00abcd X' \"not a binary string 1\" FROM DUMMY;";
String[] lines = StringUtils.tokenizeToStringArray(sqlScriptSource, "\n");
for (String line : lines) {
statementBuilder.addLine(line);
}
assertTrue(statementBuilder.isTerminated());
}
@Test
public void temporalString() {
String sqlScriptSource = "SELECT date'2010-01-01' \"date\", time'11:00:00.001' \"time\", timestamp'2011-12-31 23:59:59' \"timestamp\" FROM DUMMY;";
String[] lines = StringUtils.tokenizeToStringArray(sqlScriptSource, "\n");
for (String line : lines) {
statementBuilder.addLine(line);
}
assertTrue(statementBuilder.isTerminated());
}
} | apache-2.0 |
bpulse/bpulse-sdk-java | src/main/java/me/bpulse/java/client/pulsesrepository/H2PulsesRepository.java | 22218 | /**
* @Copyright (c) BPulse - http://www.bpulse.me
*/
package me.bpulse.java.client.pulsesrepository;
import java.io.File;
import java.io.InputStream;
import java.sql.BatchUpdateException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.sql.rowset.serial.SerialBlob;
import me.bpulse.domain.proto.collector.CollectorMessageRQ.PulsesRQ;
import me.bpulse.java.client.properties.PropertiesManager;
import org.h2.jdbcx.JdbcConnectionPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.protobuf.InvalidProtocolBufferException;
import static me.bpulse.java.client.common.BPulseConstants.BPULSE_PROPERTY_NUMBER_THREADS_SEND_PULSES;
import static me.bpulse.java.client.common.BPulseConstants.BPULSE_REPOSITORY_NAME;
import static me.bpulse.java.client.common.BPulseConstants.BPULSE_REPOSITORY_USER;
import static me.bpulse.java.client.common.BPulseConstants.BPULSE_STATUS_INPROGRESS;
import static me.bpulse.java.client.common.BPulseConstants.BPULSE_STATUS_PENDING;
import static me.bpulse.java.client.common.BPulseConstants.COMMON_NUMBER_0;
import static me.bpulse.java.client.common.BPulseConstants.COMMON_NUMBER_1;
import static me.bpulse.java.client.common.BPulseConstants.COMMON_NUMBER_2;
import static me.bpulse.java.client.common.BPulseConstants.COMMON_NUMBER_3;
import static me.bpulse.java.client.common.BPulseConstants.COMMON_NUMBER_5;
import static me.bpulse.java.client.common.BPulseConstants.COMMON_NUMBER_60;
/**
* @author BPulse team
*
* @Copyright (c) BPulse - http://www.bpulse.me
*/
public class H2PulsesRepository implements IPulsesRepository {
private JdbcConnectionPool connectionPool;
private int insertedRecords = COMMON_NUMBER_0;
private long insertTimeMillisAverage = COMMON_NUMBER_0;
private long deleteTimeMillisAverage = COMMON_NUMBER_0;
private long getTimeMillisAverage = COMMON_NUMBER_0;
private long sortedKeysTimeMillisAverage = COMMON_NUMBER_0;
private int limitNumberPulsesToReadFromDb = COMMON_NUMBER_0;
private Map<Integer,String> bpulseTableInProgressMap;
private String dbPath;
private File dbFile;
final static Logger logger = LoggerFactory.getLogger("bpulseLogger");
public H2PulsesRepository(int maxNumberPulsesToProcessByTimer) throws Exception {
dbPath = PropertiesManager.getProperty("bpulse.client.pulsesRepositoryDBPath");
if (dbPath == null) {
dbPath = "~";
}
//jdbc:h2:~/test
try {
connectionPool = JdbcConnectionPool.create("jdbc:h2:"+dbPath+"/"+BPULSE_REPOSITORY_NAME + ";DB_CLOSE_ON_EXIT=FALSE", BPULSE_REPOSITORY_USER, "");
String initialPoolSizeSendPulses = "" + COMMON_NUMBER_5;//PropertiesManager.getProperty(BPULSE_PROPERTY_NUMBER_THREADS_SEND_PULSES);
int pPoolSizeSendPulses = COMMON_NUMBER_0;
if (initialPoolSizeSendPulses != null) {
pPoolSizeSendPulses = Integer.parseInt(initialPoolSizeSendPulses);
} else {
pPoolSizeSendPulses = COMMON_NUMBER_5;
}
connectionPool.setMaxConnections(pPoolSizeSendPulses);
connectionPool.setLoginTimeout(COMMON_NUMBER_5);//TODO DEFINIR TIEMPO MAXIMO DE ESPERA
dbFile = new File(dbPath+"/"+BPULSE_REPOSITORY_NAME+".mv.db");
} catch (Exception e) {
logger.error("FAILED TO CREATE PULSES DATABASE: PLEASE CHECK YOUR PULSESREPOSITORYPATH IN THE BPULSE PROPERTIES FILE.");
throw e;
}
this.limitNumberPulsesToReadFromDb = maxNumberPulsesToProcessByTimer;
logger.debug("PREPARING TO CREATE PULSES DATABASE.");
try {
Connection conn = connectionPool.getConnection();
PreparedStatement createPreparedStatement = null;
for (int i=COMMON_NUMBER_0; i < COMMON_NUMBER_60; i++) {
String CreateQuery = "CREATE TABLE BPULSE_PULSESRQ_" + i + "(pulserq_id BIGINT primary key, pulserq_object BLOB, pulserq_status varchar(2))";
createPreparedStatement = conn.prepareStatement(CreateQuery);
createPreparedStatement.executeUpdate();
}
createPreparedStatement.close();
conn.close();
} catch (SQLException e) {
logger.debug("PULSES DATABASE ALREADY EXISTS.");
}
bpulseTableInProgressMap = new HashMap<Integer,String>();
}
/**
* Method that saves the sent pulse in the PULSESDB.
*
* @param pPulsesRQ The Pulse in Protobuf format.
*/
@Override
public synchronized void savePulse(PulsesRQ pPulsesRQ) throws Exception {
String InsertQuery = "INSERT INTO BPULSE_PULSESRQ" + "(pulserq_id, pulserq_object, pulserq_status) values" + "(?,?,?)";
Connection conn;
long initTime = Calendar.getInstance().getTimeInMillis();
Random random = new Random();
long additionalPulseId = Math.abs(random.nextLong());
long key = System.currentTimeMillis()+additionalPulseId;
try {
conn = connectionPool.getConnection();
PreparedStatement insertPreparedStatement = null;
insertPreparedStatement = conn.prepareStatement(InsertQuery);
insertPreparedStatement.setLong(COMMON_NUMBER_1, key);
Blob blob = new SerialBlob(pPulsesRQ.toByteArray());
insertPreparedStatement.setBlob(COMMON_NUMBER_2, blob);
insertPreparedStatement.setString(COMMON_NUMBER_3, BPULSE_STATUS_PENDING);
insertPreparedStatement.executeUpdate();
conn.commit();
insertPreparedStatement.close();
conn.close();
insertedRecords++;
this.insertTimeMillisAverage = this.insertTimeMillisAverage + (Calendar.getInstance().getTimeInMillis() - initTime);
} catch (SQLException e) {
logger.error("FAILED TO SAVE PULSE: ", e);
throw e;
}
}
/**
* Method that saves the sent pulse in the PULSESDB.
*
* @param pPulsesRQ The Pulse in Protobuf format.
*/
@Override
public synchronized void savePulse(PulsesRQ pPulsesRQ, int tableIndex) throws Exception {
String InsertQuery = "INSERT INTO BPULSE_PULSESRQ_" + tableIndex + "(pulserq_id, pulserq_object, pulserq_status) values" + "(?,?,?)";
Connection conn;
long initTime = Calendar.getInstance().getTimeInMillis();
Random random = new Random();
long additionalPulseId = Math.abs(random.nextLong());
long key = System.currentTimeMillis()+additionalPulseId;
try {
conn = connectionPool.getConnection();
PreparedStatement insertPreparedStatement = null;
insertPreparedStatement = conn.prepareStatement(InsertQuery);
insertPreparedStatement.setLong(COMMON_NUMBER_1, key);
Blob blob = new SerialBlob(pPulsesRQ.toByteArray());
insertPreparedStatement.setBlob(COMMON_NUMBER_2, blob);
insertPreparedStatement.setString(COMMON_NUMBER_3, BPULSE_STATUS_PENDING);
insertPreparedStatement.executeUpdate();
conn.commit();
insertPreparedStatement.close();
conn.close();
insertedRecords++;
this.insertTimeMillisAverage = this.insertTimeMillisAverage + (Calendar.getInstance().getTimeInMillis() - initTime);
} catch (SQLException e) {
logger.error("FAILED TO SAVE PULSE: ", e);
throw e;
}
}
/**
* Method that performs the query from all pulse keys pending to send to BPULSE REST SERVICE.
*
* @return Object[] with all pulse keys found.
*/
@Override
public synchronized Object[] getSortedbpulseRQMapKeys() throws Exception{
long initTime = Calendar.getInstance().getTimeInMillis();
Connection conn;
List<Object> resp = new ArrayList<Object>();
try {
conn = connectionPool.getConnection();
String SelectQuery = "select * from BPULSE_PULSESRQ where pulserq_status = 'P' order by pulserq_id LIMIT ?";
PreparedStatement selectPreparedStatement = conn.prepareStatement(SelectQuery);
selectPreparedStatement.setInt(COMMON_NUMBER_1, this.limitNumberPulsesToReadFromDb);
ResultSet rs = selectPreparedStatement.executeQuery();
while (rs.next()) {
resp.add(rs.getLong(COMMON_NUMBER_1));
}
rs.close();
selectPreparedStatement.close();
conn.close();
this.sortedKeysTimeMillisAverage = this.sortedKeysTimeMillisAverage + (Calendar.getInstance().getTimeInMillis() - initTime);
} catch (SQLException e) {
logger.error("FAILED TO GET THE PENDING PULSES LIST: ", e);
throw e;
}
return resp.toArray();
}
/**
* Method that performs the query from all pulse keys pending to send to BPULSE REST SERVICE.
*
* @return Object[] with all pulse keys found.
*/
@Override
public synchronized Object[] getSortedbpulseRQMapKeys(int tableIndex) throws Exception{
long initTime = Calendar.getInstance().getTimeInMillis();
Connection conn;
List<Object> resp = new ArrayList<Object>();
try {
conn = connectionPool.getConnection();
String SelectQuery = "select * from BPULSE_PULSESRQ_" + tableIndex + " where pulserq_status = 'P' order by pulserq_id LIMIT ?";
PreparedStatement selectPreparedStatement = conn.prepareStatement(SelectQuery);
selectPreparedStatement.setInt(COMMON_NUMBER_1, this.limitNumberPulsesToReadFromDb);
ResultSet rs = selectPreparedStatement.executeQuery();
while (rs.next()) {
resp.add(rs.getLong(COMMON_NUMBER_1));
}
rs.close();
selectPreparedStatement.close();
conn.close();
this.sortedKeysTimeMillisAverage = this.sortedKeysTimeMillisAverage + (Calendar.getInstance().getTimeInMillis() - initTime);
} catch (SQLException e) {
logger.error("FAILED TO GET THE PENDING PULSES LIST: ", e);
throw e;
}
return resp.toArray();
}
/**
* Method that obtains the associated pulsesRQ to the selected key from PULSESDB.
* @param pKey The pulses key.
* @return PulsesRQ The pulse to process.
*/
@Override
public synchronized PulsesRQ getBpulseRQByKey(Long pKey) throws Exception{
Connection conn;
PulsesRQ resp = null;
long initTime = Calendar.getInstance().getTimeInMillis();
try {
conn = connectionPool.getConnection();
String SelectQuery = "select * from BPULSE_PULSESRQ where pulserq_id=?";
PreparedStatement selectPreparedStatement = conn.prepareStatement(SelectQuery);
selectPreparedStatement.setLong(COMMON_NUMBER_1, pKey);
ResultSet rs = selectPreparedStatement.executeQuery();
while (rs.next()) {
Blob obj = rs.getBlob(COMMON_NUMBER_2);
resp = PulsesRQ.parseFrom(obj.getBytes(1L, (int)obj.length()));
}
rs.close();
selectPreparedStatement.close();
conn.close();
this.getTimeMillisAverage = this.getTimeMillisAverage + (Calendar.getInstance().getTimeInMillis() - initTime);
} catch (SQLException e) {
logger.error("FAILED TO GET THE PULSE BY KEY: ", e);
throw e;
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
logger.error("FAILED TO FORMAT PULSE TO PROTOBUF STRUCTURE: ", e);
throw e;
}
return resp;
}
/**
* Method that obtains the associated pulsesRQ to the selected key from PULSESDB.
* @param pKey The pulses key.
* @return PulsesRQ The pulse to process.
*/
@Override
public synchronized PulsesRQ getBpulseRQByKey(Long pKey, int tableIndex) throws Exception{
Connection conn;
PulsesRQ resp = null;
long initTime = Calendar.getInstance().getTimeInMillis();
try {
conn = connectionPool.getConnection();
String SelectQuery = "select * from BPULSE_PULSESRQ_" + tableIndex + " where pulserq_id=?";
PreparedStatement selectPreparedStatement = conn.prepareStatement(SelectQuery);
selectPreparedStatement.setLong(COMMON_NUMBER_1, pKey);
ResultSet rs = selectPreparedStatement.executeQuery();
while (rs.next()) {
Blob obj = rs.getBlob(COMMON_NUMBER_2);
resp = PulsesRQ.parseFrom(obj.getBytes(1L, (int)obj.length()));
}
rs.close();
selectPreparedStatement.close();
conn.close();
this.getTimeMillisAverage = this.getTimeMillisAverage + (Calendar.getInstance().getTimeInMillis() - initTime);
} catch (SQLException e) {
logger.error("FAILED TO GET THE PULSE BY KEY: ", e);
throw e;
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
logger.error("FAILED TO FORMAT PULSE TO PROTOBUF STRUCTURE: ", e);
throw e;
}
return resp;
}
/**
* Method that performs the deletion of the associated pulsesRQ to the selected key.
* @param pKey The pulses key.
*/
@Override
public synchronized void deleteBpulseRQByKey(Long pKey) throws Exception{
String deleteQuery = "DELETE FROM BPULSE_PULSESRQ" + " WHERE pulserq_id=?";
Connection conn;
long initTime = Calendar.getInstance().getTimeInMillis();
try {
conn = connectionPool.getConnection();
PreparedStatement deletePreparedStatement = null;
deletePreparedStatement = conn.prepareStatement(deleteQuery);
deletePreparedStatement.setLong(COMMON_NUMBER_1, pKey);
deletePreparedStatement.executeUpdate();
conn.commit();
deletePreparedStatement.close();
conn.close();
this.deleteTimeMillisAverage = this.deleteTimeMillisAverage + (Calendar.getInstance().getTimeInMillis() - initTime);
} catch (SQLException e) {
logger.error("FAILED TO DELETE PULSE: ", e);
throw e;
}
}
/**
* Method that performs the deletion of the associated pulsesRQ to the selected key.
* @param pKey The pulses key.
*/
@Override
public synchronized void truncateBpulseRQByTableIndex(int tableIndex) throws Exception{
String deleteQuery = "TRUNCATE TABLE BPULSE_PULSESRQ_" + tableIndex;
Connection conn;
long initTime = Calendar.getInstance().getTimeInMillis();
try {
conn = connectionPool.getConnection();
PreparedStatement deletePreparedStatement = null;
deletePreparedStatement = conn.prepareStatement(deleteQuery);
deletePreparedStatement.executeUpdate();
conn.commit();
deletePreparedStatement.close();
conn.close();
this.deleteTimeMillisAverage = this.deleteTimeMillisAverage + (Calendar.getInstance().getTimeInMillis() - initTime);
} catch (SQLException e) {
logger.error("FAILED TO TRUNCATE TABLE: BPULSE_PULSESRQ_" + tableIndex, e);
throw e;
}
}
/**
* Method that counts the current pulsesRQ in the PULSESDB.
* @return The pulses amount in the PULSESDB.
*/
@Override
public int countBpulsesRQ() throws Exception{
Connection conn;
int resp = COMMON_NUMBER_0;
long initTime = Calendar.getInstance().getTimeInMillis();
try {
conn = connectionPool.getConnection();
String SelectQuery = "select count(*) from BPULSE_PULSESRQ";
PreparedStatement selectPreparedStatement = conn.prepareStatement(SelectQuery);
ResultSet rs = selectPreparedStatement.executeQuery();
while (rs.next()) {
resp = rs.getInt(COMMON_NUMBER_1);
}
rs.close();
selectPreparedStatement.close();
conn.close();
this.getTimeMillisAverage = this.getTimeMillisAverage + (Calendar.getInstance().getTimeInMillis() - initTime);
} catch (SQLException e) {
logger.error("FAILED TO GET THE CURRENT PULSES NUMBER IN DB: ", e);
throw e;
}
return resp;
}
/**
* Method that counts the current pulsesRQ in the PULSESDB.
* @return The pulses amount in the PULSESDB.
*/
@Override
public int countBpulsesRQ(int tableIndex) throws Exception{
Connection conn;
int resp = COMMON_NUMBER_0;
long initTime = Calendar.getInstance().getTimeInMillis();
try {
conn = connectionPool.getConnection();
String SelectQuery = "select count(*) from BPULSE_PULSESRQ_" + tableIndex;
PreparedStatement selectPreparedStatement = conn.prepareStatement(SelectQuery);
ResultSet rs = selectPreparedStatement.executeQuery();
while (rs.next()) {
resp = rs.getInt(COMMON_NUMBER_1);
}
rs.close();
selectPreparedStatement.close();
conn.close();
this.getTimeMillisAverage = this.getTimeMillisAverage + (Calendar.getInstance().getTimeInMillis() - initTime);
} catch (SQLException e) {
logger.error("FAILED TO GET THE CURRENT PULSES NUMBER IN DB: ", e);
throw e;
}
return resp;
}
/**
* Method that performs the change of the pulsesRQ State from PENDING to INPROGRESS in the PULSESDB.
* @param pKey The pulses key.
*/
@Override
public synchronized void markBpulseKeyInProgress(Long pKey) throws Exception{
String updateQuery = "UPDATE BPULSE_PULSESRQ SET pulserq_status = ? WHERE pulserq_id=?";
Connection conn;
try {
conn = connectionPool.getConnection();
PreparedStatement updatePreparedStatement = null;
updatePreparedStatement = conn.prepareStatement(updateQuery);
updatePreparedStatement.setString(COMMON_NUMBER_1, BPULSE_STATUS_INPROGRESS);
updatePreparedStatement.setLong(COMMON_NUMBER_2, pKey);
updatePreparedStatement.executeUpdate();
conn.commit();
updatePreparedStatement.close();
conn.close();
} catch (SQLException e) {
logger.error("FAILED TO UPDATE THE PULSE STATE FROM PENDING TO INPROGRESS: ", e);
throw e;
}
}
/**
* Method that performs the change of the pulsesRQ State from PENDING to INPROGRESS in the PULSESDB.
* @param pKey The pulses key.
*/
@Override
public synchronized void markBpulseTableInProgress(int tableIndex) throws Exception{
try {
bpulseTableInProgressMap.put(tableIndex, BPULSE_STATUS_INPROGRESS);
} catch (Exception e) {
logger.error("FAILED TO UPDATE THE TABLE " + tableIndex + " STATE TO INPROGRESS: ", e);
throw e;
}
}
/**
* Method that counts the number of pulses with PENDING state in the PULSESDB.
* @return The PENDING pulses amount.
*/
@Override
public int countMarkBpulseKeyInProgress() throws Exception{
Connection conn;
int resp = COMMON_NUMBER_0;
try {
conn = connectionPool.getConnection();
String SelectQuery = "select count(*) from BPULSE_PULSESRQ where pulserq_status = 'I'";
PreparedStatement selectPreparedStatement = conn.prepareStatement(SelectQuery);
ResultSet rs = selectPreparedStatement.executeQuery();
while (rs.next()) {
resp = rs.getInt(COMMON_NUMBER_1);
}
rs.close();
selectPreparedStatement.close();
conn.close();
} catch (SQLException e) {
logger.error("FAILED TO GET PULSES INPROGRESS COUNT: ", e);
throw e;
}
return resp;
}
/**
* Method that counts the number of pulses with PENDING state in the PULSESDB.
* @return The PENDING pulses amount.
*/
@Override
public int countMarkBpulseTableInProgress() throws Exception{
int resp = COMMON_NUMBER_0;
try {
resp = bpulseTableInProgressMap.size();
} catch (Exception e) {
logger.error("FAILED TO GET PULSES INPROGRESS COUNT: ", e);
throw e;
}
return resp;
}
/**
* Method that performs the change of the pulsesRQ State from INPROGRESS to PENDING in the PULSESDB.
* @param pKey The pulses key.
* @return PulsesRQ The pulse to process.
*/
@Override
public synchronized void releaseBpulseKeyInProgressByKey(Long pKey) throws Exception{
String updateQuery = "UPDATE BPULSE_PULSESRQ SET pulserq_status = ? WHERE pulserq_id=?";
Connection conn;
try {
conn = connectionPool.getConnection();
PreparedStatement updatePreparedStatement = null;
updatePreparedStatement = conn.prepareStatement(updateQuery);
updatePreparedStatement.setString(COMMON_NUMBER_1, BPULSE_STATUS_PENDING);
updatePreparedStatement.setLong(COMMON_NUMBER_2, pKey);
updatePreparedStatement.executeUpdate();
conn.commit();
updatePreparedStatement.close();
conn.close();
} catch (SQLException e) {
logger.error("FAILED TO UPDATE THE PULSE STATE FROM INPROGRESS TO PENDING: ", e);
throw e;
}
}
/**
* Method that performs the change of the pulsesRQ State from INPROGRESS to PENDING in the PULSESDB.
* @param pKey The pulses key.
* @return PulsesRQ The pulse to process.
*/
@Override
public synchronized void releaseBpulseTableInProgress(int tableIndex) throws Exception{
try {
if(!bpulseTableInProgressMap.isEmpty()) {
bpulseTableInProgressMap.remove(tableIndex);
}
} catch (Exception e) {
logger.error("FAILED TO RELEASE THE TABLE " + tableIndex, e);
throw e;
}
}
public boolean isAvailableBpulseTable(int tableIndex) throws Exception{
boolean resp = true;
try {
if(!bpulseTableInProgressMap.isEmpty() && bpulseTableInProgressMap.get(tableIndex) != null) {
resp = false;
}
} catch (Exception e) {
logger.error("FAILED TO VALIDATE THE TABLE AVAILABILITY " + tableIndex, e);
throw e;
}
return resp;
}
/**
* Method that performs the change of the pulsesRQ State from INPROGRESS to PENDING for all the pulses in the PULSESDB.
*/
public void convertAllBpulseKeyInProgressToPending() throws Exception{
String updateQuery = "UPDATE BPULSE_PULSESRQ SET pulserq_status = ?";
Connection conn;
try {
conn = connectionPool.getConnection();
PreparedStatement updatePreparedStatement = null;
updatePreparedStatement = conn.prepareStatement(updateQuery);
updatePreparedStatement.setString(COMMON_NUMBER_1, BPULSE_STATUS_PENDING);
updatePreparedStatement.executeUpdate();
conn.commit();
updatePreparedStatement.close();
conn.close();
} catch (SQLException e) {
logger.error("FAILED TO MASSIVE UPDATE THE PULSES STATE FROM INPROGRESS TO PENDING: ", e);
throw e;
}
}
@Override
public int getInsertedRecords() {
return insertedRecords;
}
@Override
public long getInsertTimeMillisAverage() {
return insertTimeMillisAverage;
}
@Override
public long getDeleteTimeMillisAverage() {
return deleteTimeMillisAverage;
}
@Override
public long getGetTimeMillisAverage() {
return getTimeMillisAverage;
}
@Override
public long getSortedKeysTimeMillisAverage() {
return sortedKeysTimeMillisAverage;
}
/**
* Method that gets the current size of the PULSESDB file.
* @return The PULSESDB file size in bytes.
*/
@Override
public long getDBSize() {
return dbFile.length();
}
}
| apache-2.0 |
annomarket/java-client | library/src/main/java/com/annomarket/job/package-info.java | 74 | /**
* Classes related to job management.
*/
package com.annomarket.job;
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-cloudbuild/v1alpha1/1.31.0/com/google/api/services/cloudbuild/v1alpha1/model/ApprovalResult.java | 5505 | /*
* 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 code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudbuild.v1alpha1.model;
/**
* ApprovalResult describes the decision and associated metadata of a manual approval of a build.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Build API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class ApprovalResult extends com.google.api.client.json.GenericJson {
/**
* Output only. The time when the approval decision was made.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String approvalTime;
/**
* Output only. Email of the user that called the ApproveBuild API to approve or reject a build at
* the time that the API was called.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String approverAccount;
/**
* Optional. An optional comment for this manual approval result.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String comment;
/**
* Required. The decision of this manual approval.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String decision;
/**
* Optional. An optional URL tied to this manual approval result. This field is essentially the
* same as comment, except that it will be rendered by the UI differently. An example use case is
* a link to an external job that approved this Build.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String url;
/**
* Output only. The time when the approval decision was made.
* @return value or {@code null} for none
*/
public String getApprovalTime() {
return approvalTime;
}
/**
* Output only. The time when the approval decision was made.
* @param approvalTime approvalTime or {@code null} for none
*/
public ApprovalResult setApprovalTime(String approvalTime) {
this.approvalTime = approvalTime;
return this;
}
/**
* Output only. Email of the user that called the ApproveBuild API to approve or reject a build at
* the time that the API was called.
* @return value or {@code null} for none
*/
public java.lang.String getApproverAccount() {
return approverAccount;
}
/**
* Output only. Email of the user that called the ApproveBuild API to approve or reject a build at
* the time that the API was called.
* @param approverAccount approverAccount or {@code null} for none
*/
public ApprovalResult setApproverAccount(java.lang.String approverAccount) {
this.approverAccount = approverAccount;
return this;
}
/**
* Optional. An optional comment for this manual approval result.
* @return value or {@code null} for none
*/
public java.lang.String getComment() {
return comment;
}
/**
* Optional. An optional comment for this manual approval result.
* @param comment comment or {@code null} for none
*/
public ApprovalResult setComment(java.lang.String comment) {
this.comment = comment;
return this;
}
/**
* Required. The decision of this manual approval.
* @return value or {@code null} for none
*/
public java.lang.String getDecision() {
return decision;
}
/**
* Required. The decision of this manual approval.
* @param decision decision or {@code null} for none
*/
public ApprovalResult setDecision(java.lang.String decision) {
this.decision = decision;
return this;
}
/**
* Optional. An optional URL tied to this manual approval result. This field is essentially the
* same as comment, except that it will be rendered by the UI differently. An example use case is
* a link to an external job that approved this Build.
* @return value or {@code null} for none
*/
public java.lang.String getUrl() {
return url;
}
/**
* Optional. An optional URL tied to this manual approval result. This field is essentially the
* same as comment, except that it will be rendered by the UI differently. An example use case is
* a link to an external job that approved this Build.
* @param url url or {@code null} for none
*/
public ApprovalResult setUrl(java.lang.String url) {
this.url = url;
return this;
}
@Override
public ApprovalResult set(String fieldName, Object value) {
return (ApprovalResult) super.set(fieldName, value);
}
@Override
public ApprovalResult clone() {
return (ApprovalResult) super.clone();
}
}
| apache-2.0 |
duracloud/management-console | account-management-app/src/test/java/org/duracloud/account/app/controller/UserControllerTest.java | 17113 | /*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://duracloud.org/license/
*/
package org.duracloud.account.app.controller;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.duracloud.account.config.AmaEndpoint;
import org.duracloud.account.db.model.AccountInfo;
import org.duracloud.account.db.model.DuracloudUser;
import org.duracloud.account.db.model.UserInvitation;
import org.duracloud.account.db.util.DuracloudUserService;
import org.duracloud.account.db.util.error.AccountNotFoundException;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.web.servlet.ModelAndView;
public class UserControllerTest extends AmaControllerTestBase {
private UserController userController;
@Before
public void before() throws Exception {
super.before();
setupGenericAccountAndUserServiceMocks(TEST_ACCOUNT_ID);
userController = new UserController();
userController.setUserService(userService);
userController.setAccountManagerService(accountManagerService);
}
@Test
public void testGetNewForm() {
HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
HttpSession session = EasyMock.createMock(HttpSession.class);
EasyMock.expect(session.getAttribute("redemptionCode"))
.andReturn(null)
.anyTimes();
EasyMock.expect(request.getSession()).andReturn(session).anyTimes();
replayMocks();
EasyMock.replay(request, session);
ModelAndView mv = userController.getNewForm(request);
Assert.assertEquals(UserController.NEW_USER_VIEW, mv.getViewName());
Map<String, Object> map = mv.getModel();
Assert.assertNotNull(map);
Assert.assertTrue(map.containsKey(UserController.NEW_USER_FORM_KEY));
Object obj = map.get(UserController.NEW_USER_FORM_KEY);
Assert.assertNotNull(obj);
Assert.assertTrue(obj instanceof NewUserForm);
EasyMock.verify(request, session);
}
@Test
public void testGetForgotPasswordForm() {
replayMocks();
ModelAndView mv = userController.getForgotPasswordForm(null);
Assert.assertEquals(UserController.FORGOT_PASSWORD_VIEW,
mv.getViewName());
Map<String, Object> map = mv.getModel();
Assert.assertNotNull(map);
Assert.assertTrue(map.containsKey(UserController.FORGOT_PASSWORD_FORM_KEY));
Object obj = map.get(UserController.FORGOT_PASSWORD_FORM_KEY);
Assert.assertNotNull(obj);
Assert.assertTrue(obj instanceof ForgotPasswordForm);
}
@Test
public void testGetChangePasswordForm() throws Exception {
replayMocks();
String view = userController.changePassword(TEST_USERNAME, model);
Assert.assertEquals(UserController.CHANGE_PASSWORD_VIEW, view);
Map<String, Object> map = model.asMap();
Assert.assertNotNull(map);
Assert.assertTrue(map.containsKey(UserController.CHANGE_PASSWORD_FORM_KEY));
Assert.assertTrue(map.containsKey(UserController.USER_KEY));
Object obj = map.get(UserController.CHANGE_PASSWORD_FORM_KEY);
Assert.assertNotNull(obj);
Assert.assertTrue(obj instanceof ChangePasswordForm);
obj = map.get(UserController.USER_KEY);
Assert.assertNotNull(obj);
Assert.assertTrue(obj instanceof DuracloudUser);
}
@Test
public void testGetUser() throws Exception {
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpSession session = createMock(HttpSession.class);
EasyMock.expect(session.getAttribute("redemptionCode"))
.andReturn(null)
.anyTimes();
EasyMock.expect(request.getSession()).andReturn(session).anyTimes();
DuracloudUser u = createUser();
EasyMock.expect(userService.loadDuracloudUserByUsernameInternal(TEST_USERNAME))
.andReturn(u)
.anyTimes();
Set<AccountInfo> accounts = createAccountSet();
EasyMock.expect(accountManagerService.findAccountsByUserId(u.getId()))
.andReturn(accounts);
AmaEndpoint endpoint = EasyMock.createMock(AmaEndpoint.class);
EasyMock.expect(endpoint.getDomain()).andReturn("test");
userController.setAmaEndpoint(endpoint);
replayMocks();
ModelAndView mv = userController.getUser(TEST_USERNAME, request);
Assert.assertEquals(UserController.USER_ACCOUNTS, mv.getViewName());
Map<String, Object> map = mv.getModel();
Assert.assertNotNull(map);
Assert.assertTrue(map.containsKey(UserController.USER_KEY));
Object obj = map.get(UserController.USER_KEY);
Assert.assertNotNull(obj);
Assert.assertTrue(obj instanceof DuracloudUser);
obj = map.get("activeAccounts");
Assert.assertNotNull(obj);
Assert.assertTrue(obj instanceof List);
obj = map.get("pendingAccounts");
Assert.assertNotNull(obj);
Assert.assertTrue(obj instanceof List);
obj = map.get("inactiveAccounts");
Assert.assertNotNull(obj);
Assert.assertTrue(obj instanceof List);
}
private Set<AccountInfo> createAccountSet() {
Set<AccountInfo> s = new HashSet<AccountInfo>();
s.add(createAccountInfo());
return s;
}
@Test
public void testUpdateUser() throws Exception {
initializeMockUserServiceStoreUser();
UserProfileEditForm editForm = createMock(UserProfileEditForm.class);
setupNoBindingResultErrors();
EasyMock.expect(editForm.getFirstName()).andReturn("").anyTimes();
EasyMock.expect(editForm.getLastName()).andReturn("").anyTimes();
EasyMock.expect(editForm.getEmail()).andReturn("").anyTimes();
EasyMock.expect(editForm.getAllowableIPAddressRange()).andReturn("").anyTimes();
EasyMock.expect(editForm.getSecurityQuestion())
.andReturn("")
.anyTimes();
EasyMock.expect(editForm.getSecurityAnswer()).andReturn("").anyTimes();
replayMocks();
ModelAndView mav = userController.update(TEST_USERNAME,
editForm,
result,
null);
Assert.assertNotNull(mav);
}
@Test
public void testUpdateUserErrors() throws Exception {
setupHasBindingResultErrors(true);
replayMocks();
ModelAndView mav = userController.update(TEST_USERNAME,
null,
result,
new ExtendedModelMap());
Assert.assertNotNull(mav);
Assert.assertEquals(UserController.USER_EDIT_VIEW, mav.getViewName());
}
@Test
public void testAddUser() throws Exception {
EasyMock.expect(userService.createNewUser(EasyMock.isA(String.class),
EasyMock.isA(String.class),
EasyMock.isA(String.class),
EasyMock.isA(String.class),
EasyMock.isA(String.class),
EasyMock.isA(String.class),
EasyMock.isA(String.class)))
.andReturn(createUser())
.anyTimes();
NewUserForm newUserForm = createMock(NewUserForm.class);
setupNoBindingResultErrors();
EasyMock.expect(newUserForm.getUsername())
.andReturn(TEST_USERNAME)
.anyTimes();
EasyMock.expect(newUserForm.getPassword()).andReturn("").anyTimes();
EasyMock.expect(newUserForm.getFirstName()).andReturn("").anyTimes();
EasyMock.expect(newUserForm.getLastName()).andReturn("").anyTimes();
EasyMock.expect(newUserForm.getEmail()).andReturn("").anyTimes();
EasyMock.expect(newUserForm.getSecurityQuestion())
.andReturn("")
.anyTimes();
EasyMock.expect(newUserForm.getSecurityAnswer())
.andReturn("")
.anyTimes();
EasyMock.expect(newUserForm.getRedemptionCode())
.andReturn("")
.anyTimes();
replayMocks();
ModelAndView mav = userController.add(newUserForm, result, null, null);
Assert.assertNotNull(mav);
}
@Test
public void testAddUserErrors() throws Exception {
setupHasBindingResultErrors(true);
replayMocks();
ModelAndView mav = userController.add(null, result, model, null);
Assert.assertNotNull(mav);
Assert.assertEquals(UserController.NEW_USER_VIEW, mav.getViewName());
}
@Test
public void testForgotPassword() throws Exception {
initializeForgotPasswordMockUserService();
ForgotPasswordForm forgotPasswordForm = createMock(ForgotPasswordForm.class);
setupNoBindingResultErrors();
EasyMock.expect(forgotPasswordForm.getUsername())
.andReturn(TEST_USERNAME)
.anyTimes();
EasyMock.expect(forgotPasswordForm.getSecurityQuestion())
.andReturn("question")
.anyTimes();
forgotPasswordForm.setSecurityQuestion(EasyMock.isA(String.class));
EasyMock.expectLastCall().anyTimes();
EasyMock.expect(forgotPasswordForm.getSecurityAnswer())
.andReturn("answer")
.anyTimes();
replayMocks();
String view = userController.forgotPassword(forgotPasswordForm,
result,
model,
null);
Assert.assertNotNull(view);
Assert.assertEquals(UserController.FORGOT_PASSWORD_SUCCESS_VIEW, view);
}
@Test
public void testChangePassword() throws Exception {
initializeChangePasswordMockUserService();
ChangePasswordForm cbangePasswordForm = createMock(ChangePasswordForm.class);
setupNoBindingResultErrors();
EasyMock.expect(cbangePasswordForm.getOldPassword())
.andReturn("")
.anyTimes();
EasyMock.expect(cbangePasswordForm.getPassword())
.andReturn("")
.anyTimes();
replayMocks();
ModelAndView mav = userController.changePassword(TEST_USERNAME,
cbangePasswordForm,
result,
null);
Assert.assertNotNull(mav);
}
@Test
public void testAnonymousChangePassword() throws Exception {
ChangePasswordForm cbangePasswordForm = createMock(ChangePasswordForm.class);
setupNoBindingResultErrors();
EasyMock.expect(cbangePasswordForm.getOldPassword())
.andReturn("")
.anyTimes();
EasyMock.expect(cbangePasswordForm.getPassword())
.andReturn("")
.anyTimes();
userService = EasyMock.createMock(DuracloudUserService.class);
EasyMock.expect(userService.loadDuracloudUserByUsernameInternal(EasyMock.isA(String.class)))
.andReturn(createUser())
.anyTimes();
userService.changePasswordInternal(EasyMock.anyLong(),
EasyMock.isA(String.class),
EasyMock.anyBoolean(),
EasyMock.isA(String.class));
EasyMock.expectLastCall();
userService.redeemPasswordChangeRequest(EasyMock.anyLong(), EasyMock.isA(String.class));
EasyMock.expectLastCall();
EasyMock.expect(userService.retrievePassordChangeInvitation(EasyMock.isA(String.class)))
.andReturn(new UserInvitation(1L, createAccountInfo(-1L), "n/a", "n/a", "n/a",
"n/a", "username", "email", 1, "aaa"));
AmaEndpoint endpoint = EasyMock.createMock(AmaEndpoint.class);
EasyMock.expect(endpoint.getUrl()).andReturn("test");
EasyMock.replay(userService);
userController.setUserService(userService);
userController.setAmaEndpoint(endpoint);
replayMocks();
String view = userController.anonymousPasswordChange("ABC",
cbangePasswordForm,
result,
model);
Assert.assertNotNull(view);
}
@Test
public void testForgotPasswordErrors() throws Exception {
setupHasBindingResultErrors(true);
ForgotPasswordForm form = new ForgotPasswordForm();
form.setUsername(TEST_USERNAME);
replayMocks();
String view = userController.forgotPassword(form,
result,
model,
null);
Assert.assertNotNull(view);
Assert.assertEquals(UserController.FORGOT_PASSWORD_VIEW, view);
}
@Test
public void testChangePasswordErrors() throws Exception {
setupHasBindingResultErrors(true);
replayMocks();
ModelAndView mav = userController.changePassword(TEST_USERNAME,
null,
result,
model);
Assert.assertNotNull(mav);
Assert.assertEquals(UserController.USER_EDIT_VIEW, mav.getViewName());
Map<String, Object> map = model.asMap();
Assert.assertNotNull(map);
Assert.assertTrue(map.containsKey(UserController.USER_KEY));
Object obj = map.get(UserController.USER_KEY);
Assert.assertNotNull(obj);
Assert.assertTrue(obj instanceof DuracloudUser);
}
private void initializeMockUserServiceStoreUser() throws Exception {
userService.storeUserDetails(EasyMock.anyLong(),
EasyMock.isA(String.class),
EasyMock.isA(String.class),
EasyMock.isA(String.class),
EasyMock.isA(String.class),
EasyMock.isA(String.class),
EasyMock.isA(String.class));
EasyMock.expectLastCall().anyTimes();
}
private void initializeForgotPasswordMockUserService() throws Exception {
userService.forgotPassword(EasyMock.eq(TEST_USERNAME),
EasyMock.isA(String.class),
EasyMock.isA(String.class));
EasyMock.expectLastCall().anyTimes();
EasyMock.expect(userService.loadDuracloudUserByUsernameInternal(TEST_USERNAME))
.andReturn(createUser())
.anyTimes();
}
private void initializeChangePasswordMockUserService() throws Exception {
userService = EasyMock.createMock(DuracloudUserService.class);
EasyMock.expect(userService.loadDuracloudUserByUsername(TEST_USERNAME))
.andReturn(createUser())
.anyTimes();
userService.changePassword(EasyMock.anyLong(),
EasyMock.isA(String.class),
EasyMock.anyBoolean(),
EasyMock.isA(String.class));
EasyMock.expectLastCall().anyTimes();
EasyMock.replay(userService);
userController.setUserService(userService);
}
protected void setupAccountManagerService() throws AccountNotFoundException {
Set set = EasyMock.createMock(Set.class);
Iterator iterator = EasyMock.createMock(Iterator.class);
EasyMock.expect(iterator.hasNext()).andReturn(false).anyTimes();
EasyMock.expect(set.iterator()).andReturn(iterator).anyTimes();
EasyMock.expect(accountManagerService.findAccountsByUserId(EasyMock.anyLong()))
.andReturn(set)
.anyTimes();
EasyMock.replay(accountManagerService, set, iterator);
}
}
| apache-2.0 |
itohro/reladomo | reladomo/src/main/java/com/gs/fw/common/mithra/finder/charop/CharEqOperation.java | 4102 | /*
Copyright 2016 Goldman Sachs.
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.gs.fw.common.mithra.finder.charop;
import com.gs.fw.common.mithra.attribute.CharAttribute;
import com.gs.fw.common.mithra.extractor.CharExtractor;
import com.gs.fw.common.mithra.extractor.Extractor;
import com.gs.fw.common.mithra.extractor.OperationParameterExtractor;
import com.gs.fw.common.mithra.finder.AtomicEqualityOperation;
import com.gs.fw.common.mithra.finder.SqlParameterSetter;
import com.gs.fw.common.mithra.finder.SqlQuery;
import com.gs.fw.common.mithra.util.HashUtil;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
public class CharEqOperation extends AtomicEqualityOperation implements SqlParameterSetter
{
private char parameter;
public CharEqOperation(CharAttribute attribute, char parameter)
{
super(attribute);
this.parameter = parameter;
}
protected Boolean matchesWithoutDeleteCheck(Object o)
{
CharAttribute charAttribute = (CharAttribute)this.getAttribute();
if (charAttribute.isAttributeNull(o)) return false;
return charAttribute.charValueOf(o) == parameter;
}
protected List getByIndex()
{
return this.getCache().get(this.getIndexRef(), parameter);
}
public int setSqlParameters(PreparedStatement pstmt, int startIndex, SqlQuery query) throws SQLException
{
pstmt.setString(startIndex, new String(new char[] { parameter} ));
return 1;
}
public int hashCode()
{
return this.getAttribute().hashCode() ^ this.parameter;
}
public boolean equals(Object obj)
{
if (obj == this) return true;
if (obj instanceof CharEqOperation)
{
CharEqOperation other = (CharEqOperation) obj;
return this.parameter == other.parameter && this.getAttribute().equals(other.getAttribute());
}
return false;
}
@Override
public int getParameterHashCode()
{
return HashUtil.hash(this.parameter);
}
public Object getParameterAsObject()
{
return new Character(this.parameter);
}
@Override
public boolean parameterValueEquals(Object other, Extractor extractor)
{
if (extractor.isAttributeNull(other)) return false;
return ((CharExtractor) extractor).charValueOf(other) == this.parameter;
}
public char getParameter()
{
return parameter;
}
public Extractor getParameterExtractor()
{
return new ParameterExtractor();
}
protected class ParameterExtractor extends OperationParameterExtractor implements CharExtractor
{
public char charValueOf(Object o)
{
return getParameter();
}
public Object valueOf(Object o)
{
return new Character(this.charValueOf(o));
}
public int valueHashCode(Object o)
{
return HashUtil.hash(this.charValueOf(o));
}
public boolean valueEquals(Object first, Object second)
{
return this.charValueOf(first) == this.charValueOf(second);
}
public boolean valueEquals(Object first, Object second, Extractor secondExtractor)
{
if (secondExtractor.isAttributeNull(second)) return false;
return ((CharExtractor) secondExtractor).charValueOf(second) == this.charValueOf(first);
}
}
}
| apache-2.0 |
Pyknic/CodeGen | src/main/java/com/speedment/common/codegen/internal/model/EnumImpl.java | 3066 | /**
*
* Copyright (c) 2006-2017, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.common.codegen.internal.model;
import com.speedment.common.codegen.internal.util.Copier;
import com.speedment.common.codegen.model.Constructor;
import com.speedment.common.codegen.model.Enum;
import com.speedment.common.codegen.model.EnumConstant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* This is the default implementation of the {@link Enum} interface.
* This class should not be instantiated directly. Instead you should call the
* {@link Enum#of(String)} method to get an instance. In that way,
* you can layer change the implementing class without modifying the using code.
*
* @author Emil Forslund
* @see Enum
*/
public final class EnumImpl extends ClassOrInterfaceImpl<Enum> implements Enum {
private final List<EnumConstant> constants;
private final List<Constructor> constructors;
/**
* Initializes this enum using a name.
* <p>
* <b>Warning!</b> This class should not be instantiated directly but using
* the {@link Enum#of(String)} method!
*
* @param name the name
*/
public EnumImpl(String name) {
super(name);
constants = new ArrayList<>();
constructors = new ArrayList<>();
}
/**
* Copy constructor.
*
* @param prototype the prototype
*/
protected EnumImpl(Enum prototype) {
super (prototype);
constants = Copier.copy(prototype.getConstants());
constructors = Copier.copy(prototype.getConstructors());
}
@Override
public List<EnumConstant> getConstants() {
return constants;
}
@Override
public List<Constructor> getConstructors() {
return constructors;
}
@Override
public EnumImpl copy() {
return new EnumImpl(this);
}
@Override
public int hashCode() {
int hash = 5;
hash = 13 * hash + Objects.hashCode(this.constants);
hash = 13 * hash + Objects.hashCode(this.constructors);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final EnumImpl other = (EnumImpl) obj;
if (!Objects.equals(this.constants, other.constants)) {
return false;
}
return Objects.equals(this.constructors, other.constructors);
}
} | apache-2.0 |
mbenson/therian | core/src/test/java/therian/operator/convert/ELCoercionConverterTest.java | 2736 | /*
* Copyright 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 therian.operator.convert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import therian.TherianModule;
import therian.operation.Convert;
import therian.operator.OperatorTest;
import therian.testfixture.MetasyntacticVariable;
import therian.util.Positions;
public class ELCoercionConverterTest extends OperatorTest {
@Override
protected TherianModule[] modules() {
return new TherianModule[] { TherianModule.create().withOperators(new ELCoercionConverter.HandlesNoop()) };
}
@Test
public void testCoerciontoString() {
assertEquals("666", therianContext.eval(Convert.to(String.class, Positions.readOnly(Integer.valueOf(666)))));
}
@Test
public void testCoerciontoEnum() {
assertNull(therianContext.eval(Convert.to(MetasyntacticVariable.class, Positions.readOnly(Object.class, (Object) null))));
assertNull(therianContext.eval(Convert.to(MetasyntacticVariable.class, Positions.readOnly(""))));
assertSame(MetasyntacticVariable.FOO,
therianContext.eval(Convert.to(MetasyntacticVariable.class, Positions.readOnly("FOO"))));
}
@Test
public void testCoercionToBoolean() {
assertFalse(therianContext.eval(
Convert.<Object, Boolean> to(Boolean.class, Positions.readOnly(Object.class, (Object) null))).booleanValue());
assertFalse(therianContext.eval(Convert.<String, Boolean> to(Boolean.class, Positions.readOnly("")))
.booleanValue());
assertFalse(therianContext.eval(Convert.<String, Boolean> to(Boolean.class, Positions.readOnly("false")))
.booleanValue());
assertFalse(therianContext.eval(Convert.<String, Boolean> to(Boolean.class, Positions.readOnly("whatever")))
.booleanValue());
assertTrue(therianContext.eval(Convert.<String, Boolean> to(Boolean.class, Positions.readOnly("true")))
.booleanValue());
}
}
| apache-2.0 |
dbflute-test/dbflute-test-dbms-postgresql | src/main/java/org/docksidestage/postgresql/dbflute/bsentity/dbmeta/MemberStatusDbm.java | 13091 | package org.docksidestage.postgresql.dbflute.bsentity.dbmeta;
import java.util.List;
import java.util.Map;
import org.dbflute.Entity;
import org.dbflute.dbmeta.AbstractDBMeta;
import org.dbflute.dbmeta.info.*;
import org.dbflute.dbmeta.name.*;
import org.dbflute.dbmeta.property.PropertyGateway;
import org.dbflute.dbway.DBDef;
import org.docksidestage.postgresql.dbflute.allcommon.*;
import org.docksidestage.postgresql.dbflute.exentity.*;
/**
* The DB meta of member_status. (Singleton)
* @author DBFlute(AutoGenerator)
*/
public class MemberStatusDbm extends AbstractDBMeta {
// ===================================================================================
// Singleton
// =========
private static final MemberStatusDbm _instance = new MemberStatusDbm();
private MemberStatusDbm() {}
public static MemberStatusDbm getInstance() { return _instance; }
// ===================================================================================
// Current DBDef
// =============
public String getProjectName() { return DBCurrent.getInstance().projectName(); }
public String getProjectPrefix() { return DBCurrent.getInstance().projectPrefix(); }
public String getGenerationGapBasePrefix() { return DBCurrent.getInstance().generationGapBasePrefix(); }
public DBDef getCurrentDBDef() { return DBCurrent.getInstance().currentDBDef(); }
// ===================================================================================
// Property Gateway
// ================
// -----------------------------------------------------
// Column Property
// ---------------
protected final Map<String, PropertyGateway> _epgMap = newHashMap();
{ xsetupEpg(); }
protected void xsetupEpg() {
setupEpg(_epgMap, et -> ((MemberStatus)et).getMemberStatusCode(), (et, vl) -> {
CDef.MemberStatus cls = (CDef.MemberStatus)gcls(et, columnMemberStatusCode(), vl);
if (cls != null) {
((MemberStatus)et).setMemberStatusCodeAsMemberStatus(cls);
} else {
((MemberStatus)et).mynativeMappingMemberStatusCode((String)vl);
}
}, "memberStatusCode");
setupEpg(_epgMap, et -> ((MemberStatus)et).getMemberStatusName(), (et, vl) -> ((MemberStatus)et).setMemberStatusName((String)vl), "memberStatusName");
setupEpg(_epgMap, et -> ((MemberStatus)et).getDescription(), (et, vl) -> ((MemberStatus)et).setDescription((String)vl), "description");
setupEpg(_epgMap, et -> ((MemberStatus)et).getDisplayOrder(), (et, vl) -> ((MemberStatus)et).setDisplayOrder(cti(vl)), "displayOrder");
}
public PropertyGateway findPropertyGateway(String prop)
{ return doFindEpg(_epgMap, prop); }
// ===================================================================================
// Table Info
// ==========
protected final String _tableDbName = "member_status";
protected final String _tableDispName = "member_status";
protected final String _tablePropertyName = "memberStatus";
protected final TableSqlName _tableSqlName = new TableSqlName("member_status", _tableDbName);
{ _tableSqlName.xacceptFilter(DBFluteConfig.getInstance().getTableSqlNameFilter()); }
public String getTableDbName() { return _tableDbName; }
public String getTableDispName() { return _tableDispName; }
public String getTablePropertyName() { return _tablePropertyName; }
public TableSqlName getTableSqlName() { return _tableSqlName; }
protected final String _tableAlias = "会員ステータス";
public String getTableAlias() { return _tableAlias; }
protected final String _tableComment = "会員のステータスを示す固定的なマスタテーブル。\n業務で増えることはなく、増減するときは実装もともなうレベルの業務変更と考えられる。\n\nこういった固定的なマスタテーブルには、更新日時などの共通カラムは定義していないが、業務上そういった情報を管理する必要性が低いという理由に加え、ExampleDBとして共通カラムでER図が埋め尽くされてしまい見づらくなるという\nところで割り切っている。実業務では統一的に定義することもある。";
public String getTableComment() { return _tableComment; }
// ===================================================================================
// Column Info
// ===========
protected final ColumnInfo _columnMemberStatusCode = cci("member_status_code", "member_status_code", null, "会員ステータスコード", String.class, "memberStatusCode", null, true, false, true, "bpchar", 3, 0, null, null, false, null, "会員ステータスを識別するコード。\n固定的なデータなので、連番とか番号にはせず、\nデータを直接見たときも人が直感的にわかるように、\nこのような3桁のコード形式にしている。", null, "memberList,memberLoginList", CDef.DefMeta.MemberStatus, false);
protected final ColumnInfo _columnMemberStatusName = cci("member_status_name", "member_status_name", null, "会員ステータス名称", String.class, "memberStatusName", null, false, false, true, "varchar", 50, 0, null, null, false, null, null, null, null, null, false);
protected final ColumnInfo _columnDescription = cci("description", "description", null, "説明", String.class, "description", null, false, false, true, "varchar", 200, 0, null, null, false, null, "会員ステータスそれぞれの説明。\n気の利いた説明があるとディベロッパーがとても助かる。", null, null, null, false);
protected final ColumnInfo _columnDisplayOrder = cci("display_order", "display_order", null, "表示順", Integer.class, "displayOrder", null, false, false, true, "int4", 10, 0, null, null, false, null, "UI上のステータスの表示順を示すNO。\n並べるときは、このカラムに対して昇順のソート条件にする。", null, null, null, false);
/**
* (会員ステータスコード)member_status_code: {PK, NotNull, bpchar(3), classification=MemberStatus}
* @return The information object of specified column. (NotNull)
*/
public ColumnInfo columnMemberStatusCode() { return _columnMemberStatusCode; }
/**
* (会員ステータス名称)member_status_name: {NotNull, varchar(50)}
* @return The information object of specified column. (NotNull)
*/
public ColumnInfo columnMemberStatusName() { return _columnMemberStatusName; }
/**
* (説明)description: {NotNull, varchar(200)}
* @return The information object of specified column. (NotNull)
*/
public ColumnInfo columnDescription() { return _columnDescription; }
/**
* (表示順)display_order: {UQ, NotNull, int4(10)}
* @return The information object of specified column. (NotNull)
*/
public ColumnInfo columnDisplayOrder() { return _columnDisplayOrder; }
protected List<ColumnInfo> ccil() {
List<ColumnInfo> ls = newArrayList();
ls.add(columnMemberStatusCode());
ls.add(columnMemberStatusName());
ls.add(columnDescription());
ls.add(columnDisplayOrder());
return ls;
}
{ initializeInformationResource(); }
// ===================================================================================
// Unique Info
// ===========
// -----------------------------------------------------
// Primary Element
// ---------------
protected UniqueInfo cpui() { return hpcpui(columnMemberStatusCode()); }
public boolean hasPrimaryKey() { return true; }
public boolean hasCompoundPrimaryKey() { return false; }
// -----------------------------------------------------
// Unique Element
// --------------
public UniqueInfo uniqueOf() { return hpcui(columnDisplayOrder()); }
// ===================================================================================
// Relation Info
// =============
// cannot cache because it uses related DB meta instance while booting
// (instead, cached by super's collection)
// -----------------------------------------------------
// Foreign Property
// ----------------
// -----------------------------------------------------
// Referrer Property
// -----------------
/**
* (会員)member by member_status_code, named 'memberList'.
* @return The information object of referrer property. (NotNull)
*/
public ReferrerInfo referrerMemberList() {
Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnMemberStatusCode(), MemberDbm.getInstance().columnMemberStatusCode());
return cri("fk_member_member_status", "memberList", this, MemberDbm.getInstance(), mp, false, "memberStatus");
}
/**
* (会員ログイン)member_login by login_member_status_code, named 'memberLoginList'.
* @return The information object of referrer property. (NotNull)
*/
public ReferrerInfo referrerMemberLoginList() {
Map<ColumnInfo, ColumnInfo> mp = newLinkedHashMap(columnMemberStatusCode(), MemberLoginDbm.getInstance().columnLoginMemberStatusCode());
return cri("fk_member_login_member_status", "memberLoginList", this, MemberLoginDbm.getInstance(), mp, false, "memberStatus");
}
// ===================================================================================
// Various Info
// ============
// ===================================================================================
// Type Name
// =========
public String getEntityTypeName() { return "org.docksidestage.postgresql.dbflute.exentity.MemberStatus"; }
public String getConditionBeanTypeName() { return "org.docksidestage.postgresql.dbflute.cbean.MemberStatusCB"; }
public String getBehaviorTypeName() { return "org.docksidestage.postgresql.dbflute.exbhv.MemberStatusBhv"; }
// ===================================================================================
// Object Type
// ===========
public Class<MemberStatus> getEntityType() { return MemberStatus.class; }
// ===================================================================================
// Object Instance
// ===============
public MemberStatus newEntity() { return new MemberStatus(); }
// ===================================================================================
// Map Communication
// =================
public void acceptPrimaryKeyMap(Entity et, Map<String, ? extends Object> mp)
{ doAcceptPrimaryKeyMap((MemberStatus)et, mp); }
public void acceptAllColumnMap(Entity et, Map<String, ? extends Object> mp)
{ doAcceptAllColumnMap((MemberStatus)et, mp); }
public Map<String, Object> extractPrimaryKeyMap(Entity et) { return doExtractPrimaryKeyMap(et); }
public Map<String, Object> extractAllColumnMap(Entity et) { return doExtractAllColumnMap(et); }
}
| apache-2.0 |
FlxRobin/presto | presto-main/src/test/java/com/facebook/presto/sql/planner/TestInterpretedFilterFunction.java | 6922 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.tree.ComparisonExpression;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.Input;
import com.google.common.collect.ImmutableMap;
import org.testng.annotations.Test;
import java.util.Locale;
import static com.facebook.presto.connector.dual.DualMetadata.DUAL_METADATA_MANAGER;
import static com.facebook.presto.operator.scalar.FunctionAssertions.createExpression;
import static com.facebook.presto.spi.type.TimeZoneKey.UTC_KEY;
import static java.lang.String.format;
import static org.testng.Assert.assertEquals;
public class TestInterpretedFilterFunction
{
@Test
public void testNullLiteral()
{
assertFilter("null", false);
}
@Test
public void testBooleanLiteral()
{
assertFilter("true", true);
assertFilter("false", false);
}
@Test
public void testNotExpression()
{
assertFilter("not true", false);
assertFilter("not false", true);
assertFilter("not null", false);
}
@Test
public void testAndExpression()
{
assertFilter("true and true", true);
assertFilter("true and false", false);
assertFilter("true and null", false);
assertFilter("false and true", false);
assertFilter("false and false", false);
assertFilter("false and null", false);
assertFilter("null and true", false);
assertFilter("null and false", false);
assertFilter("null and null", false);
}
@Test
public void testORExpression()
{
assertFilter("true or true", true);
assertFilter("true or false", true);
assertFilter("true or null", true);
assertFilter("false or true", true);
assertFilter("false or false", false);
assertFilter("false or null", false);
assertFilter("null or true", true);
assertFilter("null or false", false);
assertFilter("null or null", false);
}
@Test
public void testIsNullExpression()
{
assertFilter("null is null", true);
assertFilter("42 is null", false);
}
@Test
public void testIsNotNullExpression()
{
assertFilter("42 is not null", true);
assertFilter("null is not null", false);
}
@Test
public void testComparisonExpression()
{
assertFilter("42 = 42", true);
assertFilter("42 = 42.0", true);
assertFilter("42.42 = 42.42", true);
assertFilter("'foo' = 'foo'", true);
assertFilter("42 = 87", false);
assertFilter("42 = 22.2", false);
assertFilter("42.42 = 22.2", false);
assertFilter("'foo' = 'bar'", false);
assertFilter("42 != 87", true);
assertFilter("42 != 22.2", true);
assertFilter("42.42 != 22.22", true);
assertFilter("'foo' != 'bar'", true);
assertFilter("42 != 42", false);
assertFilter("42 != 42.0", false);
assertFilter("42.42 != 42.42", false);
assertFilter("'foo' != 'foo'", false);
assertFilter("42 < 88", true);
assertFilter("42 < 88.8", true);
assertFilter("42.42 < 88.8", true);
assertFilter("'bar' < 'foo'", true);
assertFilter("88 < 42", false);
assertFilter("88 < 42.42", false);
assertFilter("88.8 < 42.42", false);
assertFilter("'foo' < 'bar'", false);
assertFilter("42 <= 88", true);
assertFilter("42 <= 88.8", true);
assertFilter("42.42 <= 88.8", true);
assertFilter("'bar' <= 'foo'", true);
assertFilter("42 <= 42", true);
assertFilter("42 <= 42.0", true);
assertFilter("42.42 <= 42.42", true);
assertFilter("'foo' <= 'foo'", true);
assertFilter("88 <= 42", false);
assertFilter("88 <= 42.42", false);
assertFilter("88.8 <= 42.42", false);
assertFilter("'foo' <= 'bar'", false);
assertFilter("88 >= 42", true);
assertFilter("88.8 >= 42.0", true);
assertFilter("88.8 >= 42.42", true);
assertFilter("'foo' >= 'bar'", true);
assertFilter("42 >= 88", false);
assertFilter("42.42 >= 88.0", false);
assertFilter("42.42 >= 88.88", false);
assertFilter("'bar' >= 'foo'", false);
assertFilter("88 >= 42", true);
assertFilter("88.8 >= 42.0", true);
assertFilter("88.8 >= 42.42", true);
assertFilter("'foo' >= 'bar'", true);
assertFilter("42 >= 42", true);
assertFilter("42 >= 42.0", true);
assertFilter("42.42 >= 42.42", true);
assertFilter("'foo' >= 'foo'", true);
assertFilter("42 >= 88", false);
assertFilter("42.42 >= 88.0", false);
assertFilter("42.42 >= 88.88", false);
assertFilter("'bar' >= 'foo'", false);
}
@Test
public void testComparisonExpressionWithNulls()
{
for (ComparisonExpression.Type type : ComparisonExpression.Type.values()) {
if (type == ComparisonExpression.Type.IS_DISTINCT_FROM) {
// IS DISTINCT FROM has different NULL semantics
continue;
}
assertFilter(format("NULL %s NULL", type.getValue()), false);
assertFilter(format("42 %s NULL", type.getValue()), false);
assertFilter(format("NULL %s 42", type.getValue()), false);
assertFilter(format("11.1 %s NULL", type.getValue()), false);
assertFilter(format("NULL %s 11.1", type.getValue()), false);
}
}
public static void assertFilter(String expression, boolean expectedValue)
{
Expression parsed = createExpression(expression, DUAL_METADATA_MANAGER, ImmutableMap.<Symbol, Type>of());
ConnectorSession session = new ConnectorSession("user", "test", "catalog", "schema", UTC_KEY, Locale.ENGLISH, null, null);
InterpretedFilterFunction filterFunction = new InterpretedFilterFunction(parsed,
ImmutableMap.<Symbol, Type>of(),
ImmutableMap.<Symbol, Input>of(),
DUAL_METADATA_MANAGER,
session
);
boolean result = filterFunction.filter();
assertEquals(result, expectedValue);
}
}
| apache-2.0 |
lujianzhao/MVPArmsCopy | arms/src/main/java/com/jess/arms/common/utils/VibrateUtil.java | 2025 | package com.jess.arms.common.utils;
import android.content.Context;
import android.os.Vibrator;
/**
* <p>All methods requires the caller to hold the permission
* {@link android.Manifest.permission#VIBRATE}.
*
* @author lujianzhao
* @date 2014-11-21
*/
public class VibrateUtil {
/**
* Vibrate constantly for the specified period of time.
* <p>This method requires the caller to hold the permission
* {@link android.Manifest.permission#VIBRATE}.
*
* @param milliseconds The number of milliseconds to vibrate.
*/
public static void vibrate(Context context, long milliseconds) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(milliseconds);
}
/**
* Vibrate with a given pattern.
* <p/>
* <p>
* Pass in an array of ints that are the durations for which to turn on or off
* the vibrator in milliseconds. The first value indicates the number of milliseconds
* to wait before turning the vibrator on. The next value indicates the number of milliseconds
* for which to keep the vibrator on before turning it off. Subsequent values alternate
* between durations in milliseconds to turn the vibrator off or to turn the vibrator on.
* </p><p>
* To cause the pattern to repeat, pass the index into the pattern array at which
* to start the repeat, or -1 to disable repeating.
* </p>
* <p>This method requires the caller to hold the permission
* {@link android.Manifest.permission#VIBRATE}.
*
* @param pattern an array of longs of times for which to turn the vibrator on or off.
* @param repeat the index into pattern at which to repeat, or -1 if
* you don't want to repeat.
*/
public static void vibrate(Context context, long[] pattern, int repeat) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, repeat);
}
}
| apache-2.0 |
davide-maestroni/jroutine | stream/src/test/java/com/github/dm/jrt/stream/transform/TransformationsTest.java | 28083 | /*
* Copyright 2016 Davide Maestroni
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.dm.jrt.stream.transform;
import com.github.dm.jrt.core.JRoutineCore;
import com.github.dm.jrt.core.builder.RoutineBuilder;
import com.github.dm.jrt.core.channel.AbortException;
import com.github.dm.jrt.core.channel.Channel;
import com.github.dm.jrt.core.common.BackoffBuilder;
import com.github.dm.jrt.core.common.RoutineException;
import com.github.dm.jrt.core.invocation.IdentityInvocation;
import com.github.dm.jrt.core.invocation.InvocationException;
import com.github.dm.jrt.core.invocation.InvocationFactory;
import com.github.dm.jrt.core.invocation.MappingInvocation;
import com.github.dm.jrt.core.invocation.TemplateInvocation;
import com.github.dm.jrt.core.routine.Routine;
import com.github.dm.jrt.core.runner.Runner;
import com.github.dm.jrt.core.runner.Runners;
import com.github.dm.jrt.function.Action;
import com.github.dm.jrt.function.BiConsumer;
import com.github.dm.jrt.function.BiFunction;
import com.github.dm.jrt.function.Function;
import com.github.dm.jrt.function.Functions;
import com.github.dm.jrt.stream.JRoutineStream;
import com.github.dm.jrt.stream.builder.StreamBuilder;
import org.assertj.core.api.Assertions;
import org.assertj.core.data.Offset;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.github.dm.jrt.core.invocation.InvocationFactory.factoryOf;
import static com.github.dm.jrt.core.util.UnitDuration.millis;
import static com.github.dm.jrt.core.util.UnitDuration.seconds;
import static com.github.dm.jrt.operator.Operators.appendAccept;
import static com.github.dm.jrt.operator.Operators.reduce;
import static com.github.dm.jrt.operator.sequence.Sequences.range;
import static com.github.dm.jrt.stream.transform.Transformations.throttle;
import static com.github.dm.jrt.stream.transform.Transformations.timeoutAfter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
/**
* Stream transformation unit tests.
* <p>
* Created by davide-maestroni on 07/07/2016.
*/
public class TransformationsTest {
private static Runner sSingleThreadRunner;
@NotNull
private static Runner getSingleThreadRunner() {
if (sSingleThreadRunner == null) {
sSingleThreadRunner = Runners.poolRunner(1);
}
return sSingleThreadRunner;
}
@Test
public void testBackoff() {
Assertions.assertThat(JRoutineStream //
.<Integer>withStream().map(appendAccept(range(1, 1000)))
.applyInvocationConfiguration()
.withRunner(getSingleThreadRunner())
.withInputBackoff(
BackoffBuilder.afterCount(2).linearDelay(seconds(10)))
.configured()
.map(Functions.<Number>identity())
.map(new Function<Number, Double>() {
public Double apply(final Number number) {
final double value = number.doubleValue();
return Math.sqrt(value);
}
})
.sync()
.map(new Function<Double, SumData>() {
public SumData apply(final Double aDouble) {
return new SumData(aDouble, 1);
}
})
.map(reduce(new BiFunction<SumData, SumData, SumData>() {
public SumData apply(final SumData data1, final SumData data2) {
return new SumData(data1.sum + data2.sum,
data1.count + data2.count);
}
}))
.map(new Function<SumData, Double>() {
public Double apply(final SumData data) {
return data.sum / data.count;
}
})
.close()
.after(seconds(3))
.next()).isCloseTo(21, Offset.offset(0.1));
Assertions.assertThat(JRoutineStream //
.<Integer>withStream().map(appendAccept(range(1, 1000)))
.applyInvocationConfiguration()
.withRunner(getSingleThreadRunner())
.withInputBackoff(
BackoffBuilder.afterCount(2).constantDelay(seconds(10)))
.configured()
.map(Functions.<Number>identity())
.map(new Function<Number, Double>() {
public Double apply(final Number number) {
final double value = number.doubleValue();
return Math.sqrt(value);
}
})
.sync()
.map(new Function<Double, SumData>() {
public SumData apply(final Double aDouble) {
return new SumData(aDouble, 1);
}
})
.map(reduce(new BiFunction<SumData, SumData, SumData>() {
public SumData apply(final SumData data1, final SumData data2) {
return new SumData(data1.sum + data2.sum,
data1.count + data2.count);
}
}))
.map(new Function<SumData, Double>() {
public Double apply(final SumData data) {
return data.sum / data.count;
}
})
.close()
.after(seconds(3))
.next()).isCloseTo(21, Offset.offset(0.1));
}
@Test
public void testConstructor() {
boolean failed = false;
try {
new Transformations();
failed = true;
} catch (final Throwable ignored) {
}
assertThat(failed).isFalse();
}
@Test
public void testDelay() {
long startTime = System.currentTimeMillis();
assertThat(JRoutineStream.withStream()
.let(Transformations.delay(1, TimeUnit.SECONDS))
.call("test")
.after(seconds(3))
.next()).isEqualTo("test");
assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(1000);
startTime = System.currentTimeMillis();
assertThat(JRoutineStream.withStream()
.let(Transformations.delay(seconds(1)))
.call("test")
.after(seconds(3))
.next()).isEqualTo("test");
assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(1000);
startTime = System.currentTimeMillis();
assertThat(JRoutineStream.withStream()
.let(Transformations.delay(1, TimeUnit.SECONDS))
.close()
.after(seconds(3))
.all()).isEmpty();
assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(1000);
startTime = System.currentTimeMillis();
assertThat(JRoutineStream.withStream()
.let(Transformations.delay(seconds(1)))
.close()
.after(seconds(3))
.all()).isEmpty();
assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(1000);
}
@Test
@SuppressWarnings("ConstantConditions")
public void testDelayNullPointerError() {
try {
Transformations.delay(1, null);
fail();
} catch (final NullPointerException ignored) {
}
}
@Test
public void testLag() {
long startTime = System.currentTimeMillis();
assertThat(JRoutineStream.withStream()
.let(Transformations.lag(1, TimeUnit.SECONDS))
.call("test")
.after(seconds(3))
.next()).isEqualTo("test");
assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(1000);
startTime = System.currentTimeMillis();
assertThat(JRoutineStream.withStream()
.let(Transformations.lag(seconds(1)))
.call("test")
.after(seconds(3))
.next()).isEqualTo("test");
assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(1000);
startTime = System.currentTimeMillis();
assertThat(JRoutineStream.withStream()
.let(Transformations.lag(1, TimeUnit.SECONDS))
.close()
.after(seconds(3))
.all()).isEmpty();
assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(1000);
startTime = System.currentTimeMillis();
assertThat(JRoutineStream.withStream()
.let(Transformations.lag(seconds(1)))
.close()
.after(seconds(3))
.all()).isEmpty();
assertThat(System.currentTimeMillis() - startTime).isGreaterThanOrEqualTo(1000);
}
@Test
@SuppressWarnings("ConstantConditions")
public void testLagNullPointerError() {
try {
Transformations.lag(1, null);
fail();
} catch (final NullPointerException ignored) {
}
}
@Test
public void testParallelSplit() {
final StreamBuilder<Integer, Long> sqr =
JRoutineStream.<Integer>withStream().map(new Function<Integer, Long>() {
public Long apply(final Integer number) {
final long value = number.longValue();
return value * value;
}
});
assertThat(JRoutineStream //
.<Integer>withStream().map(appendAccept(range(1, 3)))
.let(Transformations.<Integer, Integer, Long>parallel(2,
sqr.buildFactory()))
.close()
.after(seconds(3))
.all()).containsOnly(1L, 4L, 9L);
assertThat(JRoutineStream //
.<Integer>withStream().map(appendAccept(range(1, 3)))
.let(Transformations.<Integer, Integer, Long>parallel(2, sqr))
.close()
.after(seconds(3))
.all()).containsOnly(1L, 4L, 9L);
assertThat(JRoutineStream //
.<Integer>withStream().map(appendAccept(range(1, 3)))
.let(Transformations.<Integer, Integer, Integer>parallel(2,
JRoutineCore.with(IdentityInvocation.<Integer>factoryOf())))
.close()
.after(seconds(3))
.all()).containsOnly(1, 2, 3);
assertThat(JRoutineStream //
.<Integer>withStream().map(appendAccept(range(1, 3)))
.let(Transformations.<Integer, Integer, Long>parallelBy(
Functions.<Integer>identity(), sqr.buildFactory()))
.close()
.after(seconds(3))
.all()).containsOnly(1L, 4L, 9L);
assertThat(JRoutineStream //
.<Integer>withStream().map(appendAccept(range(1, 3)))
.let(Transformations.<Integer, Integer, Long>parallelBy(
Functions.<Integer>identity(), sqr))
.close()
.after(seconds(3))
.all()).containsOnly(1L, 4L, 9L);
assertThat(JRoutineStream //
.<Integer>withStream().map(appendAccept(range(1, 3)))
.let(Transformations.<Integer, Integer, Integer>parallelBy(
Functions.<Integer>identity(),
JRoutineCore.with(IdentityInvocation.<Integer>factoryOf())))
.close()
.after(seconds(3))
.all()).containsOnly(1, 2, 3);
}
@Test
@SuppressWarnings("ConstantConditions")
public void testParallelSplitNullPointerError() {
try {
Transformations.parallel(1, (InvocationFactory<Object, ?>) null);
fail();
} catch (final NullPointerException ignored) {
}
try {
Transformations.parallel(1, (Routine<Object, ?>) null);
fail();
} catch (final NullPointerException ignored) {
}
try {
Transformations.parallel(1, (RoutineBuilder<Object, ?>) null);
fail();
} catch (final NullPointerException ignored) {
}
try {
Transformations.parallelBy(null, JRoutineStream.withStream().buildRoutine());
fail();
} catch (final NullPointerException ignored) {
}
try {
Transformations.parallelBy(null, JRoutineStream.withStream());
fail();
} catch (final NullPointerException ignored) {
}
try {
Transformations.parallelBy(Functions.identity(), (InvocationFactory<Object, ?>) null);
fail();
} catch (final NullPointerException ignored) {
}
try {
Transformations.parallelBy(Functions.identity(), (Routine<Object, ?>) null);
fail();
} catch (final NullPointerException ignored) {
}
try {
Transformations.parallelBy(Functions.identity(), (RoutineBuilder<Object, ?>) null);
fail();
} catch (final NullPointerException ignored) {
}
}
@Test
public void testRetry() {
final AtomicInteger count1 = new AtomicInteger();
try {
JRoutineStream.<String>withStream().map(new UpperCase())
.map(factoryOf(ThrowException.class, count1))
.let(Transformations.<String, Object>retry(2))
.call("test")
.after(seconds(3))
.throwError();
fail();
} catch (final InvocationException e) {
assertThat(e.getCause()).isExactlyInstanceOf(IllegalStateException.class);
}
final AtomicInteger count2 = new AtomicInteger();
assertThat(JRoutineStream.<String>withStream().map(new UpperCase())
.map(factoryOf(ThrowException.class, count2, 1))
.let(Transformations.<String, Object>retry(1))
.call("test")
.after(seconds(3))
.all()).containsExactly("TEST");
final AtomicInteger count3 = new AtomicInteger();
try {
JRoutineStream.<String>withStream().map(new AbortInvocation())
.map(factoryOf(ThrowException.class, count3))
.let(Transformations.<String, Object>retry(2))
.call("test")
.after(seconds(3))
.throwError();
fail();
} catch (final AbortException e) {
assertThat(e.getCause()).isExactlyInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void testRetryConsumerError() {
final Channel<Object, Object> inputChannel = JRoutineCore.io().buildChannel();
final Channel<Object, Object> outputChannel = JRoutineCore.io().buildChannel();
new RetryChannelConsumer<Object, Object>(inputChannel, outputChannel, Runners.syncRunner(),
new Function<Channel<?, Object>, Channel<?, Object>>() {
public Channel<?, Object> apply(final Channel<?, Object> channel) throws Exception {
throw new NullPointerException();
}
}, new BiFunction<Integer, RoutineException, Long>() {
public Long apply(final Integer integer, final RoutineException e) {
return 0L;
}
}).run();
assertThat(inputChannel.getError()).isNotNull();
assertThat(outputChannel.getError()).isNotNull();
}
@Test
public void testRetryConsumerError2() {
final Channel<Object, Object> inputChannel = JRoutineCore.io().buildChannel();
final Channel<Object, Object> outputChannel = JRoutineCore.io().buildChannel();
new RetryChannelConsumer<Object, Object>(inputChannel, outputChannel, Runners.syncRunner(),
new Function<Channel<?, Object>, Channel<?, Object>>() {
public Channel<?, Object> apply(final Channel<?, Object> channel) {
return channel;
}
}, new BiFunction<Integer, RoutineException, Long>() {
public Long apply(final Integer integer, final RoutineException e) throws Exception {
throw new NullPointerException();
}
}).run();
inputChannel.abort(new RoutineException());
assertThat(inputChannel.getError()).isNotNull();
assertThat(outputChannel.getError()).isNotNull();
}
@Test
@SuppressWarnings("ConstantConditions")
public void testRetryNullPointerError() {
try {
Transformations.retry(1, null);
fail();
} catch (final NullPointerException ignored) {
}
try {
Transformations.retry(null);
fail();
} catch (final NullPointerException ignored) {
}
}
@Test
public void testThrottle() throws InterruptedException {
final Routine<Object, Object> routine = JRoutineStream.withStream()
.let(throttle(1))
.applyInvocationConfiguration()
.withRunner(Runners.poolRunner(1))
.configured()
.buildRoutine();
final Channel<Object, Object> channel1 = routine.call().pass("test1");
final Channel<Object, Object> channel2 = routine.call().pass("test2");
seconds(0.5).sleepAtLeast();
assertThat(channel1.close().after(seconds(1.5)).next()).isEqualTo("test1");
assertThat(channel2.close().after(seconds(1.5)).next()).isEqualTo("test2");
}
@Test
public void testThrottleAbort() throws InterruptedException {
final Routine<Object, Object> routine = JRoutineStream.withStream()
.let(throttle(1))
.applyInvocationConfiguration()
.withRunner(Runners.poolRunner(1))
.configured()
.buildRoutine();
final Channel<Object, Object> channel1 = routine.call().pass("test1");
final Channel<Object, Object> channel2 = routine.call().pass("test2");
seconds(0.5).sleepAtLeast();
assertThat(channel1.abort()).isTrue();
assertThat(channel2.close().after(seconds(1.5)).next()).isEqualTo("test2");
}
@Test
public void testTimeThrottle() {
final Routine<Object, Object> routine =
JRoutineStream.withStream().let(throttle(1, seconds(1))).buildRoutine();
final Channel<Object, Object> channel1 = routine.call("test1");
final Channel<Object, Object> channel2 = routine.call("test2");
assertThat(channel1.after(seconds(1.5)).next()).isEqualTo("test1");
assertThat(channel2.after(seconds(1.5)).next()).isEqualTo("test2");
}
@Test
public void testTimeout() {
assertThat(JRoutineStream.withStream()
.let(timeoutAfter(seconds(1)))
.call("test")
.after(seconds(1))
.all()).containsExactly("test");
final Channel<Object, Object> channel =
JRoutineStream.withStream().let(timeoutAfter(millis(1))).call().pass("test");
assertThat(channel.after(seconds(1)).getError()).isExactlyInstanceOf(
ResultTimeoutException.class);
}
@Test
public void testTryCatch() {
assertThat(JRoutineStream.<String>withStream().sync()
.map(new Function<Object, Object>() {
public Object apply(final Object o) {
throw new NullPointerException();
}
})
.let(
Transformations.<String,
Object>tryCatchAccept(
new BiConsumer<RoutineException,
Channel<Object, ?>>() {
public void accept(
final RoutineException e,
final Channel<Object, ?> channel) {
channel.pass("exception");
}
}))
.call("test")
.next()).isEqualTo("exception");
assertThat(JRoutineStream.<String>withStream().sync()
.map(new Function<Object, Object>() {
public Object apply(final Object o) {
return o;
}
})
.let(
Transformations.<String,
Object>tryCatchAccept(
new BiConsumer<RoutineException,
Channel<Object, ?>>() {
public void accept(
final RoutineException e,
final Channel<Object, ?> channel) {
channel.pass("exception");
}
}))
.call("test")
.next()).isEqualTo("test");
assertThat(JRoutineStream.<String>withStream().sync().map(new Function<Object, Object>() {
public Object apply(final Object o) {
throw new NullPointerException();
}
}).let(Transformations.<String, Object>tryCatch(new Function<RoutineException, Object>() {
public Object apply(final RoutineException e) {
return "exception";
}
})).call("test").next()).isEqualTo("exception");
}
@Test
@SuppressWarnings("ConstantConditions")
public void testTryCatchNullPointerError() {
try {
Transformations.tryCatchAccept(null);
fail();
} catch (final NullPointerException ignored) {
}
try {
Transformations.tryCatch(null);
fail();
} catch (final NullPointerException ignored) {
}
}
@Test
public void testTryFinally() {
final AtomicBoolean isRun = new AtomicBoolean(false);
try {
JRoutineStream.<String>withStream().sync().map(new Function<Object, Object>() {
public Object apply(final Object o) {
throw new NullPointerException();
}
}).let(Transformations.<String, Object>tryFinally(new Action() {
public void perform() {
isRun.set(true);
}
})).call("test").next();
} catch (final RoutineException ignored) {
}
assertThat(isRun.getAndSet(false)).isTrue();
assertThat(JRoutineStream.<String>withStream().sync().map(new Function<Object, Object>() {
public Object apply(final Object o) {
return o;
}
}).let(Transformations.<String, Object>tryFinally(new Action() {
public void perform() {
isRun.set(true);
}
})).call("test").next()).isEqualTo("test");
assertThat(isRun.getAndSet(false)).isTrue();
}
@Test
@SuppressWarnings("ConstantConditions")
public void testTryFinallyNullPointerError() {
try {
Transformations.tryFinally(null);
fail();
} catch (final NullPointerException ignored) {
}
}
private static class AbortInvocation extends MappingInvocation<Object, Object> {
private AbortInvocation() {
super(null);
}
public void onInput(final Object input, @NotNull final Channel<Object, ?> result) {
result.abort(new UnsupportedOperationException());
}
}
private static class SumData {
private final int count;
private final double sum;
private SumData(final double sum, final int count) {
this.sum = sum;
this.count = count;
}
}
@SuppressWarnings("unused")
private static class ThrowException extends TemplateInvocation<Object, Object> {
private final AtomicInteger mCount;
private final int mMaxCount;
private ThrowException(@NotNull final AtomicInteger count) {
this(count, Integer.MAX_VALUE);
}
private ThrowException(@NotNull final AtomicInteger count, final int maxCount) {
mCount = count;
mMaxCount = maxCount;
}
@Override
public void onInput(final Object input, @NotNull final Channel<Object, ?> result) {
if (mCount.getAndIncrement() < mMaxCount) {
throw new IllegalStateException();
}
result.pass(input);
}
}
private static class UpperCase extends MappingInvocation<String, String> {
/**
* Constructor.
*/
protected UpperCase() {
super(null);
}
public void onInput(final String input, @NotNull final Channel<String, ?> result) {
result.pass(input.toUpperCase());
}
}
}
| apache-2.0 |
PkayJava/pluggable | framework/src/main/java/com/googlecode/wickedcharts/highcharts/options/DummyOption.java | 1260 | /**
* Copyright 2012-2013 Wicked Charts (http://wicked-charts.googlecode.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.googlecode.wickedcharts.highcharts.options;
import java.io.Serializable;
/**
* This class is used to mark Highcharts feature which are not (yet) supported
* by wicked-charts. If you need this feature, please post a feature request at
* http://code.google.com/p/wicked-charts/issues/list.
* <p/>
* Do not use this class, since it's uses in the API are subject to change!
*
* @author Tom Hombergs (tom.hombergs@gmail.com)
*
*/
@Deprecated
public class DummyOption implements Serializable {
private static final long serialVersionUID = 1L;
}
| apache-2.0 |
syntelos/json | src/json/Primitive.java | 5415 | /*
* Gap Data
* Copyright (C) 2009 John Pritchard
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package json;
/**
* The gap primitive types from java lang and google datastore.
*
* <h3>Special note for Key type</h3>
*
* Instances of the Key type should be complete -- depending on the
* context -- before being stored. Stored incomplete keys have a name
* component and are retrieved for a unique value.
*
* <h3>Extensible user types</h3>
*
* User primitives include the extensible types enum and date.
*
*
* @author jdp
*/
public enum Primitive {
String(java.lang.String.class),
Boolean(java.lang.Boolean.class,java.lang.Boolean.TYPE),
Byte(java.lang.Byte.class,java.lang.Byte.TYPE),
Character(java.lang.Character.class,java.lang.Character.TYPE),
Short(java.lang.Short.class,java.lang.Short.TYPE),
Integer(java.lang.Integer.class,java.lang.Integer.TYPE),
Long(java.lang.Long.class,java.lang.Long.TYPE),
Float(java.lang.Float.class,java.lang.Float.TYPE),
Double(java.lang.Double.class,java.lang.Double.TYPE),
Date(java.util.Date.class),
Enum(java.lang.Enum.class),
BigInteger(java.math.BigInteger.class),
BigDecimal(java.math.BigDecimal.class);
public final boolean dual;
public final Class[] type;
public final String full, pkg, local;
private Primitive(Class... impl){
this.type = impl;
this.dual = (1 < impl.length);
this.full = impl[0].getName();
{
final int idx = this.full.lastIndexOf('.');
this.pkg = this.full.substring(0,idx);
this.local = this.full.substring(idx+1);
}
}
public String getName(){
return this.type[0].getName();
}
public boolean isNumber(){
switch(this){
case Byte:
case Short:
case Integer:
case Long:
case Float:
case Double:
return true;
default:
return false;
}
}
public boolean isInteger(){
switch(this){
case Byte:
case Short:
case Integer:
case Long:
return true;
default:
return false;
}
}
public boolean isAssignableFrom(Class type){
for (Class tt: this.type){
if (tt.isAssignableFrom(type))
return true;
}
return false;
}
public final static boolean Is(String name){
return (null != Primitive.For(name));
}
public final static boolean Is(Class type){
if (null != Primitive.For(type))
return true;
else if (Enum.isAssignableFrom(type))
return true;
else if (Date.isAssignableFrom(type))
return true;
else
return false;
}
public final static Primitive For(Class type){
if (null != type){
Primitive p = Primitive.Map.get(type.getName());
if (null != p)
return p;
else if (Enum.isAssignableFrom(type))
return Primitive.Enum;
else if (Date.isAssignableFrom(type))
return Primitive.Date;
}
return null;
}
public final static Primitive For(Class type, boolean isEnum){
if (isEnum)
return Primitive.Enum;
else
return Primitive.For(type);
}
public final static Primitive For(Class type, boolean isEnum, boolean isTable, boolean isCollection){
if (isEnum)
return Primitive.Enum;
else {
return Primitive.For(type);
}
}
public final static Primitive For(String name){
Primitive type = Primitive.Map.get(name);
if (null != type)
return type;
else {
try {
return Primitive.valueOf(name);
}
catch (IllegalArgumentException exc){
return null;
}
}
}
public final static Primitive For(String name, Class type){
if (null != type)
return Primitive.For(type);
else
return Primitive.For(name);
}
/*
* Primitive type map
*/
private final static java.util.Map<String,Primitive> Map = new java.util.HashMap<String,Primitive>();
static {
for (Primitive type : Primitive.values()){
for (Class clas: type.type){
final String name = clas.getName();
final String lname = name.toLowerCase();
Primitive.Map.put(name,type);
if (!lname.equals(name)){
Primitive.Map.put(lname,type);
}
}
}
}
}
| apache-2.0 |
marklogic/data-hub-in-a-box | web/src/main/java/com/marklogic/hub/web/web/AppController.java | 1192 | /*
* Copyright 2012-2019 MarkLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.marklogic.hub.web.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class AppController {
/**
* Assumes that the root URL should use a template named "index", which presumably will setup the Angular app.
*/
@RequestMapping(value = {"/", "/login", "/home", "/settings", "/jobs", "/traces/**", "/404"}, method = RequestMethod.GET)
public String index() {
return "index";
}
}
| apache-2.0 |
IHTSDO/snow-owl | core/com.b2international.snowowl.datastore/src/com/b2international/snowowl/datastore/request/job/CancelJobRequest.java | 1322 | /*
* Copyright 2017 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.datastore.request.job;
import com.b2international.snowowl.core.ServiceProvider;
import com.b2international.snowowl.core.events.Request;
import com.b2international.snowowl.datastore.remotejobs.RemoteJobTracker;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @since 5.7
*/
final class CancelJobRequest implements Request<ServiceProvider, Boolean> {
private static final long serialVersionUID = 1L;
@JsonProperty
private final String id;
CancelJobRequest(String id) {
this.id = id;
}
@Override
public Boolean execute(ServiceProvider context) {
context.service(RemoteJobTracker.class).requestCancel(id);
return Boolean.TRUE;
}
}
| apache-2.0 |
wskplho/jdroid | jdroid-android/src/main/java/com/jdroid/android/context/AndroidGitContext.java | 419 | package com.jdroid.android.context;
import com.jdroid.android.application.AbstractApplication;
import com.jdroid.java.context.GitContext;
public class AndroidGitContext implements GitContext {
@Override
public String getBranch() {
return AbstractApplication.get().getBuildConfigValue("GIT_BRANCH");
}
@Override
public String getSha() {
return AbstractApplication.get().getBuildConfigValue("GIT_SHA");
}
}
| apache-2.0 |
phlizik/netty | codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java | 32790 | /*
* 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_WINDOW_SIZE;
import static io.netty.handler.codec.http2.Http2Error.FLOW_CONTROL_ERROR;
import static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR;
import static io.netty.handler.codec.http2.Http2Exception.streamError;
import static io.netty.handler.codec.http2.Http2Stream.State.IDLE;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.Http2Stream.State;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
/**
* Basic implementation of {@link Http2RemoteFlowController}.
*/
public class DefaultHttp2RemoteFlowController implements Http2RemoteFlowController {
private final Http2StreamVisitor WRITE_ALLOCATED_BYTES = new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) {
state(stream).writeAllocatedBytes();
return true;
}
};
private final Http2Connection connection;
private final Http2Connection.PropertyKey stateKey;
private int initialWindowSize = DEFAULT_WINDOW_SIZE;
private ChannelHandlerContext ctx;
private boolean needFlush;
public DefaultHttp2RemoteFlowController(Http2Connection connection) {
this.connection = checkNotNull(connection, "connection");
// Add a flow state for the connection.
stateKey = connection.newKey();
connection.connectionStream().setProperty(stateKey,
new DefaultState(connection.connectionStream(), initialWindowSize));
// Register for notification of new streams.
connection.addListener(new Http2ConnectionAdapter() {
@Override
public void onStreamAdded(Http2Stream stream) {
// If the stream state is not open then the stream is not yet eligible for flow controlled frames and
// only requires the ReducedFlowState. Otherwise the full amount of memory is required.
stream.setProperty(stateKey, stream.state() == IDLE ?
new ReducedState(stream) :
new DefaultState(stream, 0));
}
@Override
public void onStreamActive(Http2Stream stream) {
// If the object was previously created, but later activated then we have to ensure
// the full state is allocated and the proper initialWindowSize is used.
AbstractState state = state(stream);
if (state.getClass() == DefaultState.class) {
state.window(initialWindowSize);
} else {
stream.setProperty(stateKey, new DefaultState(state, initialWindowSize));
}
}
@Override
public void onStreamClosed(Http2Stream stream) {
// Any pending frames can never be written, cancel and
// write errors for any pending frames.
AbstractState state = state(stream);
state.cancel();
// If the stream is now eligible for removal, but will persist in the priority tree then we can
// decrease the amount of memory required for this stream because no flow controlled frames can
// be exchanged on this stream
if (stream.prioritizableForTree() != 0) {
stream.setProperty(stateKey, new ReducedState(state));
}
}
@Override
public void onStreamHalfClosed(Http2Stream stream) {
if (State.HALF_CLOSED_LOCAL.equals(stream.state())) {
/**
* When this method is called there should not be any
* pending frames left if the API is used correctly. However,
* it is possible that a erroneous application can sneak
* in a frame even after having already written a frame with the
* END_STREAM flag set, as the stream state might not transition
* immediately to HALF_CLOSED_LOCAL / CLOSED due to flow control
* delaying the write.
*
* This is to cancel any such illegal writes.
*/
state(stream).cancel();
}
}
@Override
public void onPriorityTreeParentChanged(Http2Stream stream, Http2Stream oldParent) {
Http2Stream parent = stream.parent();
if (parent != null) {
int delta = state(stream).streamableBytesForTree();
if (delta != 0) {
state(parent).incrementStreamableBytesForTree(delta);
}
}
}
@Override
public void onPriorityTreeParentChanging(Http2Stream stream, Http2Stream newParent) {
Http2Stream parent = stream.parent();
if (parent != null) {
int delta = -state(stream).streamableBytesForTree();
if (delta != 0) {
state(parent).incrementStreamableBytesForTree(delta);
}
}
}
});
}
@Override
public void initialWindowSize(int newWindowSize) throws Http2Exception {
if (newWindowSize < 0) {
throw new IllegalArgumentException("Invalid initial window size: " + newWindowSize);
}
final int delta = newWindowSize - initialWindowSize;
initialWindowSize = newWindowSize;
connection.forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) throws Http2Exception {
// Verify that the maximum value is not exceeded by this change.
state(stream).incrementStreamWindow(delta);
return true;
}
});
if (delta > 0) {
// The window size increased, send any pending frames for all streams.
writePendingBytes();
}
}
@Override
public int initialWindowSize() {
return initialWindowSize;
}
@Override
public int windowSize(Http2Stream stream) {
return state(stream).windowSize();
}
@Override
public int initialWindowSize(Http2Stream stream) {
return state(stream).initialWindowSize();
}
@Override
public void incrementWindowSize(ChannelHandlerContext ctx, Http2Stream stream, int delta) throws Http2Exception {
if (stream.id() == CONNECTION_STREAM_ID) {
// Update the connection window and write any pending frames for all streams.
connectionState().incrementStreamWindow(delta);
writePendingBytes();
} else {
// Update the stream window and write any pending frames for the stream.
AbstractState state = state(stream);
state.incrementStreamWindow(delta);
state.writeBytes(state.writableWindow());
flush();
}
}
@Override
public void sendFlowControlled(ChannelHandlerContext ctx, Http2Stream stream, FlowControlled frame) {
checkNotNull(ctx, "ctx");
checkNotNull(frame, "frame");
if (this.ctx != null && this.ctx != ctx) {
throw new IllegalArgumentException("Writing data from multiple ChannelHandlerContexts is not supported");
}
// Save the context. We'll use this later when we write pending bytes.
this.ctx = ctx;
final AbstractState state;
try {
state = state(stream);
state.enqueueFrame(frame);
} catch (Throwable t) {
frame.error(t);
return;
}
state.writeBytes(state.writableWindow());
try {
flush();
} catch (Throwable t) {
frame.error(t);
}
}
/**
* For testing purposes only. Exposes the number of streamable bytes for the tree rooted at
* the given stream.
*/
int streamableBytesForTree(Http2Stream stream) {
return state(stream).streamableBytesForTree();
}
private AbstractState state(Http2Stream stream) {
return (AbstractState) checkNotNull(stream, "stream").getProperty(stateKey);
}
private AbstractState connectionState() {
return (AbstractState) connection.connectionStream().getProperty(stateKey);
}
/**
* Returns the flow control window for the entire connection.
*/
private int connectionWindowSize() {
return connectionState().windowSize();
}
/**
* Flushes the {@link ChannelHandlerContext} if we've received any data frames.
*/
private void flush() {
if (needFlush) {
ctx.flush();
needFlush = false;
}
}
/**
* Writes as many pending bytes as possible, according to stream priority.
*/
private void writePendingBytes() throws Http2Exception {
Http2Stream connectionStream = connection.connectionStream();
int connectionWindowSize = state(connectionStream).windowSize();
if (connectionWindowSize > 0) {
// Allocate the bytes for the connection window to the streams, but do not write.
allocateBytesForTree(connectionStream, connectionWindowSize);
// Now write all of the allocated bytes.
connection.forEachActiveStream(WRITE_ALLOCATED_BYTES);
flush();
}
}
/**
* This will allocate bytes by stream weight and priority for the entire tree rooted at {@code parent}, but does not
* write any bytes. The connection window is generally distributed amongst siblings according to their weight,
* however we need to ensure that the entire connection window is used (assuming streams have >= connection window
* bytes to send) and we may need some sort of rounding to accomplish this.
*
* @param parent The parent of the tree.
* @param connectionWindowSize The connection window this is available for use at this point in the tree.
* @return An object summarizing the write and allocation results.
*/
int allocateBytesForTree(Http2Stream parent, int connectionWindowSize) throws Http2Exception {
AbstractState state = state(parent);
if (state.streamableBytesForTree() <= 0) {
return 0;
}
// If the number of streamable bytes for this tree will fit in the connection window
// then there is no need to prioritize the bytes...everyone sends what they have
if (state.streamableBytesForTree() <= connectionWindowSize) {
SimpleChildFeeder childFeeder = new SimpleChildFeeder(connectionWindowSize);
parent.forEachChild(childFeeder);
return childFeeder.bytesAllocated;
}
ChildFeeder childFeeder = new ChildFeeder(parent, connectionWindowSize);
// Iterate once over all children of this parent and try to feed all the children.
parent.forEachChild(childFeeder);
// Now feed any remaining children that are still hungry until the connection
// window collapses.
childFeeder.feedHungryChildren();
return childFeeder.bytesAllocated;
}
/**
* A {@link Http2StreamVisitor} that performs the HTTP/2 priority algorithm to distribute the available connection
* window appropriately to the children of a given stream.
*/
private final class ChildFeeder implements Http2StreamVisitor {
final int maxSize;
int totalWeight;
int connectionWindow;
int nextTotalWeight;
int nextConnectionWindow;
int bytesAllocated;
Http2Stream[] stillHungry;
int nextTail;
ChildFeeder(Http2Stream parent, int connectionWindow) {
maxSize = parent.numChildren();
totalWeight = parent.totalChildWeights();
this.connectionWindow = connectionWindow;
this.nextConnectionWindow = connectionWindow;
}
@Override
public boolean visit(Http2Stream child) throws Http2Exception {
// In order to make progress toward the connection window due to possible rounding errors, we make sure
// that each stream (with data to send) is given at least 1 byte toward the connection window.
int connectionWindowChunk = max(1, (int) (connectionWindow * (child.weight() / (double) totalWeight)));
int bytesForTree = min(nextConnectionWindow, connectionWindowChunk);
AbstractState state = state(child);
int bytesForChild = min(state.streamableBytes(), bytesForTree);
// Allocate the bytes to this child.
if (bytesForChild > 0) {
state.allocate(bytesForChild);
bytesAllocated += bytesForChild;
nextConnectionWindow -= bytesForChild;
bytesForTree -= bytesForChild;
// If this subtree still wants to send then re-insert into children list and re-consider for next
// iteration. This is needed because we don't yet know if all the peers will be able to use
// all of their "fair share" of the connection window, and if they don't use it then we should
// divide their unused shared up for the peers who still want to send.
if (nextConnectionWindow > 0 && state.streamableBytesForTree() > 0) {
stillHungry(child);
nextTotalWeight += child.weight();
}
}
// Allocate any remaining bytes to the children of this stream.
if (bytesForTree > 0) {
int childBytesAllocated = allocateBytesForTree(child, bytesForTree);
bytesAllocated += childBytesAllocated;
nextConnectionWindow -= childBytesAllocated;
}
return nextConnectionWindow > 0;
}
void feedHungryChildren() throws Http2Exception {
if (stillHungry == null) {
// There are no hungry children to feed.
return;
}
totalWeight = nextTotalWeight;
connectionWindow = nextConnectionWindow;
// Loop until there are not bytes left to stream or the connection window has collapsed.
for (int tail = nextTail; tail > 0 && connectionWindow > 0;) {
nextTotalWeight = 0;
nextTail = 0;
// Iterate over the children that are currently still hungry.
for (int head = 0; head < tail && nextConnectionWindow > 0; ++head) {
if (!visit(stillHungry[head])) {
// The connection window has collapsed, break out of the loop.
break;
}
}
connectionWindow = nextConnectionWindow;
totalWeight = nextTotalWeight;
tail = nextTail;
}
}
/**
* Indicates that the given child is still hungry (i.e. still has streamable bytes that can
* fit within the current connection window).
*/
void stillHungry(Http2Stream child) {
ensureSpaceIsAllocated(nextTail);
stillHungry[nextTail++] = child;
}
/**
* Ensures that the {@link #stillHungry} array is properly sized to hold the given index.
*/
void ensureSpaceIsAllocated(int index) {
if (stillHungry == null) {
// Initial size is 1/4 the number of children. Clipping the minimum at 2, which will over allocate if
// maxSize == 1 but if this was true we shouldn't need to re-allocate because the 1 child should get
// all of the available connection window.
stillHungry = new Http2Stream[max(2, maxSize / 4)];
} else if (index == stillHungry.length) {
// Grow the array by a factor of 2.
stillHungry = Arrays.copyOf(stillHungry, min(maxSize, stillHungry.length * 2));
}
}
}
/**
* A simplified version of {@link ChildFeeder} that is only used when all streamable bytes fit within the
* available connection window.
*/
private final class SimpleChildFeeder implements Http2StreamVisitor {
int bytesAllocated;
int connectionWindow;
SimpleChildFeeder(int connectionWindow) {
this.connectionWindow = connectionWindow;
}
@Override
public boolean visit(Http2Stream child) throws Http2Exception {
AbstractState childState = state(child);
int bytesForChild = childState.streamableBytes();
if (bytesForChild > 0 || childState.hasFrame()) {
childState.allocate(bytesForChild);
bytesAllocated += bytesForChild;
connectionWindow -= bytesForChild;
}
int childBytesAllocated = allocateBytesForTree(child, connectionWindow);
bytesAllocated += childBytesAllocated;
connectionWindow -= childBytesAllocated;
return true;
}
}
/**
* The remote flow control state for a single stream.
*/
private final class DefaultState extends AbstractState {
private final Deque<FlowControlled> pendingWriteQueue;
private int window;
private int pendingBytes;
private int allocated;
// Set to true while a frame is being written, false otherwise.
private boolean writing;
// Set to true if cancel() was called.
private boolean cancelled;
DefaultState(Http2Stream stream, int initialWindowSize) {
super(stream);
window(initialWindowSize);
pendingWriteQueue = new ArrayDeque<FlowControlled>(2);
}
DefaultState(AbstractState existingState, int initialWindowSize) {
super(existingState);
window(initialWindowSize);
pendingWriteQueue = new ArrayDeque<FlowControlled>(2);
}
@Override
int windowSize() {
return window;
}
@Override
int initialWindowSize() {
return initialWindowSize;
}
@Override
void window(int initialWindowSize) {
window = initialWindowSize;
}
@Override
void allocate(int bytes) {
allocated += bytes;
// Also artificially reduce the streamable bytes for this tree to give the appearance
// that the data has been written. This will be restored before the allocated bytes are
// actually written.
incrementStreamableBytesForTree(-bytes);
}
@Override
void writeAllocatedBytes() {
int numBytes = allocated;
// Restore the number of streamable bytes to this branch.
incrementStreamableBytesForTree(allocated);
resetAllocated();
// Perform the write.
writeBytes(numBytes);
}
/**
* Reset the number of bytes that have been allocated to this stream by the priority algorithm.
*/
private void resetAllocated() {
allocated = 0;
}
@Override
int incrementStreamWindow(int delta) throws Http2Exception {
if (delta > 0 && Integer.MAX_VALUE - delta < window) {
throw streamError(stream.id(), FLOW_CONTROL_ERROR,
"Window size overflow for stream: %d", stream.id());
}
int previouslyStreamable = streamableBytes();
window += delta;
// Update this branch of the priority tree if the streamable bytes have changed for this node.
int streamableDelta = streamableBytes() - previouslyStreamable;
if (streamableDelta != 0) {
incrementStreamableBytesForTree(streamableDelta);
}
return window;
}
@Override
int writableWindow() {
return min(window, connectionWindowSize());
}
@Override
int streamableBytes() {
return max(0, min(pendingBytes - allocated, window));
}
@Override
int streamableBytesForTree() {
return streamableBytesForTree;
}
@Override
void enqueueFrame(FlowControlled frame) {
incrementPendingBytes(frame.size());
pendingWriteQueue.offer(frame);
}
@Override
boolean hasFrame() {
return !pendingWriteQueue.isEmpty();
}
/**
* Returns the the head of the pending queue, or {@code null} if empty.
*/
private FlowControlled peek() {
return pendingWriteQueue.peek();
}
@Override
void cancel() {
cancel(null);
}
/**
* Clears the pending queue and writes errors for each remaining frame.
* @param cause the {@link Throwable} that caused this method to be invoked.
*/
private void cancel(Throwable cause) {
cancelled = true;
// Ensure that the queue can't be modified while we are writing.
if (writing) {
return;
}
for (;;) {
FlowControlled frame = pendingWriteQueue.poll();
if (frame == null) {
break;
}
writeError(frame, streamError(stream.id(), INTERNAL_ERROR, cause,
"Stream closed before write could take place"));
}
}
@Override
int writeBytes(int bytes) {
int bytesAttempted = 0;
while (hasFrame()) {
int maxBytes = min(bytes - bytesAttempted, writableWindow());
bytesAttempted += write(peek(), maxBytes);
if (bytes - bytesAttempted <= 0 && !isNextFrameEmpty()) {
// The frame had data and all of it was written.
break;
}
}
return bytesAttempted;
}
/**
* @return {@code true} if there is a next frame and its size is zero.
*/
private boolean isNextFrameEmpty() {
return hasFrame() && peek().size() == 0;
}
/**
* Writes the frame and decrements the stream and connection window sizes. If the frame is in the pending
* queue, the written bytes are removed from this branch of the priority tree.
* <p>
* Note: this does not flush the {@link ChannelHandlerContext}.
* </p>
*/
private int write(FlowControlled frame, int allowedBytes) {
int before = frame.size();
int writtenBytes = 0;
// In case an exception is thrown we want to remember it and pass it to cancel(Throwable).
Throwable cause = null;
try {
assert !writing;
// Write the portion of the frame.
writing = true;
needFlush |= frame.write(max(0, allowedBytes));
if (!cancelled && frame.size() == 0) {
// This frame has been fully written, remove this frame and notify it. Since we remove this frame
// first, we're guaranteed that its error method will not be called when we call cancel.
pendingWriteQueue.remove();
frame.writeComplete();
}
} catch (Throwable t) {
// Mark the state as cancelled, we'll clear the pending queue
// via cancel() below.
cancelled = true;
cause = t;
} finally {
writing = false;
// Make sure we always decrement the flow control windows
// by the bytes written.
writtenBytes = before - frame.size();
decrementFlowControlWindow(writtenBytes);
decrementPendingBytes(writtenBytes);
// If a cancellation occurred while writing, call cancel again to
// clear and error all of the pending writes.
if (cancelled) {
cancel(cause);
}
}
return writtenBytes;
}
/**
* Increments the number of pending bytes for this node. If there was any change to the number of bytes that
* fit into the stream window, then {@link #incrementStreamableBytesForTree} is called to recursively update
* this branch of the priority tree.
*/
private void incrementPendingBytes(int numBytes) {
int previouslyStreamable = streamableBytes();
pendingBytes += numBytes;
int delta = streamableBytes() - previouslyStreamable;
if (delta != 0) {
incrementStreamableBytesForTree(delta);
}
}
/**
* If this frame is in the pending queue, decrements the number of pending bytes for the stream.
*/
private void decrementPendingBytes(int bytes) {
incrementPendingBytes(-bytes);
}
/**
* Decrement the per stream and connection flow control window by {@code bytes}.
*/
private void decrementFlowControlWindow(int bytes) {
try {
int negativeBytes = -bytes;
connectionState().incrementStreamWindow(negativeBytes);
incrementStreamWindow(negativeBytes);
} catch (Http2Exception e) {
// Should never get here since we're decrementing.
throw new IllegalStateException("Invalid window state when writing frame: " + e.getMessage(), e);
}
}
/**
* Discards this {@link FlowControlled}, writing an error. If this frame is in the pending queue,
* the unwritten bytes are removed from this branch of the priority tree.
*/
private void writeError(FlowControlled frame, Http2Exception cause) {
decrementPendingBytes(frame.size());
frame.error(cause);
}
}
/**
* The remote flow control state for a single stream that is not in a state where flow controlled frames cannot
* be exchanged.
*/
private final class ReducedState extends AbstractState {
ReducedState(Http2Stream stream) {
super(stream);
}
ReducedState(AbstractState existingState) {
super(existingState);
}
@Override
int windowSize() {
return 0;
}
@Override
int initialWindowSize() {
return 0;
}
@Override
int writableWindow() {
return 0;
}
@Override
int streamableBytes() {
return 0;
}
@Override
int streamableBytesForTree() {
return streamableBytesForTree;
}
@Override
void writeAllocatedBytes() {
throw new UnsupportedOperationException();
}
@Override
void cancel() {
}
@Override
void window(int initialWindowSize) {
throw new UnsupportedOperationException();
}
@Override
int incrementStreamWindow(int delta) throws Http2Exception {
// This operation needs to be supported during the initial settings exchange when
// the peer has not yet acknowledged this peer being activated.
return 0;
}
@Override
int writeBytes(int bytes) {
throw new UnsupportedOperationException();
}
@Override
void enqueueFrame(FlowControlled frame) {
throw new UnsupportedOperationException();
}
@Override
void allocate(int bytes) {
throw new UnsupportedOperationException();
}
@Override
boolean hasFrame() {
return false;
}
}
/**
* An abstraction which provides specific extensions used by remote flow control.
*/
private abstract class AbstractState {
protected final Http2Stream stream;
protected int streamableBytesForTree;
AbstractState(Http2Stream stream) {
this.stream = stream;
}
AbstractState(AbstractState existingState) {
this.stream = existingState.stream();
this.streamableBytesForTree = existingState.streamableBytesForTree();
}
/**
* The stream this state is associated with.
*/
final Http2Stream stream() {
return stream;
}
/**
* Recursively increments the {@link #streamableBytesForTree()} for this branch in the priority tree starting
* at the current node.
*/
final void incrementStreamableBytesForTree(int numBytes) {
streamableBytesForTree += numBytes;
if (!stream.isRoot()) {
state(stream.parent()).incrementStreamableBytesForTree(numBytes);
}
}
abstract int windowSize();
abstract int initialWindowSize();
/**
* Write bytes allocated bytes for this stream.
*/
abstract void writeAllocatedBytes();
/**
* Returns the number of pending bytes for this node that will fit within the
* {@link #writableWindow()}. This is used for the priority algorithm to determine the aggregate
* number of bytes that can be written at each node. Each node only takes into account its
* stream window so that when a change occurs to the connection window, these values need
* not change (i.e. no tree traversal is required).
*/
abstract int streamableBytes();
/**
* Get the {@link #streamableBytes()} for the entire tree rooted at this node.
*/
abstract int streamableBytesForTree();
/**
* Any operations that may be pending are cleared and the status of these operations is failed.
*/
abstract void cancel();
/**
* Reset the window size for this stream.
*/
abstract void window(int initialWindowSize);
/**
* Increments the flow control window for this stream by the given delta and returns the new value.
*/
abstract int incrementStreamWindow(int delta) throws Http2Exception;
/**
* Returns the maximum writable window (minimum of the stream and connection windows).
*/
abstract int writableWindow();
/**
* Writes up to the number of bytes from the pending queue. May write less if limited by the writable window, by
* the number of pending writes available, or because a frame does not support splitting on arbitrary
* boundaries.
*/
abstract int writeBytes(int bytes);
/**
* Adds the {@code frame} to the pending queue and increments the pending byte count.
*/
abstract void enqueueFrame(FlowControlled frame);
/**
* Increment the number of bytes allocated to this stream by the priority algorithm
*/
abstract void allocate(int bytes);
/**
* Indicates whether or not there are frames in the pending queue.
*/
abstract boolean hasFrame();
}
}
| apache-2.0 |
spring-cloud/spring-cloud-sleuth | spring-cloud-sleuth-autoconfigure/src/test/java/org/springframework/cloud/sleuth/autoconfig/NoOpPropagator.java | 1326 | /*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.sleuth.autoconfig;
import java.util.Collections;
import java.util.List;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.TraceContext;
import org.springframework.cloud.sleuth.propagation.Propagator;
/**
* A noop implementation. Does nothing.
*
* @author Marcin Grzejszczak
* @since 3.0.0
*/
class NoOpPropagator implements Propagator {
@Override
public List<String> fields() {
return Collections.emptyList();
}
@Override
public <C> void inject(TraceContext context, C carrier, Setter<C> setter) {
}
@Override
public <C> Span.Builder extract(C carrier, Getter<C> getter) {
return new NoOpSpanBuilder();
}
}
| apache-2.0 |
freeVM/freeVM | enhanced/buildtest/tests/stress/qa/src/test/stress/org/apache/harmony/test/stress/classloader/share/CorrectClasses/testManyClasses_C53.java | 1832 | /*
* 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.
*/
/**
* @author: Vera Y.Petrashkova
* @version: $revision$
*/
package org.apache.harmony.test.stress.classloader.share.CorrectClasses;
public class testManyClasses_C53 extends testManyClasses_CA {
protected static int cntClss = 0;
public static int PUBSTAT_F = 53;
protected int cntArObj;
testManyClasses_C53[] arObj;
public boolean initArObj(int cnt) {
cntArObj = -1;
arObj = new testManyClasses_C53[cnt];
for (int i = 0; i < cnt; i++) {
try {
arObj[i] = new testManyClasses_C53();
} catch (Throwable e) {
e.printStackTrace(System.out);
return false;
}
}
cntArObj = cnt;
return true;
}
public int getCntArObj() {
return cntArObj;
}
public testManyClasses_C53() {
super();
cntClss++;
}
public int getCntClss() {
return cntClss;
}
public int getPUBSTAT_F() {
return PUBSTAT_F;
}
}
| apache-2.0 |
medbounaga/CasaERP | src/main/java/com/defterp/modules/partners/entities/Partner.java | 12256 |
package com.defterp.modules.partners.entities;
import com.defterp.modules.inventory.entities.DeliveryOrder;
import com.defterp.modules.inventory.entities.DeliveryOrderLine;
import com.defterp.modules.accounting.entities.Payment;
import com.defterp.modules.accounting.entities.JournalEntry;
import com.defterp.modules.accounting.entities.JournalItem;
import com.defterp.modules.accounting.entities.Invoice;
import com.defterp.modules.accounting.entities.Account;
import com.defterp.modules.accounting.entities.InvoiceLine;
import com.defterp.modules.commonClasses.BaseEntity;
import com.defterp.modules.purchases.entities.PurchaseOrder;
import com.defterp.modules.sales.entities.SaleOrder;
import com.defterp.validators.annotations.InDateRange;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* @author MOHAMMED BOUNAGA
*
* github.com/medbounaga
*/
@Entity
@Table(name = "partner")
@NamedQueries({
@NamedQuery(name = "Partner.findAll", query = "SELECT p FROM Partner p"),
@NamedQuery(name = "Partner.findById", query = "SELECT p FROM Partner p WHERE p.id = :id"),
@NamedQuery(name = "Partner.findByName", query = "SELECT p FROM Partner p WHERE p.name = :name"),
@NamedQuery(name = "Partner.findByCity", query = "SELECT p FROM Partner p WHERE p.city = :city"),
@NamedQuery(name = "Partner.findByStreet", query = "SELECT p FROM Partner p WHERE p.street = :street"),
@NamedQuery(name = "Partner.findBySupplier", query = "SELECT p FROM Partner p WHERE p.supplier = 1"),
@NamedQuery(name = "Partner.findByActiveSupplier", query = "SELECT p FROM Partner p WHERE p.supplier = 1 AND p.active = 1"),
@NamedQuery(name = "Partner.findByCustomer", query = "SELECT p FROM Partner p WHERE p.customer = 1"),
@NamedQuery(name = "Partner.findByActiveCustomer", query = "SELECT p FROM Partner p WHERE p.customer = 1 AND p.active = 1"),
@NamedQuery(name = "Partner.findByEmail", query = "SELECT p FROM Partner p WHERE p.email = :email"),
@NamedQuery(name = "Partner.findByWebsite", query = "SELECT p FROM Partner p WHERE p.website = :website"),
@NamedQuery(name = "Partner.findByFax", query = "SELECT p FROM Partner p WHERE p.fax = :fax"),
@NamedQuery(name = "Partner.findByPhone", query = "SELECT p FROM Partner p WHERE p.phone = :phone"),
@NamedQuery(name = "Partner.findByCredit", query = "SELECT p FROM Partner p WHERE p.credit = :credit"),
@NamedQuery(name = "Partner.findByDebit", query = "SELECT p FROM Partner p WHERE p.debit = :debit"),
@NamedQuery(name = "Partner.findByMobile", query = "SELECT p FROM Partner p WHERE p.mobile = :mobile"),
@NamedQuery(name = "Partner.findByIsCompany", query = "SELECT p FROM Partner p WHERE p.isCompany = :isCompany"),
@NamedQuery(name = "Partner.findByPurchaseDeals", query = "SELECT p FROM Partner p WHERE p.purchaseDeals = :purchaseDeals"),
@NamedQuery(name = "Partner.findBySaleDeals", query = "SELECT p FROM Partner p WHERE p.saleDeals = :saleDeals"),
@NamedQuery(name = "Partner.findByActive", query = "SELECT p FROM Partner p WHERE p.active = :active")})
public class Partner extends BaseEntity {
private static final long serialVersionUID = 1L;
@Column(name = "name" , nullable = false)
@NotNull
@Size(min = 1, max = 128, message = "{LongString}")
private String name;
@Lob
@Column(name = "image")
private byte[] image;
@Size(max = 128, message = "{LongString}")
@Column(name = "city")
private String city;
@Size(max = 128, message = "{LongString}")
@Column(name = "street")
private String street;
@Column(name = "supplier")
private Boolean supplier;
@Column(name = "customer")
private Boolean customer;
@Size(max = 240, message = "{LongString}")
@Column(name = "email")
private String email;
@Size(max = 64, message = "{LongString}")
@Column(name = "website")
private String website;
@Size(max = 128, message = "{LongString}")
@Column(name = "country")
private String country;
@Basic(optional = false)
@NotNull
@Column(name = "create_date")
@InDateRange
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
@Size(max = 64, message = "{LongString}")
@Column(name = "fax")
private String fax;
@Size(max = 64, message = "{LongString}")
@Column(name = "phone")
private String phone;
@NotNull
@Column(name = "credit")
private Double credit;
@NotNull
@Column(name = "debit")
private Double debit;
@Lob
@Column(name = "image_medium")
private byte[] imageMedium;
@Size(max = 64, message = "{LongString}")
@Column(name = "mobile")
private String mobile;
@Column(name = "is_company")
private Boolean isCompany;
@Column(name = "purchase_deals")
private Integer purchaseDeals;
@Column(name = "sale_deals")
private Integer saleDeals;
@Basic(optional = false)
@NotNull
@Column(name = "active")
private Boolean active;
@JoinColumn(name = "accountReceivable_id", referencedColumnName = "id")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Account accountReceivable;
@JoinColumn(name = "accountPayable_id", referencedColumnName = "id")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Account accountPayable;
@OneToMany(mappedBy = "partner")
private List<JournalItem> journalItems;
@OneToMany(mappedBy = "partner")
private List<DeliveryOrderLine> deliveryOrderLines;
@OneToMany(mappedBy = "partner")
private List<DeliveryOrder> deliveryOrders;
@OneToMany(mappedBy = "partner")
private List<JournalEntry> journalEntries;
@OneToMany(mappedBy = "partner")
private List<InvoiceLine> invoiceLines;
@OneToMany(mappedBy = "partner")
private List<PurchaseOrder> purchaseOrderList;
@OneToMany(mappedBy = "partner")
private List<SaleOrder> saleOrders;
@OneToMany(mappedBy = "partner")
private List<Payment> payments;
@OneToMany(mappedBy = "partner")
private List<Invoice> invoices;
public Partner() {
}
public Partner(String name, Boolean active) {
this.name = name;
this.active = active;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public Boolean getSupplier() {
return supplier;
}
public void setSupplier(Boolean supplier) {
this.supplier = supplier;
}
public Boolean getCustomer() {
return customer;
}
public void setCustomer(Boolean customer) {
this.customer = customer;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Double getCredit() {
if(credit == null){
credit = 0d;
}
return credit;
}
public void setCredit(Double credit) {
this.credit = credit;
}
public Double getDebit() {
if(debit == null){
debit = 0d;
}
return debit;
}
public void setDebit(Double debit) {
this.debit = debit;
}
public byte[] getImageMedium() {
return imageMedium;
}
public void setImageMedium(byte[] imageMedium) {
this.imageMedium = imageMedium;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Boolean getIsCompany() {
return isCompany;
}
public void setIsCompany(Boolean isCompany) {
this.isCompany = isCompany;
}
public Integer getPurchaseDeals() {
return purchaseDeals;
}
public void setPurchaseDeals(Integer purchaseDeals) {
this.purchaseDeals = purchaseDeals;
}
public Integer getSaleDeals() {
return saleDeals;
}
public void setSaleDeals(Integer saleDeals) {
this.saleDeals = saleDeals;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Account getAccountReceivable() {
return accountReceivable;
}
public void setAccountReceivable(Account accountReceivable) {
this.accountReceivable = accountReceivable;
}
public Account getAccountPayable() {
return accountPayable;
}
public void setAccountPayable(Account accountPayable) {
this.accountPayable = accountPayable;
}
public List<JournalItem> getJournalItems() {
return journalItems;
}
public void setJournalItems(List<JournalItem> journalItems) {
this.journalItems = journalItems;
}
public List<DeliveryOrderLine> getDeliveryOrderLines() {
return deliveryOrderLines;
}
public void setDeliveryOrderLines(List<DeliveryOrderLine> deliveryOrderLines) {
this.deliveryOrderLines = deliveryOrderLines;
}
public List<DeliveryOrder> getDeliveryOrders() {
return deliveryOrders;
}
public void setDeliveryOrders(List<DeliveryOrder> deliveryOrders) {
this.deliveryOrders = deliveryOrders;
}
public List<JournalEntry> getJournalEntries() {
return journalEntries;
}
public void setJournalEntries(List<JournalEntry> journalEntries) {
this.journalEntries = journalEntries;
}
public List<InvoiceLine> getInvoiceLines() {
return invoiceLines;
}
public void setInvoiceLines(List<InvoiceLine> invoiceLines) {
this.invoiceLines = invoiceLines;
}
public List<PurchaseOrder> getPurchaseOrderList() {
return purchaseOrderList;
}
public void setPurchaseOrderList(List<PurchaseOrder> purchaseOrderList) {
this.purchaseOrderList = purchaseOrderList;
}
public List<SaleOrder> getSaleOrders() {
return saleOrders;
}
public void setSaleOrders(List<SaleOrder> saleOrders) {
this.saleOrders = saleOrders;
}
public List<Payment> getPayments() {
return payments;
}
public void setPayments(List<Payment> payments) {
this.payments = payments;
}
public List<Invoice> getInvoices() {
return invoices;
}
public void setInvoices(List<Invoice> invoices) {
this.invoices = invoices;
}
@Override
public String toString() {
return "--- Partner[ id=" + super.getId() + " ] ---";
}
}
| apache-2.0 |
juhalindfors/bazel-patches | src/main/java/com/google/devtools/build/lib/rules/android/AndroidLibrary.java | 13866 | // Copyright 2015 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.devtools.build.lib.rules.android;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.OutputGroupProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.config.CompilationMode;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.rules.RuleConfiguredTargetFactory;
import com.google.devtools.build.lib.rules.android.AndroidLibraryAarProvider.Aar;
import com.google.devtools.build.lib.rules.android.ResourceContainer.ResourceType;
import com.google.devtools.build.lib.rules.java.JavaCommon;
import com.google.devtools.build.lib.rules.java.JavaNeverlinkInfoProvider;
import com.google.devtools.build.lib.rules.java.JavaPluginInfoProvider;
import com.google.devtools.build.lib.rules.java.JavaSemantics;
import com.google.devtools.build.lib.rules.java.JavaSourceInfoProvider;
import com.google.devtools.build.lib.rules.java.JavaTargetAttributes;
import com.google.devtools.build.lib.rules.java.ProguardLibrary;
import com.google.devtools.build.lib.rules.java.ProguardSpecProvider;
/**
* An implementation for the "android_library" rule.
*/
public abstract class AndroidLibrary implements RuleConfiguredTargetFactory {
protected abstract JavaSemantics createJavaSemantics();
protected abstract AndroidSemantics createAndroidSemantics();
/**
* Checks expected rule invariants, throws rule errors if anything is set wrong.
*/
private static void validateRuleContext(RuleContext ruleContext)
throws InterruptedException, RuleErrorException {
if (ruleContext.attributes().isAttributeValueExplicitlySpecified("resources")
&& DataBinding.isEnabled(ruleContext)) {
ruleContext.throwWithRuleError("Data binding doesn't work with the \"resources\" attribute. "
+ "Use \"resource_files\" instead.");
}
}
@Override
public ConfiguredTarget create(RuleContext ruleContext)
throws InterruptedException, RuleErrorException {
validateRuleContext(ruleContext);
JavaSemantics javaSemantics = createJavaSemantics();
AndroidSemantics androidSemantics = createAndroidSemantics();
if (!AndroidSdkProvider.verifyPresence(ruleContext)) {
return null;
}
checkResourceInlining(ruleContext);
NestedSetBuilder<Aar> transitiveAars = NestedSetBuilder.naiveLinkOrder();
NestedSetBuilder<Artifact> transitiveAarArtifacts = NestedSetBuilder.stableOrder();
collectTransitiveAars(ruleContext, transitiveAars, transitiveAarArtifacts);
NestedSetBuilder<Artifact> proguardConfigsbuilder = NestedSetBuilder.stableOrder();
proguardConfigsbuilder.addTransitive(new ProguardLibrary(ruleContext).collectProguardSpecs());
AndroidIdlHelper.maybeAddSupportLibProguardConfigs(ruleContext, proguardConfigsbuilder);
NestedSet<Artifact> transitiveProguardConfigs = proguardConfigsbuilder.build();
JavaCommon javaCommon =
AndroidCommon.createJavaCommonWithAndroidDataBinding(ruleContext, javaSemantics, true);
javaSemantics.checkRule(ruleContext, javaCommon);
AndroidCommon androidCommon = new AndroidCommon(javaCommon);
boolean definesLocalResources =
LocalResourceContainer.definesAndroidResources(ruleContext.attributes());
if (definesLocalResources) {
LocalResourceContainer.validateRuleContext(ruleContext);
}
final ResourceApk resourceApk;
if (definesLocalResources) {
ApplicationManifest applicationManifest = androidSemantics.getManifestForRule(ruleContext)
.renamePackage(ruleContext, AndroidCommon.getJavaPackage(ruleContext));
resourceApk = applicationManifest.packWithDataAndResources(
null, /* resourceApk -- not needed for library */
ruleContext,
true, /* isLibrary */
ResourceDependencies.fromRuleDeps(ruleContext, JavaCommon.isNeverLink(ruleContext)),
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_R_TXT),
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_MERGED_SYMBOLS),
ResourceFilter.empty(ruleContext),
ImmutableList.<String>of(), /* uncompressedExtensions */
false, /* crunchPng */
false, /* incremental */
null, /* proguardCfgOut */
null, /* mainDexProguardCfg */
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_PROCESSED_MANIFEST),
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_ZIP),
DataBinding.isEnabled(ruleContext) ? DataBinding.getLayoutInfoFile(ruleContext) : null,
null, /* featureOf */
null /* featureAfter */);
if (ruleContext.hasErrors()) {
return null;
}
} else {
resourceApk = ResourceApk.fromTransitiveResources(
ResourceDependencies.fromRuleResourceAndDeps(ruleContext, false /* neverlink */));
}
AndroidConfiguration androidConfig = ruleContext.getFragment(AndroidConfiguration.class);
if (!androidConfig.allowSrcsLessAndroidLibraryDeps()
&& !definesLocalResources
&& ruleContext.attributes().get("srcs", BuildType.LABEL_LIST).isEmpty()
&& ruleContext.attributes().get("idl_srcs", BuildType.LABEL_LIST).isEmpty()
&& !ruleContext.attributes().get("deps", BuildType.LABEL_LIST).isEmpty()) {
ruleContext.attributeError("deps", "deps not allowed without srcs; move to exports?");
}
JavaTargetAttributes javaTargetAttributes = androidCommon.init(
javaSemantics,
androidSemantics,
resourceApk,
false /* addCoverageSupport */,
true /* collectJavaCompilationArgs */,
false /* isBinary */,
androidConfig.includeLibraryResourceJars());
if (javaTargetAttributes == null) {
return null;
}
Artifact classesJar =
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR);
Artifact aarOut = ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_LIBRARY_AAR);
final ResourceContainer primaryResources;
final Aar aar;
if (definesLocalResources) {
primaryResources = resourceApk.getPrimaryResource();
// applicationManifest has already been checked for nullness above in this method
ApplicationManifest applicationManifest = androidSemantics.getManifestForRule(ruleContext);
aar = Aar.create(aarOut, applicationManifest.getManifest());
addAarToProvider(aar, transitiveAars, transitiveAarArtifacts);
} else if (AndroidCommon.getAndroidResources(ruleContext) != null) {
primaryResources = Iterables.getOnlyElement(
AndroidCommon.getAndroidResources(ruleContext).getDirectAndroidResources());
aar = Aar.create(aarOut, primaryResources.getManifest());
addAarToProvider(aar, transitiveAars, transitiveAarArtifacts);
} else {
// there are no local resources and resources attribute was not specified either
aar = null;
ApplicationManifest applicationManifest = ApplicationManifest.generatedManifest(ruleContext)
.renamePackage(ruleContext, AndroidCommon.getJavaPackage(ruleContext));
String javaPackage = AndroidCommon.getJavaPackage(ruleContext);
ResourceContainer resourceContainer =
ResourceContainer.builder()
.setLabel(ruleContext.getLabel())
.setJavaPackageFromString(javaPackage)
.setManifest(applicationManifest.getManifest())
.setJavaSourceJar(
ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_JAVA_SOURCE_JAR))
.setManifestExported(AndroidCommon.getExportsManifest(ruleContext))
.setRTxt(ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_R_TXT))
.build();
primaryResources = new AndroidResourcesProcessorBuilder(ruleContext)
.setLibrary(true)
.setRTxtOut(resourceContainer.getRTxt())
.setManifestOut(ruleContext.getImplicitOutputArtifact(
AndroidRuleClasses.ANDROID_PROCESSED_MANIFEST))
.setSourceJarOut(resourceContainer.getJavaSourceJar())
.setJavaPackage(resourceContainer.getJavaPackage())
.withPrimary(resourceContainer)
.withDependencies(resourceApk.getResourceDependencies())
.setDebug(ruleContext.getConfiguration().getCompilationMode() != CompilationMode.OPT)
.build(ruleContext);
}
new AarGeneratorBuilder(ruleContext)
.withPrimary(primaryResources)
.withManifest(aar != null ? aar.getManifest() : primaryResources.getManifest())
.withRtxt(primaryResources.getRTxt())
.withClasses(classesJar)
.setAAROut(aarOut)
.build(ruleContext);
RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext);
androidCommon.addTransitiveInfoProviders(
builder,
androidSemantics,
aarOut,
resourceApk,
null,
ImmutableList.<Artifact>of(),
NativeLibs.EMPTY);
androidSemantics.addTransitiveInfoProviders(builder, ruleContext, javaCommon, androidCommon);
NestedSetBuilder<Artifact> transitiveResourcesJars = collectTransitiveResourceJars(ruleContext);
if (androidCommon.getResourceClassJar() != null) {
transitiveResourcesJars.add(androidCommon.getResourceClassJar());
}
builder
.addProvider(
NativeLibsZipsProvider.class,
new NativeLibsZipsProvider(
AndroidCommon.collectTransitiveNativeLibsZips(ruleContext).build()))
.add(
JavaNeverlinkInfoProvider.class,
new JavaNeverlinkInfoProvider(androidCommon.isNeverLink()))
.add(
JavaSourceInfoProvider.class,
JavaSourceInfoProvider.fromJavaTargetAttributes(javaTargetAttributes, javaSemantics))
.add(
AndroidCcLinkParamsProvider.class,
AndroidCcLinkParamsProvider.create(androidCommon.getCcLinkParamsStore()))
.add(JavaPluginInfoProvider.class, JavaCommon.getTransitivePlugins(ruleContext))
.add(ProguardSpecProvider.class, new ProguardSpecProvider(transitiveProguardConfigs))
.addOutputGroup(OutputGroupProvider.HIDDEN_TOP_LEVEL, transitiveProguardConfigs)
.add(
AndroidLibraryResourceClassJarProvider.class,
AndroidLibraryResourceClassJarProvider.create(transitiveResourcesJars.build()));
if (!JavaCommon.isNeverLink(ruleContext)) {
builder.add(
AndroidLibraryAarProvider.class,
AndroidLibraryAarProvider.create(
aar, transitiveAars.build(), transitiveAarArtifacts.build()));
}
return builder.build();
}
private void addAarToProvider(
Aar aar,
NestedSetBuilder<Aar> transitiveAars,
NestedSetBuilder<Artifact> transitiveAarArtifacts) {
transitiveAars.add(aar);
if (aar.getAar() != null) {
transitiveAarArtifacts.add(aar.getAar());
}
if (aar.getManifest() != null) {
transitiveAarArtifacts.add(aar.getManifest());
}
}
private void checkResourceInlining(RuleContext ruleContext) {
AndroidResourcesProvider resources = AndroidCommon.getAndroidResources(ruleContext);
if (resources == null) {
return;
}
ResourceContainer container = Iterables.getOnlyElement(
resources.getDirectAndroidResources());
if (container.getConstantsInlined()
&& !container.getArtifacts(ResourceType.RESOURCES).isEmpty()) {
ruleContext.ruleError("This android library has some resources assigned, so the target '"
+ resources.getLabel() + "' should have the attribute inline_constants set to 0");
}
}
private void collectTransitiveAars(
RuleContext ruleContext,
NestedSetBuilder<Aar> transitiveAars,
NestedSetBuilder<Artifact> transitiveAarArtifacts) {
for (AndroidLibraryAarProvider library : AndroidCommon.getTransitivePrerequisites(
ruleContext, Mode.TARGET, AndroidLibraryAarProvider.class)) {
transitiveAars.addTransitive(library.getTransitiveAars());
transitiveAarArtifacts.addTransitive(library.getTransitiveAarArtifacts());
}
}
private NestedSetBuilder<Artifact> collectTransitiveResourceJars(RuleContext ruleContext) {
NestedSetBuilder<Artifact> builder = NestedSetBuilder.naiveLinkOrder();
Iterable<AndroidLibraryResourceClassJarProvider> providers =
AndroidCommon.getTransitivePrerequisites(
ruleContext, Mode.TARGET, AndroidLibraryResourceClassJarProvider.class);
for (AndroidLibraryResourceClassJarProvider resourceJarProvider : providers) {
builder.addTransitive(resourceJarProvider.getResourceClassJars());
}
return builder;
}
}
| apache-2.0 |
xiaomozhang/druid | druid-1.0.9/src/test/java/com/alibaba/druid/spring/SequenceDao.java | 1557 | /*
* Copyright 1999-2011 Alibaba Group Holding Ltd.
*
* 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.alibaba.druid.spring;
import java.util.HashMap;
import java.util.Map;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
public class SequenceDao extends SqlMapClientDaoSupport implements ISequenceDao {
public boolean compareAndSet(String name, int value, int expect) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("name", name);
parameters.put("value", value);
parameters.put("expect", expect);
int updateCount = getSqlMapClientTemplate().update("Sequence.compareAndSet", parameters);
return updateCount == 1;
}
public int getValue(String name) {
return (Integer) getSqlMapClientTemplate().queryForObject("Sequence.getValue", name);
}
public int getValueForUpdate(String name) {
return (Integer) getSqlMapClientTemplate().queryForObject("Sequence.getValueForUpdate", name);
}
}
| apache-2.0 |
WaiLynnZaw/android-play-places | PlaceComplete/Application/src/main/java/com/example/android/common/activities/SampleActivityBase.java | 1643 | /*
* Copyright (C) 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.common.activities;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogWrapper;
/**
* Base launcher activity, to handle most of the common plumbing for samples.
*/
public class SampleActivityBase extends FragmentActivity {
public static final String TAG = "SampleActivityBase";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
initializeLogging();
}
/** Set up targets to receive log data */
public void initializeLogging() {
// Using Log, front-end to the logging chain, emulates android.util.log method signatures.
// Wraps Android's native log framework
LogWrapper logWrapper = new LogWrapper();
Log.setLogNode(logWrapper);
Log.i(TAG, "Ready");
}
}
| apache-2.0 |
melanj/my-spare-time-work | ActiveSplashHRM/src/java/Model/EmpEmergencyContacts.java | 3445 | package Model;
// Generated Jan 14, 2011 3:39:55 PM by Hibernate Tools 3.2.1.GA
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* EmpEmergencyContacts generated by hbm2java
*/
@Entity
@Table(name="emp_emergency_contacts"
,catalog="ashrm"
)
public class EmpEmergencyContacts implements java.io.Serializable {
private EmpEmergencyContactsId id;
private Employee employee;
private String eecName;
private String eecRelationship;
private String eecHomeNo;
private String eecMobileNo;
private String eecOfficeNo;
public EmpEmergencyContacts() {
}
public EmpEmergencyContacts(EmpEmergencyContactsId id, Employee employee) {
this.id = id;
this.employee = employee;
}
public EmpEmergencyContacts(EmpEmergencyContactsId id, Employee employee, String eecName, String eecRelationship, String eecHomeNo, String eecMobileNo, String eecOfficeNo) {
this.id = id;
this.employee = employee;
this.eecName = eecName;
this.eecRelationship = eecRelationship;
this.eecHomeNo = eecHomeNo;
this.eecMobileNo = eecMobileNo;
this.eecOfficeNo = eecOfficeNo;
}
@EmbeddedId
@AttributeOverrides( {
@AttributeOverride(name="empNumber", column=@Column(name="emp_number", nullable=false) ),
@AttributeOverride(name="eecSeqno", column=@Column(name="eec_seqno", nullable=false, precision=2, scale=0) ) } )
public EmpEmergencyContactsId getId() {
return this.id;
}
public void setId(EmpEmergencyContactsId id) {
this.id = id;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="emp_number", nullable=false, insertable=false, updatable=false)
public Employee getEmployee() {
return this.employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
@Column(name="eec_name", length=100)
public String getEecName() {
return this.eecName;
}
public void setEecName(String eecName) {
this.eecName = eecName;
}
@Column(name="eec_relationship", length=100)
public String getEecRelationship() {
return this.eecRelationship;
}
public void setEecRelationship(String eecRelationship) {
this.eecRelationship = eecRelationship;
}
@Column(name="eec_home_no", length=100)
public String getEecHomeNo() {
return this.eecHomeNo;
}
public void setEecHomeNo(String eecHomeNo) {
this.eecHomeNo = eecHomeNo;
}
@Column(name="eec_mobile_no", length=100)
public String getEecMobileNo() {
return this.eecMobileNo;
}
public void setEecMobileNo(String eecMobileNo) {
this.eecMobileNo = eecMobileNo;
}
@Column(name="eec_office_no", length=100)
public String getEecOfficeNo() {
return this.eecOfficeNo;
}
public void setEecOfficeNo(String eecOfficeNo) {
this.eecOfficeNo = eecOfficeNo;
}
}
| apache-2.0 |
ppamorim/SimpleToolbarSlider | app/src/main/java/com/simpletoolbarslider/domain/model/Happy.java | 1104 | package com.simpletoolbarslider.domain.model;
/**
* A simple model to represent an item of the list.
*/
public class Happy {
private int id;
private String title;
private String image;
public Happy(int id, String title, String image) {
this.id = id;
this.title = title;
this.image = image;
}
public String getTitle() {
return title;
}
public String getImage() {
return image;
}
/**
* Every model has your won hashCode, in this case can be used
* the id of the object to be used on a HashMap/Set.
* @return idt.of the objec.
*/
@Override public int hashCode() {
return id;
}
/**
* Verify whether the instance of the model has
* the params of the compared model.
* @param object Instance of the compared model.
* @return If item is equals or not.
*/
@Override public boolean equals(Object object) {
if (object instanceof Happy) {
Happy happy = ((Happy) object);
return (happy.title.equals(title) && happy.image.equals(image))
&& happy.hashCode() == hashCode();
}
return false;
}
}
| apache-2.0 |
wso2/security-tools | internal/scan-manager/core/src/main/java/org/wso2/security/tools/scanmanager/core/service/ScannerServiceImpl.java | 3057 | /*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.security.tools.scanmanager.core.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.wso2.security.tools.scanmanager.common.external.model.Scanner;
import org.wso2.security.tools.scanmanager.common.external.model.ScannerApp;
import org.wso2.security.tools.scanmanager.core.dao.ScannerAppDAO;
import org.wso2.security.tools.scanmanager.core.dao.ScannerDAO;
import org.wso2.security.tools.scanmanager.core.exception.ScanManagerException;
import java.util.List;
/**
* Scanner Service class that manage the method implementations of the scanners.
*/
@Service
@Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED)
public class ScannerServiceImpl implements ScannerService {
private ScannerDAO scannerDAO;
private ScannerAppDAO scannerAppDAO;
@Autowired
public ScannerServiceImpl(ScannerDAO scannerDAO, ScannerAppDAO scannerAppDAO) {
this.scannerDAO = scannerDAO;
this.scannerAppDAO = scannerAppDAO;
}
@Override
public Scanner insert(Scanner scanner) {
return scannerDAO.saveAndFlush(scanner);
}
@Override
public Scanner update(Scanner scanner) {
return scannerDAO.saveAndFlush(scanner);
}
@Override
public Scanner getById(String scannerId) {
return scannerDAO.getScannerById(scannerId);
}
@Override
public List<Scanner> getAll() {
return scannerDAO.findAll();
}
@Override
public List<ScannerApp> getAppsByScannerAndAssignedProduct(Scanner scanner, String productName) {
return scannerAppDAO.getByScannerAndAssignedProduct(scanner, productName);
}
@Override
public ScannerApp getByScannerAndAppId(Scanner scanner, String appId) {
return scannerAppDAO.getByScannerAndAppId(scanner, appId);
}
@Override
public void removeByScannerId(String scannerId) throws ScanManagerException {
Integer updatedRows = scannerDAO.removeById(scannerId);
if (updatedRows != 1) {
throw new ScanManagerException("Error occurred while removing scanner: " + scannerId);
}
}
}
| apache-2.0 |
zpao/buck | src/com/facebook/buck/core/rules/actions/lib/WriteAction.java | 3123 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.core.rules.actions.lib;
import com.facebook.buck.core.artifact.Artifact;
import com.facebook.buck.core.artifact.ArtifactFilesystem;
import com.facebook.buck.core.rules.actions.AbstractAction;
import com.facebook.buck.core.rules.actions.Action;
import com.facebook.buck.core.rules.actions.ActionExecutionContext;
import com.facebook.buck.core.rules.actions.ActionExecutionResult;
import com.facebook.buck.core.rules.actions.ActionRegistry;
import com.facebook.buck.core.rules.actions.DefaultActionRegistry;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import java.io.IOException;
import java.util.Optional;
/**
* {@link Action} that writes specified contents to all of the given output {@link
* com.facebook.buck.core.artifact.Artifact}s
*/
public class WriteAction extends AbstractAction {
private final String contents;
private final boolean isExecutable;
/**
* Create an instance of {@link WriteAction}
*
* @param actionRegistry the {@link DefaultActionRegistry} to register this action
* @param inputs the input {@link Artifact} for this {@link Action}. They can be either outputs of
* other {@link Action}s or be source files
* @param outputs the outputs for this {@link Action}
* @param contents the contents to write
* @param isExecutable whether the output is executable
*/
public WriteAction(
ActionRegistry actionRegistry,
ImmutableSortedSet<Artifact> inputs,
ImmutableSortedSet<Artifact> outputs,
String contents,
boolean isExecutable) {
super(actionRegistry, inputs, outputs);
this.contents = contents;
this.isExecutable = isExecutable;
}
@Override
public String getShortName() {
return "write";
}
@Override
public ActionExecutionResult execute(ActionExecutionContext executionContext) {
ArtifactFilesystem filesystem = executionContext.getArtifactFilesystem();
for (Artifact output : outputs) {
try {
filesystem.writeContentsToPath(contents, output);
if (isExecutable) {
filesystem.makeExecutable(output);
}
} catch (IOException e) {
return ActionExecutionResult.failure(
Optional.empty(), Optional.empty(), ImmutableList.of(), Optional.of(e));
}
}
return ActionExecutionResult.success(Optional.empty(), Optional.empty(), ImmutableList.of());
}
@Override
public boolean isCacheable() {
return true;
}
}
| apache-2.0 |
apetresc/aws-sdk-for-java-on-gae | src/main/java/com/amazonaws/services/identitymanagement/model/UploadServerCertificateRequest.java | 15587 | /*
* Copyright 2010-2011 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.identitymanagement.model;
import com.amazonaws.AmazonWebServiceRequest;
/**
* Container for the parameters to the {@link com.amazonaws.services.identitymanagement.AmazonIdentityManagement#uploadServerCertificate(UploadServerCertificateRequest) UploadServerCertificate operation}.
* <p>
* Uploads a server certificate entity for the AWS Account. The server
* certificate entity includes a public key certificate, a private key,
* and an optional certificate chain, which should all be PEM-encoded.
* </p>
* <p>
* For information about the number of server certificates you can
* upload, see <a
* vices.com/IAM/latest/UserGuide/index.html?LimitationsOnEntities.html">
* Limitations on IAM Entities </a> in <i>Using AWS Identity and Access
* Management</i> .
* </p>
* <p>
* <b>NOTE:</b>Because the body of the public key certificate, private
* key, and the certificate chain can be large, you should use POST
* rather than GET when calling UploadServerCertificate. For more
* information, see Making Query Requests in Using AWS Identity and
* Access Management.
* </p>
*
* @see com.amazonaws.services.identitymanagement.AmazonIdentityManagement#uploadServerCertificate(UploadServerCertificateRequest)
*/
public class UploadServerCertificateRequest extends AmazonWebServiceRequest {
/**
* The path for the server certificate. For more information about paths,
* see <a
* ebservices.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html"
* target="_blank">Identifiers for IAM Entities</a> in <i>Using AWS
* Identity and Access Management</i>. <p>This parameter is optional. If
* it is not included, it defaults to a slash (/).
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 512<br/>
* <b>Pattern: </b>(\u002F)|(\u002F[\u0021-\u007F]+\u002F)<br/>
*/
private String path;
/**
* The name for the server certificate. Do not include the path in this
* value.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
* <b>Pattern: </b>[\w+=,.@-]*<br/>
*/
private String serverCertificateName;
/**
* The contents of the public key certificate in PEM-encoded format.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16384<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/>
*/
private String certificateBody;
/**
* The contents of the private key in PEM-encoded format.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16384<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]*<br/>
*/
private String privateKey;
/**
* The contents of the certificate chain. This is typically a
* concatenation of the PEM-encoded public key certificates of the chain.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 2097152<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]*<br/>
*/
private String certificateChain;
/**
* Default constructor for a new UploadServerCertificateRequest object. Callers should use the
* setter or fluent setter (with...) methods to initialize this object after creating it.
*/
public UploadServerCertificateRequest() {}
/**
* Constructs a new UploadServerCertificateRequest object.
* Callers should use the setter or fluent setter (with...) methods to
* initialize any additional object members.
*
* @param serverCertificateName The name for the server certificate. Do
* not include the path in this value.
* @param certificateBody The contents of the public key certificate in
* PEM-encoded format.
* @param privateKey The contents of the private key in PEM-encoded
* format.
*/
public UploadServerCertificateRequest(String serverCertificateName, String certificateBody, String privateKey) {
this.serverCertificateName = serverCertificateName;
this.certificateBody = certificateBody;
this.privateKey = privateKey;
}
/**
* The path for the server certificate. For more information about paths,
* see <a
* ebservices.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html"
* target="_blank">Identifiers for IAM Entities</a> in <i>Using AWS
* Identity and Access Management</i>. <p>This parameter is optional. If
* it is not included, it defaults to a slash (/).
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 512<br/>
* <b>Pattern: </b>(\u002F)|(\u002F[\u0021-\u007F]+\u002F)<br/>
*
* @return The path for the server certificate. For more information about paths,
* see <a
* ebservices.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html"
* target="_blank">Identifiers for IAM Entities</a> in <i>Using AWS
* Identity and Access Management</i>. <p>This parameter is optional. If
* it is not included, it defaults to a slash (/).
*/
public String getPath() {
return path;
}
/**
* The path for the server certificate. For more information about paths,
* see <a
* ebservices.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html"
* target="_blank">Identifiers for IAM Entities</a> in <i>Using AWS
* Identity and Access Management</i>. <p>This parameter is optional. If
* it is not included, it defaults to a slash (/).
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 512<br/>
* <b>Pattern: </b>(\u002F)|(\u002F[\u0021-\u007F]+\u002F)<br/>
*
* @param path The path for the server certificate. For more information about paths,
* see <a
* ebservices.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html"
* target="_blank">Identifiers for IAM Entities</a> in <i>Using AWS
* Identity and Access Management</i>. <p>This parameter is optional. If
* it is not included, it defaults to a slash (/).
*/
public void setPath(String path) {
this.path = path;
}
/**
* The path for the server certificate. For more information about paths,
* see <a
* ebservices.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html"
* target="_blank">Identifiers for IAM Entities</a> in <i>Using AWS
* Identity and Access Management</i>. <p>This parameter is optional. If
* it is not included, it defaults to a slash (/).
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 512<br/>
* <b>Pattern: </b>(\u002F)|(\u002F[\u0021-\u007F]+\u002F)<br/>
*
* @param path The path for the server certificate. For more information about paths,
* see <a
* ebservices.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html"
* target="_blank">Identifiers for IAM Entities</a> in <i>Using AWS
* Identity and Access Management</i>. <p>This parameter is optional. If
* it is not included, it defaults to a slash (/).
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UploadServerCertificateRequest withPath(String path) {
this.path = path;
return this;
}
/**
* The name for the server certificate. Do not include the path in this
* value.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
* <b>Pattern: </b>[\w+=,.@-]*<br/>
*
* @return The name for the server certificate. Do not include the path in this
* value.
*/
public String getServerCertificateName() {
return serverCertificateName;
}
/**
* The name for the server certificate. Do not include the path in this
* value.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
* <b>Pattern: </b>[\w+=,.@-]*<br/>
*
* @param serverCertificateName The name for the server certificate. Do not include the path in this
* value.
*/
public void setServerCertificateName(String serverCertificateName) {
this.serverCertificateName = serverCertificateName;
}
/**
* The name for the server certificate. Do not include the path in this
* value.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
* <b>Pattern: </b>[\w+=,.@-]*<br/>
*
* @param serverCertificateName The name for the server certificate. Do not include the path in this
* value.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UploadServerCertificateRequest withServerCertificateName(String serverCertificateName) {
this.serverCertificateName = serverCertificateName;
return this;
}
/**
* The contents of the public key certificate in PEM-encoded format.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16384<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/>
*
* @return The contents of the public key certificate in PEM-encoded format.
*/
public String getCertificateBody() {
return certificateBody;
}
/**
* The contents of the public key certificate in PEM-encoded format.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16384<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/>
*
* @param certificateBody The contents of the public key certificate in PEM-encoded format.
*/
public void setCertificateBody(String certificateBody) {
this.certificateBody = certificateBody;
}
/**
* The contents of the public key certificate in PEM-encoded format.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16384<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]+<br/>
*
* @param certificateBody The contents of the public key certificate in PEM-encoded format.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UploadServerCertificateRequest withCertificateBody(String certificateBody) {
this.certificateBody = certificateBody;
return this;
}
/**
* The contents of the private key in PEM-encoded format.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16384<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]*<br/>
*
* @return The contents of the private key in PEM-encoded format.
*/
public String getPrivateKey() {
return privateKey;
}
/**
* The contents of the private key in PEM-encoded format.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16384<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]*<br/>
*
* @param privateKey The contents of the private key in PEM-encoded format.
*/
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
/**
* The contents of the private key in PEM-encoded format.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 16384<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]*<br/>
*
* @param privateKey The contents of the private key in PEM-encoded format.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UploadServerCertificateRequest withPrivateKey(String privateKey) {
this.privateKey = privateKey;
return this;
}
/**
* The contents of the certificate chain. This is typically a
* concatenation of the PEM-encoded public key certificates of the chain.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 2097152<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]*<br/>
*
* @return The contents of the certificate chain. This is typically a
* concatenation of the PEM-encoded public key certificates of the chain.
*/
public String getCertificateChain() {
return certificateChain;
}
/**
* The contents of the certificate chain. This is typically a
* concatenation of the PEM-encoded public key certificates of the chain.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 2097152<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]*<br/>
*
* @param certificateChain The contents of the certificate chain. This is typically a
* concatenation of the PEM-encoded public key certificates of the chain.
*/
public void setCertificateChain(String certificateChain) {
this.certificateChain = certificateChain;
}
/**
* The contents of the certificate chain. This is typically a
* concatenation of the PEM-encoded public key certificates of the chain.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 2097152<br/>
* <b>Pattern: </b>[\u0009\u000A\u000D\u0020-\u00FF]*<br/>
*
* @param certificateChain The contents of the certificate chain. This is typically a
* concatenation of the PEM-encoded public key certificates of the chain.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UploadServerCertificateRequest withCertificateChain(String certificateChain) {
this.certificateChain = certificateChain;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("Path: " + path + ", ");
sb.append("ServerCertificateName: " + serverCertificateName + ", ");
sb.append("CertificateBody: " + certificateBody + ", ");
sb.append("PrivateKey: " + privateKey + ", ");
sb.append("CertificateChain: " + certificateChain + ", ");
sb.append("}");
return sb.toString();
}
}
| apache-2.0 |
everttigchelaar/camel-svn | camel-core/src/test/java/org/apache/camel/issues/DoCatchCaughExceptionIssueTest.java | 2363 | /**
* 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.issues;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
/**
* Based on user forum issue
*
* @version
*/
public class DoCatchCaughExceptionIssueTest extends ContextTestSupport {
public void testSendThatIsCaught() {
String out = template.requestBody("direct:test", "test", String.class);
assertEquals("Forced by me but I fixed it", out);
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
errorHandler(noErrorHandler());
from("direct:test")
.doTry()
.throwException(new IllegalArgumentException("Forced by me"))
.doCatch(Exception.class)
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
Exception error = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
assertEquals("Forced by me", error.getMessage());
exchange.getOut().setBody(error.getMessage() + " but I fixed it");
}
})
.end();
}
};
}
}
| apache-2.0 |
dedmen/LEA | src/com/lea/dao/script/mission/InitMissionDAO.java | 3498 | package com.lea.dao.script.mission;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import com.lea.dao.script.AbstractScriptDAO;
import com.lea.domain.Mission;
public class InitMissionDAO extends AbstractScriptDAO {
/**
* Write the init.sqf file into mission folder
*/
@Override
public void writeScript(Object object, String path, String scriptName)
throws IOException {
String missionFolderPath = ((Mission) object).getMissionFolderPath();
String relativePath = path.subSequence(missionFolderPath.length(),
path.length()).toString();
if (relativePath.length() != 0) {
relativePath = relativePath.substring(1) + "\\";
}
File initFile = new File(missionFolderPath + "/" + scriptName);
String command = "leaFunction = compile preprocessFileLineNumbers "
+ "\"" + relativePath + "lea\\loadout-init.sqf" + "\""
+ "; call leaFunction;" + "//line generated by LEA.";
if (!initFile.exists()) {
PrintWriter fWo = new PrintWriter(new FileWriter(initFile));
fWo.println(command);
fWo.close();
} else {
DataInputStream fRo = new DataInputStream(new FileInputStream(
missionFolderPath + "/" + "init.sqf"));
BufferedReader reader = new BufferedReader(new InputStreamReader(
fRo));
DataOutputStream fWo = new DataOutputStream(new FileOutputStream(
missionFolderPath + "/" + "init.sqf.tmp"));
BufferedWriter writter = new BufferedWriter(new OutputStreamWriter(
fWo));
// String text = "_dummy = [] execVM " + "\"" + relativePath
// + "lea\\loadout-init.sqf" + "\"" + ";"
// + "//call for lea loadout scripts, line generated by LEA.";
String ligne = "";
ligne = reader.readLine();
if (ligne == null) {
ligne = command;
writter.write(ligne);
writter.newLine();
} else if (ligne.contains("loadout-init.sqf")) {
ligne = command;
writter.write(ligne);
writter.newLine();
} else {
writter.write(command);
writter.newLine();
writter.write(ligne);
writter.newLine();
}
while (true) {
ligne = reader.readLine();
if (ligne == null) {
break;
}
writter.write(ligne);
writter.newLine();
}
writter.flush();
reader.close();
writter.close();
fRo.close();
deleteFile(initFile);
File sourceLocation = new File(missionFolderPath + "/"
+ "init.sqf.tmp");
File targetLocation = new File(missionFolderPath + "/" + "init.sqf");
copyFile(sourceLocation, targetLocation);
deleteFile(sourceLocation);
fWo.close();
}
}
private void copyFile(File sourceLocation, File targetLocation)
throws IOException {
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceLocation).getChannel();
destination = new FileOutputStream(targetLocation).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
private boolean deleteFile(File file) {
boolean response = false;
if (file.exists()) {
response = file.delete();
}
return response;
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | examples/dfp_axis/src/main/java/dfp/axis/v201511/reportservice/RunDeliveryReportForOrder.java | 5073 | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dfp.axis.v201511.reportservice;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.dfp.axis.factory.DfpServices;
import com.google.api.ads.dfp.axis.utils.v201511.DateTimes;
import com.google.api.ads.dfp.axis.utils.v201511.ReportDownloader;
import com.google.api.ads.dfp.axis.utils.v201511.StatementBuilder;
import com.google.api.ads.dfp.axis.v201511.Column;
import com.google.api.ads.dfp.axis.v201511.DateRangeType;
import com.google.api.ads.dfp.axis.v201511.Dimension;
import com.google.api.ads.dfp.axis.v201511.DimensionAttribute;
import com.google.api.ads.dfp.axis.v201511.ExportFormat;
import com.google.api.ads.dfp.axis.v201511.ReportDownloadOptions;
import com.google.api.ads.dfp.axis.v201511.ReportJob;
import com.google.api.ads.dfp.axis.v201511.ReportQuery;
import com.google.api.ads.dfp.axis.v201511.ReportServiceInterface;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import java.io.File;
import java.net.URL;
/**
* This example runs a typical delivery report for a single order.
*
* Credentials and properties in {@code fromFile()} are pulled from the
* "ads.properties" file. See README for more info.
*/
public class RunDeliveryReportForOrder {
// Set the ID of the order to run the report for.
private static final String ORDER_ID = "INSERT_ORDER_ID_HERE";
public static void runExample(DfpServices dfpServices, DfpSession session, long orderId)
throws Exception {
// Get the ReportService.
ReportServiceInterface reportService = dfpServices.get(session, ReportServiceInterface.class);
// Create report query.
ReportQuery reportQuery = new ReportQuery();
reportQuery.setDimensions(new Dimension[] {Dimension.DATE, Dimension.ORDER_ID});
reportQuery.setColumns(new Column[] {Column.AD_SERVER_IMPRESSIONS,
Column.AD_SERVER_CLICKS, Column.AD_SERVER_CTR,
Column.AD_SERVER_CPM_AND_CPC_REVENUE});
reportQuery.setDimensionAttributes(new DimensionAttribute[] {
DimensionAttribute.ORDER_TRAFFICKER, DimensionAttribute.ORDER_START_DATE_TIME,
DimensionAttribute.ORDER_END_DATE_TIME});
// Create statement to filter for an order.
StatementBuilder statementBuilder = new StatementBuilder()
.where("ORDER_ID = :orderId")
.withBindVariableValue("orderId", orderId);
// Set the filter statement.
reportQuery.setStatement(statementBuilder.toStatement());
// Set the start and end dates or choose a dynamic date range type.
reportQuery.setDateRangeType(DateRangeType.CUSTOM_DATE);
reportQuery.setStartDate(
DateTimes.toDateTime("2013-05-01T00:00:00", "America/New_York").getDate());
reportQuery.setEndDate(
DateTimes.toDateTime("2013-05-31T00:00:00", "America/New_York").getDate());
// Create report job.
ReportJob reportJob = new ReportJob();
reportJob.setReportQuery(reportQuery);
// Run report job.
reportJob = reportService.runReportJob(reportJob);
// Create report downloader.
ReportDownloader reportDownloader = new ReportDownloader(reportService, reportJob.getId());
// Wait for the report to be ready.
reportDownloader.waitForReportReady();
// Change to your file location.
File file = File.createTempFile("delivery-report-", ".csv.gz");
System.out.printf("Downloading report to %s ...", file.toString());
// Download the report.
ReportDownloadOptions options = new ReportDownloadOptions();
options.setExportFormat(ExportFormat.CSV_DUMP);
options.setUseGzipCompression(true);
URL url = reportDownloader.getDownloadUrl(options);
Resources.asByteSource(url).copyTo(Files.asByteSink(file));
System.out.println("done.");
}
public static void main(String[] args) throws Exception {
// Generate a refreshable OAuth2 credential.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.DFP)
.fromFile()
.build()
.generateCredential();
// Construct a DfpSession.
DfpSession session = new DfpSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
DfpServices dfpServices = new DfpServices();
runExample(dfpServices, session, Long.parseLong(ORDER_ID));
}
}
| apache-2.0 |
dgwave/ceylon-jboss-loader | src/main/java/com/dgwave/car/loader/CarModuleFinder.java | 10700 | package com.dgwave.car.loader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.JarFile;
import org.jboss.modules.DependencySpec;
import org.jboss.modules.ModuleFinder;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleLoader;
import org.jboss.modules.ModuleSpec;
import org.jboss.modules.ModuleSpec.AliasBuilder;
import org.jboss.modules.ModuleSpec.Builder;
import org.jboss.modules.ResourceLoaderSpec;
import org.jboss.modules.ResourceLoaders;
import org.jboss.modules.filter.MultiplePathFilterBuilder;
import org.jboss.modules.filter.PathFilters;
import com.dgwave.lahore.api.Description$annotation$;
import com.dgwave.lahore.api.Id$annotation$;
import com.dgwave.lahore.api.Name$annotation$;
import com.redhat.ceylon.compiler.java.metadata.Import;
import com.redhat.ceylon.compiler.java.metadata.Module;
/**
* Only finds 'car' modules in the Ceylon modules layer.
* Does not support arbitrary layers and add-ons at this time
*
* @author Akber Choudhry
*/
public final class CarModuleFinder implements ModuleFinder {
/**
* The supported Ceylon language version.
*/
private static final String CEYLON_LANGUAGE_VERSION = "1.0.0";
/**
* The root of the Ceylon JBoss/Wildfly add-on repository.
*/
private static String ceylonLayerRoot = System.getProperty("module.path")
+ File.separator + "system" + File.separator + "add-ons" + File.separator + "ceylon";
/** Default package-private constructor.
* @param local Handle to default local module finder
*/
CarModuleFinder() {
org.jboss.modules.Module.getModuleLogger().trace("Ceylon Module Loader v0.5 activated");
System.out.println("Ceylon Module Loader v0.5 activated");
}
/**
* Utility method to convert a module identifier to a relative path within the add-on repository.
* @param moduleIdentifier The module identifier
* @return String The relaive path
*/
private static String toPathString(final ModuleIdentifier moduleIdentifier) {
StringBuilder builder = new StringBuilder(40);
builder.append(moduleIdentifier.getName().replace('.', File.separatorChar));
builder.append(File.separatorChar).append(moduleIdentifier.getSlot());
builder.append(File.separatorChar);
return builder.toString();
}
/**
* Method called by JBoss Modules to find a Ceylon module.
* @param identifier The module identifier
* @param delegateLoader Delegate loader, which is not useful in this context
* @return ModuleSpec The module spec
* @throws ModuleLoadException In case of error
*/
@Override
public ModuleSpec findModule(final ModuleIdentifier identifier, final ModuleLoader delegateLoader)
throws ModuleLoadException {
final String child = toPathString(identifier);
File file = new File(ceylonLayerRoot, child);
File moduleXml = new File(file, "module.xml");
if (moduleXml.exists()) {
if (!specialHandling(identifier)) {
return null; // nothing to do wth Ceylon
} else {
AliasBuilder aliasBuilder = ModuleSpec.buildAlias(identifier,
ModuleIdentifier.create("com.dgwave.car.loader", "main"));
return aliasBuilder.create();
}
} else {
File[] files = file.listFiles(new FileFilter() {
@Override
public boolean accept(final File candidate) {
return candidate.getName().endsWith(".car");
}
});
if (files != null && files.length == 1) {
return generateModuleSpec(files[0], identifier);
}
}
return null;
}
/**
* Deserves special consideration.
*/
private boolean specialHandling(ModuleIdentifier identifier) {
return "com.redhat.ceylon.module-resolver".equals(identifier.getName());
}
/**
* Produces a module spec from an identified 'car' file.
* @param file The Ceylon module 'car' file
* @param moduleIdentifier The module identifier
* @return ModuleSpec The module identifier
* @throws ModuleLoadException In case of error
*/
private ModuleSpec generateModuleSpec(final File file, final ModuleIdentifier moduleIdentifier)
throws ModuleLoadException {
try {
URLClassLoader cl = new URLClassLoader(new URL[]{ file.toURI().toURL() });
Class<?> moduleClass = Class.forName(moduleIdentifier.getName() + ".module_", true, cl);
if (moduleClass == null || !moduleClass.isAnnotationPresent(Module.class)) {
return null; // quick exit
}
Module ceylonModule = moduleClass.getAnnotation(Module.class);
if (ceylonModule != null) {
MultiplePathFilterBuilder pathFilterBuilder = PathFilters.multiplePathFilterBuilder(true);
pathFilterBuilder.addFilter(PathFilters.isOrIsChildOf(
moduleIdentifier.getName().replace('.', '/')), true);
ModuleSpec.Builder builder = ModuleSpec.build(moduleIdentifier);
builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(
ResourceLoaders.createJarResourceLoader(file.getName(), new JarFile(file, true)),
pathFilterBuilder.create()));
for (Import imp : ceylonModule.dependencies()) {
// Skips java and javax. oracle and sun modules wil not be found.
// Attempting to be JVM vendor agnostic
if (!imp.name().startsWith("java")) {
String name = wildflyName(imp.name());
String version = wildflyVersion(name, imp.version());
DependencySpec mds = DependencySpec.createModuleDependencySpec(
ModuleIdentifier.create(name, version), imp.export(), imp.optional());
builder.addDependency(mds);
}
}
builder.addProperty("ceylon.module", "true");
builder.addDependency(DependencySpec.createModuleDependencySpec(
ModuleIdentifier.create("ceylon.language", CEYLON_LANGUAGE_VERSION), true, false));
builder.addDependency(DependencySpec.createLocalDependencySpec());
addLahoreProperties(builder, moduleClass);
addRunClass(builder, cl, moduleIdentifier);
return builder.create();
}
} catch (MalformedURLException e) {
throw new ModuleLoadException("Error loading CAR module: ", e);
} catch (ClassNotFoundException e) {
throw new ModuleLoadException(
"Error loading CAR module. Does not contain a module descriptor (module.ceylon)", e);
} catch (IOException e) {
throw new ModuleLoadException("Error loading CAR module. Module not packaged propertly", e);
}
return null;
}
/**
* Add a run class if one exists.
* @param builder The ModuleSpec builder
* @param cl The classloader for the car file
* @param moduleIdentifier The module identifier
*/
private void addRunClass(final Builder builder, final URLClassLoader cl, final ModuleIdentifier moduleIdentifier) {
try {
Class<?> runClass = Class.forName(moduleIdentifier.getName() + ".run_", true, cl);
if (runClass == null) {
return;
} else {
builder.setMainClass(moduleIdentifier.getName() + ".run_");
}
} catch (ClassNotFoundException e) {
org.jboss.modules.Module.getModuleLogger()
.trace("run_ class not found in Ceylon module: " + moduleIdentifier);
}
}
/**
* Attaches Lahore properties to the loaded module.
* @param builder The moduleSpec builder
* @param moduleCls The module class
*/
private void addLahoreProperties(final Builder builder, final Class<?> moduleCls) {
Id$annotation$ lahoreId = moduleCls.getAnnotation(Id$annotation$.class);
if (lahoreId != null) {
builder.addProperty("lahore.id", lahoreId.id());
Name$annotation$ lahoreName = moduleCls.getAnnotation(Name$annotation$.class);
if (lahoreName != null) {
builder.addProperty("lahore.name", lahoreName.name());
}
Description$annotation$ lahoreDescription = moduleCls.getAnnotation(Description$annotation$.class);
if (lahoreDescription != null) {
builder.addProperty("lahore.description", lahoreDescription.description());
}
}
}
/**
* Override Ceylon Java module dependencies to JBoss/Wildfly module names.
* Although Ceylon Herd repository may serve Java modules, it attempts to rename them from their published names
* Not every module needs to be listed here. Other modules with new names or aliases can be added to the
* Ceylon layer. This override is required only when interaction with existing JBoss subsystems is needed.
* @param name Name of the module
* @return String The canonical JBoss/Wildfly name
*/
private String wildflyName(final String name) {
if ("org.jboss.xnio.api".equals(name)) {
return "org.jboss.xnio";
}
return name;
}
/**
* Override Ceylon Java module versions to JBoss/Wildfly versions, generally 'main'.
* @param name The name of the module
* @param version The vesion
* @return String The canonical JBoss/Wildfly version
*/
private String wildflyVersion(final String name, final String version) {
if (name.startsWith("io.undertow")
|| name.startsWith("org.jboss.xnio")) {
return "main";
}
return version;
}
}
| apache-2.0 |
tommyettinger/SquidLib-Demos | Sampler/desktop/src/main/java/com/squidpony/samples/WorldMapTextDemo.java | 17460 | package com.squidpony.samples;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.squidpony.samples.desktop.CustomConfig;
import squidpony.ArrayTools;
import squidpony.FakeLanguageGen;
import squidpony.StringKit;
import squidpony.squidgrid.gui.gdx.DefaultResources;
import squidpony.squidgrid.gui.gdx.FilterBatch;
import squidpony.squidgrid.gui.gdx.SColor;
import squidpony.squidgrid.gui.gdx.SparseLayers;
import squidpony.squidgrid.gui.gdx.SquidInput;
import squidpony.squidgrid.gui.gdx.SquidMouse;
import squidpony.squidgrid.gui.gdx.WorldMapView;
import squidpony.squidgrid.mapping.PoliticalMapper;
import squidpony.squidgrid.mapping.WorldMapGenerator;
import squidpony.squidmath.Coord;
import squidpony.squidmath.FastNoise;
import squidpony.squidmath.OrderedMap;
import squidpony.squidmath.StatefulRNG;
/**
* Map generator that uses text to show features at a location as well as color.
* Port of Zachary Carter's world generation technique, https://github.com/zacharycarter/mapgen
* It seems to mostly work now, though it only generates one view of the map that it renders (but biome, moisture, heat,
* and height maps can all be requested from it).
*/
public class WorldMapTextDemo extends ApplicationAdapter {
public static final char[] terrainChars = {
'¿', //sand
'„', //lush grass
'♣', //jungle
'‚', //barren grass
'¥', //forest
'¥', //forest
'♣', //jungle
'¥', //forest
'‚', //barren grass
'¤', //ice
'.', //sand
'∆', //rocky
'~', //shallow
'≈', //ocean
' ', //empty space
//'■', //active city
'□', //empty city
};
//public static final char[] terrainChars = {
// '.', //sand
// '"', //lush grass
// '?', //jungle
// '\'', //barren grass
// '$', //forest
// '$', //forest
// '?', //jungle
// '$', //forest
// '‚', //barren grass
// '*', //ice
// '.', //sand
// '^', //rocky
// '~', //shallow
// '~', //ocean
// ' ', //empty space
// //'■', //active city
// '#', //empty city
//};
//private static final int bigWidth = 314 * 3, bigHeight = 300;
// private static final int bigWidth = 256, bigHeight = 256;
// private static final int bigWidth = 1024, bigHeight = 512;
private static final int bigWidth = 512, bigHeight = 256;
// private static final int bigWidth = 2048, bigHeight = 1024;
//private static final int bigWidth = 400, bigHeight = 400;
private static final int cellWidth = 16, cellHeight = 16;
private static final int shownWidth = 96, shownHeight = 48;
private FilterBatch batch;
private SparseLayers display;//, overlay;
private SquidInput input;
private Stage stage;
private Viewport view;
private StatefulRNG rng;
private long seed;
private Vector3 position, previousPosition, nextPosition;
private WorldMapGenerator world;
private WorldMapView wmv;
private PoliticalMapper pm;
private OrderedMap<Character, FakeLanguageGen> atlas;
private OrderedMap<Coord, String> cities;
//private WorldMapGenerator.EllipticalMap world;
//private final float[][][] cloudData = new float[128][128][128];
private long counter = 0;
//private float nation = 0f;
private long ttg = 0; // time to generate
private float moveAmount = 0f;
private static float black = SColor.FLOAT_BLACK,
white = SColor.FLOAT_WHITE;
// Biome map colors
private static float ice = SColor.ALICE_BLUE.toFloatBits();
private static float lightIce = white;
private static float desert = SColor.floatGetI(248, 229, 180);
private static float savanna = SColor.floatGetI(181, 200, 100);
private static float tropicalRainforest = SColor.floatGetI(66, 123, 25);
private static float tundra = SColor.floatGetI(151, 175, 159);
private static float temperateRainforest = SColor.floatGetI(54, 113, 60);
private static float grassland = SColor.floatGetI(169, 185, 105);
private static float seasonalForest = SColor.floatGetI(100, 158, 75);
private static float borealForest = SColor.floatGetI(75, 105, 45);
private static float woodland = SColor.floatGetI(122, 170, 90);
private static float rocky = SColor.floatGetI(171, 175, 145);
private static float beach = SColor.floatGetI(255, 235, 180);
private static float emptyColor = SColor.DB_INK.toFloatBits();
// water colors
private static float deepColor = SColor.floatGetI(0, 42, 88);
private static float mediumColor = SColor.floatGetI(0, 89, 159);
private static float shallowColor = SColor.floatGetI(0, 73, 137);
private static float coastalColor = SColor.lightenFloat(shallowColor, 0.3f);
private static float foamColor = SColor.floatGetI(61, 162, 215);
private static final char[] BIOME_CHARS = new char[61];
static {
for (int i = 0; i < 61; i++) {
BIOME_CHARS[i] = terrainChars[(int) WorldMapView.BIOME_TABLE[i]];
}
}
@Override
public void create() {
batch = new FilterBatch();
display = new SparseLayers(bigWidth, bigHeight, cellWidth, cellHeight, DefaultResources.getCrispSlabFamily());
view = new StretchViewport(shownWidth * cellWidth, shownHeight * cellHeight);
stage = new Stage(view, batch);
seed = 1234567890L;
rng = new StatefulRNG(seed);
//// you can use whatever map you have instead of fantasy_map.png, where white means land and black means water
// Pixmap pix = new Pixmap(Gdx.files.internal("special/fantasy_map.png"));
// final int bigWidth = pix.getWidth() / 4, bigHeight = pix.getHeight() / 4;
// GreasedRegion basis = new GreasedRegion(bigWidth, bigHeight);
// for (int x = 0; x < bigWidth; x++) {
// for (int y = 0; y < bigHeight; y++) {
// if(pix.getPixel(x * 4, y * 4) < 0) // only counts every fourth row and every fourth column
// basis.insert(x, y);
// }
// }
// basis = WorldMapGenerator.MimicMap.reprojectToElliptical(basis);
//// at this point you could get the GreasedRegion as a String, and save the compressed output to a file:
//// Gdx.files.local("map.txt").writeString(LZSPlus.compress(basis.serializeToString()), false, "UTF16");
//// you could reload basis without needing the original map image with
//// basis = GreasedRegion.deserializeFromString(LZSPlus.decompress(Gdx.files.local("map.txt").readString("UTF16")));
//// it's also possible to store the compressed map as a String in code, but you need to be careful about escaped chars.
// world = new WorldMapGenerator.LocalMimicMap(seed, basis, FastNoise.instance, 0.8);
// pix.dispose();
FastNoise noise = new FastNoise(0x1337BEEF, 2f, FastNoise.FOAM_FRACTAL, 2, 2.5f, 0.4f);
world = new WorldMapGenerator.MimicMap(seed, noise, 0.8); // uses a map of Earth for land
// world = new WorldMapGenerator.HyperellipticalMap(seed, bigWidth, bigHeight, WorldMapGenerator.DEFAULT_NOISE, 0.8);
//world = new WorldMapGenerator.TilingMap(seed, bigWidth, bigHeight, WhirlingNoise.instance, 0.9);
wmv = new WorldMapView(world);
pm = new PoliticalMapper(FakeLanguageGen.SIMPLISH.word(rng, true));
cities = new OrderedMap<>(96);
atlas = new OrderedMap<>(80);
position = new Vector3(bigWidth * cellWidth * 0.5f, bigHeight * cellHeight * 0.5f, 0);
previousPosition = position.cpy();
nextPosition = position.cpy();
input = new SquidInput(new SquidInput.KeyHandler() {
@Override
public void handle(char key, boolean alt, boolean ctrl, boolean shift) {
switch (key) {
case SquidInput.ENTER:
seed = rng.nextLong();
generate(seed);
rng.setState(seed);
break;
case SquidInput.DOWN_ARROW:
position.add(0, 1, 0);
break;
case SquidInput.UP_ARROW:
position.add(0, -1, 0);
break;
case SquidInput.LEFT_ARROW:
position.add(-1, 0, 0);
break;
case SquidInput.RIGHT_ARROW:
position.add(1, 0, 0);
break;
case 'Q':
case 'q':
case SquidInput.ESCAPE: {
Gdx.app.exit();
}
}
}
}, new SquidMouse(1, 1, bigWidth * cellWidth, bigHeight * cellHeight, 0, 0, new InputAdapter()
{
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
previousPosition.set(position);
nextPosition.set(screenX, screenY, 0);
stage.getCamera().unproject(nextPosition);
nextPosition.set(MathUtils.round(nextPosition.x), MathUtils.round(nextPosition.y), nextPosition.z);
counter = System.currentTimeMillis();
moveAmount = 0f;
return true;
}
}));
generate(seed);
rng.setState(seed);
Gdx.input.setInputProcessor(input);
display.setPosition(0, 0);
stage.addActor(display);
}
// public void zoomIn() {
// zoomIn(bigWidth >> 1, bigHeight >> 1);
// }
// public void zoomIn(int zoomX, int zoomY)
// {
// long startTime = System.currentTimeMillis();
// world.zoomIn(1, zoomX, zoomY);
// dbm.makeBiomes(world);
// //counter = 0L;
// ttg = System.currentTimeMillis() - startTime;
// }
// public void zoomOut()
// {
// zoomOut(bigWidth >>1, bigHeight >>1);
// }
// public void zoomOut(int zoomX, int zoomY)
// {
// long startTime = System.currentTimeMillis();
// world.zoomOut(1, zoomX, zoomY);
// dbm.makeBiomes(world);
// //counter = 0L;
// ttg = System.currentTimeMillis() - startTime;
// }
public void generate(final long seed)
{
long startTime = System.currentTimeMillis();
System.out.println("Seed used: 0x" + StringKit.hex(seed) + "L");
world.seedA = (int)(seed & 0xFFFFFFFFL);
world.seedB = (int) (seed >>> 32);
wmv.generate();
wmv.show();
atlas.clear();
for (int i = 0; i < 64; i++) {
atlas.put(ArrayTools.letterAt(i),
rng.getRandomElement(FakeLanguageGen.romanizedHumanLanguages).mix(rng.getRandomElement(FakeLanguageGen.romanizedHumanLanguages), rng.nextFloat()).removeAccents());
}
final char[][] political = pm.generate(world, atlas, 1.0);
cities.clear();
Coord[] points = world.landData
.copy() // don't want to edit the actual land map
.removeEdges() // don't want cities on the edge of the map
.separatedRegionBlue(0.1, 500) // get 500 points in a regularly-tiling but unpredictable, sparse pattern
.randomPortion(rng,112); // randomly select less than 1/4 of those points, breaking the pattern
for (int i = 0; i < points.length; i++) {
char p = political[points[i].x][points[i].y];
if(p == '~' || p == '%')
continue;
FakeLanguageGen lang = atlas.get(p);
if(lang != null)
{
cities.put(points[i], lang.word(rng, false).toUpperCase());
}
}
//counter = 0L;
ttg = System.currentTimeMillis() - startTime;
}
public void putMap() {
// uncomment next line to generate maps as quickly as possible
//generate(rng.nextLong());
// ArrayTools.fill(display.backgrounds, -0x1.0p125F);
ArrayTools.insert(wmv.getColorMap(), display.backgrounds, 0, 0);
WorldMapGenerator.DetailedBiomeMapper dbm = wmv.getBiomeMapper();
int hc, tc, codeA, codeB;
float mix;
int[][] heightCodeData = world.heightCodeData;
//double xp, yp, zp;
for (int y = 0; y < bigHeight; y++) {
PER_CELL:
for (int x = 0; x < bigWidth; x++) {
hc = heightCodeData[x][y];
if(hc == 1000)
continue;
tc = dbm.heatCodeData[x][y];
if(tc == 0)
{
switch (hc)
{
case 0:
case 1:
case 2:
display.put(x, y, '≈', wmv.BIOME_DARK_COLOR_TABLE[30]);//SColor.darkenFloat(ice, 0.45f));
continue PER_CELL;
case 3:
display.put(x, y, '~', wmv.BIOME_DARK_COLOR_TABLE[24]);//SColor.darkenFloat(ice, 0.35f));
continue PER_CELL;
case 4:
display.put(x, y, '¤', wmv.BIOME_DARK_COLOR_TABLE[42]);//SColor.darkenFloat(ice, 0.25f));
continue PER_CELL;
}
}
switch (hc) {
case 0:
case 1:
case 2:
display.put(x, y, '≈', wmv.BIOME_COLOR_TABLE[44]);// SColor.lightenFloat(WorldMapView.foamColor, 0.3f));
break;
case 3:
display.put(x, y, '~', wmv.BIOME_COLOR_TABLE[43]);// SColor.lightenFloat(WorldMapView.foamColor, 0.3f));
break;
default:
int bc = dbm.biomeCodeData[x][y];
codeB = dbm.extractPartB(bc);
codeA = dbm.extractPartA(bc);
mix = dbm.extractMixAmount(bc);
if(mix <= 0.5)
display.put(x, y, BIOME_CHARS[codeA], SColor.contrastLuma(wmv.BIOME_COLOR_TABLE[codeB], wmv.BIOME_COLOR_TABLE[codeA]));
else
display.put(x, y, BIOME_CHARS[codeB], SColor.contrastLuma(wmv.BIOME_COLOR_TABLE[codeA], wmv.BIOME_COLOR_TABLE[codeB]));
}
}
}
for (int i = 0; i < cities.size(); i++) {
Coord ct = cities.keyAt(i);
String cname = cities.getAt(i);
display.put(ct.x, ct.y, '□', SColor.SOOTY_WILLOW_BAMBOO);
// display.put(ct.x, ct.y, '#', SColor.SOOTY_WILLOW_BAMBOO);
display.put(ct.x - (cname.length() >> 1), ct.y - 1, cname, SColor.CW_FADED_YELLOW, SColor.SOOTY_WILLOW_BAMBOO);
}
}
@Override
public void render() {
// standard clear the background routine for libGDX
Gdx.gl.glClearColor(SColor.DB_INK.r, SColor.DB_INK.g, SColor.DB_INK.b, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glDisable(GL20.GL_BLEND);
if(!nextPosition.epsilonEquals(previousPosition)) {
moveAmount = (System.currentTimeMillis() - counter) * 0.001f;
if (moveAmount <= 1f) {
position.set(previousPosition).lerp(nextPosition, moveAmount);
position.set(MathUtils.round(position.x), MathUtils.round(position.y), position.z);
}
else {
previousPosition.set(position);
nextPosition.set(position);
nextPosition.set(MathUtils.round(nextPosition.x), MathUtils.round(nextPosition.y), nextPosition.z);
moveAmount = 0f;
counter = System.currentTimeMillis();
}
}
stage.getCamera().position.set(position);
// need to display the map every frame, since we clear the screen to avoid artifacts.
putMap();
Gdx.graphics.setTitle("Map! Took " + ttg + " ms to generate");
// if we are waiting for the player's input and get input, process it.
if (input.hasNext()) {
input.next();
}
// stage has its own batch and must be explicitly told to draw().
stage.draw();
}
@Override
public void resize(int width, int height) {
super.resize(width, height);
view.update(width, height, true);
view.apply(true);
}
public static CustomConfig config = new CustomConfig("WorldMapTextDemo"){
{
setTitle("SquidLib Demo: Earth-Mimic WorldMap With Text");
setWindowedMode(shownWidth * cellWidth, shownHeight * cellHeight);
useVsync(true);
setIdleFPS(1);
}
@Override
public ApplicationListener instantiate() {
return new WorldMapTextDemo();
}
};
}
| apache-2.0 |
Corporatique-dev/Corporatique | src/com/beust/jcommander/IDefaultProvider.java | 1149 | /**
* Copyright (C) 2010 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.beust.jcommander;
/**
* Allows the specification of default values.
*
* @author cbeust
*/
public interface IDefaultProvider {
/**
* @param optionName The name of the option as specified in the names() attribute
* of the @Parameter option (e.g. "-file").
* @return the default value for this option.
*/
String getDefaultValueFor(String optionName);
}
| apache-2.0 |
dianping/cat | cat-home/src/main/java/com/dianping/cat/report/alert/transaction/TransactionContactor.java | 1212 | /*
* Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dianping.cat.report.alert.transaction;
import com.dianping.cat.alarm.spi.AlertType;
import com.dianping.cat.alarm.spi.receiver.ProjectContactor;
public class TransactionContactor extends ProjectContactor {
public static final String ID = AlertType.Transaction.getName();
@Override
public String getId() {
return ID;
}
}
| apache-2.0 |
sxxlearn2rock/AgileJavaStudy | src/cn/sxx/agilejava/util/DateUtil.java | 443 | package cn.sxx.agilejava.util;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateUtil
{
public static Date createDate(int year, int month, int date)
{
GregorianCalendar calendar = new GregorianCalendar();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DAY_OF_MONTH, date);
return calendar.getTime();
}
}
| apache-2.0 |
Commit451/bypasses | bypass/src/main/java/in/uncod/android/bypass/ImageSpanClickListener.java | 441 | package in.uncod.android.bypass;
import android.text.style.ImageSpan;
import android.view.View;
/**
* Callback when the image span is clicked
*/
public interface ImageSpanClickListener {
/**
* Indicates that an image span has been clicked
*
* @param view the view
* @param imageSpan the imageSpan
* @param span the string
*/
void onImageClicked(View view, ImageSpan imageSpan, String span);
}
| apache-2.0 |
ibuildthecloud/dstack | code/framework/object/src/main/java/io/github/ibuildthecloud/dstack/object/serialization/impl/DefaultObjectSerializerImpl.java | 2931 | package io.github.ibuildthecloud.dstack.object.serialization.impl;
import io.github.ibuildthecloud.dstack.json.JsonMapper;
import io.github.ibuildthecloud.dstack.object.ObjectManager;
import io.github.ibuildthecloud.dstack.object.meta.ObjectMetaDataManager;
import io.github.ibuildthecloud.dstack.object.meta.Relationship;
import io.github.ibuildthecloud.dstack.object.serialization.ObjectSerializer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DefaultObjectSerializerImpl implements ObjectSerializer {
JsonMapper jsonMapper;
ObjectManager objectManager;
ObjectMetaDataManager metaDataManager;
Action action;
String expression;
public DefaultObjectSerializerImpl(JsonMapper jsonMapper, ObjectManager objectManager,
ObjectMetaDataManager metaDataManager, Action action, String expression) {
super();
this.jsonMapper = jsonMapper;
this.objectManager = objectManager;
this.metaDataManager = metaDataManager;
this.action = action;
this.expression = expression;
}
@Override
public Map<String, Object> serialize(Object obj) {
Map<String, Object> data = new HashMap<String, Object>();
data.put(action.getName(), marshall(obj, action.getName(), action));
return data;
}
protected Map<String,Object> marshall(Object obj, String type, Action action) {
Map<String,Object> data = obj == null ? null : jsonMapper.writeValueAsMap(obj);
if ( data != null ) {
data.put("type", type);
}
for ( Action childAction : action.getChildren() ) {
Relationship rel = metaDataManager.getRelationship(type, childAction.getName().toLowerCase());
if ( rel == null ) {
throw new IllegalStateException("Failed to find link for [" + childAction.getName() + "]");
}
Class<?> clz = rel.getObjectType();
String childType = objectManager.getType(clz);
if ( rel.isListResult() ) {
List<Map<String,Object>> childData = new ArrayList<Map<String,Object>>();
for ( Object childObject : objectManager.getListByRelationship(obj, rel) ) {
childData.add(marshall(childObject, childType, childAction));
}
if ( data != null ) {
data.put(rel.getName(), childData);
}
} else {
Object childObject = objectManager.getObjectByRelationship(obj, rel);
Map<String,Object> childData = marshall(childObject, childType, childAction);
if ( data != null ) {
data.put(rel.getName(), childData);
}
}
}
return data;
}
@Override
public String getExpression() {
return expression;
}
}
| apache-2.0 |
pdrados/cas | core/cas-server-core-authentication-attributes/src/test/java/org/apereo/cas/services/ChainingAttributeReleasePolicyTests.java | 4343 | package org.apereo.cas.services;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.util.CollectionUtils;
import lombok.val;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import static org.junit.jupiter.api.Assertions.*;
/**
* This is {@link ChainingAttributeReleasePolicyTests}.
*
* @author Misagh Moayyed
* @since 6.1.0
*/
@Tag("Attributes")
@SpringBootTest(classes = {
RefreshAutoConfiguration.class,
CasCoreUtilConfiguration.class
})
public class ChainingAttributeReleasePolicyTests {
private ChainingAttributeReleasePolicy chain;
@BeforeEach
public void initialize() {
configureChainingReleasePolicy(0, 0);
}
private void configureChainingReleasePolicy(final int order1, final int order2) {
chain = new ChainingAttributeReleasePolicy();
val p1 = new ReturnMappedAttributeReleasePolicy();
p1.setOrder(order1);
p1.setAllowedAttributes(CollectionUtils.wrap("givenName", "groovy {return ['CasUserPolicy1']}"));
val p2 = new ReturnMappedAttributeReleasePolicy();
p2.setOrder(order2);
p2.setAllowedAttributes(CollectionUtils.wrap("givenName", "groovy {return ['CasUserPolicy2']}"));
chain.addPolicies(p1, p2);
}
@Test
public void verifyOperationWithReplaceAndOrder() {
configureChainingReleasePolicy(10, 1);
chain.setMergingPolicy("replace");
val results = chain.getAttributes(CoreAuthenticationTestUtils.getPrincipal(),
CoreAuthenticationTestUtils.getService(),
CoreAuthenticationTestUtils.getRegisteredService());
assertTrue(results.containsKey("givenName"));
val values = CollectionUtils.toCollection(results.get("givenName"));
assertEquals(1, values.size());
assertEquals("CasUserPolicy1", values.iterator().next().toString());
}
@Test
public void verifyOperationWithReplace() {
chain.setMergingPolicy("replace");
val results = chain.getAttributes(CoreAuthenticationTestUtils.getPrincipal(),
CoreAuthenticationTestUtils.getService(),
CoreAuthenticationTestUtils.getRegisteredService());
assertTrue(results.containsKey("givenName"));
val values = CollectionUtils.toCollection(results.get("givenName"));
assertEquals(1, values.size());
assertEquals("CasUserPolicy2", values.iterator().next().toString());
}
@Test
public void verifyOperationWithAdd() {
chain.setMergingPolicy("add");
val results = chain.getAttributes(CoreAuthenticationTestUtils.getPrincipal(),
CoreAuthenticationTestUtils.getService(),
CoreAuthenticationTestUtils.getRegisteredService());
assertTrue(results.containsKey("givenName"));
val values = CollectionUtils.toCollection(results.get("givenName"));
assertEquals(1, values.size());
assertEquals("CasUserPolicy1", values.iterator().next().toString());
}
@Test
public void verifyOperationWithMultivalued() {
chain.setMergingPolicy("multivalued");
val results = chain.getAttributes(CoreAuthenticationTestUtils.getPrincipal(),
CoreAuthenticationTestUtils.getService(),
CoreAuthenticationTestUtils.getRegisteredService());
assertTrue(results.containsKey("givenName"));
val values = CollectionUtils.toCollection(results.get("givenName"));
assertEquals(2, values.size());
assertTrue(values.contains("CasUserPolicy1"));
assertTrue(values.contains("CasUserPolicy2"));
}
@Test
public void verifyConsentableAttrs() {
chain.setMergingPolicy("multivalued");
val results = chain.getConsentableAttributes(CoreAuthenticationTestUtils.getPrincipal(),
CoreAuthenticationTestUtils.getService(),
CoreAuthenticationTestUtils.getRegisteredService());
assertTrue(results.containsKey("givenName"));
val values = CollectionUtils.toCollection(results.get("givenName"));
assertEquals(2, values.size());
}
}
| apache-2.0 |
howepeng/isis | core/runtime/src/main/java/org/apache/isis/core/runtime/system/session/IsisSessionFactory.java | 8032 | /*
* 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.isis.core.runtime.system.session;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.isis.core.commons.authentication.AuthenticationSession;
import org.apache.isis.core.commons.components.ApplicationScopedComponent;
import org.apache.isis.core.commons.config.IsisConfiguration;
import org.apache.isis.core.metamodel.adapter.oid.Oid;
import org.apache.isis.core.metamodel.adapter.oid.OidMarshaller;
import org.apache.isis.core.metamodel.runtimecontext.ServicesInjector;
import org.apache.isis.core.metamodel.services.ServicesInjectorSpi;
import org.apache.isis.core.metamodel.spec.SpecificationLoaderSpi;
import org.apache.isis.core.runtime.authentication.AuthenticationManager;
import org.apache.isis.core.runtime.authorization.AuthorizationManager;
import org.apache.isis.core.runtime.installerregistry.InstallerLookup;
import org.apache.isis.core.runtime.system.DeploymentType;
import org.apache.isis.core.runtime.system.persistence.PersistenceSession;
import org.apache.isis.core.runtime.system.persistence.PersistenceSessionFactory;
import static org.apache.isis.core.commons.ensure.Ensure.ensureThatArg;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
/**
* Analogous (and in essence a wrapper for) a JDO <code>PersistenceManagerFactory</code>
*
* Creates an implementation of
* {@link IsisSessionFactory#openSession(AuthenticationSession)} to create an
* {@link IsisSession}, but delegates to subclasses to actually obtain the
* components that make up that {@link IsisSession}.
*
* <p>
* The idea is that one subclass can use the {@link InstallerLookup} design to
* lookup installers for components (and hence create the components
* themselves), whereas another subclass might simply use Spring (or another DI
* container) to inject in the components according to some Spring-configured
* application context.
*/
public class IsisSessionFactory implements ApplicationScopedComponent {
@SuppressWarnings("unused")
private final static Logger LOG = LoggerFactory.getLogger(IsisSessionFactory.class);
private final DeploymentType deploymentType;
private final IsisConfiguration configuration;
private final SpecificationLoaderSpi specificationLoaderSpi;
private final ServicesInjectorSpi servicesInjector;
private final AuthenticationManager authenticationManager;
private final AuthorizationManager authorizationManager;
private final PersistenceSessionFactory persistenceSessionFactory;
private final OidMarshaller oidMarshaller;
public IsisSessionFactory(
final DeploymentType deploymentType,
final IsisConfiguration configuration,
final ServicesInjectorSpi servicesInjector,
final SpecificationLoaderSpi specificationLoader,
final AuthenticationManager authenticationManager,
final AuthorizationManager authorizationManager,
final PersistenceSessionFactory persistenceSessionFactory) {
ensureThatArg(deploymentType, is(not(nullValue())));
ensureThatArg(configuration, is(not(nullValue())));
ensureThatArg(specificationLoader, is(not(nullValue())));
ensureThatArg(servicesInjector, is(not(nullValue())));
ensureThatArg(authenticationManager, is(not(nullValue())));
ensureThatArg(authorizationManager, is(not(nullValue())));
ensureThatArg(persistenceSessionFactory, is(not(nullValue())));
this.deploymentType = deploymentType;
this.configuration = configuration;
this.specificationLoaderSpi = specificationLoader;
this.authenticationManager = authenticationManager;
this.authorizationManager = authorizationManager;
this.servicesInjector = servicesInjector;
this.persistenceSessionFactory = persistenceSessionFactory;
this.oidMarshaller = new OidMarshaller();
}
public void shutdown() {
persistenceSessionFactory.shutdown();
authenticationManager.shutdown();
specificationLoaderSpi.shutdown();
}
/**
* Creates and {@link IsisSession#open() open}s the {@link IsisSession}.
*/
public IsisSession openSession(final AuthenticationSession authenticationSession) {
final PersistenceSession persistenceSession =
persistenceSessionFactory.createPersistenceSession(
servicesInjector, getSpecificationLoader(), authenticationSession);
ensureThatArg(persistenceSession, is(not(nullValue())));
return newIsisSession(authenticationSession, persistenceSession);
}
protected IsisSession newIsisSession(
final AuthenticationSession authenticationSession,
final PersistenceSession persistenceSession) {
return new IsisSession(this, authenticationSession, persistenceSession);
}
/**
* The {@link ApplicationScopedComponent application-scoped}
* {@link DeploymentType}.
*/
public DeploymentType getDeploymentType() {
return deploymentType;
}
/**
* The {@link ApplicationScopedComponent application-scoped}
* {@link IsisConfiguration}.
*/
public IsisConfiguration getConfiguration() {
return configuration;
}
/**
* The {@link ApplicationScopedComponent application-scoped} {@link ServicesInjector}.
*/
public ServicesInjector getServicesInjector() {
return servicesInjector;
}
/**
* Derived from {@link #getServicesInjector()}.
*
* @deprecated - use {@link #getServicesInjector()} instead.
*/
@Deprecated
public List<Object> getServices() {
return servicesInjector.getRegisteredServices();
}
/**
* The {@link ApplicationScopedComponent application-scoped}
* {@link SpecificationLoaderSpi}.
*/
public SpecificationLoaderSpi getSpecificationLoader() {
return specificationLoaderSpi;
}
/**
* The {@link AuthenticationManager} that will be used to authenticate and
* create {@link AuthenticationSession}s
* {@link IsisSession#getAuthenticationSession() within} the
* {@link IsisSession}.
*/
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
/**
* The {@link AuthorizationManager} that will be used to authorize access to
* domain objects.
*/
public AuthorizationManager getAuthorizationManager() {
return authorizationManager;
}
/**
* The {@link org.apache.isis.core.runtime.system.persistence.PersistenceSessionFactory} that will be used to create
* {@link PersistenceSession} {@link IsisSession#getPersistenceSession()
* within} the {@link IsisSession}.
*/
public PersistenceSessionFactory getPersistenceSessionFactory() {
return persistenceSessionFactory;
}
/**
* The {@link OidMarshaller} to use for marshalling and unmarshalling {@link Oid}s
* into strings.
*/
public OidMarshaller getOidMarshaller() {
return oidMarshaller;
}
}
| apache-2.0 |
lesinsa/horn-soft-pub | commons-2.3/common-jee/src/test/java/ru/prbb/common/cdi/sampleclass/C2.java | 136 | package ru.prbb.common.cdi.sampleclass;
/**
* @author lesinsa on 23.03.14.
*/
public class C2 extends BA implements Intf1, Intf2 {
}
| apache-2.0 |
darranl/directory-shared | ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/normalizers/NumericNormalizer.java | 2681 | /*
* 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.directory.api.ldap.model.schema.normalizers;
import java.io.IOException;
import org.apache.directory.api.i18n.I18n;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.entry.StringValue;
import org.apache.directory.api.ldap.model.entry.Value;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.schema.Normalizer;
import org.apache.directory.api.ldap.model.schema.PrepareString;
/**
* Normalize Numeric Strings
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
@SuppressWarnings("serial")
public class NumericNormalizer extends Normalizer
{
/**
* Creates a new instance of NumericNormalizer.
*/
public NumericNormalizer()
{
super( SchemaConstants.NUMERIC_STRING_MATCH_MR_OID );
}
/**
* {@inheritDoc}
*/
public Value<?> normalize( Value<?> value ) throws LdapException
{
try
{
String normalized = PrepareString.normalize( value.getString(),
PrepareString.StringType.NUMERIC_STRING );
return new StringValue( normalized );
}
catch ( IOException ioe )
{
throw new LdapInvalidDnException( I18n.err( I18n.ERR_04224, value ), ioe );
}
}
/**
* {@inheritDoc}
*/
public String normalize( String value ) throws LdapException
{
try
{
return PrepareString.normalize( value,
PrepareString.StringType.NUMERIC_STRING );
}
catch ( IOException ioe )
{
throw new LdapInvalidDnException( I18n.err( I18n.ERR_04224, value ), ioe );
}
}
} | apache-2.0 |
Wolfgang-Winter/cibet | cibet-core/src/main/java/com/logitags/cibet/actuator/owner/WrongOwnerException.java | 1711 | /*
*******************************************************************************
* L O G I T A G S
* Software and Programming
* Dr. Wolfgang Winter
* Germany
*
* All rights reserved
*
* Copyright 2014 Dr. Wolfgang Winter
*
* 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.logitags.cibet.actuator.owner;
import com.logitags.cibet.core.CibetException;
public class WrongOwnerException extends CibetException {
/**
*
*/
private static final long serialVersionUID = 1L;
private Object offendingEntity;
private String ownerString;
public WrongOwnerException(Object entity, String err, String ownerString) {
super(err);
offendingEntity = entity;
this.ownerString = ownerString;
}
public WrongOwnerException(String err) {
super(err);
}
/**
* @return the offendingEntity
*/
public Object getOffendingEntity() {
return offendingEntity;
}
/**
* @return the ownerString
*/
public String getOwnerString() {
return ownerString;
}
}
| apache-2.0 |
timtish/matrix-world-emulator | core/src/main/java/neo/matrix/reversing/process/EventListener.java | 149 | package neo.matrix.reversing.process;
import neo.matrix.reversing.model.Event;
public interface EventListener {
void onEvent(Event event);
}
| apache-2.0 |
liftting/XmWeiBo | XmWei/app/src/main/java/wm/xmwei/ui/view/lib/TimeLineAvatarImageView.java | 4548 | package wm.xmwei.ui.view.lib;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.ProgressBar;
import wm.xmwei.R;
import wm.xmwei.bean.UserDomain;
import wm.xmwei.ui.view.lib.asyncpicture.IXmDrawable;
import wm.xmwei.util.XmUtils;
/**
*
*
*/
public class TimeLineAvatarImageView extends ImageView implements IXmDrawable {
private Paint paint = new Paint();
private boolean showPressedState = true;
private boolean pressed = false;
private int vType = UserDomain.V_TYPE_NONE;
public TimeLineAvatarImageView(Context context) {
this(context, null);
}
public TimeLineAvatarImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TimeLineAvatarImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initLayout(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Bitmap bitmap;
switch (vType) {
case UserDomain.V_TYPE_PERSONAL:
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.avatar_vip);
canvas.drawBitmap(bitmap, getWidth() - bitmap.getWidth(),
getHeight() - bitmap.getHeight(), paint);
break;
case UserDomain.V_TYPE_ENTERPRISE:
bitmap = BitmapFactory
.decodeResource(getResources(), R.drawable.avatar_enterprise_vip);
canvas.drawBitmap(bitmap, getWidth() - bitmap.getWidth(),
getHeight() - bitmap.getHeight(), paint);
break;
default:
break;
}
if (pressed) {
canvas.drawColor(getResources().getColor(R.color.transparent_cover));
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!showPressedState || !isClickable() || !isLongClickable()) {
return super.onTouchEvent(event);
}
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
pressed = true;
invalidate();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
pressed = false;
invalidate();
break;
}
return super.onTouchEvent(event);
}
protected void initLayout(Context context) {
setPadding(XmUtils.dip2px(5), XmUtils.dip2px(5), XmUtils.dip2px(5), XmUtils.dip2px(5));
}
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
}
@Override
public ImageView getImageView() {
return this;
}
@Override
public void setProgress(int value, int max) {
}
@Override
public ProgressBar getProgressBar() {
return null;
}
@Override
public void setGifFlag(boolean value) {
}
/**
* 检查user级别的
* @param user
*/
public void checkVerified(UserDomain user) {
if (user != null && user.isVerified() && !TextUtils.isEmpty(user.getVerified_reason())) {
if (user.isPersonalV()) {
verifiedPersonal();
} else {
verifiedEnterprise();
}
} else {
reset();
}
}
private void verifiedPersonal() {
if (vType != UserDomain.V_TYPE_PERSONAL) {
vType = UserDomain.V_TYPE_PERSONAL;
invalidate();
}
}
private void verifiedEnterprise() {
if (vType != UserDomain.V_TYPE_ENTERPRISE) {
vType = UserDomain.V_TYPE_ENTERPRISE;
invalidate();
}
}
private void reset() {
if (vType != UserDomain.V_TYPE_NONE) {
vType = UserDomain.V_TYPE_NONE;
invalidate();
}
}
@Override
public void setPressesStateVisibility(boolean value) {
if (showPressedState == value) {
return;
}
showPressedState = value;
invalidate();
}
}
| apache-2.0 |
lgoldstein/communitychest | chest/web/jnlp-servlet/src/main/java/jnlp/sample/servlet/XMLParsing.java | 8061 | /*
* @(#)XMLParsing.java 1.6 05/11/17
*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution 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 Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
package jnlp.sample.servlet;
import java.util.Collection;
import java.util.LinkedList;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
/** Contains handy methods for looking up information
* stored in XMLNodes.
*/
public final class XMLParsing {
private XMLParsing ()
{
// no instance
}
public static XMLNode convert (Node n)
{
if (n == null)
return null;
else if (n instanceof Text)
return new XMLNode(((Text)n).getNodeValue());
else if (n instanceof Element)
{
final Element en=(Element) n;
final NamedNodeMap attributes=en.getAttributes();
final int numAttrs=(null == attributes) ? 0 : attributes.getLength();
XMLAttribute xmlatts=null;
for (int i =numAttrs - 1; i >= 0; i--)
{
final Attr ar=(Attr) attributes.item(i);
xmlatts = new XMLAttribute(ar.getName(), ar.getValue(), xmlatts);
}
// Convert children
XMLNode thisNode=new XMLNode(en.getNodeName(), xmlatts, null, null), last = null;
for (Node nn=en.getFirstChild(); nn != null; nn=nn.getNextSibling())
{
if (thisNode.getNested() == null)
{
last = convert(nn);
thisNode.setNested(last);
}
else
{
XMLNode nnode = convert(nn);
last.setNext(nnode);
last = nnode;
}
last.setParent(thisNode);
}
return thisNode;
}
return null;
}
/* Returns true if the path exists in the document, otherwise false */
static public boolean isElementPath (XMLNode root, String path)
{
return findElementPath(root, path) != null;
}
/* Returns a string describing the current location in the DOM */
static public String getPathString (XMLNode e)
{
return (e == null || !(e.isElement())) ? "" : getPathString(e.getParent()) + "<" + e.getName() + ">";
}
/* Like getElementContents(...) but with a defaultValue of null */
static public String getElementContent (XMLNode root, String path)
{
return getElementContent(root, path, null);
}
/* Like getElementContents(...) but with a defaultValue of null */
static public String[] getMultiElementContent (XMLNode root, String path)
{
final Collection<String> list=new LinkedList<String>();
visitElements(root, path, new ElementVisitor() {
/*
* @see jnlp.sample.servlet.XMLParsing.ElementVisitor#visitElement(jnlp.sample.servlet.XMLNode)
*/
@Override
public void visitElement(XMLNode n)
{
final String value=getElementContent(n, "");
if ((value == null) || (value.length() <= 0))
return;
list.add(value);
}
});
if (list.size() <= 0)
return null;
return list.toArray(new String[list.size()]);
}
/* Returns the value of the last element tag in the path, e.g., <..><tag>value</tag>. The DOM is assumes
* to be normalized. If no value is found, the default value is returned
*/
static public String getElementContent (XMLNode root, String path, String defaultvalue)
{
final XMLNode e=findElementPath(root, path);
if (e == null)
return defaultvalue;
final XMLNode n=e.getNested();
if ((n != null) && (!n.isElement()))
return n.getName();
return defaultvalue;
}
/* Parses a path string of the form <tag1><tag2><tag3> and returns the specific Element
* node for that tag, or null if it does not exist. If multiple elements exists with same
* path the first is returned
*/
static public XMLNode findElementPath (XMLNode elem, String path)
{
// End condition. Root null -> path does not exist
if (elem == null)
return null;
// End condition. String empty, return current root
if ((path == null) || (path.length() <= 0))
return elem;
// Strip off first tag
final int idx=path.indexOf('>');
final String head=path.substring(1, idx), tail=path.substring(idx + 1);
return findElementPath(findChildElement(elem, head), tail);
}
/* Returns an child element with the current tag name or null. */
static public XMLNode findChildElement (XMLNode elem, String tag)
{
for (XMLNode n=(null == elem) ? null : elem.getNested(); n != null; n = n.getNext())
{
if (n.isElement() && tag.equalsIgnoreCase(n.getName()))
return n;
}
return null;
}
/** Iterator class */
public static interface ElementVisitor {
void visitElement (XMLNode e);
}
/* Visits all elements which matches the <path>. The iteration is only
* done on the last elment in the path.
*/
static public void visitElements (XMLNode root, String path, ElementVisitor ev)
{
// Get last element in path
final int idx=path.lastIndexOf('<');
final String head=path.substring(0, idx), tag=path.substring(idx + 1, path.length() - 1);
final XMLNode elem=findElementPath(root, head);
// Iterate through all child nodes
for (XMLNode n=(null == elem) ? null : elem.getNested(); n != null; n=n.getNext())
{
if (n.isElement() && tag.equalsIgnoreCase(n.getName()))
ev.visitElement(n);
}
}
static public void visitChildrenElements (XMLNode elem, ElementVisitor ev)
{
// Iterate through all child nodes
for (XMLNode n=(null == elem) ? null : elem.getNested(); n != null; n=n.getNext())
{
if (n.isElement())
ev.visitElement(n);
}
}
}
| apache-2.0 |
zhangdaiscott/jeewx-api | src/main/java/org/jeewx/api/coupon/location/model/Cash.java | 681 | package org.jeewx.api.coupon.location.model;
public class Cash {
//基本的卡券
private BaseInfo base_info;
//代金券专用,表示起用金额
private Double least_cost;
//代金券专用,表示减免金额
private Double reduce_cost;
public BaseInfo getBase_info() {
return base_info;
}
public void setBase_info(BaseInfo base_info) {
this.base_info = base_info;
}
public Double getLeast_cost() {
return least_cost;
}
public void setLeast_cost(Double least_cost) {
this.least_cost = least_cost;
}
public Double getReduce_cost() {
return reduce_cost;
}
public void setReduce_cost(Double reduce_cost) {
this.reduce_cost = reduce_cost;
}
}
| apache-2.0 |
cheng-li/pyramid | core/src/main/java/edu/neu/ccs/pyramid/regression/p_boost/PBoostOptimizer.java | 3271 | package edu.neu.ccs.pyramid.regression.p_boost;
import edu.neu.ccs.pyramid.dataset.DataSet;
import edu.neu.ccs.pyramid.dataset.RegDataSet;
import edu.neu.ccs.pyramid.optimization.gradient_boosting.GBOptimizer;
import edu.neu.ccs.pyramid.optimization.gradient_boosting.GradientBoosting;
import edu.neu.ccs.pyramid.regression.ConstantRegressor;
import edu.neu.ccs.pyramid.regression.Regressor;
import edu.neu.ccs.pyramid.regression.RegressorFactory;
import edu.neu.ccs.pyramid.util.MathUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Arrays;
import java.util.stream.IntStream;
/**
* Created by chengli on 10/8/16.
*/
public class PBoostOptimizer extends GBOptimizer {
private static final Logger logger = LogManager.getLogger();
private double[] labels;
public PBoostOptimizer(GradientBoosting boosting, DataSet dataSet, RegressorFactory factory, double[] weights, double[] labels) {
super(boosting, dataSet, factory, weights);
this.labels = labels;
}
public PBoostOptimizer(GradientBoosting boosting, DataSet dataSet, RegressorFactory factory, double[] labels) {
super(boosting, dataSet, factory);
this.labels = labels;
}
public PBoostOptimizer(GradientBoosting boosting, RegDataSet dataSet, RegressorFactory factory) {
this(boosting, dataSet, factory, dataSet.getLabels());
}
@Override
protected void addPriors() {
double average = IntStream.range(0,dataSet.getNumDataPoints()).parallel().mapToDouble(i-> labels[i]*weights[i]).average().getAsDouble();
Regressor constant = new ConstantRegressor(average);
boosting.getEnsemble(0).add(constant);
}
@Override
protected double[] gradient(int ensembleIndex) {
int n = dataSet.getNumDataPoints();
double labelAve = MathUtil.arraySum(labels)/n;
double[] pred = IntStream.range(0, n).mapToDouble(i->scoreMatrix.getScoresForData(i)[0]).toArray();
double predAve = MathUtil.arraySum(pred)/n;
double[] labelDev = IntStream.range(0, n).mapToDouble(i->labels[i]-labelAve).toArray();
double[] predDev = IntStream.range(0, n).mapToDouble(i->pred[i]-predAve).toArray();
double labelDevAve = MathUtil.arraySum(labelDev)/n;
double predDevAve = MathUtil.arraySum(predDev)/n;
double product = IntStream.range(0, n).mapToDouble(i->predDev[i]*labelDev[i]).sum();
double sigmaSquqre = IntStream.range(0, n).mapToDouble(i->Math.pow(predDev[i],2)).sum();
if (sigmaSquqre==0){
sigmaSquqre= 1;
}
double sigma = Math.sqrt(sigmaSquqre);
//todo second order; to fix vannishing gradient
double[] gradient = new double[n];
for (int i=0;i<n;i++){
double g = (labelDev[i]-labelDevAve)*sigma - 1/sigma*(product*(predDev[i]-predDevAve));
g = g/sigmaSquqre;
gradient[i] = g;
}
// System.out.println("-----------------------------");
// System.out.println(Arrays.toString(gradient));
return gradient;
}
@Override
protected void initializeOthers() {
return;
}
@Override
protected void updateOthers() {
return;
}
}
| apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p494/Production9895.java | 1891 | package org.gradle.test.performance.mediummonolithicjavaproject.p494;
public class Production9895 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | apache-2.0 |
gawkermedia/googleads-java-lib | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201511/AdExclusionRule.java | 19528 | /**
* AdExclusionRule.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201511;
/**
* Represents an inventory blocking rule, which prevents certain ads
* from being
* served to specified ad units.
*/
public class AdExclusionRule implements java.io.Serializable {
/* The unique ID of the {@code AdExclusionRule}. This attribute
* is readonly and is assigned
* by Google. */
private java.lang.Long id;
/* The name of the {@code AdExclusionRule}. This attribute is
* required. */
private java.lang.String name;
/* Whether or not the {@code AdExclusionRule} is active. An inactive
* rule will have no
* effect on adserving. This attribute is readonly. */
private java.lang.Boolean isActive;
/* The targeting information about which {@link AdUnitTargeting}
* objects this rule is in effect
* for. Any {@link AdUnitTargeting} objects included
* here will have their children included
* implicitly. Children of a targeted ad unit can be
* excluded. This attribute is required. */
private com.google.api.ads.dfp.axis.v201511.InventoryTargeting inventoryTargeting;
/* Whether or not this rule blocks all ads from serving other
* than the labels or advertisers
* specified. This attribute is optional and defaults
* to false. */
private java.lang.Boolean isBlockAll;
/* The labels that will be blocked from serving. Any advertiser,
* order or line item
* with one of these labels will not serve on the relevant
* ad units and their children. */
private long[] blockedLabelIds;
/* The allowed list of labels that will not be blocked by this
* rule. This trumps the values of
* {@link #isBlockAllLabels} and {@link #blockedLabelIds}.
* For example, if a rule specifies
* a blocked label "Cars", and an allowed label "Sports",
* any ad that is labeled both
* "Sports" and "Cars" will not be blocked by this rule. */
private long[] allowedLabelIds;
/* The derived type of this rule: whether it is associated with
* labels, unified entities,
* or competitive groups. Because it is derived, it
* is also read-only, so changes made to this
* field will not be persisted. */
private com.google.api.ads.dfp.axis.v201511.AdExclusionRuleType type;
public AdExclusionRule() {
}
public AdExclusionRule(
java.lang.Long id,
java.lang.String name,
java.lang.Boolean isActive,
com.google.api.ads.dfp.axis.v201511.InventoryTargeting inventoryTargeting,
java.lang.Boolean isBlockAll,
long[] blockedLabelIds,
long[] allowedLabelIds,
com.google.api.ads.dfp.axis.v201511.AdExclusionRuleType type) {
this.id = id;
this.name = name;
this.isActive = isActive;
this.inventoryTargeting = inventoryTargeting;
this.isBlockAll = isBlockAll;
this.blockedLabelIds = blockedLabelIds;
this.allowedLabelIds = allowedLabelIds;
this.type = type;
}
/**
* Gets the id value for this AdExclusionRule.
*
* @return id * The unique ID of the {@code AdExclusionRule}. This attribute
* is readonly and is assigned
* by Google.
*/
public java.lang.Long getId() {
return id;
}
/**
* Sets the id value for this AdExclusionRule.
*
* @param id * The unique ID of the {@code AdExclusionRule}. This attribute
* is readonly and is assigned
* by Google.
*/
public void setId(java.lang.Long id) {
this.id = id;
}
/**
* Gets the name value for this AdExclusionRule.
*
* @return name * The name of the {@code AdExclusionRule}. This attribute is
* required.
*/
public java.lang.String getName() {
return name;
}
/**
* Sets the name value for this AdExclusionRule.
*
* @param name * The name of the {@code AdExclusionRule}. This attribute is
* required.
*/
public void setName(java.lang.String name) {
this.name = name;
}
/**
* Gets the isActive value for this AdExclusionRule.
*
* @return isActive * Whether or not the {@code AdExclusionRule} is active. An inactive
* rule will have no
* effect on adserving. This attribute is readonly.
*/
public java.lang.Boolean getIsActive() {
return isActive;
}
/**
* Sets the isActive value for this AdExclusionRule.
*
* @param isActive * Whether or not the {@code AdExclusionRule} is active. An inactive
* rule will have no
* effect on adserving. This attribute is readonly.
*/
public void setIsActive(java.lang.Boolean isActive) {
this.isActive = isActive;
}
/**
* Gets the inventoryTargeting value for this AdExclusionRule.
*
* @return inventoryTargeting * The targeting information about which {@link AdUnitTargeting}
* objects this rule is in effect
* for. Any {@link AdUnitTargeting} objects included
* here will have their children included
* implicitly. Children of a targeted ad unit can be
* excluded. This attribute is required.
*/
public com.google.api.ads.dfp.axis.v201511.InventoryTargeting getInventoryTargeting() {
return inventoryTargeting;
}
/**
* Sets the inventoryTargeting value for this AdExclusionRule.
*
* @param inventoryTargeting * The targeting information about which {@link AdUnitTargeting}
* objects this rule is in effect
* for. Any {@link AdUnitTargeting} objects included
* here will have their children included
* implicitly. Children of a targeted ad unit can be
* excluded. This attribute is required.
*/
public void setInventoryTargeting(com.google.api.ads.dfp.axis.v201511.InventoryTargeting inventoryTargeting) {
this.inventoryTargeting = inventoryTargeting;
}
/**
* Gets the isBlockAll value for this AdExclusionRule.
*
* @return isBlockAll * Whether or not this rule blocks all ads from serving other
* than the labels or advertisers
* specified. This attribute is optional and defaults
* to false.
*/
public java.lang.Boolean getIsBlockAll() {
return isBlockAll;
}
/**
* Sets the isBlockAll value for this AdExclusionRule.
*
* @param isBlockAll * Whether or not this rule blocks all ads from serving other
* than the labels or advertisers
* specified. This attribute is optional and defaults
* to false.
*/
public void setIsBlockAll(java.lang.Boolean isBlockAll) {
this.isBlockAll = isBlockAll;
}
/**
* Gets the blockedLabelIds value for this AdExclusionRule.
*
* @return blockedLabelIds * The labels that will be blocked from serving. Any advertiser,
* order or line item
* with one of these labels will not serve on the relevant
* ad units and their children.
*/
public long[] getBlockedLabelIds() {
return blockedLabelIds;
}
/**
* Sets the blockedLabelIds value for this AdExclusionRule.
*
* @param blockedLabelIds * The labels that will be blocked from serving. Any advertiser,
* order or line item
* with one of these labels will not serve on the relevant
* ad units and their children.
*/
public void setBlockedLabelIds(long[] blockedLabelIds) {
this.blockedLabelIds = blockedLabelIds;
}
public long getBlockedLabelIds(int i) {
return this.blockedLabelIds[i];
}
public void setBlockedLabelIds(int i, long _value) {
this.blockedLabelIds[i] = _value;
}
/**
* Gets the allowedLabelIds value for this AdExclusionRule.
*
* @return allowedLabelIds * The allowed list of labels that will not be blocked by this
* rule. This trumps the values of
* {@link #isBlockAllLabels} and {@link #blockedLabelIds}.
* For example, if a rule specifies
* a blocked label "Cars", and an allowed label "Sports",
* any ad that is labeled both
* "Sports" and "Cars" will not be blocked by this rule.
*/
public long[] getAllowedLabelIds() {
return allowedLabelIds;
}
/**
* Sets the allowedLabelIds value for this AdExclusionRule.
*
* @param allowedLabelIds * The allowed list of labels that will not be blocked by this
* rule. This trumps the values of
* {@link #isBlockAllLabels} and {@link #blockedLabelIds}.
* For example, if a rule specifies
* a blocked label "Cars", and an allowed label "Sports",
* any ad that is labeled both
* "Sports" and "Cars" will not be blocked by this rule.
*/
public void setAllowedLabelIds(long[] allowedLabelIds) {
this.allowedLabelIds = allowedLabelIds;
}
public long getAllowedLabelIds(int i) {
return this.allowedLabelIds[i];
}
public void setAllowedLabelIds(int i, long _value) {
this.allowedLabelIds[i] = _value;
}
/**
* Gets the type value for this AdExclusionRule.
*
* @return type * The derived type of this rule: whether it is associated with
* labels, unified entities,
* or competitive groups. Because it is derived, it
* is also read-only, so changes made to this
* field will not be persisted.
*/
public com.google.api.ads.dfp.axis.v201511.AdExclusionRuleType getType() {
return type;
}
/**
* Sets the type value for this AdExclusionRule.
*
* @param type * The derived type of this rule: whether it is associated with
* labels, unified entities,
* or competitive groups. Because it is derived, it
* is also read-only, so changes made to this
* field will not be persisted.
*/
public void setType(com.google.api.ads.dfp.axis.v201511.AdExclusionRuleType type) {
this.type = type;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof AdExclusionRule)) return false;
AdExclusionRule other = (AdExclusionRule) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.id==null && other.getId()==null) ||
(this.id!=null &&
this.id.equals(other.getId()))) &&
((this.name==null && other.getName()==null) ||
(this.name!=null &&
this.name.equals(other.getName()))) &&
((this.isActive==null && other.getIsActive()==null) ||
(this.isActive!=null &&
this.isActive.equals(other.getIsActive()))) &&
((this.inventoryTargeting==null && other.getInventoryTargeting()==null) ||
(this.inventoryTargeting!=null &&
this.inventoryTargeting.equals(other.getInventoryTargeting()))) &&
((this.isBlockAll==null && other.getIsBlockAll()==null) ||
(this.isBlockAll!=null &&
this.isBlockAll.equals(other.getIsBlockAll()))) &&
((this.blockedLabelIds==null && other.getBlockedLabelIds()==null) ||
(this.blockedLabelIds!=null &&
java.util.Arrays.equals(this.blockedLabelIds, other.getBlockedLabelIds()))) &&
((this.allowedLabelIds==null && other.getAllowedLabelIds()==null) ||
(this.allowedLabelIds!=null &&
java.util.Arrays.equals(this.allowedLabelIds, other.getAllowedLabelIds()))) &&
((this.type==null && other.getType()==null) ||
(this.type!=null &&
this.type.equals(other.getType())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getId() != null) {
_hashCode += getId().hashCode();
}
if (getName() != null) {
_hashCode += getName().hashCode();
}
if (getIsActive() != null) {
_hashCode += getIsActive().hashCode();
}
if (getInventoryTargeting() != null) {
_hashCode += getInventoryTargeting().hashCode();
}
if (getIsBlockAll() != null) {
_hashCode += getIsBlockAll().hashCode();
}
if (getBlockedLabelIds() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getBlockedLabelIds());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getBlockedLabelIds(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getAllowedLabelIds() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getAllowedLabelIds());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getAllowedLabelIds(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getType() != null) {
_hashCode += getType().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(AdExclusionRule.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "AdExclusionRule"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("id");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "id"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("name");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "name"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("isActive");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "isActive"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("inventoryTargeting");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "inventoryTargeting"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "InventoryTargeting"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("isBlockAll");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "isBlockAll"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("blockedLabelIds");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "blockedLabelIds"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("allowedLabelIds");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "allowedLabelIds"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("type");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "type"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "AdExclusionRuleType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
crow-misia/xmlbeans | src/xmlpublic/org/apache/xmlbeans/XmlCursor.java | 69754 | /* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xmlbeans;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.Map;
import javax.xml.namespace.QName;
/**
* Represents a position between two logical tokens in an XML document.
*
* The tokens themselves are not exposed as objects, but their type and properties
* are discoverable through methods on the cursor. In particular, the general
* category of token is represented by a {@link XmlCursor.TokenType TokenType}.<br/><br/>
*
* You use an XmlCursor instance to navigate through and manipulate an XML
* instance document.
* Once you obtain an XML document, you can create a cursor to represent
* a specific place in the XML. Because you can use a cursor with or
* without a schema corresponding to the XML, cursors are an ideal
* way to handle XML without a schema. You can create a new cursor by
* calling the {@link XmlTokenSource#newCursor() newCursor} method
* exposed by an object representing
* the XML, whether it was parsed into a strong type compiled from
* schema or an {@link XmlObject XmlObject} (as in the no-schema case).<br/><br/>
*
* With an XmlCursor, you can also: <br/><br/>
*
* <ul>
* <li>Execute XQuery and XPath expressions against the XML with the
* execQuery and selectPath methods.</li>
*
* <li>Edit and reshape the document by inserting, moving, copying, and removing
* XML.</li>
*
* <li>Insert bookmarks that "stick" to the XML at the cursor's
* position even if the cursor or XML moves.</li>
* <li>Get and set values for containers (elements and whole documents),
* attributes, processing instructions, and comments.</li>
* </ul>
*
* A cursor moves through XML by moving past tokens. A
* token represents a category of XML markup, such as the start of an element,
* its end, an attribute, comment, and so on. XmlCursor methods such as
* toNextToken, toNextSibling, toParent, and so on move the cursor
* among tokens. Each token's category is of a particular <em>type</em>, represented
* by one of the nine types defined by the {@link XmlCursor.TokenType TokenType} class. <br/><br/>
*
* When you get a new cursor for a whole instance document, the cursor is
* intially located before the STARTDOC token. This token, which has no analogy
* in the XML specification, is present in this logical model of XML
* so that you may distinguish between the document as a whole
* and the content of the document. Terminating the document is an ENDDOC
* token. This token is also not part of the XML specification. A cursor
* located immediately before this token is at the very end of the document.
* It is not possible to position the cursor after the ENDDOC token.
* Thus, the STARTDOC and ENDDOC tokens are effectively "bookends" for the content of
* the document.<br/><br/>
*
* For example, for the following XML, if you were the navigate a cursor
* through the XML document using toNextToken(), the list of token types that
* follows represents the token sequence you would encounter. <br/><br/>
*
* <pre>
* <sample x='y'>
* <value>foo</value>
* </sample>
* </pre>
*
* STARTDOC <br/>
* START (sample) <br/>
* ATTR (x='y') <br/>
* TEXT ("\n ") <br/>
* START (value) <br/>
* TEXT ("foo") <br/>
* END (value) <br/>
* TEXT ("\n") <br/>
* END (sample)<br/>
* ENDDOC <br/><br/>
*
* When there are no more tokens available, hasNextToken() returns
* false and toNextToken() returns the special token type NONE and does not move
* the cursor.
* <br/><br/>
*
* The {@link #currentTokenType() currentTokenType()} method
* will return the type of the token that is immediately after the cursor.
* You can also use a number of convenience methods that test for a particular
* token type. These include the methods isStart(),
* isStartdoc(), isText(), isAttr(), and so on. Each returns a boolean
* value indicating whether the token that follows the cursor is the type
* in question.
* <br/><br/>
*
* A few other methods determine whether the token is of a kind that may include
* multiple token types. The isAnyAttr() method, for example, returns true if
* the token immediately following the cursor is any kind of attribute,
* including those of the ATTR token type and xmlns attributes.
* <br/><br/>
*
* Legitimate sequences of tokens for an XML document are described
* by the following Backus-Naur Form (BNF): <br/>
*
* <pre>
* <doc> ::= STARTDOC <attributes> <content> ENDDOC
* <element> ::= START <attributes> <content> END
* <attributes> ::= ( ATTR | NAMESPACE ) *
* <content> ::= ( COMMENT | PROCINST | TEXT | <element> ) *
* </pre>
*
* Note that a legitimate sequence is STARTDOC ENDDOC, the result of
* creating a brand new instance of an empty document. Also note that
* attributes may only follow container tokens (STARTDOC or START)
*/
public interface XmlCursor extends XmlTokenSource
{
/**
* An enumeration that identifies the type of an XML token.
*/
public static final class TokenType
{
public String toString ( ) { return _name; }
/**
* Returns one of the INT_ values defined in this class.
*/
public int intValue ( ) { return _value; }
/** No token. See {@link #intValue}. */
public static final int INT_NONE = 0;
/** The start-document token. See {@link #intValue}. */
public static final int INT_STARTDOC = 1;
/** The end-document token. See {@link #intValue}. */
public static final int INT_ENDDOC = 2;
/** The start-element token. See {@link #intValue}. */
public static final int INT_START = 3;
/** The end-element token. See {@link #intValue}. */
public static final int INT_END = 4;
/** The text token. See {@link #intValue}. */
public static final int INT_TEXT = 5;
/** The attribute token. See {@link #intValue}. */
public static final int INT_ATTR = 6;
/** The namespace declaration token. See {@link #intValue}. */
public static final int INT_NAMESPACE = 7;
/** The comment token. See {@link #intValue}. */
public static final int INT_COMMENT = 8;
/** The processing instruction token. See {@link #intValue}. */
public static final int INT_PROCINST = 9;
/** True if no token. */
public boolean isNone ( ) { return this == NONE; }
/** True if is start-document token. */
public boolean isStartdoc ( ) { return this == STARTDOC; }
/** True if is end-document token. */
public boolean isEnddoc ( ) { return this == ENDDOC; }
/** True if is start-element token. */
public boolean isStart ( ) { return this == START; }
/** True if is end-element token. */
public boolean isEnd ( ) { return this == END; }
/** True if is text token. */
public boolean isText ( ) { return this == TEXT; }
/** True if is attribute token. */
public boolean isAttr ( ) { return this == ATTR; }
/** True if is namespace declaration token. */
public boolean isNamespace ( ) { return this == NAMESPACE; }
/** True if is comment token. */
public boolean isComment ( ) { return this == COMMENT; }
/** True if is processing instruction token. */
public boolean isProcinst ( ) { return this == PROCINST; }
/** True if is start-document or start-element token */
public boolean isContainer ( ) { return this == STARTDOC || this == START; }
/** True if is end-document or end-element token */
public boolean isFinish ( ) { return this == ENDDOC || this == END; }
/** True if is attribute or namespace declaration token */
public boolean isAnyAttr ( ) { return this == NAMESPACE || this == ATTR; }
/** The singleton no-token type */
public static final TokenType NONE = new TokenType( "NONE", INT_NONE );
/** The singleton start-document token type */
public static final TokenType STARTDOC = new TokenType( "STARTDOC", INT_STARTDOC );
/** The singleton start-document token type */
public static final TokenType ENDDOC = new TokenType( "ENDDOC", INT_ENDDOC );
/** The singleton start-element token type */
public static final TokenType START = new TokenType( "START", INT_START );
/** The singleton end-element token type */
public static final TokenType END = new TokenType( "END", INT_END );
/** The singleton text token type */
public static final TokenType TEXT = new TokenType( "TEXT", INT_TEXT );
/** The singleton attribute token type */
public static final TokenType ATTR = new TokenType( "ATTR", INT_ATTR );
/** The singleton namespace declaration token type */
public static final TokenType NAMESPACE = new TokenType( "NAMESPACE", INT_NAMESPACE );
/** The singleton comment token type */
public static final TokenType COMMENT = new TokenType( "COMMENT", INT_COMMENT );
/** The singleton processing instruction token type */
public static final TokenType PROCINST = new TokenType( "PROCINST", INT_PROCINST );
private TokenType ( String name, int value )
{
_name = name;
_value = value;
}
private String _name;
private int _value;
}
/**
* Deallocates resources needed to manage the cursor, rendering this cursor
* inoperable. Because cursors are managed by a mechanism which stores the
* XML, simply letting a cursor go out of scope and having the garbage collector
* attempt to reclaim it may not produce desirable performance.<br/><br/>
*
* So, explicitly disposing a cursor allows the underlying implementation
* to release its responsibility of maintaining its position.<br/><br/>
*
* After a cursor has been disposed, it may not be used again. It can
* throw IllegalStateException or NullPointerException if used after
* disposal.<br/><br/>
*/
void dispose ( );
/**
* Moves this cursor to the same position as the moveTo cursor. if the
* moveTo cursor is in a different document from this cursor, this cursor
* will not be moved, and false returned.
*
* @param moveTo The cursor at the location to which this cursor
* should be moved.
* @return true if the cursor moved; otherwise, false.
*/
boolean toCursor ( XmlCursor moveTo );
/**
* Saves the current location of this cursor on an internal stack of saved
* positions (independent of selection). This location may be restored
* later by calling the pop() method.
*/
void push ( );
/**
* Restores the cursor location most recently saved with the push() method.
*
* @return true if there was a location to restore; otherwise, false.
*/
boolean pop ( );
/**
* Executes the specified XPath expression against the XML that this
* cursor is in. The cursor's position does not change. To navigate to the
* selections, use {@link #hasNextSelection} and {@link #toNextSelection} (similar to
* {@link java.util.Iterator}).<br/><br/>
*
* The root referred to by the expression should be given as
* a dot. The following is an example path expression:
* <pre>
* cursor.selectPath("./purchase-order/line-item");
* </pre>
*
* Note that this method does not support top-level XPath functions.
*
* @param path The path expression to execute.
* @throws XmlRuntimeException If the query expression is invalid.
*/
void selectPath ( String path );
/**
* Executes the specified XPath expression against the XML that this
* cursor is in. The cursor's position does not change. To navigate to the
* selections, use hasNextSelection and toNextSelection (similar to
* java.util.Iterator).<br/><br/>
*
* The root referred to by the expression should be given as
* a dot. The following is an example path expression:
* <pre>
* cursor.selectPath("./purchase-order/line-item");
* </pre>
*
* Note that this method does not support top-level XPath functions.
*
* @param path The path expression to execute.
* @param options Options for the query. For example, you can call
* the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
* method to specify a particular name for the query expression
* variable that indicates the context node.
* @throws XmlRuntimeException If the query expression is invalid.
*/
void selectPath ( String path, XmlOptions options );
/**
* Returns whether or not there is a next selection.
*
* @return true if there is a next selection; otherwise, false.
*/
boolean hasNextSelection ( );
/**
* Moves this cursor to the next location in the selection,
* if any. See the {@link #selectPath} and {@link #addToSelection} methods.
*
* @return true if the cursor moved; otherwise, false.
*/
boolean toNextSelection ( );
/**
* Moves this cursor to the specified location in the selection.
* If i is less than zero or greater than or equal to the selection
* count, this method returns false.
*
* See also the selectPath() and addToSelection() methods.
*
* @param i The index of the desired location.
* @return true if the cursor was moved; otherwise, false.
*/
boolean toSelection ( int i );
/**
* Returns the count of the current selection. See also the selectPath()
* and addToSelection() methods.
*
* You may experience better performance if you use the iteration
* model using the toNextSelection method, rather than
* the indexing model using the getSelectionCount and
* toSelection methods.
*
* @return A number indicating the size of the current selection.
*/
int getSelectionCount ( );
/**
* Appends the current location of the cursor to the selection.
* See also the selectPath() method. You can use this as an
* alternative to calling the selectPath method when you want
* to define your own selection.
*/
void addToSelection ( );
/**
* Clears this cursor's selection, but does not modify the document.
*/
void clearSelections ( );
/**
* Moves this cursor to the same position as the bookmark. If the
* bookmark is in a different document from this cursor or if the
* bookmark is orphaned, this cursor
* will not be moved, and false will be returned.
*
* @param bookmark The bookmark at the location to which this
* cursor should be moved.
* @return true if the cursor moved; otherwise, false.
*/
boolean toBookmark ( XmlBookmark bookmark );
/**
* Moves this cursor to the location after its current position
* where a bookmark with the given key exists. Returns false if no
* such bookmark exists.
*
* @param key The key held by the next bookmark at the location to
* which this cursor should be moved.
* @return The next corresponding bookmark, if it exists; null if there
* is no next bookmark with the specified key.
*/
XmlBookmark toNextBookmark ( Object key );
/**
* Moves this cursor to the location before its current position
* where a bookmark with the given key exists. Returns false if no
* such bookmark exists.
*
* @param key The key held by the previous bookmark at the location to
* which this cursor should be moved.
* @return The previous corresponding bookmark, if it exists; null if
* there is no previous bookmark with the specified key.
*/
XmlBookmark toPrevBookmark ( Object key );
/**
* Returns the name of the current token. Names may be associated with
* START, ATTR, NAMESPACE or PROCINST. Returns null if there is no
* name associated with the current token. For START and ATTR, the
* name returned identifies the name of the element or attribute.
* For NAMESPACE, the local part of the name is the prefix, while
* the URI is the namespace defined. For PROCINST, the local part
* is the target and the uri is "".
* <p>
* In the following example, <code>xmlObject</code> represents
* an XML instance whose root element is not preceded by any other XML.
* This code prints the root element name (here, the local name, or
* name without URI).
* <pre>
* XmlCursor cursor = xmlObject.newCursor();
* cursor.toFirstContentToken();
* String elementName = cursor.getName().getLocalPart();
* System.out.println(elementName);
* </pre>
*
* @return The name of the XML at this cursor's location; null if there
* is no name.
*/
QName getName ( );
/**
* Sets the name of the current token. This token can be START, NAMESPACE,
* ATTR or PROCINST.
*
* @param name The new name for the current token.
*/
void setName ( QName name );
/**
* Returns the namespace URI indicated by the given prefix. The current
* context must be at a START or STARTDOC. Namespace prefix mappings
* are queried for the mappings defined at the current container first,
* then parents are queried. The prefix can be "" or null to indicate
* a search for the default namespace. To conform with the
* XML spec, the default namespace will return the no-namespace ("")
* if it is not mapped.<br/><br/>
*
* Note that this queries the current state of the document. When the
* document is persisted, the saving mechanism may synthesize namespaces
* (ns1, ns2, and so on) for the purposes of persistence. These namepaces are
* only present in the serialized form, and are not reflected back into
* the document being saved.
*
* @param prefix The namespace prefix for the requested namespace.
* @return The URI for corresponding to the specified prefix if it
* exists; otherwise, null.
*/
String namespaceForPrefix ( String prefix );
/**
* Returns a prefix that can be used to indicate a namespace URI. The
* current context must be at a START or STARTDOC. If there is an
* existing prefix that indicates the URI in the current context, that
* prefix may be returned. Otherwise, a new prefix for the URI will be
* defined by adding an xmlns attribute to the current container or a
* parent container.
*
* Note that this queries the current state of the document. When the
* document is persisted, the saving mechanism may synthesize namespaces
* (ns1, ns2, and so on) for the purposes of persistence. These namepaces are
* only present in the serialized form, and are not reflected back into
* the document being saved.
*
* @param namespaceURI The namespace URI corresponding to the requested
* prefix.
* @return The prefix corresponding to the specified URI if it exists;
* otherwise, a newly generated prefix.
*/
String prefixForNamespace ( String namespaceURI );
/**
* Adds to the specified map, all the namespaces in scope at the container
* where this cursor is positioned. This method is useful for
* container tokens only.
*
* @param addToThis The Map to add the namespaces to.
*/
void getAllNamespaces ( Map addToThis );
/**
* Returns the strongly-typed XmlObject at the current START,
* STARTDOC, or ATTR. <br/><br/>
*
* The strongly-typed object can be cast to the strongly-typed
* XBean interface corresponding to the XML Schema Type given
* by result.getSchemaType().<br/><br/>
*
* If a more specific type cannot be determined, an XmlObject
* whose schema type is anyType will be returned.
*
* @return The strongly-typed object at the cursor's current location;
* null if the current location is not a START, STARTDOC, or ATTR.
*/
XmlObject getObject ( );
/**
* Returns the type of the current token. By definition, the current
* token is the token immediately to the right of the cursor.
* If you're in the middle of text, before a character, you get TEXT.
* You can't dive into the text of an ATTR, COMMENT or PROCINST.<br/><br/>
*
* As an alternative, it may be more convenient for you to use one of the
* methods that test for a particular token type. These include the methods
* isStart(), isStartdoc(), isText(), isAttr(), and so on. Each returns a boolean
* value indicating whether the token that follows the cursor is the type
* in question.
* <br/><br/>
*
* @return The TokenType instance for the token at the cursor's current
* location.
*/
TokenType currentTokenType ( );
/**
* True if the current token is a STARTDOC token type, meaning
* at the very root of the document.
*
* @return true if this token is a STARTDOC token type;
* otherwise, false.
*/
boolean isStartdoc ( );
/**
* True if this token is an ENDDOC token type, meaning
* at the very end of the document.
*
* @return true if this token is an ENDDOC token type;
* otherwise, false.
*/
boolean isEnddoc ( );
/**
* True if this token is a START token type, meaning
* just before an element's start.
*
* @return true if this token is a START token type;
* otherwise, false.
*/
boolean isStart ( );
/**
* True if this token is an END token type, meaning
* just before an element's end.
*
* @return true if this token is an END token type;
* otherwise, false.
*/
boolean isEnd ( );
/**
* True if the this token is a TEXT token type, meaning
* just before or inside text.
*
* @return true if this token is a TEXT token type;
* otherwise, false.
*/
boolean isText ( );
/**
* True if this token is an ATTR token type, meaning
* just before an attribute.
*
* @return true if this token is an ATTR token type;
* otherwise, false.
*/
boolean isAttr ( );
/**
* True if this token is a NAMESPACE token type, meaning
* just before a namespace declaration.
*
* @return true if this token is a NAMESPACE token type;
* otherwise, false.
*/
boolean isNamespace ( );
/**
* True if this token is a COMMENT token type, meaning
* just before a comment.
*
* @return true if this token is a COMMENT token type;
* otherwise, false.
*/
boolean isComment ( );
/**
* True if this token is a PROCINST token type, meaning
* just before a processing instruction.
*
* @return true if this token is a PROCINST token type;
* otherwise, false.
*/
boolean isProcinst ( );
/**
* True if this token is a container token. The STARTDOC and START
* token types are containers. Containers, including documents and elements,
* have the same content model. In other words, a document and an element
* may have the same contents. For example, a document may contain attributes
* or text, without any child elements.
*
* @return true if this token is a container token; otherwise, false.
*/
boolean isContainer ( );
/**
* True if this token is a finish token. A finish token can be an ENDDOC
* or END token type.
* @return true if this token is a finish token; otherwise, false.
*/
boolean isFinish ( );
/**
* True if this token is any attribute. This includes an ATTR token type and
* the NAMESPACE token type attribute.
*
* @return true if the current cursor is at any attribute; otherwise, false.
*/
boolean isAnyAttr ( );
/**
* Returns the type of the previous token. By definition, the previous
* token is the token immediately to the left of the cursor.<br/><br/>
*
* If you're in the middle of text, after a character, you get TEXT.
*
* @return The TokenType instance for the token immediately before the
* token at the cursor's current location.
*/
TokenType prevTokenType ( );
/**
* True if there is a next token. When this is false, as when the cursor is
* at the ENDDOC token, the toNextToken() method returns NONE and does not
* move the cursor.
*
* @return true if there is a next token; otherwise, false.
*/
boolean hasNextToken ( );
/**
* True if there is a previous token. When this is false, toPrevToken
* returns NONE and does not move the cursor.
*
* @return true if there is a previous token; otherwise, false.
*/
boolean hasPrevToken ( );
/**
* Moves the cursor to the next token. When there are no more tokens
* available, hasNextToken returns false and toNextToken() returns
* NONE and does not move the cursor. Returns the token type
* of the token to the right of the cursor upon a successful move.
*
* @return The token type for the next token if the cursor was moved;
* otherwise, NONE.
*/
TokenType toNextToken ( );
/**
* Moves the cursor to the previous token. When there is no
* previous token, returns NONE, otherwise returns the token
* to the left of the new position of the cursor.
*
* @return The token type for the previous token if the cursor was moved;
* otherwise, NONE.
*/
TokenType toPrevToken ( );
/**
* Moves the cursor to the first token in the content of the current
* START or STARTDOC. That is, the first token after all ATTR and NAMESPACE
* tokens associated with this START.<br/><br/>
*
* If the current token is not a START or STARTDOC, the cursor is not
* moved and NONE is returned. If the current START or STARTDOC
* has no content, the cursor is moved to the END or ENDDOC token.<br/><br/>
*
* @return The new current token type.
*/
TokenType toFirstContentToken ( );
/**
* Moves the cursor to the END or ENDDOC token corresponding to the
* current START or STARTDOC, and returns END or ENDDOC. <br/><br/>
*
* If the current token is not a START or STARTDOC, the cursor is not
* moved and NONE is returned.
*
* @return The new current token type.
*/
TokenType toEndToken ( );
/**
* Moves the cursor forward by the specified number of characters, and
* stops at the next non-TEXT token. Returns the number of characters
* actually moved across, which is guaranteed to be less than or equal to
* <em>maxCharacterCount</em>. If there is no further text, or if
* there is no text at all, returns zero.<br/><br/>
*
* Note this does not dive into attribute values, comment contents,
* processing instruction contents, etc., but only content text.<br/><br/>
*
* You can pass maxCharacterCount < 0 to move over all the text to the
* right. This has the same effect as toNextToken, but returns the amount
* of text moved over.
*
* @param maxCharacterCount The maximum number of characters by which
* the cursor should be moved.
* @return The actual number of characters by which the cursor was moved;
* 0 if the cursor was not moved.
*/
int toNextChar ( int maxCharacterCount );
/**
* Moves the cursor backwards by the number of characters given. Has
* similar characteristics to the {@link #toNextChar(int) toNextChar} method.
*
* @param maxCharacterCount The maximum number of characters by which
* the cursor should be moved.
* @return The actual number of characters by which the cursor was moved;
* 0 if the cursor was not moved.
*/
int toPrevChar ( int maxCharacterCount );
/**
* Moves the cursor to the next sibling element, or returns
* false and does not move the cursor if there is no next sibling
* element. (By definition the position of an element is the same
* as the position of its START token.)
*
* If the current token is not s START, the cursor will be
* moved to the next START without moving out of the scope of the
* current element.
*
* @return true if the cursor was moved; otherwise, false.
*/
boolean toNextSibling ( );
/**
* Moves the cursor to the previous sibling element, or returns
* false and does not move the cursor if there is no previous sibling
* element. (By definition the position of an element is the same
* as the position of its START token.)
*
* @return true if the cursor was moved; otherwise, false.
*/
boolean toPrevSibling ( );
/**
* Moves the cursor to the parent element or STARTDOC, or returns
* false and does not move the cursor if there is no parent.<br/><br/>
*
* Works if you're in attributes or content. Returns false only if at
* STARTDOC. Note that the parent of an END token is the corresponding
* START token.
*
* @return true if the cursor was moved; false if the cursor is at the STARTDOC
* token.
*/
boolean toParent ( );
/**
* Moves the cursor to the first child element, or returns false and
* does not move the cursor if there are no element children. <br/><br/>
*
* If the cursor is not currently in an element, it moves into the
* first child element of the next element.
*
* @return true if the cursor was moved; otherwise, false.
*/
boolean toFirstChild ( );
/**
* Moves the cursor to the last element child, or returns false and
* does not move the cursor if there are no element children.
*
* @return true if the cursor was moved; otherwise, false.
*/
boolean toLastChild ( );
/**
* Moves the cursor to the first child element of the specified name in
* no namespace.
*
* @param name The name of the element to move the cursor to.
* @return true if the cursor was moved; otherwise, false.
*/
boolean toChild ( String name );
/**
* Moves the cursor to the first child element of the specified name in the
* specified namespace.
*
* @param namespace The namespace URI for the element to move the cursor
* to.
* @param name The name of the element to move to.
* @return true if the cursor was moved; otherwise, false.
* @throws IllegalArgumentException If the name is not a valid local name.
*/
boolean toChild ( String namespace, String name );
/**
* Moves the cursor to the first child element of the specified qualified name.
*
* @param name The name of the element to move the cursor to.
*/
boolean toChild ( QName name );
/**
* Moves the cursor to the child element specified by <em>index</em>.
*
* @param index The position of the element in the sequence of child
* elements.
* @return true if the cursor was moved; otherwise, false.
*/
boolean toChild ( int index );
/**
* Moves the cursor to the specified <em>index</em> child element of the
* specified name, where that element is the .
*
* @param name The name of the child element to move the cursor to.
* @param index The position of the element in the sequence of child
* elements.
* @return true if the cursor was moved; otherwise, false.
*/
boolean toChild ( QName name, int index );
/**
* Moves the cursor to the next sibling element of the specified name in no
* namespace.
*
* @param name The name of the element to move the cursor to.
* @return true if the cursor was moved; otherwise, false.
*/
boolean toNextSibling ( String name );
/**
* Moves the cursor to the next sibling element of the specified name
* in the specified namespace.
*
* @param namespace The namespace URI for the element to move the cursor
* to.
* @param name The name of the element to move the cursor to.
* @return true if the cursor was moved; otherwise, false.
*/
boolean toNextSibling ( String namespace, String name );
/**
* Moves the cursor to the next sibling element of the specified
* qualified name.
*
* @param name The name of the element to move the cursor to.
* @return true if the cursor was moved; otherwise, false.
*/
boolean toNextSibling ( QName name );
/**
* Moves the cursor to the first attribute of this element, or
* returns false and does not move the cursor if there are no
* attributes. The order of attributes is arbitrary, but stable.<br/><br/>
*
* If the cursor is on a STARTDOC of a document-fragment, this method will
* move it to the first top level attribute if one exists.<br></br>
*
* xmlns attributes (namespace declarations) are not considered
* attributes by this function.<br/><br/>
*
* The cursor must be on a START or STARTDOC (in the case of a
* document fragment with top level attributes) for this method to
* succeed.
*
* Example for looping through attributes:
* <pre>
* XmlCursor cursor = ... //cursor on START or STARTDOC
* if (cursor.toFirstAttribute())
* {
* do
* {
* // do something using attribute's name and value
* cursor.getName();
* cursor.getTextValue();
* }
* while (cursor.toNextAttribute());
* }
* </pre>
*
* @return true if the cursor was moved; otherwise, false.
*/
boolean toFirstAttribute ( );
/**
* Moves the cursor to the last attribute of this element, or
* returns false and does not move the cursor if there are no
* attributes. The order of attributes is arbitrary, but stable.<br/><br/>
*
* xmlns attributes (namespace declarations) are not considered
* attributes by this function.<br/><br/>
*
* The cursor must be on a START or STARTDOC for this method
* to succeed.
*
* @return true if the cursor was moved; otherwise, false.
*/
boolean toLastAttribute ( );
/**
* Moves the cursor to the next sibling attribute, or returns
* false and does not move the cursor if there is no next
* sibling attribute. The order of attributes is arbitrary, but stable.<br/><br/>
*
* xmlns attributes (namespace declarations) are not considered
* attributes by this function.<br/><br/>
*
* The cursor must be on an attribute for this method to succeed.
* @see #toFirstAttribute()
*
* @return true if the cursor was moved; otherwise, false.
*/
boolean toNextAttribute ( );
/**
* Moves the cursor to the previous sibling attribute, or returns
* false and does not move the cursor if there is no previous
* sibling attribute. The order of attributes is arbitrary, but stable.<br/><br/>
*
* xmlns attributes (namespace declarations) are not considered
* attributes by this function.<br/><br/>
*
* The cursor must be on an attribute for this method to succeed.
*
* @return true if the cursor was moved; otherwise, false.
*/
boolean toPrevAttribute ( );
/**
* When at a START or STARTDOC, returns the attribute text for the given
* attribute. When not at a START or STARTDOC or the attribute does not
* exist, returns null.
*
* @param attrName The name of the attribute whose value is requested.
* @return The attribute's value if it has one; otherwise, null.
*/
String getAttributeText ( QName attrName );
/**
* When at a START or STARTDOC, sets the attribute text for the given
* attribute. When not at a START or STARTDOC returns false.
* If the attribute does not exist, one is created.
*
* @param attrName The name of the attribute whose value is being set.
* @param value The new value for the attribute.
* @return true if the new value was set; otherwise, false.
*/
boolean setAttributeText ( QName attrName, String value );
/**
* When at a START or STARTDOC, removes the attribute with the given name.
*
* @param attrName The name of the attribute that should be removed.
* @return true if the attribute was removed; otherwise, false.
*/
boolean removeAttribute ( QName attrName );
/**
* Gets the text value of the current document, element, attribute,
* comment, procinst or text token. <br/><br/>
*
* When getting the text value of an element, non-text content such
* as comments and processing instructions are ignored and text is concatenated.
* For elements that have nested element children, this
* returns the concatenated text of all mixed content and the
* text of all the element children, recursing in first-to-last
* depthfirst order.<br/><br/>
*
* For attributes, including namespaces, this returns the attribute value.<br/><br/>
*
* For comments and processing instructions, this returns the text content
* of the comment or PI, not including the delimiting sequences <!-- -->, <? ?>.
* For a PI, the name of the PI is also not included.
*<br/><br/>
* The value of an empty tag is the empty string.<br/><br/>
*
* If the current token is END or ENDDOC, this throws an {@link java.lang.IllegalStateException}.<br/><br/>
*
* @return The text value of the current token if the token's type is
* START, STARTDOC, TEXT, ATTR, COMMENT, PROCINST, or NAMESPACE; null
* if the type is NONE.
*/
String getTextValue ( );
/**
* Copies the text value of the current document, element, attribute,
* comment, processing instruction or text token, counting right from
* this cursor's location up to <em>maxCharacterCount</em>,
* and copies the returned text into <em>returnedChars</em>. <br/><br/>
*
* When getting the text value of an element, non-text content such
* as comments and processing instructions are ignored and text is concatenated.
* For elements that have nested element children, this
* returns the concatenated text of all mixed content and the
* text of all the element children, recursing in first-to-last
* depthfirst order.<br/><br/>
*
* For attributes, including namespaces, this returns the attribute value.<br/><br/>
*
* For comments and processing instructions, this returns the text contents
* of the comment or PI, not including the delimiting sequences <!-- -->, <? ?>. For
* a PI, the text will not include the name of the PI.<br/><br/>
*
* If the current token is END or ENDDOC, this throws an {@link java.lang.IllegalStateException}.<br/><br/>
*
* The value of an empty tag is the empty string.<br/><br/>
*
* @param returnedChars A character array to hold the returned characters.
* @param offset The position within returnedChars to which the first of the
* returned characters should be copied.
* @param maxCharacterCount The maximum number of characters after this cursor's
* location to copy. A negative value specifies that all characters should be copied.
* @return The actual number of characters copied; 0 if no characters
* were copied.
*/
int getTextValue ( char[] returnedChars, int offset, int maxCharacterCount );
/**
* Returns the characters of the current TEXT token. If the current token
* is not TEXT, returns "". If in the middle of a TEXT token, returns
* those chars to the right of the cursor of the TEXT token.
*
* @return The requested text; an empty string if the current token type is
* not TEXT.
*/
/**
* Sets the text value of the XML at this cursor's location if that XML's
* token type is START, STARTDOC, ATTR, COMMENT or PROCINST. <br/><br/>
*
* For elements that have nested children this first removes all
* the content of the element and replaces it with the given text.
*
* @param text The text to use as a new value.
* @throws java.lang.IllegalStateException If the token type at this
* cursor's location is not START, STARTDOC, ATTR, COMMENT or
* PROCINST.
*/
void setTextValue ( String text );
/**
* Sets the text value of the XML at this cursor's location (if that XML's
* token type is START, STARTDOC, ATTR, COMMENT or PROCINST) to the
* contents of the specified character array. <br/><br/>
*
* For elements that have nested children this first removes all
* the content of the element and replaces it with the given text.
*
* @param sourceChars A character array containing the XML's new value.
* @param offset The position within sourceChars from which the first of
* the source characters should be copied.
* @param length The maximum number of characters to set as the XML's new
* value.
* @throws java.lang.IllegalArgumentException If the token type at this
* cursor's location is not START, STARTDOC, ATTR, COMMENT or
* PROCINST.
*/
void setTextValue ( char[] sourceChars, int offset, int length );
/**
* Returns characters to the right of the cursor up to the next token.
*/
String getChars ( );
/**
* Copies characters up to the specified maximum number, counting right from
* this cursor's location to the character at <em>maxCharacterCount</em>. The
* returned characters are added to <em>returnedChars</em>, with the first
* character copied to the <em>offset</em> position. The <em>maxCharacterCount</em>
* parameter should be less than or equal to the length of <em>returnedChars</em>
* minus <em>offset</em>. Copies a number of characters, which is
* either <em>maxCharacterCount</em> or the number of characters up to the next token,
* whichever is less.
*
* @param returnedChars A character array to hold the returned characters.
* @param offset The position within returnedChars at which the first of the
* returned characters should be added.
* @param maxCharacterCount The maximum number of characters after this cursor's
* location to return.
* @return The actual number of characters returned; 0 if no characters
* were returned or if the current token is not TEXT.
*/
int getChars ( char[] returnedChars, int offset, int maxCharacterCount );
/**
* Moves the cursor to the STARTDOC token, which is the
* root of the document.
*/
void toStartDoc ( );
/**
* Moves the cursor to the ENDDOC token, which is the end
* of the document.
*/
void toEndDoc ( );
/**
* Determines if the specified cursor is in the same document as
* this cursor.
*
* @param cursor The cursor that may be in the same document
* as this cursor.
* @return true if the specified cursor is in the same document;
* otherwise, false.
*/
boolean isInSameDocument ( XmlCursor cursor );
/**
* Returns an integer indicating whether this cursor is before,
* after, or at the same position as the specified cursor. <br/><br/>
*
* <code>a.comparePosition(b) < 0</code> means a is to the left of b.<br/>
* <code>a.comparePosition(b) == 0</code> means a is at the same position as b.<br/>
* <code>a.comparePosition(b) > 0</code> means a is to the right of b.<br/><br/>
*
* The sort order of cursors in the document is the token order.
* For example, if cursor "a" is at a START token and the cursor "b"
* is at a token within the contents of the same element, then
* a.comparePosition(b) will return -1, meaning that the position
* of a is before b.
*
* @param cursor The cursor whose position should be compared
* with this cursor.
* @return 1 if this cursor is after the specified cursor; 0 if
* this cursor is at the same position as the specified cursor;
* -1 if this cursor is before the specified cursor.
* @throws java.lang.IllegalArgumentException If the specified
* cursor is not in the same document as this cursor.
*/
int comparePosition ( XmlCursor cursor );
/**
* Determines if this cursor is to the left of (or before)
* the specified cursor. Note that this is the same as
* <code>a.comparePosition(b) < 0 </code>
*
* @param cursor The cursor whose position should be compared
* with this cursor.
* @return true if this cursor is to the left of the specified
* cursor; otherwise, false.
*/
boolean isLeftOf ( XmlCursor cursor );
/**
* Determines if this cursor is at the same position as
* the specified cursor. Note that this is the same as
* <code>a.comparePosition(b) == 0 </code>
*
* @param cursor The cursor whose position should be compared
* with this cursor.
* @return true if this cursor is at the same position as
* the specified cursor; otherwise, false.
*/
boolean isAtSamePositionAs ( XmlCursor cursor );
/**
* Determines if this cursor is to the right of (or after)
* the specified cursor. Note that this is the same as
* <code>a.comparePosition(b) > 0 </code>
*
* @param cursor The cursor whose position should be compared
* with this cursor.
* @return true if this cursor is to the right of the specified
* cursor; otherwise, false.
*/
boolean isRightOf ( XmlCursor cursor );
/**
* Executes the specified XQuery expression against the XML this
* cursor is in. <br/><br/>
*
* The query may be a String or a compiled query. You can precompile
* an XQuery expression using the XmlBeans.compileQuery method. <br/><br>
*
* The root referred to by the expression should be given as
* a dot. The following is an example path expression:
* <pre>
* XmlCursor results = cursor.execQuery("purchase-order/line-item[price <= 20.00]");
* </pre>
*
* @param query The XQuery expression to execute.
* @return A cursor containing the results of the query.
* @throws XmlRuntimeException If the query expression is invalid.
*/
XmlCursor execQuery ( String query );
/**
* Executes the specified XQuery expression against the XML this
* cursor is in, and using the specified options. <br/><br/>
*
* @param query The XQuery expression to execute.
* @param options Options for the query. For example, you can call
* the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
* method to specify a particular name for the query expression
* variable that indicates the context node.
* @throws XmlRuntimeException If the query expression is invalid.
*/
XmlCursor execQuery ( String query, XmlOptions options );
/**
* Represents the state of a dcoument at a particular point
* in time. It is used to determine if a document has been changed
* since that point in time.
*/
interface ChangeStamp
{
/**
* Returns whether or not the document assoiated with this ChangeStamp
* has been altered since the ChangeStamp had been created.
*/
public boolean hasChanged ( );
}
/**
* Returns the current change stamp for the document the current cursor is in.
* This change stamp can be queried at a later point in time to find out
* if the document has changed.
*
* @return The change stamp for the document the current cursor is in.
*/
ChangeStamp getDocChangeStamp ( );
/**
* Subclasses of XmlBookmark can be used to annotate an XML document.
* This class is abstract to prevent parties from inadvertently
* interfering with each others' bookmarks without explicitly
* sharing a bookmark class.
*/
abstract class XmlBookmark
{
/**
* Constructs a strongly-referenced bookmark.
*/
public XmlBookmark ( ) { this( false ); }
/**
* Constructs a bookmark.
* @param weak true if the document's reference to the bookmark should be a WeakReference
*/
public XmlBookmark ( boolean weak )
{
_ref = weak ? new WeakReference( this ) : null;
}
/**
* Call the createCursor method to create a new cursor which is
* positioned at the same splace as the bookmark. It is much more
* efficient to call toBookmark on an existing cursor than it
* is to create a new cursor. However, toBookmark may fail if the
* bookmark is in a different document than the cursor. It is
* under these circumstances where createCursor needs to be called
* on the bookmark. Subsequent navigations to bookmark
* positions should attempt to reuse the last cursor to
* improve performace.
*/
public final XmlCursor createCursor ( )
{
return _currentMark == null ? null : _currentMark.createCursor();
}
/**
* Moves the given cursor to this bookmark, and returns it.
*/
public final XmlCursor toBookmark ( XmlCursor c )
{
return c == null || !c.toBookmark( this ) ? createCursor() : c;
}
/**
* The default key for bookmarks is the class which implements
* them. This way, multiple parties using bookmarks in the
* same instance document will not interfere with eachother.
* One can, however, override getKey() to use a key other than
* the class.
*/
public Object getKey ( )
{
return this.getClass();
}
/**
* The mark is set by the host document; it is capable of
* returning an XmlCursor implementation at the location of
* the bookmark.
*/
public XmlMark _currentMark;
/**
* If non-null, the ref is used by the host document
* to maintain a reference to the bookmark. If it is a weak
* reference, the host document will not prevent the Bookmark
* from being garbage collected.
*/
public final Reference _ref;
}
/**
* An abstract {@link XmlCursor} factory.
* Implementations of XmlCursor implement XmlMark to be able to
* reconstitute a cursor from a bookmark. When content moves between
* implementations, the XmlMark is set to the implmentation's which
* recieves the new content.
*/
interface XmlMark
{
XmlCursor createCursor ( );
}
/**
* Sets a bookmark to the document at this cursor's location.
*
* The bookmark is attached to the token in the tree immediately
* after the cursor. If the tree is manipulated to move
* that object to a different place, the bookmark moves with it.
* If the tree is manipulated to delete that token from the
* tree, the bookmark is orphaned. Copy operations do not copy
* bookmarks.
*
* @param bookmark The bookmark to set.
*/
void setBookmark ( XmlBookmark bookmark );
/**
* Retrieves the bookmark with the specified key
* at this cursor's location. If there is no bookmark whose key is
* given by the specified key at the current position, null is returned.
* If the {@link XmlCursor.XmlBookmark#getKey() getKey} method is not overridden on
* the bookmark, then the bookmark's class is used as the key.
*
* @param key The key for the bookmark to retrieve.
* @return The requested bookmark; null if there is no bookmark
* corresponding to the specified key.
*/
XmlBookmark getBookmark ( Object key );
/**
* Clears the bookmark whose key is specified, if the bookmark
* exists at this cursor's location.
*
* @param key The for the bookmark to clear.
*/
void clearBookmark ( Object key );
/**
* Retrieves all the bookmarks at this location, adding them to
* the specified collection. Bookmarks held by weak references are
* added to this collection as Weak referenced objects pointing to the
* bookmark.
*
* @param listToFill The collection that will contain bookmarks
* returned by this method.
*/
void getAllBookmarkRefs ( Collection listToFill );
/**
* Removes the XML that is immediately after this cursor.
*
* For the TEXT, ATTR, NAMESPACE, COMMENT and PROCINST tokens, a single
* token is removed. For a START token, the corresponding element and all
* of its contents are removed. For all other tokens, this is a no-op.
* You cannot remove a STARTDOC.
*
* The cursors located in the XML that was removed all collapse to the
* same location. All bookmarks in this XML will be orphaned.
*
* @return true if anything was removed; false only if the cursor is
* just before END or ENDDOC token.
* @throws java.lang.IllegalArgumentException If the cursor is at a
* STARTDOC token.
*/
boolean removeXml ( );
/**
* Moves the XML immediately after this cursor to the location
* specified by the <em>toHere</em> cursor, shifting XML at that location
* to the right to make room. For the TEXT, ATTR, NAMESPACE,
* COMMENT and PROCINST tokens, a single token is moved. For a start token, the
* element and all of its contents are moved. For all other tokens, this
* is a no-op.
*
* The bookmarks located in the XML that was moved also move to the
* new location; the cursors don't move with the content.
*
* @param toHere The cursor at the location to which the XML should
* be moved.
* @return true if anything was moved. This only happens when the XML to be
* moved contains the target of the move.
* @throws java.lang.IllegalArgumentException If the operation is not allowed
* at the cursor's location. This includes attempting to move an end token or the
* document as a whole. Also, moving to a location before the start document or moving
* an attribute to a location other than after another attribute or start token
* will throw.
*/
boolean moveXml ( XmlCursor toHere );
/**
* Copies the XML immediately after this cursor to the location
* specified by the <em>toHere</em> cursor. For the TEXT, ATTR, NAMESPACE,
* COMMENT and PROCINST tokens, a single token is copied. For a start token,
* the element and all of its contents are copied. For all other tokens, this
* is a no-op.
*
* The cursors and bookmarks located in the XML that was copied are also copied
* to the new location.
*
* @param toHere The cursor at the location to which the XML should
* be copied.
* @return true if anything was copied; false if the token supports the operation,
* but nothing was copied.
* @throws java.lang.IllegalArgumentException If the operation is not allowed
* at the cursor's location.
*/
boolean copyXml ( XmlCursor toHere );
/**
* Removes the contents of the container (STARTDOC OR START) immediately after
* this cursor. For all other situations, returns false. Does
* not remove attributes or namspaces.
*
* @return true if anything was copied; otherwise, false.
*/
boolean removeXmlContents ( );
/**
* Moves the contents of the container (STARTDOC OR START) immediately after
* this cursor to the location specified by the <em>toHere</em> cursor.
* For all other situations, returns false. Does not move attributes or
* namespaces.
*
* @param toHere The cursor at the location to which the XML should be moved.
* @return true if anything was moved; otherwise, false.
*/
boolean moveXmlContents ( XmlCursor toHere );
/**
* Copies the contents of the container (STARTDOC OR START) immediately to
* the right of the cursor to the location specified by the <em>toHere</em> cursor.
* For all other situations, returns false. Does not copy attributes or
* namespaces.
*
* @param toHere The cursor at the location to which the XML should
* be copied.
* @return true if anything was copied; otherwise, false.
*/
boolean copyXmlContents ( XmlCursor toHere );
/**
* Removes characters up to the specified maximum number, counting right from
* this cursor's location to the character at <em>maxCharacterCount</em>. The
* space remaining from removing the characters collapses up to this cursor.
*
* @param maxCharacterCount The maximum number of characters after this cursor's
* location to remove.
* @return The actual number of characters removed.
* @throws java.lang.IllegalArgumentException If the operation is not allowed
* at the cursor's location.
*/
int removeChars ( int maxCharacterCount );
/**
* Moves characters immediately after this cursor to the position immediately
* after the specified cursor. Characters are counted to the right up to the
* specified maximum number. XML after the destination cursor is
* shifted to the right to make room. The space remaining from moving the
* characters collapses up to this cursor.
*
* @param maxCharacterCount The maximum number of characters after this cursor's
* location to move.
* @param toHere The cursor to which the characters should be moved.
* @return The actual number of characters moved.
* @throws java.lang.IllegalArgumentException If the operation is not allowed
* at the cursor's location.
*/
int moveChars ( int maxCharacterCount, XmlCursor toHere );
/**
* Copies characters to the position immediately after the specified cursor.
* Characters are counted to the right up to the specified maximum number.
* XML after the destination cursor is shifted to the right to make room.
*
* @param maxCharacterCount The maximum number of characters after this cursor's
* location to copy.
* @param toHere The cursor to which the characters should be copied.
* @return The actual number of characters copied.
* @throws java.lang.IllegalArgumentException If the operation is not allowed
* at the cursor's location.
*/
int copyChars ( int maxCharacterCount, XmlCursor toHere );
/**
* Inserts the specified text immediately before this cursor's location.
*
* @param text The text to insert.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertChars ( String text );
/**
* Inserts an element immediately before this cursor's location, giving
* the element the specified qualified name.
*
* @param name The qualified name for the element.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertElement ( QName name );
/**
* Inserts an element immediately before this cursor's location, giving
* the element the specified local name.
*
* @param localName The local name for the new element.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertElement ( String localName );
/**
* Inserts a new element immediately before this cursor's location, giving the
* element the specified local name and associating it with specified namespace
*
* @param localName The local name for the new element.
* @param uri The URI for the new element's namespace.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertElement ( String localName, String uri );
/**
* Inserts a new element around this cursor, giving the element the specified
* qualified name. After the element is inserted, this cursor is between its start
* and end. This cursor can then be used to insert additional XML into
* the new element.
*
* @param name The qualified name for the new element.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void beginElement ( QName name );
/**
* Inserts a new element around this cursor, giving the element the specified
* local name. After the element is inserted, this cursor is between its start
* and end. This cursor can then be used to insert additional XML into
* the new element.
*
* @param localName The local name for the new element.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void beginElement ( String localName );
/**
* Inserts a new element around this cursor, giving the element the specified
* local name and associating it with the specified namespace. After the element
* is inserted, this cursor is between its start and end. This cursor
* can then be used to insert additional XML into the new element.
*
* @param localName The local name for the new element.
* @param uri The URI for the new element's namespace.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void beginElement ( String localName, String uri );
/**
* Inserts a new element immediately before this cursor's location, giving the
* element the specified qualified name and content.
*
* @param name The qualified name for the new element.
* @param text The content for the new element.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertElementWithText ( QName name, String text );
/**
* Inserts a new element immediately before this cursor's location, giving the
* element the specified local name and content.
*
* @param localName The local name for the new element.
* @param text The content for the new element.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertElementWithText ( String localName, String text );
/**
* Inserts a new element immediately before this cursor's location, giving the
* element the specified local name, associating it with the specified namespace,
* and giving it the specified content.
*
* @param localName The local name for the new element.
* @param uri The URI for the new element's namespace.
* @param text The content for the new element.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertElementWithText ( String localName, String uri, String text );
/**
* Inserts a new attribute immediately before this cursor's location, giving it
* the specified local name.
*
* @param localName The local name for the new attribute.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertAttribute ( String localName );
/**
* Inserts a new attribute immediately before this cursor's location, giving it
* the specified local name and associating it with the specified namespace.
*
* @param localName The local name for the new attribute.
* @param uri The URI for the new attribute's namespace.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertAttribute ( String localName, String uri );
/**
* Inserts a new attribute immediately before this cursor's location, giving it
* the specified name.
*
* @param name The local name for the new attribute.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertAttribute ( QName name );
/**
* Inserts a new attribute immediately before this cursor's location, giving it
* the specified value and name.
*
* @param Name The local name for the new attribute.
* @param value The value for the new attribute.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertAttributeWithValue ( String Name, String value );
/**
* Inserts an attribute immediately before the cursor's location, giving it
* the specified name and value, and associating it with the specified namespace.
*
* @param name The name for the new attribute.
* @param uri The URI for the new attribute's namespace.
* @param value The value for the new attribute.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertAttributeWithValue ( String name, String uri, String value );
/**
* Inserts an attribute immediately before the cursor's location, giving it
* the specified name and value.
*
* @param name The name for the new attribute.
* @param value The value for the new attribute.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertAttributeWithValue ( QName name, String value );
/**
* Inserts a namespace declaration immediately before the cursor's location,
* giving it the specified prefix and URI.
*
* @param prefix The prefix for the namespace.
* @param namespace The URI for the namespace.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertNamespace ( String prefix, String namespace );
/**
* Inserts an XML comment immediately before the cursor's location,
* giving it the specified content.
*
* @param text The new comment's content.
* @throws java.lang.IllegalArgumentException If the insertion is not allowed
* at the cursor's location.
*/
void insertComment ( String text );
/**
* Inserts an XML processing instruction immediately before the cursor's location,
* giving it the specified target and text.
*
* @param target The target for the processing instruction.
* @param text The new processing instruction's text.
* @throws java.lang.IllegalStateException If the insertion is not allowed
* at the cursor's location.
*/
void insertProcInst ( String target, String text );
}
| apache-2.0 |
Wechat-Group/WxJava | weixin-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/constant/WxMaConstants.java | 3434 | package cn.binarywang.wx.miniapp.constant;
/**
* <pre>
* 小程序常量.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
public abstract class WxMaConstants {
private WxMaConstants() {
}
/**
* 默认的env_version值
*/
public static final String DEFAULT_ENV_VERSION = "release";
/**
* 微信接口返回的参数errcode.
*/
public static final String ERRCODE = "errcode";
/**
* 素材类型.
*/
public abstract static class MediaType {
/**
* 图片.
*/
public static final String IMAGE = "image";
}
/**
* 消息格式.
*/
public abstract static class MsgDataFormat {
public static final String XML = "XML";
public static final String JSON = "JSON";
}
/**
* 客服消息的消息类型.
*/
public static class KefuMsgType {
/**
* 文本消息.
*/
public static final String TEXT = "text";
/**
* 图片消息.
*/
public static final String IMAGE = "image";
/**
* 图文链接.
*/
public static final String LINK = "link";
/**
* 小程序卡片消息.
*/
public static final String MA_PAGE = "miniprogrampage";
}
/**
* 内容安全检测的媒体类型
*/
public static final class SecCheckMediaType {
/**
* 音频
*/
public static final int VOICE = 1;
/**
* 图片
*/
public static final int IMAGE = 2;
}
/**
* 快递账号绑定类型
*/
public static final class BindAccountType {
/**
* 绑定
*/
public static final String BIND = "bind";
/**
* 解绑
*/
public static final String UNBIND = "unbind";
}
/**
* 快递下单订单来源
*/
public static final class OrderAddSource {
/**
* 小程序
*/
public static final int MINI_PROGRAM = 0;
/**
* APP或H5
*/
public static final int APP_OR_H5 = 2;
}
/**
* 快递下单保价
*/
public static final class OrderAddInsured {
private OrderAddInsured() {
}
/**
* 不保价
*/
public static final int INSURED_PROGRAM = 0;
/**
* 保价
*/
public static final int USE_INSURED = 1;
/**
* 默认保价金额
*/
public static final int DEFAULT_INSURED_VALUE = 0;
}
/**
* 小程序订阅消息跳转小程序类型
* <p>
* developer为开发版;trial为体验版;formal为正式版;默认为正式版
*/
public static final class MiniProgramState {
private MiniProgramState() {
}
/**
* 开发版
*/
public static final String DEVELOPER = "developer";
/**
* 体验版
*/
public static final String TRIAL = "trial";
/**
* 正式版
*/
public static final String FORMAL = "formal";
}
/**
* 进入小程序查看的语言类型
* 支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN
*/
public static final class MiniProgramLang {
private MiniProgramLang() {
}
/**
* 简体中文
*/
public static final String ZH_CN = "zh_CN";
/**
* 英文
*/
public static final String EN_US = "en_US";
/**
* 繁体中文
*/
public static final String ZH_HK = "zh_HK";
/**
* 繁体中文
*/
public static final String ZH_TW = "zh_TW";
}
}
| apache-2.0 |
consulo/consulo-android | android/android/src/com/android/tools/idea/gradle/project/PostProjectSetupTasksExecutor.java | 29206 | /*
* Copyright (C) 2014 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.tools.idea.gradle.project;
import com.android.builder.model.AndroidProject;
import com.android.ide.common.repository.SdkMavenRepository;
import com.android.sdklib.AndroidTargetHash;
import com.android.sdklib.AndroidVersion;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.repository.FullRevision;
import com.android.sdklib.repository.descriptors.IPkgDesc;
import com.android.sdklib.repository.descriptors.PkgDesc;
import com.android.sdklib.repository.descriptors.PkgType;
import com.android.sdklib.repository.local.LocalSdk;
import com.android.tools.idea.gradle.GradleSyncState;
import com.android.tools.idea.gradle.IdeaAndroidProject;
import com.android.tools.idea.gradle.customizer.android.DependenciesModuleCustomizer;
import com.android.tools.idea.gradle.dependency.LibraryDependency;
import com.android.tools.idea.gradle.eclipse.ImportModule;
import com.android.tools.idea.gradle.messages.Message;
import com.android.tools.idea.gradle.messages.ProjectSyncMessages;
import com.android.tools.idea.gradle.service.notification.hyperlink.InstallPlatformHyperlink;
import com.android.tools.idea.gradle.service.notification.hyperlink.NotificationHyperlink;
import com.android.tools.idea.gradle.service.notification.hyperlink.OpenAndroidSdkManagerHyperlink;
import com.android.tools.idea.gradle.service.notification.hyperlink.OpenUrlHyperlink;
import com.android.tools.idea.gradle.util.ProjectBuilder;
import com.android.tools.idea.gradle.variant.conflict.Conflict;
import com.android.tools.idea.gradle.variant.conflict.ConflictSet;
import com.android.tools.idea.gradle.variant.profiles.ProjectProfileSelectionDialog;
import com.android.tools.idea.rendering.ProjectResourceRepository;
import com.android.tools.idea.sdk.IdeSdks;
import com.android.tools.idea.sdk.VersionCheck;
import com.android.tools.idea.sdk.wizard.SdkQuickfixWizard;
import com.android.tools.idea.templates.TemplateManager;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.intellij.jarFinder.InternetAttachSourceProvider;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider;
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProviderImpl;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkModificator;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.libraries.ui.OrderRoot;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.NonNavigatable;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.SystemProperties;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.android.facet.ResourceFolderManager;
import org.jetbrains.android.sdk.AndroidSdkAdditionalData;
import org.jetbrains.android.sdk.AndroidSdkData;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.must.android.module.extension.AndroidModuleExtension;
import java.io.File;
import java.util.*;
import static com.android.SdkConstants.FN_ANNOTATIONS_JAR;
import static com.android.SdkConstants.FN_FRAMEWORK_LIBRARY;
import static com.android.tools.idea.gradle.customizer.AbstractDependenciesModuleCustomizer.pathToUrl;
import static com.android.tools.idea.gradle.messages.CommonMessageGroupNames.FAILED_TO_SET_UP_SDK;
import static com.android.tools.idea.gradle.project.LibraryAttachments.getStoredLibraryAttachments;
import static com.android.tools.idea.gradle.project.ProjectDiagnostics.findAndReportStructureIssues;
import static com.android.tools.idea.gradle.project.ProjectJdkChecks.hasCorrectJdkVersion;
import static com.android.tools.idea.gradle.service.notification.errors.AbstractSyncErrorHandler.FAILED_TO_SYNC_GRADLE_PROJECT_ERROR_GROUP_FORMAT;
import static com.android.tools.idea.gradle.util.GradleUtil.getAndroidProject;
import static com.android.tools.idea.gradle.util.Projects.*;
import static com.android.tools.idea.gradle.variant.conflict.ConflictResolution.solveSelectionConflicts;
import static com.android.tools.idea.gradle.variant.conflict.ConflictSet.findConflicts;
import static com.android.tools.idea.startup.ExternalAnnotationsSupport.attachJdkAnnotations;
import static com.intellij.notification.NotificationType.INFORMATION;
import static com.intellij.openapi.roots.OrderRootType.CLASSES;
import static com.intellij.openapi.roots.OrderRootType.SOURCES;
import static com.intellij.openapi.util.io.FileUtil.*;
import static com.intellij.openapi.vfs.StandardFileSystems.JAR_PROTOCOL_PREFIX;
import static com.intellij.util.ArrayUtil.toStringArray;
import static com.intellij.util.io.URLUtil.JAR_SEPARATOR;
import static org.jetbrains.android.sdk.AndroidSdkUtils.*;
public class PostProjectSetupTasksExecutor {
private static final String SOURCES_JAR_NAME_SUFFIX = "-sources.jar";
/** Whether a message indicating that "a new SDK Tools version is available" is already shown. */
private static boolean ourNewSdkVersionToolsInfoAlreadyShown;
/** Whether we've checked for build expiration */
private static boolean ourCheckedExpiration;
private static final boolean DEFAULT_GENERATE_SOURCES_AFTER_SYNC = true;
private static final boolean DEFAULT_USING_CACHED_PROJECT_DATA = false;
private static final long DEFAULT_LAST_SYNC_TIMESTAMP = -1;
@NotNull private final Project myProject;
private volatile boolean myGenerateSourcesAfterSync = DEFAULT_GENERATE_SOURCES_AFTER_SYNC;
private volatile boolean myUsingCachedProjectData = DEFAULT_USING_CACHED_PROJECT_DATA;
private volatile long myLastSyncTimestamp = DEFAULT_LAST_SYNC_TIMESTAMP;
@NotNull
public static PostProjectSetupTasksExecutor getInstance(@NotNull Project project) {
return ServiceManager.getService(project, PostProjectSetupTasksExecutor.class);
}
public PostProjectSetupTasksExecutor(@NotNull Project project) {
myProject = project;
}
/**
* Invoked after a project has been synced with Gradle.
*/
public void onProjectSyncCompletion() {
ProjectSyncMessages messages = ProjectSyncMessages.getInstance(myProject);
messages.reportDependencySetupErrors();
messages.reportComponentIncompatibilities();
findAndReportStructureIssues(myProject);
ModuleManager moduleManager = ModuleManager.getInstance(myProject);
for (Module module : moduleManager.getModules()) {
if (!hasCorrectJdkVersion(module)) {
// we already displayed the error, no need to check each module.
break;
}
}
if (hasErrors(myProject)) {
addSdkLinkIfNecessary();
checkSdkToolsVersion(myProject);
updateGradleSyncState();
return;
}
executeProjectChanges(myProject, new Runnable() {
@Override
public void run() {
attachSourcesToLibraries();
adjustModuleStructures();
ensureValidSdks();
}
});
enforceExternalBuild(myProject);
AndroidGradleProjectComponent.getInstance(myProject).checkForSupportedModules();
findAndShowVariantConflicts();
checkSdkToolsVersion(myProject);
addSdkLinkIfNecessary();
ProjectResourceRepository.moduleRootsChanged(myProject);
updateGradleSyncState();
if (myGenerateSourcesAfterSync) {
ProjectBuilder.getInstance(myProject).generateSourcesOnly();
}
// set default value back.
myGenerateSourcesAfterSync = DEFAULT_GENERATE_SOURCES_AFTER_SYNC;
TemplateManager.getInstance().refreshDynamicTemplateMenu(myProject);
}
private void updateGradleSyncState() {
if (!myUsingCachedProjectData) {
// Notify "sync end" event first, to register the timestamp. Otherwise the cache (GradleProjectSyncData) will store the date of the
// previous sync, and not the one from the sync that just ended.
GradleSyncState.getInstance(myProject).syncEnded();
GradleProjectSyncData.save(myProject);
} else {
long lastSyncTimestamp = myLastSyncTimestamp;
if (lastSyncTimestamp == DEFAULT_LAST_SYNC_TIMESTAMP) {
lastSyncTimestamp = System.currentTimeMillis();
}
GradleSyncState.getInstance(myProject).syncSkipped(lastSyncTimestamp);
}
// set default value back.
myUsingCachedProjectData = DEFAULT_USING_CACHED_PROJECT_DATA;
myLastSyncTimestamp = DEFAULT_LAST_SYNC_TIMESTAMP;
}
private void adjustModuleStructures() {
final IdeModifiableModelsProvider modelsProvider = new IdeModifiableModelsProviderImpl(myProject);
Set<Sdk> androidSdks = Sets.newHashSet();
try {
for (Module module : modelsProvider.getModules()) {
ModifiableRootModel model = modelsProvider.getModifiableRootModel(module);
adjustInterModuleDependencies(module, modelsProvider);
Sdk sdk = model.getSdk();
if (sdk != null) {
if (isAndroidSdk(sdk)) {
androidSdks.add(sdk);
}
continue;
}
Sdk jdk = IdeSdks.getJdk();
model.setSdk(jdk);
}
modelsProvider.commit();
}
catch (Throwable t) {
modelsProvider.dispose();
ExceptionUtil.rethrowAllAsUnchecked(t);
}
for (Sdk sdk: androidSdks) {
refreshLibrariesIn(sdk);
}
removeAllModuleCompiledArtifacts(myProject);
}
private static void adjustInterModuleDependencies(@NotNull Module module, @NotNull IdeModifiableModelsProvider modelsProvider) {
// Verifies that inter-module dependencies between Android modules are correctly set. If module A depends on module B, and module B
// does not contain sources but exposes an AAR as an artifact, the IDE should set the dependency in the 'exploded AAR' instead of trying
// to find the library in module B. The 'exploded AAR' is in the 'build' folder of module A.
// See: https://code.google.com/p/android/issues/detail?id=162634
AndroidProject androidProject = getAndroidProject(module);
if (androidProject == null) {
return;
}
ModifiableRootModel modifiableModel = modelsProvider.getModifiableRootModel(module);
for (Module dependency : modifiableModel.getModuleDependencies()) {
AndroidProject dependencyAndroidProject = getAndroidProject(dependency);
if (dependencyAndroidProject == null) {
LibraryDependency backup = getModuleCompiledArtifact(dependency);
if (backup != null) {
DependenciesModuleCustomizer.updateLibraryDependency(module, modelsProvider, backup, androidProject);
}
}
}
}
// After a sync, the contents of an IDEA SDK does not get refreshed. This is an issue when an IDEA SDK is corrupt (e.g. missing libraries
// like android.jar) and then it is restored by installing the missing platform from within the IDE (using a "quick fix.") After the
// automatic project sync (triggered by the SDK restore) the contents of the SDK are not refreshed, and references to Android classes are
// not found in editors. Removing and adding the libraries effectively refreshes the contents of the IDEA SDK, and references in editors
// work again.
private static void refreshLibrariesIn(@NotNull Sdk sdk) {
VirtualFile[] libraries = sdk.getRootProvider().getFiles(CLASSES);
SdkModificator sdkModificator = sdk.getSdkModificator();
sdkModificator.removeRoots(CLASSES);
sdkModificator.commitChanges();
sdkModificator = sdk.getSdkModificator();
for (VirtualFile library : libraries) {
sdkModificator.addRoot(library, CLASSES);
}
sdkModificator.commitChanges();
}
private void attachSourcesToLibraries() {
LibraryTable libraryTable = ProjectLibraryTable.getInstance(myProject);
LibraryAttachments storedLibraryAttachments = getStoredLibraryAttachments(myProject);
for (Library library : libraryTable.getLibraries()) {
Set<String> sourcePaths = Sets.newHashSet();
for (VirtualFile file : library.getFiles(SOURCES)) {
sourcePaths.add(file.getUrl());
}
Library.ModifiableModel libraryModel = library.getModifiableModel();
// Find the source attachment based on the location of the library jar file.
for (VirtualFile classFile : library.getFiles(CLASSES)) {
VirtualFile sourceJar = findSourceJarForJar(classFile);
if (sourceJar != null) {
String url = pathToUrl(sourceJar.getPath());
if (!sourcePaths.contains(url)) {
libraryModel.addRoot(url, SOURCES);
sourcePaths.add(url);
}
}
}
if (storedLibraryAttachments != null) {
storedLibraryAttachments.addUrlsTo(libraryModel);
}
libraryModel.commit();
}
if (storedLibraryAttachments != null) {
storedLibraryAttachments.removeFromProject();
}
}
@Nullable
private static VirtualFile findSourceJarForJar(@NotNull VirtualFile jarFile) {
// We need to get the real jar file. The one that we received is just a wrapper around a URL. Getting the parent from this file returns
// null.
File jarFilePath = getJarFromJarUrl(jarFile.getUrl());
if (jarFilePath == null) {
return null;
}
File sourceJarPath = getSourceJarForAndroidSupportAar(jarFilePath);
if (sourceJarPath != null) {
return VfsUtil.findFileByIoFile(sourceJarPath, true);
}
VirtualFile realJarFile = VfsUtil.findFileByIoFile(jarFilePath, true);
if (realJarFile == null) {
// Unlikely to happen. At this point the jar file should exist.
return null;
}
VirtualFile parent = realJarFile.getParent();
String sourceFileName = jarFile.getNameWithoutExtension() + SOURCES_JAR_NAME_SUFFIX;
if (parent != null) {
// Try finding sources in the same folder as the jar file. This is the layout of Maven repositories.
VirtualFile sourceJar = parent.findChild(sourceFileName);
if (sourceJar != null) {
return sourceJar;
}
// Try the parent's parent. This is the layout of the repository cache in .gradle folder.
parent = parent.getParent();
if (parent != null) {
for (VirtualFile child : parent.getChildren()) {
if (!child.isDirectory()) {
continue;
}
sourceJar = child.findChild(sourceFileName);
if (sourceJar != null) {
return sourceJar;
}
}
}
}
// Try IDEA's own cache.
File librarySourceDirPath = InternetAttachSourceProvider.getLibrarySourceDir();
File sourceJar = new File(librarySourceDirPath, sourceFileName);
return VfsUtil.findFileByIoFile(sourceJar, true);
}
/**
* Provides the path of the source jar for the libraries in the group "com.android.support" in the Android Support Maven repository (in
* the Android SDK.)
* <p>
* Since AndroidProject (the Gradle model) does not provide the location of the source jar for aar libraries, we can deduce it from the
* path of the "exploded aar".
* </p>
*/
@Nullable
private static File getSourceJarForAndroidSupportAar(@NotNull File jarFilePath) {
String path = jarFilePath.getPath();
if (!path.contains(ImportModule.SUPPORT_GROUP_ID)) {
return null;
}
int startingIndex = -1;
List<String> pathSegments = splitPath(jarFilePath.getParentFile().getPath());
int segmentCount = pathSegments.size();
for (int i = 0; i < segmentCount; i++) {
if (ResourceFolderManager.EXPLODED_AAR.equals(pathSegments.get(i))) {
startingIndex = i + 1;
break;
}
}
if (startingIndex == -1 || startingIndex >= segmentCount) {
return null;
}
List<String> sourceJarRelativePath = Lists.newArrayList();
String groupId = pathSegments.get(startingIndex++);
if (ImportModule.SUPPORT_GROUP_ID.equals(groupId)) {
File androidHomePath = IdeSdks.getAndroidSdkPath();
File repositoryLocation = SdkMavenRepository.ANDROID.getRepositoryLocation(androidHomePath, true);
if (repositoryLocation != null) {
sourceJarRelativePath.addAll(Splitter.on('.').splitToList(groupId));
String artifactId = pathSegments.get(startingIndex++);
sourceJarRelativePath.add(artifactId);
String version = pathSegments.get(startingIndex);
sourceJarRelativePath.add(version);
String sourceJarName = artifactId + "-" + version + SOURCES_JAR_NAME_SUFFIX;
sourceJarRelativePath.add(sourceJarName);
File sourceJar = new File(repositoryLocation, join(toStringArray(sourceJarRelativePath)));
return sourceJar.isFile() ? sourceJar : null;
}
}
return null;
}
@Nullable
private static File getJarFromJarUrl(@NotNull String url) {
// URLs for jar file start with "jar://" and end with "!/".
if (!url.startsWith(JAR_PROTOCOL_PREFIX)) {
return null;
}
String path = url.substring(JAR_PROTOCOL_PREFIX.length());
int index = path.lastIndexOf(JAR_SEPARATOR);
if (index != -1) {
path = path.substring(0, index);
}
return new File(toSystemDependentName(path));
}
private void findAndShowVariantConflicts() {
ConflictSet conflicts = findConflicts(myProject);
List<Conflict> structureConflicts = conflicts.getStructureConflicts();
if (!structureConflicts.isEmpty() && SystemProperties.getBooleanProperty("enable.project.profiles", false)) {
ProjectProfileSelectionDialog dialog = new ProjectProfileSelectionDialog(myProject, structureConflicts);
dialog.show();
}
List<Conflict> selectionConflicts = conflicts.getSelectionConflicts();
if (!selectionConflicts.isEmpty()) {
boolean atLeastOneSolved = solveSelectionConflicts(selectionConflicts);
if (atLeastOneSolved) {
conflicts = findConflicts(myProject);
}
}
conflicts.showSelectionConflicts();
}
private void addSdkLinkIfNecessary() {
ProjectSyncMessages messages = ProjectSyncMessages.getInstance(myProject);
int sdkErrorCount = messages.getMessageCount(FAILED_TO_SET_UP_SDK);
if (sdkErrorCount > 0) {
// If we have errors due to platforms not being installed, we add an extra message that prompts user to open Android SDK manager and
// install any missing platforms.
String text = "Open Android SDK Manager and install all missing platforms.";
Message hint = new Message(FAILED_TO_SET_UP_SDK, Message.Type.INFO, NonNavigatable.INSTANCE, text);
messages.add(hint, new OpenAndroidSdkManagerHyperlink());
}
}
private static void checkSdkToolsVersion(@NotNull Project project) {
if (project.isDisposed() || ourNewSdkVersionToolsInfoAlreadyShown) {
return;
}
// Piggy-back off of the SDK update check (which is called from a handful of places) to also see if this is an expired preview build
checkExpiredPreviewBuild(project);
File androidHome = IdeSdks.getAndroidSdkPath();
if (androidHome != null && !VersionCheck.isCompatibleVersion(androidHome)) {
InstallSdkToolsHyperlink hyperlink = new InstallSdkToolsHyperlink(VersionCheck.MIN_TOOLS_REV);
String message = "Version " + VersionCheck.MIN_TOOLS_REV + " is available.";
AndroidGradleNotification.getInstance(project).showBalloon("Android SDK Tools", message, INFORMATION, hyperlink);
ourNewSdkVersionToolsInfoAlreadyShown = true;
}
}
private static void checkExpiredPreviewBuild(@NotNull Project project) {
if (project.isDisposed() || ourCheckedExpiration) {
return;
}
String fullVersion = ApplicationInfo.getInstance().getFullVersion();
if (fullVersion.contains("Preview") || fullVersion.contains("Beta") || fullVersion.contains("RC")) {
// Expire preview builds two months after their build date (which is going to be roughly six weeks after release; by
// then will definitely have updated the build
Calendar expirationDate = (Calendar)ApplicationInfo.getInstance().getBuildDate().clone();
expirationDate.add(Calendar.MONTH, 2);
Calendar now = Calendar.getInstance();
if (now.after(expirationDate)) {
OpenUrlHyperlink hyperlink = new OpenUrlHyperlink("http://tools.android.com/download/studio/", "Show Available Versions");
String message = String.format("This preview build (%1$s) is old; please update to a newer preview or a stable version",
fullVersion);
AndroidGradleNotification.getInstance(project).showBalloon("Old Preview Build", message, INFORMATION, hyperlink);
// If we show an expiration message, don't also show a second balloon regarding available SDKs
ourNewSdkVersionToolsInfoAlreadyShown = true;
}
}
ourCheckedExpiration = true;
}
private void ensureValidSdks() {
boolean checkJdkVersion = true;
Collection<Sdk> invalidAndroidSdks = Sets.newHashSet();
ModuleManager moduleManager = ModuleManager.getInstance(myProject);
for (Module module : moduleManager.getModules()) {
AndroidFacet androidFacet = ModuleUtilCore.getExtension(module, AndroidModuleExtension.class);
if (androidFacet != null && androidFacet.getIdeaAndroidProject() != null) {
Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null && !invalidAndroidSdks.contains(sdk) && (isMissingAndroidLibrary(sdk) || shouldRemoveAnnotationsJar(sdk))) {
// First try to recreate SDK; workaround for issue 78072
AndroidSdkAdditionalData additionalData = getAndroidSdkAdditionalData(sdk);
AndroidSdkData sdkData = AndroidSdkData.getSdkData(sdk);
if (additionalData != null && sdkData != null) {
IAndroidTarget target = additionalData.getBuildTarget(sdkData);
if (target == null) {
LocalSdk localSdk = sdkData.getLocalSdk();
localSdk.clearLocalPkg(EnumSet.of(PkgType.PKG_PLATFORM));
target = localSdk.getTargetFromHashString(additionalData.getBuildTargetHashString());
}
if (target != null) {
SdkModificator sdkModificator = sdk.getSdkModificator();
sdkModificator.removeAllRoots();
for (OrderRoot orderRoot : getLibraryRootsForTarget(target, sdk.getHomePath(), true)) {
sdkModificator.addRoot(orderRoot.getFile(), orderRoot.getType());
}
attachJdkAnnotations(sdkModificator);
sdkModificator.commitChanges();
}
}
// If attempting to fix up the roots in the SDK fails, install the target over again
// (this is a truly corrupt install, as opposed to an incorrectly synced SDK which the
// above workaround deals with)
if (isMissingAndroidLibrary(sdk)) {
invalidAndroidSdks.add(sdk);
}
}
IdeaAndroidProject androidProject = androidFacet.getIdeaAndroidProject();
if (checkJdkVersion && !hasCorrectJdkVersion(module, androidProject)) {
// we already displayed the error, no need to check each module.
checkJdkVersion = false;
}
}
}
if (!invalidAndroidSdks.isEmpty()) {
reinstallMissingPlatforms(invalidAndroidSdks);
}
}
private static boolean isMissingAndroidLibrary(@NotNull Sdk sdk) {
if (isAndroidSdk(sdk)) {
for (VirtualFile library : sdk.getRootProvider().getFiles(CLASSES)) {
// This code does not through the classes in the Android SDK. It iterates through a list of 3 files in the IDEA SDK: android.jar,
// annotations.jar and res folder.
if (library.getName().equals(FN_FRAMEWORK_LIBRARY) && library.exists()) {
return false;
}
}
}
return true;
}
/*
* Indicates whether annotations.jar should be removed from the given SDK (if it is an Android SDK.)
* There are 2 issues:
* 1. annotations.jar is not needed for API level 16 and above. The annotations are already included in android.jar. Until recently, the
* IDE added annotations.jar to the IDEA Android SDK definition unconditionally.
* 2. Because annotations.jar is in the classpath, the IDE locks the file on Windows making automatic updates of SDK Tools fail. The
* update not only fails, it corrupts the 'tools' folder in the SDK.
* From now on, creating IDEA Android SDKs will not include annotations.jar if API level is 16 or above, but we still need to remove
* this jar from existing IDEA Android SDKs.
*/
private static boolean shouldRemoveAnnotationsJar(@NotNull Sdk sdk) {
if (isAndroidSdk(sdk)) {
AndroidSdkAdditionalData additionalData = getAndroidSdkAdditionalData(sdk);
AndroidSdkData sdkData = AndroidSdkData.getSdkData(sdk);
boolean needsAnnotationsJar = false;
if (additionalData != null && sdkData != null) {
IAndroidTarget target = additionalData.getBuildTarget(sdkData);
if (target != null) {
needsAnnotationsJar = needsAnnotationsJarInClasspath(target);
}
}
for (VirtualFile library : sdk.getRootProvider().getFiles(CLASSES)) {
// This code does not through the classes in the Android SDK. It iterates through a list of 3 files in the IDEA SDK: android.jar,
// annotations.jar and res folder.
if (library.getName().equals(FN_ANNOTATIONS_JAR) && library.exists() && !needsAnnotationsJar) {
return true;
}
}
}
return false;
}
private void reinstallMissingPlatforms(@NotNull Collection<Sdk> invalidAndroidSdks) {
ProjectSyncMessages messages = ProjectSyncMessages.getInstance(myProject);
List<AndroidVersion> versionsToInstall = Lists.newArrayList();
List<String> missingPlatforms = Lists.newArrayList();
for (Sdk sdk : invalidAndroidSdks) {
AndroidSdkAdditionalData additionalData = getAndroidSdkAdditionalData(sdk);
if (additionalData != null) {
String platform = additionalData.getBuildTargetHashString();
if (platform != null) {
missingPlatforms.add("'" + platform + "'");
AndroidVersion version = AndroidTargetHash.getPlatformVersion(platform);
if (version != null) {
versionsToInstall.add(version);
}
}
}
}
if (!versionsToInstall.isEmpty()) {
String group = String.format(FAILED_TO_SYNC_GRADLE_PROJECT_ERROR_GROUP_FORMAT, myProject.getName());
String text = "Missing Android platform(s) detected: " + Joiner.on(", ").join(missingPlatforms);
Message msg = new Message(group, Message.Type.ERROR, text);
messages.add(msg, new InstallPlatformHyperlink(versionsToInstall.toArray(new AndroidVersion[versionsToInstall.size()])));
}
}
public void setGenerateSourcesAfterSync(boolean generateSourcesAfterSync) {
myGenerateSourcesAfterSync = generateSourcesAfterSync;
}
public void setLastSyncTimestamp(long lastSyncTimestamp) {
myLastSyncTimestamp = lastSyncTimestamp;
}
public void setUsingCachedProjectData(boolean usingCachedProjectData) {
myUsingCachedProjectData = usingCachedProjectData;
}
private static class InstallSdkToolsHyperlink extends NotificationHyperlink {
@NotNull private final FullRevision myVersion;
InstallSdkToolsHyperlink(@NotNull FullRevision version) {
super("install.build.tools", "Install Tools " + version);
myVersion = version;
}
@Override
protected void execute(@NotNull Project project) {
List<IPkgDesc> requested = Lists.newArrayList();
if (myVersion.getMajor() == 23) {
FullRevision minBuildToolsRev = new FullRevision(20, 0, 0);
requested.add(PkgDesc.Builder.newPlatformTool(minBuildToolsRev).create());
}
requested.add(PkgDesc.Builder.newTool(myVersion, myVersion).create());
SdkQuickfixWizard wizard = new SdkQuickfixWizard(project, null, requested);
wizard.init();
if (wizard.showAndGet()) {
GradleProjectImporter.getInstance().requestProjectSync(project, null);
}
}
}
}
| apache-2.0 |
Barry1990/ad | src/main/java/com/gxq/util/HttpKit.java | 6439 | package com.gxq.util;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.Response;
/**
* 创建时间:2016年11月8日 下午5:16:32
*
* @author andy
* @version 2.2
*/
public class HttpKit {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final int CONNECT_TIME_OUT = 5000; //链接超时时间3秒
private static SSLContext wx_ssl_context = null; //微信支付ssl证书
static{
Resource resource = new ClassPathResource("wx_apiclient_cert.p12"); //获取微信证书 或者直接从文件流读取
char[] keyStorePassword = ConfigUtil.getProperty("wx.mchid").toCharArray(); //证书密码
try {
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(resource.getInputStream(), keyStorePassword);
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, keyStorePassword);
SSLContext wx_ssl_context = SSLContext.getInstance("TLS");
wx_ssl_context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @description 功能描述: get 请求
* @param url 请求地址
* @param params 参数
* @param headers headers参数
* @return 请求失败返回null
*/
public static String get(String url, Map<String, String> params, Map<String, String> headers) {
AsyncHttpClient http = new AsyncHttpClient(new AsyncHttpClientConfig.Builder()
.setConnectTimeout(CONNECT_TIME_OUT).build());
AsyncHttpClient.BoundRequestBuilder builder = http.prepareGet(url);
builder.setBodyEncoding(DEFAULT_CHARSET);
if (params != null && !params.isEmpty()) {
Set<String> keys = params.keySet();
for (String key : keys) {
builder.addQueryParam(key, params.get(key));
}
}
if (headers != null && !headers.isEmpty()) {
Set<String> keys = headers.keySet();
for (String key : keys) {
builder.addHeader(key, params.get(key));
}
}
Future<Response> f = builder.execute();
String body = null;
try {
body = f.get().getResponseBody(DEFAULT_CHARSET);
} catch (Exception e) {
e.printStackTrace();
}
http.close();
return body;
}
/**
* @description 功能描述: get 请求
* @param url 请求地址
* @return 请求失败返回null
*/
public static String get(String url) {
return get(url, null);
}
/**
* @description 功能描述: get 请求
* @param url 请求地址
* @param params 参数
* @return 请求失败返回null
*/
public static String get(String url, Map<String, String> params) {
return get(url, params, null);
}
/**
* @description 功能描述: post 请求
* @param url 请求地址
* @param params 参数
* @return 请求失败返回null
*/
public static String post(String url, Map<String, String> params) {
AsyncHttpClient http = new AsyncHttpClient(new AsyncHttpClientConfig.Builder()
.setConnectTimeout(CONNECT_TIME_OUT).build());
AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
builder.setBodyEncoding(DEFAULT_CHARSET);
if (params != null && !params.isEmpty()) {
Set<String> keys = params.keySet();
for (String key : keys) {
builder.addQueryParam(key, params.get(key));
}
}
Future<Response> f = builder.execute();
String body = null;
try {
body = f.get().getResponseBody(DEFAULT_CHARSET);
} catch (Exception e) {
e.printStackTrace();
}
http.close();
return body;
}
/**
* @description 功能描述: post 请求
* @param url 请求地址
* @param s 参数xml
* @return 请求失败返回null
*/
public static String post(String url, String s) {
AsyncHttpClient http = new AsyncHttpClient(new AsyncHttpClientConfig.Builder()
.setConnectTimeout(CONNECT_TIME_OUT).build());
AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
builder.setBodyEncoding(DEFAULT_CHARSET);
builder.setBody(s);
Future<Response> f = builder.execute();
String body = null;
try {
body = f.get().getResponseBody(DEFAULT_CHARSET);
} catch (Exception e) {
e.printStackTrace();
}
http.close();
return body;
}
/**
* @description 功能描述: post https请求,服务器双向证书验证
* @param url 请求地址
* @param params 参数
* @return 请求失败返回null
*/
public static String posts(String url, Map<String, String> params){
AsyncHttpClient http = new AsyncHttpClient(
new AsyncHttpClientConfig.Builder()
.setConnectTimeout(CONNECT_TIME_OUT)
.setSSLContext(wx_ssl_context)
.build());
AsyncHttpClient.BoundRequestBuilder bbuilder = http.preparePost(url);
bbuilder.setBodyEncoding(DEFAULT_CHARSET);
if (params != null && !params.isEmpty()) {
Set<String> keys = params.keySet();
for (String key : keys) {
bbuilder.addQueryParam(key, params.get(key));
}
}
Future<Response> f = bbuilder.execute();
String body = null;
try {
body = f.get().getResponseBody(DEFAULT_CHARSET);
} catch (Exception e) {
e.printStackTrace();
}
http.close();
return body;
}
/**
* @description 功能描述: post https请求,服务器双向证书验证
* @param url 请求地址
* @param s 参数xml
* @return 请求失败返回null
*/
public static String posts(String url, String s) {
AsyncHttpClient http = new AsyncHttpClient(
new AsyncHttpClientConfig.Builder()
.setConnectTimeout(CONNECT_TIME_OUT)
.setSSLContext(wx_ssl_context).build());
AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
builder.setBodyEncoding(DEFAULT_CHARSET);
builder.setBody(s);
Future<Response> f = builder.execute();
String body = null;
try {
body = f.get().getResponseBody(DEFAULT_CHARSET);
} catch (Exception e) {
e.printStackTrace();
}
http.close();
return body;
}
} | apache-2.0 |
support-project/knowledge | src/main/java/org/support/project/knowledge/dao/gen/GenServiceConfigsDao.java | 16811 | package org.support.project.knowledge.dao.gen;
import java.util.List;
import java.io.InputStream;
import java.sql.Timestamp;
import org.support.project.knowledge.entity.ServiceConfigsEntity;
import org.support.project.ormapping.dao.AbstractDao;
import org.support.project.ormapping.exception.ORMappingException;
import org.support.project.ormapping.common.SQLManager;
import org.support.project.ormapping.common.DBUserPool;
import org.support.project.ormapping.common.IDGen;
import org.support.project.ormapping.config.ORMappingParameter;
import org.support.project.ormapping.config.Order;
import org.support.project.ormapping.connection.ConnectionManager;
import org.support.project.common.util.PropertyUtil;
import org.support.project.common.util.DateUtils;
import org.support.project.di.Container;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.aop.Aspect;
/**
* サービスの設定
* this class is auto generate and not edit.
* if modify dao method, you can edit ServiceConfigsDao.
*/
@DI(instance = Instance.Singleton)
public class GenServiceConfigsDao extends AbstractDao {
/** SerialVersion */
private static final long serialVersionUID = 1L;
/**
* Get instance from DI container.
* @return instance
*/
public static GenServiceConfigsDao get() {
return Container.getComp(GenServiceConfigsDao.class);
}
/**
* Select all data.
* @return all data
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public List<ServiceConfigsEntity> physicalSelectAll() {
return physicalSelectAll(Order.DESC);
}
/**
* Select all data.
* @param order order
* @return all data
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public List<ServiceConfigsEntity> physicalSelectAll(Order order) {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_physical_select_all.sql");
sql = String.format(sql, order.toString());
return executeQueryList(sql, ServiceConfigsEntity.class);
}
/**
* Select all data with pager.
* @param limit limit
* @param offset offset
* @return all data on limit and offset
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public List<ServiceConfigsEntity> physicalSelectAllWithPager(int limit, int offset) {
return physicalSelectAllWithPager(limit, offset, Order.DESC);
}
/**
* Select all data with pager.
* @param limit limit
* @param offset offset
* @param order order
* @return all data on limit and offset
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public List<ServiceConfigsEntity> physicalSelectAllWithPager(int limit, int offset, Order order) {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_physical_select_all_with_pager.sql");
sql = String.format(sql, order.toString());
return executeQueryList(sql, ServiceConfigsEntity.class, limit, offset);
}
/**
* Select data on key.
* @param serviceName serviceName
* @return data
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity physicalSelectOnKey(String serviceName) {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_physical_select_on_key.sql");
return executeQuerySingle(sql, ServiceConfigsEntity.class, serviceName);
}
/**
* Select all data that not deleted.
* @return all data
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public List<ServiceConfigsEntity> selectAll() {
return selectAll(Order.DESC);
}
/**
* Select all data that not deleted.
* @param order order
* @return all data
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public List<ServiceConfigsEntity> selectAll(Order order) {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_select_all.sql");
sql = String.format(sql, order.toString());
return executeQueryList(sql, ServiceConfigsEntity.class);
}
/**
* Select all data that not deleted with pager.
* @param limit limit
* @param offset offset
* @return all data
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public List<ServiceConfigsEntity> selectAllWidthPager(int limit, int offset) {
return selectAllWidthPager(limit, offset, Order.DESC);
}
/**
* Select all data that not deleted with pager.
* @param limit limit
* @param offset offset
* @param order order
* @return all data
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public List<ServiceConfigsEntity> selectAllWidthPager(int limit, int offset, Order order) {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_select_all_with_pager.sql");
sql = String.format(sql, order.toString());
return executeQueryList(sql, ServiceConfigsEntity.class, limit, offset);
}
/**
* Select count that not deleted.
* @return count
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public Integer selectCountAll() {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_select_count_all.sql");
return executeQuerySingle(sql, Integer.class);
}
/**
* Select data that not deleted on key.
* @param serviceName serviceName
* @return data
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity selectOnKey(String serviceName) {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_select_on_key.sql");
return executeQuerySingle(sql, ServiceConfigsEntity.class, serviceName);
}
/**
* Count all data
* @return count
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public int physicalCountAll() {
String sql = "SELECT COUNT(*) FROM SERVICE_CONFIGS";
return executeQuerySingle(sql, Integer.class);
}
/**
* Physical Insert.
* it is not create key on database sequence.
* @param entity entity
* @return saved entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity rawPhysicalInsert(ServiceConfigsEntity entity) {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_raw_insert.sql");
executeUpdate(sql,
entity.getServiceName(),
entity.getServiceLabel(),
entity.getServiceIcon(),
entity.getServiceImage(),
entity.getInsertUser(),
entity.getInsertDatetime(),
entity.getUpdateUser(),
entity.getUpdateDatetime(),
entity.getDeleteFlag());
return entity;
}
/**
* Physical Insert.
* if key column have sequence, key value create by database.
* @param entity entity
* @return saved entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity physicalInsert(ServiceConfigsEntity entity) {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_insert.sql");
executeUpdate(sql,
entity.getServiceName(),
entity.getServiceLabel(),
entity.getServiceIcon(),
entity.getServiceImage(),
entity.getInsertUser(),
entity.getInsertDatetime(),
entity.getUpdateUser(),
entity.getUpdateDatetime(),
entity.getDeleteFlag());
return entity;
}
/**
* Insert.
* set saved user id.
* @param user saved userid
* @param entity entity
* @return saved entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity insert(Integer user, ServiceConfigsEntity entity) {
entity.setInsertUser(user);
entity.setInsertDatetime(new Timestamp(DateUtils.now().getTime()));
entity.setUpdateUser(user);
entity.setUpdateDatetime(new Timestamp(DateUtils.now().getTime()));
entity.setDeleteFlag(0);
return physicalInsert(entity);
}
/**
* Insert.
* saved user id is auto set.
* @param entity entity
* @return saved entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity insert(ServiceConfigsEntity entity) {
DBUserPool pool = Container.getComp(DBUserPool.class);
Integer userId = (Integer) pool.getUser();
return insert(userId, entity);
}
/**
* Physical Update.
* @param entity entity
* @return saved entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity physicalUpdate(ServiceConfigsEntity entity) {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_update.sql");
executeUpdate(sql,
entity.getServiceLabel(),
entity.getServiceIcon(),
entity.getServiceImage(),
entity.getInsertUser(),
entity.getInsertDatetime(),
entity.getUpdateUser(),
entity.getUpdateDatetime(),
entity.getDeleteFlag(),
entity.getServiceName());
return entity;
}
/**
* Update.
* set saved user id.
* @param user saved userid
* @param entity entity
* @return saved entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity update(Integer user, ServiceConfigsEntity entity) {
ServiceConfigsEntity db = selectOnKey(entity.getServiceName());
entity.setInsertUser(db.getInsertUser());
entity.setInsertDatetime(db.getInsertDatetime());
entity.setDeleteFlag(db.getDeleteFlag());
entity.setUpdateUser(user);
entity.setUpdateDatetime(new Timestamp(DateUtils.now().getTime()));
return physicalUpdate(entity);
}
/**
* Update.
* saved user id is auto set.
* @param entity entity
* @return saved entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity update(ServiceConfigsEntity entity) {
DBUserPool pool = Container.getComp(DBUserPool.class);
Integer userId = (Integer) pool.getUser();
return update(userId, entity);
}
/**
* Save.
* if same key data is exists, the data is update. otherwise the data is insert.
* set saved user id.
* @param user saved userid
* @param entity entity
* @return saved entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity save(Integer user, ServiceConfigsEntity entity) {
ServiceConfigsEntity db = selectOnKey(entity.getServiceName());
if (db == null) {
return insert(user, entity);
} else {
return update(user, entity);
}
}
/**
* Save.
* if same key data is exists, the data is update. otherwise the data is insert.
* @param entity entity
* @return saved entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public ServiceConfigsEntity save(ServiceConfigsEntity entity) {
ServiceConfigsEntity db = selectOnKey(entity.getServiceName());
if (db == null) {
return insert(entity);
} else {
return update(entity);
}
}
/**
* Physical Delete.
* @param serviceName serviceName
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void physicalDelete(String serviceName) {
String sql = SQLManager.getInstance().getSql("/org/support/project/knowledge/dao/sql/ServiceConfigsDao/ServiceConfigsDao_delete.sql");
executeUpdate(sql, serviceName);
}
/**
* Physical Delete.
* @param entity entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void physicalDelete(ServiceConfigsEntity entity) {
physicalDelete(entity.getServiceName());
}
/**
* Delete.
* if delete flag is exists, the data is logical delete.
* set saved user id.
* @param user saved userid
* @param serviceName serviceName
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void delete(Integer user, String serviceName) {
ServiceConfigsEntity db = selectOnKey(serviceName);
db.setDeleteFlag(1);
db.setUpdateUser(user);
db.setUpdateDatetime(new Timestamp(DateUtils.now().getTime()));
physicalUpdate(db);
}
/**
* Delete.
* if delete flag is exists, the data is logical delete.
* @param serviceName serviceName
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void delete(String serviceName) {
DBUserPool pool = Container.getComp(DBUserPool.class);
Integer user = (Integer) pool.getUser();
delete(user, serviceName);
}
/**
* Delete.
* if delete flag is exists, the data is logical delete.
* set saved user id.
* @param user saved userid
* @param entity entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void delete(Integer user, ServiceConfigsEntity entity) {
delete(user, entity.getServiceName());
}
/**
* Delete.
* if delete flag is exists, the data is logical delete.
* set saved user id.
* @param entity entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void delete(ServiceConfigsEntity entity) {
delete(entity.getServiceName());
}
/**
* Ativation.
* if delete flag is exists and delete flag is true, delete flug is false to activate.
* set saved user id.
* @param user saved userid
* @param serviceName serviceName
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void activation(Integer user, String serviceName) {
ServiceConfigsEntity db = physicalSelectOnKey(serviceName);
db.setDeleteFlag(0);
db.setUpdateUser(user);
db.setUpdateDatetime(new Timestamp(DateUtils.now().getTime()));
physicalUpdate(db);
}
/**
* Ativation.
* if delete flag is exists and delete flag is true, delete flug is false to activate.
* @param serviceName serviceName
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void activation(String serviceName) {
DBUserPool pool = Container.getComp(DBUserPool.class);
Integer user = (Integer) pool.getUser();
activation(user, serviceName);
}
/**
* Ativation.
* if delete flag is exists and delete flag is true, delete flug is false to activate.
* set saved user id.
* @param user saved userid
* @param entity entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void activation(Integer user, ServiceConfigsEntity entity) {
activation(user, entity.getServiceName());
}
/**
* Ativation.
* if delete flag is exists and delete flag is true, delete flug is false to activate.
* @param entity entity
*/
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public void activation(ServiceConfigsEntity entity) {
activation(entity.getServiceName());
}
}
| apache-2.0 |
yuyakaido/CouplesCalendar | couples-calendar/src/main/java/com/yuyakaido/android/couplescalendar/model/InternalEvent.java | 3661 | package com.yuyakaido.android.couplescalendar.model;
import android.text.TextUtils;
import com.yuyakaido.android.couplescalendar.util.CalendarUtils;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by yuyakaido on 8/14/15.
*/
public class InternalEvent implements CouplesCalendarEvent {
private DateTime mStartAt;
private DateTime mEndAt;
private String mRecurrenceRule;
private LinePosition mLinePosition;
private DurationType mDurationType;
private EventType mEventType = EventType.NORMAL;
private int mEventColor;
@Override
public Date getStartAt() {
return mStartAt.toDate();
}
public DateTime getStartAtDateTime() {
return mStartAt;
}
public DateTime getZonedStartAt() {
return CalendarUtils.getZonedDateTime(mStartAt);
}
public void setStartAt(DateTime startAt) {
mStartAt = startAt;
setDurationType();
}
@Override
public Date getEndAt() {
return mEndAt.toDate();
}
public DateTime getEndAtDateTime() {
return mEndAt;
}
public DateTime getZonedEndAt() {
return CalendarUtils.getZonedDateTime(mEndAt);
}
public void setEndAt(DateTime endAt) {
mEndAt = endAt;
setDurationType();
}
public String getRecurrenceRule() {
return mRecurrenceRule;
}
public void setRecurrenceRule(String recurrenceRule) {
mRecurrenceRule = recurrenceRule;
if (TextUtils.isEmpty(mRecurrenceRule)) {
mEventType = EventType.NORMAL;
} else {
mEventType = EventType.RECURRING;
}
}
public LinePosition getLinePosition() {
return mLinePosition;
}
public void setLinePosition(LinePosition linePosition) {
mLinePosition = linePosition;
}
public DurationType getDurationType() {
return mDurationType;
}
public void setDurationType() {
if (mStartAt != null && mEndAt != null) {
Duration duration = new Duration(mStartAt, mEndAt);
if (!CalendarUtils.isSameDay(mStartAt, mEndAt)
&& CalendarUtils.isLongerThenTwelveHours(duration)) {
mDurationType = DurationType.MULTIPLE_DAYS;
} else {
mDurationType = DurationType.ONE_DAY;
}
}
}
public EventType getEventType() {
return mEventType;
}
public void setEventType(EventType eventType) {
mEventType = eventType;
}
@Override
public int getEventColor() {
return mEventColor;
}
public void setEventColor(int eventColor) {
mEventColor = eventColor;
}
/**
* そのイベントが属している日付リストを返す
* (例)
* 2015-06-25 から 2015-06-26 までのイベントだった場合
* 2015-06-25, 2015-06-26 が返る
* @return
*/
public List<DateTime> getEventDays() {
List<DateTime> days = new ArrayList<>();
DateTime startAtDateTime = CalendarUtils.getMidnight(getZonedStartAt());
DateTime endAtDateTime = CalendarUtils.getMidnight(getZonedEndAt());
days.add(startAtDateTime);
if (CalendarUtils.isSameDay(startAtDateTime, endAtDateTime)) {
return days;
} else {
while (!CalendarUtils.isEqualOrAfter(startAtDateTime, endAtDateTime)) {
startAtDateTime = startAtDateTime.plusDays(1);
days.add(startAtDateTime);
}
return days;
}
}
}
| apache-2.0 |
ksaric/DbTester | src/main/java/hr/oet/dbtester/tester/list/DbTester.java | 3770 | package hr.oet.dbtester.tester.list;
import com.google.common.collect.*;
import hr.oet.dbtester.ParametersProvider;
import hr.oet.dbtester.ResultProvider;
import hr.oet.dbtester.datasource.DataSourceFactory;
import oracle.jdbc.pool.OracleDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;
/**
* User: ksaric
*/
abstract class DbTester {
protected QueryRunner queryRunner;
private DataSourceFactory dataSourceFactory;
protected DbTester( DataSourceFactory dataSourceFactory ) {
this.dataSourceFactory = dataSourceFactory;
}
public <T> List<T> runSQLMultiple( final QueryRunner run, final List<String> sql, Class<T> aClass, final Object... params ) {
List<T> list = Lists.newArrayList();
ResultSetHandler<List<T>> resultSetHandler = new BeanListHandler<>( aClass );
try {
for ( String currentDml : sql ) {
List<T> query = run.query( currentDml, resultSetHandler, params );
list.addAll( query );
}
return list;
} catch ( SQLException e ) {
e.printStackTrace();
}
throw new RuntimeException( "FATAL!" );
}
protected int runDMLMultiple( final QueryRunner run, final List<String> dml ) {
try {
int totalModified = 0;
for ( String currentDml : dml ) {
totalModified += run.update( currentDml );
}
return totalModified;
} catch ( SQLException e ) {
e.printStackTrace();
}
throw new RuntimeException( "FATAL!" );
}
protected int runDMLSingle( final QueryRunner run, final String dml ) {
try {
return run.update( dml );
} catch ( SQLException e ) {
e.printStackTrace();
}
throw new RuntimeException( "FATAL!" );
}
protected void prepareDataSourceQueryRunner() {
dataSourceFactory.checkForDriver();
final OracleDataSource dataSource = dataSourceFactory.getDataSourceUnchecked();
queryRunner = new QueryRunner( dataSource );
}
protected PreparedStatement getPreparedStatement( final String statement ) {
try {
return queryRunner.getDataSource().getConnection().prepareStatement( statement );
} catch ( SQLException e ) {
e.printStackTrace();
}
throw new RuntimeException( "FATAL!" );
}
protected CallableStatement getCallableStatement( final String statement ) {
try {
return queryRunner.getDataSource().getConnection().prepareCall( statement );
} catch ( SQLException e ) {
e.printStackTrace();
}
throw new RuntimeException( "FATAL!" );
}
public abstract <T extends List<String>> void input( final ParametersProvider<T> parameters );
// public abstract <T extends List<String>> void input( final String scriptName );
public abstract Boolean function( final String statement, final Object... params );
public abstract <T, L extends List<String>> ResultProvider<List<T>> output( final ParametersProvider<L> selectScripts, final Class<T> type, final Objects... params );
public abstract <K, L extends List<String>> ResultProvider<List<K>> listOutput( ParametersProvider<L> selectScripts, Class<K> type, Objects... params );
public abstract Boolean cleanup( final List<String> downScripts );
// public abstract Boolean cleanup( final String scriptName );
}
| apache-2.0 |
edithzavala/sacre-sv | SmartVehicleView/SmartVehicleView/src/edu/smartvehicle/view/reader/ActuatorsReader.java | 1303 | package edu.smartvehicle.view.reader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* @author Edith Zavala
*/
public class ActuatorsReader {
public void readActuators(SmartVehicleViewReader svvr, String fileName) {
/* Read a file and assign values to readings */
FileInputStream file;
XSSFWorkbook test;
try {
file = new FileInputStream(fileName);
test = new XSSFWorkbook(file);
XSSFSheet driverSensors = test.getSheetAt(0);
Iterator<Row> driverSensorsIterator = driverSensors.iterator();
driverSensorsIterator.next();
while (driverSensorsIterator.hasNext()) {
Row row = driverSensorsIterator.next();
if (row.getCell(0) == null) {
break;
}
svvr.getSupportLaneKeeping().add(row.getCell(1));
svvr.getVibrationAlarm()
.add(row.getCell(2));
svvr.getSoundLightAlarm().add(
row.getCell(3));
svvr.getSupportLaneKeepingE().add(row.getCell(4));
svvr.getVibrationAlarmE()
.add(row.getCell(5));
svvr.getSoundLightAlarmE().add(
row.getCell(6));
}
test.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| apache-2.0 |
syntelos/gwtcc | src/com/google/gwt/dom/client/HeadingElement.java | 2043 | /*
* Copyright 2008 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.gwt.dom.client;
/**
* For the H1 to H6 elements.
*
* @see <a
* href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#edef-H1">W3C
* HTML Specification</a>
*/
@TagName({HeadingElement.TAG_H1, HeadingElement.TAG_H2, HeadingElement.TAG_H3,
HeadingElement.TAG_H4, HeadingElement.TAG_H5, HeadingElement.TAG_H6})
public class HeadingElement extends Element {
static final String[] TAGS = {
HeadingElement.TAG_H1, HeadingElement.TAG_H2, HeadingElement.TAG_H3,
HeadingElement.TAG_H4, HeadingElement.TAG_H5, HeadingElement.TAG_H6};
public static final String TAG_H1 = "h1";
public static final String TAG_H2 = "h2";
public static final String TAG_H3 = "h3";
public static final String TAG_H4 = "h4";
public static final String TAG_H5 = "h5";
public static final String TAG_H6 = "h6";
/**
* Assert that the given {@link Element} is compatible with this class and
* automatically typecast it.
*/
public static HeadingElement as(Element elem) {
if (HeadingElement.class.desiredAssertionStatus()) {
// Assert that this element's tag name is one of [h1 .. h6].
String tag = elem.getTagName().toLowerCase();
assert tag.length() == 2;
assert tag.charAt(0) == 'h';
int n = Integer.parseInt(tag.substring(1, 2));
assert (n >= 1) && (n <= 6);
}
return (HeadingElement) elem;
}
protected HeadingElement() {
}
}
| apache-2.0 |
hazendaz/assertj-core | src/test/java/org/assertj/core/api/Assertions_withinPercentage_Test.java | 1154 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.withinPercentage;
import org.junit.jupiter.api.Test;
class Assertions_withinPercentage_Test {
@Test
void should_create_double() {
assertThat(withinPercentage(1d)).isNotNull();
}
@Test
void should_create_integer() {
assertThat(withinPercentage(1)).isNotNull();
}
@Test
void should_create_long() {
assertThat(withinPercentage(1L)).isNotNull();
}
}
| apache-2.0 |
Uni-Sol/batik | sources/org/apache/batik/css/engine/sac/CSSAttributeCondition.java | 3552 | /*
Copyright 2002 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.batik.css.engine.sac;
import java.util.Set;
import org.w3c.dom.Element;
/**
* This class provides an implementation of the
* {@link org.w3c.css.sac.AttributeCondition} interface.
*
* @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
* @version $Id$
*/
public class CSSAttributeCondition extends AbstractAttributeCondition {
/**
* The attribute's local name.
*/
protected String localName;
/**
* The attribute's namespace URI.
*/
protected String namespaceURI;
/**
* Whether this condition applies to specified attributes.
*/
protected boolean specified;
/**
* Creates a new CSSAttributeCondition object.
*/
public CSSAttributeCondition(String localName,
String namespaceURI,
boolean specified,
String value) {
super(value);
this.localName = localName;
this.namespaceURI = namespaceURI;
this.specified = specified;
}
/**
* Indicates whether some other object is "equal to" this one.
* @param obj the reference object with which to compare.
*/
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
CSSAttributeCondition c = (CSSAttributeCondition)obj;
return (c.namespaceURI.equals(namespaceURI) &&
c.localName.equals(localName) &&
c.specified == specified);
}
/**
* <b>SAC</b>: Implements {@link
* org.w3c.css.sac.Condition#getConditionType()}.
*/
public short getConditionType() {
return SAC_ATTRIBUTE_CONDITION;
}
/**
* <b>SAC</b>: Implements {@link
* org.w3c.css.sac.AttributeCondition#getNamespaceURI()}.
*/
public String getNamespaceURI() {
return namespaceURI;
}
/**
* <b>SAC</b>: Implements {@link
* org.w3c.css.sac.AttributeCondition#getLocalName()}.
*/
public String getLocalName() {
return localName;
}
/**
* <b>SAC</b>: Implements {@link
* org.w3c.css.sac.AttributeCondition#getSpecified()}.
*/
public boolean getSpecified() {
return specified;
}
/**
* Tests whether this condition matches the given element.
*/
public boolean match(Element e, String pseudoE) {
String val = getValue();
if (val == null) {
return !e.getAttribute(getLocalName()).equals("");
}
return e.getAttribute(getLocalName()).equals(val);
}
/**
* Fills the given set with the attribute names found in this selector.
*/
public void fillAttributeSet(Set attrSet) {
attrSet.add(localName);
}
/**
* Returns a text representation of this object.
*/
public String toString() {
if (value == null) {
return "[" + localName + "]";
}
return "[" + localName + "=\"" + value + "\"]";
}
}
| apache-2.0 |
xe1gyq/androidlearning | training/NewCircle/github/FibonacciBinderDemo/FibonacciCommon/src/com/marakana/android/fibonaccicommon/FibonacciRequest.java | 1464 | package com.marakana.android.fibonaccicommon;
import android.os.Parcel;
import android.os.Parcelable;
public class FibonacciRequest implements Parcelable {
public static enum Type {
RECURSIVE_JAVA, ITERATIVE_JAVA, RECURSIVE_NATIVE, ITERATIVE_NATIVE
}
private long n;
private Type type;
public FibonacciRequest(long n, Type type) {
this.n = n;
if (type == null) {
throw new NullPointerException("Type must not be null");
}
this.type = type;
}
/** Constructors used implicitly with Parcelable */
public FibonacciRequest() {
this.n = 0;
this.type = Type.RECURSIVE_JAVA;
}
public FibonacciRequest(Parcel in) {
readFromParcel(in);
}
/** Public Accessors */
public long getN() {
return n;
}
public Type getType() {
return type;
}
/** Explicit Parcelable Requirements */
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeLong(this.n);
parcel.writeInt(this.type.ordinal());
}
/** Implicit Parcelable Requirements */
public void readFromParcel(Parcel in) {
this.n = in.readLong();
this.type = Type.values()[in.readInt()];
}
public static final Parcelable.Creator<FibonacciRequest> CREATOR = new Parcelable.Creator<FibonacciRequest>() {
public FibonacciRequest createFromParcel(Parcel in) {
return new FibonacciRequest(in);
}
public FibonacciRequest[] newArray(int size) {
return new FibonacciRequest[size];
}
};
}
| apache-2.0 |
statsbiblioteket/doms-client | domsClient-common-interface/src/main/java/dk/statsbiblioteket/doms/client/objects/DigitalObject.java | 4367 | package dk.statsbiblioteket.doms.client.objects;
import dk.statsbiblioteket.doms.client.datastreams.Datastream;
import dk.statsbiblioteket.doms.client.exceptions.NotFoundException;
import dk.statsbiblioteket.doms.client.exceptions.ServerOperationFailed;
import dk.statsbiblioteket.doms.client.exceptions.XMLParseException;
import dk.statsbiblioteket.doms.client.links.LinkPattern;
import dk.statsbiblioteket.doms.client.methods.Method;
import dk.statsbiblioteket.doms.client.relations.LiteralRelation;
import dk.statsbiblioteket.doms.client.relations.ObjectRelation;
import dk.statsbiblioteket.doms.client.relations.Relation;
import dk.statsbiblioteket.doms.client.utils.Constants;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* The digital Object
*/
public interface DigitalObject {
/**
* Saves the digital object to the Server.
*
* @throws ServerOperationFailed
*/
void save() throws ServerOperationFailed, XMLParseException;
/**
* Saves the digital object to the Server.
*
* @throws ServerOperationFailed
*/
void save(String viewAngle) throws ServerOperationFailed, XMLParseException;
/**
* @return the object pid
*/
String getPid();
Set<CollectionObject> getCollections() throws ServerOperationFailed;
public void addToCollection(CollectionObject collection) throws ServerOperationFailed;
/**
* @return the object's content models
*/
List<ContentModelObject> getType() throws ServerOperationFailed;
/**
* @return the object title
*/
String getTitle() throws ServerOperationFailed;
/**
* Set the object title. Will not save, yet
*
* @param title the title
*/
void setTitle(String title) throws ServerOperationFailed;
/**
* @return the Object State
*/
Constants.FedoraState getState() throws ServerOperationFailed;
void setState(Constants.FedoraState state) throws ServerOperationFailed;
public void setState(Constants.FedoraState state, String viewAngle) throws ServerOperationFailed;
/**
* @return the lastModified date for the object
*/
Date getLastModified() throws ServerOperationFailed;
/**
* @return the createdDate for the object
*/
Date getCreated() throws ServerOperationFailed;
/**
* @return The list of datastreams in the object
*/
List<Datastream> getDatastreams() throws ServerOperationFailed;
/**
* Create new internal datastream
*
* @param name the id of the datastream
*
* @return the datastream object
* @throws ServerOperationFailed
*/
Datastream addInternalDatastream(String name) throws ServerOperationFailed;
/**
* @param id datastream ID
*
* @return The datastream
* @throws ServerOperationFailed
*/
Datastream getDatastream(String id) throws ServerOperationFailed, NotFoundException;
/**
* Not implemented
*
* @param addition
*/
void addDatastream(Datastream addition) throws ServerOperationFailed;
/**
* Not implemented
*
* @param deleted
*/
void removeDatastream(Datastream deleted) throws ServerOperationFailed;
/**
* The list of relations in the object.
*
* @return
*/
List<Relation> getRelations() throws ServerOperationFailed;
/**
* The list of inverse relations. TODO implement
*
* @return
*/
List<ObjectRelation> getInverseRelations() throws ServerOperationFailed;
/**
* The list of inverse relations. TODO implement
*
* @return
*/
List<ObjectRelation> getInverseRelations(String predicate) throws ServerOperationFailed;
/**
* Remove a relation from this object
*
* @param relation the relation to remove
*/
void removeRelation(Relation relation) throws ServerOperationFailed;
ObjectRelation addObjectRelation(String predicate, DigitalObject object) throws ServerOperationFailed;
LiteralRelation addLiteralRelation(String predicate, String value);
public Set<DigitalObject> getChildObjects(String viewAngle) throws ServerOperationFailed;
public Set<Method> getMethods() throws ServerOperationFailed;
public List<LinkPattern> getLinkPatterns() throws ServerOperationFailed;
}
| apache-2.0 |
googleapis/java-vision | proto-google-cloud-vision-v1p4beta1/src/main/java/com/google/cloud/vision/v1p4beta1/ColorInfo.java | 26401 | /*
* 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/vision/v1p4beta1/image_annotator.proto
package com.google.cloud.vision.v1p4beta1;
/**
*
*
* <pre>
* Color information consists of RGB channels, score, and the fraction of
* the image that the color occupies in the image.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p4beta1.ColorInfo}
*/
public final class ColorInfo extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vision.v1p4beta1.ColorInfo)
ColorInfoOrBuilder {
private static final long serialVersionUID = 0L;
// Use ColorInfo.newBuilder() to construct.
private ColorInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ColorInfo() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ColorInfo();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ColorInfo(
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:
{
com.google.type.Color.Builder subBuilder = null;
if (color_ != null) {
subBuilder = color_.toBuilder();
}
color_ = input.readMessage(com.google.type.Color.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(color_);
color_ = subBuilder.buildPartial();
}
break;
}
case 21:
{
score_ = input.readFloat();
break;
}
case 29:
{
pixelFraction_ = input.readFloat();
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.cloud.vision.v1p4beta1.ImageAnnotatorProto
.internal_static_google_cloud_vision_v1p4beta1_ColorInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p4beta1.ImageAnnotatorProto
.internal_static_google_cloud_vision_v1p4beta1_ColorInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p4beta1.ColorInfo.class,
com.google.cloud.vision.v1p4beta1.ColorInfo.Builder.class);
}
public static final int COLOR_FIELD_NUMBER = 1;
private com.google.type.Color color_;
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*
* @return Whether the color field is set.
*/
@java.lang.Override
public boolean hasColor() {
return color_ != null;
}
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*
* @return The color.
*/
@java.lang.Override
public com.google.type.Color getColor() {
return color_ == null ? com.google.type.Color.getDefaultInstance() : color_;
}
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*/
@java.lang.Override
public com.google.type.ColorOrBuilder getColorOrBuilder() {
return getColor();
}
public static final int SCORE_FIELD_NUMBER = 2;
private float score_;
/**
*
*
* <pre>
* Image-specific score for this color. Value in range [0, 1].
* </pre>
*
* <code>float score = 2;</code>
*
* @return The score.
*/
@java.lang.Override
public float getScore() {
return score_;
}
public static final int PIXEL_FRACTION_FIELD_NUMBER = 3;
private float pixelFraction_;
/**
*
*
* <pre>
* The fraction of pixels the color occupies in the image.
* Value in range [0, 1].
* </pre>
*
* <code>float pixel_fraction = 3;</code>
*
* @return The pixelFraction.
*/
@java.lang.Override
public float getPixelFraction() {
return pixelFraction_;
}
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 (color_ != null) {
output.writeMessage(1, getColor());
}
if (score_ != 0F) {
output.writeFloat(2, score_);
}
if (pixelFraction_ != 0F) {
output.writeFloat(3, pixelFraction_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (color_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getColor());
}
if (score_ != 0F) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(2, score_);
}
if (pixelFraction_ != 0F) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(3, pixelFraction_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.vision.v1p4beta1.ColorInfo)) {
return super.equals(obj);
}
com.google.cloud.vision.v1p4beta1.ColorInfo other =
(com.google.cloud.vision.v1p4beta1.ColorInfo) obj;
if (hasColor() != other.hasColor()) return false;
if (hasColor()) {
if (!getColor().equals(other.getColor())) return false;
}
if (java.lang.Float.floatToIntBits(getScore())
!= java.lang.Float.floatToIntBits(other.getScore())) return false;
if (java.lang.Float.floatToIntBits(getPixelFraction())
!= java.lang.Float.floatToIntBits(other.getPixelFraction())) 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();
if (hasColor()) {
hash = (37 * hash) + COLOR_FIELD_NUMBER;
hash = (53 * hash) + getColor().hashCode();
}
hash = (37 * hash) + SCORE_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getScore());
hash = (37 * hash) + PIXEL_FRACTION_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getPixelFraction());
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.vision.v1p4beta1.ColorInfo 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>
* Color information consists of RGB channels, score, and the fraction of
* the image that the color occupies in the image.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p4beta1.ColorInfo}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vision.v1p4beta1.ColorInfo)
com.google.cloud.vision.v1p4beta1.ColorInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p4beta1.ImageAnnotatorProto
.internal_static_google_cloud_vision_v1p4beta1_ColorInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p4beta1.ImageAnnotatorProto
.internal_static_google_cloud_vision_v1p4beta1_ColorInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p4beta1.ColorInfo.class,
com.google.cloud.vision.v1p4beta1.ColorInfo.Builder.class);
}
// Construct using com.google.cloud.vision.v1p4beta1.ColorInfo.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();
if (colorBuilder_ == null) {
color_ = null;
} else {
color_ = null;
colorBuilder_ = null;
}
score_ = 0F;
pixelFraction_ = 0F;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vision.v1p4beta1.ImageAnnotatorProto
.internal_static_google_cloud_vision_v1p4beta1_ColorInfo_descriptor;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ColorInfo getDefaultInstanceForType() {
return com.google.cloud.vision.v1p4beta1.ColorInfo.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ColorInfo build() {
com.google.cloud.vision.v1p4beta1.ColorInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ColorInfo buildPartial() {
com.google.cloud.vision.v1p4beta1.ColorInfo result =
new com.google.cloud.vision.v1p4beta1.ColorInfo(this);
if (colorBuilder_ == null) {
result.color_ = color_;
} else {
result.color_ = colorBuilder_.build();
}
result.score_ = score_;
result.pixelFraction_ = pixelFraction_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.vision.v1p4beta1.ColorInfo) {
return mergeFrom((com.google.cloud.vision.v1p4beta1.ColorInfo) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vision.v1p4beta1.ColorInfo other) {
if (other == com.google.cloud.vision.v1p4beta1.ColorInfo.getDefaultInstance()) return this;
if (other.hasColor()) {
mergeColor(other.getColor());
}
if (other.getScore() != 0F) {
setScore(other.getScore());
}
if (other.getPixelFraction() != 0F) {
setPixelFraction(other.getPixelFraction());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.vision.v1p4beta1.ColorInfo parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.vision.v1p4beta1.ColorInfo) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private com.google.type.Color color_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.type.Color, com.google.type.Color.Builder, com.google.type.ColorOrBuilder>
colorBuilder_;
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*
* @return Whether the color field is set.
*/
public boolean hasColor() {
return colorBuilder_ != null || color_ != null;
}
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*
* @return The color.
*/
public com.google.type.Color getColor() {
if (colorBuilder_ == null) {
return color_ == null ? com.google.type.Color.getDefaultInstance() : color_;
} else {
return colorBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*/
public Builder setColor(com.google.type.Color value) {
if (colorBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
color_ = value;
onChanged();
} else {
colorBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*/
public Builder setColor(com.google.type.Color.Builder builderForValue) {
if (colorBuilder_ == null) {
color_ = builderForValue.build();
onChanged();
} else {
colorBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*/
public Builder mergeColor(com.google.type.Color value) {
if (colorBuilder_ == null) {
if (color_ != null) {
color_ = com.google.type.Color.newBuilder(color_).mergeFrom(value).buildPartial();
} else {
color_ = value;
}
onChanged();
} else {
colorBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*/
public Builder clearColor() {
if (colorBuilder_ == null) {
color_ = null;
onChanged();
} else {
color_ = null;
colorBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*/
public com.google.type.Color.Builder getColorBuilder() {
onChanged();
return getColorFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*/
public com.google.type.ColorOrBuilder getColorOrBuilder() {
if (colorBuilder_ != null) {
return colorBuilder_.getMessageOrBuilder();
} else {
return color_ == null ? com.google.type.Color.getDefaultInstance() : color_;
}
}
/**
*
*
* <pre>
* RGB components of the color.
* </pre>
*
* <code>.google.type.Color color = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.type.Color, com.google.type.Color.Builder, com.google.type.ColorOrBuilder>
getColorFieldBuilder() {
if (colorBuilder_ == null) {
colorBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.type.Color,
com.google.type.Color.Builder,
com.google.type.ColorOrBuilder>(getColor(), getParentForChildren(), isClean());
color_ = null;
}
return colorBuilder_;
}
private float score_;
/**
*
*
* <pre>
* Image-specific score for this color. Value in range [0, 1].
* </pre>
*
* <code>float score = 2;</code>
*
* @return The score.
*/
@java.lang.Override
public float getScore() {
return score_;
}
/**
*
*
* <pre>
* Image-specific score for this color. Value in range [0, 1].
* </pre>
*
* <code>float score = 2;</code>
*
* @param value The score to set.
* @return This builder for chaining.
*/
public Builder setScore(float value) {
score_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Image-specific score for this color. Value in range [0, 1].
* </pre>
*
* <code>float score = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearScore() {
score_ = 0F;
onChanged();
return this;
}
private float pixelFraction_;
/**
*
*
* <pre>
* The fraction of pixels the color occupies in the image.
* Value in range [0, 1].
* </pre>
*
* <code>float pixel_fraction = 3;</code>
*
* @return The pixelFraction.
*/
@java.lang.Override
public float getPixelFraction() {
return pixelFraction_;
}
/**
*
*
* <pre>
* The fraction of pixels the color occupies in the image.
* Value in range [0, 1].
* </pre>
*
* <code>float pixel_fraction = 3;</code>
*
* @param value The pixelFraction to set.
* @return This builder for chaining.
*/
public Builder setPixelFraction(float value) {
pixelFraction_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The fraction of pixels the color occupies in the image.
* Value in range [0, 1].
* </pre>
*
* <code>float pixel_fraction = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPixelFraction() {
pixelFraction_ = 0F;
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.cloud.vision.v1p4beta1.ColorInfo)
}
// @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ColorInfo)
private static final com.google.cloud.vision.v1p4beta1.ColorInfo DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vision.v1p4beta1.ColorInfo();
}
public static com.google.cloud.vision.v1p4beta1.ColorInfo getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ColorInfo> PARSER =
new com.google.protobuf.AbstractParser<ColorInfo>() {
@java.lang.Override
public ColorInfo parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ColorInfo(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ColorInfo> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ColorInfo> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ColorInfo getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
fjfalcon/TwoLevelCache | src/test/java/com/fjfalcon/cache/memory/MemoryCacheTest.java | 1909 | package com.fjfalcon.cache.memory;
import com.fjfalcon.cache.Cache;
import com.fjfalcon.cache.filesystem.FileSystemCache;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class MemoryCacheTest {
private Cache<Integer, String> cache;
@Before
public void setUp() throws Exception {
cache = new MemoryCache<>(3);
}
@After
public void tearDown() throws Exception {
cache.clear();
}
@Test
public void put() throws Exception {
cache.put(0, "value");
assertEquals("value", cache.get(0));
}
@Test
public void contains() throws Exception {
cache.put(0, "value");
assertTrue(cache.contains(0));
}
@Test
public void get() throws Exception {
cache.put(0, "value");
assertEquals("value", cache.get(0));
assertNull(cache.get(123));
}
@Test
public void remove() throws Exception {
cache.put(0, "value");
cache.put(1, "value");
cache.remove(0);
assertTrue(cache.contains(1));
assertFalse(cache.contains(0));
}
@Test
public void clear() throws Exception {
cache.put(0, "value");
cache.put(1, "value");
assertEquals(cache.size(), 2);
cache.clear();
assertEquals(cache.size(), 0);
}
@Test
public void size() throws Exception {
assertEquals(0, cache.size());
cache.put(1, "value");
assertEquals(cache.size(), 1);
cache.put(2, "value");
assertEquals(cache.size(), 2);
cache.remove(2);
assertEquals(cache.size(), 1);
}
@Test
public void isFull() throws Exception {
cache.put(0, "value");
cache.put(1, "value");
assertFalse(cache.isFull());
cache.put(2, "value");
assertTrue(cache.isFull());
}} | apache-2.0 |
uwolfer/gerrit-rest-java-client | src/main/java/com/urswolfer/gerrit/client/rest/http/config/ServerRestClient.java | 2125 | /*
* Copyright 2013-2015 Urs Wolfer
*
* 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.urswolfer.gerrit.client.rest.http.config;
import static org.apache.http.HttpStatus.SC_NOT_FOUND;
import com.google.gerrit.extensions.api.config.Server;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gson.JsonElement;
import com.urswolfer.gerrit.client.rest.http.GerritRestClient;
import com.urswolfer.gerrit.client.rest.http.HttpStatusException;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author Urs Wolfer
*/
public class ServerRestClient extends Server.NotImplemented implements Server {
private final GerritRestClient gerritRestClient;
private final AtomicReference<String> version = new AtomicReference<>();
public ServerRestClient(GerritRestClient gerritRestClient) {
this.gerritRestClient = gerritRestClient;
}
@Override
public String getVersion() throws RestApiException {
try {
JsonElement jsonElement = gerritRestClient.getRequest("/config/server/version");
version.set(jsonElement.getAsString());
return version.get();
} catch (HttpStatusException e) {
int statusCode = e.getStatusCode();
if (statusCode == SC_NOT_FOUND) { // Gerrit older than 2.8
return "<2.8";
} else {
throw e;
}
}
}
public String getVersionCached() throws RestApiException {
String gerritVersion = version.get();
return gerritVersion == null ? getVersion() : gerritVersion;
}
}
| apache-2.0 |
YoungOG/CarbyneCore | src/com/medievallords/carbyne/utils/slack/SlackMessage.java | 2778 | package com.medievallords.carbyne.utils.slack;
import com.google.gson.JsonObject;
/**
* A message to be sent through the {@link SlackAPI}.
*/
public class SlackMessage {
private String _username;
private String _icon;
private String _content;
/**
* Class constructor.
*
* @param content The content of the message.
*/
public SlackMessage(String content) {
_icon = SlackAPI.DEFAULT_ICON;
_content = content;
}
/**
* Class constructor.
*
* @param username The username of the message.
* @param content The content of the message.
*/
public SlackMessage(String username, String content) {
_username = username;
_icon = SlackAPI.DEFAULT_ICON;
_content = content;
}
/**
* Class constructor.
*
* @param username The username of the message.
* @param icon The icon/emoji of the message.
* @param content The content of the message.
*/
public SlackMessage(String username, String icon, String content) {
_username = username;
_icon = ":" + icon + ":";
_content = content;
}
/**
* Converts the message to JSON format.
*
* @return The {@link SlackMessage} in the form of a {@link JsonObject}.
*/
public JsonObject toJson() {
JsonObject msg = new JsonObject();
if (_username != null) {
msg.addProperty("username", _username);
}
if (_icon != null) {
msg.addProperty("icon_emoji", _icon);
}
if (_content != null) {
msg.addProperty("text", _content);
}
return msg;
}
/**
* Gets the username that displays as a title.
*
* @return The username in use.
*/
public String getUsername() {
return _username;
}
/**
* Sets the username that displays as a title.
*
* @param username The username to use.
*/
public void setUsername(String username) {
_username = username;
}
/**
* Gets the icon that displays with the title.
*
* @return The icon in use.
*/
public String getIcon() {
return _icon;
}
/**
* Sets the icon that displays with the title.
*
* @param icon The icon to use.
*/
public void setIcon(String icon) {
_icon = icon;
}
/**
* Gets the content of the message.
*
* @return The content of the message.
*/
public String getContent() {
return _content;
}
/**
* Sets the content of the message.
*
* @param content The content of the message.
*/
public void setContent(String content) {
_content = content;
}
} | apache-2.0 |
lixiaodong0814/CoolWeather | src/com/coolweather/app/util/Utility.java | 3963 | package com.coolweather.app.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.json.JSONException;
import org.json.JSONObject;
import com.coolweather.app.db.CoolWeatherDB;
import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
public class Utility {
/**
* ½âÎöºÍ´¦Àí·þÎñÆ÷·µ»ØµÄÊ¡¼¶Êý¾Ý
*/
public synchronized static boolean handleProvincesResponse(
CoolWeatherDB coolWeatherDB, String response) {
if (!TextUtils.isEmpty(response)) {
String[] allProvinces = response.split(",");
if (allProvinces != null && allProvinces.length > 0) {
for (String p : allProvinces) {
String[] array = p.split("\\|");
Province province = new Province();
province.setProvinceCode(array[0]);
province.setProvinceName(array[1]);
// ½«½âÎö³öÀ´µÄÊý¾Ý´æ´¢µ½Province±í
coolWeatherDB.saveProvince(province);
}
return true;
}
}
return false;
}
/**
* ½âÎöºÍ´¦Àí·þÎñÆ÷·µ»ØµÄÊм¶Êý¾Ý
*/
public static boolean handleCitiesResponse(CoolWeatherDB coolWeatherDB,
String response, int provinceId) {
if (!TextUtils.isEmpty(response)) {
String[] allCities = response.split(",");
if (allCities != null && allCities.length > 0) {
for (String c : allCities) {
String[] array = c.split("\\|");
City city = new City();
city.setCityCode(array[0]);
city.setCityName(array[1]);
city.setProvinceId(provinceId);
// ½«½âÎö³öÀ´µÄÊý¾Ý´æ´¢µ½City±í
coolWeatherDB.saveCity(city);
}
return true;
}
}
return false;
}
/**
* ½âÎöºÍ´¦Àí·þÎñÆ÷·µ»ØµÄÏØ¼¶Êý¾Ý
*/
public static boolean handleCountiesResponse(CoolWeatherDB coolWeatherDB,
String response, int cityId) {
if (!TextUtils.isEmpty(response)) {
String[] allCounties = response.split(",");
if (allCounties != null && allCounties.length > 0) {
for (String c : allCounties) {
String[] array = c.split("\\|");
County county = new County();
county.setCountyCode(array[0]);
county.setCountyName(array[1]);
county.setCityId(cityId);
// ½«½âÎö³öÀ´µÄÊý¾Ý´æ´¢µ½County±í
coolWeatherDB.saveCounty(county);
}
return true;
}
}
return false;
}
public static void handleWeatherResponse(Context context, String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo");
String cityName = weatherInfo.getString("city");
String weatherCode = weatherInfo.getString("cityid");
String temp1 = weatherInfo.getString("temp1");
String temp2 = weatherInfo.getString("temp2");
String weatherDesp = weatherInfo.getString("weather");
String publishTime = weatherInfo.getString("ptime");
saveWeatherInfo(context, cityName, weatherCode,
temp1, temp2, weatherDesp, publishTime);
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void saveWeatherInfo(Context context, String cityName, String weatherCode,
String temp1, String temp2, String weatherDesp, String publishTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyÄêMÔÂdÈÕ", Locale.CHINA);
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(context).edit();
editor.putBoolean("city_selected", true);
editor.putString("city_name", cityName);
editor.putString("weather_code", weatherCode);
editor.putString("temp1", temp1);
editor.putString("temp2", temp2);
editor.putString("weather_desp", weatherDesp);
editor.putString("publish_time", publishTime);
editor.putString("current_date", sdf.format(new Date()));
editor.commit();
}
} | apache-2.0 |
emil-wcislo/sbql4j8 | sbql4j8/src/test/openjdk/tools/javac/api/T6431879.java | 2541 | /*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6431879
* @summary TreePathSCanner(CompilationUnitTree tree, P p) overloading forces use of most specific type
*/
import java.io.*;
import java.util.*;
import javax.tools.*;
import sbql4j8.com.sun.source.tree.*;
import sbql4j8.com.sun.source.util.*;
import sbql4j8.com.sun.tools.javac.api.*;
public class T6431879 {
public static void main(String... args) throws IOException {
String testSrc = System.getProperty("test.src", ".");
String testClasses = System.getProperty("test.classes", ".");
JavacTool tool = JavacTool.create();
StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> files =
fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, T6431879.class.getName()+".java")));
JavacTask task = tool.getTask(null, fm, null, null, null, files);
Iterable<? extends CompilationUnitTree> trees = task.parse();
TreeScanner<Void,Trees> dependencyScanner = new DependencyScanner();
Trees treeUtil = Trees.instance(task);
for (CompilationUnitTree unit : trees) {
//System.err.println("scan " + unit);
dependencyScanner.scan(unit, treeUtil);
}
}
private static class DependencyScanner<R,P> extends TreePathScanner<R,P> {
public R visitIdentifier(IdentifierTree tree, P p) {
//System.err.println(tree);
return null;
}
}
}
| apache-2.0 |
mwkang/zeppelin | spark/spark2-shims/src/main/scala/org/apache/zeppelin/spark/Spark2Shims.java | 4240 | /*
* 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.zeppelin.spark;
import org.apache.commons.lang.StringUtils;
import org.apache.spark.SparkContext;
import org.apache.spark.scheduler.SparkListener;
import org.apache.spark.scheduler.SparkListenerJobStart;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.catalyst.expressions.GenericRow;
import org.apache.spark.sql.types.StructType;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.ResultMessages;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class Spark2Shims extends SparkShims {
private SparkSession sparkSession;
public Spark2Shims(Properties properties, Object entryPoint) {
super(properties);
this.sparkSession = (SparkSession) entryPoint;
}
public void setupSparkListener(final String master,
final String sparkWebUrl,
final InterpreterContext context) {
SparkContext sc = SparkContext.getOrCreate();
sc.addSparkListener(new SparkListener() {
@Override
public void onJobStart(SparkListenerJobStart jobStart) {
if (sc.getConf().getBoolean("spark.ui.enabled", true) &&
!Boolean.parseBoolean(properties.getProperty("zeppelin.spark.ui.hidden", "false"))) {
buildSparkJobUrl(master, sparkWebUrl, jobStart.jobId(), jobStart.properties(), context);
}
}
});
}
@Override
public String showDataFrame(Object obj, int maxResult) {
if (obj instanceof Dataset) {
Dataset<Row> df = ((Dataset) obj).toDF();
String[] columns = df.columns();
// DDL will empty DataFrame
if (columns.length == 0) {
return "";
}
// fetch maxResult+1 rows so that we can check whether it is larger than zeppelin.spark.maxResult
List<Row> rows = df.takeAsList(maxResult + 1);
StringBuilder msg = new StringBuilder();
msg.append("%table ");
msg.append(StringUtils.join(columns, "\t"));
msg.append("\n");
boolean isLargerThanMaxResult = rows.size() > maxResult;
if (isLargerThanMaxResult) {
rows = rows.subList(0, maxResult);
}
for (Row row : rows) {
for (int i = 0; i < row.size(); ++i) {
msg.append(row.get(i));
if (i != row.size() -1) {
msg.append("\t");
}
}
msg.append("\n");
}
if (isLargerThanMaxResult) {
msg.append("\n");
msg.append(ResultMessages.getExceedsLimitRowsMessage(maxResult, "zeppelin.spark.maxResult"));
}
// append %text at the end, otherwise the following output will be put in table as well.
msg.append("\n%text ");
return msg.toString();
} else {
return obj.toString();
}
}
@Override
public Dataset<Row> getAsDataFrame(String value) {
String[] lines = value.split("\\n");
String head = lines[0];
String[] columns = head.split("\t");
StructType schema = new StructType();
for (String column : columns) {
schema = schema.add(column, "String");
}
List<Row> rows = new ArrayList<>();
for (int i = 1; i < lines.length; ++i) {
String[] tokens = lines[i].split("\t");
Row row = new GenericRow(tokens);
rows.add(row);
}
return sparkSession.createDataFrame(rows, schema);
}
}
| apache-2.0 |
Capgemini/gregor | src/test/java/com/capgemini/gregor/internal/consumer/KafkaConsumersConfigurationTest.java | 3140 | /*
* 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 com.capgemini.gregor.internal.consumer;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.springframework.core.env.Environment;
import org.springframework.integration.kafka.core.BrokerAddress;
import org.springframework.integration.kafka.core.Configuration;
import com.capgemini.gregor.internal.KafkaSettings;
import java.util.ArrayList;
import java.util.List;
public class KafkaConsumersConfigurationTest {
private static final String BROKER_ADDRESS = "kafka.url:1234";
private KafkaConsumersConfiguration underTest = new KafkaConsumersConfiguration();
@Test
public void testKafkaBrokerConfiguration() {
final Configuration config = underTest.kafkaBrokerConfiguration(createSettings());
assertCorrectBrokerAddress(config);
}
// @Test
// public void testKafkaBrokerConnectionFactory() throws Exception {
// final DefaultConnectionFactory connectionFactory = (DefaultConnectionFactory) underTest.kafkaBrokerConnectionFactory(createSettings());
//
// assertCorrectBrokerAddress(connectionFactory.getConfiguration());
// }
// @Test public void testTest() {
// final KafkaSettings settings = underTest.kafkaSettings(createEnvironment());
//
// assertEquals("Broker address incorrect", BROKER_ADDRESS, settings.getBrokerAddress());
// }
private void assertCorrectBrokerAddress(Configuration configuration) {
assertEquals("Broker address list is wrong size", 1, configuration.getBrokerAddresses().size());
final BrokerAddress address = configuration.getBrokerAddresses().get(0);
assertEquals("Incorrect broker address", BROKER_ADDRESS, address.toString());
}
private Environment createEnvironment() {
final Environment environment = mock(Environment.class);
when(environment.getProperty(eq("kafka.address"), isA(String.class))).thenReturn(BROKER_ADDRESS);
return environment;
}
private KafkaSettings createSettings() {
final KafkaSettings mockSettings = mock(KafkaSettings.class);
final List<String> addresses = new ArrayList<String>();
addresses.add(BROKER_ADDRESS);
when(mockSettings.getBrokerAddresses()).thenReturn(addresses);
return mockSettings;
}
}
| apache-2.0 |
jdcasey/pnc | model/src/main/java/org/jboss/pnc/model/BuildRecordPushResult.java | 5573 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2018 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.model;
import org.hibernate.annotations.Type;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* @author <a href="mailto:matejonnet@gmail.com">Matej Lazar</a>
*/
@Entity
@Table(indexes = {@Index(name = "idx_buildrecordpushresult_buildrecord", columnList = "buildRecord_id")})
public class BuildRecordPushResult implements GenericEntity<Integer> {
public static final String SEQUENCE_NAME = "build_record_push_result_id_seq";
@Id
@SequenceGenerator(name = SEQUENCE_NAME, sequenceName = SEQUENCE_NAME, initialValue = 100, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE_NAME)
private Integer id;
@JoinColumn(foreignKey = @ForeignKey(name = "fk_buildrecordpushresult_buildrecord"))
@ManyToOne
private BuildRecord buildRecord;
@Enumerated(EnumType.STRING)
private Status status;
@Lob
@Type(type = "org.hibernate.type.TextType")
private String log;
/**
* build id assigned by brew
*/
private Integer brewBuildId;
/**
* link to brew
*/
private String brewBuildUrl;
private String tagPrefix;
public BuildRecordPushResult() {
}
private BuildRecordPushResult(Builder builder) {
setId(builder.id);
setBuildRecord(builder.buildRecord);
setStatus(builder.status);
setLog(builder.log);
setBrewBuildId(builder.brewBuildId);
setBrewBuildUrl(builder.brewBuildUrl);
setTagPrefix(builder.tagPrefix);
}
public static Builder newBuilder() {
return new Builder();
}
public enum Status {
SUCCESS, FAILED, SYSTEM_ERROR, CANCELED;
}
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Integer id) {
this.id = id;
}
public BuildRecord getBuildRecord() {
return buildRecord;
}
public void setBuildRecord(BuildRecord buildRecord) {
this.buildRecord = buildRecord;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getLog() {
return log;
}
public void setLog(String log) {
this.log = log;
}
public Integer getBrewBuildId() {
return brewBuildId;
}
public void setBrewBuildId(Integer brewBuildId) {
this.brewBuildId = brewBuildId;
}
public String getBrewBuildUrl() {
return brewBuildUrl;
}
public void setBrewBuildUrl(String brewBuildUrl) {
this.brewBuildUrl = brewBuildUrl;
}
public String getTagPrefix() {
return tagPrefix;
}
public void setTagPrefix(String tagPrefix) {
this.tagPrefix = tagPrefix;
}
@Override
public String toString() {
return "BuildRecordPushResult{" +
"id=" + id +
", buildRecord=" + buildRecord +
", status=" + status +
", log='" + log + '\'' +
", brewBuildId=" + brewBuildId +
", brewBuildUrl='" + brewBuildUrl + '\'' +
", tagPrefix='" + tagPrefix + '\'' +
'}';
}
public static final class Builder {
private Integer id;
private BuildRecord buildRecord;
private Status status;
private String log;
private Integer brewBuildId;
private String brewBuildUrl;
private String tagPrefix;
private Builder() {
}
public Builder id(Integer val) {
id = val;
return this;
}
public Builder buildRecord(BuildRecord val) {
buildRecord = val;
return this;
}
public Builder status(Status val) {
status = val;
return this;
}
public Builder log(String val) {
log = val;
return this;
}
public Builder brewBuildId(Integer val) {
brewBuildId = val;
return this;
}
public Builder brewBuildUrl(String val) {
brewBuildUrl = val;
return this;
}
public Builder tagPrefix(String val) {
tagPrefix = val;
return this;
}
public BuildRecordPushResult build() {
return new BuildRecordPushResult(this);
}
}
}
| apache-2.0 |